?
preferences-persistence.js 0000666 00000104227 15123355174 0011745 0 ustar 00 /******/ (function() { // webpackBootstrap
/******/ "use strict";
/******/ // The require scope
/******/ var __webpack_require__ = {};
/******/
/************************************************************************/
/******/ /* 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__ = {};
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"__unstableCreatePersistenceLayer": function() { return /* binding */ __unstableCreatePersistenceLayer; },
"create": function() { return /* reexport */ create; }
});
;// CONCATENATED MODULE: external ["wp","apiFetch"]
var external_wp_apiFetch_namespaceObject = window["wp"]["apiFetch"];
var external_wp_apiFetch_default = /*#__PURE__*/__webpack_require__.n(external_wp_apiFetch_namespaceObject);
;// CONCATENATED MODULE: ./node_modules/@wordpress/preferences-persistence/build-module/create/debounce-async.js
/**
* Performs a leading edge debounce of async functions.
*
* If three functions are throttled at the same time:
* - The first happens immediately.
* - The second is never called.
* - The third happens `delayMS` milliseconds after the first has resolved.
*
* This is distinct from `{ debounce } from @wordpress/compose` in that it
* waits for promise resolution.
*
* @param {Function} func A function that returns a promise.
* @param {number} delayMS A delay in milliseconds.
*
* @return {Function} A function that debounce whatever function is passed
* to it.
*/
function debounceAsync(func, delayMS) {
let timeoutId;
let activePromise;
return async function debounced() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
// This is a leading edge debounce. If there's no promise or timeout
// in progress, call the debounced function immediately.
if (!activePromise && !timeoutId) {
return new Promise((resolve, reject) => {
// Keep a reference to the promise.
activePromise = func(...args).then(function () {
resolve(...arguments);
}).catch(error => {
reject(error);
}).finally(() => {
// As soon this promise is complete, clear the way for the
// next one to happen immediately.
activePromise = null;
});
});
}
if (activePromise) {
// Let any active promises finish before queuing the next request.
await activePromise;
} // 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.
return new Promise((resolve, reject) => {
// Schedule the next request but with a delay.
timeoutId = setTimeout(() => {
activePromise = func(...args).then(function () {
resolve(...arguments);
}).catch(error => {
reject(error);
}).finally(() => {
// As soon this promise is complete, clear the way for the
// next one to happen immediately.
activePromise = null;
timeoutId = null;
});
}, delayMS);
});
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/preferences-persistence/build-module/create/index.js
/**
* 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.
*
* @param {Object} options
* @param {?Object} options.preloadedData Any persisted preferences data that should be preloaded.
* When set, the persistence layer will avoid fetching data
* from the REST API.
* @param {?string} options.localStorageRestoreKey The key to use for restoring the localStorage backup, used
* when the persistence layer calls `localStorage.getItem` or
* `localStorage.setItem`.
* @param {?number} options.requestDebounceMS Debounce requests to the API so that they only occur at
* minimum every `requestDebounceMS` milliseconds, and don't
* swamp the server. Defaults to 2500ms.
*
* @return {Object} A persistence layer for WordPress user meta.
*/
function create() {
let {
preloadedData,
localStorageRestoreKey = 'WP_PREFERENCES_RESTORE_DATA',
requestDebounceMS = 2500
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let cache = preloadedData;
const debouncedApiFetch = debounceAsync((external_wp_apiFetch_default()), requestDebounceMS);
async function get() {
var _user$meta;
if (cache) {
return cache;
}
const user = await external_wp_apiFetch_default()({
path: '/wp/v2/users/me?context=edit'
});
const serverData = user === null || user === void 0 ? void 0 : (_user$meta = user.meta) === null || _user$meta === void 0 ? void 0 : _user$meta.persisted_preferences;
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 === null || serverData === void 0 ? void 0 : serverData._modified) || 0;
const localTimestamp = Date.parse(localData === null || localData === void 0 ? void 0 : 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) {
cache = localData;
} else {
cache = EMPTY_OBJECT;
}
return cache;
}
function set(newData) {
const dataWithTimestamp = { ...newData,
_modified: new Date().toISOString()
};
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)); // 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',
// `keepalive` will still send the request in the background,
// even when a browser unload event might interrupt it.
// This should hopefully make things more resilient.
// This does have a size limit of 64kb, but the data is usually
// much less.
keepalive: true,
data: {
meta: {
persisted_preferences: dataWithTimestamp
}
}
}).catch(() => {});
}
return {
get,
set
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/preferences-persistence/build-module/migrations/legacy-local-storage-data/move-feature-preferences.js
/**
* Move the 'features' object in local storage from the sourceStoreName to the
* preferences store data structure.
*
* Previously, editors used a data structure like this for feature preferences:
* ```js
* {
* 'core/edit-post': {
* preferences: {
* features; {
* topToolbar: true,
* // ... other boolean 'feature' preferences
* },
* },
* },
* }
* ```
*
* And for a while these feature preferences lived in the interface package:
* ```js
* {
* 'core/interface': {
* preferences: {
* features: {
* 'core/edit-post': {
* topToolbar: true
* }
* }
* }
* }
* }
* ```
*
* In the preferences store, 'features' aren't considered special, they're
* merged to the root level of the scope along with other preferences:
* ```js
* {
* 'core/preferences': {
* preferences: {
* 'core/edit-post': {
* topToolbar: true,
* // ... any other preferences.
* }
* }
* }
* }
* ```
*
* This function handles moving from either the source store or the interface
* store to the preferences data structure.
*
* @param {Object} state The state before migration.
* @param {string} sourceStoreName The name of the store that has persisted
* preferences to migrate to the preferences
* package.
* @return {Object} The migrated state
*/
function moveFeaturePreferences(state, sourceStoreName) {
var _state$interfaceStore, _state$interfaceStore2, _state$interfaceStore3, _state$sourceStoreNam, _state$sourceStoreNam2, _state$preferencesSto;
const preferencesStoreName = 'core/preferences';
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 === null || state === void 0 ? void 0 : (_state$interfaceStore = state[interfaceStoreName]) === null || _state$interfaceStore === void 0 ? void 0 : (_state$interfaceStore2 = _state$interfaceStore.preferences) === null || _state$interfaceStore2 === void 0 ? void 0 : (_state$interfaceStore3 = _state$interfaceStore2.features) === null || _state$interfaceStore3 === void 0 ? void 0 : _state$interfaceStore3[sourceStoreName];
const sourceFeatures = state === null || state === void 0 ? void 0 : (_state$sourceStoreNam = state[sourceStoreName]) === null || _state$sourceStoreNam === void 0 ? void 0 : (_state$sourceStoreNam2 = _state$sourceStoreNam.preferences) === null || _state$sourceStoreNam2 === void 0 ? void 0 : _state$sourceStoreNam2.features;
const featuresToMigrate = interfaceFeatures ? interfaceFeatures : sourceFeatures;
if (!featuresToMigrate) {
return state;
}
const existingPreferences = state === null || state === void 0 ? void 0 : (_state$preferencesSto = state[preferencesStoreName]) === null || _state$preferencesSto === void 0 ? void 0 : _state$preferencesSto.preferences; // Avoid migrating features again if they've previously been migrated.
if (existingPreferences !== null && existingPreferences !== void 0 && existingPreferences[sourceStoreName]) {
return state;
}
let updatedInterfaceState;
if (interfaceFeatures) {
var _state$interfaceStore4, _state$interfaceStore5;
const otherInterfaceState = state === null || state === void 0 ? void 0 : state[interfaceStoreName];
const otherInterfaceScopes = state === null || state === void 0 ? void 0 : (_state$interfaceStore4 = state[interfaceStoreName]) === null || _state$interfaceStore4 === void 0 ? void 0 : (_state$interfaceStore5 = _state$interfaceStore4.preferences) === null || _state$interfaceStore5 === void 0 ? void 0 : _state$interfaceStore5.features;
updatedInterfaceState = {
[interfaceStoreName]: { ...otherInterfaceState,
preferences: {
features: { ...otherInterfaceScopes,
[sourceStoreName]: undefined
}
}
}
};
}
let updatedSourceState;
if (sourceFeatures) {
var _state$sourceStoreNam3;
const otherSourceState = state === null || state === void 0 ? void 0 : state[sourceStoreName];
const sourcePreferences = state === null || state === void 0 ? void 0 : (_state$sourceStoreNam3 = state[sourceStoreName]) === null || _state$sourceStoreNam3 === void 0 ? void 0 : _state$sourceStoreNam3.preferences;
updatedSourceState = {
[sourceStoreName]: { ...otherSourceState,
preferences: { ...sourcePreferences,
features: undefined
}
}
};
} // 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,
[preferencesStoreName]: {
preferences: { ...existingPreferences,
[sourceStoreName]: featuresToMigrate
}
},
...updatedInterfaceState,
...updatedSourceState
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/preferences-persistence/build-module/migrations/legacy-local-storage-data/move-third-party-feature-preferences.js
/**
* The interface package previously had a public API that could be used by
* plugins to set persisted boolean 'feature' preferences.
*
* While usage was likely non-existent or very small, this function ensures
* those are migrated to the preferences data structure. The interface
* package's APIs have now been deprecated and use the preferences store.
*
* This will convert data that looks like this:
* ```js
* {
* 'core/interface': {
* preferences: {
* features: {
* 'my-plugin': {
* myPluginFeature: true
* }
* }
* }
* }
* }
* ```
*
* To this:
* ```js
* * {
* 'core/preferences': {
* preferences: {
* 'my-plugin': {
* myPluginFeature: true
* }
* }
* }
* }
* ```
*
* @param {Object} state The local storage state
*
* @return {Object} The state with third party preferences moved to the
* preferences data structure.
*/
function moveThirdPartyFeaturePreferencesToPreferences(state) {
var _state$interfaceStore, _state$interfaceStore2;
const interfaceStoreName = 'core/interface';
const preferencesStoreName = 'core/preferences';
const interfaceScopes = state === null || state === void 0 ? void 0 : (_state$interfaceStore = state[interfaceStoreName]) === null || _state$interfaceStore === void 0 ? void 0 : (_state$interfaceStore2 = _state$interfaceStore.preferences) === null || _state$interfaceStore2 === void 0 ? void 0 : _state$interfaceStore2.features;
const interfaceScopeKeys = interfaceScopes ? Object.keys(interfaceScopes) : [];
if (!(interfaceScopeKeys !== null && interfaceScopeKeys !== void 0 && interfaceScopeKeys.length)) {
return state;
}
return interfaceScopeKeys.reduce(function (convertedState, scope) {
var _convertedState$prefe, _convertedState$prefe2, _convertedState$prefe3, _convertedState$inter, _convertedState$inter2;
if (scope.startsWith('core')) {
return convertedState;
}
const featuresToMigrate = interfaceScopes === null || interfaceScopes === void 0 ? void 0 : interfaceScopes[scope];
if (!featuresToMigrate) {
return convertedState;
}
const existingMigratedData = convertedState === null || convertedState === void 0 ? void 0 : (_convertedState$prefe = convertedState[preferencesStoreName]) === null || _convertedState$prefe === void 0 ? void 0 : (_convertedState$prefe2 = _convertedState$prefe.preferences) === null || _convertedState$prefe2 === void 0 ? void 0 : _convertedState$prefe2[scope];
if (existingMigratedData) {
return convertedState;
}
const otherPreferencesScopes = convertedState === null || convertedState === void 0 ? void 0 : (_convertedState$prefe3 = convertedState[preferencesStoreName]) === null || _convertedState$prefe3 === void 0 ? void 0 : _convertedState$prefe3.preferences;
const otherInterfaceState = convertedState === null || convertedState === void 0 ? void 0 : convertedState[interfaceStoreName];
const otherInterfaceScopes = convertedState === null || convertedState === void 0 ? void 0 : (_convertedState$inter = convertedState[interfaceStoreName]) === null || _convertedState$inter === void 0 ? void 0 : (_convertedState$inter2 = _convertedState$inter.preferences) === null || _convertedState$inter2 === void 0 ? void 0 : _convertedState$inter2.features;
return { ...convertedState,
[preferencesStoreName]: {
preferences: { ...otherPreferencesScopes,
[scope]: featuresToMigrate
}
},
[interfaceStoreName]: { ...otherInterfaceState,
preferences: {
features: { ...otherInterfaceScopes,
[scope]: undefined
}
}
}
};
}, 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.
*
* Previously, some packages had individual 'preferences' of any data type, and many used
* complex nested data structures. For example:
* ```js
* {
* 'core/edit-post': {
* preferences: {
* panels: {
* publish: {
* opened: true,
* enabled: true,
* }
* },
* // ...other preferences.
* },
* },
* }
*
* This function supports moving an individual preference like 'panels' above into the
* preferences package data structure.
*
* It supports moving a preference to a particular scope in the preferences store and
* optionally converting the data using a `convert` function.
*
* ```
*
* @param {Object} state The original state.
* @param {Object} migrate An options object that contains details of the migration.
* @param {string} migrate.from The name of the store to migrate from.
* @param {string} migrate.to The scope in the preferences store to migrate to.
* @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, _ref, key) {
var _state$sourceStoreNam, _state$sourceStoreNam2, _state$preferencesSto, _state$preferencesSto2, _state$preferencesSto3, _state$preferencesSto4, _state$preferencesSto5, _state$preferencesSto6, _state$sourceStoreNam3;
let {
from: sourceStoreName,
to: scope
} = _ref;
let convert = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : identity;
const preferencesStoreName = 'core/preferences';
const sourcePreference = state === null || state === void 0 ? void 0 : (_state$sourceStoreNam = state[sourceStoreName]) === null || _state$sourceStoreNam === void 0 ? void 0 : (_state$sourceStoreNam2 = _state$sourceStoreNam.preferences) === null || _state$sourceStoreNam2 === void 0 ? void 0 : _state$sourceStoreNam2[key]; // There's nothing to migrate, exit early.
if (sourcePreference === undefined) {
return state;
}
const targetPreference = state === null || state === void 0 ? void 0 : (_state$preferencesSto = state[preferencesStoreName]) === null || _state$preferencesSto === void 0 ? void 0 : (_state$preferencesSto2 = _state$preferencesSto.preferences) === null || _state$preferencesSto2 === void 0 ? void 0 : (_state$preferencesSto3 = _state$preferencesSto2[scope]) === null || _state$preferencesSto3 === void 0 ? void 0 : _state$preferencesSto3[key]; // There's existing data at the target, so don't overwrite it, exit early.
if (targetPreference) {
return state;
}
const otherScopes = state === null || state === void 0 ? void 0 : (_state$preferencesSto4 = state[preferencesStoreName]) === null || _state$preferencesSto4 === void 0 ? void 0 : _state$preferencesSto4.preferences;
const otherPreferences = state === null || state === void 0 ? void 0 : (_state$preferencesSto5 = state[preferencesStoreName]) === null || _state$preferencesSto5 === void 0 ? void 0 : (_state$preferencesSto6 = _state$preferencesSto5.preferences) === null || _state$preferencesSto6 === void 0 ? void 0 : _state$preferencesSto6[scope];
const otherSourceState = state === null || state === void 0 ? void 0 : state[sourceStoreName];
const allSourcePreferences = state === null || state === void 0 ? void 0 : (_state$sourceStoreNam3 = state[sourceStoreName]) === null || _state$sourceStoreNam3 === void 0 ? void 0 : _state$sourceStoreNam3.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,
[preferencesStoreName]: {
preferences: { ...otherScopes,
[scope]: { ...otherPreferences,
...convertedPreferences
}
}
},
[sourceStoreName]: { ...otherSourceState,
preferences: { ...allSourcePreferences,
[key]: undefined
}
}
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/preferences-persistence/build-module/migrations/legacy-local-storage-data/move-interface-enable-items.js
/**
* Migrates interface 'enableItems' data to the preferences store.
*
* The interface package stores this data in this format:
* ```js
* {
* enableItems: {
* singleEnableItems: {
* complementaryArea: {
* 'core/edit-post': 'edit-post/document',
* 'core/edit-site': 'edit-site/global-styles',
* }
* },
* multipleEnableItems: {
* pinnedItems: {
* 'core/edit-post': {
* 'plugin-1': true,
* },
* 'core/edit-site': {
* 'plugin-2': true,
* },
* },
* }
* }
* }
* ```
*
* and it should be converted it to:
* ```js
* {
* 'core/edit-post': {
* complementaryArea: 'edit-post/document',
* pinnedItems: {
* 'plugin-1': true,
* },
* },
* 'core/edit-site': {
* complementaryArea: 'edit-site/global-styles',
* pinnedItems: {
* 'plugin-2': true,
* },
* },
* }
* ```
*
* @param {Object} state The local storage state.
*/
function moveInterfaceEnableItems(state) {
var _state$interfaceStore, _state$preferencesSto, _state$preferencesSto2, _sourceEnableItems$si, _sourceEnableItems$si2, _sourceEnableItems$mu, _sourceEnableItems$mu2;
const interfaceStoreName = 'core/interface';
const preferencesStoreName = 'core/preferences';
const sourceEnableItems = state === null || state === void 0 ? void 0 : (_state$interfaceStore = state[interfaceStoreName]) === null || _state$interfaceStore === void 0 ? void 0 : _state$interfaceStore.enableItems; // There's nothing to migrate, exit early.
if (!sourceEnableItems) {
return state;
}
const allPreferences = (_state$preferencesSto = state === null || state === void 0 ? void 0 : (_state$preferencesSto2 = state[preferencesStoreName]) === null || _state$preferencesSto2 === void 0 ? void 0 : _state$preferencesSto2.preferences) !== null && _state$preferencesSto !== void 0 ? _state$preferencesSto : {}; // 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 === null || sourceEnableItems === void 0 ? void 0 : (_sourceEnableItems$si2 = sourceEnableItems.singleEnableItems) === null || _sourceEnableItems$si2 === void 0 ? void 0 : _sourceEnableItems$si2.complementaryArea) !== null && _sourceEnableItems$si !== void 0 ? _sourceEnableItems$si : {};
const preferencesWithConvertedComplementaryAreas = Object.keys(sourceComplementaryAreas).reduce((accumulator, scope) => {
var _accumulator$scope;
const data = sourceComplementaryAreas[scope]; // Don't overwrite any existing data in the preferences store.
if (accumulator !== null && accumulator !== void 0 && (_accumulator$scope = accumulator[scope]) !== null && _accumulator$scope !== void 0 && _accumulator$scope.complementaryArea) {
return accumulator;
}
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.
const sourcePinnedItems = (_sourceEnableItems$mu = sourceEnableItems === null || sourceEnableItems === void 0 ? void 0 : (_sourceEnableItems$mu2 = sourceEnableItems.multipleEnableItems) === null || _sourceEnableItems$mu2 === void 0 ? void 0 : _sourceEnableItems$mu2.pinnedItems) !== null && _sourceEnableItems$mu !== void 0 ? _sourceEnableItems$mu : {};
const allConvertedData = Object.keys(sourcePinnedItems).reduce((accumulator, scope) => {
var _accumulator$scope2;
const data = sourcePinnedItems[scope]; // Don't overwrite any existing data in the preferences store.
if (accumulator !== null && accumulator !== void 0 && (_accumulator$scope2 = accumulator[scope]) !== null && _accumulator$scope2 !== void 0 && _accumulator$scope2.pinnedItems) {
return accumulator;
}
return { ...accumulator,
[scope]: { ...accumulator[scope],
pinnedItems: data
}
};
}, preferencesWithConvertedComplementaryAreas);
const otherInterfaceItems = state[interfaceStoreName];
return { ...state,
[preferencesStoreName]: {
preferences: allConvertedData
},
[interfaceStoreName]: { ...otherInterfaceItems,
enableItems: undefined
}
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/preferences-persistence/build-module/migrations/legacy-local-storage-data/convert-edit-post-panels.js
/**
* Convert the post editor's panels state from:
* ```
* {
* panels: {
* tags: {
* enabled: true,
* opened: true,
* },
* permalinks: {
* enabled: false,
* opened: false,
* },
* },
* }
* ```
*
* to a new, more concise data structure:
* {
* inactivePanels: [
* 'permalinks',
* ],
* openPanels: [
* 'tags',
* ],
* }
*
* @param {Object} preferences A preferences object.
*
* @return {Object} The converted data.
*/
function convertEditPostPanels(preferences) {
var _preferences$panels;
const panels = (_preferences$panels = preferences === null || preferences === void 0 ? void 0 : preferences.panels) !== null && _preferences$panels !== void 0 ? _preferences$panels : {};
return Object.keys(panels).reduce((convertedData, panelName) => {
const panel = panels[panelName];
if ((panel === null || panel === void 0 ? void 0 : panel.enabled) === false) {
convertedData.inactivePanels.push(panelName);
}
if ((panel === null || panel === void 0 ? void 0 : panel.opened) === true) {
convertedData.openPanels.push(panelName);
}
return convertedData;
}, {
inactivePanels: [],
openPanels: []
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/preferences-persistence/build-module/migrations/legacy-local-storage-data/index.js
/**
* Internal dependencies
*/
/**
* Gets the legacy local storage data for a given user.
*
* @param {string | number} userId The user id.
*
* @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.
*
* @param {Object | null | undefined} data The legacy data in its original format.
*
* @return {Object | undefined} The converted data or `undefined` if there was
* nothing to convert.
*/
function convertLegacyData(data) {
var _data, _data$corePreference;
if (!data) {
return;
} // 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
// to the preferences store data structure.
data = moveThirdPartyFeaturePreferencesToPreferences(data); // Move and convert the interface store's `enableItems` data into the
// preferences data structure.
data = moveInterfaceEnableItems(data); // 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'
}, 'hiddenBlockTypes');
data = moveIndividualPreferenceToPreferences(data, {
from: 'core/edit-post',
to: 'core/edit-post'
}, 'editorMode');
data = moveIndividualPreferenceToPreferences(data, {
from: 'core/edit-post',
to: 'core/edit-post'
}, 'preferredStyleVariations');
data = moveIndividualPreferenceToPreferences(data, {
from: 'core/edit-post',
to: 'core/edit-post'
}, 'panels', convertEditPostPanels);
data = moveIndividualPreferenceToPreferences(data, {
from: 'core/editor',
to: 'core/edit-post'
}, 'isPublishSidebarEnabled');
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.
return (_data = data) === null || _data === void 0 ? void 0 : (_data$corePreference = _data['core/preferences']) === null || _data$corePreference === void 0 ? void 0 : _data$corePreference.preferences;
}
/**
* Gets the legacy local storage data for the given user and returns the
* data converted to the new format.
*
* @param {string | number} userId The user id.
*
* @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);
}
;// 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.
if (scopeData !== null && scopeData !== void 0 && scopeData.complementaryArea) {
const updatedScopeData = { ...scopeData
};
delete updatedScopeData.complementaryArea;
updatedScopeData.isComplementaryAreaVisible = true;
stateAccumulator[scope] = updatedScopeData;
return stateAccumulator;
}
return stateAccumulator;
}, state);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/preferences-persistence/build-module/migrations/preferences-package-data/index.js
/**
* Internal dependencies
*/
function convertPreferencesPackageData(data) {
return convertComplementaryAreas(data);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/preferences-persistence/build-module/index.js
/**
* Internal dependencies
*/
/**
* Creates the persistence layer with preloaded data.
*
* It prioritizes any data from the server, but falls back first to localStorage
* restore data, and then to any legacy data.
*
* This function is used internally by WordPress in an inline script, so
* prefixed with `__unstable`.
*
* @param {Object} serverData Preferences data preloaded from the server.
* @param {string} userId The user id.
*
* @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 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) {
preloadedData = convertPreferencesPackageData(localData);
} else {
// Check if there is data in the legacy format from the old persistence system.
preloadedData = convertLegacyLocalStorageData(userId);
}
return create({
preloadedData,
localStorageRestoreKey
});
}
(window.wp = window.wp || {}).preferencesPersistence = __webpack_exports__;
/******/ })()
; dom-ready.js 0000666 00000004716 15123355174 0007005 0 ustar 00 /******/ (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); }
/******/ }();
/******/
/************************************************************************/
var __webpack_exports__ = {};
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": function() { return /* binding */ domReady; }
/* harmony export */ });
/**
* @typedef {() => void} Callback
*
* TODO: Remove this typedef and inline `() => void` type.
*
* This typedef is used so that a descriptive type is provided in our
* automatically generated documentation.
*
* An in-line type `() => void` would be preferable, but the generated
* documentation is `null` in that case.
*
* @see https://github.com/WordPress/gutenberg/issues/18045
*/
/**
* Specify a function to execute when the DOM is fully loaded.
*
* @param {Callback} callback A function to execute after the DOM is ready.
*
* @example
* ```js
* import domReady from '@wordpress/dom-ready';
*
* domReady( function() {
* //do something after DOM loads.
* } );
* ```
*
* @return {void}
*/
function domReady(callback) {
if (typeof document === 'undefined') {
return;
}
if (document.readyState === 'complete' || // DOMContentLoaded + Images/Styles/etc loaded, so we call directly.
document.readyState === 'interactive' // DOMContentLoaded fires at this point, so we call directly.
) {
return void callback();
} // DOMContentLoaded has not fired yet, delay callback until then.
document.addEventListener('DOMContentLoaded', callback);
}
(window.wp = window.wp || {}).domReady = __webpack_exports__["default"];
/******/ })()
; widgets.js 0000666 00000157741 15123355174 0006601 0 ustar 00 /******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 7153:
/***/ (function(module, exports) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2018 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
'use strict';
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = '';
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
classes = appendClass(classes, parseValue(arg));
}
}
return classes;
}
function parseValue (arg) {
if (typeof arg === 'string' || typeof arg === 'number') {
return arg;
}
if (typeof arg !== 'object') {
return '';
}
if (Array.isArray(arg)) {
return classNames.apply(null, arg);
}
if (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes('[native code]')) {
return arg.toString();
}
var classes = '';
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes = appendClass(classes, key);
}
}
return classes;
}
function appendClass (value, newClass) {
if (!newClass) {
return value;
}
if (value) {
return value + ' ' + newClass;
}
return value + newClass;
}
if ( true && module.exports) {
classNames.default = classNames;
module.exports = classNames;
} else if (true) {
// register as 'classnames', consistent with npm package name
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () {
return classNames;
}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
}());
/***/ })
/******/ });
/************************************************************************/
/******/ // 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 in strict mode.
!function() {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"MoveToWidgetArea": function() { return /* reexport */ MoveToWidgetArea; },
"addWidgetIdToBlock": function() { return /* reexport */ addWidgetIdToBlock; },
"getWidgetIdFromBlock": function() { return /* reexport */ getWidgetIdFromBlock; },
"registerLegacyWidgetBlock": function() { return /* binding */ registerLegacyWidgetBlock; },
"registerLegacyWidgetVariations": function() { return /* reexport */ registerLegacyWidgetVariations; },
"registerWidgetGroupBlock": function() { return /* binding */ registerWidgetGroupBlock; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/widgets/build-module/blocks/legacy-widget/index.js
var legacy_widget_namespaceObject = {};
__webpack_require__.r(legacy_widget_namespaceObject);
__webpack_require__.d(legacy_widget_namespaceObject, {
"metadata": function() { return metadata; },
"name": function() { return legacy_widget_name; },
"settings": function() { return settings; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/widgets/build-module/blocks/widget-group/index.js
var widget_group_namespaceObject = {};
__webpack_require__.r(widget_group_namespaceObject);
__webpack_require__.d(widget_group_namespaceObject, {
"metadata": function() { return widget_group_metadata; },
"name": function() { return widget_group_name; },
"settings": function() { return widget_group_settings; }
});
;// CONCATENATED MODULE: external ["wp","blocks"]
var external_wp_blocks_namespaceObject = window["wp"]["blocks"];
;// CONCATENATED MODULE: external ["wp","element"]
var external_wp_element_namespaceObject = window["wp"]["element"];
;// CONCATENATED MODULE: external ["wp","primitives"]
var external_wp_primitives_namespaceObject = window["wp"]["primitives"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/widget.js
/**
* WordPress dependencies
*/
const widget = (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: "M6 3H8V5H16V3H18V5C19.1046 5 20 5.89543 20 7V19C20 20.1046 19.1046 21 18 21H6C4.89543 21 4 20.1046 4 19V7C4 5.89543 4.89543 5 6 5V3ZM18 6.5H6C5.72386 6.5 5.5 6.72386 5.5 7V8H18.5V7C18.5 6.72386 18.2761 6.5 18 6.5ZM18.5 9.5H5.5V19C5.5 19.2761 5.72386 19.5 6 19.5H18C18.2761 19.5 18.5 19.2761 18.5 19V9.5ZM11 11H13V13H11V11ZM7 11V13H9V11H7ZM15 13V11H17V13H15Z"
}));
/* harmony default export */ var library_widget = (widget);
// EXTERNAL MODULE: ./node_modules/classnames/index.js
var classnames = __webpack_require__(7153);
var classnames_default = /*#__PURE__*/__webpack_require__.n(classnames);
;// CONCATENATED MODULE: external ["wp","blockEditor"]
var external_wp_blockEditor_namespaceObject = window["wp"]["blockEditor"];
;// CONCATENATED MODULE: external ["wp","components"]
var external_wp_components_namespaceObject = window["wp"]["components"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/brush.js
/**
* WordPress dependencies
*/
const brush = (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: "M4 20h8v-1.5H4V20zM18.9 3.5c-.6-.6-1.5-.6-2.1 0l-7.2 7.2c-.4-.1-.7 0-1.1.1-.5.2-1.5.7-1.9 2.2-.4 1.7-.8 2.2-1.1 2.7-.1.1-.2.3-.3.4l-.6 1.1H6c2 0 3.4-.4 4.7-1.4.8-.6 1.2-1.4 1.3-2.3 0-.3 0-.5-.1-.7L19 5.7c.5-.6.5-1.6-.1-2.2zM9.7 14.7c-.7.5-1.5.8-2.4 1 .2-.5.5-1.2.8-2.3.2-.6.4-1 .8-1.1.5-.1 1 .1 1.3.3.2.2.3.5.2.8 0 .3-.1.9-.7 1.3z"
}));
/* harmony default export */ var library_brush = (brush);
;// CONCATENATED MODULE: external ["wp","i18n"]
var external_wp_i18n_namespaceObject = window["wp"]["i18n"];
;// 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/widgets/build-module/blocks/legacy-widget/edit/widget-type-selector.js
/**
* WordPress dependencies
*/
function WidgetTypeSelector(_ref) {
let {
selectedId,
onSelect
} = _ref;
const widgetTypes = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _select$getSettings$w, _select$getSettings, _select$getWidgetType;
const hiddenIds = (_select$getSettings$w = (_select$getSettings = select(external_wp_blockEditor_namespaceObject.store).getSettings()) === null || _select$getSettings === void 0 ? void 0 : _select$getSettings.widgetTypesToHideFromLegacyWidgetBlock) !== null && _select$getSettings$w !== void 0 ? _select$getSettings$w : [];
return (_select$getWidgetType = select(external_wp_coreData_namespaceObject.store).getWidgetTypes({
per_page: -1
})) === null || _select$getWidgetType === void 0 ? void 0 : _select$getWidgetType.filter(widgetType => !hiddenIds.includes(widgetType.id));
}, []);
if (!widgetTypes) {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Spinner, null);
}
if (widgetTypes.length === 0) {
return (0,external_wp_i18n_namespaceObject.__)('There are no widgets available.');
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SelectControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Select a legacy widget to display:'),
value: selectedId !== null && selectedId !== void 0 ? selectedId : '',
options: [{
value: '',
label: (0,external_wp_i18n_namespaceObject.__)('Select widget')
}, ...widgetTypes.map(widgetType => ({
value: widgetType.id,
label: widgetType.name
}))],
onChange: value => {
if (value) {
const selected = widgetTypes.find(widgetType => widgetType.id === value);
onSelect({
selectedId: selected.id,
isMulti: selected.is_multi
});
} else {
onSelect({
selectedId: null
});
}
}
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/widgets/build-module/blocks/legacy-widget/edit/inspector-card.js
function InspectorCard(_ref) {
let {
name,
description
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "wp-block-legacy-widget-inspector-card"
}, (0,external_wp_element_namespaceObject.createElement)("h3", {
className: "wp-block-legacy-widget-inspector-card__name"
}, name), (0,external_wp_element_namespaceObject.createElement)("span", null, description));
}
;// 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","apiFetch"]
var external_wp_apiFetch_namespaceObject = window["wp"]["apiFetch"];
var external_wp_apiFetch_default = /*#__PURE__*/__webpack_require__.n(external_wp_apiFetch_namespaceObject);
;// CONCATENATED MODULE: ./node_modules/@wordpress/widgets/build-module/blocks/legacy-widget/edit/control.js
/**
* WordPress dependencies
*/
/**
* An API for creating and loading a widget control (a <div class="widget">
* element) that is compatible with most third party widget scripts. By not
* using React for this, we ensure that we have complete contorl over the DOM
* and do not accidentally remove any elements that a third party widget script
* has attached an event listener to.
*
* @property {Element} element The control's DOM element.
*/
class Control {
/**
* Creates and loads a new control.
*
* @access public
* @param {Object} params
* @param {string} params.id
* @param {string} params.idBase
* @param {Object} params.instance
* @param {Function} params.onChangeInstance
* @param {Function} params.onChangeHasPreview
* @param {Function} params.onError
*/
constructor(_ref) {
let {
id,
idBase,
instance,
onChangeInstance,
onChangeHasPreview,
onError
} = _ref;
this.id = id;
this.idBase = idBase;
this._instance = instance;
this._hasPreview = null;
this.onChangeInstance = onChangeInstance;
this.onChangeHasPreview = onChangeHasPreview;
this.onError = onError; // We can't use the real widget number as this is calculated by the
// server and we may not ever *actually* save this widget. Instead, use
// a fake but unique number.
this.number = ++lastNumber;
this.handleFormChange = (0,external_wp_compose_namespaceObject.debounce)(this.handleFormChange.bind(this), 200);
this.handleFormSubmit = this.handleFormSubmit.bind(this);
this.initDOM();
this.bindEvents();
this.loadContent();
}
/**
* Clean up the control so that it can be garabge collected.
*
* @access public
*/
destroy() {
this.unbindEvents();
this.element.remove(); // TODO: How do we make third party widget scripts remove their event
// listeners?
}
/**
* Creates the control's DOM structure.
*
* @access private
*/
initDOM() {
var _this$id, _this$idBase;
this.element = el('div', {
class: 'widget open'
}, [el('div', {
class: 'widget-inside'
}, [this.form = el('form', {
class: 'form',
method: 'post'
}, [// These hidden form inputs are what most widgets' scripts
// use to access data about the widget.
el('input', {
class: 'widget-id',
type: 'hidden',
name: 'widget-id',
value: (_this$id = this.id) !== null && _this$id !== void 0 ? _this$id : `${this.idBase}-${this.number}`
}), el('input', {
class: 'id_base',
type: 'hidden',
name: 'id_base',
value: (_this$idBase = this.idBase) !== null && _this$idBase !== void 0 ? _this$idBase : this.id
}), el('input', {
class: 'widget-width',
type: 'hidden',
name: 'widget-width',
value: '250'
}), el('input', {
class: 'widget-height',
type: 'hidden',
name: 'widget-height',
value: '200'
}), el('input', {
class: 'widget_number',
type: 'hidden',
name: 'widget_number',
value: this.idBase ? this.number.toString() : ''
}), this.content = el('div', {
class: 'widget-content'
}), // Non-multi widgets can be saved via a Save button.
this.id && el('button', {
class: 'button is-primary',
type: 'submit'
}, (0,external_wp_i18n_namespaceObject.__)('Save'))])])]);
}
/**
* Adds the control's event listeners.
*
* @access private
*/
bindEvents() {
// Prefer jQuery 'change' event instead of the native 'change' event
// because many widgets use jQuery's event bus to trigger an update.
if (window.jQuery) {
const {
jQuery: $
} = window;
$(this.form).on('change', null, this.handleFormChange);
$(this.form).on('input', null, this.handleFormChange);
$(this.form).on('submit', this.handleFormSubmit);
} else {
this.form.addEventListener('change', this.handleFormChange);
this.form.addEventListener('input', this.handleFormChange);
this.form.addEventListener('submit', this.handleFormSubmit);
}
}
/**
* Removes the control's event listeners.
*
* @access private
*/
unbindEvents() {
if (window.jQuery) {
const {
jQuery: $
} = window;
$(this.form).off('change', null, this.handleFormChange);
$(this.form).off('input', null, this.handleFormChange);
$(this.form).off('submit', this.handleFormSubmit);
} else {
this.form.removeEventListener('change', this.handleFormChange);
this.form.removeEventListener('input', this.handleFormChange);
this.form.removeEventListener('submit', this.handleFormSubmit);
}
}
/**
* Fetches the widget's form HTML from the REST API and loads it into the
* control's form.
*
* @access private
*/
async loadContent() {
try {
if (this.id) {
const {
form
} = await saveWidget(this.id);
this.content.innerHTML = form;
} else if (this.idBase) {
const {
form,
preview
} = await encodeWidget({
idBase: this.idBase,
instance: this.instance,
number: this.number
});
this.content.innerHTML = form;
this.hasPreview = !isEmptyHTML(preview); // If we don't have an instance, perform a save right away. This
// happens when creating a new Legacy Widget block.
if (!this.instance.hash) {
const {
instance
} = await encodeWidget({
idBase: this.idBase,
instance: this.instance,
number: this.number,
formData: serializeForm(this.form)
});
this.instance = instance;
}
} // Trigger 'widget-added' when widget is ready. This event is what
// widgets' scripts use to initialize, attach events, etc. The event
// must be fired using jQuery's event bus as this is what widget
// scripts expect. If jQuery is not loaded, do nothing - some
// widgets will still work regardless.
if (window.jQuery) {
const {
jQuery: $
} = window;
$(document).trigger('widget-added', [$(this.element)]);
}
} catch (error) {
this.onError(error);
}
}
/**
* Perform a save when a multi widget's form is changed. Non-multi widgets
* are saved manually.
*
* @access private
*/
handleFormChange() {
if (this.idBase) {
this.saveForm();
}
}
/**
* Perform a save when the control's form is manually submitted.
*
* @access private
* @param {Event} event
*/
handleFormSubmit(event) {
event.preventDefault();
this.saveForm();
}
/**
* Serialize the control's form, send it to the REST API, and update the
* instance with the encoded instance that the REST API returns.
*
* @access private
*/
async saveForm() {
const formData = serializeForm(this.form);
try {
if (this.id) {
const {
form
} = await saveWidget(this.id, formData);
this.content.innerHTML = form;
if (window.jQuery) {
const {
jQuery: $
} = window;
$(document).trigger('widget-updated', [$(this.element)]);
}
} else if (this.idBase) {
const {
instance,
preview
} = await encodeWidget({
idBase: this.idBase,
instance: this.instance,
number: this.number,
formData
});
this.instance = instance;
this.hasPreview = !isEmptyHTML(preview);
}
} catch (error) {
this.onError(error);
}
}
/**
* The widget's instance object.
*
* @access private
*/
get instance() {
return this._instance;
}
/**
* The widget's instance object.
*
* @access private
*/
set instance(instance) {
if (this._instance !== instance) {
this._instance = instance;
this.onChangeInstance(instance);
}
}
/**
* Whether or not the widget can be previewed.
*
* @access public
*/
get hasPreview() {
return this._hasPreview;
}
/**
* Whether or not the widget can be previewed.
*
* @access private
*/
set hasPreview(hasPreview) {
if (this._hasPreview !== hasPreview) {
this._hasPreview = hasPreview;
this.onChangeHasPreview(hasPreview);
}
}
}
let lastNumber = 0;
function el(tagName) {
let attributes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
let content = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
const element = document.createElement(tagName);
for (const [attribute, value] of Object.entries(attributes)) {
element.setAttribute(attribute, value);
}
if (Array.isArray(content)) {
for (const child of content) {
if (child) {
element.appendChild(child);
}
}
} else if (typeof content === 'string') {
element.innerText = content;
}
return element;
}
async function saveWidget(id) {
let formData = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
let widget;
if (formData) {
widget = await external_wp_apiFetch_default()({
path: `/wp/v2/widgets/${id}?context=edit`,
method: 'PUT',
data: {
form_data: formData
}
});
} else {
widget = await external_wp_apiFetch_default()({
path: `/wp/v2/widgets/${id}?context=edit`,
method: 'GET'
});
}
return {
form: widget.rendered_form
};
}
async function encodeWidget(_ref2) {
let {
idBase,
instance,
number,
formData = null
} = _ref2;
const response = await external_wp_apiFetch_default()({
path: `/wp/v2/widget-types/${idBase}/encode`,
method: 'POST',
data: {
instance,
number,
form_data: formData
}
});
return {
instance: response.instance,
form: response.form,
preview: response.preview
};
}
function isEmptyHTML(html) {
const element = document.createElement('div');
element.innerHTML = html;
return isEmptyNode(element);
}
function isEmptyNode(node) {
switch (node.nodeType) {
case node.TEXT_NODE:
// Text nodes are empty if it's entirely whitespace.
return node.nodeValue.trim() === '';
case node.ELEMENT_NODE:
// Elements that are "embedded content" are not empty.
// https://dev.w3.org/html5/spec-LC/content-models.html#embedded-content-0
if (['AUDIO', 'CANVAS', 'EMBED', 'IFRAME', 'IMG', 'MATH', 'OBJECT', 'SVG', 'VIDEO'].includes(node.tagName)) {
return false;
} // Elements with no children are empty.
if (!node.hasChildNodes()) {
return true;
} // Elements with children are empty if all their children are empty.
return Array.from(node.childNodes).every(isEmptyNode);
default:
return true;
}
}
function serializeForm(form) {
return new window.URLSearchParams(Array.from(new window.FormData(form))).toString();
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/widgets/build-module/blocks/legacy-widget/edit/form.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function Form(_ref) {
let {
title,
isVisible,
id,
idBase,
instance,
isWide,
onChangeInstance,
onChangeHasPreview
} = _ref;
const ref = (0,external_wp_element_namespaceObject.useRef)();
const isMediumLargeViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('small'); // We only want to remount the control when the instance changes
// *externally*. For example, if the user performs an undo. To do this, we
// keep track of changes made to instance by the control itself and then
// ignore those.
const outgoingInstances = (0,external_wp_element_namespaceObject.useRef)(new Set());
const incomingInstances = (0,external_wp_element_namespaceObject.useRef)(new Set());
const {
createNotice
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_notices_namespaceObject.store);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (incomingInstances.current.has(instance)) {
incomingInstances.current.delete(instance);
return;
}
const control = new Control({
id,
idBase,
instance,
onChangeInstance(nextInstance) {
outgoingInstances.current.add(instance);
incomingInstances.current.add(nextInstance);
onChangeInstance(nextInstance);
},
onChangeHasPreview,
onError(error) {
window.console.error(error);
createNotice('error', (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: the name of the affected block. */
(0,external_wp_i18n_namespaceObject.__)('The "%s" block was affected by errors and may not function properly. Check the developer tools for more details.'), idBase || id));
}
});
ref.current.appendChild(control.element);
return () => {
if (outgoingInstances.current.has(instance)) {
outgoingInstances.current.delete(instance);
return;
}
control.destroy();
};
}, [id, idBase, instance, onChangeInstance, onChangeHasPreview, isMediumLargeViewport]);
if (isWide && isMediumLargeViewport) {
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()({
'wp-block-legacy-widget__container': isVisible
})
}, isVisible && (0,external_wp_element_namespaceObject.createElement)("h3", {
className: "wp-block-legacy-widget__edit-form-title"
}, title), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Popover, {
focusOnMount: false,
placement: "right",
offset: 32,
resize: false,
flip: false,
shift: true
}, (0,external_wp_element_namespaceObject.createElement)("div", {
ref: ref,
className: "wp-block-legacy-widget__edit-form",
hidden: !isVisible
})));
}
return (0,external_wp_element_namespaceObject.createElement)("div", {
ref: ref,
className: "wp-block-legacy-widget__edit-form",
hidden: !isVisible
}, (0,external_wp_element_namespaceObject.createElement)("h3", {
className: "wp-block-legacy-widget__edit-form-title"
}, title));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/widgets/build-module/blocks/legacy-widget/edit/preview.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
function Preview(_ref) {
let {
idBase,
instance,
isVisible
} = _ref;
const [isLoaded, setIsLoaded] = (0,external_wp_element_namespaceObject.useState)(false);
const [srcDoc, setSrcDoc] = (0,external_wp_element_namespaceObject.useState)('');
(0,external_wp_element_namespaceObject.useEffect)(() => {
const abortController = typeof window.AbortController === 'undefined' ? undefined : new window.AbortController();
async function fetchPreviewHTML() {
const restRoute = `/wp/v2/widget-types/${idBase}/render`;
return await external_wp_apiFetch_default()({
path: restRoute,
method: 'POST',
signal: abortController === null || abortController === void 0 ? void 0 : abortController.signal,
data: instance ? {
instance
} : {}
});
}
fetchPreviewHTML().then(response => {
setSrcDoc(response.preview);
}).catch(error => {
if ('AbortError' === error.name) {
// We don't want to log aborted requests.
return;
}
throw error;
});
return () => abortController === null || abortController === void 0 ? void 0 : abortController.abort();
}, [idBase, instance]); // Resize the iframe on either the load event, or when the iframe becomes visible.
const ref = (0,external_wp_compose_namespaceObject.useRefEffect)(iframe => {
// Only set height if the iframe is loaded,
// or it will grow to an unexpected large height in Safari if it's hidden initially.
if (!isLoaded) {
return;
} // If the preview frame has another origin then this won't work.
// One possible solution is to add custom script to call `postMessage` in the preview frame.
// Or, better yet, we migrate away from iframe.
function setHeight() {
var _iframe$contentDocume, _iframe$contentDocume2, _iframe$contentDocume3, _iframe$contentDocume4;
// Pick the maximum of these two values to account for margin collapsing.
const height = Math.max((_iframe$contentDocume = (_iframe$contentDocume2 = iframe.contentDocument.documentElement) === null || _iframe$contentDocume2 === void 0 ? void 0 : _iframe$contentDocume2.offsetHeight) !== null && _iframe$contentDocume !== void 0 ? _iframe$contentDocume : 0, (_iframe$contentDocume3 = (_iframe$contentDocume4 = iframe.contentDocument.body) === null || _iframe$contentDocume4 === void 0 ? void 0 : _iframe$contentDocume4.offsetHeight) !== null && _iframe$contentDocume3 !== void 0 ? _iframe$contentDocume3 : 0); // Fallback to a height of 100px if the height cannot be determined.
// This ensures the block is still selectable. 100px should hopefully
// be not so big that it's annoying, and not so small that nothing
// can be seen.
iframe.style.height = `${height !== 0 ? height : 100}px`;
}
const {
IntersectionObserver
} = iframe.ownerDocument.defaultView; // Observe for intersections that might cause a change in the height of
// the iframe, e.g. a Widget Area becoming expanded.
const intersectionObserver = new IntersectionObserver(_ref2 => {
let [entry] = _ref2;
if (entry.isIntersecting) {
setHeight();
}
}, {
threshold: 1
});
intersectionObserver.observe(iframe);
iframe.addEventListener('load', setHeight);
return () => {
intersectionObserver.disconnect();
iframe.removeEventListener('load', setHeight);
};
}, [isLoaded]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, isVisible && !isLoaded && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Placeholder, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Spinner, null)), (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('wp-block-legacy-widget__edit-preview', {
'is-offscreen': !isVisible || !isLoaded
})
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Disabled, null, (0,external_wp_element_namespaceObject.createElement)("iframe", {
ref: ref,
className: "wp-block-legacy-widget__edit-preview-iframe",
tabIndex: "-1",
title: (0,external_wp_i18n_namespaceObject.__)('Legacy Widget Preview'),
srcDoc: srcDoc,
onLoad: event => {
// To hide the scrollbars of the preview frame for some edge cases,
// such as negative margins in the Gallery Legacy Widget.
// It can't be scrolled anyway.
// TODO: Ideally, this should be fixed in core.
event.target.contentDocument.body.style.overflow = 'hidden';
setIsLoaded(true);
},
height: 100
}))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/widgets/build-module/blocks/legacy-widget/edit/no-preview.js
/**
* WordPress dependencies
*/
function NoPreview(_ref) {
let {
name
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "wp-block-legacy-widget__edit-no-preview"
}, name && (0,external_wp_element_namespaceObject.createElement)("h3", null, name), (0,external_wp_element_namespaceObject.createElement)("p", null, (0,external_wp_i18n_namespaceObject.__)('No preview available.')));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/widgets/build-module/blocks/legacy-widget/edit/convert-to-blocks-button.js
/**
* WordPress dependencies
*/
function ConvertToBlocksButton(_ref) {
let {
clientId,
rawInstance
} = _ref;
const {
replaceBlocks
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_blockEditor_namespaceObject.store);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
onClick: () => {
if (rawInstance.title) {
replaceBlocks(clientId, [(0,external_wp_blocks_namespaceObject.createBlock)('core/heading', {
content: rawInstance.title
}), ...(0,external_wp_blocks_namespaceObject.rawHandler)({
HTML: rawInstance.text
})]);
} else {
replaceBlocks(clientId, (0,external_wp_blocks_namespaceObject.rawHandler)({
HTML: rawInstance.text
}));
}
}
}, (0,external_wp_i18n_namespaceObject.__)('Convert to blocks'));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/widgets/build-module/blocks/legacy-widget/edit/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function Edit(props) {
const {
id,
idBase
} = props.attributes;
const {
isWide = false
} = props;
const blockProps = (0,external_wp_blockEditor_namespaceObject.useBlockProps)({
className: classnames_default()({
'is-wide-widget': isWide
})
});
return (0,external_wp_element_namespaceObject.createElement)("div", blockProps, !id && !idBase ? (0,external_wp_element_namespaceObject.createElement)(Empty, props) : (0,external_wp_element_namespaceObject.createElement)(NotEmpty, props));
}
function Empty(_ref) {
let {
attributes: {
id,
idBase
},
setAttributes
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Placeholder, {
icon: (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockIcon, {
icon: library_brush
}),
label: (0,external_wp_i18n_namespaceObject.__)('Legacy Widget')
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Flex, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexBlock, null, (0,external_wp_element_namespaceObject.createElement)(WidgetTypeSelector, {
selectedId: id !== null && id !== void 0 ? id : idBase,
onSelect: _ref2 => {
let {
selectedId,
isMulti
} = _ref2;
if (!selectedId) {
setAttributes({
id: null,
idBase: null,
instance: null
});
} else if (isMulti) {
setAttributes({
id: null,
idBase: selectedId,
instance: {}
});
} else {
setAttributes({
id: selectedId,
idBase: null,
instance: null
});
}
}
}))));
}
function NotEmpty(_ref3) {
let {
attributes: {
id,
idBase,
instance
},
setAttributes,
clientId,
isSelected,
isWide = false
} = _ref3;
const [hasPreview, setHasPreview] = (0,external_wp_element_namespaceObject.useState)(null);
const widgetTypeId = id !== null && id !== void 0 ? id : idBase;
const {
record: widgetType,
hasResolved: hasResolvedWidgetType
} = (0,external_wp_coreData_namespaceObject.useEntityRecord)('root', 'widgetType', widgetTypeId);
const isNavigationMode = (0,external_wp_data_namespaceObject.useSelect)(select => select(external_wp_blockEditor_namespaceObject.store).isNavigationMode(), []);
const setInstance = (0,external_wp_element_namespaceObject.useCallback)(nextInstance => {
setAttributes({
instance: nextInstance
});
}, []);
if (!widgetType && hasResolvedWidgetType) {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Placeholder, {
icon: (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockIcon, {
icon: library_brush
}),
label: (0,external_wp_i18n_namespaceObject.__)('Legacy Widget')
}, (0,external_wp_i18n_namespaceObject.__)('Widget is missing.'));
}
if (!hasResolvedWidgetType) {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Placeholder, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Spinner, null));
}
const mode = idBase && (isNavigationMode || !isSelected) ? 'preview' : 'edit';
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, idBase === 'text' && (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockControls, {
group: "other"
}, (0,external_wp_element_namespaceObject.createElement)(ConvertToBlocksButton, {
clientId: clientId,
rawInstance: instance.raw
})), (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.InspectorControls, null, (0,external_wp_element_namespaceObject.createElement)(InspectorCard, {
name: widgetType.name,
description: widgetType.description
})), (0,external_wp_element_namespaceObject.createElement)(Form, {
title: widgetType.name,
isVisible: mode === 'edit',
id: id,
idBase: idBase,
instance: instance,
isWide: isWide,
onChangeInstance: setInstance,
onChangeHasPreview: setHasPreview
}), idBase && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, hasPreview === null && mode === 'preview' && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Placeholder, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Spinner, null)), hasPreview === true && (0,external_wp_element_namespaceObject.createElement)(Preview, {
idBase: idBase,
instance: instance,
isVisible: mode === 'preview'
}), hasPreview === false && mode === 'preview' && (0,external_wp_element_namespaceObject.createElement)(NoPreview, {
name: widgetType.name
})));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/widgets/build-module/blocks/legacy-widget/transforms.js
/**
* WordPress dependencies
*/
const legacyWidgetTransforms = [{
block: 'core/calendar',
widget: 'calendar'
}, {
block: 'core/search',
widget: 'search'
}, {
block: 'core/html',
widget: 'custom_html',
transform: _ref => {
let {
content
} = _ref;
return {
content
};
}
}, {
block: 'core/archives',
widget: 'archives',
transform: _ref2 => {
let {
count,
dropdown
} = _ref2;
return {
displayAsDropdown: !!dropdown,
showPostCounts: !!count
};
}
}, {
block: 'core/latest-posts',
widget: 'recent-posts',
transform: _ref3 => {
let {
show_date: displayPostDate,
number
} = _ref3;
return {
displayPostDate: !!displayPostDate,
postsToShow: number
};
}
}, {
block: 'core/latest-comments',
widget: 'recent-comments',
transform: _ref4 => {
let {
number
} = _ref4;
return {
commentsToShow: number
};
}
}, {
block: 'core/tag-cloud',
widget: 'tag_cloud',
transform: _ref5 => {
let {
taxonomy,
count
} = _ref5;
return {
showTagCounts: !!count,
taxonomy
};
}
}, {
block: 'core/categories',
widget: 'categories',
transform: _ref6 => {
let {
count,
dropdown,
hierarchical
} = _ref6;
return {
displayAsDropdown: !!dropdown,
showPostCounts: !!count,
showHierarchy: !!hierarchical
};
}
}, {
block: 'core/audio',
widget: 'media_audio',
transform: _ref7 => {
let {
url,
preload,
loop,
attachment_id: id
} = _ref7;
return {
src: url,
id,
preload,
loop
};
}
}, {
block: 'core/video',
widget: 'media_video',
transform: _ref8 => {
let {
url,
preload,
loop,
attachment_id: id
} = _ref8;
return {
src: url,
id,
preload,
loop
};
}
}, {
block: 'core/image',
widget: 'media_image',
transform: _ref9 => {
let {
alt,
attachment_id: id,
caption,
height,
link_classes: linkClass,
link_rel: rel,
link_target_blank: targetBlack,
link_type: linkDestination,
link_url: link,
size: sizeSlug,
url,
width
} = _ref9;
return {
alt,
caption,
height,
id,
link,
linkClass,
linkDestination,
linkTarget: targetBlack ? '_blank' : undefined,
rel,
sizeSlug,
url,
width
};
}
}, {
block: 'core/gallery',
widget: 'media_gallery',
transform: _ref10 => {
let {
ids,
link_type: linkTo,
size,
number
} = _ref10;
return {
ids,
columns: number,
linkTo,
sizeSlug: size,
images: ids.map(id => ({
id
}))
};
}
}, {
block: 'core/rss',
widget: 'rss',
transform: _ref11 => {
let {
url,
show_author: displayAuthor,
show_date: displayDate,
show_summary: displayExcerpt,
items
} = _ref11;
return {
feedURL: url,
displayAuthor: !!displayAuthor,
displayDate: !!displayDate,
displayExcerpt: !!displayExcerpt,
itemsToShow: items
};
}
}].map(_ref12 => {
let {
block,
widget,
transform
} = _ref12;
return {
type: 'block',
blocks: [block],
isMatch: _ref13 => {
let {
idBase,
instance
} = _ref13;
return idBase === widget && !!(instance !== null && instance !== void 0 && instance.raw);
},
transform: _ref14 => {
var _instance$raw;
let {
instance
} = _ref14;
const transformedBlock = (0,external_wp_blocks_namespaceObject.createBlock)(block, transform ? transform(instance.raw) : undefined);
if (!((_instance$raw = instance.raw) !== null && _instance$raw !== void 0 && _instance$raw.title)) {
return transformedBlock;
}
return [(0,external_wp_blocks_namespaceObject.createBlock)('core/heading', {
content: instance.raw.title
}), transformedBlock];
}
};
});
const transforms = {
to: legacyWidgetTransforms
};
/* harmony default export */ var legacy_widget_transforms = (transforms);
;// CONCATENATED MODULE: ./node_modules/@wordpress/widgets/build-module/blocks/legacy-widget/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const metadata = {
apiVersion: 2,
name: "core/legacy-widget",
title: "Legacy Widget",
category: "widgets",
description: "Display a legacy widget.",
textdomain: "default",
attributes: {
id: {
type: "string",
"default": null
},
idBase: {
type: "string",
"default": null
},
instance: {
type: "object",
"default": null
}
},
supports: {
html: false,
customClassName: false,
reusable: false
},
editorStyle: "wp-block-legacy-widget-editor"
};
const {
name: legacy_widget_name
} = metadata;
const settings = {
icon: library_widget,
edit: Edit,
transforms: legacy_widget_transforms
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/group.js
/**
* WordPress dependencies
*/
const group = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M18 4h-7c-1.1 0-2 .9-2 2v3H6c-1.1 0-2 .9-2 2v7c0 1.1.9 2 2 2h7c1.1 0 2-.9 2-2v-3h3c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-4.5 14c0 .3-.2.5-.5.5H6c-.3 0-.5-.2-.5-.5v-7c0-.3.2-.5.5-.5h3V13c0 1.1.9 2 2 2h2.5v3zm0-4.5H11c-.3 0-.5-.2-.5-.5v-2.5H13c.3 0 .5.2.5.5v2.5zm5-.5c0 .3-.2.5-.5.5h-3V11c0-1.1-.9-2-2-2h-2.5V6c0-.3.2-.5.5-.5h7c.3 0 .5.2.5.5v7z"
}));
/* harmony default export */ var library_group = (group);
;// CONCATENATED MODULE: ./node_modules/@wordpress/widgets/build-module/blocks/widget-group/edit.js
/**
* WordPress dependencies
*/
function edit_Edit(props) {
const {
clientId
} = props;
const {
innerBlocks
} = (0,external_wp_data_namespaceObject.useSelect)(select => select(external_wp_blockEditor_namespaceObject.store).getBlock(clientId), [clientId]);
return (0,external_wp_element_namespaceObject.createElement)("div", (0,external_wp_blockEditor_namespaceObject.useBlockProps)({
className: 'widget'
}), innerBlocks.length === 0 ? (0,external_wp_element_namespaceObject.createElement)(PlaceholderContent, props) : (0,external_wp_element_namespaceObject.createElement)(PreviewContent, props));
}
function PlaceholderContent(_ref) {
let {
clientId
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Placeholder, {
className: "wp-block-widget-group__placeholder",
icon: (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockIcon, {
icon: library_group
}),
label: (0,external_wp_i18n_namespaceObject.__)('Widget Group')
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.ButtonBlockAppender, {
rootClientId: clientId
})), (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.InnerBlocks, {
renderAppender: false
}));
}
function PreviewContent(_ref2) {
var _attributes$title;
let {
attributes,
setAttributes
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.RichText, {
tagName: "h2",
className: "widget-title",
allowedFormats: [],
placeholder: (0,external_wp_i18n_namespaceObject.__)('Title'),
value: (_attributes$title = attributes.title) !== null && _attributes$title !== void 0 ? _attributes$title : '',
onChange: title => setAttributes({
title
})
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.InnerBlocks, null));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/widgets/build-module/blocks/widget-group/save.js
/**
* WordPress dependencies
*/
function save(_ref) {
let {
attributes
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.RichText.Content, {
tagName: "h2",
className: "widget-title",
value: attributes.title
}), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "wp-widget-group__inner-blocks"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.InnerBlocks.Content, null)));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/widgets/build-module/blocks/widget-group/deprecated.js
/**
* WordPress dependencies
*/
const v1 = {
attributes: {
title: {
type: 'string'
}
},
supports: {
html: false,
inserter: true,
customClassName: true,
reusable: false
},
save(_ref) {
let {
attributes
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.RichText.Content, {
tagName: "h2",
className: "widget-title",
value: attributes.title
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.InnerBlocks.Content, null));
}
};
/* harmony default export */ var deprecated = ([v1]);
;// CONCATENATED MODULE: ./node_modules/@wordpress/widgets/build-module/blocks/widget-group/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const widget_group_metadata = {
apiVersion: 2,
name: "core/widget-group",
category: "widgets",
attributes: {
title: {
type: "string"
}
},
supports: {
html: false,
inserter: true,
customClassName: true,
reusable: false
},
editorStyle: "wp-block-widget-group-editor",
style: "wp-block-widget-group"
};
const {
name: widget_group_name
} = widget_group_metadata;
const widget_group_settings = {
title: (0,external_wp_i18n_namespaceObject.__)('Widget Group'),
description: (0,external_wp_i18n_namespaceObject.__)('Create a classic widget layout with a title that’s styled by your theme for your widget areas.'),
icon: library_group,
__experimentalLabel: _ref => {
let {
name: label
} = _ref;
return label;
},
edit: edit_Edit,
save: save,
transforms: {
from: [{
type: 'block',
isMultiBlock: true,
blocks: ['*'],
isMatch(attributes, blocks) {
// Avoid transforming existing `widget-group` blocks.
return !blocks.some(block => block.name === 'core/widget-group');
},
__experimentalConvert(blocks) {
// Put the selected blocks inside the new Widget Group's innerBlocks.
let innerBlocks = [...blocks.map(block => {
return (0,external_wp_blocks_namespaceObject.createBlock)(block.name, block.attributes, block.innerBlocks);
})]; // If the first block is a heading then assume this is intended
// to be the Widget's "title".
const firstHeadingBlock = innerBlocks[0].name === 'core/heading' ? innerBlocks[0] : null; // Remove the first heading block as we're copying
// it's content into the Widget Group's title attribute.
innerBlocks = innerBlocks.filter(block => block !== firstHeadingBlock);
return (0,external_wp_blocks_namespaceObject.createBlock)('core/widget-group', { ...(firstHeadingBlock && {
title: firstHeadingBlock.attributes.content
})
}, innerBlocks);
}
}]
},
deprecated: deprecated
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/move-to.js
/**
* WordPress dependencies
*/
const moveTo = (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.75 9c0-1.257-.565-2.197-1.39-2.858-.797-.64-1.827-1.017-2.815-1.247-1.802-.42-3.703-.403-4.383-.396L11 4.5V6l.177-.001c.696-.006 2.416-.02 4.028.356.887.207 1.67.518 2.216.957.52.416.829.945.829 1.688 0 .592-.167.966-.407 1.23-.255.281-.656.508-1.236.674-1.19.34-2.82.346-4.607.346h-.077c-1.692 0-3.527 0-4.942.404-.732.209-1.424.545-1.935 1.108-.526.579-.796 1.33-.796 2.238 0 1.257.565 2.197 1.39 2.858.797.64 1.827 1.017 2.815 1.247 1.802.42 3.703.403 4.383.396L13 19.5h.714V22L18 18.5 13.714 15v3H13l-.177.001c-.696.006-2.416.02-4.028-.356-.887-.207-1.67-.518-2.216-.957-.52-.416-.829-.945-.829-1.688 0-.592.167-.966.407-1.23.255-.281.656-.508 1.237-.674 1.189-.34 2.819-.346 4.606-.346h.077c1.692 0 3.527 0 4.941-.404.732-.209 1.425-.545 1.936-1.108.526-.579.796-1.33.796-2.238z"
}));
/* harmony default export */ var move_to = (moveTo);
;// CONCATENATED MODULE: ./node_modules/@wordpress/widgets/build-module/components/move-to-widget-area/index.js
/**
* WordPress dependencies
*/
function MoveToWidgetArea(_ref) {
let {
currentWidgetAreaId,
widgetAreas,
onSelect
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarGroup, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarItem, null, toggleProps => (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.DropdownMenu, {
icon: move_to,
label: (0,external_wp_i18n_namespaceObject.__)('Move to widget area'),
toggleProps: toggleProps
}, _ref2 => {
let {
onClose
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, {
label: (0,external_wp_i18n_namespaceObject.__)('Move to')
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItemsChoice, {
choices: widgetAreas.map(widgetArea => ({
value: widgetArea.id,
label: widgetArea.name,
info: widgetArea.description
})),
value: currentWidgetAreaId,
onSelect: value => {
onSelect(value);
onClose();
}
}));
})));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/widgets/build-module/components/index.js
;// CONCATENATED MODULE: ./node_modules/@wordpress/widgets/build-module/utils.js
// @ts-check
/**
* Get the internal widget id from block.
*
* @typedef {Object} Attributes
* @property {string} __internalWidgetId The internal widget id.
* @typedef {Object} Block
* @property {Attributes} attributes The attributes of the block.
*
* @param {Block} block The block.
* @return {string} The internal widget id.
*/
function getWidgetIdFromBlock(block) {
return block.attributes.__internalWidgetId;
}
/**
* Add internal widget id to block's attributes.
*
* @param {Block} block The block.
* @param {string} widgetId The widget id.
* @return {Block} The updated block.
*/
function addWidgetIdToBlock(block, widgetId) {
return { ...block,
attributes: { ...(block.attributes || {}),
__internalWidgetId: widgetId
}
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/widgets/build-module/register-legacy-widget-variations.js
/**
* WordPress dependencies
*/
function registerLegacyWidgetVariations(settings) {
const unsubscribe = (0,external_wp_data_namespaceObject.subscribe)(() => {
var _settings$widgetTypes, _select$getWidgetType;
const hiddenIds = (_settings$widgetTypes = settings === null || settings === void 0 ? void 0 : settings.widgetTypesToHideFromLegacyWidgetBlock) !== null && _settings$widgetTypes !== void 0 ? _settings$widgetTypes : [];
const widgetTypes = (_select$getWidgetType = (0,external_wp_data_namespaceObject.select)(external_wp_coreData_namespaceObject.store).getWidgetTypes({
per_page: -1
})) === null || _select$getWidgetType === void 0 ? void 0 : _select$getWidgetType.filter(widgetType => !hiddenIds.includes(widgetType.id));
if (widgetTypes) {
unsubscribe();
(0,external_wp_data_namespaceObject.dispatch)(external_wp_blocks_namespaceObject.store).addBlockVariations('core/legacy-widget', widgetTypes.map(widgetType => ({
name: widgetType.id,
title: widgetType.name,
description: widgetType.description,
attributes: widgetType.is_multi ? {
idBase: widgetType.id,
instance: {}
} : {
id: widgetType.id
}
})));
}
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/widgets/build-module/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Registers the Legacy Widget block.
*
* Note that for the block to be useful, any scripts required by a widget must
* be loaded into the page.
*
* @param {Object} supports Block support settings.
* @see https://developer.wordpress.org/block-editor/how-to-guides/widgets/legacy-widget-block/
*/
function registerLegacyWidgetBlock() {
let supports = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const {
metadata,
settings,
name
} = legacy_widget_namespaceObject;
(0,external_wp_blocks_namespaceObject.registerBlockType)({
name,
...metadata
}, { ...settings,
supports: { ...settings.supports,
...supports
}
});
}
/**
* Registers the Widget Group block.
*
* @param {Object} supports Block support settings.
*/
function registerWidgetGroupBlock() {
let supports = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const {
metadata,
settings,
name
} = widget_group_namespaceObject;
(0,external_wp_blocks_namespaceObject.registerBlockType)({
name,
...metadata
}, { ...settings,
supports: { ...settings.supports,
...supports
}
});
}
}();
(window.wp = window.wp || {}).widgets = __webpack_exports__;
/******/ })()
; warning.min.js 0000666 00000000610 15123355174 0007340 0 ustar 00 /*! 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}(); url.js 0000666 00000101453 15123355174 0005722 0 ustar 00 /******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 4793:
/***/ (function(module) {
var characterMap = {
"À": "A",
"Á": "A",
"Â": "A",
"Ã": "A",
"Ä": "A",
"Å": "A",
"Ấ": "A",
"Ắ": "A",
"Ẳ": "A",
"Ẵ": "A",
"Ặ": "A",
"Æ": "AE",
"Ầ": "A",
"Ằ": "A",
"Ȃ": "A",
"Ç": "C",
"Ḉ": "C",
"È": "E",
"É": "E",
"Ê": "E",
"Ë": "E",
"Ế": "E",
"Ḗ": "E",
"Ề": "E",
"Ḕ": "E",
"Ḝ": "E",
"Ȇ": "E",
"Ì": "I",
"Í": "I",
"Î": "I",
"Ï": "I",
"Ḯ": "I",
"Ȋ": "I",
"Ð": "D",
"Ñ": "N",
"Ò": "O",
"Ó": "O",
"Ô": "O",
"Õ": "O",
"Ö": "O",
"Ø": "O",
"Ố": "O",
"Ṍ": "O",
"Ṓ": "O",
"Ȏ": "O",
"Ù": "U",
"Ú": "U",
"Û": "U",
"Ü": "U",
"Ý": "Y",
"à": "a",
"á": "a",
"â": "a",
"ã": "a",
"ä": "a",
"å": "a",
"ấ": "a",
"ắ": "a",
"ẳ": "a",
"ẵ": "a",
"ặ": "a",
"æ": "ae",
"ầ": "a",
"ằ": "a",
"ȃ": "a",
"ç": "c",
"ḉ": "c",
"è": "e",
"é": "e",
"ê": "e",
"ë": "e",
"ế": "e",
"ḗ": "e",
"ề": "e",
"ḕ": "e",
"ḝ": "e",
"ȇ": "e",
"ì": "i",
"í": "i",
"î": "i",
"ï": "i",
"ḯ": "i",
"ȋ": "i",
"ð": "d",
"ñ": "n",
"ò": "o",
"ó": "o",
"ô": "o",
"õ": "o",
"ö": "o",
"ø": "o",
"ố": "o",
"ṍ": "o",
"ṓ": "o",
"ȏ": "o",
"ù": "u",
"ú": "u",
"û": "u",
"ü": "u",
"ý": "y",
"ÿ": "y",
"Ā": "A",
"ā": "a",
"Ă": "A",
"ă": "a",
"Ą": "A",
"ą": "a",
"Ć": "C",
"ć": "c",
"Ĉ": "C",
"ĉ": "c",
"Ċ": "C",
"ċ": "c",
"Č": "C",
"č": "c",
"C̆": "C",
"c̆": "c",
"Ď": "D",
"ď": "d",
"Đ": "D",
"đ": "d",
"Ē": "E",
"ē": "e",
"Ĕ": "E",
"ĕ": "e",
"Ė": "E",
"ė": "e",
"Ę": "E",
"ę": "e",
"Ě": "E",
"ě": "e",
"Ĝ": "G",
"Ǵ": "G",
"ĝ": "g",
"ǵ": "g",
"Ğ": "G",
"ğ": "g",
"Ġ": "G",
"ġ": "g",
"Ģ": "G",
"ģ": "g",
"Ĥ": "H",
"ĥ": "h",
"Ħ": "H",
"ħ": "h",
"Ḫ": "H",
"ḫ": "h",
"Ĩ": "I",
"ĩ": "i",
"Ī": "I",
"ī": "i",
"Ĭ": "I",
"ĭ": "i",
"Į": "I",
"į": "i",
"İ": "I",
"ı": "i",
"IJ": "IJ",
"ij": "ij",
"Ĵ": "J",
"ĵ": "j",
"Ķ": "K",
"ķ": "k",
"Ḱ": "K",
"ḱ": "k",
"K̆": "K",
"k̆": "k",
"Ĺ": "L",
"ĺ": "l",
"Ļ": "L",
"ļ": "l",
"Ľ": "L",
"ľ": "l",
"Ŀ": "L",
"ŀ": "l",
"Ł": "l",
"ł": "l",
"Ḿ": "M",
"ḿ": "m",
"M̆": "M",
"m̆": "m",
"Ń": "N",
"ń": "n",
"Ņ": "N",
"ņ": "n",
"Ň": "N",
"ň": "n",
"ʼn": "n",
"N̆": "N",
"n̆": "n",
"Ō": "O",
"ō": "o",
"Ŏ": "O",
"ŏ": "o",
"Ő": "O",
"ő": "o",
"Œ": "OE",
"œ": "oe",
"P̆": "P",
"p̆": "p",
"Ŕ": "R",
"ŕ": "r",
"Ŗ": "R",
"ŗ": "r",
"Ř": "R",
"ř": "r",
"R̆": "R",
"r̆": "r",
"Ȓ": "R",
"ȓ": "r",
"Ś": "S",
"ś": "s",
"Ŝ": "S",
"ŝ": "s",
"Ş": "S",
"Ș": "S",
"ș": "s",
"ş": "s",
"Š": "S",
"š": "s",
"ß": "ss",
"Ţ": "T",
"ţ": "t",
"ț": "t",
"Ț": "T",
"Ť": "T",
"ť": "t",
"Ŧ": "T",
"ŧ": "t",
"T̆": "T",
"t̆": "t",
"Ũ": "U",
"ũ": "u",
"Ū": "U",
"ū": "u",
"Ŭ": "U",
"ŭ": "u",
"Ů": "U",
"ů": "u",
"Ű": "U",
"ű": "u",
"Ų": "U",
"ų": "u",
"Ȗ": "U",
"ȗ": "u",
"V̆": "V",
"v̆": "v",
"Ŵ": "W",
"ŵ": "w",
"Ẃ": "W",
"ẃ": "w",
"X̆": "X",
"x̆": "x",
"Ŷ": "Y",
"ŷ": "y",
"Ÿ": "Y",
"Y̆": "Y",
"y̆": "y",
"Ź": "Z",
"ź": "z",
"Ż": "Z",
"ż": "z",
"Ž": "Z",
"ž": "z",
"ſ": "s",
"ƒ": "f",
"Ơ": "O",
"ơ": "o",
"Ư": "U",
"ư": "u",
"Ǎ": "A",
"ǎ": "a",
"Ǐ": "I",
"ǐ": "i",
"Ǒ": "O",
"ǒ": "o",
"Ǔ": "U",
"ǔ": "u",
"Ǖ": "U",
"ǖ": "u",
"Ǘ": "U",
"ǘ": "u",
"Ǚ": "U",
"ǚ": "u",
"Ǜ": "U",
"ǜ": "u",
"Ứ": "U",
"ứ": "u",
"Ṹ": "U",
"ṹ": "u",
"Ǻ": "A",
"ǻ": "a",
"Ǽ": "AE",
"ǽ": "ae",
"Ǿ": "O",
"ǿ": "o",
"Þ": "TH",
"þ": "th",
"Ṕ": "P",
"ṕ": "p",
"Ṥ": "S",
"ṥ": "s",
"X́": "X",
"x́": "x",
"Ѓ": "Г",
"ѓ": "г",
"Ќ": "К",
"ќ": "к",
"A̋": "A",
"a̋": "a",
"E̋": "E",
"e̋": "e",
"I̋": "I",
"i̋": "i",
"Ǹ": "N",
"ǹ": "n",
"Ồ": "O",
"ồ": "o",
"Ṑ": "O",
"ṑ": "o",
"Ừ": "U",
"ừ": "u",
"Ẁ": "W",
"ẁ": "w",
"Ỳ": "Y",
"ỳ": "y",
"Ȁ": "A",
"ȁ": "a",
"Ȅ": "E",
"ȅ": "e",
"Ȉ": "I",
"ȉ": "i",
"Ȍ": "O",
"ȍ": "o",
"Ȑ": "R",
"ȑ": "r",
"Ȕ": "U",
"ȕ": "u",
"B̌": "B",
"b̌": "b",
"Č̣": "C",
"č̣": "c",
"Ê̌": "E",
"ê̌": "e",
"F̌": "F",
"f̌": "f",
"Ǧ": "G",
"ǧ": "g",
"Ȟ": "H",
"ȟ": "h",
"J̌": "J",
"ǰ": "j",
"Ǩ": "K",
"ǩ": "k",
"M̌": "M",
"m̌": "m",
"P̌": "P",
"p̌": "p",
"Q̌": "Q",
"q̌": "q",
"Ř̩": "R",
"ř̩": "r",
"Ṧ": "S",
"ṧ": "s",
"V̌": "V",
"v̌": "v",
"W̌": "W",
"w̌": "w",
"X̌": "X",
"x̌": "x",
"Y̌": "Y",
"y̌": "y",
"A̧": "A",
"a̧": "a",
"B̧": "B",
"b̧": "b",
"Ḑ": "D",
"ḑ": "d",
"Ȩ": "E",
"ȩ": "e",
"Ɛ̧": "E",
"ɛ̧": "e",
"Ḩ": "H",
"ḩ": "h",
"I̧": "I",
"i̧": "i",
"Ɨ̧": "I",
"ɨ̧": "i",
"M̧": "M",
"m̧": "m",
"O̧": "O",
"o̧": "o",
"Q̧": "Q",
"q̧": "q",
"U̧": "U",
"u̧": "u",
"X̧": "X",
"x̧": "x",
"Z̧": "Z",
"z̧": "z",
"й":"и",
"Й":"И",
"ё":"е",
"Ё":"Е",
};
var chars = Object.keys(characterMap).join('|');
var allAccents = new RegExp(chars, 'g');
var firstAccent = new RegExp(chars, '');
function matcher(match) {
return characterMap[match];
}
var removeAccents = function(string) {
return string.replace(allAccents, matcher);
};
var hasAccents = function(string) {
return !!string.match(firstAccent);
};
module.exports = removeAccents;
module.exports.has = hasAccents;
module.exports.remove = removeAccents;
/***/ })
/******/ });
/************************************************************************/
/******/ // 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 in strict mode.
!function() {
"use strict";
// ESM COMPAT FLAG
__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; },
"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
/**
* Determines whether the given string looks like a URL.
*
* @param {string} url The string to scrutinise.
*
* @example
* ```js
* const isURL = isURL( 'https://wordpress.org' ); // true
* ```
*
* @see https://url.spec.whatwg.org/
* @see https://url.spec.whatwg.org/#valid-url-string
*
* @return {boolean} Whether or not it looks like a URL.
*/
function isURL(url) {
// A URL can be considered value if the `URL` constructor is able to parse
// it. The constructor throws an error for an invalid URL.
try {
new URL(url);
return true;
} catch {
return false;
}
}
;// 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.
*
* @param {string} email The string to scrutinise.
*
* @example
* ```js
* const isEmail = isEmail( 'hello@wordpress.org' ); // true
* ```
*
* @return {boolean} Whether or not it looks like an email.
*/
function isEmail(email) {
return EMAIL_REGEXP.test(email);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/get-protocol.js
/**
* Returns the protocol part of the URL.
*
* @param {string} url The full URL.
*
* @example
* ```js
* const protocol1 = getProtocol( 'tel:012345678' ); // 'tel:'
* const protocol2 = getProtocol( 'https://wordpress.org' ); // 'https:'
* ```
*
* @return {string|void} The protocol part of the URL.
*/
function getProtocol(url) {
const matches = /^([^\s:]+:)/.exec(url);
if (matches) {
return matches[1];
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/is-valid-protocol.js
/**
* Tests if a url protocol is valid.
*
* @param {string} protocol The url protocol.
*
* @example
* ```js
* const isValid = isValidProtocol( 'https:' ); // true
* const isNotValid = isValidProtocol( 'https :' ); // false
* ```
*
* @return {boolean} True if the argument is a valid protocol (e.g. http:, tel:).
*/
function isValidProtocol(protocol) {
if (!protocol) {
return false;
}
return /^[a-z\-.\+]+[0-9]*:$/i.test(protocol);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/get-authority.js
/**
* Returns the authority part of the URL.
*
* @param {string} url The full URL.
*
* @example
* ```js
* const authority1 = getAuthority( 'https://wordpress.org/help/' ); // 'wordpress.org'
* const authority2 = getAuthority( 'https://localhost:8080/test/' ); // 'localhost:8080'
* ```
*
* @return {string|void} The authority part of the URL.
*/
function getAuthority(url) {
const matches = /^[^\/\s:]+:(?:\/\/)?\/?([^\/\s#?]+)[\/#?]{0,1}\S*$/.exec(url);
if (matches) {
return matches[1];
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/is-valid-authority.js
/**
* Checks for invalid characters within the provided authority.
*
* @param {string} authority A string containing the URL authority.
*
* @example
* ```js
* const isValid = isValidAuthority( 'wordpress.org' ); // true
* const isNotValid = isValidAuthority( 'wordpress#org' ); // false
* ```
*
* @return {boolean} True if the argument contains a valid authority.
*/
function isValidAuthority(authority) {
if (!authority) {
return false;
}
return /^[^\s#?]+$/.test(authority);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/get-path.js
/**
* Returns the path part of the URL.
*
* @param {string} url The full URL.
*
* @example
* ```js
* const path1 = getPath( 'http://localhost:8080/this/is/a/test?query=true' ); // 'this/is/a/test'
* const path2 = getPath( 'https://wordpress.org/help/faq/' ); // 'help/faq'
* ```
*
* @return {string|void} The path part of the URL.
*/
function getPath(url) {
const matches = /^[^\/\s:]+:(?:\/\/)?[^\/\s#?]+[\/]([^\s#?]+)[#?]{0,1}\S*$/.exec(url);
if (matches) {
return matches[1];
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/is-valid-path.js
/**
* Checks for invalid characters within the provided path.
*
* @param {string} path The URL path.
*
* @example
* ```js
* const isValid = isValidPath( 'test/path/' ); // true
* const isNotValid = isValidPath( '/invalid?test/path/' ); // false
* ```
*
* @return {boolean} True if the argument contains a valid path
*/
function isValidPath(path) {
if (!path) {
return false;
}
return /^[^\s#?]+$/.test(path);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/get-query-string.js
/**
* Returns the query string part of the URL.
*
* @param {string} url The full URL.
*
* @example
* ```js
* const queryString = getQueryString( 'http://localhost:8080/this/is/a/test?query=true#fragment' ); // 'query=true'
* ```
*
* @return {string|void} The query string part of the URL.
*/
function getQueryString(url) {
let query;
try {
query = new URL(url, 'http://example.com').search.substring(1);
} catch (error) {}
if (query) {
return query;
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/build-query-string.js
/**
* Generates URL-encoded query string using input query data.
*
* It is intended to behave equivalent as PHP's `http_build_query`, configured
* with encoding type PHP_QUERY_RFC3986 (spaces as `%20`).
*
* @example
* ```js
* const queryString = buildQueryString( {
* simple: 'is ok',
* arrays: [ 'are', 'fine', 'too' ],
* objects: {
* evenNested: {
* ok: 'yes',
* },
* },
* } );
* // "simple=is%20ok&arrays%5B0%5D=are&arrays%5B1%5D=fine&arrays%5B2%5D=too&objects%5BevenNested%5D%5Bok%5D=yes"
* ```
*
* @param {Record<string,*>} data Data to encode.
*
* @return {string} Query string.
*/
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.
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]);
}
} else if (value !== undefined) {
// Null is treated as special case, equivalent to empty string.
if (value === null) {
value = '';
}
string += '&' + [key, value].map(encodeURIComponent).join('=');
}
} // 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);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/is-valid-query-string.js
/**
* Checks for invalid characters within the provided query string.
*
* @param {string} queryString The query string.
*
* @example
* ```js
* const isValid = isValidQueryString( 'query=true&another=false' ); // true
* const isNotValid = isValidQueryString( 'query=true?another=false' ); // false
* ```
*
* @return {boolean} True if the argument contains a valid query string.
*/
function isValidQueryString(queryString) {
if (!queryString) {
return false;
}
return /^[^\s#?\/]+$/.test(queryString);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/get-path-and-query-string.js
/**
* Internal dependencies
*/
/**
* Returns the path part and query string part of the URL.
*
* @param {string} url The full URL.
*
* @example
* ```js
* const pathAndQueryString1 = getPathAndQueryString( 'http://localhost:8080/this/is/a/test?query=true' ); // '/this/is/a/test?query=true'
* const pathAndQueryString2 = getPathAndQueryString( 'https://wordpress.org/help/faq/' ); // '/help/faq'
* ```
*
* @return {string} The path part and query string part of the URL.
*/
function getPathAndQueryString(url) {
const path = getPath(url);
const queryString = getQueryString(url);
let value = '/';
if (path) value += path;
if (queryString) value += `?${queryString}`;
return value;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/get-fragment.js
/**
* Returns the fragment part of the URL.
*
* @param {string} url The full URL
*
* @example
* ```js
* const fragment1 = getFragment( 'http://localhost:8080/this/is/a/test?query=true#fragment' ); // '#fragment'
* const fragment2 = getFragment( 'https://wordpress.org#another-fragment?query=true' ); // '#another-fragment'
* ```
*
* @return {string|void} The fragment part of the URL.
*/
function getFragment(url) {
const matches = /^\S+?(#[^\s\?]*)/.exec(url);
if (matches) {
return matches[1];
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/is-valid-fragment.js
/**
* Checks for invalid characters within the provided fragment.
*
* @param {string} fragment The url fragment.
*
* @example
* ```js
* const isValid = isValidFragment( '#valid-fragment' ); // true
* const isNotValid = isValidFragment( '#invalid-#fragment' ); // false
* ```
*
* @return {boolean} True if the argument contains a valid fragment.
*/
function isValidFragment(fragment) {
if (!fragment) {
return false;
}
return /^#[^\s#?\/]*$/.test(fragment);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/safe-decode-uri-component.js
/**
* Safely decodes a URI component with `decodeURIComponent`. Returns the URI component unmodified if
* `decodeURIComponent` throws an error.
*
* @param {string} uriComponent URI component to decode.
*
* @return {string} Decoded URI component if possible.
*/
function safeDecodeURIComponent(uriComponent) {
try {
return decodeURIComponent(uriComponent);
} catch (uriComponentError) {
return uriComponent;
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/get-query-args.js
/**
* Internal dependencies
*/
/** @typedef {import('./get-query-arg').QueryArgParsed} QueryArgParsed */
/**
* @typedef {Record<string,QueryArgParsed>} QueryArgs
*/
/**
* Sets a value in object deeply by a given array of path segments. Mutates the
* object reference.
*
* @param {Record<string,*>} object Object in which to assign.
* @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; // 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
// 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]
};
} // 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.
*
* @param {string} url URL.
*
* @example
* ```js
* const foo = getQueryArgs( 'https://wordpress.org?foo=bar&bar=baz' );
* // { "foo": "bar", "bar": "baz" }
* ```
*
* @return {QueryArgs} Query args object.
*/
function getQueryArgs(url) {
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
// 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));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/add-query-args.js
/**
* Internal dependencies
*/
/**
* Appends arguments as querystring to the provided URL. If the URL already
* includes query arguments, the arguments are merged with (and take precedent
* over) the existing set.
*
* @param {string} [url=''] URL to which arguments should be appended. If omitted,
* only the resulting querystring is returned.
* @param {Object} [args] Query arguments to apply to URL.
*
* @example
* ```js
* const newURL = addQueryArgs( 'https://google.com', { q: 'test' } ); // https://google.com/?q=test
* ```
*
* @return {string} URL with arguments applied.
*/
function addQueryArgs() {
let url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
let args = arguments.length > 1 ? arguments[1] : undefined;
// If no arguments are to be appended, return original URL.
if (!args || !Object.keys(args).length) {
return url;
}
let baseUrl = url; // 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.
baseUrl = baseUrl.substr(0, queryStringIndex);
}
return baseUrl + '?' + buildQueryString(args);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/get-query-arg.js
/**
* Internal dependencies
*/
/**
* @typedef {{[key: string]: QueryArgParsed}} QueryArgObject
*/
/**
* @typedef {string|string[]|QueryArgObject} QueryArgParsed
*/
/**
* Returns a single query argument of the url
*
* @param {string} url URL.
* @param {string} arg Query arg name.
*
* @example
* ```js
* const foo = getQueryArg( 'https://wordpress.org?foo=bar&bar=baz', 'foo' ); // bar
* ```
*
* @return {QueryArgParsed|void} Query arg value.
*/
function getQueryArg(url, arg) {
return getQueryArgs(url)[arg];
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/has-query-arg.js
/**
* Internal dependencies
*/
/**
* Determines whether the URL contains a given query arg.
*
* @param {string} url URL.
* @param {string} arg Query arg name.
*
* @example
* ```js
* const hasBar = hasQueryArg( 'https://wordpress.org?foo=bar&bar=baz', 'bar' ); // true
* ```
*
* @return {boolean} Whether or not the URL contains the query arg.
*/
function hasQueryArg(url, arg) {
return getQueryArg(url, arg) !== undefined;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/remove-query-args.js
/**
* Internal dependencies
*/
/**
* Removes arguments from the query string of the url
*
* @param {string} url URL.
* @param {...string} args Query Args.
*
* @example
* ```js
* const newUrl = removeQueryArgs( 'https://wordpress.org?foo=bar&bar=baz&baz=foobar', 'foo', 'bar' ); // https://wordpress.org?baz=foobar
* ```
*
* @return {string} Updated URL.
*/
function removeQueryArgs(url) {
const queryStringIndex = url.indexOf('?');
if (queryStringIndex === -1) {
return url;
}
const query = getQueryArgs(url);
const baseURL = url.substr(0, queryStringIndex);
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
args.forEach(arg => delete query[arg]);
const queryString = buildQueryString(query);
return queryString ? baseURL + '?' + queryString : baseURL;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/prepend-http.js
/**
* Internal dependencies
*/
const USABLE_HREF_REGEXP = /^(?:[a-z]+:|#|\?|\.|\/)/i;
/**
* Prepends "http://" to a url, if it looks like something that is meant to be a TLD.
*
* @param {string} url The URL to test.
*
* @example
* ```js
* const actualURL = prependHTTP( 'wordpress.org' ); // http://wordpress.org
* ```
*
* @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;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/safe-decode-uri.js
/**
* 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/url/build-module/filter-url-for-display.js
/**
* Returns a URL for display.
*
* @param {string} url Original URL.
* @param {number|null} maxLength URL length.
*
* @example
* ```js
* const displayUrl = filterURLForDisplay( 'https://www.wordpress.org/gutenberg/' ); // wordpress.org/gutenberg
* const imageUrl = filterURLForDisplay( 'https://www.wordpress.org/wp-content/uploads/img.png', 20 ); // …ent/uploads/img.png
* ```
*
* @return {string} Displayed URL.
*/
function filterURLForDisplay(url) {
let maxLength = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
// Remove protocol and www prefixes.
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.
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.
const index = file.lastIndexOf('.');
const [fileName, extension] = [file.slice(0, index), file.slice(index + 1)];
const truncatedFile = fileName.slice(-3) + '.' + extension;
return file.slice(0, maxLength - truncatedFile.length - 1) + '…' + truncatedFile;
}
// EXTERNAL MODULE: ./node_modules/remove-accents/index.js
var remove_accents = __webpack_require__(4793);
var remove_accents_default = /*#__PURE__*/__webpack_require__.n(remove_accents);
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/clean-for-slug.js
/**
* External dependencies
*/
/**
* Performs some basic cleanup of a string for use as a post slug.
*
* This replicates some of what `sanitize_title()` does in WordPress core, but
* is only designed to approximate what the slug will be.
*
* Converts Latin-1 Supplement and Latin Extended-A letters to basic Latin
* letters. Removes combining diacritical marks. Converts whitespace, periods,
* and forward slashes to hyphens. Removes any remaining non-word characters
* except hyphens. Converts remaining string to lowercase. It does not account
* for octets, HTML entities, or other encoded characters.
*
* @param {string} string Title or slug to be processed.
*
* @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.
.replace(/(^-+)|(-+$)/g, '');
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/get-filename.js
/**
* Returns the filename part of the URL.
*
* @param {string} url The full URL.
*
* @example
* ```js
* const filename1 = getFilename( 'http://localhost:8080/this/is/a/test.jpg' ); // 'test.jpg'
* const filename2 = getFilename( '/this/is/a/test.png' ); // 'test.png'
* ```
*
* @return {string|void} The filename part of the URL.
*/
function getFilename(url) {
let filename;
try {
filename = new URL(url, 'http://example.com').pathname.split('/').pop();
} catch (error) {}
if (filename) {
return filename;
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/normalize-path.js
/**
* Given a path, returns a normalized path where equal query parameter values
* will be treated as identical, regardless of order they appear in the original
* text.
*
* @param {string} path Original path.
*
* @return {string} Normalized path.
*/
function 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'
.join('&');
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/url/build-module/index.js
}();
(window.wp = window.wp || {}).url = __webpack_exports__;
/******/ })()
; annotations.js 0000666 00000077300 15123355174 0007460 0 ustar 00 /******/ (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__, {
"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; }
});
// 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; }
});
;// CONCATENATED MODULE: external ["wp","richText"]
var external_wp_richText_namespaceObject = window["wp"]["richText"];
;// CONCATENATED MODULE: external ["wp","i18n"]
var external_wp_i18n_namespaceObject = window["wp"]["i18n"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/annotations/build-module/store/constants.js
/**
* The identifier for the data store.
*
* @type {string}
*/
const STORE_NAME = 'core/annotations';
;// CONCATENATED MODULE: ./node_modules/@wordpress/annotations/build-module/format/annotation.js
/**
* WordPress dependencies
*/
const FORMAT_NAME = 'core/annotation';
const ANNOTATION_ATTRIBUTE_PREFIX = 'annotation-text-';
/**
* Internal dependencies
*/
/**
* Applies given annotations to the given record.
*
* @param {Object} record The record to apply annotations to.
* @param {Array} annotations The annotation to apply.
* @return {Object} A record with the annotations applied.
*/
function applyAnnotations(record) {
let annotations = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
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, {
type: FORMAT_NAME,
attributes: {
className,
id
}
}, start, end);
});
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) => {
characterFormats = characterFormats || [];
characterFormats = characterFormats.filter(format => format.type === FORMAT_NAME);
characterFormats.forEach(format => {
let {
id
} = format.attributes;
id = id.replace(ANNOTATION_ATTRIBUTE_PREFIX, '');
if (!positions.hasOwnProperty(id)) {
positions[id] = {
start: i
};
} // 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.
*
* @param {Array} annotations The annotations that are currently applied.
* @param {Array} positions The current positions of the given annotations.
* @param {Object} actions
* @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, _ref) {
let {
removeAnnotation,
updateAnnotationRange
} = _ref;
annotations.forEach(currentAnnotation => {
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'),
tagName: 'mark',
className: 'annotation-text',
attributes: {
className: 'class',
id: 'id'
},
edit() {
return null;
},
__experimentalGetPropsForEditableTreePreparation(select, _ref2) {
let {
richTextIdentifier,
blockClientId
} = _ref2;
return {
annotations: select(STORE_NAME).__experimentalGetAnnotationsForRichText(blockClientId, richTextIdentifier)
};
},
__experimentalCreatePrepareEditableTree(_ref3) {
let {
annotations
} = _ref3;
return (formats, text) => {
if (annotations.length === 0) {
return formats;
}
let record = {
formats,
text
};
record = applyAnnotations(record, annotations);
return record.formats;
};
},
__experimentalGetPropsForEditableTreeChangeHandler(dispatch) {
return {
removeAnnotation: dispatch(STORE_NAME).__experimentalRemoveAnnotation,
updateAnnotationRange: dispatch(STORE_NAME).__experimentalUpdateAnnotationRange
};
},
__experimentalCreateOnChangeEditableValue(props) {
return formats => {
const positions = retrieveAnnotationPositions(formats);
const {
removeAnnotation,
updateAnnotationRange,
annotations
} = props;
updateAnnotationsWithPositions(annotations, positions, {
removeAnnotation,
updateAnnotationRange
});
};
}
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/annotations/build-module/format/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const {
name: format_name,
...settings
} = annotation;
(0,external_wp_richText_namespaceObject.registerFormatType)(format_name, settings);
;// CONCATENATED MODULE: external ["wp","hooks"]
var external_wp_hooks_namespaceObject = window["wp"]["hooks"];
;// CONCATENATED MODULE: external ["wp","data"]
var external_wp_data_namespaceObject = window["wp"]["data"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/annotations/build-module/block/index.js
/**
* WordPress dependencies
*/
/**
* 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, _ref) => {
let {
clientId,
className
} = _ref;
const annotations = select(STORE_NAME).__experimentalGetAnnotationsForBlock(clientId);
return {
className: annotations.map(annotation => {
return 'is-annotated-by-' + annotation.source;
}).concat(className).filter(Boolean).join(' ')
};
})(OriginalComponent);
};
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockListBlock', 'core/annotations', addAnnotationClassName);
;// CONCATENATED MODULE: ./node_modules/@wordpress/annotations/build-module/store/reducer.js
/**
* Filters an array based on the predicate, but keeps the reference the same if
* the array hasn't changed.
*
* @param {Array} collection The collection to filter.
* @param {Function} predicate Function that determines if the item should stay
* in the array.
* @return {Array} Filtered array.
*/
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.
*
* @param {Object} obj The object to transform.
* @param {Function} callback The function to transform each object value.
* @return {Array} Transformed object.
*/
const mapValues = (obj, callback) => Object.entries(obj).reduce((acc, _ref) => {
let [key, value] = _ref;
return { ...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.
*
* @param {Object} state The annotations currently shown in the editor.
* @param {Object} action Dispatched action.
*
* @return {Array} Updated state.
*/
function annotations() {
var _state$blockClientId;
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'ANNOTATION_ADD':
const blockClientId = action.blockClientId;
const newAnnotation = {
id: action.id,
blockClientId,
richTextIdentifier: action.richTextIdentifier,
source: action.source,
selector: action.selector,
range: action.range
};
if (newAnnotation.selector === 'range' && !isValidAnnotationRange(newAnnotation.range)) {
return state;
}
const previousAnnotationsForBlock = (_state$blockClientId = state === null || state === void 0 ? void 0 : state[blockClientId]) !== null && _state$blockClientId !== void 0 ? _state$blockClientId : [];
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,
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 => {
return annotation.source !== action.source;
});
});
}
return state;
}
/* harmony default export */ var reducer = (annotations);
;// CONCATENATED MODULE: ./node_modules/rememo/rememo.js
/** @typedef {(...args: any[]) => *[]} GetDependants */
/** @typedef {() => void} Clear */
/**
* @typedef {{
* getDependants: GetDependants,
* clear: Clear
* }} EnhancedSelector
*/
/**
* Internal cache entry.
*
* @typedef CacheNode
*
* @property {?CacheNode|undefined} [prev] Previous node.
* @property {?CacheNode|undefined} [next] Next node.
* @property {*[]} args Function arguments for cache entry.
* @property {*} val Function result.
*/
/**
* @typedef Cache
*
* @property {Clear} clear Function to clear cache.
* @property {boolean} [isUniqueByDependants] Whether dependants are valid in
* considering cache uniqueness. A cache is unique if dependents are all arrays
* or objects.
* @property {CacheNode?} [head] Cache head.
* @property {*[]} [lastDependants] Dependants from previous invocation.
*/
/**
* Arbitrary value used as key for referencing cache object in WeakMap tree.
*
* @type {{}}
*/
var LEAF_KEY = {};
/**
* Returns the first argument as the sole entry in an array.
*
* @template T
*
* @param {T} value Value to return.
*
* @return {[T]} Value returned as entry in array.
*/
function arrayOf(value) {
return [value];
}
/**
* Returns true if the value passed is object-like, or false otherwise. A value
* is object-like if it can support property assignment, e.g. object or array.
*
* @param {*} value Value to test.
*
* @return {boolean} Whether value is object-like.
*/
function isObjectLike(value) {
return !!value && 'object' === typeof value;
}
/**
* Creates and returns a new cache object.
*
* @return {Cache} Cache object.
*/
function createCache() {
/** @type {Cache} */
var cache = {
clear: function () {
cache.head = null;
},
};
return cache;
}
/**
* Returns true if entries within the two arrays are strictly equal by
* reference from a starting index.
*
* @param {*[]} a First array.
* @param {*[]} b Second array.
* @param {number} fromIndex Index from which to start comparison.
*
* @return {boolean} Whether arrays are shallowly equal.
*/
function isShallowEqual(a, b, fromIndex) {
var i;
if (a.length !== b.length) {
return false;
}
for (i = fromIndex; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
/**
* Returns a memoized selector function. The getDependants function argument is
* called before the memoized selector and is expected to return an immutable
* reference or array of references on which the selector depends for computing
* its own return value. The memoize cache is preserved only as long as those
* dependant references remain the same. If getDependants returns a different
* reference(s), the cache is cleared and the selector value regenerated.
*
* @template {(...args: *[]) => *} S
*
* @param {S} selector Selector function.
* @param {GetDependants=} getDependants Dependant getter returning an array of
* references used in cache bust consideration.
*/
/* harmony default export */ function rememo(selector, getDependants) {
/** @type {WeakMap<*,*>} */
var rootCache;
/** @type {GetDependants} */
var normalizedGetDependants = getDependants ? getDependants : arrayOf;
/**
* Returns the cache for a given dependants array. When possible, a WeakMap
* will be used to create a unique cache for each set of dependants. This
* is feasible due to the nature of WeakMap in allowing garbage collection
* to occur on entries where the key object is no longer referenced. Since
* WeakMap requires the key to be an object, this is only possible when the
* dependant is object-like. The root cache is created as a hierarchy where
* each top-level key is the first entry in a dependants set, the value a
* WeakMap where each key is the next dependant, and so on. This continues
* so long as the dependants are object-like. If no dependants are object-
* like, then the cache is shared across all invocations.
*
* @see isObjectLike
*
* @param {*[]} dependants Selector dependants.
*
* @return {Cache} Cache object.
*/
function getCache(dependants) {
var caches = rootCache,
isUniqueByDependants = true,
i,
dependant,
map,
cache;
for (i = 0; i < dependants.length; i++) {
dependant = dependants[i];
// Can only compose WeakMap from object-like key.
if (!isObjectLike(dependant)) {
isUniqueByDependants = false;
break;
}
// Does current segment of cache already have a WeakMap?
if (caches.has(dependant)) {
// Traverse into nested WeakMap.
caches = caches.get(dependant);
} else {
// Create, set, and traverse into a new one.
map = new WeakMap();
caches.set(dependant, map);
caches = map;
}
}
// We use an arbitrary (but consistent) object as key for the last item
// in the WeakMap to serve as our running cache.
if (!caches.has(LEAF_KEY)) {
cache = createCache();
cache.isUniqueByDependants = isUniqueByDependants;
caches.set(LEAF_KEY, cache);
}
return caches.get(LEAF_KEY);
}
/**
* Resets root memoization cache.
*/
function clear() {
rootCache = new WeakMap();
}
/* eslint-disable jsdoc/check-param-names */
/**
* The augmented selector call, considering first whether dependants have
* changed before passing it to underlying memoize function.
*
* @param {*} source Source object for derivation.
* @param {...*} extraArgs Additional arguments to pass to selector.
*
* @return {*} Selector result.
*/
/* eslint-enable jsdoc/check-param-names */
function callSelector(/* source, ...extraArgs */) {
var len = arguments.length,
cache,
node,
i,
args,
dependants;
// Create copy of arguments (avoid leaking deoptimization).
args = new Array(len);
for (i = 0; i < len; i++) {
args[i] = arguments[i];
}
dependants = normalizedGetDependants.apply(null, args);
cache = getCache(dependants);
// If not guaranteed uniqueness by dependants (primitive type), shallow
// compare against last dependants and, if references have changed,
// destroy cache to recalculate result.
if (!cache.isUniqueByDependants) {
if (
cache.lastDependants &&
!isShallowEqual(dependants, cache.lastDependants, 0)
) {
cache.clear();
}
cache.lastDependants = dependants;
}
node = cache.head;
while (node) {
// Check whether node arguments match arguments
if (!isShallowEqual(node.args, args, 1)) {
node = node.next;
continue;
}
// At this point we can assume we've found a match
// Surface matched node to head if not already
if (node !== cache.head) {
// Adjust siblings to point to each other.
/** @type {CacheNode} */ (node.prev).next = node.next;
if (node.next) {
node.next.prev = node.prev;
}
node.next = cache.head;
node.prev = null;
/** @type {CacheNode} */ (cache.head).prev = node;
cache.head = node;
}
// Return immediately
return node.val;
}
// No cached value found. Continue to insertion phase:
node = /** @type {CacheNode} */ ({
// Generate the result from original function
val: selector.apply(null, args),
});
// Avoid including the source object in the cache.
args[0] = null;
node.args = args;
// Don't need to check whether node is already head, since it would
// have been returned above already if it was
// Shift existing head down list
if (cache.head) {
cache.head.prev = node;
node.next = cache.head;
}
cache.head = node;
return node.val;
}
callSelector.getDependants = normalizedGetDependants;
callSelector.clear = clear;
clear();
return /** @type {S & EnhancedSelector} */ (callSelector);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/annotations/build-module/store/selectors.js
/**
* 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
* other pure component which performs `shouldComponentUpdate` check on props.
* This should be used as a last resort, since the normalized data should be
* maintained by the reducer result in state.
*
* @type {Array}
*/
const EMPTY_ARRAY = [];
/**
* Returns the annotations for a specific client ID.
*
* @param {Object} state Editor state.
* @param {string} clientId The ID of the block to get the annotations for.
*
* @return {Array} The annotations applicable to this block.
*/
const __experimentalGetAnnotationsForBlock = rememo((state, blockClientId) => {
var _state$blockClientId;
return ((_state$blockClientId = state === null || state === void 0 ? void 0 : state[blockClientId]) !== null && _state$blockClientId !== void 0 ? _state$blockClientId : []).filter(annotation => {
return annotation.selector === 'block';
});
}, (state, blockClientId) => {
var _state$blockClientId2;
return [(_state$blockClientId2 = state === null || state === void 0 ? void 0 : state[blockClientId]) !== null && _state$blockClientId2 !== void 0 ? _state$blockClientId2 : EMPTY_ARRAY];
});
function __experimentalGetAllAnnotationsForBlock(state, blockClientId) {
var _state$blockClientId3;
return (_state$blockClientId3 = state === null || state === void 0 ? void 0 : state[blockClientId]) !== null && _state$blockClientId3 !== void 0 ? _state$blockClientId3 : EMPTY_ARRAY;
}
/**
* Returns the annotations that apply to the given RichText instance.
*
* Both a blockClientId and a richTextIdentifier are required. This is because
* a block might have multiple `RichText` components. This does mean that every
* block needs to implement annotations itself.
*
* @param {Object} state Editor state.
* @param {string} blockClientId The client ID for the block.
* @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 === null || state === void 0 ? void 0 : state[blockClientId]) !== null && _state$blockClientId4 !== void 0 ? _state$blockClientId4 : []).filter(annotation => {
return annotation.selector === 'range' && richTextIdentifier === annotation.richTextIdentifier;
}).map(annotation => {
const {
range,
...other
} = annotation;
return { ...range,
...other
};
});
}, (state, blockClientId) => {
var _state$blockClientId5;
return [(_state$blockClientId5 = state === null || state === void 0 ? void 0 : 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
// 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);
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);
if (!getRandomValues) {
throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
}
}
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
/**
* Convert array of 16 byte values to UUID string format of the form:
* XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
*/
var byteToHex = [];
for (var i = 0; i < 256; ++i) {
byteToHex.push((i + 0x100).toString(16).substr(1));
}
function stringify(arr) {
var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 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
// 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)) {
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
function v4(options, buf, offset) {
options = options || {};
var 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
if (buf) {
offset = offset || 0;
for (var i = 0; i < 16; ++i) {
buf[offset + i] = rnds[i];
}
return buf;
}
return esm_browser_stringify(rnds);
}
/* harmony default export */ var esm_browser_v4 = (v4);
;// CONCATENATED MODULE: ./node_modules/@wordpress/annotations/build-module/store/actions.js
/**
* External dependencies
*/
/**
* @typedef WPAnnotationRange
*
* @property {number} start The offset where the annotation should start.
* @property {number} end The offset where the annotation should end.
*/
/**
* Adds an annotation to a block.
*
* The `block` attribute refers to a block ID that needs to be annotated.
* `isBlockAnnotation` controls whether or not the annotation is a block
* annotation. The `source` is the source of the annotation, this will be used
* to identity groups of annotations.
*
* The `range` property is only relevant if the selector is 'range'.
*
* @param {Object} annotation The annotation to add.
* @param {string} annotation.blockClientId The blockClientId to add the annotation to.
* @param {string} annotation.richTextIdentifier Identifier for the RichText instance the annotation applies to.
* @param {WPAnnotationRange} annotation.range The range at which to apply this annotation.
* @param {string} [annotation.selector="range"] The way to apply this annotation.
* @param {string} [annotation.source="default"] The source that added the annotation.
* @param {string} [annotation.id] The ID the annotation should have. Generates a UUID by default.
*
* @return {Object} Action object.
*/
function __experimentalAddAnnotation(_ref) {
let {
blockClientId,
richTextIdentifier = null,
range = null,
selector = 'range',
source = 'default',
id = esm_browser_v4()
} = _ref;
const action = {
type: 'ANNOTATION_ADD',
id,
blockClientId,
richTextIdentifier,
source,
selector
};
if (selector === 'range') {
action.range = range;
}
return action;
}
/**
* Removes an annotation with a specific ID.
*
* @param {string} annotationId The annotation to remove.
*
* @return {Object} Action object.
*/
function __experimentalRemoveAnnotation(annotationId) {
return {
type: 'ANNOTATION_REMOVE',
annotationId
};
}
/**
* Updates the range of an annotation.
*
* @param {string} annotationId ID of the annotation to update.
* @param {number} start The start of the new range.
* @param {number} end The end of the new range.
*
* @return {Object} Action object.
*/
function __experimentalUpdateAnnotationRange(annotationId, start, end) {
return {
type: 'ANNOTATION_UPDATE_RANGE',
annotationId,
start,
end
};
}
/**
* Removes all annotations of a specific source.
*
* @param {string} source The source to remove.
*
* @return {Object} Action object.
*/
function __experimentalRemoveAnnotationsBySource(source) {
return {
type: 'ANNOTATION_REMOVE_SOURCE',
source
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/annotations/build-module/store/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Module Constants
*/
/**
* Store definition for the annotations 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, {
reducer: reducer,
selectors: selectors_namespaceObject,
actions: actions_namespaceObject
});
(0,external_wp_data_namespaceObject.register)(store);
;// CONCATENATED MODULE: ./node_modules/@wordpress/annotations/build-module/index.js
/**
* Internal dependencies
*/
(window.wp = window.wp || {}).annotations = __webpack_exports__;
/******/ })()
; widgets.min.js 0000666 00000053031 15123355174 0007346 0 ustar 00 /*! This file is auto-generated */
!function(){var e={7153:function(e,t){var n;
/*!
Copyright (c) 2018 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/!function(){"use strict";var i={}.hasOwnProperty;function r(){for(var e="",t=0;t<arguments.length;t++){var n=arguments[t];n&&(e=o(e,a(n)))}return e}function a(e){if("string"==typeof e||"number"==typeof e)return e;if("object"!=typeof e)return"";if(Array.isArray(e))return r.apply(null,e);if(e.toString!==Object.prototype.toString&&!e.toString.toString().includes("[native code]"))return e.toString();var t="";for(var n in e)i.call(e,n)&&e[n]&&(t=o(t,n));return t}function o(e,t){return t?e?e+" "+t:e+t:e}e.exports?(r.default=r,e.exports=r):void 0===(n=function(){return r}.apply(t,[]))||(e.exports=n)}()}},t={};function n(i){var r=t[i];if(void 0!==r)return r.exports;var a=t[i]={exports:{}};return e[i](a,a.exports,n),a.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 i in t)n.o(t,i)&&!n.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},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 i={};!function(){"use strict";n.r(i),n.d(i,{MoveToWidgetArea:function(){return J},addWidgetIdToBlock:function(){return q},getWidgetIdFromBlock:function(){return X},registerLegacyWidgetBlock:function(){return Y},registerLegacyWidgetVariations:function(){return K},registerWidgetGroupBlock:function(){return ee}});var e={};n.r(e),n.d(e,{metadata:function(){return A},name:function(){return W},settings:function(){return O}});var t={};n.r(t),n.d(t,{metadata:function(){return Q},name:function(){return $},settings:function(){return Z}});var r=window.wp.blocks,a=window.wp.element,o=window.wp.primitives;var l=(0,a.createElement)(o.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,a.createElement)(o.Path,{d:"M6 3H8V5H16V3H18V5C19.1046 5 20 5.89543 20 7V19C20 20.1046 19.1046 21 18 21H6C4.89543 21 4 20.1046 4 19V7C4 5.89543 4.89543 5 6 5V3ZM18 6.5H6C5.72386 6.5 5.5 6.72386 5.5 7V8H18.5V7C18.5 6.72386 18.2761 6.5 18 6.5ZM18.5 9.5H5.5V19C5.5 19.2761 5.72386 19.5 6 19.5H18C18.2761 19.5 18.5 19.2761 18.5 19V9.5ZM11 11H13V13H11V11ZM7 11V13H9V11H7ZM15 13V11H17V13H15Z"})),s=n(7153),c=n.n(s),d=window.wp.blockEditor,u=window.wp.components;var m=(0,a.createElement)(o.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,a.createElement)(o.Path,{d:"M4 20h8v-1.5H4V20zM18.9 3.5c-.6-.6-1.5-.6-2.1 0l-7.2 7.2c-.4-.1-.7 0-1.1.1-.5.2-1.5.7-1.9 2.2-.4 1.7-.8 2.2-1.1 2.7-.1.1-.2.3-.3.4l-.6 1.1H6c2 0 3.4-.4 4.7-1.4.8-.6 1.2-1.4 1.3-2.3 0-.3 0-.5-.1-.7L19 5.7c.5-.6.5-1.6-.1-2.2zM9.7 14.7c-.7.5-1.5.8-2.4 1 .2-.5.5-1.2.8-2.3.2-.6.4-1 .8-1.1.5-.1 1 .1 1.3.3.2.2.3.5.2.8 0 .3-.1.9-.7 1.3z"})),h=window.wp.i18n,w=window.wp.data,g=window.wp.coreData;function p(e){let{selectedId:t,onSelect:n}=e;const i=(0,w.useSelect)((e=>{var t,n,i;const r=null!==(t=null===(n=e(d.store).getSettings())||void 0===n?void 0:n.widgetTypesToHideFromLegacyWidgetBlock)&&void 0!==t?t:[];return null===(i=e(g.store).getWidgetTypes({per_page:-1}))||void 0===i?void 0:i.filter((e=>!r.includes(e.id)))}),[]);return i?0===i.length?(0,h.__)("There are no widgets available."):(0,a.createElement)(u.SelectControl,{__nextHasNoMarginBottom:!0,label:(0,h.__)("Select a legacy widget to display:"),value:null!=t?t:"",options:[{value:"",label:(0,h.__)("Select widget")},...i.map((e=>({value:e.id,label:e.name})))],onChange:e=>{if(e){const t=i.find((t=>t.id===e));n({selectedId:t.id,isMulti:t.is_multi})}else n({selectedId:null})}}):(0,a.createElement)(u.Spinner,null)}function f(e){let{name:t,description:n}=e;return(0,a.createElement)("div",{className:"wp-block-legacy-widget-inspector-card"},(0,a.createElement)("h3",{className:"wp-block-legacy-widget-inspector-card__name"},t),(0,a.createElement)("span",null,n))}var v=window.wp.notices,b=window.wp.compose,y=window.wp.apiFetch,E=n.n(y);class _{constructor(e){let{id:t,idBase:n,instance:i,onChangeInstance:r,onChangeHasPreview:a,onError:o}=e;this.id=t,this.idBase=n,this._instance=i,this._hasPreview=null,this.onChangeInstance=r,this.onChangeHasPreview=a,this.onError=o,this.number=++k,this.handleFormChange=(0,b.debounce)(this.handleFormChange.bind(this),200),this.handleFormSubmit=this.handleFormSubmit.bind(this),this.initDOM(),this.bindEvents(),this.loadContent()}destroy(){this.unbindEvents(),this.element.remove()}initDOM(){var e,t;this.element=B("div",{class:"widget open"},[B("div",{class:"widget-inside"},[this.form=B("form",{class:"form",method:"post"},[B("input",{class:"widget-id",type:"hidden",name:"widget-id",value:null!==(e=this.id)&&void 0!==e?e:`${this.idBase}-${this.number}`}),B("input",{class:"id_base",type:"hidden",name:"id_base",value:null!==(t=this.idBase)&&void 0!==t?t:this.id}),B("input",{class:"widget-width",type:"hidden",name:"widget-width",value:"250"}),B("input",{class:"widget-height",type:"hidden",name:"widget-height",value:"200"}),B("input",{class:"widget_number",type:"hidden",name:"widget_number",value:this.idBase?this.number.toString():""}),this.content=B("div",{class:"widget-content"}),this.id&&B("button",{class:"button is-primary",type:"submit"},(0,h.__)("Save"))])])])}bindEvents(){if(window.jQuery){const{jQuery:e}=window;e(this.form).on("change",null,this.handleFormChange),e(this.form).on("input",null,this.handleFormChange),e(this.form).on("submit",this.handleFormSubmit)}else this.form.addEventListener("change",this.handleFormChange),this.form.addEventListener("input",this.handleFormChange),this.form.addEventListener("submit",this.handleFormSubmit)}unbindEvents(){if(window.jQuery){const{jQuery:e}=window;e(this.form).off("change",null,this.handleFormChange),e(this.form).off("input",null,this.handleFormChange),e(this.form).off("submit",this.handleFormSubmit)}else this.form.removeEventListener("change",this.handleFormChange),this.form.removeEventListener("input",this.handleFormChange),this.form.removeEventListener("submit",this.handleFormSubmit)}async loadContent(){try{if(this.id){const{form:e}=await C(this.id);this.content.innerHTML=e}else if(this.idBase){const{form:e,preview:t}=await S({idBase:this.idBase,instance:this.instance,number:this.number});if(this.content.innerHTML=e,this.hasPreview=!T(t),!this.instance.hash){const{instance:e}=await S({idBase:this.idBase,instance:this.instance,number:this.number,formData:H(this.form)});this.instance=e}}if(window.jQuery){const{jQuery:e}=window;e(document).trigger("widget-added",[e(this.element)])}}catch(e){this.onError(e)}}handleFormChange(){this.idBase&&this.saveForm()}handleFormSubmit(e){e.preventDefault(),this.saveForm()}async saveForm(){const e=H(this.form);try{if(this.id){const{form:t}=await C(this.id,e);if(this.content.innerHTML=t,window.jQuery){const{jQuery:e}=window;e(document).trigger("widget-updated",[e(this.element)])}}else if(this.idBase){const{instance:t,preview:n}=await S({idBase:this.idBase,instance:this.instance,number:this.number,formData:e});this.instance=t,this.hasPreview=!T(n)}}catch(e){this.onError(e)}}get instance(){return this._instance}set instance(e){this._instance!==e&&(this._instance=e,this.onChangeInstance(e))}get hasPreview(){return this._hasPreview}set hasPreview(e){this._hasPreview!==e&&(this._hasPreview=e,this.onChangeHasPreview(e))}}let k=0;function B(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;const i=document.createElement(e);for(const[e,n]of Object.entries(t))i.setAttribute(e,n);if(Array.isArray(n))for(const e of n)e&&i.appendChild(e);else"string"==typeof n&&(i.innerText=n);return i}async function C(e){let t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return t=n?await E()({path:`/wp/v2/widgets/${e}?context=edit`,method:"PUT",data:{form_data:n}}):await E()({path:`/wp/v2/widgets/${e}?context=edit`,method:"GET"}),{form:t.rendered_form}}async function S(e){let{idBase:t,instance:n,number:i,formData:r=null}=e;const a=await E()({path:`/wp/v2/widget-types/${t}/encode`,method:"POST",data:{instance:n,number:i,form_data:r}});return{instance:a.instance,form:a.form,preview:a.preview}}function T(e){const t=document.createElement("div");return t.innerHTML=e,M(t)}function M(e){switch(e.nodeType){case e.TEXT_NODE:return""===e.nodeValue.trim();case e.ELEMENT_NODE:return!["AUDIO","CANVAS","EMBED","IFRAME","IMG","MATH","OBJECT","SVG","VIDEO"].includes(e.tagName)&&(!e.hasChildNodes()||Array.from(e.childNodes).every(M));default:return!0}}function H(e){return new window.URLSearchParams(Array.from(new window.FormData(e))).toString()}function I(e){let{title:t,isVisible:n,id:i,idBase:r,instance:o,isWide:l,onChangeInstance:s,onChangeHasPreview:d}=e;const m=(0,a.useRef)(),g=(0,b.useViewportMatch)("small"),p=(0,a.useRef)(new Set),f=(0,a.useRef)(new Set),{createNotice:y}=(0,w.useDispatch)(v.store);return(0,a.useEffect)((()=>{if(f.current.has(o))return void f.current.delete(o);const e=new _({id:i,idBase:r,instance:o,onChangeInstance(e){p.current.add(o),f.current.add(e),s(e)},onChangeHasPreview:d,onError(e){window.console.error(e),y("error",(0,h.sprintf)((0,h.__)('The "%s" block was affected by errors and may not function properly. Check the developer tools for more details.'),r||i))}});return m.current.appendChild(e.element),()=>{p.current.has(o)?p.current.delete(o):e.destroy()}}),[i,r,o,s,d,g]),l&&g?(0,a.createElement)("div",{className:c()({"wp-block-legacy-widget__container":n})},n&&(0,a.createElement)("h3",{className:"wp-block-legacy-widget__edit-form-title"},t),(0,a.createElement)(u.Popover,{focusOnMount:!1,placement:"right",offset:32,resize:!1,flip:!1,shift:!0},(0,a.createElement)("div",{ref:m,className:"wp-block-legacy-widget__edit-form",hidden:!n}))):(0,a.createElement)("div",{ref:m,className:"wp-block-legacy-widget__edit-form",hidden:!n},(0,a.createElement)("h3",{className:"wp-block-legacy-widget__edit-form-title"},t))}function P(e){let{idBase:t,instance:n,isVisible:i}=e;const[r,o]=(0,a.useState)(!1),[l,s]=(0,a.useState)("");(0,a.useEffect)((()=>{const e=void 0===window.AbortController?void 0:new window.AbortController;return async function(){const i=`/wp/v2/widget-types/${t}/render`;return await E()({path:i,method:"POST",signal:null==e?void 0:e.signal,data:n?{instance:n}:{}})}().then((e=>{s(e.preview)})).catch((e=>{if("AbortError"!==e.name)throw e})),()=>null==e?void 0:e.abort()}),[t,n]);const d=(0,b.useRefEffect)((e=>{if(!r)return;function t(){var t,n,i,r;const a=Math.max(null!==(t=null===(n=e.contentDocument.documentElement)||void 0===n?void 0:n.offsetHeight)&&void 0!==t?t:0,null!==(i=null===(r=e.contentDocument.body)||void 0===r?void 0:r.offsetHeight)&&void 0!==i?i:0);e.style.height=`${0!==a?a:100}px`}const{IntersectionObserver:n}=e.ownerDocument.defaultView,i=new n((e=>{let[n]=e;n.isIntersecting&&t()}),{threshold:1});return i.observe(e),e.addEventListener("load",t),()=>{i.disconnect(),e.removeEventListener("load",t)}}),[r]);return(0,a.createElement)(a.Fragment,null,i&&!r&&(0,a.createElement)(u.Placeholder,null,(0,a.createElement)(u.Spinner,null)),(0,a.createElement)("div",{className:c()("wp-block-legacy-widget__edit-preview",{"is-offscreen":!i||!r})},(0,a.createElement)(u.Disabled,null,(0,a.createElement)("iframe",{ref:d,className:"wp-block-legacy-widget__edit-preview-iframe",tabIndex:"-1",title:(0,h.__)("Legacy Widget Preview"),srcDoc:l,onLoad:e=>{e.target.contentDocument.body.style.overflow="hidden",o(!0)},height:100}))))}function V(e){let{name:t}=e;return(0,a.createElement)("div",{className:"wp-block-legacy-widget__edit-no-preview"},t&&(0,a.createElement)("h3",null,t),(0,a.createElement)("p",null,(0,h.__)("No preview available.")))}function F(e){let{clientId:t,rawInstance:n}=e;const{replaceBlocks:i}=(0,w.useDispatch)(d.store);return(0,a.createElement)(u.ToolbarButton,{onClick:()=>{n.title?i(t,[(0,r.createBlock)("core/heading",{content:n.title}),...(0,r.rawHandler)({HTML:n.text})]):i(t,(0,r.rawHandler)({HTML:n.text}))}},(0,h.__)("Convert to blocks"))}function x(e){let{attributes:{id:t,idBase:n},setAttributes:i}=e;return(0,a.createElement)(u.Placeholder,{icon:(0,a.createElement)(d.BlockIcon,{icon:m}),label:(0,h.__)("Legacy Widget")},(0,a.createElement)(u.Flex,null,(0,a.createElement)(u.FlexBlock,null,(0,a.createElement)(p,{selectedId:null!=t?t:n,onSelect:e=>{let{selectedId:t,isMulti:n}=e;i(t?n?{id:null,idBase:t,instance:{}}:{id:t,idBase:null,instance:null}:{id:null,idBase:null,instance:null})}}))))}function N(e){let{attributes:{id:t,idBase:n,instance:i},setAttributes:r,clientId:o,isSelected:l,isWide:s=!1}=e;const[c,p]=(0,a.useState)(null),v=null!=t?t:n,{record:b,hasResolved:y}=(0,g.useEntityRecord)("root","widgetType",v),E=(0,w.useSelect)((e=>e(d.store).isNavigationMode()),[]),_=(0,a.useCallback)((e=>{r({instance:e})}),[]);if(!b&&y)return(0,a.createElement)(u.Placeholder,{icon:(0,a.createElement)(d.BlockIcon,{icon:m}),label:(0,h.__)("Legacy Widget")},(0,h.__)("Widget is missing."));if(!y)return(0,a.createElement)(u.Placeholder,null,(0,a.createElement)(u.Spinner,null));const k=!n||!E&&l?"edit":"preview";return(0,a.createElement)(a.Fragment,null,"text"===n&&(0,a.createElement)(d.BlockControls,{group:"other"},(0,a.createElement)(F,{clientId:o,rawInstance:i.raw})),(0,a.createElement)(d.InspectorControls,null,(0,a.createElement)(f,{name:b.name,description:b.description})),(0,a.createElement)(I,{title:b.name,isVisible:"edit"===k,id:t,idBase:n,instance:i,isWide:s,onChangeInstance:_,onChangeHasPreview:p}),n&&(0,a.createElement)(a.Fragment,null,null===c&&"preview"===k&&(0,a.createElement)(u.Placeholder,null,(0,a.createElement)(u.Spinner,null)),!0===c&&(0,a.createElement)(P,{idBase:n,instance:i,isVisible:"preview"===k}),!1===c&&"preview"===k&&(0,a.createElement)(V,{name:b.name})))}const L=[{block:"core/calendar",widget:"calendar"},{block:"core/search",widget:"search"},{block:"core/html",widget:"custom_html",transform:e=>{let{content:t}=e;return{content:t}}},{block:"core/archives",widget:"archives",transform:e=>{let{count:t,dropdown:n}=e;return{displayAsDropdown:!!n,showPostCounts:!!t}}},{block:"core/latest-posts",widget:"recent-posts",transform:e=>{let{show_date:t,number:n}=e;return{displayPostDate:!!t,postsToShow:n}}},{block:"core/latest-comments",widget:"recent-comments",transform:e=>{let{number:t}=e;return{commentsToShow:t}}},{block:"core/tag-cloud",widget:"tag_cloud",transform:e=>{let{taxonomy:t,count:n}=e;return{showTagCounts:!!n,taxonomy:t}}},{block:"core/categories",widget:"categories",transform:e=>{let{count:t,dropdown:n,hierarchical:i}=e;return{displayAsDropdown:!!n,showPostCounts:!!t,showHierarchy:!!i}}},{block:"core/audio",widget:"media_audio",transform:e=>{let{url:t,preload:n,loop:i,attachment_id:r}=e;return{src:t,id:r,preload:n,loop:i}}},{block:"core/video",widget:"media_video",transform:e=>{let{url:t,preload:n,loop:i,attachment_id:r}=e;return{src:t,id:r,preload:n,loop:i}}},{block:"core/image",widget:"media_image",transform:e=>{let{alt:t,attachment_id:n,caption:i,height:r,link_classes:a,link_rel:o,link_target_blank:l,link_type:s,link_url:c,size:d,url:u,width:m}=e;return{alt:t,caption:i,height:r,id:n,link:c,linkClass:a,linkDestination:s,linkTarget:l?"_blank":void 0,rel:o,sizeSlug:d,url:u,width:m}}},{block:"core/gallery",widget:"media_gallery",transform:e=>{let{ids:t,link_type:n,size:i,number:r}=e;return{ids:t,columns:r,linkTo:n,sizeSlug:i,images:t.map((e=>({id:e})))}}},{block:"core/rss",widget:"rss",transform:e=>{let{url:t,show_author:n,show_date:i,show_summary:r,items:a}=e;return{feedURL:t,displayAuthor:!!n,displayDate:!!i,displayExcerpt:!!r,itemsToShow:a}}}].map((e=>{let{block:t,widget:n,transform:i}=e;return{type:"block",blocks:[t],isMatch:e=>{let{idBase:t,instance:i}=e;return t===n&&!(null==i||!i.raw)},transform:e=>{var n;let{instance:a}=e;const o=(0,r.createBlock)(t,i?i(a.raw):void 0);return null!==(n=a.raw)&&void 0!==n&&n.title?[(0,r.createBlock)("core/heading",{content:a.raw.title}),o]:o}}}));var D={to:L};const A={apiVersion:2,name:"core/legacy-widget",title:"Legacy Widget",category:"widgets",description:"Display a legacy widget.",textdomain:"default",attributes:{id:{type:"string",default:null},idBase:{type:"string",default:null},instance:{type:"object",default:null}},supports:{html:!1,customClassName:!1,reusable:!1},editorStyle:"wp-block-legacy-widget-editor"},{name:W}=A,O={icon:l,edit:function(e){const{id:t,idBase:n}=e.attributes,{isWide:i=!1}=e,r=(0,d.useBlockProps)({className:c()({"is-wide-widget":i})});return(0,a.createElement)("div",r,t||n?(0,a.createElement)(N,e):(0,a.createElement)(x,e))},transforms:D};var j=(0,a.createElement)(o.SVG,{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},(0,a.createElement)(o.Path,{d:"M18 4h-7c-1.1 0-2 .9-2 2v3H6c-1.1 0-2 .9-2 2v7c0 1.1.9 2 2 2h7c1.1 0 2-.9 2-2v-3h3c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-4.5 14c0 .3-.2.5-.5.5H6c-.3 0-.5-.2-.5-.5v-7c0-.3.2-.5.5-.5h3V13c0 1.1.9 2 2 2h2.5v3zm0-4.5H11c-.3 0-.5-.2-.5-.5v-2.5H13c.3 0 .5.2.5.5v2.5zm5-.5c0 .3-.2.5-.5.5h-3V11c0-1.1-.9-2-2-2h-2.5V6c0-.3.2-.5.5-.5h7c.3 0 .5.2.5.5v7z"}));function z(e){let{clientId:t}=e;return(0,a.createElement)(a.Fragment,null,(0,a.createElement)(u.Placeholder,{className:"wp-block-widget-group__placeholder",icon:(0,a.createElement)(d.BlockIcon,{icon:j}),label:(0,h.__)("Widget Group")},(0,a.createElement)(d.ButtonBlockAppender,{rootClientId:t})),(0,a.createElement)(d.InnerBlocks,{renderAppender:!1}))}function G(e){var t;let{attributes:n,setAttributes:i}=e;return(0,a.createElement)(a.Fragment,null,(0,a.createElement)(d.RichText,{tagName:"h2",className:"widget-title",allowedFormats:[],placeholder:(0,h.__)("Title"),value:null!==(t=n.title)&&void 0!==t?t:"",onChange:e=>i({title:e})}),(0,a.createElement)(d.InnerBlocks,null))}var R=[{attributes:{title:{type:"string"}},supports:{html:!1,inserter:!0,customClassName:!0,reusable:!1},save(e){let{attributes:t}=e;return(0,a.createElement)(a.Fragment,null,(0,a.createElement)(d.RichText.Content,{tagName:"h2",className:"widget-title",value:t.title}),(0,a.createElement)(d.InnerBlocks.Content,null))}}];const Q={apiVersion:2,name:"core/widget-group",category:"widgets",attributes:{title:{type:"string"}},supports:{html:!1,inserter:!0,customClassName:!0,reusable:!1},editorStyle:"wp-block-widget-group-editor",style:"wp-block-widget-group"},{name:$}=Q,Z={title:(0,h.__)("Widget Group"),description:(0,h.__)("Create a classic widget layout with a title that’s styled by your theme for your widget areas."),icon:j,__experimentalLabel:e=>{let{name:t}=e;return t},edit:function(e){const{clientId:t}=e,{innerBlocks:n}=(0,w.useSelect)((e=>e(d.store).getBlock(t)),[t]);return(0,a.createElement)("div",(0,d.useBlockProps)({className:"widget"}),0===n.length?(0,a.createElement)(z,e):(0,a.createElement)(G,e))},save:function(e){let{attributes:t}=e;return(0,a.createElement)(a.Fragment,null,(0,a.createElement)(d.RichText.Content,{tagName:"h2",className:"widget-title",value:t.title}),(0,a.createElement)("div",{className:"wp-widget-group__inner-blocks"},(0,a.createElement)(d.InnerBlocks.Content,null)))},transforms:{from:[{type:"block",isMultiBlock:!0,blocks:["*"],isMatch(e,t){return!t.some((e=>"core/widget-group"===e.name))},__experimentalConvert(e){let t=[...e.map((e=>(0,r.createBlock)(e.name,e.attributes,e.innerBlocks)))];const n="core/heading"===t[0].name?t[0]:null;return t=t.filter((e=>e!==n)),(0,r.createBlock)("core/widget-group",{...n&&{title:n.attributes.content}},t)}}]},deprecated:R};var U=(0,a.createElement)(o.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,a.createElement)(o.Path,{d:"M19.75 9c0-1.257-.565-2.197-1.39-2.858-.797-.64-1.827-1.017-2.815-1.247-1.802-.42-3.703-.403-4.383-.396L11 4.5V6l.177-.001c.696-.006 2.416-.02 4.028.356.887.207 1.67.518 2.216.957.52.416.829.945.829 1.688 0 .592-.167.966-.407 1.23-.255.281-.656.508-1.236.674-1.19.34-2.82.346-4.607.346h-.077c-1.692 0-3.527 0-4.942.404-.732.209-1.424.545-1.935 1.108-.526.579-.796 1.33-.796 2.238 0 1.257.565 2.197 1.39 2.858.797.64 1.827 1.017 2.815 1.247 1.802.42 3.703.403 4.383.396L13 19.5h.714V22L18 18.5 13.714 15v3H13l-.177.001c-.696.006-2.416.02-4.028-.356-.887-.207-1.67-.518-2.216-.957-.52-.416-.829-.945-.829-1.688 0-.592.167-.966.407-1.23.255-.281.656-.508 1.237-.674 1.189-.34 2.819-.346 4.606-.346h.077c1.692 0 3.527 0 4.941-.404.732-.209 1.425-.545 1.936-1.108.526-.579.796-1.33.796-2.238z"}));function J(e){let{currentWidgetAreaId:t,widgetAreas:n,onSelect:i}=e;return(0,a.createElement)(u.ToolbarGroup,null,(0,a.createElement)(u.ToolbarItem,null,(e=>(0,a.createElement)(u.DropdownMenu,{icon:U,label:(0,h.__)("Move to widget area"),toggleProps:e},(e=>{let{onClose:r}=e;return(0,a.createElement)(u.MenuGroup,{label:(0,h.__)("Move to")},(0,a.createElement)(u.MenuItemsChoice,{choices:n.map((e=>({value:e.id,label:e.name,info:e.description}))),value:t,onSelect:e=>{i(e),r()}}))})))))}function X(e){return e.attributes.__internalWidgetId}function q(e,t){return{...e,attributes:{...e.attributes||{},__internalWidgetId:t}}}function K(e){const t=(0,w.subscribe)((()=>{var n,i;const a=null!==(n=null==e?void 0:e.widgetTypesToHideFromLegacyWidgetBlock)&&void 0!==n?n:[],o=null===(i=(0,w.select)(g.store).getWidgetTypes({per_page:-1}))||void 0===i?void 0:i.filter((e=>!a.includes(e.id)));o&&(t(),(0,w.dispatch)(r.store).addBlockVariations("core/legacy-widget",o.map((e=>({name:e.id,title:e.name,description:e.description,attributes:e.is_multi?{idBase:e.id,instance:{}}:{id:e.id}})))))}))}function Y(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{metadata:n,settings:i,name:a}=e;(0,r.registerBlockType)({name:a,...n},{...i,supports:{...i.supports,...t}})}function ee(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{metadata:n,settings:i,name:a}=t;(0,r.registerBlockType)({name:a,...n},{...i,supports:{...i.supports,...e}})}}(),(window.wp=window.wp||{}).widgets=i}(); edit-post.min.js 0000666 00000365455 15123355174 0007630 0 ustar 00 /*! This file is auto-generated */
!function(){var e={7153:function(e,t){var n;
/*!
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];n&&(e=a(e,l(n)))}return e}function l(e){if("string"==typeof e||"number"==typeof e)return e;if("object"!=typeof e)return"";if(Array.isArray(e))return o.apply(null,e);if(e.toString!==Object.prototype.toString&&!e.toString.toString().includes("[native code]"))return e.toString();var t="";for(var n in e)r.call(e,n)&&e[n]&&(t=a(t,n));return t}function a(e,t){return t?e?e+" "+t:e+t:e}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 l=t[r]={exports:{}};return e[r](l,l.exports,n),l.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,{PluginBlockSettingsMenuItem:function(){return Bo},PluginDocumentSettingPanel:function(){return jr},PluginMoreMenuItem:function(){return Mo},PluginPostPublishPanel:function(){return ao},PluginPostStatusInfo:function(){return _r},PluginPrePublishPanel:function(){return uo},PluginSidebar:function(){return Zr},PluginSidebarMoreMenuItem:function(){return No},__experimentalFullscreenModeClose:function(){return Cn},__experimentalMainDashboardButton:function(){return Un},initializeEditor:function(){return Io},reinitializeEditor:function(){return Do},store:function(){return Rt}});var e={};n.r(e),n.d(e,{disableComplementaryArea:function(){return $},enableComplementaryArea:function(){return W},pinItem:function(){return q},setDefaultComplementaryArea:function(){return z},setFeatureDefaults:function(){return Y},setFeatureValue:function(){return K},toggleFeature:function(){return Z},unpinItem:function(){return j}});var t={};n.r(t),n.d(t,{getActiveComplementaryArea:function(){return X},isFeatureActive:function(){return J},isItemPinned:function(){return Q}});var o={};n.r(o),n.d(o,{__experimentalSetPreviewDeviceType:function(){return Ye},__unstableCreateTemplate:function(){return tt},__unstableSwitchToTemplateMode:function(){return et},closeGeneralSidebar:function(){return Ne},closeModal:function(){return De},closePublishSidebar:function(){return Le},hideBlockTypes:function(){return $e},initializeMetaBoxes:function(){return rt},metaBoxUpdatesFailure:function(){return Ke},metaBoxUpdatesSuccess:function(){return Ze},openGeneralSidebar:function(){return Me},openModal:function(){return Ie},openPublishSidebar:function(){return Ae},removeEditorPanel:function(){return Re},requestMetaBoxUpdates:function(){return je},setAvailableMetaBoxesPerLocation:function(){return qe},setIsEditingTemplate:function(){return Je},setIsInserterOpened:function(){return Xe},setIsListViewOpened:function(){return Qe},showBlockTypes:function(){return We},switchEditorMode:function(){return Ge},toggleEditorPanelEnabled:function(){return Ve},toggleEditorPanelOpened:function(){return Fe},toggleFeature:function(){return He},togglePinnedPluginItem:function(){return Ue},togglePublishSidebar:function(){return Oe},updatePreferredStyleVariations:function(){return ze}});var l={};n.r(l),n.d(l,{__experimentalGetInsertionPoint:function(){return Dt},__experimentalGetPreviewDeviceType:function(){return Nt},areMetaBoxesInitialized:function(){return Ot},getActiveGeneralSidebarName:function(){return pt},getActiveMetaBoxLocations:function(){return kt},getAllMetaBoxes:function(){return xt},getEditedPostTemplate:function(){return Vt},getEditorMode:function(){return dt},getHiddenBlockTypes:function(){return _t},getMetaBoxesPerLocation:function(){return Tt},getPreference:function(){return ht},getPreferences:function(){return gt},hasMetaBoxes:function(){return Bt},isEditingTemplate:function(){return Lt},isEditorPanelEnabled:function(){return ft},isEditorPanelOpened:function(){return vt},isEditorPanelRemoved:function(){return bt},isEditorSidebarOpened:function(){return ut},isFeatureActive:function(){return wt},isInserterOpened:function(){return It},isListViewOpened:function(){return At},isMetaBoxLocationActive:function(){return Ct},isMetaBoxLocationVisible:function(){return Pt},isModalActive:function(){return yt},isPluginItemPinned:function(){return St},isPluginSidebarOpened:function(){return mt},isPublishSidebarOpened:function(){return Et},isSavingMetaBoxes:function(){return Mt}});var a=window.wp.element,i=window.wp.blocks,s=window.wp.blockLibrary,c=window.wp.deprecated,d=n.n(c),u=window.wp.data,m=window.wp.hooks,p=window.wp.preferences,g=window.wp.widgets,h=window.wp.mediaUtils;function _(){return _=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},_.apply(null,arguments)}(0,m.addFilter)("editor.MediaUpload","core/edit-post/replace-media-upload",(()=>h.MediaUpload));var E=window.wp.components,b=window.wp.blockEditor,f=window.wp.i18n,v=window.wp.compose;const y=(0,v.compose)((0,u.withSelect)(((e,t)=>{if((0,i.hasBlockSupport)(t.name,"multiple",!0))return{};const n=e(b.store).getBlocks().find((e=>{let{name:n}=e;return t.name===n}));return{originalBlockClientId:n&&n.clientId!==t.clientId&&n.clientId}})),(0,u.withDispatch)(((e,t)=>{let{originalBlockClientId:n}=t;return{selectFirst:()=>e(b.store).selectBlock(n)}}))),w=(0,v.createHigherOrderComponent)((e=>y((t=>{let{originalBlockClientId:n,selectFirst:r,...o}=t;if(!n)return(0,a.createElement)(e,o);const l=(0,i.getBlockType)(o.name),s=function(e){const t=(0,i.findTransform)((0,i.getBlockTransforms)("to",e),(e=>{let{type:t,blocks:n}=e;return"block"===t&&1===n.length}));if(!t)return null;return(0,i.getBlockType)(t.blocks[0])}(o.name);return[(0,a.createElement)("div",{key:"invalid-preview",style:{minHeight:"60px"}},(0,a.createElement)(e,_({key:"block-edit"},o))),(0,a.createElement)(b.Warning,{key:"multiple-use-warning",actions:[(0,a.createElement)(E.Button,{key:"find-original",variant:"secondary",onClick:r},(0,f.__)("Find original")),(0,a.createElement)(E.Button,{key:"remove",variant:"secondary",onClick:()=>o.onReplace([])},(0,f.__)("Remove")),s&&(0,a.createElement)(E.Button,{key:"transform",variant:"secondary",onClick:()=>o.onReplace((0,i.createBlock)(s.name,o.attributes))},(0,f.__)("Transform into:")," ",s.title)]},(0,a.createElement)("strong",null,null==l?void 0:l.title,": "),(0,f.__)("This block can only be used once."))]}))),"withMultipleValidation");(0,m.addFilter)("editor.BlockEdit","core/edit-post/validate-multiple-use/with-multiple-validation",w);var S=window.wp.primitives;var k=(0,a.createElement)(S.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,a.createElement)(S.Path,{d:"M18.2 17c0 .7-.6 1.2-1.2 1.2H7c-.7 0-1.2-.6-1.2-1.2V7c0-.7.6-1.2 1.2-1.2h3.2V4.2H7C5.5 4.2 4.2 5.5 4.2 7v10c0 1.5 1.2 2.8 2.8 2.8h10c1.5 0 2.8-1.2 2.8-2.8v-3.6h-1.5V17zM14.9 3v1.5h3.7l-6.4 6.4 1.1 1.1 6.4-6.4v3.7h1.5V3h-6.3z"})),P=window.wp.plugins,C=window.wp.url,T=window.wp.notices,x=window.wp.editor;function B(){const{createNotice:e}=(0,u.useDispatch)(T.store),t=(0,u.useSelect)((e=>()=>e(x.store).getEditedPostAttribute("content")),[]);const n=(0,v.useCopyToClipboard)(t,(function(){e("info",(0,f.__)("All content copied."),{isDismissible:!0,type:"snackbar"})}));return(0,a.createElement)(E.MenuItem,{ref:n},(0,f.__)("Copy all blocks"))}var M=window.wp.keycodes;function N(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1?arguments[1]:void 0;const n=[...e];for(const e of t){const t=n.findIndex((t=>t.id===e.id));-1!==t?n[t]=e:n.push(e)}return n}const I=(0,u.combineReducers)({isSaving:function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0;switch(t.type){case"REQUEST_META_BOX_UPDATES":return!0;case"META_BOX_UPDATES_SUCCESS":case"META_BOX_UPDATES_FAILURE":return!1;default:return e}},locations:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;if("SET_META_BOXES_PER_LOCATIONS"===t.type){const n={...e};for(const[e,r]of Object.entries(t.metaBoxesPerLocation))n[e]=N(n[e],r);return n}return e},initialized:function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0;return"META_BOXES_INITIALIZED"===t.type||e}});var D=(0,u.combineReducers)({activeModal:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1?arguments[1]:void 0;switch(t.type){case"OPEN_MODAL":return t.name;case"CLOSE_MODAL":return null}return e},metaBoxes:I,publishSidebarActive:function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0;switch(t.type){case"OPEN_PUBLISH_SIDEBAR":return!0;case"CLOSE_PUBLISH_SIDEBAR":return!1;case"TOGGLE_PUBLISH_SIDEBAR":return!e}return e},removedPanels:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1?arguments[1]:void 0;if("REMOVE_PANEL"===t.type)if(!e.includes(t.panelName))return[...e,t.panelName];return e},deviceType:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Desktop",t=arguments.length>1?arguments[1]:void 0;return"SET_PREVIEW_DEVICE_TYPE"===t.type?t.deviceType:e},blockInserterPanel:function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0;switch(t.type){case"SET_IS_LIST_VIEW_OPENED":return!t.isOpen&&e;case"SET_IS_INSERTER_OPENED":return t.value}return e},listViewPanel:function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0;switch(t.type){case"SET_IS_INSERTER_OPENED":return!t.value&&e;case"SET_IS_LIST_VIEW_OPENED":return t.isOpen}return e},isEditingTemplate:function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0;return"SET_IS_EDITING_TEMPLATE"===t.type?t.value:e}}),A=window.wp.apiFetch,L=n.n(A),O=n(7153),V=n.n(O);var F=(0,a.createElement)(S.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,a.createElement)(S.Path,{d:"M16.7 7.1l-6.3 8.5-3.3-2.5-.9 1.2 4.5 3.4L17.9 8z"}));var R=(0,a.createElement)(S.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,a.createElement)(S.Path,{d:"M11.776 4.454a.25.25 0 01.448 0l2.069 4.192a.25.25 0 00.188.137l4.626.672a.25.25 0 01.139.426l-3.348 3.263a.25.25 0 00-.072.222l.79 4.607a.25.25 0 01-.362.263l-4.138-2.175a.25.25 0 00-.232 0l-4.138 2.175a.25.25 0 01-.363-.263l.79-4.607a.25.25 0 00-.071-.222L4.754 9.881a.25.25 0 01.139-.426l4.626-.672a.25.25 0 00.188-.137l2.069-4.192z"}));var H=(0,a.createElement)(S.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,a.createElement)(S.Path,{fillRule:"evenodd",d:"M9.706 8.646a.25.25 0 01-.188.137l-4.626.672a.25.25 0 00-.139.427l3.348 3.262a.25.25 0 01.072.222l-.79 4.607a.25.25 0 00.362.264l4.138-2.176a.25.25 0 01.233 0l4.137 2.175a.25.25 0 00.363-.263l-.79-4.607a.25.25 0 01.072-.222l3.347-3.262a.25.25 0 00-.139-.427l-4.626-.672a.25.25 0 01-.188-.137l-2.069-4.192a.25.25 0 00-.448 0L9.706 8.646zM12 7.39l-.948 1.921a1.75 1.75 0 01-1.317.957l-2.12.308 1.534 1.495c.412.402.6.982.503 1.55l-.362 2.11 1.896-.997a1.75 1.75 0 011.629 0l1.895.997-.362-2.11a1.75 1.75 0 01.504-1.55l1.533-1.495-2.12-.308a1.75 1.75 0 01-1.317-.957L12 7.39z",clipRule:"evenodd"})),G=window.wp.viewport;var U=(0,a.createElement)(S.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,a.createElement)(S.Path,{d:"M12 13.06l3.712 3.713 1.061-1.06L13.061 12l3.712-3.712-1.06-1.06L12 10.938 8.288 7.227l-1.061 1.06L10.939 12l-3.712 3.712 1.06 1.061L12 13.061z"}));const z=(e,t)=>({type:"SET_DEFAULT_COMPLEMENTARY_AREA",scope:e,area:t}),W=(e,t)=>n=>{let{registry:r,dispatch:o}=n;if(!t)return;r.select(p.store).get(e,"isComplementaryAreaVisible")||r.dispatch(p.store).set(e,"isComplementaryAreaVisible",!0),o({type:"ENABLE_COMPLEMENTARY_AREA",scope:e,area:t})},$=e=>t=>{let{registry:n}=t;n.select(p.store).get(e,"isComplementaryAreaVisible")&&n.dispatch(p.store).set(e,"isComplementaryAreaVisible",!1)},q=(e,t)=>n=>{let{registry:r}=n;if(!t)return;const o=r.select(p.store).get(e,"pinnedItems");!0!==(null==o?void 0:o[t])&&r.dispatch(p.store).set(e,"pinnedItems",{...o,[t]:!0})},j=(e,t)=>n=>{let{registry:r}=n;if(!t)return;const o=r.select(p.store).get(e,"pinnedItems");r.dispatch(p.store).set(e,"pinnedItems",{...o,[t]:!1})};function Z(e,t){return function(n){let{registry:r}=n;d()("dispatch( 'core/interface' ).toggleFeature",{since:"6.0",alternative:"dispatch( 'core/preferences' ).toggle"}),r.dispatch(p.store).toggle(e,t)}}function K(e,t,n){return function(r){let{registry:o}=r;d()("dispatch( 'core/interface' ).setFeatureValue",{since:"6.0",alternative:"dispatch( 'core/preferences' ).set"}),o.dispatch(p.store).set(e,t,!!n)}}function Y(e,t){return function(n){let{registry:r}=n;d()("dispatch( 'core/interface' ).setFeatureDefaults",{since:"6.0",alternative:"dispatch( 'core/preferences' ).setDefaults"}),r.dispatch(p.store).setDefaults(e,t)}}const X=(0,u.createRegistrySelector)((e=>(t,n)=>{var r;const o=e(p.store).get(n,"isComplementaryAreaVisible");if(void 0!==o)return o?null==t||null===(r=t.complementaryAreas)||void 0===r?void 0:r[n]:null})),Q=(0,u.createRegistrySelector)((e=>(t,n,r)=>{var o;const l=e(p.store).get(n,"pinnedItems");return null===(o=null==l?void 0:l[r])||void 0===o||o})),J=(0,u.createRegistrySelector)((e=>(t,n,r)=>(d()("select( 'core/interface' ).isFeatureActive( scope, featureName )",{since:"6.0",alternative:"select( 'core/preferences' ).get( scope, featureName )"}),!!e(p.store).get(n,r))));var ee=(0,u.combineReducers)({complementaryAreas:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;switch(t.type){case"SET_DEFAULT_COMPLEMENTARY_AREA":{const{scope:n,area:r}=t;return e[n]?e:{...e,[n]:r}}case"ENABLE_COMPLEMENTARY_AREA":{const{scope:n,area:r}=t;return{...e,[n]:r}}}return e}});const te=(0,u.createReduxStore)("core/interface",{reducer:ee,actions:e,selectors:t});(0,u.register)(te);var ne=(0,P.withPluginContext)(((e,t)=>({icon:t.icon||e.icon,identifier:t.identifier||`${e.name}/${t.name}`})));var re=ne((function(e){let{as:t=E.Button,scope:n,identifier:r,icon:o,selectedIcon:l,name:i,...s}=e;const c=t,d=(0,u.useSelect)((e=>e(te).getActiveComplementaryArea(n)===r),[r]),{enableComplementaryArea:m,disableComplementaryArea:p}=(0,u.useDispatch)(te);return(0,a.createElement)(c,_({icon:l&&d?l:o,onClick:()=>{d?p(n):m(n,r)}},s))}));var oe=e=>{let{smallScreenTitle:t,children:n,className:r,toggleButtonProps:o}=e;const l=(0,a.createElement)(re,_({icon:U},o));return(0,a.createElement)(a.Fragment,null,(0,a.createElement)("div",{className:"components-panel__header interface-complementary-area-header__small"},t&&(0,a.createElement)("span",{className:"interface-complementary-area-header__small-title"},t),l),(0,a.createElement)("div",{className:V()("components-panel__header","interface-complementary-area-header",r),tabIndex:-1},n,l))};const le=()=>{};function ae(e){let{name:t,as:n=E.Button,onClick:r,...o}=e;return(0,a.createElement)(E.Fill,{name:t},(e=>{let{onClick:t}=e;return(0,a.createElement)(n,_({onClick:r||t?function(){(r||le)(...arguments),(t||le)(...arguments)}:void 0},o))}))}ae.Slot=function(e){let{name:t,as:n=E.ButtonGroup,fillProps:r={},bubblesVirtually:o,...l}=e;return(0,a.createElement)(E.Slot,{name:t,bubblesVirtually:o,fillProps:r},(e=>{if(!a.Children.toArray(e).length)return null;const t=[];a.Children.forEach(e,(e=>{let{props:{__unstableExplicitMenuItem:n,__unstableTarget:r}}=e;r&&n&&t.push(r)}));const r=a.Children.map(e,(e=>!e.props.__unstableExplicitMenuItem&&t.includes(e.props.__unstableTarget)?null:e));return(0,a.createElement)(n,l,r)}))};var ie=ae;const se=e=>{let{__unstableExplicitMenuItem:t,__unstableTarget:n,...r}=e;return(0,a.createElement)(E.MenuItem,r)};function ce(e){let{scope:t,target:n,__unstableExplicitMenuItem:r,...o}=e;return(0,a.createElement)(re,_({as:e=>(0,a.createElement)(ie,_({__unstableExplicitMenuItem:r,__unstableTarget:`${t}/${n}`,as:se,name:`${t}/plugin-more-menu`},e)),role:"menuitemcheckbox",selectedIcon:F,name:n,scope:t},o))}function de(e){let{scope:t,...n}=e;return(0,a.createElement)(E.Fill,_({name:`PinnedItems/${t}`},n))}de.Slot=function(e){let{scope:t,className:n,...r}=e;return(0,a.createElement)(E.Slot,_({name:`PinnedItems/${t}`},r),(e=>(null==e?void 0:e.length)>0&&(0,a.createElement)("div",{className:V()(n,"interface-pinned-items")},e)))};var ue=de;function me(e){let{scope:t,children:n,className:r}=e;return(0,a.createElement)(E.Fill,{name:`ComplementaryArea/${t}`},(0,a.createElement)("div",{className:r},n))}const pe=ne((function(e){let{children:t,className:n,closeLabel:r=(0,f.__)("Close plugin"),identifier:o,header:l,headerClassName:i,icon:s,isPinnable:c=!0,panelClassName:d,scope:m,name:p,smallScreenTitle:g,title:h,toggleShortcut:_,isActiveByDefault:b,showIconLabels:v=!1}=e;const{isActive:y,isPinned:w,activeArea:S,isSmall:k,isLarge:P}=(0,u.useSelect)((e=>{const{getActiveComplementaryArea:t,isItemPinned:n}=e(te),r=t(m);return{isActive:r===o,isPinned:n(m,o),activeArea:r,isSmall:e(G.store).isViewportMatch("< medium"),isLarge:e(G.store).isViewportMatch("large")}}),[o,m]);!function(e,t,n,r,o){const l=(0,a.useRef)(!1),i=(0,a.useRef)(!1),{enableComplementaryArea:s,disableComplementaryArea:c}=(0,u.useDispatch)(te);(0,a.useEffect)((()=>{r&&o&&!l.current?(c(e),i.current=!0):i.current&&!o&&l.current?(i.current=!1,s(e,t)):i.current&&n&&n!==t&&(i.current=!1),o!==l.current&&(l.current=o)}),[r,o,e,t,n])}(m,o,S,y,k);const{enableComplementaryArea:C,disableComplementaryArea:T,pinItem:x,unpinItem:B}=(0,u.useDispatch)(te);return(0,a.useEffect)((()=>{b&&void 0===S&&!k&&C(m,o)}),[S,b,m,o,k]),(0,a.createElement)(a.Fragment,null,c&&(0,a.createElement)(ue,{scope:m},w&&(0,a.createElement)(re,{scope:m,identifier:o,isPressed:y&&(!v||P),"aria-expanded":y,label:h,icon:v?F:s,showTooltip:!v,variant:v?"tertiary":void 0})),p&&c&&(0,a.createElement)(ce,{target:p,scope:m,icon:s},h),y&&(0,a.createElement)(me,{className:V()("interface-complementary-area",n),scope:m},(0,a.createElement)(oe,{className:i,closeLabel:r,onClose:()=>T(m),smallScreenTitle:g,toggleButtonProps:{label:r,shortcut:_,scope:m,identifier:o}},l||(0,a.createElement)(a.Fragment,null,(0,a.createElement)("strong",null,h),c&&(0,a.createElement)(E.Button,{className:"interface-complementary-area__pin-unpin-item",icon:w?R:H,label:w?(0,f.__)("Unpin from toolbar"):(0,f.__)("Pin to toolbar"),onClick:()=>(w?B:x)(m,o),isPressed:w,"aria-expanded":w}))),(0,a.createElement)(E.Panel,{className:d},t)))}));pe.Slot=function(e){let{scope:t,...n}=e;return(0,a.createElement)(E.Slot,_({name:`ComplementaryArea/${t}`},n))};var ge=pe;var he=e=>{let{isActive:t}=e;return(0,a.useEffect)((()=>{let e=!1;return document.body.classList.contains("sticky-menu")&&(e=!0,document.body.classList.remove("sticky-menu")),()=>{e&&document.body.classList.add("sticky-menu")}}),[]),(0,a.useEffect)((()=>(t?document.body.classList.add("is-fullscreen-mode"):document.body.classList.remove("is-fullscreen-mode"),()=>{t&&document.body.classList.remove("is-fullscreen-mode")})),[t]),null};function _e(e){let{children:t,className:n,ariaLabel:r,as:o="div",...l}=e;return(0,a.createElement)(o,_({className:V()("interface-navigable-region",n),"aria-label":r,role:"region",tabIndex:"-1"},l),t)}var Ee=(0,a.forwardRef)((function(e,t){let{isDistractionFree:n,footer:r,header:o,editorNotices:l,sidebar:i,secondarySidebar:s,notices:c,content:d,actions:u,labels:m,className:p,enableRegionNavigation:g=!0,shortcuts:h}=e;const b=(0,E.__unstableUseNavigateRegions)(h);!function(e){(0,a.useEffect)((()=>{const t=document&&document.querySelector(`html:not(.${e})`);if(t)return t.classList.toggle(e),()=>{t.classList.toggle(e)}}),[e])}("interface-interface-skeleton__html-container");const y={...{header:(0,f.__)("Header"),body:(0,f.__)("Content"),secondarySidebar:(0,f.__)("Block Library"),sidebar:(0,f.__)("Settings"),actions:(0,f.__)("Publish"),footer:(0,f.__)("Footer")},...m},w={hidden:n?{opacity:0}:{opacity:1},hover:{opacity:1,transition:{type:"tween",delay:.2,delayChildren:.2}}};return(0,a.createElement)("div",_({},g?b:{},{ref:(0,v.useMergeRefs)([t,g?b.ref:void 0]),className:V()(p,"interface-interface-skeleton",b.className,!!r&&"has-footer")}),(0,a.createElement)("div",{className:"interface-interface-skeleton__editor"},!!o&&n&&(0,a.createElement)(_e,{as:E.__unstableMotion.div,className:"interface-interface-skeleton__header","aria-label":y.header,initial:n?"hidden":"hover",whileHover:"hover",variants:w,transition:{type:"tween",delay:.8}},o),!!o&&!n&&(0,a.createElement)(_e,{className:"interface-interface-skeleton__header",ariaLabel:y.header},o),n&&(0,a.createElement)("div",{className:"interface-interface-skeleton__header"},l),(0,a.createElement)("div",{className:"interface-interface-skeleton__body"},!!s&&(0,a.createElement)(_e,{className:"interface-interface-skeleton__secondary-sidebar",ariaLabel:y.secondarySidebar},s),!!c&&(0,a.createElement)("div",{className:"interface-interface-skeleton__notices"},c),(0,a.createElement)(_e,{className:"interface-interface-skeleton__content",ariaLabel:y.body},d),!!i&&(0,a.createElement)(_e,{className:"interface-interface-skeleton__sidebar",ariaLabel:y.sidebar},i),!!u&&(0,a.createElement)(_e,{className:"interface-interface-skeleton__actions",ariaLabel:y.actions},u))),!!r&&(0,a.createElement)(_e,{className:"interface-interface-skeleton__footer",ariaLabel:y.footer},r))}));var be=(0,a.createElement)(S.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,a.createElement)(S.Path,{d:"M13 19h-2v-2h2v2zm0-6h-2v-2h2v2zm0-6h-2V5h2v2z"}));function fe(e){let{as:t=E.DropdownMenu,className:n,label:r=(0,f.__)("Options"),popoverProps:o,toggleProps:l,children:i}=e;return(0,a.createElement)(t,{className:V()("interface-more-menu-dropdown",n),icon:be,label:r,popoverProps:{placement:"bottom-end",...o,className:V()("interface-more-menu-dropdown__content",null==o?void 0:o.className)},toggleProps:{tooltipPosition:"bottom",...l}},(e=>i(e)))}function ve(e){let{closeModal:t,children:n}=e;return(0,a.createElement)(E.Modal,{className:"interface-preferences-modal",title:(0,f.__)("Preferences"),onRequestClose:t},n)}var ye=function(e){let{icon:t,size:n=24,...r}=e;return(0,a.cloneElement)(t,{width:n,height:n,...r})};var we=(0,a.createElement)(S.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,a.createElement)(S.Path,{d:"M14.6 7l-1.2-1L8 12l5.4 6 1.2-1-4.6-5z"}));var Se=(0,a.createElement)(S.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,a.createElement)(S.Path,{d:"M10.6 6L9.4 7l4.6 5-4.6 5 1.2 1 5.4-6z"}));const ke="preferences-menu";function Pe(e){let{sections:t}=e;const n=(0,v.useViewportMatch)("medium"),[r,o]=(0,a.useState)(ke),{tabs:l,sectionsContentMap:i}=(0,a.useMemo)((()=>{let e={tabs:[],sectionsContentMap:{}};return t.length&&(e=t.reduce(((e,t)=>{let{name:n,tabLabel:r,content:o}=t;return e.tabs.push({name:n,title:r}),e.sectionsContentMap[n]=o,e}),{tabs:[],sectionsContentMap:{}})),e}),[t]),s=(0,a.useCallback)((e=>i[e.name]||null),[i]);let c;return c=n?(0,a.createElement)(E.TabPanel,{className:"interface-preferences__tabs",tabs:l,initialTabName:r!==ke?r:void 0,onSelect:o,orientation:"vertical"},s):(0,a.createElement)(E.__experimentalNavigatorProvider,{initialPath:"/",className:"interface-preferences__provider"},(0,a.createElement)(E.__experimentalNavigatorScreen,{path:"/"},(0,a.createElement)(E.Card,{isBorderless:!0,size:"small"},(0,a.createElement)(E.CardBody,null,(0,a.createElement)(E.__experimentalItemGroup,null,l.map((e=>(0,a.createElement)(E.__experimentalNavigatorButton,{key:e.name,path:e.name,as:E.__experimentalItem,isAction:!0},(0,a.createElement)(E.__experimentalHStack,{justify:"space-between"},(0,a.createElement)(E.FlexItem,null,(0,a.createElement)(E.__experimentalTruncate,null,e.title)),(0,a.createElement)(E.FlexItem,null,(0,a.createElement)(ye,{icon:(0,f.isRTL)()?we:Se})))))))))),t.length&&t.map((e=>(0,a.createElement)(E.__experimentalNavigatorScreen,{key:`${e.name}-menu`,path:e.name},(0,a.createElement)(E.Card,{isBorderless:!0,size:"large"},(0,a.createElement)(E.CardHeader,{isBorderless:!1,justify:"left",size:"small",gap:"6"},(0,a.createElement)(E.__experimentalNavigatorBackButton,{icon:(0,f.isRTL)()?Se:we,"aria-label":(0,f.__)("Navigate to the previous view")}),(0,a.createElement)(E.__experimentalText,{size:"16"},e.tabLabel)),(0,a.createElement)(E.CardBody,null,e.content)))))),c}var Ce=e=>{let{description:t,title:n,children:r}=e;return(0,a.createElement)("fieldset",{className:"interface-preferences-modal__section"},(0,a.createElement)("legend",{className:"interface-preferences-modal__section-legend"},(0,a.createElement)("h2",{className:"interface-preferences-modal__section-title"},n),t&&(0,a.createElement)("p",{className:"interface-preferences-modal__section-description"},t)),r)};var Te=function(e){let{help:t,label:n,isChecked:r,onChange:o,children:l}=e;return(0,a.createElement)("div",{className:"interface-preferences-modal__option"},(0,a.createElement)(E.ToggleControl,{__nextHasNoMarginBottom:!0,help:t,label:n,checked:r,onChange:o}),l)},xe=window.wp.a11y,Be=window.wp.coreData;const Me=e=>t=>{let{registry:n}=t;return n.dispatch(te).enableComplementaryArea(Rt.name,e)},Ne=()=>e=>{let{registry:t}=e;return t.dispatch(te).disableComplementaryArea(Rt.name)};function Ie(e){return{type:"OPEN_MODAL",name:e}}function De(){return{type:"CLOSE_MODAL"}}function Ae(){return{type:"OPEN_PUBLISH_SIDEBAR"}}function Le(){return{type:"CLOSE_PUBLISH_SIDEBAR"}}function Oe(){return{type:"TOGGLE_PUBLISH_SIDEBAR"}}const Ve=e=>t=>{var n;let{registry:r}=t;const o=null!==(n=r.select(p.store).get("core/edit-post","inactivePanels"))&&void 0!==n?n:[];let l;l=!(null==o||!o.includes(e))?o.filter((t=>t!==e)):[...o,e],r.dispatch(p.store).set("core/edit-post","inactivePanels",l)},Fe=e=>t=>{var n;let{registry:r}=t;const o=null!==(n=r.select(p.store).get("core/edit-post","openPanels"))&&void 0!==n?n:[];let l;l=!(null==o||!o.includes(e))?o.filter((t=>t!==e)):[...o,e],r.dispatch(p.store).set("core/edit-post","openPanels",l)};function Re(e){return{type:"REMOVE_PANEL",panelName:e}}const He=e=>t=>{let{registry:n}=t;return n.dispatch(p.store).toggle("core/edit-post",e)},Ge=e=>t=>{let{registry:n}=t;n.dispatch(p.store).set("core/edit-post","editorMode",e),"visual"!==e&&n.dispatch(b.store).clearSelectedBlock();const r="visual"===e?(0,f.__)("Visual editor selected"):(0,f.__)("Code editor selected");(0,xe.speak)(r,"assertive")},Ue=e=>t=>{let{registry:n}=t;const r=n.select(te).isItemPinned("core/edit-post",e);n.dispatch(te)[r?"unpinItem":"pinItem"]("core/edit-post",e)},ze=(e,t)=>n=>{var r;let{registry:o}=n;if(!e)return;const l=null!==(r=o.select(p.store).get("core/edit-post","preferredStyleVariations"))&&void 0!==r?r:{};if(t)o.dispatch(p.store).set("core/edit-post","preferredStyleVariations",{...l,[e]:t});else{const t={...l};delete t[e],o.dispatch(p.store).set("core/edit-post","preferredStyleVariations",t)}},We=e=>t=>{var n;let{registry:r}=t;const o=(null!==(n=r.select(p.store).get("core/edit-post","hiddenBlockTypes"))&&void 0!==n?n:[]).filter((t=>!(Array.isArray(e)?e:[e]).includes(t)));r.dispatch(p.store).set("core/edit-post","hiddenBlockTypes",o)},$e=e=>t=>{var n;let{registry:r}=t;const o=null!==(n=r.select(p.store).get("core/edit-post","hiddenBlockTypes"))&&void 0!==n?n:[],l=new Set([...o,...Array.isArray(e)?e:[e]]);r.dispatch(p.store).set("core/edit-post","hiddenBlockTypes",[...l])};function qe(e){return{type:"SET_META_BOXES_PER_LOCATIONS",metaBoxesPerLocation:e}}const je=()=>async e=>{let{registry:t,select:n,dispatch:r}=e;r({type:"REQUEST_META_BOX_UPDATES"}),window.tinyMCE&&window.tinyMCE.triggerSave();const o=t.select(x.store).getCurrentPost(),l=[!!o.comment_status&&["comment_status",o.comment_status],!!o.ping_status&&["ping_status",o.ping_status],!!o.sticky&&["sticky",o.sticky],!!o.author&&["post_author",o.author]].filter(Boolean),a=[new window.FormData(document.querySelector(".metabox-base-form")),...n.getActiveMetaBoxLocations().map((e=>new window.FormData((e=>document.querySelector(`.edit-post-meta-boxes-area.is-${e} .metabox-location-${e}`)||document.querySelector("#metaboxes .metabox-location-"+e))(e))))].reduce(((e,t)=>{for(const[n,r]of t)e.append(n,r);return e}),new window.FormData);l.forEach((e=>{let[t,n]=e;return a.append(t,n)}));try{await L()({url:window._wpMetaBoxUrl,method:"POST",body:a,parse:!1}),r.metaBoxUpdatesSuccess()}catch{r.metaBoxUpdatesFailure()}};function Ze(){return{type:"META_BOX_UPDATES_SUCCESS"}}function Ke(){return{type:"META_BOX_UPDATES_FAILURE"}}function Ye(e){return{type:"SET_PREVIEW_DEVICE_TYPE",deviceType:e}}function Xe(e){return{type:"SET_IS_INSERTER_OPENED",value:e}}function Qe(e){return{type:"SET_IS_LIST_VIEW_OPENED",isOpen:e}}function Je(e){return{type:"SET_IS_EDITING_TEMPLATE",value:e}}const et=function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return t=>{let{registry:n,select:r,dispatch:o}=t;o(Je(!0));if(!r.isFeatureActive("welcomeGuideTemplate")){const t=e?(0,f.__)("Custom template created. You're in template mode now."):(0,f.__)("Editing template. Changes made here affect all posts and pages that use the template.");n.dispatch(T.store).createSuccessNotice(t,{type:"snackbar"})}}},tt=e=>async t=>{let{registry:n}=t;const r=await n.dispatch(Be.store).saveEntityRecord("postType","wp_template",e),o=n.select(x.store).getCurrentPost();n.dispatch(Be.store).editEntityRecord("postType",o.type,o.id,{template:r.slug})};let nt=!1;const rt=()=>e=>{let{registry:t,select:n,dispatch:r}=e;if(!t.select(x.store).__unstableIsEditorReady())return;if(nt)return;const o=t.select(x.store).getCurrentPostType();window.postboxes.page!==o&&window.postboxes.add_postbox_toggles(o),nt=!0;let l=t.select(x.store).isSavingPost(),a=t.select(x.store).isAutosavingPost();t.subscribe((async()=>{const e=t.select(x.store).isSavingPost(),o=t.select(x.store).isAutosavingPost(),i=l&&!a&&!e&&n.hasMetaBoxes();l=e,a=o,i&&await r.requestMetaBoxUpdates()})),r({type:"META_BOXES_INITIALIZED"})};var ot={};function lt(e){return[e]}function at(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 it(e,t){var n,r=t||lt;function o(e){var t,r,o,l,a,i=n,s=!0;for(t=0;t<e.length;t++){if(r=e[t],!(a=r)||"object"!=typeof a){s=!1;break}i.has(r)?i=i.get(r):(o=new WeakMap,i.set(r,o),i=o)}return i.has(ot)||((l=function(){var e={clear:function(){e.head=null}};return e}()).isUniqueByDependants=s,i.set(ot,l)),i.get(ot)}function l(){n=new WeakMap}function a(){var t,n,l,a,i,s=arguments.length;for(a=new Array(s),l=0;l<s;l++)a[l]=arguments[l];for((t=o(i=r.apply(null,a))).isUniqueByDependants||(t.lastDependants&&!at(i,t.lastDependants,0)&&t.clear(),t.lastDependants=i),n=t.head;n;){if(at(n.args,a,1))return n!==t.head&&(n.prev.next=n.next,n.next&&(n.next.prev=n.prev),n.next=t.head,n.prev=null,t.head.prev=n,t.head=n),n.val;n=n.next}return n={val:e.apply(null,a)},a[0]=null,n.args=a,t.head&&(t.head.prev=n,n.next=t.head),t.head=n,n.val}return a.getDependants=r,a.clear=l,l(),a}const st=[],ct={},dt=(0,u.createRegistrySelector)((e=>()=>{var t;return null!==(t=e(p.store).get("core/edit-post","editorMode"))&&void 0!==t?t:"visual"})),ut=(0,u.createRegistrySelector)((e=>()=>{const t=e(te).getActiveComplementaryArea("core/edit-post");return["edit-post/document","edit-post/block"].includes(t)})),mt=(0,u.createRegistrySelector)((e=>()=>{const t=e(te).getActiveComplementaryArea("core/edit-post");return!!t&&!["edit-post/document","edit-post/block"].includes(t)})),pt=(0,u.createRegistrySelector)((e=>()=>e(te).getActiveComplementaryArea("core/edit-post")));const gt=(0,u.createRegistrySelector)((e=>()=>{d()("select( 'core/edit-post' ).getPreferences",{since:"6.0",alternative:"select( 'core/preferences' ).get"});const t=["hiddenBlockTypes","editorMode","preferredStyleVariations"].reduce(((t,n)=>({...t,[n]:e(p.store).get("core/edit-post",n)})),{}),n=function(e,t){var n;const r=null==e?void 0:e.reduce(((e,t)=>({...e,[t]:{enabled:!1}})),{}),o=null==t?void 0:t.reduce(((e,t)=>{const n=null==e?void 0:e[t];return{...e,[t]:{...n,opened:!0}}}),null!=r?r:{});return null!==(n=null!=o?o:r)&&void 0!==n?n:ct}(e(p.store).get("core/edit-post","inactivePanels"),e(p.store).get("core/edit-post","openPanels"));return{...t,panels:n}}));function ht(e,t,n){d()("select( 'core/edit-post' ).getPreference",{since:"6.0",alternative:"select( 'core/preferences' ).get"});const r=gt(e)[t];return void 0===r?n:r}const _t=(0,u.createRegistrySelector)((e=>()=>{var t;return null!==(t=e(p.store).get("core/edit-post","hiddenBlockTypes"))&&void 0!==t?t:st}));function Et(e){return e.publishSidebarActive}function bt(e,t){return e.removedPanels.includes(t)}const ft=(0,u.createRegistrySelector)((e=>(t,n)=>{const r=e(p.store).get("core/edit-post","inactivePanels");return!(bt(t,n)||null!=r&&r.includes(n))})),vt=(0,u.createRegistrySelector)((e=>(t,n)=>{const r=e(p.store).get("core/edit-post","openPanels");return!(null==r||!r.includes(n))}));function yt(e,t){return e.activeModal===t}const wt=(0,u.createRegistrySelector)((e=>(t,n)=>!!e(p.store).get("core/edit-post",n))),St=(0,u.createRegistrySelector)((e=>(t,n)=>e(te).isItemPinned("core/edit-post",n))),kt=it((e=>Object.keys(e.metaBoxes.locations).filter((t=>Ct(e,t)))),(e=>[e.metaBoxes.locations]));function Pt(e,t){var n;return Ct(e,t)&&(null===(n=Tt(e,t))||void 0===n?void 0:n.some((t=>{let{id:n}=t;return ft(e,`meta-box-${n}`)})))}function Ct(e,t){const n=Tt(e,t);return!!n&&0!==n.length}function Tt(e,t){return e.metaBoxes.locations[t]}const xt=it((e=>Object.values(e.metaBoxes.locations).flat()),(e=>[e.metaBoxes.locations]));function Bt(e){return kt(e).length>0}function Mt(e){return e.metaBoxes.isSaving}function Nt(e){return e.deviceType}function It(e){return!!e.blockInserterPanel}function Dt(e){const{rootClientId:t,insertionIndex:n,filterValue:r}=e.blockInserterPanel;return{rootClientId:t,insertionIndex:n,filterValue:r}}function At(e){return e.listViewPanel}function Lt(e){return e.isEditingTemplate}function Ot(e){return e.metaBoxes.initialized}const Vt=(0,u.createRegistrySelector)((e=>()=>{const t=e(x.store).getEditedPostAttribute("template");if(t){var n;const r=null===(n=e(Be.store).getEntityRecords("postType","wp_template",{per_page:-1}))||void 0===n?void 0:n.find((e=>e.slug===t));return r?e(Be.store).getEditedEntityRecord("postType","wp_template",r.id):r}const r=e(x.store).getCurrentPost();return r.link?e(Be.store).__experimentalGetTemplateForLink(r.link):null})),Ft="core/edit-post",Rt=(0,u.createReduxStore)(Ft,{reducer:D,actions:o,selectors:l});(0,u.register)(Rt);var Ht=(0,u.withDispatch)((e=>{const{openModal:t}=e(Rt);return{openModal:t}}))((function(e){let{openModal:t}=e;return(0,a.createElement)(E.MenuItem,{onClick:()=>{t("edit-post/keyboard-shortcut-help")},shortcut:M.displayShortcut.access("h")},(0,f.__)("Keyboard shortcuts"))})),Gt=window.lodash;const{Fill:Ut,Slot:zt}=(0,E.createSlotFill)("ToolsMoreMenuGroup");Ut.Slot=e=>{let{fillProps:t}=e;return(0,a.createElement)(zt,{fillProps:t},(e=>!(0,Gt.isEmpty)(e)&&(0,a.createElement)(E.MenuGroup,{label:(0,f.__)("Tools")},e)))};var Wt=Ut;function $t(){const e=(0,u.useSelect)((e=>e(Rt).isEditingTemplate()),[]);return(0,a.createElement)(p.PreferenceToggleMenuItem,{scope:"core/edit-post",name:e?"welcomeGuideTemplate":"welcomeGuide",label:(0,f.__)("Welcome Guide")})}(0,P.registerPlugin)("edit-post",{render(){return(0,a.createElement)(a.Fragment,null,(0,a.createElement)(Wt,null,(e=>{let{onClose:t}=e;return(0,a.createElement)(a.Fragment,null,(0,a.createElement)(E.MenuItem,{role:"menuitem",href:(0,C.addQueryArgs)("edit.php",{post_type:"wp_block"})},(0,f.__)("Manage Reusable blocks")),(0,a.createElement)(Ht,{onSelect:t}),(0,a.createElement)($t,null),(0,a.createElement)(B,null),(0,a.createElement)(E.MenuItem,{role:"menuitem",icon:k,href:(0,f.__)("https://wordpress.org/support/article/wordpress-editor/"),target:"_blank",rel:"noopener noreferrer"},(0,f.__)("Help"),(0,a.createElement)(E.VisuallyHidden,{as:"span"},(0,f.__)("(opens in a new tab)"))))})))}});var qt=window.wp.keyboardShortcuts;function jt(){const e=(0,u.useSelect)((e=>e(x.store).getEditorSettings().richEditingEnabled),[]),{switchEditorMode:t}=(0,u.useDispatch)(Rt);return(0,a.createElement)("div",{className:"edit-post-text-editor"},(0,a.createElement)(x.TextEditorGlobalKeyboardShortcuts,null),e&&(0,a.createElement)("div",{className:"edit-post-text-editor__toolbar"},(0,a.createElement)("h2",null,(0,f.__)("Editing code")),(0,a.createElement)(E.Button,{variant:"tertiary",onClick:()=>t("visual"),shortcut:M.displayShortcut.secondary("m")},(0,f.__)("Exit code editor"))),(0,a.createElement)("div",{className:"edit-post-text-editor__body"},(0,a.createElement)(x.PostTitle,null),(0,a.createElement)(x.PostTextEditor,null)))}var Zt=(0,a.createElement)(S.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,a.createElement)(S.Path,{d:"M20 11.2H6.8l3.7-3.7-1-1L3.9 12l5.6 5.5 1-1-3.7-3.7H20z"}));function Kt(e){let{children:t,contentRef:n,shouldIframe:r,styles:o,style:l}=e;const i=(0,b.__unstableUseMouseMoveTypingReset)();return r?(0,a.createElement)(b.__unstableIframe,{head:(0,a.createElement)(b.__unstableEditorStyles,{styles:o}),ref:i,contentRef:n,style:{width:"100%",height:"100%",display:"block"},name:"editor-canvas"},t):(0,a.createElement)(a.Fragment,null,(0,a.createElement)(b.__unstableEditorStyles,{styles:o}),(0,a.createElement)(b.WritingFlow,{ref:n,className:"editor-styles-wrapper",style:{flex:"1",...l},tabIndex:-1},t))}function Yt(e){for(let t=0;t<e.length;t++){if("core/post-content"===e[t].name)return e[t];if(e[t].innerBlocks.length){const n=Yt(e[t].innerBlocks);if(n)return n}}}function Xt(e){var t;let{styles:n}=e;const{deviceType:r,isWelcomeGuideVisible:o,isTemplateMode:l,editedPostTemplate:s={},wrapperBlockName:c,wrapperUniqueId:d,isBlockBasedTheme:m}=(0,u.useSelect)((e=>{const{isFeatureActive:t,isEditingTemplate:n,__experimentalGetPreviewDeviceType:r,getEditedPostTemplate:o}=e(Rt),{getCurrentPostId:l,getCurrentPostType:a,getEditorSettings:i}=e(x.store),s=n();let c;"wp_block"===a()?c="core/block":s||(c="core/post-content");const d=i(),u=d.supportsTemplateMode,m=e(Be.store).canUser("create","templates");return{deviceType:r(),isWelcomeGuideVisible:t("welcomeGuide"),isTemplateMode:s,editedPostTemplate:u&&m?o():void 0,wrapperBlockName:c,wrapperUniqueId:l(),isBlockBasedTheme:d.__unstableIsBlockBasedTheme}}),[]),{isCleanNewPost:p}=(0,u.useSelect)(x.store),g=(0,u.useSelect)((e=>e(Rt).hasMetaBoxes()),[]),{themeHasDisabledLayoutStyles:h,themeSupportsLayout:_,isFocusMode:y}=(0,u.useSelect)((e=>{const t=e(b.store).getSettings();return{themeHasDisabledLayoutStyles:t.disableLayoutStyles,themeSupportsLayout:t.supportsLayout,isFocusMode:t.focusMode}}),[]),{clearSelectedBlock:w}=(0,u.useDispatch)(b.store),{setIsEditingTemplate:S}=(0,u.useDispatch)(Rt),k={height:"100%",width:"100%",margin:0,display:"flex",flexFlow:"column",background:"white"},P={...k,borderRadius:"2px 2px 0 0",border:"1px solid #ddd",borderBottom:0},C=(0,b.__experimentalUseResizeCanvas)(r,l),T=(0,b.useSetting)("layout"),B="is-"+r.toLowerCase()+"-preview";let M,N=l?P:k;C&&(N=C),g||C||l||(M="40vh");const I=(0,a.useRef)(),D=(0,v.useMergeRefs)([I,(0,b.__unstableUseClipboardHandler)(),(0,b.__unstableUseTypewriter)(),(0,b.__unstableUseTypingObserver)(),(0,b.__unstableUseBlockSelectionClearer)()]),A=(0,b.__unstableUseBlockSelectionClearer)(),L=(0,a.useMemo)((()=>l?{type:"default"}:_?{...T,type:"constrained"}:{type:"default"}),[l,_,T]),O=(0,a.useMemo)((()=>{if(null!=s&&s.blocks)return Yt(null==s?void 0:s.blocks);const e="string"==typeof(null==s?void 0:s.content)?null==s?void 0:s.content:"";return Yt((0,i.parse)(e))||{}}),[null==s?void 0:s.content,null==s?void 0:s.blocks]),F=(0,b.__experimentaluseLayoutClasses)(O),R=V()({"is-layout-flow":!_},_&&F),H=(0,b.__experimentaluseLayoutStyles)(O,".block-editor-block-list__layout.is-root-container"),G=(null==O||null===(t=O.attributes)||void 0===t?void 0:t.layout)||{},U=(0,a.useMemo)((()=>G&&("constrained"===(null==G?void 0:G.type)||null!=G&&G.inherit||null!=G&&G.contentSize||null!=G&&G.wideSize)?{...T,...G,type:"constrained"}:{...T,...G,type:"default"}),[null==G?void 0:G.type,null==G?void 0:G.inherit,null==G?void 0:G.contentSize,null==G?void 0:G.wideSize,T]),z=null!=O&&O.isValid?U:L,W=(0,a.useRef)();return(0,a.useEffect)((()=>{var e;!o&&p()&&(null==W||null===(e=W.current)||void 0===e||e.focus())}),[o,p]),n=(0,a.useMemo)((()=>[...n,{css:".edit-post-visual-editor__post-title-wrapper{margin-top:4rem}"+(M?`body{padding-bottom:${M}}`:"")}]),[n]),(0,a.createElement)(b.BlockTools,{__unstableContentRef:I,className:V()("edit-post-visual-editor",{"is-template-mode":l})},(0,a.createElement)(x.VisualEditorGlobalKeyboardShortcuts,null),(0,a.createElement)(E.__unstableMotion.div,{className:"edit-post-visual-editor__content-area",animate:{padding:l?"48px 48px 0":"0"},ref:A},l&&(0,a.createElement)(E.Button,{className:"edit-post-visual-editor__exit-template-mode",icon:Zt,onClick:()=>{w(),S(!1)}},(0,f.__)("Back")),(0,a.createElement)(E.__unstableMotion.div,{animate:N,initial:k,className:B},(0,a.createElement)(Kt,{shouldIframe:l||"Tablet"===r||"Mobile"===r,contentRef:D,styles:n},_&&!h&&!l&&(0,a.createElement)(a.Fragment,null,(0,a.createElement)(b.__experimentalLayoutStyle,{selector:".edit-post-visual-editor__post-title-wrapper, .block-editor-block-list__layout.is-root-container",layout:L,layoutDefinitions:null==T?void 0:T.definitions}),H&&(0,a.createElement)(b.__experimentalLayoutStyle,{layout:U,css:H,layoutDefinitions:null==T?void 0:T.definitions})),!l&&(0,a.createElement)("div",{className:V()("edit-post-visual-editor__post-title-wrapper",{"is-focus-mode":y},"is-layout-flow"),contentEditable:!1},(0,a.createElement)(x.PostTitle,{ref:W})),(0,a.createElement)(b.__experimentalRecursionProvider,{blockName:c,uniqueId:d},(0,a.createElement)(b.BlockList,{className:l?"wp-site-blocks":`${R} wp-block-post-content`,__experimentalLayout:z}))))))}var Qt=function(){const{getBlockSelectionStart:e}=(0,u.useSelect)(b.store),{getEditorMode:t,isEditorSidebarOpened:n,isListViewOpened:r,isFeatureActive:o}=(0,u.useSelect)(Rt),l=(0,u.useSelect)((e=>{const{richEditingEnabled:t,codeEditingEnabled:n}=e(x.store).getEditorSettings();return!t||!n}),[]),{createInfoNotice:s}=(0,u.useDispatch)(T.store),{switchEditorMode:c,openGeneralSidebar:d,closeGeneralSidebar:m,toggleFeature:g,setIsListViewOpened:h,setIsInserterOpened:_}=(0,u.useDispatch)(Rt),{registerShortcut:E}=(0,u.useDispatch)(qt.store),{set:v}=(0,u.useDispatch)(p.store),{replaceBlocks:y}=(0,u.useDispatch)(b.store),{getBlockName:w,getSelectedBlockClientId:S,getBlockAttributes:k}=(0,u.useSelect)(b.store),P=(e,t)=>{e.preventDefault();const n=0===t?"core/paragraph":"core/heading",r=S();if(null===r)return;const o=w(r);if("core/paragraph"!==o&&"core/heading"!==o)return;const l=k(r),{content:a,align:s}=l;y(r,(0,i.createBlock)(n,{level:t,content:a,align:s}))};return(0,a.useEffect)((()=>{E({name:"core/edit-post/toggle-mode",category:"global",description:(0,f.__)("Switch between visual editor and code editor."),keyCombination:{modifier:"secondary",character:"m"}}),E({name:"core/edit-post/toggle-distraction-free",category:"global",description:(0,f.__)("Toggle distraction free mode."),keyCombination:{modifier:"primaryShift",character:"\\"}}),E({name:"core/edit-post/toggle-fullscreen",category:"global",description:(0,f.__)("Toggle fullscreen mode."),keyCombination:{modifier:"secondary",character:"f"}}),E({name:"core/edit-post/toggle-list-view",category:"global",description:(0,f.__)("Open the block list view."),keyCombination:{modifier:"access",character:"o"}}),E({name:"core/edit-post/toggle-sidebar",category:"global",description:(0,f.__)("Show or hide the settings sidebar."),keyCombination:{modifier:"primaryShift",character:","}}),E({name:"core/edit-post/next-region",category:"global",description:(0,f.__)("Navigate to the next part of the editor."),keyCombination:{modifier:"ctrl",character:"`"},aliases:[{modifier:"access",character:"n"}]}),E({name:"core/edit-post/previous-region",category:"global",description:(0,f.__)("Navigate to the previous part of the editor."),keyCombination:{modifier:"ctrlShift",character:"`"},aliases:[{modifier:"access",character:"p"},{modifier:"ctrlShift",character:"~"}]}),E({name:"core/edit-post/keyboard-shortcuts",category:"main",description:(0,f.__)("Display these keyboard shortcuts."),keyCombination:{modifier:"access",character:"h"}}),E({name:"core/block-editor/transform-heading-to-paragraph",category:"block-library",description:(0,f.__)("Transform heading to paragraph."),keyCombination:{modifier:"access",character:"0"}}),[1,2,3,4,5,6].forEach((e=>{E({name:`core/block-editor/transform-paragraph-to-heading-${e}`,category:"block-library",description:(0,f.__)("Transform paragraph to heading."),keyCombination:{modifier:"access",character:`${e}`}})}))}),[]),(0,qt.useShortcut)("core/edit-post/toggle-mode",(()=>{c("visual"===t()?"text":"visual")}),{isDisabled:l}),(0,qt.useShortcut)("core/edit-post/toggle-fullscreen",(()=>{g("fullscreenMode")})),(0,qt.useShortcut)("core/edit-post/toggle-distraction-free",(()=>{m(),h(!1),v("core/edit-post","fixedToolbar",!1),_(!1),h(!1),m(),g("distractionFree"),s(o("distractionFree")?(0,f.__)("Distraction free mode turned on."):(0,f.__)("Distraction free mode turned off."),{id:"core/edit-post/distraction-free-mode/notice",type:"snackbar"})})),(0,qt.useShortcut)("core/edit-post/toggle-sidebar",(t=>{if(t.preventDefault(),n())m();else{const t=e()?"edit-post/block":"edit-post/document";d(t)}})),(0,qt.useShortcut)("core/edit-post/toggle-list-view",(()=>h(!r()))),(0,qt.useShortcut)("core/block-editor/transform-heading-to-paragraph",(e=>P(e,0))),[1,2,3,4,5,6].forEach((e=>{(0,qt.useShortcut)(`core/block-editor/transform-paragraph-to-heading-${e}`,(t=>P(t,e)))})),null};const Jt=[{keyCombination:{modifier:"primary",character:"b"},description:(0,f.__)("Make the selected text bold.")},{keyCombination:{modifier:"primary",character:"i"},description:(0,f.__)("Make the selected text italic.")},{keyCombination:{modifier:"primary",character:"k"},description:(0,f.__)("Convert the selected text into a link.")},{keyCombination:{modifier:"primaryShift",character:"k"},description:(0,f.__)("Remove a link.")},{keyCombination:{character:"[["},description:(0,f.__)("Insert a link to a post or page.")},{keyCombination:{modifier:"primary",character:"u"},description:(0,f.__)("Underline the selected text.")},{keyCombination:{modifier:"access",character:"d"},description:(0,f.__)("Strikethrough the selected text.")},{keyCombination:{modifier:"access",character:"x"},description:(0,f.__)("Make the selected text inline code.")},{keyCombination:{modifier:"access",character:"0"},description:(0,f.__)("Convert the current heading to a paragraph.")},{keyCombination:{modifier:"access",character:"1-6"},description:(0,f.__)("Convert the current paragraph or heading to a heading of level 1 to 6.")}];function en(e){let{keyCombination:t,forceAriaLabel:n}=e;const r=t.modifier?M.displayShortcutList[t.modifier](t.character):t.character,o=t.modifier?M.shortcutAriaLabel[t.modifier](t.character):t.character;return(0,a.createElement)("kbd",{className:"edit-post-keyboard-shortcut-help-modal__shortcut-key-combination","aria-label":n||o},(Array.isArray(r)?r:[r]).map(((e,t)=>"+"===e?(0,a.createElement)(a.Fragment,{key:t},e):(0,a.createElement)("kbd",{key:t,className:"edit-post-keyboard-shortcut-help-modal__shortcut-key"},e))))}var tn=function(e){let{description:t,keyCombination:n,aliases:r=[],ariaLabel:o}=e;return(0,a.createElement)(a.Fragment,null,(0,a.createElement)("div",{className:"edit-post-keyboard-shortcut-help-modal__shortcut-description"},t),(0,a.createElement)("div",{className:"edit-post-keyboard-shortcut-help-modal__shortcut-term"},(0,a.createElement)(en,{keyCombination:n,forceAriaLabel:o}),r.map(((e,t)=>(0,a.createElement)(en,{keyCombination:e,forceAriaLabel:o,key:t})))))};var nn=function(e){let{name:t}=e;const{keyCombination:n,description:r,aliases:o}=(0,u.useSelect)((e=>{const{getShortcutKeyCombination:n,getShortcutDescription:r,getShortcutAliases:o}=e(qt.store);return{keyCombination:n(t),aliases:o(t),description:r(t)}}),[t]);return n?(0,a.createElement)(tn,{keyCombination:n,description:r,aliases:o}):null};const rn="edit-post/keyboard-shortcut-help",on=e=>{let{shortcuts:t}=e;return(0,a.createElement)("ul",{className:"edit-post-keyboard-shortcut-help-modal__shortcut-list",role:"list"},t.map(((e,t)=>(0,a.createElement)("li",{className:"edit-post-keyboard-shortcut-help-modal__shortcut",key:t},"string"==typeof e?(0,a.createElement)(nn,{name:e}):(0,a.createElement)(tn,e)))))},ln=e=>{let{title:t,shortcuts:n,className:r}=e;return(0,a.createElement)("section",{className:V()("edit-post-keyboard-shortcut-help-modal__section",r)},!!t&&(0,a.createElement)("h2",{className:"edit-post-keyboard-shortcut-help-modal__section-title"},t),(0,a.createElement)(on,{shortcuts:n}))},an=e=>{let{title:t,categoryName:n,additionalShortcuts:r=[]}=e;const o=(0,u.useSelect)((e=>e(qt.store).getCategoryShortcuts(n)),[n]);return(0,a.createElement)(ln,{title:t,shortcuts:o.concat(r)})};var sn=(0,v.compose)([(0,u.withSelect)((e=>({isModalActive:e(Rt).isModalActive(rn)}))),(0,u.withDispatch)(((e,t)=>{let{isModalActive:n}=t;const{openModal:r,closeModal:o}=e(Rt);return{toggleModal:()=>n?o():r(rn)}}))])((function(e){let{isModalActive:t,toggleModal:n}=e;return(0,qt.useShortcut)("core/edit-post/keyboard-shortcuts",n),t?(0,a.createElement)(E.Modal,{className:"edit-post-keyboard-shortcut-help-modal",title:(0,f.__)("Keyboard shortcuts"),closeButtonLabel:(0,f.__)("Close"),onRequestClose:n},(0,a.createElement)(ln,{className:"edit-post-keyboard-shortcut-help-modal__main-shortcuts",shortcuts:["core/edit-post/keyboard-shortcuts"]}),(0,a.createElement)(an,{title:(0,f.__)("Global shortcuts"),categoryName:"global"}),(0,a.createElement)(an,{title:(0,f.__)("Selection shortcuts"),categoryName:"selection"}),(0,a.createElement)(an,{title:(0,f.__)("Block shortcuts"),categoryName:"block",additionalShortcuts:[{keyCombination:{character:"/"},description:(0,f.__)("Change the block type after adding a new paragraph."),ariaLabel:(0,f.__)("Forward-slash")}]}),(0,a.createElement)(ln,{title:(0,f.__)("Text formatting"),shortcuts:Jt})):null}));function cn(e){let{willEnable:t}=e;const[n,r]=(0,a.useState)(!1);return(0,a.createElement)(a.Fragment,null,(0,a.createElement)("p",{className:"edit-post-preferences-modal__custom-fields-confirmation-message"},(0,f.__)("A page reload is required for this change. Make sure your content is saved before reloading.")),(0,a.createElement)(E.Button,{className:"edit-post-preferences-modal__custom-fields-confirmation-button",variant:"secondary",isBusy:n,disabled:n,onClick:()=>{r(!0),document.getElementById("toggle-custom-fields-form").submit()}},t?(0,f.__)("Enable & Reload"):(0,f.__)("Disable & Reload")))}var dn=(0,u.withSelect)((e=>({areCustomFieldsEnabled:!!e(x.store).getEditorSettings().enableCustomFields})))((function(e){let{label:t,areCustomFieldsEnabled:n}=e;const[r,o]=(0,a.useState)(n);return(0,a.createElement)(Te,{label:t,isChecked:r,onChange:o},r!==n&&(0,a.createElement)(cn,{willEnable:r}))})),un=(0,v.compose)((0,u.withSelect)(((e,t)=>{let{panelName:n}=t;const{isEditorPanelEnabled:r,isEditorPanelRemoved:o}=e(Rt);return{isRemoved:o(n),isChecked:r(n)}})),(0,v.ifCondition)((e=>{let{isRemoved:t}=e;return!t})),(0,u.withDispatch)(((e,t)=>{let{panelName:n}=t;return{onChange:()=>e(Rt).toggleEditorPanelEnabled(n)}})))(Te);const{Fill:mn,Slot:pn}=(0,E.createSlotFill)("EnablePluginDocumentSettingPanelOption"),gn=e=>{let{label:t,panelName:n}=e;return(0,a.createElement)(mn,null,(0,a.createElement)(un,{label:t,panelName:n}))};gn.Slot=pn;var hn=gn,_n=(0,v.compose)((0,u.withSelect)((e=>({isChecked:e(x.store).isPublishSidebarEnabled()}))),(0,u.withDispatch)((e=>{const{enablePublishSidebar:t,disablePublishSidebar:n}=e(x.store);return{onChange:e=>e?t():n()}})),(0,G.ifViewportMatches)("medium"))(Te),En=(0,v.compose)((0,u.withSelect)(((e,t)=>{let{featureName:n}=t;const{isFeatureActive:r}=e(Rt);return{isChecked:r(n)}})),(0,u.withDispatch)(((e,t)=>{let{featureName:n,onToggle:r=(()=>{})}=t;return{onChange:()=>{r(),e(Rt).toggleFeature(n)}}})))(Te);var bn=(0,u.withSelect)((e=>{const{getEditorSettings:t}=e(x.store),{getAllMetaBoxes:n}=e(Rt);return{areCustomFieldsRegistered:void 0!==t().enableCustomFields,metaBoxes:n()}}))((function(e){let{areCustomFieldsRegistered:t,metaBoxes:n,...r}=e;const o=n.filter((e=>{let{id:t}=e;return"postcustom"!==t}));return t||0!==o.length?(0,a.createElement)(Ce,r,t&&(0,a.createElement)(dn,{label:(0,f.__)("Custom fields")}),o.map((e=>{let{id:t,title:n}=e;return(0,a.createElement)(un,{key:t,label:n,panelName:`meta-box-${t}`})}))):null}));var fn=function(e){let{blockTypes:t,value:n,onItemChange:r}=e;return(0,a.createElement)("ul",{className:"edit-post-block-manager__checklist"},t.map((e=>(0,a.createElement)("li",{key:e.name,className:"edit-post-block-manager__checklist-item"},(0,a.createElement)(E.CheckboxControl,{__nextHasNoMarginBottom:!0,label:e.title,checked:n.includes(e.name),onChange:function(){for(var t=arguments.length,n=new Array(t),o=0;o<t;o++)n[o]=arguments[o];return r(e.name,...n)}}),(0,a.createElement)(b.BlockIcon,{icon:e.icon})))))};var vn=function e(t){let{title:n,blockTypes:r}=t;const o=(0,v.useInstanceId)(e),{defaultAllowedBlockTypes:l,hiddenBlockTypes:i}=(0,u.useSelect)((e=>{const{getEditorSettings:t}=e(x.store),{getHiddenBlockTypes:n}=e(Rt);return{defaultAllowedBlockTypes:t().defaultAllowedBlockTypes,hiddenBlockTypes:n()}}),[]),s=(0,a.useMemo)((()=>!0===l?r:r.filter((e=>{let{name:t}=e;return null==l?void 0:l.includes(t)}))),[l,r]),{showBlockTypes:c,hideBlockTypes:d}=(0,u.useDispatch)(Rt),m=(0,a.useCallback)(((e,t)=>{t?c(e):d(e)}),[]),p=(0,a.useCallback)((e=>{const t=r.map((e=>{let{name:t}=e;return t}));e?c(t):d(t)}),[r]);if(!s.length)return null;const g=s.map((e=>{let{name:t}=e;return t})).filter((e=>!i.includes(e))),h="edit-post-block-manager__category-title-"+o,_=g.length===s.length,b=!_&&g.length>0;return(0,a.createElement)("div",{role:"group","aria-labelledby":h,className:"edit-post-block-manager__category"},(0,a.createElement)(E.CheckboxControl,{__nextHasNoMarginBottom:!0,checked:_,onChange:p,className:"edit-post-block-manager__category-title",indeterminate:b,label:(0,a.createElement)("span",{id:h},n)}),(0,a.createElement)(fn,{blockTypes:s,value:g,onItemChange:m}))};var yn=(0,u.withSelect)((e=>{const{getBlockTypes:t,getCategories:n,hasBlockSupport:r,isMatchingSearchTerm:o}=e(i.store),{getHiddenBlockTypes:l}=e(Rt),a=t(),s=l().filter((e=>a.some((t=>t.name===e)))),c=Array.isArray(s)&&s.length;return{blockTypes:a,categories:n(),hasBlockSupport:r,isMatchingSearchTerm:o,numberOfHiddenBlocks:c}}))((function(e){let{blockTypes:t,categories:n,hasBlockSupport:r,isMatchingSearchTerm:o,numberOfHiddenBlocks:l}=e;const i=(0,v.useDebounce)(xe.speak,500),[s,c]=(0,a.useState)("");return t=t.filter((e=>r(e,"inserter",!0)&&(!s||o(e,s))&&(!e.parent||e.parent.includes("core/post-content")))),(0,a.useEffect)((()=>{if(!s)return;const e=t.length,n=(0,f.sprintf)((0,f._n)("%d result found.","%d results found.",e),e);i(n)}),[t.length,s,i]),(0,a.createElement)("div",{className:"edit-post-block-manager__content"},!!l&&(0,a.createElement)("div",{className:"edit-post-block-manager__disabled-blocks-count"},(0,f.sprintf)((0,f._n)("%d block is hidden.","%d blocks are hidden.",l),l)),(0,a.createElement)(E.SearchControl,{__nextHasNoMarginBottom:!0,label:(0,f.__)("Search for a block"),placeholder:(0,f.__)("Search for a block"),value:s,onChange:e=>c(e),className:"edit-post-block-manager__search"}),(0,a.createElement)("div",{tabIndex:"0",role:"region","aria-label":(0,f.__)("Available block types"),className:"edit-post-block-manager__results"},0===t.length&&(0,a.createElement)("p",{className:"edit-post-block-manager__no-results"},(0,f.__)("No blocks found.")),n.map((e=>(0,a.createElement)(vn,{key:e.slug,title:e.title,blockTypes:t.filter((t=>t.category===e.slug))}))),(0,a.createElement)(vn,{title:(0,f.__)("Uncategorized"),blockTypes:t.filter((e=>{let{category:t}=e;return!t}))})))}));function wn(){const e=(0,v.useViewportMatch)("medium"),{closeModal:t}=(0,u.useDispatch)(Rt),[n,r]=(0,u.useSelect)((t=>{const{getEditorSettings:n}=t(x.store),{getEditorMode:r,isFeatureActive:o}=t(Rt),l=t(Rt).isModalActive("edit-post/preferences"),a=r(),i=n().richEditingEnabled,s=o("distractionFree");return[l,!s&&e&&i&&"visual"===a,s]}),[e]),{closeGeneralSidebar:o,setIsListViewOpened:l,setIsInserterOpened:i}=(0,u.useDispatch)(Rt),{set:s}=(0,u.useDispatch)(p.store),c=()=>{s("core/edit-post","fixedToolbar",!1),i(!1),l(!1),o()},d=(0,a.useMemo)((()=>[{name:"general",tabLabel:(0,f.__)("General"),content:(0,a.createElement)(a.Fragment,null,e&&(0,a.createElement)(Ce,{title:(0,f.__)("Publishing"),description:(0,f.__)("Change options related to publishing.")},(0,a.createElement)(_n,{help:(0,f.__)("Review settings, such as visibility and tags."),label:(0,f.__)("Include pre-publish checklist")})),(0,a.createElement)(Ce,{title:(0,f.__)("Appearance"),description:(0,f.__)("Customize options related to the block editor interface and editing flow.")},(0,a.createElement)(En,{featureName:"distractionFree",onToggle:c,help:(0,f.__)("Reduce visual distractions by hiding the toolbar and other elements to focus on writing."),label:(0,f.__)("Distraction free")}),(0,a.createElement)(En,{featureName:"focusMode",help:(0,f.__)("Highlights the current block and fades other content."),label:(0,f.__)("Spotlight mode")}),(0,a.createElement)(En,{featureName:"showIconLabels",label:(0,f.__)("Show button text labels"),help:(0,f.__)("Show text instead of icons on buttons.")}),(0,a.createElement)(En,{featureName:"showListViewByDefault",help:(0,f.__)("Opens the block list view sidebar by default."),label:(0,f.__)("Always open list view")}),(0,a.createElement)(En,{featureName:"themeStyles",help:(0,f.__)("Make the editor look like your theme."),label:(0,f.__)("Use theme styles")}),r&&(0,a.createElement)(En,{featureName:"showBlockBreadcrumbs",help:(0,f.__)("Shows block breadcrumbs at the bottom of the editor."),label:(0,f.__)("Display block breadcrumbs")})))},{name:"blocks",tabLabel:(0,f.__)("Blocks"),content:(0,a.createElement)(a.Fragment,null,(0,a.createElement)(Ce,{title:(0,f.__)("Block interactions"),description:(0,f.__)("Customize how you interact with blocks in the block library and editing canvas.")},(0,a.createElement)(En,{featureName:"mostUsedBlocks",help:(0,f.__)("Places the most frequent blocks in the block library."),label:(0,f.__)("Show most used blocks")}),(0,a.createElement)(En,{featureName:"keepCaretInsideBlock",help:(0,f.__)("Aids screen readers by stopping text caret from leaving blocks."),label:(0,f.__)("Contain text cursor inside block")})),(0,a.createElement)(Ce,{title:(0,f.__)("Visible blocks"),description:(0,f.__)("Disable blocks that you don't want to appear in the inserter. They can always be toggled back on later.")},(0,a.createElement)(yn,null)))},{name:"panels",tabLabel:(0,f.__)("Panels"),content:(0,a.createElement)(a.Fragment,null,(0,a.createElement)(Ce,{title:(0,f.__)("Document settings"),description:(0,f.__)("Choose what displays in the panel.")},(0,a.createElement)(hn.Slot,null),(0,a.createElement)(x.PostTaxonomies,{taxonomyWrapper:(e,t)=>(0,a.createElement)(un,{label:(0,Gt.get)(t,["labels","menu_name"]),panelName:`taxonomy-panel-${t.slug}`})}),(0,a.createElement)(x.PostFeaturedImageCheck,null,(0,a.createElement)(un,{label:(0,f.__)("Featured image"),panelName:"featured-image"})),(0,a.createElement)(x.PostExcerptCheck,null,(0,a.createElement)(un,{label:(0,f.__)("Excerpt"),panelName:"post-excerpt"})),(0,a.createElement)(x.PostTypeSupportCheck,{supportKeys:["comments","trackbacks"]},(0,a.createElement)(un,{label:(0,f.__)("Discussion"),panelName:"discussion-panel"})),(0,a.createElement)(x.PageAttributesCheck,null,(0,a.createElement)(un,{label:(0,f.__)("Page attributes"),panelName:"page-attributes"}))),(0,a.createElement)(bn,{title:(0,f.__)("Additional"),description:(0,f.__)("Add extra areas to the editor.")}))}]),[e,r]);return n?(0,a.createElement)(ve,{closeModal:t},(0,a.createElement)(Pe,{sections:d})):null}class Sn extends a.Component{constructor(){super(...arguments),this.state={historyId:null}}componentDidUpdate(e){const{postId:t,postStatus:n,postType:r,isSavingPost:o}=this.props,{historyId:l}=this.state;"trash"!==n||o?t===e.postId&&t===l||"auto-draft"===n||!t||this.setBrowserURL(t):this.setTrashURL(t,r)}setTrashURL(e,t){window.location.href=function(e,t){return(0,C.addQueryArgs)("edit.php",{trashed:1,post_type:t,ids:e})}(e,t)}setBrowserURL(e){window.history.replaceState({id:e},"Post "+e,function(e){return(0,C.addQueryArgs)("post.php",{post:e,action:"edit"})}(e)),this.setState((()=>({historyId:e})))}render(){return null}}var kn=(0,u.withSelect)((e=>{const{getCurrentPost:t,isSavingPost:n}=e(x.store),r=t();let{id:o,status:l,type:a}=r;return["wp_template","wp_template_part"].includes(a)&&(o=r.wp_id),{postId:o,postStatus:l,postType:a,isSavingPost:n()}}))(Sn);var Pn=(0,a.createElement)(S.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"-2 -2 24 24"},(0,a.createElement)(S.Path,{d:"M20 10c0-5.51-4.49-10-10-10C4.48 0 0 4.49 0 10c0 5.52 4.48 10 10 10 5.51 0 10-4.48 10-10zM7.78 15.37L4.37 6.22c.55-.02 1.17-.08 1.17-.08.5-.06.44-1.13-.06-1.11 0 0-1.45.11-2.37.11-.18 0-.37 0-.58-.01C4.12 2.69 6.87 1.11 10 1.11c2.33 0 4.45.87 6.05 2.34-.68-.11-1.65.39-1.65 1.58 0 .74.45 1.36.9 2.1.35.61.55 1.36.55 2.46 0 1.49-1.4 5-1.4 5l-3.03-8.37c.54-.02.82-.17.82-.17.5-.05.44-1.25-.06-1.22 0 0-1.44.12-2.38.12-.87 0-2.33-.12-2.33-.12-.5-.03-.56 1.2-.06 1.22l.92.08 1.26 3.41zM17.41 10c.24-.64.74-1.87.43-4.25.7 1.29 1.05 2.71 1.05 4.25 0 3.29-1.73 6.24-4.4 7.78.97-2.59 1.94-5.2 2.92-7.78zM6.1 18.09C3.12 16.65 1.11 13.53 1.11 10c0-1.3.23-2.48.72-3.59C3.25 10.3 4.67 14.2 6.1 18.09zm4.03-6.63l2.58 6.98c-.86.29-1.76.45-2.71.45-.79 0-1.57-.11-2.29-.33.81-2.38 1.62-4.74 2.42-7.1z"}));var Cn=function(e){let{showTooltip:t,icon:n,href:r}=e;const{isActive:o,isRequestingSiteIcon:l,postType:i,siteIconUrl:s}=(0,u.useSelect)((e=>{const{getCurrentPostType:t}=e(x.store),{isFeatureActive:n}=e(Rt),{getEntityRecord:r,getPostType:o,isResolving:l}=e(Be.store),a=r("root","__unstableBase",void 0)||{};return{isActive:n("fullscreenMode"),isRequestingSiteIcon:l("getEntityRecord",["root","__unstableBase",void 0]),postType:o(t()),siteIconUrl:a.site_icon_url}}),[]),c=(0,v.useReducedMotion)();if(!o||!i)return null;let d=(0,a.createElement)(E.Icon,{size:"36px",icon:Pn});const m={expand:{scale:1.25,transition:{type:"tween",duration:"0.3"}}};s&&(d=(0,a.createElement)(E.__unstableMotion.img,{variants:!c&&m,alt:(0,f.__)("Site Icon"),className:"edit-post-fullscreen-mode-close_site-icon",src:s})),l&&(d=null),n&&(d=(0,a.createElement)(E.Icon,{size:"36px",icon:n}));const p=V()({"edit-post-fullscreen-mode-close":!0,"has-icon":s});return(0,a.createElement)(E.__unstableMotion.div,{whileHover:"expand"},(0,a.createElement)(E.Button,{className:p,href:null!=r?r:(0,C.addQueryArgs)("edit.php",{post_type:i.slug}),label:(0,Gt.get)(i,["labels","view_items"],(0,f.__)("Back")),showTooltip:t},d))};var Tn=(0,a.createElement)(S.SVG,{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},(0,a.createElement)(S.Path,{d:"M13.8 5.2H3v1.5h10.8V5.2zm-3.6 12v1.5H21v-1.5H10.2zm7.2-6H6.6v1.5h10.8v-1.5z"}));var xn=(0,a.createElement)(S.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,a.createElement)(S.Path,{d:"M18 11.2h-5.2V6h-1.6v5.2H6v1.6h5.2V18h1.6v-5.2H18z"}));const Bn=e=>{e.preventDefault()};var Mn=function(){const e=(0,a.useRef)(),{setIsInserterOpened:t,setIsListViewOpened:n}=(0,u.useDispatch)(Rt),{isInserterEnabled:r,isInserterOpened:o,isTextModeEnabled:l,showIconLabels:i,isListViewOpen:s,listViewShortcut:c}=(0,u.useSelect)((e=>{const{hasInserterItems:t,getBlockRootClientId:n,getBlockSelectionEnd:r}=e(b.store),{getEditorSettings:o}=e(x.store),{getEditorMode:l,isFeatureActive:a,isListViewOpened:i}=e(Rt),{getShortcutRepresentation:s}=e(qt.store);return{isInserterEnabled:"visual"===l()&&o().richEditingEnabled&&t(n(r())),isInserterOpened:e(Rt).isInserterOpened(),isTextModeEnabled:"text"===l(),showIconLabels:a("showIconLabels"),isListViewOpen:i(),listViewShortcut:s("core/edit-post/toggle-list-view")}}),[]),d=(0,v.useViewportMatch)("medium"),m=(0,v.useViewportMatch)("wide"),p=(0,f.__)("Document tools"),g=(0,a.useCallback)((()=>n(!s)),[n,s]),h=(0,a.createElement)(a.Fragment,null,(0,a.createElement)(E.ToolbarItem,{as:E.Button,className:"edit-post-header-toolbar__document-overview-toggle",icon:Tn,disabled:l,isPressed:s,label:(0,f.__)("Document Overview"),onClick:g,shortcut:c,showTooltip:!i,variant:i?"tertiary":void 0})),_=(0,a.useCallback)((()=>{o?(e.current.focus(),t(!1)):t(!0)}),[o,t]),y=(0,f._x)("Toggle block inserter","Generic label for block inserter button"),w=o?(0,f.__)("Close"):(0,f.__)("Add");return(0,a.createElement)(b.NavigableToolbar,{className:"edit-post-header-toolbar","aria-label":p},(0,a.createElement)("div",{className:"edit-post-header-toolbar__left"},(0,a.createElement)(E.ToolbarItem,{ref:e,as:E.Button,className:"edit-post-header-toolbar__inserter-toggle",variant:"primary",isPressed:o,onMouseDown:Bn,onClick:_,disabled:!r,icon:xn,label:i?w:y,showTooltip:!i}),(m||!i)&&(0,a.createElement)(a.Fragment,null,d&&(0,a.createElement)(E.ToolbarItem,{as:b.ToolSelector,showTooltip:!i,variant:i?"tertiary":void 0,disabled:l}),(0,a.createElement)(E.ToolbarItem,{as:x.EditorHistoryUndo,showTooltip:!i,variant:i?"tertiary":void 0}),(0,a.createElement)(E.ToolbarItem,{as:x.EditorHistoryRedo,showTooltip:!i,variant:i?"tertiary":void 0}),h)))};const Nn=[{value:"visual",label:(0,f.__)("Visual editor")},{value:"text",label:(0,f.__)("Code editor")}];var In=function(){const{shortcut:e,isRichEditingEnabled:t,isCodeEditingEnabled:n,isEditingTemplate:r,mode:o}=(0,u.useSelect)((e=>({shortcut:e(qt.store).getShortcutRepresentation("core/edit-post/toggle-mode"),isRichEditingEnabled:e(x.store).getEditorSettings().richEditingEnabled,isCodeEditingEnabled:e(x.store).getEditorSettings().codeEditingEnabled,isEditingTemplate:e(Rt).isEditingTemplate(),mode:e(Rt).getEditorMode()})),[]),{switchEditorMode:l}=(0,u.useDispatch)(Rt);if(r)return null;if(!t||!n)return null;const i=Nn.map((t=>t.value!==o?{...t,shortcut:e}:t));return(0,a.createElement)(E.MenuGroup,{label:(0,f.__)("Editor")},(0,a.createElement)(E.MenuItemsChoice,{choices:i,value:o,onSelect:l}))};function Dn(){const{openModal:e}=(0,u.useDispatch)(Rt);return(0,a.createElement)(E.MenuItem,{onClick:()=>{e("edit-post/preferences")}},(0,f.__)("Preferences"))}var An=function(){const e=(0,u.useRegistry)(),t=(0,u.useSelect)((e=>e(b.store).getSettings().isDistractionFree),[]),n=(0,u.useSelect)((e=>e(b.store).getBlocks()),[]),{setIsInserterOpened:r,setIsListViewOpened:o,closeGeneralSidebar:l}=(0,u.useDispatch)(Rt),{set:i}=(0,u.useDispatch)(p.store),{selectBlock:s}=(0,u.useDispatch)(b.store);return(0,v.useViewportMatch)("medium")?(0,a.createElement)(E.MenuGroup,{label:(0,f._x)("View","noun")},(0,a.createElement)(p.PreferenceToggleMenuItem,{scope:"core/edit-post",disabled:t,name:"fixedToolbar",label:(0,f.__)("Top toolbar"),info:(0,f.__)("Access all block and document tools in a single place"),messageActivated:(0,f.__)("Top toolbar activated"),messageDeactivated:(0,f.__)("Top toolbar deactivated")}),(0,a.createElement)(p.PreferenceToggleMenuItem,{scope:"core/edit-post",name:"focusMode",label:(0,f.__)("Spotlight mode"),info:(0,f.__)("Focus on one block at a time"),messageActivated:(0,f.__)("Spotlight mode activated"),messageDeactivated:(0,f.__)("Spotlight mode deactivated")}),(0,a.createElement)(p.PreferenceToggleMenuItem,{scope:"core/edit-post",name:"fullscreenMode",label:(0,f.__)("Fullscreen mode"),info:(0,f.__)("Show and hide admin UI"),messageActivated:(0,f.__)("Fullscreen mode activated"),messageDeactivated:(0,f.__)("Fullscreen mode deactivated"),shortcut:M.displayShortcut.secondary("f")}),(0,a.createElement)(p.PreferenceToggleMenuItem,{scope:"core/edit-post",name:"distractionFree",onToggle:()=>{e.batch((()=>{i("core/edit-post","fixedToolbar",!1),r(!1),o(!1),l(),!t&&n.length&&s(n[0].clientId)}))},label:(0,f.__)("Distraction free"),info:(0,f.__)("Write with calmness"),messageActivated:(0,f.__)("Distraction free mode activated"),messageDeactivated:(0,f.__)("Distraction free mode deactivated"),shortcut:M.displayShortcut.primaryShift("\\")})):null};var Ln=e=>{let{showIconLabels:t}=e;const n=(0,v.useViewportMatch)("large");return(0,a.createElement)(fe,{toggleProps:{showTooltip:!t,...t&&{variant:"tertiary"}}},(e=>{let{onClose:r}=e;return(0,a.createElement)(a.Fragment,null,t&&!n&&(0,a.createElement)(ue.Slot,{className:t&&"show-icon-labels",scope:"core/edit-post"}),(0,a.createElement)(An,null),(0,a.createElement)(In,null),(0,a.createElement)(ie.Slot,{name:"core/edit-post/plugin-more-menu",label:(0,f.__)("Plugins"),as:E.MenuGroup,fillProps:{onClick:r}}),(0,a.createElement)(Wt.Slot,{fillProps:{onClose:r}}),(0,a.createElement)(E.MenuGroup,null,(0,a.createElement)(Dn,null)))}))};var On=(0,v.compose)((0,u.withSelect)((e=>({hasPublishAction:(0,Gt.get)(e(x.store).getCurrentPost(),["_links","wp:action-publish"],!1),isBeingScheduled:e(x.store).isEditedPostBeingScheduled(),isPending:e(x.store).isCurrentPostPending(),isPublished:e(x.store).isCurrentPostPublished(),isPublishSidebarEnabled:e(x.store).isPublishSidebarEnabled(),isPublishSidebarOpened:e(Rt).isPublishSidebarOpened(),isScheduled:e(x.store).isCurrentPostScheduled()}))),(0,u.withDispatch)((e=>{const{togglePublishSidebar:t}=e(Rt);return{togglePublishSidebar:t}})))((function(e){let{forceIsDirty:t,forceIsSaving:n,hasPublishAction:r,isBeingScheduled:o,isPending:l,isPublished:i,isPublishSidebarEnabled:s,isPublishSidebarOpened:c,isScheduled:d,togglePublishSidebar:u,setEntitiesSavedStatesCallback:m}=e;const p="toggle",g="button",h=(0,v.useViewportMatch)("medium","<");let _;return _=i||d&&o||l&&!r&&!h?g:h||s?p:g,(0,a.createElement)(x.PostPublishButton,{forceIsDirty:t,forceIsSaving:n,isOpen:c,isToggle:_===p,onToggle:u,setEntitiesSavedStatesCallback:m})}));function Vn(){const{hasActiveMetaboxes:e,isPostSaveable:t,isSaving:n,isViewable:r,deviceType:o}=(0,u.useSelect)((e=>{const{getEditedPostAttribute:t}=e(x.store),{getPostType:n}=e(Be.store),r=n(t("type"));return{hasActiveMetaboxes:e(Rt).hasMetaBoxes(),isSaving:e(Rt).isSavingMetaBoxes(),isPostSaveable:e(x.store).isEditedPostSaveable(),isViewable:(0,Gt.get)(r,["viewable"],!1),deviceType:e(Rt).__experimentalGetPreviewDeviceType()}}),[]),{__experimentalSetPreviewDeviceType:l}=(0,u.useDispatch)(Rt);return(0,a.createElement)(b.__experimentalPreviewOptions,{isEnabled:t,className:"edit-post-post-preview-dropdown",deviceType:o,setDeviceType:l,viewLabel:(0,f.__)("Preview")},r&&(0,a.createElement)(E.MenuGroup,null,(0,a.createElement)("div",{className:"edit-post-header-preview__grouping-external"},(0,a.createElement)(x.PostPreviewButton,{className:"edit-post-header-preview__button-external",role:"menuitem",forceIsAutosaveable:e,forcePreviewLink:n?null:void 0,textContent:(0,a.createElement)(a.Fragment,null,(0,f.__)("Preview in new tab"),(0,a.createElement)(E.Icon,{icon:k}))}))))}const Fn="__experimentalMainDashboardButton",{Fill:Rn,Slot:Hn}=(0,E.createSlotFill)(Fn),Gn=Rn;Gn.Slot=e=>{let{children:t}=e;const n=(0,E.__experimentalUseSlotFills)(Fn);return Boolean(n&&n.length)?(0,a.createElement)(Hn,{bubblesVirtually:!0}):t};var Un=Gn;var zn=(0,a.createElement)(S.SVG,{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},(0,a.createElement)(S.Path,{d:"M17.5 11.6L12 16l-5.5-4.4.9-1.2L12 14l4.5-3.6 1 1.2z"}));function Wn(){const{clearSelectedBlock:e}=(0,u.useDispatch)(b.store),{setIsEditingTemplate:t}=(0,u.useDispatch)(Rt),{getEditorSettings:n}=(0,u.useSelect)(x.store),{updateEditorSettings:r,editPost:o}=(0,u.useDispatch)(x.store),{deleteEntityRecord:l}=(0,u.useDispatch)(Be.store),{template:i}=(0,u.useSelect)((e=>{const{isEditingTemplate:t,getEditedPostTemplate:n}=e(Rt);return{template:t()?n():null}}),[]),[s,c]=(0,a.useState)(!1);if(!i||!i.wp_id)return null;let d=i.slug;null!=i&&i.title&&(d=i.title);const m=null==i?void 0:i.has_theme_file;return(0,a.createElement)(E.MenuGroup,{className:"edit-post-template-top-area__second-menu-group"},(0,a.createElement)(a.Fragment,null,(0,a.createElement)(E.MenuItem,{className:"edit-post-template-top-area__delete-template-button",isDestructive:!m,onClick:()=>{c(!0)},info:m?(0,f.__)("Use the template as supplied by the theme."):void 0},m?(0,f.__)("Clear customizations"):(0,f.__)("Delete template")),(0,a.createElement)(E.__experimentalConfirmDialog,{isOpen:s,onConfirm:()=>{var a;e(),t(!1),c(!1),o({template:""});const s=n(),d=Object.fromEntries(Object.entries(null!==(a=s.availableTemplates)&&void 0!==a?a:{}).filter((e=>{let[t]=e;return t!==i.slug})));r({...s,availableTemplates:d}),l("postType","wp_template",i.id,{throwOnError:!0})},onCancel:()=>{c(!1)}},(0,f.sprintf)((0,f.__)("Are you sure you want to delete the %s template? It may be used by other pages or posts."),d))))}function $n(){const[e,t]=(0,a.useState)(!1),{template:n}=(0,u.useSelect)((e=>{const{getEditedPostTemplate:t}=e(Rt);return{template:t()}}),[]),{editEntityRecord:r}=(0,u.useDispatch)(Be.store),{getEditorSettings:o}=(0,u.useSelect)(x.store),{updateEditorSettings:l}=(0,u.useDispatch)(x.store);if(!n.is_custom||n.has_theme_file)return null;let i=(0,f.__)("Default");return null!=n&&n.title?i=n.title:n&&(i=n.slug),(0,a.createElement)("div",{className:"edit-site-template-details__group"},(0,a.createElement)(E.TextControl,{__nextHasNoMarginBottom:!0,label:(0,f.__)("Title"),value:e?"":i,help:(0,f.__)('Give the template a title that indicates its purpose, e.g. "Full Width".'),onChange:a=>{if(!a&&!e)return void t(!0);t(!1);const i=o(),s=(0,Gt.mapValues)(i.availableTemplates,((e,t)=>t!==n.slug?e:a));l({...i,availableTemplates:s}),r("postType","wp_template",n.id,{title:a})},onBlur:()=>t(!1)}))}function qn(){const{description:e,title:t}=(0,u.useSelect)((e=>{const{getEditedPostTemplate:t}=e(Rt);return{title:t().title,description:t().description}}),[]);return e?(0,a.createElement)("div",{className:"edit-site-template-details__group"},(0,a.createElement)(E.__experimentalHeading,{level:4,weight:600},t),(0,a.createElement)(E.__experimentalText,{className:"edit-post-template-details__description",size:"body",as:"p",style:{marginTop:"12px"}},e)):null}var jn=function(){const{template:e,isEditing:t,title:n}=(0,u.useSelect)((e=>{const{isEditingTemplate:t,getEditedPostTemplate:n}=e(Rt),{getEditedPostAttribute:r}=e(x.store),o=t();return{template:o?n():null,isEditing:o,title:r("title")?r("title"):(0,f.__)("Untitled")}}),[]),{clearSelectedBlock:r}=(0,u.useDispatch)(b.store),{setIsEditingTemplate:o}=(0,u.useDispatch)(Rt);if(!t||!e)return null;let l=(0,f.__)("Default");null!=e&&e.title?l=e.title:e&&(l=e.slug);const i=!!(e.custom||e.wp_id||e.description);return(0,a.createElement)("div",{className:"edit-post-template-top-area"},(0,a.createElement)(E.Button,{className:"edit-post-template-post-title",isLink:!0,showTooltip:!0,label:(0,f.sprintf)((0,f.__)("Edit %s"),n),onClick:()=>{r(),o(!1)}},n),i?(0,a.createElement)(E.Dropdown,{popoverProps:{placement:"bottom"},contentClassName:"edit-post-template-top-area__popover",renderToggle:e=>{let{onToggle:t}=e;return(0,a.createElement)(E.Button,{className:"edit-post-template-title",isLink:!0,icon:zn,showTooltip:!0,onClick:t,label:(0,f.__)("Template Options")},l)},renderContent:()=>(0,a.createElement)(a.Fragment,null,(0,a.createElement)($n,null),(0,a.createElement)(qn,null),(0,a.createElement)(Wn,null))}):(0,a.createElement)(E.__experimentalText,{className:"edit-post-template-title",size:"body",style:{lineHeight:"24px"}},l))};var Zn=function(e){let{setEntitiesSavedStatesCallback:t}=e;const n=(0,v.useViewportMatch)("large"),{hasActiveMetaboxes:r,isPublishSidebarOpened:o,isSaving:l,showIconLabels:i,isDistractionFreeMode:s}=(0,u.useSelect)((e=>({hasActiveMetaboxes:e(Rt).hasMetaBoxes(),isPublishSidebarOpened:e(Rt).isPublishSidebarOpened(),isSaving:e(Rt).isSavingMetaBoxes(),showIconLabels:e(Rt).isFeatureActive("showIconLabels"),isDistractionFreeMode:e(Rt).isFeatureActive("distractionFree")})),[]),c=s&&n,d=V()("edit-post-header"),m={hidden:c?{y:"-50"}:{y:0},hover:{y:0,transition:{type:"tween",delay:.2}}},p={hidden:c?{x:"-100%"}:{x:0},hover:{x:0,transition:{type:"tween",delay:.2}}};return(0,a.createElement)("div",{className:d},(0,a.createElement)(Un.Slot,null,(0,a.createElement)(E.__unstableMotion.div,{variants:p,transition:{type:"tween",delay:.8}},(0,a.createElement)(Cn,{showTooltip:!0}))),(0,a.createElement)(E.__unstableMotion.div,{variants:m,transition:{type:"tween",delay:.8},className:"edit-post-header__toolbar"},(0,a.createElement)(Mn,null),(0,a.createElement)(jn,null)),(0,a.createElement)(E.__unstableMotion.div,{variants:m,transition:{type:"tween",delay:.8},className:"edit-post-header__settings"},!o&&(0,a.createElement)(x.PostSavedState,{forceIsDirty:r,forceIsSaving:l,showIconLabels:i}),(0,a.createElement)(Vn,null),(0,a.createElement)(x.PostPreviewButton,{forceIsAutosaveable:r,forcePreviewLink:l?null:void 0}),(0,a.createElement)(On,{forceIsDirty:r,forceIsSaving:l,setEntitiesSavedStatesCallback:t}),(n||!i)&&(0,a.createElement)(a.Fragment,null,(0,a.createElement)(ue.Slot,{scope:"core/edit-post"}),(0,a.createElement)(Ln,{showIconLabels:i})),i&&!n&&(0,a.createElement)(Ln,{showIconLabels:i})))};var Kn=(0,a.createElement)(S.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,a.createElement)(S.Path,{d:"M13 11.8l6.1-6.3-1-1-6.1 6.2-6.1-6.2-1 1 6.1 6.3-6.5 6.7 1 1 6.5-6.6 6.5 6.6 1-1z"}));function Yn(){const{insertionPoint:e,showMostUsedBlocks:t}=(0,u.useSelect)((e=>{const{isFeatureActive:t,__experimentalGetInsertionPoint:n}=e(Rt);return{insertionPoint:n(),showMostUsedBlocks:t("mostUsedBlocks")}}),[]),{setIsInserterOpened:n}=(0,u.useDispatch)(Rt),r=(0,v.useViewportMatch)("medium","<"),o=r?"div":E.VisuallyHidden,[l,i]=(0,v.__experimentalUseDialog)({onClose:()=>n(!1),focusOnMount:null}),s=(0,a.useRef)();return(0,a.useEffect)((()=>{s.current.focusSearch()}),[]),(0,a.createElement)("div",_({ref:l},i,{className:"edit-post-editor__inserter-panel"}),(0,a.createElement)(o,{className:"edit-post-editor__inserter-panel-header"},(0,a.createElement)(E.Button,{icon:Kn,label:(0,f.__)("Close block inserter"),onClick:()=>n(!1)})),(0,a.createElement)("div",{className:"edit-post-editor__inserter-panel-content"},(0,a.createElement)(b.__experimentalLibrary,{showMostUsedBlocks:t,showInserterHelpPanel:!0,shouldFocusBlock:r,rootClientId:e.rootClientId,__experimentalInsertionIndex:e.insertionIndex,__experimentalFilterValue:e.filterValue,ref:s})))}function Xn(){return(0,a.createElement)(E.SVG,{width:"138",height:"148",viewBox:"0 0 138 148",fill:"none",xmlns:"http://www.w3.org/2000/svg"},(0,a.createElement)(E.Rect,{width:"138",height:"148",rx:"4",fill:"#F0F6FC"}),(0,a.createElement)(E.Line,{x1:"44",y1:"28",x2:"24",y2:"28",stroke:"#DDDDDD"}),(0,a.createElement)(E.Rect,{x:"48",y:"16",width:"27",height:"23",rx:"4",fill:"#DDDDDD"}),(0,a.createElement)(E.Path,{d:"M54.7585 32V23.2727H56.6037V26.8736H60.3494V23.2727H62.1903V32H60.3494V28.3949H56.6037V32H54.7585ZM67.4574 23.2727V32H65.6122V25.0241H65.5611L63.5625 26.277V24.6406L65.723 23.2727H67.4574Z",fill:"black"}),(0,a.createElement)(E.Line,{x1:"55",y1:"59",x2:"24",y2:"59",stroke:"#DDDDDD"}),(0,a.createElement)(E.Rect,{x:"59",y:"47",width:"29",height:"23",rx:"4",fill:"#DDDDDD"}),(0,a.createElement)(E.Path,{d:"M65.7585 63V54.2727H67.6037V57.8736H71.3494V54.2727H73.1903V63H71.3494V59.3949H67.6037V63H65.7585ZM74.6605 63V61.6705L77.767 58.794C78.0313 58.5384 78.2528 58.3082 78.4318 58.1037C78.6136 57.8991 78.7514 57.6989 78.8452 57.5028C78.9389 57.304 78.9858 57.0895 78.9858 56.8594C78.9858 56.6037 78.9276 56.3835 78.8111 56.1989C78.6946 56.0114 78.5355 55.8679 78.3338 55.7685C78.1321 55.6662 77.9034 55.6151 77.6477 55.6151C77.3807 55.6151 77.1477 55.669 76.9489 55.777C76.75 55.8849 76.5966 56.0398 76.4886 56.2415C76.3807 56.4432 76.3267 56.6832 76.3267 56.9616H74.5753C74.5753 56.3906 74.7045 55.8949 74.9631 55.4744C75.2216 55.054 75.5838 54.7287 76.0497 54.4986C76.5156 54.2685 77.0526 54.1534 77.6605 54.1534C78.2855 54.1534 78.8295 54.2642 79.2926 54.4858C79.7585 54.7045 80.1207 55.0085 80.3793 55.3977C80.6378 55.7869 80.767 56.233 80.767 56.7358C80.767 57.0653 80.7017 57.3906 80.571 57.7116C80.4432 58.0327 80.2145 58.3892 79.8849 58.7812C79.5554 59.1705 79.0909 59.6378 78.4915 60.1832L77.2173 61.4318V61.4915H80.8821V63H74.6605Z",fill:"black"}),(0,a.createElement)(E.Line,{x1:"80",y1:"90",x2:"24",y2:"90",stroke:"#DDDDDD"}),(0,a.createElement)(E.Rect,{x:"84",y:"78",width:"30",height:"23",rx:"4",fill:"#F0B849"}),(0,a.createElement)(E.Path,{d:"M90.7585 94V85.2727H92.6037V88.8736H96.3494V85.2727H98.1903V94H96.3494V90.3949H92.6037V94H90.7585ZM99.5284 92.4659V91.0128L103.172 85.2727H104.425V87.2841H103.683L101.386 90.919V90.9872H106.564V92.4659H99.5284ZM103.717 94V92.0227L103.751 91.3793V85.2727H105.482V94H103.717Z",fill:"black"}),(0,a.createElement)(E.Line,{x1:"66",y1:"121",x2:"24",y2:"121",stroke:"#DDDDDD"}),(0,a.createElement)(E.Rect,{x:"70",y:"109",width:"29",height:"23",rx:"4",fill:"#DDDDDD"}),(0,a.createElement)(E.Path,{d:"M76.7585 125V116.273H78.6037V119.874H82.3494V116.273H84.1903V125H82.3494V121.395H78.6037V125H76.7585ZM88.8864 125.119C88.25 125.119 87.6832 125.01 87.1861 124.791C86.6918 124.57 86.3011 124.266 86.0142 123.879C85.7301 123.49 85.5838 123.041 85.5753 122.533H87.4332C87.4446 122.746 87.5142 122.933 87.642 123.095C87.7727 123.254 87.946 123.378 88.1619 123.466C88.3778 123.554 88.6207 123.598 88.8906 123.598C89.1719 123.598 89.4205 123.548 89.6364 123.449C89.8523 123.349 90.0213 123.212 90.1435 123.036C90.2656 122.859 90.3267 122.656 90.3267 122.426C90.3267 122.193 90.2614 121.987 90.1307 121.808C90.0028 121.626 89.8182 121.484 89.5767 121.382C89.3381 121.28 89.054 121.229 88.7244 121.229H87.9105V119.874H88.7244C89.0028 119.874 89.2486 119.825 89.4616 119.729C89.6776 119.632 89.8452 119.499 89.9645 119.328C90.0838 119.155 90.1435 118.953 90.1435 118.723C90.1435 118.504 90.0909 118.312 89.9858 118.148C89.8835 117.98 89.7386 117.849 89.5511 117.756C89.3665 117.662 89.1506 117.615 88.9034 117.615C88.6534 117.615 88.4247 117.661 88.2173 117.751C88.0099 117.839 87.8438 117.966 87.7188 118.131C87.5938 118.295 87.527 118.489 87.5185 118.71H85.75C85.7585 118.207 85.902 117.764 86.1804 117.381C86.4588 116.997 86.8338 116.697 87.3054 116.482C87.7798 116.263 88.3153 116.153 88.9119 116.153C89.5142 116.153 90.0412 116.263 90.4929 116.482C90.9446 116.7 91.2955 116.996 91.5455 117.368C91.7983 117.737 91.9233 118.152 91.9205 118.612C91.9233 119.101 91.7713 119.509 91.4645 119.835C91.1605 120.162 90.7642 120.369 90.2756 120.457V120.526C90.9176 120.608 91.4063 120.831 91.7415 121.195C92.0795 121.555 92.2472 122.007 92.2443 122.55C92.2472 123.047 92.1037 123.489 91.8139 123.875C91.527 124.261 91.1307 124.565 90.625 124.787C90.1193 125.009 89.5398 125.119 88.8864 125.119Z",fill:"black"}))}function Qn(){const{headingCount:e}=(0,u.useSelect)((e=>{const{getGlobalBlockCount:t}=e(b.store);return{headingCount:t("core/heading")}}),[]);return(0,a.createElement)(a.Fragment,null,(0,a.createElement)("div",{className:"edit-post-editor__list-view-overview"},(0,a.createElement)("div",null,(0,a.createElement)(E.__experimentalText,null,(0,f.__)("Characters:")),(0,a.createElement)(E.__experimentalText,null,(0,a.createElement)(x.CharacterCount,null))),(0,a.createElement)("div",null,(0,a.createElement)(E.__experimentalText,null,(0,f.__)("Words:")),(0,a.createElement)(x.WordCount,null)),(0,a.createElement)("div",null,(0,a.createElement)(E.__experimentalText,null,(0,f.__)("Time to read:")),(0,a.createElement)(x.TimeToRead,null))),e>0?(0,a.createElement)(x.DocumentOutline,null):(0,a.createElement)("div",{className:"edit-post-editor__list-view-empty-headings"},(0,a.createElement)(Xn,null),(0,a.createElement)("p",null,(0,f.__)("Navigate the structure of your document and address issues like empty or incorrect heading levels."))))}function Jn(){const{setIsListViewOpened:e}=(0,u.useDispatch)(Rt),t=(0,v.useFocusOnMount)("firstElement"),n=(0,v.useFocusReturn)(),r=(0,v.useFocusReturn)();const[o,l]=(0,a.useState)("list-view");return(0,a.createElement)("div",{"aria-label":(0,f.__)("Document Overview"),className:"edit-post-editor__document-overview-panel",onKeyDown:function(t){t.keyCode!==M.ESCAPE||t.defaultPrevented||(t.preventDefault(),e(!1))}},(0,a.createElement)("div",{className:"edit-post-editor__document-overview-panel-header components-panel__header edit-post-sidebar__panel-tabs",ref:n},(0,a.createElement)(E.Button,{icon:U,label:(0,f.__)("Close Document Overview Sidebar"),onClick:()=>e(!1)}),(0,a.createElement)("ul",null,(0,a.createElement)("li",null,(0,a.createElement)(E.Button,{onClick:()=>{l("list-view")},className:V()("edit-post-sidebar__panel-tab",{"is-active":"list-view"===o}),"aria-current":"list-view"===o},(0,f.__)("List View"))),(0,a.createElement)("li",null,(0,a.createElement)(E.Button,{onClick:()=>{l("outline")},className:V()("edit-post-sidebar__panel-tab",{"is-active":"outline"===o}),"aria-current":"outline"===o},(0,f.__)("Outline"))))),(0,a.createElement)("div",{ref:(0,v.useMergeRefs)([r,t]),className:"edit-post-editor__list-view-container"},"list-view"===o&&(0,a.createElement)("div",{className:"edit-post-editor__list-view-panel-content"},(0,a.createElement)(b.__experimentalListView,null)),"outline"===o&&(0,a.createElement)(Qn,null)))}var er=(0,a.createElement)(S.SVG,{width:"24",height:"24",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,a.createElement)(S.Path,{fillRule:"evenodd",clipRule:"evenodd",d:"M18 4H6c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zM8.5 18.5H6c-.3 0-.5-.2-.5-.5V6c0-.3.2-.5.5-.5h2.5v13zm10-.5c0 .3-.2.5-.5.5h-8v-13h8c.3 0 .5.2.5.5v12z"}));var tr=(0,a.createElement)(S.SVG,{width:"24",height:"24",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,a.createElement)(S.Path,{fillRule:"evenodd",clipRule:"evenodd",d:"M18 4H6c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-4 14.5H6c-.3 0-.5-.2-.5-.5V6c0-.3.2-.5.5-.5h8v13zm4.5-.5c0 .3-.2.5-.5.5h-2.5v-13H18c.3 0 .5.2.5.5v12z"}));var nr=e=>{let{sidebarName:t}=e;const{openGeneralSidebar:n}=(0,u.useDispatch)(Rt),r=()=>n("edit-post/document"),{documentLabel:o,isTemplateMode:l}=(0,u.useSelect)((e=>({documentLabel:e(x.store).getPostTypeLabel()||(0,f._x)("Document","noun"),isTemplateMode:e(Rt).isEditingTemplate()})),[]),[i,s]="edit-post/document"===t?[(0,f.sprintf)((0,f.__)("%s (selected)"),o),"is-active"]:[o,""],[c,d]="edit-post/block"===t?[(0,f.__)("Block (selected)"),"is-active"]:[(0,f.__)("Block"),""],[m,p]="edit-post/document"===t?[(0,f.__)("Template (selected)"),"is-active"]:[(0,f.__)("Template"),""];return(0,a.createElement)("ul",null,!l&&(0,a.createElement)("li",null,(0,a.createElement)(E.Button,{onClick:r,className:`edit-post-sidebar__panel-tab ${s}`,"aria-label":i,"data-label":o},o)),l&&(0,a.createElement)("li",null,(0,a.createElement)(E.Button,{onClick:r,className:`edit-post-sidebar__panel-tab ${p}`,"aria-label":m,"data-label":(0,f.__)("Template")},(0,f.__)("Template"))),(0,a.createElement)("li",null,(0,a.createElement)(E.Button,{onClick:()=>n("edit-post/block"),className:`edit-post-sidebar__panel-tab ${d}`,"aria-label":c,"data-label":(0,f.__)("Block")},(0,f.__)("Block"))))};function rr(e){let{isOpen:t,onClick:n}=e;const r=(0,x.usePostVisibilityLabel)();return(0,a.createElement)(E.Button,{className:"edit-post-post-visibility__toggle",variant:"tertiary","aria-expanded":t,"aria-label":(0,f.sprintf)((0,f.__)("Select visibility: %s"),r),onClick:n},r)}var or=function(){const[e,t]=(0,a.useState)(null),n=(0,a.useMemo)((()=>({anchor:e,placement:"bottom-end"})),[e]);return(0,a.createElement)(x.PostVisibilityCheck,{render:e=>{let{canEdit:r}=e;return(0,a.createElement)(E.PanelRow,{ref:t,className:"edit-post-post-visibility"},(0,a.createElement)("span",null,(0,f.__)("Visibility")),!r&&(0,a.createElement)("span",null,(0,a.createElement)(x.PostVisibilityLabel,null)),r&&(0,a.createElement)(E.Dropdown,{contentClassName:"edit-post-post-visibility__dialog",popoverProps:n,focusOnMount:!0,renderToggle:e=>{let{isOpen:t,onToggle:n}=e;return(0,a.createElement)(rr,{isOpen:t,onClick:n})},renderContent:e=>{let{onClose:t}=e;return(0,a.createElement)(x.PostVisibility,{onClose:t})}}))}})};function lr(){return(0,a.createElement)(x.PostTrashCheck,null,(0,a.createElement)(E.PanelRow,null,(0,a.createElement)(x.PostTrash,null)))}function ar(){const[e,t]=(0,a.useState)(null),n=(0,a.useMemo)((()=>({anchor:e,placement:"bottom-end"})),[e]);return(0,a.createElement)(x.PostScheduleCheck,null,(0,a.createElement)(E.PanelRow,{className:"edit-post-post-schedule",ref:t},(0,a.createElement)("span",null,(0,f.__)("Publish")),(0,a.createElement)(E.Dropdown,{popoverProps:n,contentClassName:"edit-post-post-schedule__dialog",focusOnMount:!0,renderToggle:e=>{let{isOpen:t,onToggle:n}=e;return(0,a.createElement)(ir,{isOpen:t,onClick:n})},renderContent:e=>{let{onClose:t}=e;return(0,a.createElement)(x.PostSchedule,{onClose:t})}})))}function ir(e){let{isOpen:t,onClick:n}=e;const r=(0,x.usePostScheduleLabel)(),o=(0,x.usePostScheduleLabel)({full:!0});return(0,a.createElement)(E.Button,{className:"edit-post-post-schedule__toggle",variant:"tertiary",label:o,showTooltip:!0,"aria-expanded":t,"aria-label":(0,f.sprintf)((0,f.__)("Change date: %s"),r),onClick:n},r)}var sr=function(){return(0,a.createElement)(x.PostStickyCheck,null,(0,a.createElement)(E.PanelRow,null,(0,a.createElement)(x.PostSticky,null)))};var cr=function(){return(0,a.createElement)(x.PostAuthorCheck,null,(0,a.createElement)(E.PanelRow,{className:"edit-post-post-author"},(0,a.createElement)(x.PostAuthor,null)))};var dr=function(){return(0,a.createElement)(x.PostSlugCheck,null,(0,a.createElement)(E.PanelRow,{className:"edit-post-post-slug"},(0,a.createElement)(x.PostSlug,null)))};var ur=function(){return(0,a.createElement)(x.PostFormatCheck,null,(0,a.createElement)(E.PanelRow,{className:"edit-post-post-format"},(0,a.createElement)(x.PostFormat,null)))};var mr=function(){return(0,a.createElement)(x.PostPendingStatusCheck,null,(0,a.createElement)(E.PanelRow,null,(0,a.createElement)(x.PostPendingStatus,null)))};const{Fill:pr,Slot:gr}=(0,E.createSlotFill)("PluginPostStatusInfo"),hr=e=>{let{children:t,className:n}=e;return(0,a.createElement)(pr,null,(0,a.createElement)(E.PanelRow,{className:n},t))};hr.Slot=gr;var _r=hr;var Er=(0,a.createElement)(S.SVG,{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},(0,a.createElement)(S.Path,{fillRule:"evenodd",clipRule:"evenodd",d:"M18.5 5.5V8H20V5.5H22.5V4H20V1.5H18.5V4H16V5.5H18.5ZM13.9624 4H6C4.89543 4 4 4.89543 4 6V18C4 19.1046 4.89543 20 6 20H18C19.1046 20 20 19.1046 20 18V10.0391H18.5V18C18.5 18.2761 18.2761 18.5 18 18.5H10L10 10.4917L16.4589 10.5139L16.4641 9.01389L5.5 8.97618V6C5.5 5.72386 5.72386 5.5 6 5.5H13.9624V4ZM5.5 10.4762V18C5.5 18.2761 5.72386 18.5 6 18.5H8.5L8.5 10.4865L5.5 10.4762Z"}));const br=(0,f.__)("Custom Template");function fr(e){let{onClose:t}=e;const n=(0,u.useSelect)((e=>e(x.store).getEditorSettings().defaultBlockTemplate),[]),{__unstableCreateTemplate:r,__unstableSwitchToTemplateMode:o}=(0,u.useDispatch)(Rt),[l,s]=(0,a.useState)(""),[c,d]=(0,a.useState)(!1),m=()=>{s(""),t()};return(0,a.createElement)(E.Modal,{title:(0,f.__)("Create custom template"),onRequestClose:m,className:"edit-post-post-template__create-modal"},(0,a.createElement)("form",{className:"edit-post-post-template__create-form",onSubmit:async e=>{if(e.preventDefault(),c)return;d(!0);const t=null!=n?n:(0,i.serialize)([(0,i.createBlock)("core/group",{tagName:"header",layout:{inherit:!0}},[(0,i.createBlock)("core/site-title"),(0,i.createBlock)("core/site-tagline")]),(0,i.createBlock)("core/separator"),(0,i.createBlock)("core/group",{tagName:"main"},[(0,i.createBlock)("core/group",{layout:{inherit:!0}},[(0,i.createBlock)("core/post-title")]),(0,i.createBlock)("core/post-content",{layout:{inherit:!0}})])]);await r({slug:(0,C.cleanForSlug)(l||br),content:t,title:l||br}),d(!1),m(),o(!0)}},(0,a.createElement)(E.__experimentalVStack,{spacing:"3"},(0,a.createElement)(E.TextControl,{__nextHasNoMarginBottom:!0,label:(0,f.__)("Name"),value:l,onChange:s,placeholder:br,disabled:c,help:(0,f.__)('Describe the template, e.g. "Post with sidebar". A custom template can be manually applied to any post or page.')}),(0,a.createElement)(E.__experimentalHStack,{justify:"right"},(0,a.createElement)(E.Button,{variant:"tertiary",onClick:m},(0,f.__)("Cancel")),(0,a.createElement)(E.Button,{variant:"primary",type:"submit",isBusy:c,"aria-disabled":c},(0,f.__)("Create"))))))}function vr(e){var t,n;let{onClose:r}=e;const{isPostsPage:o,availableTemplates:l,fetchedTemplates:i,selectedTemplateSlug:s,canCreate:c,canEdit:d}=(0,u.useSelect)((e=>{const{canUser:t,getEntityRecord:n,getEntityRecords:r}=e(Be.store),o=e(x.store).getEditorSettings(),l=t("read","settings")?n("root","site"):void 0,a=e(x.store).getCurrentPostId()===(null==l?void 0:l.page_for_posts),i=t("create","templates");return{isPostsPage:a,availableTemplates:o.availableTemplates,fetchedTemplates:i?r("postType","wp_template",{post_type:e(x.store).getCurrentPostType(),per_page:-1}):void 0,selectedTemplateSlug:e(x.store).getEditedPostAttribute("template"),canCreate:i&&!a&&o.supportsTemplateMode,canEdit:i&&o.supportsTemplateMode&&!!e(Rt).getEditedPostTemplate()}}),[]),m=(0,a.useMemo)((()=>Object.entries({...l,...Object.fromEntries((null!=i?i:[]).map((e=>{let{slug:t,title:n}=e;return[t,n.rendered]})))}).map((e=>{let[t,n]=e;return{value:t,label:n}}))),[l,i]),p=null!==(t=m.find((e=>e.value===s)))&&void 0!==t?t:m.find((e=>!e.value)),{editPost:g}=(0,u.useDispatch)(x.store),{__unstableSwitchToTemplateMode:h}=(0,u.useDispatch)(Rt),[_,v]=(0,a.useState)(!1);return(0,a.createElement)("div",{className:"edit-post-post-template__form"},(0,a.createElement)(b.__experimentalInspectorPopoverHeader,{title:(0,f.__)("Template"),help:(0,f.__)("Templates define the way content is displayed when viewing your site."),actions:c?[{icon:Er,label:(0,f.__)("Add template"),onClick:()=>v(!0)}]:[],onClose:r}),o?(0,a.createElement)(E.Notice,{className:"edit-post-post-template__notice",status:"warning",isDismissible:!1},(0,f.__)("The posts page template cannot be changed.")):(0,a.createElement)(E.SelectControl,{__nextHasNoMarginBottom:!0,hideLabelFromVision:!0,label:(0,f.__)("Template"),value:null!==(n=null==p?void 0:p.value)&&void 0!==n?n:"",options:m,onChange:e=>g({template:e||""})}),d&&(0,a.createElement)("p",null,(0,a.createElement)(E.Button,{variant:"link",onClick:()=>h()},(0,f.__)("Edit template"))),_&&(0,a.createElement)(fr,{onClose:()=>v(!1)}))}function yr(){const[e,t]=(0,a.useState)(null),n=(0,a.useMemo)((()=>({anchor:e,placement:"bottom-end"})),[e]);return(0,u.useSelect)((e=>{var t;const n=e(x.store).getCurrentPostType(),r=e(Be.store).getPostType(n);if(null==r||!r.viewable)return!1;const o=e(x.store).getEditorSettings();if(!!o.availableTemplates&&Object.keys(o.availableTemplates).length>0)return!0;if(!o.supportsTemplateMode)return!1;return null!==(t=e(Be.store).canUser("create","templates"))&&void 0!==t&&t}),[])?(0,a.createElement)(E.PanelRow,{className:"edit-post-post-template",ref:t},(0,a.createElement)("span",null,(0,f.__)("Template")),(0,a.createElement)(E.Dropdown,{popoverProps:n,className:"edit-post-post-template__dropdown",contentClassName:"edit-post-post-template__dialog",focusOnMount:!0,renderToggle:e=>{let{isOpen:t,onToggle:n}=e;return(0,a.createElement)(wr,{isOpen:t,onClick:n})},renderContent:e=>{let{onClose:t}=e;return(0,a.createElement)(vr,{onClose:t})}})):null}function wr(e){let{isOpen:t,onClick:n}=e;const r=(0,u.useSelect)((e=>{const t=e(x.store).getEditedPostAttribute("template"),{supportsTemplateMode:n,availableTemplates:r}=e(x.store).getEditorSettings();if(!n&&r[t])return r[t];const o=e(Be.store).canUser("create","templates")&&e(Rt).getEditedPostTemplate();return(null==o?void 0:o.title)||(null==o?void 0:o.slug)||(null==r?void 0:r[t])}),[]);return(0,a.createElement)(E.Button,{className:"edit-post-post-template__toggle",variant:"tertiary","aria-expanded":t,"aria-label":r?(0,f.sprintf)((0,f.__)("Select template: %s"),r):(0,f.__)("Select template"),onClick:n},null!=r?r:(0,f.__)("Default template"))}function Sr(){const[e,t]=(0,a.useState)(null),n=(0,a.useMemo)((()=>({anchor:e,placement:"bottom-end"})),[e]);return(0,a.createElement)(x.PostURLCheck,null,(0,a.createElement)(E.PanelRow,{className:"edit-post-post-url",ref:t},(0,a.createElement)("span",null,(0,f.__)("URL")),(0,a.createElement)(E.Dropdown,{popoverProps:n,className:"edit-post-post-url__dropdown",contentClassName:"edit-post-post-url__dialog",focusOnMount:!0,renderToggle:e=>{let{isOpen:t,onToggle:n}=e;return(0,a.createElement)(kr,{isOpen:t,onClick:n})},renderContent:e=>{let{onClose:t}=e;return(0,a.createElement)(x.PostURL,{onClose:t})}})))}function kr(e){let{isOpen:t,onClick:n}=e;const r=(0,x.usePostURLLabel)();return(0,a.createElement)(E.Button,{className:"edit-post-post-url__toggle",variant:"tertiary","aria-expanded":t,"aria-label":(0,f.sprintf)((0,f.__)("Change URL: %s"),r),onClick:n},r)}const Pr="post-status";var Cr=(0,v.compose)([(0,u.withSelect)((e=>{const{isEditorPanelRemoved:t,isEditorPanelOpened:n}=e(Rt);return{isRemoved:t(Pr),isOpened:n(Pr)}})),(0,v.ifCondition)((e=>{let{isRemoved:t}=e;return!t})),(0,u.withDispatch)((e=>({onTogglePanel(){return e(Rt).toggleEditorPanelOpened(Pr)}})))])((function(e){let{isOpened:t,onTogglePanel:n}=e;return(0,a.createElement)(E.PanelBody,{className:"edit-post-post-status",title:(0,f.__)("Summary"),opened:t,onToggle:n},(0,a.createElement)(_r.Slot,null,(e=>(0,a.createElement)(a.Fragment,null,(0,a.createElement)(or,null),(0,a.createElement)(ar,null),(0,a.createElement)(yr,null),(0,a.createElement)(Sr,null),(0,a.createElement)(sr,null),(0,a.createElement)(mr,null),(0,a.createElement)(ur,null),(0,a.createElement)(dr,null),(0,a.createElement)(cr,null),e,(0,a.createElement)(lr,null)))))}));var Tr=function(){return(0,a.createElement)(x.PostLastRevisionCheck,null,(0,a.createElement)(E.PanelBody,{className:"edit-post-last-revision__panel"},(0,a.createElement)(x.PostLastRevision,null)))};var xr=(0,v.compose)((0,u.withSelect)(((e,t)=>{const n=(0,Gt.get)(t.taxonomy,["slug"]),r=n?`taxonomy-panel-${n}`:"";return{panelName:r,isEnabled:!!n&&e(Rt).isEditorPanelEnabled(r),isOpened:!!n&&e(Rt).isEditorPanelOpened(r)}})),(0,u.withDispatch)(((e,t)=>({onTogglePanel:()=>{e(Rt).toggleEditorPanelOpened(t.panelName)}}))))((function(e){let{isEnabled:t,taxonomy:n,isOpened:r,onTogglePanel:o,children:l}=e;if(!t)return null;const i=(0,Gt.get)(n,["labels","menu_name"]);return i?(0,a.createElement)(E.PanelBody,{title:i,opened:r,onToggle:o},l):null}));var Br=function(){return(0,a.createElement)(x.PostTaxonomiesCheck,null,(0,a.createElement)(x.PostTaxonomies,{taxonomyWrapper:(e,t)=>(0,a.createElement)(xr,{taxonomy:t},e)}))};const Mr="featured-image";const Nr=(0,u.withSelect)((e=>{const{getEditedPostAttribute:t}=e(x.store),{getPostType:n}=e(Be.store),{isEditorPanelEnabled:r,isEditorPanelOpened:o}=e(Rt);return{postType:n(t("type")),isEnabled:r(Mr),isOpened:o(Mr)}})),Ir=(0,u.withDispatch)((e=>{const{toggleEditorPanelOpened:t}=e(Rt);return{onTogglePanel:function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return t(Mr,...n)}}}));var Dr=(0,v.compose)(Nr,Ir)((function(e){let{isEnabled:t,isOpened:n,postType:r,onTogglePanel:o}=e;return t?(0,a.createElement)(x.PostFeaturedImageCheck,null,(0,a.createElement)(E.PanelBody,{title:(0,Gt.get)(r,["labels","featured_image"],(0,f.__)("Featured image")),opened:n,onToggle:o},(0,a.createElement)(x.PostFeaturedImage,null))):null}));const Ar="post-excerpt";var Lr=(0,v.compose)([(0,u.withSelect)((e=>({isEnabled:e(Rt).isEditorPanelEnabled(Ar),isOpened:e(Rt).isEditorPanelOpened(Ar)}))),(0,u.withDispatch)((e=>({onTogglePanel(){return e(Rt).toggleEditorPanelOpened(Ar)}})))])((function(e){let{isEnabled:t,isOpened:n,onTogglePanel:r}=e;return t?(0,a.createElement)(x.PostExcerptCheck,null,(0,a.createElement)(E.PanelBody,{title:(0,f.__)("Excerpt"),opened:n,onToggle:r},(0,a.createElement)(x.PostExcerpt,null))):null}));const Or="discussion-panel";var Vr=(0,v.compose)([(0,u.withSelect)((e=>({isEnabled:e(Rt).isEditorPanelEnabled(Or),isOpened:e(Rt).isEditorPanelOpened(Or)}))),(0,u.withDispatch)((e=>({onTogglePanel(){return e(Rt).toggleEditorPanelOpened(Or)}})))])((function(e){let{isEnabled:t,isOpened:n,onTogglePanel:r}=e;return t?(0,a.createElement)(x.PostTypeSupportCheck,{supportKeys:["comments","trackbacks"]},(0,a.createElement)(E.PanelBody,{title:(0,f.__)("Discussion"),opened:n,onToggle:r},(0,a.createElement)(x.PostTypeSupportCheck,{supportKeys:"comments"},(0,a.createElement)(E.PanelRow,null,(0,a.createElement)(x.PostComments,null))),(0,a.createElement)(x.PostTypeSupportCheck,{supportKeys:"trackbacks"},(0,a.createElement)(E.PanelRow,null,(0,a.createElement)(x.PostPingbacks,null))))):null}));const Fr="page-attributes";var Rr=function(){const{isEnabled:e,isOpened:t,postType:n}=(0,u.useSelect)((e=>{const{getEditedPostAttribute:t}=e(x.store),{isEditorPanelEnabled:n,isEditorPanelOpened:r}=e(Rt),{getPostType:o}=e(Be.store);return{isEnabled:n(Fr),isOpened:r(Fr),postType:o(t("type"))}}),[]),{toggleEditorPanelOpened:r}=(0,u.useDispatch)(Rt);return e&&n?(0,a.createElement)(x.PageAttributesCheck,null,(0,a.createElement)(E.PanelBody,{title:(0,Gt.get)(n,["labels","attributes"],(0,f.__)("Page attributes")),opened:t,onToggle:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return r(Fr,...t)}},(0,a.createElement)(x.PageAttributesParent,null),(0,a.createElement)(E.PanelRow,null,(0,a.createElement)(x.PageAttributesOrder,null)))):null};var Hr=function(e){let{location:t}=e;const n=(0,a.useRef)(null),r=(0,a.useRef)(null);(0,a.useEffect)((()=>(r.current=document.querySelector(".metabox-location-"+t),r.current&&n.current.appendChild(r.current),()=>{r.current&&document.querySelector("#metaboxes").appendChild(r.current)})),[t]);const o=(0,u.useSelect)((e=>e(Rt).isSavingMetaBoxes()),[]),l=V()("edit-post-meta-boxes-area",`is-${t}`,{"is-loading":o});return(0,a.createElement)("div",{className:l},o&&(0,a.createElement)(E.Spinner,null),(0,a.createElement)("div",{className:"edit-post-meta-boxes-area__container",ref:n}),(0,a.createElement)("div",{className:"edit-post-meta-boxes-area__clear"}))};class Gr extends a.Component{componentDidMount(){this.updateDOM()}componentDidUpdate(e){this.props.isVisible!==e.isVisible&&this.updateDOM()}updateDOM(){const{id:e,isVisible:t}=this.props,n=document.getElementById(e);n&&(t?n.classList.remove("is-hidden"):n.classList.add("is-hidden"))}render(){return null}}var Ur=(0,u.withSelect)(((e,t)=>{let{id:n}=t;return{isVisible:e(Rt).isEditorPanelEnabled(`meta-box-${n}`)}}))(Gr);function zr(e){let{location:t}=e;const n=(0,u.useRegistry)(),{metaBoxes:r,areMetaBoxesInitialized:o,isEditorReady:l}=(0,u.useSelect)((e=>{const{__unstableIsEditorReady:n}=e(x.store),{getMetaBoxesPerLocation:r,areMetaBoxesInitialized:o}=e(Rt);return{metaBoxes:r(t),areMetaBoxesInitialized:o(),isEditorReady:n()}}),[t]);return(0,a.useEffect)((()=>{l&&!o&&n.dispatch(Rt).initializeMetaBoxes()}),[l,o]),o?(0,a.createElement)(a.Fragment,null,(null!=r?r:[]).map((e=>{let{id:t}=e;return(0,a.createElement)(Ur,{key:t,id:t})})),(0,a.createElement)(Hr,{location:t})):null}window.wp.warning;const{Fill:Wr,Slot:$r}=(0,E.createSlotFill)("PluginDocumentSettingPanel"),qr=(0,v.compose)((0,P.withPluginContext)(((e,t)=>(void 0===t.name&&"undefined"!=typeof process&&process.env,{panelName:`${e.name}/${t.name}`}))),(0,u.withSelect)(((e,t)=>{let{panelName:n}=t;return{opened:e(Rt).isEditorPanelOpened(n),isEnabled:e(Rt).isEditorPanelEnabled(n)}})),(0,u.withDispatch)(((e,t)=>{let{panelName:n}=t;return{onToggle(){return e(Rt).toggleEditorPanelOpened(n)}}})))((e=>{let{isEnabled:t,panelName:n,opened:r,onToggle:o,className:l,title:i,icon:s,children:c}=e;return(0,a.createElement)(a.Fragment,null,(0,a.createElement)(hn,{label:i,panelName:n}),(0,a.createElement)(Wr,null,t&&(0,a.createElement)(E.PanelBody,{className:l,title:i,icon:s,opened:r,onToggle:o},c)))}));qr.Slot=$r;var jr=qr;function Zr(e){let{className:t,...n}=e;const{postTitle:r,shortcut:o,showIconLabels:l}=(0,u.useSelect)((e=>({postTitle:e(x.store).getEditedPostAttribute("title"),shortcut:e(qt.store).getShortcutRepresentation("core/edit-post/toggle-sidebar"),showIconLabels:e(Rt).isFeatureActive("showIconLabels")})),[]);return(0,a.createElement)(ge,_({panelClassName:t,className:"edit-post-sidebar",smallScreenTitle:r||(0,f.__)("(no title)"),scope:"core/edit-post",toggleShortcut:o,showIconLabels:l},n))}var Kr=(0,a.createElement)(S.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,a.createElement)(S.Path,{d:"M18 5.5H6a.5.5 0 00-.5.5v3h13V6a.5.5 0 00-.5-.5zm.5 5H10v8h8a.5.5 0 00.5-.5v-7.5zm-10 0h-3V18a.5.5 0 00.5.5h2.5v-8zM6 4h12a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2z"}));var Yr=function(){const e=(0,u.useSelect)((e=>{const{getEditedPostTemplate:t}=e(Rt);return t()}),[]);return e?(0,a.createElement)(E.PanelBody,null,(0,a.createElement)(E.Flex,{align:"flex-start",gap:"3"},(0,a.createElement)(E.FlexItem,null,(0,a.createElement)(ye,{icon:Kr})),(0,a.createElement)(E.FlexBlock,null,(0,a.createElement)("h2",{className:"edit-post-template-summary__title"},(null==e?void 0:e.title)||(null==e?void 0:e.slug)),(0,a.createElement)("p",null,null==e?void 0:e.description)))):null};const Xr=a.Platform.select({web:!0,native:!1});var Qr=()=>{const{sidebarName:e,keyboardShortcut:t,isTemplateMode:n}=(0,u.useSelect)((e=>{let t=e(te).getActiveComplementaryArea(Rt.name);["edit-post/document","edit-post/block"].includes(t)||(e(b.store).getBlockSelectionStart()&&(t="edit-post/block"),t="edit-post/document");return{sidebarName:t,keyboardShortcut:e(qt.store).getShortcutRepresentation("core/edit-post/toggle-sidebar"),isTemplateMode:e(Rt).isEditingTemplate()}}),[]);return(0,a.createElement)(Zr,{identifier:e,header:(0,a.createElement)(nr,{sidebarName:e}),closeLabel:(0,f.__)("Close settings"),headerClassName:"edit-post-sidebar__panel-tabs",title:(0,f.__)("Settings"),toggleShortcut:t,icon:(0,f.isRTL)()?er:tr,isActiveByDefault:Xr},!n&&"edit-post/document"===e&&(0,a.createElement)(a.Fragment,null,(0,a.createElement)(Cr,null),(0,a.createElement)(jr.Slot,null),(0,a.createElement)(Tr,null),(0,a.createElement)(Br,null),(0,a.createElement)(Dr,null),(0,a.createElement)(Lr,null),(0,a.createElement)(Vr,null),(0,a.createElement)(Rr,null),(0,a.createElement)(zr,{location:"side"})),n&&"edit-post/document"===e&&(0,a.createElement)(Yr,null),"edit-post/block"===e&&(0,a.createElement)(b.BlockInspector,null))};function Jr(e){let{nonAnimatedSrc:t,animatedSrc:n}=e;return(0,a.createElement)("picture",{className:"edit-post-welcome-guide__image"},(0,a.createElement)("source",{srcSet:t,media:"(prefers-reduced-motion: reduce)"}),(0,a.createElement)("img",{src:n,width:"312",height:"240",alt:""}))}function eo(){const{toggleFeature:e}=(0,u.useDispatch)(Rt);return(0,a.createElement)(E.Guide,{className:"edit-post-welcome-guide",contentLabel:(0,f.__)("Welcome to the block editor"),finishButtonText:(0,f.__)("Get started"),onFinish:()=>e("welcomeGuide"),pages:[{image:(0,a.createElement)(Jr,{nonAnimatedSrc:"https://s.w.org/images/block-editor/welcome-canvas.svg",animatedSrc:"https://s.w.org/images/block-editor/welcome-canvas.gif"}),content:(0,a.createElement)(a.Fragment,null,(0,a.createElement)("h1",{className:"edit-post-welcome-guide__heading"},(0,f.__)("Welcome to the block editor")),(0,a.createElement)("p",{className:"edit-post-welcome-guide__text"},(0,f.__)("In the WordPress editor, each paragraph, image, or video is presented as a distinct “block” of content.")))},{image:(0,a.createElement)(Jr,{nonAnimatedSrc:"https://s.w.org/images/block-editor/welcome-editor.svg",animatedSrc:"https://s.w.org/images/block-editor/welcome-editor.gif"}),content:(0,a.createElement)(a.Fragment,null,(0,a.createElement)("h1",{className:"edit-post-welcome-guide__heading"},(0,f.__)("Make each block your own")),(0,a.createElement)("p",{className:"edit-post-welcome-guide__text"},(0,f.__)("Each block comes with its own set of controls for changing things like color, width, and alignment. These will show and hide automatically when you have a block selected.")))},{image:(0,a.createElement)(Jr,{nonAnimatedSrc:"https://s.w.org/images/block-editor/welcome-library.svg",animatedSrc:"https://s.w.org/images/block-editor/welcome-library.gif"}),content:(0,a.createElement)(a.Fragment,null,(0,a.createElement)("h1",{className:"edit-post-welcome-guide__heading"},(0,f.__)("Get to know the block library")),(0,a.createElement)("p",{className:"edit-post-welcome-guide__text"},(0,a.createInterpolateElement)((0,f.__)("All of the blocks available to you live in the block library. You’ll find it wherever you see the <InserterIconImage /> icon."),{InserterIconImage:(0,a.createElement)("img",{alt:(0,f.__)("inserter"),src:"data:image/svg+xml,%3Csvg width='18' height='18' viewBox='0 0 18 18' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='18' height='18' rx='2' fill='%231E1E1E'/%3E%3Cpath d='M9.22727 4V14M4 8.77273H14' stroke='white' stroke-width='1.5'/%3E%3C/svg%3E%0A"})})))},{image:(0,a.createElement)(Jr,{nonAnimatedSrc:"https://s.w.org/images/block-editor/welcome-documentation.svg",animatedSrc:"https://s.w.org/images/block-editor/welcome-documentation.gif"}),content:(0,a.createElement)(a.Fragment,null,(0,a.createElement)("h1",{className:"edit-post-welcome-guide__heading"},(0,f.__)("Learn how to use the block editor")),(0,a.createElement)("p",{className:"edit-post-welcome-guide__text"},(0,f.__)("New to the block editor? Want to learn more about using it? "),(0,a.createElement)(E.ExternalLink,{href:(0,f.__)("https://wordpress.org/support/article/wordpress-editor/")},(0,f.__)("Here's a detailed guide."))))}]})}function to(){const{toggleFeature:e}=(0,u.useDispatch)(Rt);return(0,a.createElement)(E.Guide,{className:"edit-template-welcome-guide",contentLabel:(0,f.__)("Welcome to the template editor"),finishButtonText:(0,f.__)("Get started"),onFinish:()=>e("welcomeGuideTemplate"),pages:[{image:(0,a.createElement)(Jr,{nonAnimatedSrc:"https://s.w.org/images/block-editor/welcome-template-editor.svg",animatedSrc:"https://s.w.org/images/block-editor/welcome-template-editor.gif"}),content:(0,a.createElement)(a.Fragment,null,(0,a.createElement)("h1",{className:"edit-post-welcome-guide__heading"},(0,f.__)("Welcome to the template editor")),(0,a.createElement)("p",{className:"edit-post-welcome-guide__text"},(0,f.__)("Templates help define the layout of the site. You can customize all aspects of your posts and pages using blocks and patterns in this editor.")))}]})}function no(){const{isActive:e,isTemplateMode:t}=(0,u.useSelect)((e=>{const{isFeatureActive:t,isEditingTemplate:n}=e(Rt),r=n();return{isActive:t(r?"welcomeGuideTemplate":"welcomeGuide"),isTemplateMode:r}}),[]);return e?t?(0,a.createElement)(to,null):(0,a.createElement)(eo,null):null}const{Fill:ro,Slot:oo}=(0,E.createSlotFill)("PluginPostPublishPanel"),lo=(0,v.compose)((0,P.withPluginContext)(((e,t)=>({icon:t.icon||e.icon}))))((e=>{let{children:t,className:n,title:r,initialOpen:o=!1,icon:l}=e;return(0,a.createElement)(ro,null,(0,a.createElement)(E.PanelBody,{className:n,initialOpen:o||!r,title:r,icon:l},t))}));lo.Slot=oo;var ao=lo;const{Fill:io,Slot:so}=(0,E.createSlotFill)("PluginPrePublishPanel"),co=(0,v.compose)((0,P.withPluginContext)(((e,t)=>({icon:t.icon||e.icon}))))((e=>{let{children:t,className:n,title:r,initialOpen:o=!1,icon:l}=e;return(0,a.createElement)(io,null,(0,a.createElement)(E.PanelBody,{className:n,initialOpen:o||!r,title:r,icon:l},t))}));co.Slot=so;var uo=co;const{Fill:mo,Slot:po}=(0,E.createSlotFill)("ActionsPanel");function go(e){let{setEntitiesSavedStatesCallback:t,closeEntitiesSavedStates:n,isEntitiesSavedStatesOpen:r}=e;const{closePublishSidebar:o,togglePublishSidebar:l}=(0,u.useDispatch)(Rt),{publishSidebarOpened:i,hasActiveMetaboxes:s,isSavingMetaBoxes:c,hasNonPostEntityChanges:d}=(0,u.useSelect)((e=>({publishSidebarOpened:e(Rt).isPublishSidebarOpened(),hasActiveMetaboxes:e(Rt).hasMetaBoxes(),isSavingMetaBoxes:e(Rt).isSavingMetaBoxes(),hasNonPostEntityChanges:e(x.store).hasNonPostEntityChanges()})),[]),m=(0,a.useCallback)((()=>t(!0)),[]);let p;return p=i?(0,a.createElement)(x.PostPublishPanel,{onClose:o,forceIsDirty:s,forceIsSaving:c,PrePublishExtension:uo.Slot,PostPublishExtension:ao.Slot}):d?(0,a.createElement)("div",{className:"edit-post-layout__toggle-entities-saved-states-panel"},(0,a.createElement)(E.Button,{variant:"secondary",className:"edit-post-layout__toggle-entities-saved-states-panel-button",onClick:m,"aria-expanded":!1},(0,f.__)("Open save panel"))):(0,a.createElement)("div",{className:"edit-post-layout__toggle-publish-panel"},(0,a.createElement)(E.Button,{variant:"secondary",className:"edit-post-layout__toggle-publish-panel-button",onClick:l,"aria-expanded":!1},(0,f.__)("Open publish panel"))),(0,a.createElement)(a.Fragment,null,r&&(0,a.createElement)(x.EntitiesSavedStates,{close:n}),(0,a.createElement)(po,{bubblesVirtually:!0}),!r&&p)}function ho(){const{blockPatternsWithPostContentBlockType:e,postType:t}=(0,u.useSelect)((e=>{const{getPatternsByBlockTypes:t}=e(b.store),{getCurrentPostType:n}=e(x.store);return{blockPatternsWithPostContentBlockType:t("core/post-content"),postType:n()}}),[]);return(0,a.useMemo)((()=>e.filter((e=>"page"===t&&!e.postTypes||Array.isArray(e.postTypes)&&e.postTypes.includes(t)))),[t,e])}function _o(e){let{onChoosePattern:t}=e;const n=ho(),r=(0,v.useAsyncList)(n),{resetEditorBlocks:o}=(0,u.useDispatch)(x.store);return(0,a.createElement)(b.__experimentalBlockPatternsList,{blockPatterns:n,shownPatterns:r,onClickPattern:(e,n)=>{o(n),t()}})}const Eo="INITIAL",bo="PATTERN",fo="CLOSED";function vo(){const[e,t]=(0,a.useState)(Eo),n=ho().length>0,r=(0,u.useSelect)((t=>{if(!n||e!==Eo)return!1;const{getEditedPostContent:r,isEditedPostSaveable:o}=t(x.store),{isEditingTemplate:l,isFeatureActive:a}=t(Rt);return!o()&&""===r()&&!l()&&!a("welcomeGuide")}),[e,n]);return(0,a.useEffect)((()=>{r&&t(bo)}),[r]),e===Eo||e===fo?null:(0,a.createElement)(E.Modal,{className:"edit-post-start-page-options__modal",title:(0,f.__)("Choose a pattern"),onRequestClose:()=>{t(fo)}},(0,a.createElement)("div",{className:"edit-post-start-page-options__modal-content"},e===bo&&(0,a.createElement)(_o,{onChoosePattern:()=>{t(fo)}})))}const yo={header:(0,f.__)("Editor top bar"),body:(0,f.__)("Editor content"),sidebar:(0,f.__)("Editor settings"),actions:(0,f.__)("Editor publish"),footer:(0,f.__)("Editor footer")};var wo=function(e){let{styles:t}=e;const n=(0,v.useViewportMatch)("medium","<"),r=(0,v.useViewportMatch)("huge",">="),o=(0,v.useViewportMatch)("large"),{openGeneralSidebar:l,closeGeneralSidebar:i,setIsInserterOpened:s}=(0,u.useDispatch)(Rt),{createErrorNotice:c}=(0,u.useDispatch)(T.store),{mode:d,isFullscreenActive:m,isRichEditingEnabled:p,sidebarIsOpened:g,hasActiveMetaboxes:h,hasFixedToolbar:_,previousShortcut:y,nextShortcut:w,hasBlockSelected:S,isInserterOpened:k,isListViewOpened:C,showIconLabels:B,isDistractionFree:M,showBlockBreadcrumbs:N,isTemplateMode:I,documentLabel:D}=(0,u.useSelect)((e=>{const{getEditorSettings:t,getPostTypeLabel:n}=e(x.store),r=t(),o=n();return{isTemplateMode:e(Rt).isEditingTemplate(),hasFixedToolbar:e(Rt).isFeatureActive("fixedToolbar"),sidebarIsOpened:!(!e(te).getActiveComplementaryArea(Rt.name)&&!e(Rt).isPublishSidebarOpened()),isFullscreenActive:e(Rt).isFeatureActive("fullscreenMode"),isInserterOpened:e(Rt).isInserterOpened(),isListViewOpened:e(Rt).isListViewOpened(),mode:e(Rt).getEditorMode(),isRichEditingEnabled:r.richEditingEnabled,hasActiveMetaboxes:e(Rt).hasMetaBoxes(),previousShortcut:e(qt.store).getAllShortcutKeyCombinations("core/edit-post/previous-region"),nextShortcut:e(qt.store).getAllShortcutKeyCombinations("core/edit-post/next-region"),showIconLabels:e(Rt).isFeatureActive("showIconLabels"),isDistractionFree:e(Rt).isFeatureActive("distractionFree"),showBlockBreadcrumbs:e(Rt).isFeatureActive("showBlockBreadcrumbs"),documentLabel:o||(0,f._x)("Document","noun")}}),[]);(0,a.useEffect)((()=>{g&&!r&&s(!1)}),[g,r]),(0,a.useEffect)((()=>{k&&!r&&i()}),[k,r]);const[A,L]=(0,a.useState)(!1),O=(0,a.useCallback)((e=>{"function"==typeof A&&A(e),L(!1)}),[A]),F=V()("edit-post-layout","is-mode-"+d,{"is-sidebar-opened":g,"has-fixed-toolbar":_,"has-metaboxes":h,"show-icon-labels":B,"is-distraction-free":M&&o,"is-entity-save-view-open":!!A}),R=C?(0,f.__)("Document Overview"):(0,f.__)("Block Library");return(0,a.createElement)(a.Fragment,null,(0,a.createElement)(he,{isActive:m}),(0,a.createElement)(kn,null),(0,a.createElement)(x.UnsavedChangesWarning,null),(0,a.createElement)(x.AutosaveMonitor,null),(0,a.createElement)(x.LocalAutosaveMonitor,null),(0,a.createElement)(Qt,null),(0,a.createElement)(x.EditorKeyboardShortcutsRegister,null),(0,a.createElement)(Qr,null),(0,a.createElement)(Ee,{isDistractionFree:M&&o,className:F,labels:{...yo,secondarySidebar:R},header:(0,a.createElement)(Zn,{setEntitiesSavedStatesCallback:L}),editorNotices:(0,a.createElement)(x.EditorNotices,null),secondarySidebar:"visual"===d&&k?(0,a.createElement)(Yn,null):"visual"===d&&C?(0,a.createElement)(Jn,null):null,sidebar:(!n||g)&&(0,a.createElement)(a.Fragment,null,!n&&!g&&(0,a.createElement)("div",{className:"edit-post-layout__toggle-sidebar-panel"},(0,a.createElement)(E.Button,{variant:"secondary",className:"edit-post-layout__toggle-sidebar-panel-button",onClick:()=>l(S?"edit-post/block":"edit-post/document"),"aria-expanded":!1},S?(0,f.__)("Open block settings"):(0,f.__)("Open document settings"))),(0,a.createElement)(ge.Slot,{scope:"core/edit-post"})),notices:(0,a.createElement)(x.EditorSnackbars,null),content:(0,a.createElement)(a.Fragment,null,!M&&(0,a.createElement)(x.EditorNotices,null),("text"===d||!p)&&(0,a.createElement)(jt,null),p&&"visual"===d&&(0,a.createElement)(Xt,{styles:t}),!M&&!I&&(0,a.createElement)("div",{className:"edit-post-layout__metaboxes"},(0,a.createElement)(zr,{location:"normal"}),(0,a.createElement)(zr,{location:"advanced"})),n&&g&&(0,a.createElement)(E.ScrollLock,null)),footer:!M&&!n&&N&&p&&"visual"===d&&(0,a.createElement)("div",{className:"edit-post-layout__footer"},(0,a.createElement)(b.BlockBreadcrumb,{rootLabelText:D})),actions:(0,a.createElement)(go,{closeEntitiesSavedStates:O,isEntitiesSavedStatesOpen:A,setEntitiesSavedStatesCallback:L}),shortcuts:{previous:y,next:w}}),(0,a.createElement)(wn,null),(0,a.createElement)(sn,null),(0,a.createElement)(no,null),(0,a.createElement)(vo,null),(0,a.createElement)(E.Popover.Slot,null),(0,a.createElement)(P.PluginArea,{onError:function(e){c((0,f.sprintf)((0,f.__)('The "%s" plugin has encountered an error and cannot be rendered.'),e))}}))};function So(e){let{postId:t}=e;return(e=>{const{hasBlockSelection:t,isEditorSidebarOpened:n}=(0,u.useSelect)((e=>({hasBlockSelection:!!e(b.store).getBlockSelectionStart(),isEditorSidebarOpened:e(Ft).isEditorSidebarOpened()})),[e]),{openGeneralSidebar:r}=(0,u.useDispatch)(Ft);(0,a.useEffect)((()=>{n&&r(t?"edit-post/block":"edit-post/document")}),[t,n])})(t),(e=>{const{newPermalink:t}=(0,u.useSelect)((e=>({newPermalink:e(x.store).getCurrentPost().link})),[e]),n=(0,a.useRef)();(0,a.useEffect)((()=>{n.current=document.querySelector("#wp-admin-bar-preview a")||document.querySelector("#wp-admin-bar-view a")}),[e]),(0,a.useEffect)((()=>{t&&n.current&&n.current.setAttribute("href",t)}),[t])})(t),null}var ko=window.wp.privateApis;const{lock:Po,unlock:Co}=(0,ko.__dangerousOptInToUnstableAPIsOnlyForCoreModules)("I know using unstable features means my plugin or theme will inevitably break on the next WordPress release.","@wordpress/edit-post"),{ExperimentalEditorProvider:To}=Co(x.privateApis);var xo=function(e){let{postId:t,postType:n,settings:r,initialEdits:o,...l}=e;const{hasFixedToolbar:s,focusMode:c,isDistractionFree:d,hasInlineToolbar:m,hasThemeStyles:g,post:h,preferredStyleVariations:b,hiddenBlockTypes:f,blockTypes:v,keepCaretInsideBlock:y,isTemplateMode:w,template:S}=(0,u.useSelect)((e=>{var r,o;const{isFeatureActive:l,__experimentalGetPreviewDeviceType:a,isEditingTemplate:s,getEditedPostTemplate:c,getHiddenBlockTypes:d}=e(Rt),{getEntityRecord:u,getPostType:m,getEntityRecords:g,canUser:h}=e(Be.store),{getEditorSettings:_}=e(x.store),{getBlockTypes:E}=e(i.store);let b;if(["wp_template","wp_template_part"].includes(n)){const e=g("postType",n,{wp_id:t});b=null==e?void 0:e[0]}else b=u("postType",n,t);const f=_().supportsTemplateMode,v=null!==(r=null===(o=m(n))||void 0===o?void 0:o.viewable)&&void 0!==r&&r,y=h("create","templates");return{hasFixedToolbar:l("fixedToolbar")||"Desktop"!==a(),focusMode:l("focusMode"),isDistractionFree:l("distractionFree"),hasInlineToolbar:l("inlineToolbar"),hasThemeStyles:l("themeStyles"),preferredStyleVariations:e(p.store).get("core/edit-post","preferredStyleVariations"),hiddenBlockTypes:d(),blockTypes:E(),keepCaretInsideBlock:l("keepCaretInsideBlock"),isTemplateMode:s(),template:f&&v&&y?c():null,post:b}}),[n,t]),{updatePreferredStyleVariations:k,setIsInserterOpened:P}=(0,u.useDispatch)(Rt),C=(0,a.useMemo)((()=>{const e={...r,__experimentalPreferredStyleVariations:{value:b,onChange:k},hasFixedToolbar:s,focusMode:c,isDistractionFree:d,hasInlineToolbar:m,__experimentalSetIsInserterOpened:P,keepCaretInsideBlock:y,defaultAllowedBlockTypes:r.allowedBlockTypes};if(f.length>0){const t=!0===r.allowedBlockTypes?v.map((e=>{let{name:t}=e;return t})):r.allowedBlockTypes||[];e.allowedBlockTypes=t.filter((e=>!f.includes(e)))}return e}),[r,s,c,d,f,v,b,P,k,y]),T=(0,a.useMemo)((()=>{var e;const t=[],n=[];null===(e=r.styles)||void 0===e||e.forEach((e=>{e.__unstableType&&"theme"!==e.__unstableType?n.push(e):t.push(e)}));const o=[...r.defaultEditorStyles,...n];return g&&t.length?r.styles:o}),[r,g]);return h?(0,a.createElement)(qt.ShortcutProvider,null,(0,a.createElement)(E.SlotFillProvider,null,(0,a.createElement)(To,_({settings:C,post:h,initialEdits:o,useSubRegistry:!1,__unstableTemplate:w?S:void 0},l),(0,a.createElement)(x.ErrorBoundary,null,(0,a.createElement)(So,{postId:t}),(0,a.createElement)(wo,{styles:T})),(0,a.createElement)(x.PostLockedModal,null)))):null};var Bo=e=>{let{allowedBlocks:t,icon:n,label:r,onClick:o,small:l,role:i}=e;return(0,a.createElement)(b.BlockSettingsMenuControls,null,(e=>{let{selectedBlocks:s,onClose:c}=e;return((e,t)=>{return!Array.isArray(t)||(n=t,0===e.filter((e=>!n.includes(e))).length);var n})(s,t)?(0,a.createElement)(E.MenuItem,{onClick:(0,v.compose)(o,c),icon:n,label:l?r:void 0,role:i},!l&&r):null}))},Mo=(0,v.compose)((0,P.withPluginContext)(((e,t)=>{var n;return{as:null!==(n=t.as)&&void 0!==n?n:E.MenuItem,icon:t.icon||e.icon,name:"core/edit-post/plugin-more-menu"}})))(ie);function No(e){return(0,a.createElement)(ce,_({__unstableExplicitMenuItem:!0,scope:"core/edit-post"},e))}function Io(e,t,n,r,o){const l=document.getElementById(e),c=(0,a.createRoot)(l);(0,u.dispatch)(p.store).setDefaults("core/edit-post",{editorMode:"visual",fixedToolbar:!1,fullscreenMode:!0,hiddenBlockTypes:[],inactivePanels:[],isPublishSidebarEnabled:!0,openPanels:["post-status"],preferredStyleVariations:{},showBlockBreadcrumbs:!0,showIconLabels:!1,showListViewByDefault:!1,themeStyles:!0,welcomeGuide:!0,welcomeGuideTemplate:!0}),(0,u.dispatch)(i.store).__experimentalReapplyBlockTypeFilters(),(0,u.select)(Rt).isFeatureActive("showListViewByDefault")&&(0,u.dispatch)(Rt).setIsListViewOpened(!0),(0,s.registerCoreBlocks)(),(0,g.registerLegacyWidgetBlock)({inserter:!1}),(0,g.registerWidgetGroupBlock)({inserter:!1}),(0,m.addFilter)("blockEditor.__unstableCanInsertBlockType","removeTemplatePartsFromInserter",((e,t)=>!(!(0,u.select)(Rt).isEditingTemplate()&&"core/template-part"===t.name)&&e));"Standards"!==("CSS1Compat"===document.compatMode?"Standards":"Quirks")&&console.warn("Your browser is using Quirks Mode. \nThis can cause rendering issues such as blocks overlaying meta boxes in the editor. Quirks Mode can be triggered by PHP errors or HTML code appearing before the opening <!DOCTYPE html>. Try checking the raw page source or your site's PHP error log and resolving errors there, removing any HTML before the doctype, or disabling plugins.");return-1!==window.navigator.userAgent.indexOf("iPhone")&&window.addEventListener("scroll",(e=>{const t=document.getElementsByClassName("interface-interface-skeleton__body")[0];e.target===document&&(window.scrollY>100&&(t.scrollTop=t.scrollTop+window.scrollY),document.getElementsByClassName("is-mode-visual")[0]&&window.scrollTo(0,0))})),window.addEventListener("dragover",(e=>e.preventDefault()),!1),window.addEventListener("drop",(e=>e.preventDefault()),!1),c.render((0,a.createElement)(xo,{settings:r,postId:n,postType:t,initialEdits:o})),c}function Do(){d()("wp.editPost.reinitializeEditor",{since:"6.2",version:"6.3"})}}(),(window.wp=window.wp||{}).editPost=r}(); priority-queue.min.js 0000666 00000006562 15123355174 0010712 0 ustar 00 /*! This file is auto-generated */
!function(){var e={3159:function(e,t,n){var o,r,i;r=[],void 0===(i="function"==typeof(o=function(){"use strict";var e,t,o,r,i="undefined"!=typeof window?window:null!=typeof n.g?n.g:this||{},u=i.cancelRequestAnimationFrame&&i.requestAnimationFrame||setTimeout,a=i.cancelRequestAnimationFrame||clearTimeout,c=[],l=0,s=!1,d=7,f=35,m=125,b=0,p=0,v=0,w={get didTimeout(){return!1},timeRemaining:function(){var e=d-(Date.now()-p);return e<0?0:e}},y=g((function(){d=22,m=66,f=0}));function g(e){var t,n,o=99,r=function(){var i=Date.now()-n;i<o?t=setTimeout(r,o-i):(t=null,e())};return function(){n=Date.now(),t||(t=setTimeout(r,o))}}function h(){s&&(r&&a(r),o&&clearTimeout(o),s=!1)}function k(){125!=m&&(d=7,m=125,f=35,s&&(h(),C())),y()}function T(){r=null,o=setTimeout(D,0)}function q(){o=null,u(T)}function C(){s||(t=m-(Date.now()-p),e=Date.now(),s=!0,f&&t<f&&(t=f),t>9?o=setTimeout(q,t):(t=0,q()))}function D(){var n,r,i,u=d>9?9:1;if(p=Date.now(),s=!1,o=null,l>2||p-t-50<e)for(r=0,i=c.length;r<i&&w.timeRemaining()>u;r++)n=c.shift(),v++,n&&n(w);c.length?C():l=0}function I(e){return b++,c.push(e),C(),b}function O(e){var t=e-1-v;c[t]&&(c[t]=null)}if(i.requestIdleCallback&&i.cancelIdleCallback)try{i.requestIdleCallback((function(){}),{timeout:0})}catch(e){!function(e){var t,n;if(i.requestIdleCallback=function(t,n){return n&&"number"==typeof n.timeout?e(t,n.timeout):e(t)},i.IdleCallbackDeadline&&(t=IdleCallbackDeadline.prototype)){if(!(n=Object.getOwnPropertyDescriptor(t,"timeRemaining"))||!n.configurable||!n.get)return;Object.defineProperty(t,"timeRemaining",{value:function(){return n.get.call(this)},enumerable:!0,configurable:!0})}}(i.requestIdleCallback)}else i.requestIdleCallback=I,i.cancelIdleCallback=O,i.document&&document.addEventListener&&(i.addEventListener("scroll",k,!0),i.addEventListener("resize",k),document.addEventListener("focus",k,!0),document.addEventListener("mouseover",k,!0),["click","keypress","touchstart","mousedown"].forEach((function(e){document.addEventListener(e,k,{capture:!0,passive:!0})})),i.MutationObserver&&new MutationObserver(k).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0}));return{request:I,cancel:O}})?o.apply(t,r):o)||(e.exports=i)}},t={};function n(o){var r=t[o];if(void 0!==r)return r.exports;var i=t[o]={exports:{}};return e[o](i,i.exports,n),i.exports}n.d=function(e,t){for(var o in t)n.o(t,o)&&!n.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),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 o={};!function(){"use strict";n.r(o),n.d(o,{createQueue:function(){return t}});n(3159);var e="undefined"==typeof window?e=>{setTimeout((()=>e(Date.now())),0)}:window.requestIdleCallback;const t=()=>{const t=new Map;let n=!1;const o=r=>{for(const[e,n]of t)if(t.delete(e),n(),"number"==typeof r||r.timeRemaining()<=0)break;0!==t.size?e(o):n=!1};return{add:(r,i)=>{t.set(r,i),n||(n=!0,e(o))},flush:e=>{const n=t.get(e);return void 0!==n&&(t.delete(e),n(),!0)},cancel:e=>t.delete(e),reset:()=>{t.clear(),n=!1}}}}(),(window.wp=window.wp||{}).priorityQueue=o}(); i18n.min.js 0000666 00000023766 15123355174 0006473 0 ustar 00 /*! This file is auto-generated */
!function(){var t={9756:function(t){t.exports=function(t,n){var e,r,i=0;function o(){var o,a,s=e,u=arguments.length;t:for(;s;){if(s.args.length===arguments.length){for(a=0;a<u;a++)if(s.args[a]!==arguments[a]){s=s.next;continue t}return s!==e&&(s===r&&(r=s.prev),s.prev.next=s.next,s.next&&(s.next.prev=s.prev),s.next=e,s.prev=null,e.prev=s,e=s),s.val}s=s.next}for(o=new Array(u),a=0;a<u;a++)o[a]=arguments[a];return s={args:o,val:t.apply(null,o)},e?(e.prev=s,s.next=e):r=s,i===n.maxSize?(r=r.prev).next=null:i++,e=s,s.val}return n=n||{},o.clear=function(){e=null,r=null,i=0},o}},124:function(t,n,e){var r;!function(){"use strict";var i={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function o(t){return s(l(t),arguments)}function a(t,n){return o.apply(null,[t].concat(n||[]))}function s(t,n){var e,r,a,s,u,l,c,p,f,d=1,h=t.length,g="";for(r=0;r<h;r++)if("string"==typeof t[r])g+=t[r];else if("object"==typeof t[r]){if((s=t[r]).keys)for(e=n[d],a=0;a<s.keys.length;a++){if(null==e)throw new Error(o('[sprintf] Cannot access property "%s" of undefined value "%s"',s.keys[a],s.keys[a-1]));e=e[s.keys[a]]}else e=s.param_no?n[s.param_no]:n[d++];if(i.not_type.test(s.type)&&i.not_primitive.test(s.type)&&e instanceof Function&&(e=e()),i.numeric_arg.test(s.type)&&"number"!=typeof e&&isNaN(e))throw new TypeError(o("[sprintf] expecting number but found %T",e));switch(i.number.test(s.type)&&(p=e>=0),s.type){case"b":e=parseInt(e,10).toString(2);break;case"c":e=String.fromCharCode(parseInt(e,10));break;case"d":case"i":e=parseInt(e,10);break;case"j":e=JSON.stringify(e,null,s.width?parseInt(s.width):0);break;case"e":e=s.precision?parseFloat(e).toExponential(s.precision):parseFloat(e).toExponential();break;case"f":e=s.precision?parseFloat(e).toFixed(s.precision):parseFloat(e);break;case"g":e=s.precision?String(Number(e.toPrecision(s.precision))):parseFloat(e);break;case"o":e=(parseInt(e,10)>>>0).toString(8);break;case"s":e=String(e),e=s.precision?e.substring(0,s.precision):e;break;case"t":e=String(!!e),e=s.precision?e.substring(0,s.precision):e;break;case"T":e=Object.prototype.toString.call(e).slice(8,-1).toLowerCase(),e=s.precision?e.substring(0,s.precision):e;break;case"u":e=parseInt(e,10)>>>0;break;case"v":e=e.valueOf(),e=s.precision?e.substring(0,s.precision):e;break;case"x":e=(parseInt(e,10)>>>0).toString(16);break;case"X":e=(parseInt(e,10)>>>0).toString(16).toUpperCase()}i.json.test(s.type)?g+=e:(!i.number.test(s.type)||p&&!s.sign?f="":(f=p?"+":"-",e=e.toString().replace(i.sign,"")),l=s.pad_char?"0"===s.pad_char?"0":s.pad_char.charAt(1):" ",c=s.width-(f+e).length,u=s.width&&c>0?l.repeat(c):"",g+=s.align?f+e+u:"0"===l?f+u+e:u+f+e)}return g}var u=Object.create(null);function l(t){if(u[t])return u[t];for(var n,e=t,r=[],o=0;e;){if(null!==(n=i.text.exec(e)))r.push(n[0]);else if(null!==(n=i.modulo.exec(e)))r.push("%");else{if(null===(n=i.placeholder.exec(e)))throw new SyntaxError("[sprintf] unexpected placeholder");if(n[2]){o|=1;var a=[],s=n[2],l=[];if(null===(l=i.key.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(a.push(l[1]);""!==(s=s.substring(l[0].length));)if(null!==(l=i.key_access.exec(s)))a.push(l[1]);else{if(null===(l=i.index_access.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");a.push(l[1])}n[2]=a}else o|=2;if(3===o)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");r.push({placeholder:n[0],param_no:n[1],keys:n[2],sign:n[3],pad_char:n[4],align:n[5],width:n[6],precision:n[7],type:n[8]})}e=e.substring(n[0].length)}return u[t]=r}n.sprintf=o,n.vsprintf=a,"undefined"!=typeof window&&(window.sprintf=o,window.vsprintf=a,void 0===(r=function(){return{sprintf:o,vsprintf:a}}.call(n,e,n,t))||(t.exports=r))}()}},n={};function e(r){var i=n[r];if(void 0!==i)return i.exports;var o=n[r]={exports:{}};return t[r](o,o.exports,e),o.exports}e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,{a:n}),n},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]})},e.o=function(t,n){return Object.prototype.hasOwnProperty.call(t,n)},e.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var r={};!function(){"use strict";e.r(r),e.d(r,{__:function(){return j},_n:function(){return T},_nx:function(){return D},_x:function(){return L},createI18n:function(){return y},defaultI18n:function(){return m},getLocaleData:function(){return w},hasTranslation:function(){return E},isRTL:function(){return O},resetLocaleData:function(){return F},setLocaleData:function(){return k},sprintf:function(){return s},subscribe:function(){return S}});var t=e(9756),n=e.n(t),i=e(124),o=e.n(i);const a=n()(console.error);function s(t){try{for(var n=arguments.length,e=new Array(n>1?n-1:0),r=1;r<n;r++)e[r-1]=arguments[r];return o().sprintf(t,...e)}catch(n){return n instanceof Error&&a("sprintf error: \n\n"+n.toString()),t}}var u,l,c,p;u={"(":9,"!":8,"*":7,"/":7,"%":7,"+":6,"-":6,"<":5,"<=":5,">":5,">=":5,"==":4,"!=":4,"&&":3,"||":2,"?":1,"?:":1},l=["(","?"],c={")":["("],":":["?","?:"]},p=/<=|>=|==|!=|&&|\|\||\?:|\(|!|\*|\/|%|\+|-|<|>|\?|\)|:/;var f={"!":function(t){return!t},"*":function(t,n){return t*n},"/":function(t,n){return t/n},"%":function(t,n){return t%n},"+":function(t,n){return t+n},"-":function(t,n){return t-n},"<":function(t,n){return t<n},"<=":function(t,n){return t<=n},">":function(t,n){return t>n},">=":function(t,n){return t>=n},"==":function(t,n){return t===n},"!=":function(t,n){return t!==n},"&&":function(t,n){return t&&n},"||":function(t,n){return t||n},"?:":function(t,n,e){if(t)throw n;return e}};function d(t){var n=function(t){for(var n,e,r,i,o=[],a=[];n=t.match(p);){for(e=n[0],(r=t.substr(0,n.index).trim())&&o.push(r);i=a.pop();){if(c[e]){if(c[e][0]===i){e=c[e][1]||e;break}}else if(l.indexOf(i)>=0||u[i]<u[e]){a.push(i);break}o.push(i)}c[e]||a.push(e),t=t.substr(n.index+e.length)}return(t=t.trim())&&o.push(t),o.concat(a.reverse())}(t);return function(t){return function(t,n){var e,r,i,o,a,s,u=[];for(e=0;e<t.length;e++){if(a=t[e],o=f[a]){for(r=o.length,i=Array(r);r--;)i[r]=u.pop();try{s=o.apply(null,i)}catch(t){return t}}else s=n.hasOwnProperty(a)?n[a]:+a;u.push(s)}return u[0]}(n,t)}}var h={contextDelimiter:"",onMissingKey:null};function g(t,n){var e;for(e in this.data=t,this.pluralForms={},this.options={},h)this.options[e]=void 0!==n&&e in n?n[e]:h[e]}g.prototype.getPluralForm=function(t,n){var e,r,i,o=this.pluralForms[t];return o||("function"!=typeof(i=(e=this.data[t][""])["Plural-Forms"]||e["plural-forms"]||e.plural_forms)&&(r=function(t){var n,e,r;for(n=t.split(";"),e=0;e<n.length;e++)if(0===(r=n[e].trim()).indexOf("plural="))return r.substr(7)}(e["Plural-Forms"]||e["plural-forms"]||e.plural_forms),i=function(t){var n=d(t);return function(t){return+n({n:t})}}(r)),o=this.pluralForms[t]=i),o(n)},g.prototype.dcnpgettext=function(t,n,e,r,i){var o,a,s;return o=void 0===i?0:this.getPluralForm(t,i),a=e,n&&(a=n+this.options.contextDelimiter+e),(s=this.data[t][a])&&s[o]?s[o]:(this.options.onMissingKey&&this.options.onMissingKey(e,t),0===o?e:r)};const v={plural_forms(t){return 1===t?0:1}},x=/^i18n\.(n?gettext|has_translation)(_|$)/,y=(t,n,e)=>{const r=new g({}),i=new Set,o=()=>{i.forEach((t=>t()))},a=function(t){var n;let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"default";r.data[e]={...r.data[e],...t},r.data[e][""]={...v,...null===(n=r.data[e])||void 0===n?void 0:n[""]},delete r.pluralForms[e]},s=(t,n)=>{a(t,n),o()},u=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"default",n=arguments.length>1?arguments[1]:void 0,e=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,o=arguments.length>4?arguments[4]:void 0;return r.data[t]||a(void 0,t),r.dcnpgettext(t,n,e,i,o)},l=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"default";return t},c=(t,n,r)=>{let i=u(r,n,t);return e?(i=e.applyFilters("i18n.gettext_with_context",i,t,n,r),e.applyFilters("i18n.gettext_with_context_"+l(r),i,t,n,r)):i};if(t&&s(t,n),e){const t=t=>{x.test(t)&&o()};e.addAction("hookAdded","core/i18n",t),e.addAction("hookRemoved","core/i18n",t)}return{getLocaleData:function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"default";return r.data[t]},setLocaleData:s,addLocaleData:function(t){var n;let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"default";r.data[e]={...r.data[e],...t,"":{...v,...null===(n=r.data[e])||void 0===n?void 0:n[""],...null==t?void 0:t[""]}},delete r.pluralForms[e],o()},resetLocaleData:(t,n)=>{r.data={},r.pluralForms={},s(t,n)},subscribe:t=>(i.add(t),()=>i.delete(t)),__:(t,n)=>{let r=u(n,void 0,t);return e?(r=e.applyFilters("i18n.gettext",r,t,n),e.applyFilters("i18n.gettext_"+l(n),r,t,n)):r},_x:c,_n:(t,n,r,i)=>{let o=u(i,void 0,t,n,r);return e?(o=e.applyFilters("i18n.ngettext",o,t,n,r,i),e.applyFilters("i18n.ngettext_"+l(i),o,t,n,r,i)):o},_nx:(t,n,r,i,o)=>{let a=u(o,i,t,n,r);return e?(a=e.applyFilters("i18n.ngettext_with_context",a,t,n,r,i,o),e.applyFilters("i18n.ngettext_with_context_"+l(o),a,t,n,r,i,o)):a},isRTL:()=>"rtl"===c("ltr","text direction"),hasTranslation:(t,n,i)=>{var o,a;const s=n?n+""+t:t;let u=!(null===(o=r.data)||void 0===o||null===(a=o[null!=i?i:"default"])||void 0===a||!a[s]);return e&&(u=e.applyFilters("i18n.has_translation",u,t,n,i),u=e.applyFilters("i18n.has_translation_"+l(i),u,t,n,i)),u}}};var b=window.wp.hooks;const _=y(void 0,void 0,b.defaultHooks);var m=_;const w=_.getLocaleData.bind(_),k=_.setLocaleData.bind(_),F=_.resetLocaleData.bind(_),S=_.subscribe.bind(_),j=_.__.bind(_),L=_._x.bind(_),T=_._n.bind(_),D=_._nx.bind(_),O=_.isRTL.bind(_),E=_.hasTranslation.bind(_)}(),(window.wp=window.wp||{}).i18n=r}(); block-serialization-default-parser.js 0000666 00000035703 15123355174 0014005 0 ustar 00 /******/ (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__ = {};
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "parse": function() { return /* binding */ parse; }
/* harmony export */ });
/**
* @type {string}
*/
let document;
/**
* @type {number}
*/
let offset;
/**
* @type {ParsedBlock[]}
*/
let output;
/**
* @type {ParsedFrame[]}
*/
let stack;
/**
* @typedef {Object|null} Attributes
*/
/**
* @typedef {Object} ParsedBlock
* @property {string|null} blockName Block name.
* @property {Attributes} attrs Block attributes.
* @property {ParsedBlock[]} innerBlocks Inner blocks.
* @property {string} innerHTML Inner HTML.
* @property {Array<string|null>} innerContent Inner content.
*/
/**
* @typedef {Object} ParsedFrame
* @property {ParsedBlock} block Block.
* @property {number} tokenStart Token start.
* @property {number} tokenLength Token length.
* @property {number} prevOffset Previous offset.
* @property {number|null} leadingHtmlStart Leading HTML start.
*/
/**
* @typedef {'no-more-tokens'|'void-block'|'block-opener'|'block-closer'} TokenType
*/
/**
* @typedef {[TokenType, string, Attributes, number, number]} Token
*/
/**
* Matches block comment delimiters
*
* While most of this pattern is straightforward the attribute parsing
* incorporates a tricks to make sure we don't choke on specific input
*
* - since JavaScript has no possessive quantifier or atomic grouping
* we are emulating it with a trick
*
* we want a possessive quantifier or atomic group to prevent backtracking
* on the `}`s should we fail to match the remainder of the pattern
*
* we can emulate this with a positive lookahead and back reference
* (a++)*c === ((?=(a+))\1)*c
*
* let's examine an example:
* - /(a+)*c/.test('aaaaaaaaaaaaad') fails after over 49,000 steps
* - /(a++)*c/.test('aaaaaaaaaaaaad') fails after 85 steps
* - /(?>a+)*c/.test('aaaaaaaaaaaaad') fails after 126 steps
*
* this is because the possessive `++` and the atomic group `(?>)`
* tell the engine that all those `a`s belong together as a single group
* and so it won't split it up when stepping backwards to try and match
*
* if we use /((?=(a+))\1)*c/ then we get the same behavior as the atomic group
* or possessive and prevent the backtracking because the `a+` is matched but
* not captured. thus, we find the long string of `a`s and remember it, then
* reference it as a whole unit inside our pattern
*
* @see http://instanceof.me/post/52245507631/regex-emulate-atomic-grouping-with-lookahead
* @see http://blog.stevenlevithan.com/archives/mimic-atomic-groups
* @see https://javascript.info/regexp-infinite-backtracking-problem
*
* once browsers reliably support atomic grouping or possessive
* quantifiers natively we should remove this trick and simplify
*
* @type {RegExp}
*
* @since 3.8.0
* @since 4.6.1 added optimization to prevent backtracking on attribute parsing
*/
const tokenizer = /<!--\s+(\/)?wp:([a-z][a-z0-9_-]*\/)?([a-z][a-z0-9_-]*)\s+({(?:(?=([^}]+|}+(?=})|(?!}\s+\/?-->)[^])*)\5|[^]*?)}\s+)?(\/)?-->/g;
/**
* Constructs a block object.
*
* @param {string|null} blockName
* @param {Attributes} attrs
* @param {ParsedBlock[]} innerBlocks
* @param {string} innerHTML
* @param {string[]} innerContent
* @return {ParsedBlock} The block object.
*/
function Block(blockName, attrs, innerBlocks, innerHTML, innerContent) {
return {
blockName,
attrs,
innerBlocks,
innerHTML,
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.
*
* @param {ParsedBlock} block
* @param {number} tokenStart
* @param {number} tokenLength
* @param {number} prevOffset
* @param {number|null} leadingHtmlStart
* @return {ParsedFrame} The frame object.
*/
function Frame(block, tokenStart, tokenLength, prevOffset, leadingHtmlStart) {
return {
block,
tokenStart,
tokenLength,
prevOffset: prevOffset || tokenStart + tokenLength,
leadingHtmlStart
};
}
/**
* Parser function, that converts input HTML into a block based structure.
*
* @param {string} doc The HTML document to parse.
*
* @example
* Input post:
* ```html
* <!-- wp:columns {"columns":3} -->
* <div class="wp-block-columns has-3-columns"><!-- wp:column -->
* <div class="wp-block-column"><!-- wp:paragraph -->
* <p>Left</p>
* <!-- /wp:paragraph --></div>
* <!-- /wp:column -->
*
* <!-- wp:column -->
* <div class="wp-block-column"><!-- wp:paragraph -->
* <p><strong>Middle</strong></p>
* <!-- /wp:paragraph --></div>
* <!-- /wp:column -->
*
* <!-- wp:column -->
* <div class="wp-block-column"></div>
* <!-- /wp:column --></div>
* <!-- /wp:columns -->
* ```
*
* Parsing code:
* ```js
* import { parse } from '@wordpress/block-serialization-default-parser';
*
* parse( post ) === [
* {
* blockName: "core/columns",
* attrs: {
* columns: 3
* },
* innerBlocks: [
* {
* blockName: "core/column",
* attrs: null,
* innerBlocks: [
* {
* blockName: "core/paragraph",
* attrs: null,
* innerBlocks: [],
* innerHTML: "\n<p>Left</p>\n"
* }
* ],
* innerHTML: '\n<div class="wp-block-column"></div>\n'
* },
* {
* blockName: "core/column",
* attrs: null,
* innerBlocks: [
* {
* blockName: "core/paragraph",
* attrs: null,
* innerBlocks: [],
* innerHTML: "\n<p><strong>Middle</strong></p>\n"
* }
* ],
* innerHTML: '\n<div class="wp-block-column"></div>\n'
* },
* {
* blockName: "core/column",
* attrs: null,
* innerBlocks: [],
* innerHTML: '\n<div class="wp-block-column"></div>\n'
* }
* ],
* innerHTML: '\n<div class="wp-block-columns has-3-columns">\n\n\n\n</div>\n'
* }
* ];
* ```
* @return {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
} 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 leadingHtmlStart = startOffset > offset ? offset : null;
switch (tokenType) {
case 'no-more-tokens':
// If not in a block then flush output.
if (0 === stackDepth) {
addFreeform();
return false;
} // Otherwise we have a problem
// This is an error
// we have options
// - treat it all as freeform text
// - assume an implicit closer (easiest when not nesting)
// For the easy case we'll assume an implicit closer.
if (1 === stackDepth) {
addBlockFromStack();
return false;
} // For the nested case where it's more difficult we'll
// have to assume that multiple closers are missing
// and so we'll collapse the whole stack piecewise.
while (0 < stack.length) {
addBlockFromStack();
}
return false;
case 'void-block':
// easy case is if we stumbled upon a void block
// in the top-level of the document.
if (0 === stackDepth) {
if (null !== leadingHtmlStart) {
output.push(Freeform(document.substr(leadingHtmlStart, startOffset - leadingHtmlStart)));
}
output.push(Block(blockName, attrs, [], '', []));
offset = startOffset + tokenLength;
return true;
} // Otherwise we found an inner block.
addInnerBlock(Block(blockName, attrs, [], '', []), startOffset, tokenLength);
offset = startOffset + tokenLength;
return true;
case 'block-opener':
// Track all newly-opened blocks on the stack.
stack.push(Frame(Block(blockName, attrs, [], '', []), startOffset, tokenLength, startOffset + tokenLength, leadingHtmlStart));
offset = startOffset + tokenLength;
return true;
case 'block-closer':
// If we're missing an opener we're in trouble
// This is an error.
if (0 === stackDepth) {
// We have options
// - assume an implicit opener
// - assume _this_ is the opener
// - give up and close out the document.
addFreeform();
return false;
} // If we're not nesting then this is easy - close the block.
if (1 === stackDepth) {
addBlockFromStack(startOffset);
offset = startOffset + tokenLength;
return true;
} // Otherwise we're nested and we have to close out the current
// block and add it as a innerBlock to the parent.
const stackTop =
/** @type {ParsedFrame} */
stack.pop();
const html = document.substr(stackTop.prevOffset, startOffset - stackTop.prevOffset);
stackTop.block.innerHTML += html;
stackTop.block.innerContent.push(html);
stackTop.prevOffset = startOffset + tokenLength;
addInnerBlock(stackTop.block, stackTop.tokenStart, stackTop.tokenLength, startOffset + tokenLength);
offset = startOffset + tokenLength;
return true;
default:
// This is an error.
addFreeform();
return false;
}
}
/**
* Parse JSON if valid, otherwise return null
*
* Note that JSON coming from the block comment
* delimiters is constrained to be an object
* and cannot be things like `true` or `null`
*
* @param {string} input JSON input string to parse
* @return {Object|null} parsed JSON if valid
*/
function parseJSON(input) {
try {
return JSON.parse(input);
} catch (e) {
return null;
}
}
/**
* 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
// we're also using a trick here because the only difference between a
// block opener and a block closer is the leading `/` before `wp:` (and
// a closer has no attributes). we can trap them both and process the
// match back in JavaScript to see which one it was.
const matches = tokenizer.exec(document); // We have no more tokens.
if (null === matches) {
return ['no-more-tokens', '', null, 0, 0];
}
const startedAt = matches.index;
const [match, closerMatch, namespaceMatch, nameMatch, attrsMatch
/* Internal/unused. */
,, voidMatch] = matches;
const length = match.length;
const isCloser = !!closerMatch;
const isVoid = !!voidMatch;
const namespace = namespaceMatch || 'core/';
const name = namespace + nameMatch;
const hasAttrs = !!attrsMatch;
const attrs = hasAttrs ? parseJSON(attrsMatch) : {}; // This state isn't allowed
// This is an error.
if (isCloser && (isVoid || hasAttrs)) {// We can ignore them since they don't hurt anything
// we may warn against this at some point or reject it.
}
if (isVoid) {
return ['void-block', name, attrs, startedAt, length];
}
if (isCloser) {
return ['block-closer', name, null, startedAt, length];
}
return ['block-opener', name, attrs, startedAt, length];
}
/**
* 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.
*
* @param {ParsedBlock} block
* @param {number} tokenStart
* @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();
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);
}
(window.wp = window.wp || {}).blockSerializationDefaultParser = __webpack_exports__;
/******/ })()
; preferences.js 0000666 00000030176 15123355174 0007424 0 ustar 00 /******/ (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__, {
"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; }
});
// 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; }
});
;// CONCATENATED MODULE: external ["wp","element"]
var external_wp_element_namespaceObject = window["wp"]["element"];
;// CONCATENATED MODULE: external ["wp","data"]
var external_wp_data_namespaceObject = window["wp"]["data"];
;// 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","primitives"]
var external_wp_primitives_namespaceObject = window["wp"]["primitives"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/check.js
/**
* WordPress dependencies
*/
const check = (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: "M16.7 7.1l-6.3 8.5-3.3-2.5-.9 1.2 4.5 3.4L17.9 8z"
}));
/* harmony default export */ var library_check = (check);
;// CONCATENATED MODULE: external ["wp","a11y"]
var external_wp_a11y_namespaceObject = window["wp"]["a11y"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/preferences/build-module/store/reducer.js
/**
* WordPress dependencies
*/
/**
* Reducer returning the defaults for user preferences.
*
* This is kept intentionally separate from the preferences
* themselves so that defaults are not persisted.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
function defaults() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
if (action.type === 'SET_PREFERENCE_DEFAULTS') {
const {
scope,
defaults: values
} = action;
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
* `SET_PERSISTENCE_LAYER` action is received.
* - Passes any preferences changes to the persistence layer.
*
* @param {Function} reducer The preferences reducer.
*
* @return {Function} The enhanced reducer.
*/
function withPersistenceLayer(reducer) {
let persistenceLayer;
return (state, action) => {
// Setup the persistence layer, and return the persisted data
// as the state.
if (action.type === 'SET_PERSISTENCE_LAYER') {
const {
persistenceLayer: persistence,
persistedData
} = action;
persistenceLayer = persistence;
return persistedData;
}
const nextState = reducer(state, action);
if (action.type === 'SET_PREFERENCE_VALUE') {
var _persistenceLayer;
(_persistenceLayer = persistenceLayer) === null || _persistenceLayer === void 0 ? void 0 : _persistenceLayer.set(nextState);
}
return nextState;
};
}
/**
* Reducer returning the user preferences.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
const preferences = withPersistenceLayer(function () {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
if (action.type === 'SET_PREFERENCE_VALUE') {
const {
scope,
name,
value
} = action;
return { ...state,
[scope]: { ...state[scope],
[name]: value
}
};
}
return state;
});
/* harmony default export */ var reducer = ((0,external_wp_data_namespaceObject.combineReducers)({
defaults,
preferences
}));
;// CONCATENATED MODULE: ./node_modules/@wordpress/preferences/build-module/store/actions.js
/**
* Returns an action object used in signalling that a preference should be
* toggled.
*
* @param {string} scope The preference scope (e.g. core/edit-post).
* @param {string} name The preference name.
*/
function toggle(scope, name) {
return function (_ref) {
let {
select,
dispatch
} = _ref;
const currentValue = select.get(scope, name);
dispatch.set(scope, name, !currentValue);
};
}
/**
* Returns an action object used in signalling that a preference should be set
* to a value
*
* @param {string} scope The preference scope (e.g. core/edit-post).
* @param {string} name The preference name.
* @param {*} value The value to set.
*
* @return {Object} Action object.
*/
function set(scope, name, value) {
return {
type: 'SET_PREFERENCE_VALUE',
scope,
name,
value
};
}
/**
* Returns an action object used in signalling that preference defaults should
* be set.
*
* @param {string} scope The preference scope (e.g. core/edit-post).
* @param {Object<string, *>} defaults A key/value map of preference names to values.
*
* @return {Object} Action object.
*/
function setDefaults(scope, defaults) {
return {
type: 'SET_PREFERENCE_DEFAULTS',
scope,
defaults
};
}
/** @typedef {() => Promise<Object>} WPPreferencesPersistenceLayerGet */
/** @typedef {(*) => void} WPPreferencesPersistenceLayerSet */
/**
* @typedef WPPreferencesPersistenceLayer
*
* @property {WPPreferencesPersistenceLayerGet} get An async function that gets data from the persistence layer.
* @property {WPPreferencesPersistenceLayerSet} set A function that sets data in the persistence layer.
*/
/**
* Sets the persistence layer.
*
* When a persistence layer is set, the preferences store will:
* - call `get` immediately and update the store state to the value returned.
* - call `set` with all preferences whenever a preference changes value.
*
* `setPersistenceLayer` should ideally be dispatched at the start of an
* application's lifecycle, before any other actions have been dispatched to
* the preferences store.
*
* @param {WPPreferencesPersistenceLayer} persistenceLayer The persistence layer.
*
* @return {Object} Action object.
*/
async function setPersistenceLayer(persistenceLayer) {
const persistedData = await persistenceLayer.get();
return {
type: 'SET_PERSISTENCE_LAYER',
persistenceLayer,
persistedData
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/preferences/build-module/store/selectors.js
/**
* Returns a boolean indicating whether a prefer is active for a particular
* scope.
*
* @param {Object} state The store state.
* @param {string} scope The scope of the feature (e.g. core/edit-post).
* @param {string} name The name of the feature.
*
* @return {*} Is the feature enabled?
*/
function get(state, scope, name) {
var _state$preferences$sc, _state$defaults$scope;
const value = (_state$preferences$sc = state.preferences[scope]) === null || _state$preferences$sc === void 0 ? void 0 : _state$preferences$sc[name];
return value !== undefined ? value : (_state$defaults$scope = state.defaults[scope]) === null || _state$defaults$scope === void 0 ? void 0 : _state$defaults$scope[name];
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/preferences/build-module/store/constants.js
/**
* The identifier for the data store.
*
* @type {string}
*/
const STORE_NAME = 'core/preferences';
;// CONCATENATED MODULE: ./node_modules/@wordpress/preferences/build-module/store/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Store definition for the interface 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, {
reducer: reducer,
actions: actions_namespaceObject,
selectors: selectors_namespaceObject
});
(0,external_wp_data_namespaceObject.register)(store);
;// CONCATENATED MODULE: ./node_modules/@wordpress/preferences/build-module/components/preference-toggle-menu-item/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PreferenceToggleMenuItem(_ref) {
let {
scope,
name,
label,
info,
messageActivated,
messageDeactivated,
shortcut,
onToggle = () => null,
disabled = false
} = _ref;
const isActive = (0,external_wp_data_namespaceObject.useSelect)(select => !!select(store).get(scope, name), [name]);
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' */
(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' */
(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,
onClick: () => {
onToggle();
toggle(scope, name);
speakMessage();
},
role: "menuitemcheckbox",
info: info,
shortcut: shortcut,
disabled: disabled
}, label);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/preferences/build-module/components/index.js
;// CONCATENATED MODULE: ./node_modules/@wordpress/preferences/build-module/index.js
(window.wp = window.wp || {}).preferences = __webpack_exports__;
/******/ })()
; blob.min.js 0000666 00000001672 15123355174 0006622 0 ustar 00 /*! 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)},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,{createBlobURL:function(){return o},getBlobByURL:function(){return r},getBlobTypeByURL:function(){return i},isBlobURL:function(){return c},revokeBlobURL:function(){return u}});const t={};function o(e){const n=window.URL.createObjectURL(e);return t[n]=e,n}function r(e){return t[e]}function i(e){var n;return null===(n=r(e))||void 0===n?void 0:n.type.split("/")[0]}function u(e){t[e]&&window.URL.revokeObjectURL(e),delete t[e]}function c(e){return!(!e||!e.indexOf)&&0===e.indexOf("blob:")}(window.wp=window.wp||{}).blob=n}(); priority-queue.js 0000666 00000033771 15123355174 0010132 0 ustar 00 /******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 3159:
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (factory) {
if (true) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
}(function(){
'use strict';
var scheduleStart, throttleDelay, lazytimer, lazyraf;
var root = typeof window != 'undefined' ?
window :
typeof __webpack_require__.g != undefined ?
__webpack_require__.g :
this || {};
var requestAnimationFrame = root.cancelRequestAnimationFrame && root.requestAnimationFrame || setTimeout;
var cancelRequestAnimationFrame = root.cancelRequestAnimationFrame || clearTimeout;
var tasks = [];
var runAttempts = 0;
var isRunning = false;
var remainingTime = 7;
var minThrottle = 35;
var throttle = 125;
var index = 0;
var taskStart = 0;
var tasklength = 0;
var IdleDeadline = {
get didTimeout(){
return false;
},
timeRemaining: function(){
var timeRemaining = remainingTime - (Date.now() - taskStart);
return timeRemaining < 0 ? 0 : timeRemaining;
},
};
var setInactive = debounce(function(){
remainingTime = 22;
throttle = 66;
minThrottle = 0;
});
function debounce(fn){
var id, timestamp;
var wait = 99;
var check = function(){
var last = (Date.now()) - timestamp;
if (last < wait) {
id = setTimeout(check, wait - last);
} else {
id = null;
fn();
}
};
return function(){
timestamp = Date.now();
if(!id){
id = setTimeout(check, wait);
}
};
}
function abortRunning(){
if(isRunning){
if(lazyraf){
cancelRequestAnimationFrame(lazyraf);
}
if(lazytimer){
clearTimeout(lazytimer);
}
isRunning = false;
}
}
function onInputorMutation(){
if(throttle != 125){
remainingTime = 7;
throttle = 125;
minThrottle = 35;
if(isRunning) {
abortRunning();
scheduleLazy();
}
}
setInactive();
}
function scheduleAfterRaf() {
lazyraf = null;
lazytimer = setTimeout(runTasks, 0);
}
function scheduleRaf(){
lazytimer = null;
requestAnimationFrame(scheduleAfterRaf);
}
function scheduleLazy(){
if(isRunning){return;}
throttleDelay = throttle - (Date.now() - taskStart);
scheduleStart = Date.now();
isRunning = true;
if(minThrottle && throttleDelay < minThrottle){
throttleDelay = minThrottle;
}
if(throttleDelay > 9){
lazytimer = setTimeout(scheduleRaf, throttleDelay);
} else {
throttleDelay = 0;
scheduleRaf();
}
}
function runTasks(){
var task, i, len;
var timeThreshold = remainingTime > 9 ?
9 :
1
;
taskStart = Date.now();
isRunning = false;
lazytimer = null;
if(runAttempts > 2 || taskStart - throttleDelay - 50 < scheduleStart){
for(i = 0, len = tasks.length; i < len && IdleDeadline.timeRemaining() > timeThreshold; i++){
task = tasks.shift();
tasklength++;
if(task){
task(IdleDeadline);
}
}
}
if(tasks.length){
scheduleLazy();
} else {
runAttempts = 0;
}
}
function requestIdleCallbackShim(task){
index++;
tasks.push(task);
scheduleLazy();
return index;
}
function cancelIdleCallbackShim(id){
var index = id - 1 - tasklength;
if(tasks[index]){
tasks[index] = null;
}
}
if(!root.requestIdleCallback || !root.cancelIdleCallback){
root.requestIdleCallback = requestIdleCallbackShim;
root.cancelIdleCallback = cancelIdleCallbackShim;
if(root.document && document.addEventListener){
root.addEventListener('scroll', onInputorMutation, true);
root.addEventListener('resize', onInputorMutation);
document.addEventListener('focus', onInputorMutation, true);
document.addEventListener('mouseover', onInputorMutation, true);
['click', 'keypress', 'touchstart', 'mousedown'].forEach(function(name){
document.addEventListener(name, onInputorMutation, {capture: true, passive: true});
});
if(root.MutationObserver){
new MutationObserver( onInputorMutation ).observe( document.documentElement, {childList: true, subtree: true, attributes: true} );
}
}
} else {
try{
root.requestIdleCallback(function(){}, {timeout: 0});
} catch(e){
(function(rIC){
var timeRemainingProto, timeRemaining;
root.requestIdleCallback = function(fn, timeout){
if(timeout && typeof timeout.timeout == 'number'){
return rIC(fn, timeout.timeout);
}
return rIC(fn);
};
if(root.IdleCallbackDeadline && (timeRemainingProto = IdleCallbackDeadline.prototype)){
timeRemaining = Object.getOwnPropertyDescriptor(timeRemainingProto, 'timeRemaining');
if(!timeRemaining || !timeRemaining.configurable || !timeRemaining.get){return;}
Object.defineProperty(timeRemainingProto, 'timeRemaining', {
value: function(){
return timeRemaining.get.call(this);
},
enumerable: true,
configurable: true,
});
}
})(root.requestIdleCallback)
}
}
return {
request: requestIdleCallbackShim,
cancel: cancelIdleCallbackShim,
};
}));
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/define property getters */
/******/ !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/global */
/******/ !function() {
/******/ __webpack_require__.g = (function() {
/******/ if (typeof globalThis === 'object') return globalThis;
/******/ try {
/******/ return this || new Function('return this')();
/******/ } catch (e) {
/******/ if (typeof window === 'object') return window;
/******/ }
/******/ })();
/******/ }();
/******/
/******/ /* 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 in strict mode.
!function() {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"createQueue": function() { return /* binding */ createQueue; }
});
// EXTERNAL MODULE: ./node_modules/requestidlecallback/index.js
var requestidlecallback = __webpack_require__(3159);
;// CONCATENATED MODULE: ./node_modules/@wordpress/priority-queue/build-module/request-idle-callback.js
/**
* External dependencies
*/
/**
* @typedef {( timeOrDeadline: IdleDeadline | number ) => void} Callback
*/
/**
* @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());
;// CONCATENATED MODULE: ./node_modules/@wordpress/priority-queue/build-module/index.js
/**
* Internal dependencies
*/
/**
* Enqueued callback to invoke once idle time permits.
*
* @typedef {()=>void} WPPriorityQueueCallback
*/
/**
* An object used to associate callbacks in a particular context grouping.
*
* @typedef {{}} WPPriorityQueueContext
*/
/**
* Function to add callback to priority queue.
*
* @typedef {(element:WPPriorityQueueContext,item:WPPriorityQueueCallback)=>void} WPPriorityQueueAdd
*/
/**
* Function to flush callbacks from priority queue.
*
* @typedef {(element:WPPriorityQueueContext)=>boolean} WPPriorityQueueFlush
*/
/**
* Reset the queue.
*
* @typedef {()=>void} WPPriorityQueueReset
*/
/**
* Priority queue instance.
*
* @typedef {Object} WPPriorityQueue
*
* @property {WPPriorityQueueAdd} add Add callback to queue for context.
* @property {WPPriorityQueueFlush} flush Flush queue for context.
* @property {WPPriorityQueueFlush} cancel Clear queue for context.
* @property {WPPriorityQueueReset} reset Reset queue.
*/
/**
* Creates a context-aware queue that only executes
* the last task of a given context.
*
* @example
*```js
* import { createQueue } from '@wordpress/priority-queue';
*
* const queue = createQueue();
*
* // Context objects.
* const ctx1 = {};
* const ctx2 = {};
*
* // For a given context in the queue, only the last callback is executed.
* queue.add( ctx1, () => console.log( 'This will be printed first' ) );
* queue.add( ctx2, () => console.log( 'This won\'t be printed' ) );
* queue.add( ctx2, () => console.log( 'This will be printed second' ) );
*```
*
* @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.
*
* Map Iteration follows the original insertion order. This means that here
* we can iterate the queue and know that the first contexts which were
* added will be run first. On the other hand, if anyone adds a new callback
* for an existing context it will supplant the previously-set callback for
* that context because we reassigned that map key's value.
*
* In the case that a callback adds a new callback to its own context then
* the callback it adds will appear at the end of the iteration and will be
* run only after all other existing contexts have finished executing.
*
* @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.
*
* If errors with undefined callbacks are encountered double check that
* all of your useSelect calls have the right dependencies set correctly
* in their second parameter. Missing dependencies can cause unexpected
* loops and race conditions in the queue.
*
* @type {WPPriorityQueueAdd}
*
* @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.
*
* @type {WPPriorityQueueFlush}
*
* @param {WPPriorityQueueContext} element Context object.
*
* @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,
* or `false` if there was is no queue for the given context.
*
* @type {WPPriorityQueueFlush}
*
* @param {WPPriorityQueueContext} element Context object.
*
* @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,
cancel,
reset
};
};
}();
(window.wp = window.wp || {}).priorityQueue = __webpack_exports__;
/******/ })()
; redux-routine.js 0000666 00000057522 15123355174 0007741 0 ustar 00 /******/ (function() { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ({
/***/ 9025:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports.race = exports.join = exports.fork = exports.promise = undefined;
var _is = __webpack_require__(9681);
var _is2 = _interopRequireDefault(_is);
var _helpers = __webpack_require__(7783);
var _dispatcher = __webpack_require__(2451);
var _dispatcher2 = _interopRequireDefault(_dispatcher);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var promise = exports.promise = function promise(value, next, rungen, yieldNext, raiseNext) {
if (!_is2.default.promise(value)) return false;
value.then(next, raiseNext);
return true;
};
var forkedTasks = new Map();
var fork = exports.fork = function fork(value, next, rungen) {
if (!_is2.default.fork(value)) return false;
var task = Symbol('fork');
var dispatcher = (0, _dispatcher2.default)();
forkedTasks.set(task, dispatcher);
rungen(value.iterator.apply(null, value.args), function (result) {
return dispatcher.dispatch(result);
}, function (err) {
return dispatcher.dispatch((0, _helpers.error)(err));
});
var unsubscribe = dispatcher.subscribe(function () {
unsubscribe();
forkedTasks.delete(task);
});
next(task);
return true;
};
var join = exports.join = function join(value, next, rungen, yieldNext, raiseNext) {
if (!_is2.default.join(value)) return false;
var dispatcher = forkedTasks.get(value.task);
if (!dispatcher) {
raiseNext('join error : task not found');
} else {
(function () {
var unsubscribe = dispatcher.subscribe(function (result) {
unsubscribe();
next(result);
});
})();
}
return true;
};
var race = exports.race = function race(value, next, rungen, yieldNext, raiseNext) {
if (!_is2.default.race(value)) return false;
var finished = false;
var success = function success(result, k, v) {
if (finished) return;
finished = true;
result[k] = v;
next(result);
};
var fail = function fail(err) {
if (finished) return;
raiseNext(err);
};
if (_is2.default.array(value.competitors)) {
(function () {
var result = value.competitors.map(function () {
return false;
});
value.competitors.forEach(function (competitor, index) {
rungen(competitor, function (output) {
return success(result, index, output);
}, fail);
});
})();
} else {
(function () {
var result = Object.keys(value.competitors).reduce(function (p, c) {
p[c] = false;
return p;
}, {});
Object.keys(value.competitors).forEach(function (index) {
rungen(value.competitors[index], function (output) {
return success(result, index, output);
}, fail);
});
})();
}
return true;
};
var subscribe = function subscribe(value, next) {
if (!_is2.default.subscribe(value)) return false;
if (!_is2.default.channel(value.channel)) {
throw new Error('the first argument of "subscribe" must be a valid channel');
}
var unsubscribe = value.channel.subscribe(function (ret) {
unsubscribe && unsubscribe();
next(ret);
});
return true;
};
exports["default"] = [promise, fork, join, race, subscribe];
/***/ }),
/***/ 1575:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports.iterator = exports.array = exports.object = exports.error = exports.any = undefined;
var _is = __webpack_require__(9681);
var _is2 = _interopRequireDefault(_is);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var any = exports.any = function any(value, next, rungen, yieldNext) {
yieldNext(value);
return true;
};
var error = exports.error = function error(value, next, rungen, yieldNext, raiseNext) {
if (!_is2.default.error(value)) return false;
raiseNext(value.error);
return true;
};
var object = exports.object = function object(value, next, rungen, yieldNext, raiseNext) {
if (!_is2.default.all(value) || !_is2.default.obj(value.value)) return false;
var result = {};
var keys = Object.keys(value.value);
var count = 0;
var hasError = false;
var gotResultSuccess = function gotResultSuccess(key, ret) {
if (hasError) return;
result[key] = ret;
count++;
if (count === keys.length) {
yieldNext(result);
}
};
var gotResultError = function gotResultError(key, error) {
if (hasError) return;
hasError = true;
raiseNext(error);
};
keys.map(function (key) {
rungen(value.value[key], function (ret) {
return gotResultSuccess(key, ret);
}, function (err) {
return gotResultError(key, err);
});
});
return true;
};
var array = exports.array = function array(value, next, rungen, yieldNext, raiseNext) {
if (!_is2.default.all(value) || !_is2.default.array(value.value)) return false;
var result = [];
var count = 0;
var hasError = false;
var gotResultSuccess = function gotResultSuccess(key, ret) {
if (hasError) return;
result[key] = ret;
count++;
if (count === value.value.length) {
yieldNext(result);
}
};
var gotResultError = function gotResultError(key, error) {
if (hasError) return;
hasError = true;
raiseNext(error);
};
value.value.map(function (v, key) {
rungen(v, function (ret) {
return gotResultSuccess(key, ret);
}, function (err) {
return gotResultError(key, err);
});
});
return true;
};
var iterator = exports.iterator = function iterator(value, next, rungen, yieldNext, raiseNext) {
if (!_is2.default.iterator(value)) return false;
rungen(value, next, raiseNext);
return true;
};
exports["default"] = [error, iterator, array, object, any];
/***/ }),
/***/ 2165:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports.cps = exports.call = undefined;
var _is = __webpack_require__(9681);
var _is2 = _interopRequireDefault(_is);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var call = exports.call = function call(value, next, rungen, yieldNext, raiseNext) {
if (!_is2.default.call(value)) return false;
try {
next(value.func.apply(value.context, value.args));
} catch (err) {
raiseNext(err);
}
return true;
};
var cps = exports.cps = function cps(value, next, rungen, yieldNext, raiseNext) {
var _value$func;
if (!_is2.default.cps(value)) return false;
(_value$func = value.func).call.apply(_value$func, [null].concat(_toConsumableArray(value.args), [function (err, result) {
if (err) raiseNext(err);else next(result);
}]));
return true;
};
exports["default"] = [call, cps];
/***/ }),
/***/ 6288:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
Object.defineProperty(exports, "__esModule", ({
value: true
}));
var _builtin = __webpack_require__(1575);
var _builtin2 = _interopRequireDefault(_builtin);
var _is = __webpack_require__(9681);
var _is2 = _interopRequireDefault(_is);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var create = function create() {
var userControls = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0];
var controls = [].concat(_toConsumableArray(userControls), _toConsumableArray(_builtin2.default));
var runtime = function runtime(input) {
var success = arguments.length <= 1 || arguments[1] === undefined ? function () {} : arguments[1];
var error = arguments.length <= 2 || arguments[2] === undefined ? function () {} : arguments[2];
var iterate = function iterate(gen) {
var yieldValue = function yieldValue(isError) {
return function (ret) {
try {
var _ref = isError ? gen.throw(ret) : gen.next(ret);
var value = _ref.value;
var done = _ref.done;
if (done) return success(value);
next(value);
} catch (e) {
return error(e);
}
};
};
var next = function next(ret) {
controls.some(function (control) {
return control(ret, next, runtime, yieldValue(false), yieldValue(true));
});
};
yieldValue(false)();
};
var iterator = _is2.default.iterator(input) ? input : regeneratorRuntime.mark(function _callee() {
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return input;
case 2:
return _context.abrupt('return', _context.sent);
case 3:
case 'end':
return _context.stop();
}
}
}, _callee, this);
})();
iterate(iterator, success, error);
};
return runtime;
};
exports["default"] = create;
/***/ }),
/***/ 2290:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports.wrapControls = exports.asyncControls = exports.create = undefined;
var _helpers = __webpack_require__(7783);
Object.keys(_helpers).forEach(function (key) {
if (key === "default") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _helpers[key];
}
});
});
var _create = __webpack_require__(6288);
var _create2 = _interopRequireDefault(_create);
var _async = __webpack_require__(9025);
var _async2 = _interopRequireDefault(_async);
var _wrap = __webpack_require__(2165);
var _wrap2 = _interopRequireDefault(_wrap);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.create = _create2.default;
exports.asyncControls = _async2.default;
exports.wrapControls = _wrap2.default;
/***/ }),
/***/ 2451:
/***/ (function(__unused_webpack_module, exports) {
Object.defineProperty(exports, "__esModule", ({
value: true
}));
var createDispatcher = function createDispatcher() {
var listeners = [];
return {
subscribe: function subscribe(listener) {
listeners.push(listener);
return function () {
listeners = listeners.filter(function (l) {
return l !== listener;
});
};
},
dispatch: function dispatch(action) {
listeners.slice().forEach(function (listener) {
return listener(action);
});
}
};
};
exports["default"] = createDispatcher;
/***/ }),
/***/ 7783:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports.createChannel = exports.subscribe = exports.cps = exports.apply = exports.call = exports.invoke = exports.delay = exports.race = exports.join = exports.fork = exports.error = exports.all = undefined;
var _keys = __webpack_require__(9851);
var _keys2 = _interopRequireDefault(_keys);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var all = exports.all = function all(value) {
return {
type: _keys2.default.all,
value: value
};
};
var error = exports.error = function error(err) {
return {
type: _keys2.default.error,
error: err
};
};
var fork = exports.fork = function fork(iterator) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return {
type: _keys2.default.fork,
iterator: iterator,
args: args
};
};
var join = exports.join = function join(task) {
return {
type: _keys2.default.join,
task: task
};
};
var race = exports.race = function race(competitors) {
return {
type: _keys2.default.race,
competitors: competitors
};
};
var delay = exports.delay = function delay(timeout) {
return new Promise(function (resolve) {
setTimeout(function () {
return resolve(true);
}, timeout);
});
};
var invoke = exports.invoke = function invoke(func) {
for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
return {
type: _keys2.default.call,
func: func,
context: null,
args: args
};
};
var call = exports.call = function call(func, context) {
for (var _len3 = arguments.length, args = Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
args[_key3 - 2] = arguments[_key3];
}
return {
type: _keys2.default.call,
func: func,
context: context,
args: args
};
};
var apply = exports.apply = function apply(func, context, args) {
return {
type: _keys2.default.call,
func: func,
context: context,
args: args
};
};
var cps = exports.cps = function cps(func) {
for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
args[_key4 - 1] = arguments[_key4];
}
return {
type: _keys2.default.cps,
func: func,
args: args
};
};
var subscribe = exports.subscribe = function subscribe(channel) {
return {
type: _keys2.default.subscribe,
channel: channel
};
};
var createChannel = exports.createChannel = function createChannel(callback) {
var listeners = [];
var subscribe = function subscribe(l) {
listeners.push(l);
return function () {
return listeners.splice(listeners.indexOf(l), 1);
};
};
var next = function next(val) {
return listeners.forEach(function (l) {
return l(val);
});
};
callback(next);
return {
subscribe: subscribe
};
};
/***/ }),
/***/ 9681:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
Object.defineProperty(exports, "__esModule", ({
value: true
}));
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
var _keys = __webpack_require__(9851);
var _keys2 = _interopRequireDefault(_keys);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var is = {
obj: function obj(value) {
return (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && !!value;
},
all: function all(value) {
return is.obj(value) && value.type === _keys2.default.all;
},
error: function error(value) {
return is.obj(value) && value.type === _keys2.default.error;
},
array: Array.isArray,
func: function func(value) {
return typeof value === 'function';
},
promise: function promise(value) {
return value && is.func(value.then);
},
iterator: function iterator(value) {
return value && is.func(value.next) && is.func(value.throw);
},
fork: function fork(value) {
return is.obj(value) && value.type === _keys2.default.fork;
},
join: function join(value) {
return is.obj(value) && value.type === _keys2.default.join;
},
race: function race(value) {
return is.obj(value) && value.type === _keys2.default.race;
},
call: function call(value) {
return is.obj(value) && value.type === _keys2.default.call;
},
cps: function cps(value) {
return is.obj(value) && value.type === _keys2.default.cps;
},
subscribe: function subscribe(value) {
return is.obj(value) && value.type === _keys2.default.subscribe;
},
channel: function channel(value) {
return is.obj(value) && is.func(value.subscribe);
}
};
exports["default"] = is;
/***/ }),
/***/ 9851:
/***/ (function(__unused_webpack_module, exports) {
Object.defineProperty(exports, "__esModule", ({
value: true
}));
var keys = {
all: Symbol('all'),
error: Symbol('error'),
fork: Symbol('fork'),
join: Symbol('join'),
race: Symbol('race'),
call: Symbol('call'),
cps: Symbol('cps'),
subscribe: Symbol('subscribe')
};
exports["default"] = keys;
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/define property getters */
/******/ !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); }
/******/ }();
/******/
/************************************************************************/
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() {
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"default": function() { return /* binding */ createMiddleware; }
});
;// 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.
*
* @see https://www.ecma-international.org/ecma-262/6.0/#sec-generator-objects
*
* @param {any} object Object to test.
*
* @return {object is Generator} Whether object is a generator.
*/
function isGenerator(object) {
/* eslint-enable jsdoc/valid-types */
// Check that iterator (next) and iterable (Symbol.iterator) interfaces are satisfied.
// These checks seem to be compatible with several generator helpers as well as the native implementation.
return !!object && typeof object[Symbol.iterator] === 'function' && typeof object.next === 'function';
}
// EXTERNAL MODULE: ./node_modules/rungen/dist/index.js
var dist = __webpack_require__(2290);
;// CONCATENATED MODULE: ./node_modules/is-promise/index.mjs
function isPromise(obj) {
return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/redux-routine/node_modules/is-plain-object/dist/is-plain-object.mjs
/*!
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*/
function isObject(o) {
return Object.prototype.toString.call(o) === '[object Object]';
}
function isPlainObject(o) {
var ctor,prot;
if (isObject(o) === false) return false;
// If has modified constructor
ctor = o.constructor;
if (ctor === undefined) return true;
// If has modified prototype
prot = ctor.prototype;
if (isObject(prot) === false) return false;
// If constructor does not have an Object-specific method
if (prot.hasOwnProperty('isPrototypeOf') === false) {
return false;
}
// Most likely a plain Object
return true;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/redux-routine/build-module/is-action.js
/**
* External dependencies
*/
/* eslint-disable jsdoc/valid-types */
/**
* Returns true if the given object quacks like an action.
*
* @param {any} object Object to test
*
* @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
*
* @param {unknown} object Object to test
* @param {string} expectedType The expected type for the action.
*
* @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;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/redux-routine/build-module/runtime.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
/**
* Create a co-routine runtime.
*
* @param controls Object of control handlers.
* @param dispatch Unhandled action dispatch.
*/
function createRuntime() {
let controls = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let dispatch = arguments.length > 1 ? arguments[1] : undefined;
const rungenControls = Object.entries(controls).map(_ref => {
let [actionType, control] = _ref;
return (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));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/redux-routine/build-module/index.js
/**
* Internal dependencies
*/
/**
* 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
* a promise which is to resolve when evaluation of the action should continue,
* or a value. The value or resolved promise value is assigned on the return
* value of the yield assignment. If the control handler returns undefined, the
* execution is not continued.
*
* @param {Record<string, (value: import('redux').AnyAction) => Promise<boolean> | boolean>} controls Object of control handlers.
*
* @return {import('redux').Middleware} Co-routine runtime
*/
function createMiddleware() {
let controls = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return store => {
const runtime = createRuntime(controls, store.dispatch);
return next => action => {
if (!isGenerator(action)) {
return next(action);
}
return runtime(action);
};
};
}
}();
(window.wp = window.wp || {}).reduxRoutine = __webpack_exports__["default"];
/******/ })()
; warning.js 0000666 00000005013 15123355174 0006560 0 ustar 00 /******/ (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); }
/******/ }();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"default": function() { return /* binding */ warning; }
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/warning/build-module/utils.js
/**
* Object map tracking messages which have been logged, for use in ensuring a
* message is only logged once.
*
* @type {Set<string>}
*/
const logged = new Set();
;// CONCATENATED MODULE: ./node_modules/@wordpress/warning/build-module/index.js
/**
* Internal dependencies
*/
function isDev() {
return typeof process !== 'undefined' && process.env && "production" !== 'production';
}
/**
* Shows a warning with `message` if environment is not `production`.
*
* @param {string} message Message to show in the warning.
*
* @example
* ```js
* import warning from '@wordpress/warning';
*
* function MyComponent( props ) {
* if ( ! props.title ) {
* warning( '`props.title` was not passed' );
* }
* ...
* }
* ```
*/
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.
}
logged.add(message);
}
(window.wp = window.wp || {}).warning = __webpack_exports__["default"];
/******/ })()
; notices.js 0000666 00000047140 15123355174 0006566 0 ustar 00 /******/ (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__, {
"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; },
"removeNotice": function() { return removeNotice; }
});
// 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; }
});
;// CONCATENATED MODULE: external ["wp","data"]
var external_wp_data_namespaceObject = window["wp"]["data"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/notices/build-module/store/utils/on-sub-key.js
/**
* Higher-order reducer creator which creates a combined reducer object, keyed
* by a property on the action object.
*
* @param {string} actionProperty Action property by which to key object.
*
* @return {Function} Higher-order reducer.
*/
const onSubKey = actionProperty => reducer => function () {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
// 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,
[key]: nextKeyState
};
};
/* harmony default export */ var on_sub_key = (onSubKey);
;// CONCATENATED MODULE: ./node_modules/@wordpress/notices/build-module/store/reducer.js
/**
* 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.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
const notices = on_sub_key('context')(function () {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'CREATE_NOTICE':
// Avoid duplicates on ID.
return [...state.filter(_ref => {
let {
id
} = _ref;
return id !== action.notice.id;
}), action.notice];
case 'REMOVE_NOTICE':
return state.filter(_ref2 => {
let {
id
} = _ref2;
return id !== action.id;
});
}
return state;
});
/* harmony default export */ var reducer = (notices);
;// CONCATENATED MODULE: ./node_modules/@wordpress/notices/build-module/store/constants.js
/**
* Default context to use for notice grouping when not otherwise specified. Its
* specific value doesn't hold much meaning, but it must be reasonably unique
* and, more importantly, referenced consistently in the store implementation.
*
* @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
/**
* Internal dependencies
*/
/**
* @typedef {Object} WPNoticeAction Object describing a user action option associated with a notice.
*
* @property {string} label Message to use as action label.
* @property {?string} url Optional URL of resource if action incurs
* 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.
*
* @param {string} [status='info'] Notice status.
* @param {string} content Notice message.
* @param {Object} [options] Notice options.
* @param {string} [options.context='global'] Context under which to
* group notice.
* @param {string} [options.id] Identifier for notice.
* Automatically assigned
* if not specified.
* @param {boolean} [options.isDismissible=true] Whether the notice can
* be dismissed by user.
* @param {string} [options.type='default'] Type of notice, one of
* `default`, or `snackbar`.
* @param {boolean} [options.speak=true] Whether the notice
* content should be
* announced to screen
* readers.
* @param {Array<WPNoticeAction>} [options.actions] User actions to be
* presented with notice.
* @param {string} [options.icon] An icon displayed with the notice.
* Only used when type is set to `snackbar`.
* @param {boolean} [options.explicitDismiss] Whether the notice includes
* an explicit dismiss button and
* can't be dismissed by clicking
* the body of the notice. Only applies
* when type is set to `snackbar`.
* @param {Function} [options.onDismiss] Called when the notice is dismissed.
*
* @example
* ```js
* import { __ } from '@wordpress/i18n';
* import { useDispatch } from '@wordpress/data';
* import { store as noticesStore } from '@wordpress/notices';
* import { Button } from '@wordpress/components';
*
* const ExampleComponent = () => {
* const { createNotice } = useDispatch( noticesStore );
* return (
* <Button
* onClick={ () => createNotice( 'success', __( 'Notice message' ) ) }
* >
* { __( 'Generate a success notice!' ) }
* </Button>
* );
* };
* ```
*
* @return {Object} Action object.
*/
function createNotice() {
let status = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DEFAULT_STATUS;
let content = arguments.length > 1 ? arguments[1] : undefined;
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
const {
speak = true,
isDismissible = true,
context = DEFAULT_CONTEXT,
id = `${context}${++uniqueId}`,
actions = [],
type = 'default',
__unstableHTML,
icon = null,
explicitDismiss = false,
onDismiss
} = 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',
context,
notice: {
id,
status,
content,
spokenMessage: speak ? content : null,
__unstableHTML,
isDismissible,
actions,
type,
icon,
explicitDismiss,
onDismiss
}
};
}
/**
* Returns an action object used in signalling that a success notice is to be
* created. Refer to `createNotice` for options documentation.
*
* @see createNotice
*
* @param {string} content Notice message.
* @param {Object} [options] Optional notice options.
*
* @example
* ```js
* import { __ } from '@wordpress/i18n';
* import { useDispatch } from '@wordpress/data';
* import { store as noticesStore } from '@wordpress/notices';
* import { Button } from '@wordpress/components';
*
* const ExampleComponent = () => {
* const { createSuccessNotice } = useDispatch( noticesStore );
* return (
* <Button
* onClick={ () =>
* createSuccessNotice( __( 'Success!' ), {
* type: 'snackbar',
* icon: '🔥',
* } )
* }
* >
* { __( 'Generate a snackbar success notice!' ) }
* </Button>
* );
* };
* ```
*
* @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.
*
* @see createNotice
*
* @param {string} content Notice message.
* @param {Object} [options] Optional notice options.
*
* @example
* ```js
* import { __ } from '@wordpress/i18n';
* import { useDispatch } from '@wordpress/data';
* import { store as noticesStore } from '@wordpress/notices';
* import { Button } from '@wordpress/components';
*
* const ExampleComponent = () => {
* const { createInfoNotice } = useDispatch( noticesStore );
* return (
* <Button
* onClick={ () =>
* createInfoNotice( __( 'Something happened!' ), {
* isDismissible: false,
* } )
* }
* >
* { __( 'Generate a notice that cannot be dismissed.' ) }
* </Button>
* );
* };
*```
*
* @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.
*
* @see createNotice
*
* @param {string} content Notice message.
* @param {Object} [options] Optional notice options.
*
* @example
* ```js
* import { __ } from '@wordpress/i18n';
* import { useDispatch } from '@wordpress/data';
* import { store as noticesStore } from '@wordpress/notices';
* import { Button } from '@wordpress/components';
*
* const ExampleComponent = () => {
* const { createErrorNotice } = useDispatch( noticesStore );
* return (
* <Button
* onClick={ () =>
* createErrorNotice( __( 'An error occurred!' ), {
* type: 'snackbar',
* explicitDismiss: true,
* } )
* }
* >
* { __(
* 'Generate an snackbar error notice with explicit dismiss button.'
* ) }
* </Button>
* );
* };
* ```
*
* @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.
*
* @see createNotice
*
* @param {string} content Notice message.
* @param {Object} [options] Optional notice options.
*
* @example
* ```js
* import { __ } from '@wordpress/i18n';
* import { useDispatch } from '@wordpress/data';
* import { store as noticesStore } from '@wordpress/notices';
* import { Button } from '@wordpress/components';
*
* const ExampleComponent = () => {
* const { createWarningNotice, createInfoNotice } = useDispatch( noticesStore );
* return (
* <Button
* onClick={ () =>
* createWarningNotice( __( 'Warning!' ), {
* onDismiss: () => {
* createInfoNotice(
* __( 'The warning has been dismissed!' )
* );
* },
* } )
* }
* >
* { __( 'Generates a warning notice with onDismiss callback' ) }
* </Button>
* );
* };
* ```
*
* @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.
*
* @param {string} id Notice unique identifier.
* @param {string} [context='global'] Optional context (grouping) in which the notice is
* intended to appear. Defaults to default context.
*
* @example
* ```js
* import { __ } from '@wordpress/i18n';
* import { useDispatch } from '@wordpress/data';
* import { store as noticesStore } from '@wordpress/notices';
* import { Button } from '@wordpress/components';
*
* const ExampleComponent = () => {
* const notices = useSelect( ( select ) => select( noticesStore ).getNotices() );
* const { createWarningNotice, removeNotice } = useDispatch( noticesStore );
*
* return (
* <>
* <Button
* onClick={ () =>
* createWarningNotice( __( 'Warning!' ), {
* isDismissible: false,
* } )
* }
* >
* { __( 'Generate a notice' ) }
* </Button>
* { notices.length > 0 && (
* <Button onClick={ () => removeNotice( notices[ 0 ].id ) }>
* { __( 'Remove the notice' ) }
* </Button>
* ) }
* </>
* );
*};
* ```
*
* @return {Object} Action object.
*/
function removeNotice(id) {
let context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_CONTEXT;
return {
type: 'REMOVE_NOTICE',
id,
context
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/notices/build-module/store/selectors.js
/**
* Internal dependencies
*/
/** @typedef {import('./actions').WPNoticeAction} WPNoticeAction */
/**
* The default empty set of notices to return when there are no notices
* assigned for a given notices context. This can occur if the getNotices
* selector is called without a notice ever having been created for the
* context. A shared value is used to ensure referential equality between
* sequential selector calls, since otherwise `[] !== []`.
*
* @type {Array}
*/
const DEFAULT_NOTICES = [];
/**
* @typedef {Object} WPNotice Notice object.
*
* @property {string} id Unique identifier of notice.
* @property {string} status Status of notice, one of `success`,
* `info`, `error`, or `warning`. Defaults
* to `info`.
* @property {string} content Notice message.
* @property {string} spokenMessage Audibly announced message text used by
* assistive technologies.
* @property {string} __unstableHTML Notice message as raw HTML. Intended to
* serve primarily for compatibility of
* server-rendered notices, and SHOULD NOT
* be used for notices. It is subject to
* removal without notice.
* @property {boolean} isDismissible Whether the notice can be dismissed by
* user. Defaults to `true`.
* @property {string} type Type of notice, one of `default`,
* or `snackbar`. Defaults to `default`.
* @property {boolean} speak Whether the notice content should be
* announced to screen readers. Defaults to
* `true`.
* @property {WPNoticeAction[]} actions User actions to present with notice.
*
*/
/**
* Returns all notices as an array, optionally for a given context. Defaults to
* the global context.
*
* @param {Object} state Notices state.
* @param {?string} context Optional grouping context.
*
* @example
*
*```js
* import { useSelect } from '@wordpress/data';
* import { store as noticesStore } from '@wordpress/notices';
*
* const ExampleComponent = () => {
* const notices = useSelect( ( select ) => select( noticesStore ).getNotices() );
* return (
* <ul>
* { notices.map( ( notice ) => (
* <li key={ notice.ID }>{ notice.content }</li>
* ) ) }
* </ul>
* )
* };
*```
*
* @return {WPNotice[]} Array of notices.
*/
function getNotices(state) {
let context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_CONTEXT;
return state[context] || DEFAULT_NOTICES;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/notices/build-module/store/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Store definition for the notices namespace.
*
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/data/README.md#createReduxStore
*
* @type {Object}
*/
const store = (0,external_wp_data_namespaceObject.createReduxStore)('core/notices', {
reducer: reducer,
actions: actions_namespaceObject,
selectors: selectors_namespaceObject
});
(0,external_wp_data_namespaceObject.register)(store);
;// CONCATENATED MODULE: ./node_modules/@wordpress/notices/build-module/index.js
(window.wp = window.wp || {}).notices = __webpack_exports__;
/******/ })()
; html-entities.min.js 0000666 00000001505 15123355174 0010465 0 ustar 00 /*! This file is auto-generated */
!function(){"use strict";var e={d:function(t,n){for(var o in n)e.o(n,o)&&!e.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:n[o]})},o: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={};let n;function o(e){if("string"!=typeof e||-1===e.indexOf("&"))return e;void 0===n&&(n=document.implementation&&document.implementation.createHTMLDocument?document.implementation.createHTMLDocument("").createElement("textarea"):document.createElement("textarea")),n.innerHTML=e;const t=n.textContent;return n.innerHTML="",t}e.r(t),e.d(t,{decodeEntities:function(){return o}}),(window.wp=window.wp||{}).htmlEntities=t}(); a11y.min.js 0000666 00000004714 15123355174 0006457 0 ustar 00 /*! This file is auto-generated */
!function(){"use strict";var t={n:function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,{a:n}),n},d:function(e,n){for(var i in n)t.o(n,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:n[i]})},o:function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r:function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{setup:function(){return d},speak:function(){return p}});var n=window.wp.domReady,i=t.n(n),o=window.wp.i18n;function r(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"polite";const e=document.createElement("div");e.id=`a11y-speak-${t}`,e.className="a11y-speak-region",e.setAttribute("style","position: absolute;margin: -1px;padding: 0;height: 1px;width: 1px;overflow: hidden;clip: rect(1px, 1px, 1px, 1px);-webkit-clip-path: inset(50%);clip-path: inset(50%);border: 0;word-wrap: normal !important;"),e.setAttribute("aria-live",t),e.setAttribute("aria-relevant","additions text"),e.setAttribute("aria-atomic","true");const{body:n}=document;return n&&n.appendChild(e),e}let a="";function d(){const t=document.getElementById("a11y-speak-intro-text"),e=document.getElementById("a11y-speak-assertive"),n=document.getElementById("a11y-speak-polite");null===t&&function(){const t=document.createElement("p");t.id="a11y-speak-intro-text",t.className="a11y-speak-intro-text",t.textContent=(0,o.__)("Notifications"),t.setAttribute("style","position: absolute;margin: -1px;padding: 0;height: 1px;width: 1px;overflow: hidden;clip: rect(1px, 1px, 1px, 1px);-webkit-clip-path: inset(50%);clip-path: inset(50%);border: 0;word-wrap: normal !important;"),t.setAttribute("hidden","hidden");const{body:e}=document;e&&e.appendChild(t)}(),null===e&&r("assertive"),null===n&&r("polite")}function p(t,e){!function(){const t=document.getElementsByClassName("a11y-speak-region"),e=document.getElementById("a11y-speak-intro-text");for(let e=0;e<t.length;e++)t[e].textContent="";e&&e.setAttribute("hidden","hidden")}(),t=function(t){return t=t.replace(/<[^<>]+>/g," "),a===t&&(t+=" "),a=t,t}(t);const n=document.getElementById("a11y-speak-intro-text"),i=document.getElementById("a11y-speak-assertive"),o=document.getElementById("a11y-speak-polite");i&&"assertive"===e?i.textContent=t:o&&(o.textContent=t),n&&n.removeAttribute("hidden")}i()(d),(window.wp=window.wp||{}).a11y=e}(); edit-widgets.min.js 0000666 00000162457 15123355174 0010306 0 ustar 00 /*! This file is auto-generated */
!function(){var e={7153:function(e,t){var r;
/*!
Copyright (c) 2018 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/!function(){"use strict";var n={}.hasOwnProperty;function i(){for(var e="",t=0;t<arguments.length;t++){var r=arguments[t];r&&(e=o(e,a(r)))}return e}function a(e){if("string"==typeof e||"number"==typeof e)return e;if("object"!=typeof e)return"";if(Array.isArray(e))return i.apply(null,e);if(e.toString!==Object.prototype.toString&&!e.toString.toString().includes("[native code]"))return e.toString();var t="";for(var r in e)n.call(e,r)&&e[r]&&(t=o(t,r));return t}function o(e,t){return t?e?e+" "+t:e+t:e}e.exports?(i.default=i,e.exports=i):void 0===(r=function(){return i}.apply(t,[]))||(e.exports=r)}()}},t={};function r(n){var i=t[n];if(void 0!==i)return i.exports;var a=t[n]={exports:{}};return e[n](a,a.exports,r),a.exports}r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,{a:t}),t},r.d=function(e,t){for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};!function(){"use strict";r.r(n),r.d(n,{initialize:function(){return lr},initializeEditor:function(){return sr},reinitializeEditor:function(){return cr}});var e={};r.r(e),r.d(e,{disableComplementaryArea:function(){return P},enableComplementaryArea:function(){return L},pinItem:function(){return R},setDefaultComplementaryArea:function(){return T},setFeatureDefaults:function(){return V},setFeatureValue:function(){return D},toggleFeature:function(){return M},unpinItem:function(){return O}});var t={};r.r(t),r.d(t,{getActiveComplementaryArea:function(){return F},isFeatureActive:function(){return z},isItemPinned:function(){return G}});var i={};r.r(i),r.d(i,{closeGeneralSidebar:function(){return Ne},moveBlockToWidgetArea:function(){return Be},persistStubPost:function(){return fe},saveEditedWidgetAreas:function(){return Ee},saveWidgetArea:function(){return ve},saveWidgetAreas:function(){return be},setIsInserterOpened:function(){return Ae},setIsListViewOpened:function(){return Ce},setIsWidgetAreaOpen:function(){return Ie},setWidgetAreasOpenState:function(){return Se},setWidgetIdForClientId:function(){return ke}});var a={};r.r(a),r.d(a,{getWidgetAreas:function(){return xe},getWidgets:function(){return We}});var o={};r.r(o),r.d(o,{__experimentalGetInsertionPoint:function(){return ze},canInsertBlockInWidgetArea:function(){return He},getEditedWidgetAreas:function(){return Me},getIsWidgetAreaOpen:function(){return Fe},getParentWidgetAreaBlock:function(){return Oe},getReferenceWidgetBlocks:function(){return De},getWidget:function(){return Le},getWidgetAreaForWidgetId:function(){return Re},getWidgetAreas:function(){return Pe},getWidgets:function(){return Te},isInserterOpened:function(){return Ge},isListViewOpened:function(){return Ue},isSavingWidgetAreas:function(){return Ve}});var s={};r.r(s),r.d(s,{metadata:function(){return Ze},name:function(){return et},settings:function(){return tt}});var l=window.wp.element,c=window.wp.blocks,d=window.wp.data,u=window.wp.deprecated,m=r.n(u),g=window.wp.blockLibrary,p=window.wp.coreData,h=window.wp.widgets,_=window.wp.preferences,w=window.wp.apiFetch,f=r.n(w);var E=(0,d.combineReducers)({blockInserterPanel:function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0;switch(t.type){case"SET_IS_LIST_VIEW_OPENED":return!t.isOpen&&e;case"SET_IS_INSERTER_OPENED":return t.value}return e},listViewPanel:function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0;switch(t.type){case"SET_IS_INSERTER_OPENED":return!t.value&&e;case"SET_IS_LIST_VIEW_OPENED":return t.isOpen}return e},widgetAreasOpenState:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;const{type:r}=t;switch(r){case"SET_WIDGET_AREAS_OPEN_STATE":return t.widgetAreasOpenState;case"SET_IS_WIDGET_AREA_OPEN":{const{clientId:r,isOpen:n}=t;return{...e,[r]:n}}default:return e}}}),b=window.wp.i18n,v=window.wp.notices;function y(){return y=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},y.apply(null,arguments)}var k=r(7153),S=r.n(k),I=window.wp.components,A=window.wp.primitives;var C=(0,l.createElement)(A.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,l.createElement)(A.Path,{d:"M16.7 7.1l-6.3 8.5-3.3-2.5-.9 1.2 4.5 3.4L17.9 8z"}));var N=(0,l.createElement)(A.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,l.createElement)(A.Path,{d:"M11.776 4.454a.25.25 0 01.448 0l2.069 4.192a.25.25 0 00.188.137l4.626.672a.25.25 0 01.139.426l-3.348 3.263a.25.25 0 00-.072.222l.79 4.607a.25.25 0 01-.362.263l-4.138-2.175a.25.25 0 00-.232 0l-4.138 2.175a.25.25 0 01-.363-.263l.79-4.607a.25.25 0 00-.071-.222L4.754 9.881a.25.25 0 01.139-.426l4.626-.672a.25.25 0 00.188-.137l2.069-4.192z"}));var B=(0,l.createElement)(A.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,l.createElement)(A.Path,{fillRule:"evenodd",d:"M9.706 8.646a.25.25 0 01-.188.137l-4.626.672a.25.25 0 00-.139.427l3.348 3.262a.25.25 0 01.072.222l-.79 4.607a.25.25 0 00.362.264l4.138-2.176a.25.25 0 01.233 0l4.137 2.175a.25.25 0 00.363-.263l-.79-4.607a.25.25 0 01.072-.222l3.347-3.262a.25.25 0 00-.139-.427l-4.626-.672a.25.25 0 01-.188-.137l-2.069-4.192a.25.25 0 00-.448 0L9.706 8.646zM12 7.39l-.948 1.921a1.75 1.75 0 01-1.317.957l-2.12.308 1.534 1.495c.412.402.6.982.503 1.55l-.362 2.11 1.896-.997a1.75 1.75 0 011.629 0l1.895.997-.362-2.11a1.75 1.75 0 01.504-1.55l1.533-1.495-2.12-.308a1.75 1.75 0 01-1.317-.957L12 7.39z",clipRule:"evenodd"})),x=window.wp.viewport;var W=(0,l.createElement)(A.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,l.createElement)(A.Path,{d:"M12 13.06l3.712 3.713 1.061-1.06L13.061 12l3.712-3.712-1.06-1.06L12 10.938 8.288 7.227l-1.061 1.06L10.939 12l-3.712 3.712 1.06 1.061L12 13.061z"}));const T=(e,t)=>({type:"SET_DEFAULT_COMPLEMENTARY_AREA",scope:e,area:t}),L=(e,t)=>r=>{let{registry:n,dispatch:i}=r;if(!t)return;n.select(_.store).get(e,"isComplementaryAreaVisible")||n.dispatch(_.store).set(e,"isComplementaryAreaVisible",!0),i({type:"ENABLE_COMPLEMENTARY_AREA",scope:e,area:t})},P=e=>t=>{let{registry:r}=t;r.select(_.store).get(e,"isComplementaryAreaVisible")&&r.dispatch(_.store).set(e,"isComplementaryAreaVisible",!1)},R=(e,t)=>r=>{let{registry:n}=r;if(!t)return;const i=n.select(_.store).get(e,"pinnedItems");!0!==(null==i?void 0:i[t])&&n.dispatch(_.store).set(e,"pinnedItems",{...i,[t]:!0})},O=(e,t)=>r=>{let{registry:n}=r;if(!t)return;const i=n.select(_.store).get(e,"pinnedItems");n.dispatch(_.store).set(e,"pinnedItems",{...i,[t]:!1})};function M(e,t){return function(r){let{registry:n}=r;m()("dispatch( 'core/interface' ).toggleFeature",{since:"6.0",alternative:"dispatch( 'core/preferences' ).toggle"}),n.dispatch(_.store).toggle(e,t)}}function D(e,t,r){return function(n){let{registry:i}=n;m()("dispatch( 'core/interface' ).setFeatureValue",{since:"6.0",alternative:"dispatch( 'core/preferences' ).set"}),i.dispatch(_.store).set(e,t,!!r)}}function V(e,t){return function(r){let{registry:n}=r;m()("dispatch( 'core/interface' ).setFeatureDefaults",{since:"6.0",alternative:"dispatch( 'core/preferences' ).setDefaults"}),n.dispatch(_.store).setDefaults(e,t)}}const F=(0,d.createRegistrySelector)((e=>(t,r)=>{var n;const i=e(_.store).get(r,"isComplementaryAreaVisible");if(void 0!==i)return i?null==t||null===(n=t.complementaryAreas)||void 0===n?void 0:n[r]:null})),G=(0,d.createRegistrySelector)((e=>(t,r,n)=>{var i;const a=e(_.store).get(r,"pinnedItems");return null===(i=null==a?void 0:a[n])||void 0===i||i})),z=(0,d.createRegistrySelector)((e=>(t,r,n)=>(m()("select( 'core/interface' ).isFeatureActive( scope, featureName )",{since:"6.0",alternative:"select( 'core/preferences' ).get( scope, featureName )"}),!!e(_.store).get(r,n))));var H=(0,d.combineReducers)({complementaryAreas:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;switch(t.type){case"SET_DEFAULT_COMPLEMENTARY_AREA":{const{scope:r,area:n}=t;return e[r]?e:{...e,[r]:n}}case"ENABLE_COMPLEMENTARY_AREA":{const{scope:r,area:n}=t;return{...e,[r]:n}}}return e}});const U=(0,d.createReduxStore)("core/interface",{reducer:H,actions:e,selectors:t});(0,d.register)(U);var $=window.wp.plugins,j=(0,$.withPluginContext)(((e,t)=>({icon:t.icon||e.icon,identifier:t.identifier||`${e.name}/${t.name}`})));var Y=j((function(e){let{as:t=I.Button,scope:r,identifier:n,icon:i,selectedIcon:a,name:o,...s}=e;const c=t,u=(0,d.useSelect)((e=>e(U).getActiveComplementaryArea(r)===n),[n]),{enableComplementaryArea:m,disableComplementaryArea:g}=(0,d.useDispatch)(U);return(0,l.createElement)(c,y({icon:a&&u?a:i,onClick:()=>{u?g(r):m(r,n)}},s))}));var K=e=>{let{smallScreenTitle:t,children:r,className:n,toggleButtonProps:i}=e;const a=(0,l.createElement)(Y,y({icon:W},i));return(0,l.createElement)(l.Fragment,null,(0,l.createElement)("div",{className:"components-panel__header interface-complementary-area-header__small"},t&&(0,l.createElement)("span",{className:"interface-complementary-area-header__small-title"},t),a),(0,l.createElement)("div",{className:S()("components-panel__header","interface-complementary-area-header",n),tabIndex:-1},r,a))};const q=()=>{};function Q(e){let{name:t,as:r=I.Button,onClick:n,...i}=e;return(0,l.createElement)(I.Fill,{name:t},(e=>{let{onClick:t}=e;return(0,l.createElement)(r,y({onClick:n||t?function(){(n||q)(...arguments),(t||q)(...arguments)}:void 0},i))}))}Q.Slot=function(e){let{name:t,as:r=I.ButtonGroup,fillProps:n={},bubblesVirtually:i,...a}=e;return(0,l.createElement)(I.Slot,{name:t,bubblesVirtually:i,fillProps:n},(e=>{if(!l.Children.toArray(e).length)return null;const t=[];l.Children.forEach(e,(e=>{let{props:{__unstableExplicitMenuItem:r,__unstableTarget:n}}=e;n&&r&&t.push(n)}));const n=l.Children.map(e,(e=>!e.props.__unstableExplicitMenuItem&&t.includes(e.props.__unstableTarget)?null:e));return(0,l.createElement)(r,a,n)}))};var J=Q;const X=e=>{let{__unstableExplicitMenuItem:t,__unstableTarget:r,...n}=e;return(0,l.createElement)(I.MenuItem,n)};function Z(e){let{scope:t,target:r,__unstableExplicitMenuItem:n,...i}=e;return(0,l.createElement)(Y,y({as:e=>(0,l.createElement)(J,y({__unstableExplicitMenuItem:n,__unstableTarget:`${t}/${r}`,as:X,name:`${t}/plugin-more-menu`},e)),role:"menuitemcheckbox",selectedIcon:C,name:r,scope:t},i))}function ee(e){let{scope:t,...r}=e;return(0,l.createElement)(I.Fill,y({name:`PinnedItems/${t}`},r))}ee.Slot=function(e){let{scope:t,className:r,...n}=e;return(0,l.createElement)(I.Slot,y({name:`PinnedItems/${t}`},n),(e=>(null==e?void 0:e.length)>0&&(0,l.createElement)("div",{className:S()(r,"interface-pinned-items")},e)))};var te=ee;function re(e){let{scope:t,children:r,className:n}=e;return(0,l.createElement)(I.Fill,{name:`ComplementaryArea/${t}`},(0,l.createElement)("div",{className:n},r))}const ne=j((function(e){let{children:t,className:r,closeLabel:n=(0,b.__)("Close plugin"),identifier:i,header:a,headerClassName:o,icon:s,isPinnable:c=!0,panelClassName:u,scope:m,name:g,smallScreenTitle:p,title:h,toggleShortcut:_,isActiveByDefault:w,showIconLabels:f=!1}=e;const{isActive:E,isPinned:v,activeArea:y,isSmall:k,isLarge:A}=(0,d.useSelect)((e=>{const{getActiveComplementaryArea:t,isItemPinned:r}=e(U),n=t(m);return{isActive:n===i,isPinned:r(m,i),activeArea:n,isSmall:e(x.store).isViewportMatch("< medium"),isLarge:e(x.store).isViewportMatch("large")}}),[i,m]);!function(e,t,r,n,i){const a=(0,l.useRef)(!1),o=(0,l.useRef)(!1),{enableComplementaryArea:s,disableComplementaryArea:c}=(0,d.useDispatch)(U);(0,l.useEffect)((()=>{n&&i&&!a.current?(c(e),o.current=!0):o.current&&!i&&a.current?(o.current=!1,s(e,t)):o.current&&r&&r!==t&&(o.current=!1),i!==a.current&&(a.current=i)}),[n,i,e,t,r])}(m,i,y,E,k);const{enableComplementaryArea:W,disableComplementaryArea:T,pinItem:L,unpinItem:P}=(0,d.useDispatch)(U);return(0,l.useEffect)((()=>{w&&void 0===y&&!k&&W(m,i)}),[y,w,m,i,k]),(0,l.createElement)(l.Fragment,null,c&&(0,l.createElement)(te,{scope:m},v&&(0,l.createElement)(Y,{scope:m,identifier:i,isPressed:E&&(!f||A),"aria-expanded":E,label:h,icon:f?C:s,showTooltip:!f,variant:f?"tertiary":void 0})),g&&c&&(0,l.createElement)(Z,{target:g,scope:m,icon:s},h),E&&(0,l.createElement)(re,{className:S()("interface-complementary-area",r),scope:m},(0,l.createElement)(K,{className:o,closeLabel:n,onClose:()=>T(m),smallScreenTitle:p,toggleButtonProps:{label:n,shortcut:_,scope:m,identifier:i}},a||(0,l.createElement)(l.Fragment,null,(0,l.createElement)("strong",null,h),c&&(0,l.createElement)(I.Button,{className:"interface-complementary-area__pin-unpin-item",icon:v?N:B,label:v?(0,b.__)("Unpin from toolbar"):(0,b.__)("Pin to toolbar"),onClick:()=>(v?P:L)(m,i),isPressed:v,"aria-expanded":v}))),(0,l.createElement)(I.Panel,{className:u},t)))}));ne.Slot=function(e){let{scope:t,...r}=e;return(0,l.createElement)(I.Slot,y({name:`ComplementaryArea/${t}`},r))};var ie=ne,ae=window.wp.compose;function oe(e){let{children:t,className:r,ariaLabel:n,as:i="div",...a}=e;return(0,l.createElement)(i,y({className:S()("interface-navigable-region",r),"aria-label":n,role:"region",tabIndex:"-1"},a),t)}var se=(0,l.forwardRef)((function(e,t){let{isDistractionFree:r,footer:n,header:i,editorNotices:a,sidebar:o,secondarySidebar:s,notices:c,content:d,actions:u,labels:m,className:g,enableRegionNavigation:p=!0,shortcuts:h}=e;const _=(0,I.__unstableUseNavigateRegions)(h);!function(e){(0,l.useEffect)((()=>{const t=document&&document.querySelector(`html:not(.${e})`);if(t)return t.classList.toggle(e),()=>{t.classList.toggle(e)}}),[e])}("interface-interface-skeleton__html-container");const w={...{header:(0,b.__)("Header"),body:(0,b.__)("Content"),secondarySidebar:(0,b.__)("Block Library"),sidebar:(0,b.__)("Settings"),actions:(0,b.__)("Publish"),footer:(0,b.__)("Footer")},...m},f={hidden:r?{opacity:0}:{opacity:1},hover:{opacity:1,transition:{type:"tween",delay:.2,delayChildren:.2}}};return(0,l.createElement)("div",y({},p?_:{},{ref:(0,ae.useMergeRefs)([t,p?_.ref:void 0]),className:S()(g,"interface-interface-skeleton",_.className,!!n&&"has-footer")}),(0,l.createElement)("div",{className:"interface-interface-skeleton__editor"},!!i&&r&&(0,l.createElement)(oe,{as:I.__unstableMotion.div,className:"interface-interface-skeleton__header","aria-label":w.header,initial:r?"hidden":"hover",whileHover:"hover",variants:f,transition:{type:"tween",delay:.8}},i),!!i&&!r&&(0,l.createElement)(oe,{className:"interface-interface-skeleton__header",ariaLabel:w.header},i),r&&(0,l.createElement)("div",{className:"interface-interface-skeleton__header"},a),(0,l.createElement)("div",{className:"interface-interface-skeleton__body"},!!s&&(0,l.createElement)(oe,{className:"interface-interface-skeleton__secondary-sidebar",ariaLabel:w.secondarySidebar},s),!!c&&(0,l.createElement)("div",{className:"interface-interface-skeleton__notices"},c),(0,l.createElement)(oe,{className:"interface-interface-skeleton__content",ariaLabel:w.body},d),!!o&&(0,l.createElement)(oe,{className:"interface-interface-skeleton__sidebar",ariaLabel:w.sidebar},o),!!u&&(0,l.createElement)(oe,{className:"interface-interface-skeleton__actions",ariaLabel:w.actions},u))),!!n&&(0,l.createElement)(oe,{className:"interface-interface-skeleton__footer",ariaLabel:w.footer},n))}));var le=(0,l.createElement)(A.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,l.createElement)(A.Path,{d:"M13 19h-2v-2h2v2zm0-6h-2v-2h2v2zm0-6h-2V5h2v2z"}));function ce(e){let{as:t=I.DropdownMenu,className:r,label:n=(0,b.__)("Options"),popoverProps:i,toggleProps:a,children:o}=e;return(0,l.createElement)(t,{className:S()("interface-more-menu-dropdown",r),icon:le,label:n,popoverProps:{placement:"bottom-end",...i,className:S()("interface-more-menu-dropdown__content",null==i?void 0:i.className)},toggleProps:{tooltipPosition:"bottom",...a}},(e=>o(e)))}var de=window.wp.blockEditor;function ue(e){if("block"===e.id_base){const t=(0,c.parse)(e.instance.raw.content,{__unstableSkipAutop:!0});return t.length?(0,h.addWidgetIdToBlock)(t[0],e.id):(0,h.addWidgetIdToBlock)((0,c.createBlock)("core/paragraph",{},[]),e.id)}let t;return t=e._embedded.about[0].is_multi?{idBase:e.id_base,instance:e.instance}:{id:e.id},(0,h.addWidgetIdToBlock)((0,c.createBlock)("core/legacy-widget",t,[]),e.id)}function me(e){let t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n="core/legacy-widget"===e.name&&(e.attributes.id||e.attributes.instance);var i,a,o;n?t={...r,id:null!==(i=e.attributes.id)&&void 0!==i?i:r.id,id_base:null!==(a=e.attributes.idBase)&&void 0!==a?a:r.id_base,instance:null!==(o=e.attributes.instance)&&void 0!==o?o:r.instance}:t={...r,id_base:"block",instance:{raw:{content:(0,c.serialize)(e)}}};return delete t.rendered,delete t.rendered_form,t}const ge="root",pe="sidebar",he="postType",_e=e=>`widget-area-${e}`;const we="core/edit-widgets",fe=(e,t)=>r=>{let{registry:n}=r;const i=((e,t)=>({id:e,slug:e,status:"draft",type:"page",blocks:t,meta:{widgetAreaId:e}}))(e,t);return n.dispatch(p.store).receiveEntityRecords(ge,he,i,{id:i.id},!1),i},Ee=()=>async e=>{let{select:t,dispatch:r,registry:n}=e;const i=t.getEditedWidgetAreas();if(null!=i&&i.length)try{await r.saveWidgetAreas(i),n.dispatch(v.store).createSuccessNotice((0,b.__)("Widgets saved."),{type:"snackbar"})}catch(e){n.dispatch(v.store).createErrorNotice((0,b.sprintf)((0,b.__)("There was an error. %s"),e.message),{type:"snackbar"})}},be=e=>async t=>{let{dispatch:r,registry:n}=t;try{for(const t of e)await r.saveWidgetArea(t.id)}finally{await n.dispatch(p.store).finishResolution("getEntityRecord",ge,pe,{per_page:-1})}},ve=e=>async t=>{let{dispatch:r,select:n,registry:i}=t;const a=n.getWidgets(),o=i.select(p.store).getEditedEntityRecord(ge,he,_e(e)),s=Object.values(a).filter((t=>{let{sidebar:r}=t;return r===e})),l=[],c=o.blocks.filter((e=>{const{id:t}=e.attributes;if("core/legacy-widget"===e.name&&t){if(l.includes(t))return!1;l.push(t)}return!0})),d=[];for(const e of s){n.getWidgetAreaForWidgetId(e.id)||d.push(e)}const u=[],m=[],g=[];for(let t=0;t<c.length;t++){const r=c[t],n=(0,h.getWidgetIdFromBlock)(r),o=a[n],s=me(r,o);if(g.push(n),o){i.dispatch(p.store).editEntityRecord("root","widget",n,{...s,sidebar:e},{undoIgnore:!0});if(!i.select(p.store).hasEditsForEntityRecord("root","widget",n))continue;m.push((e=>{let{saveEditedEntityRecord:t}=e;return t("root","widget",n)}))}else m.push((t=>{let{saveEntityRecord:r}=t;return r("root","widget",{...s,sidebar:e})}));u.push({block:r,position:t,clientId:r.clientId})}for(const e of d)m.push((t=>{let{deleteEntityRecord:r}=t;return r("root","widget",e.id,{force:!0})}));const _=(await i.dispatch(p.store).__experimentalBatch(m)).filter((e=>!e.hasOwnProperty("deleted"))),w=[];for(let e=0;e<_.length;e++){const t=_[e],{block:r,position:n}=u[e];o.blocks[n].attributes.__internalWidgetId=t.id;var f;if(i.select(p.store).getLastEntitySaveError("root","widget",t.id))w.push((null===(f=r.attributes)||void 0===f?void 0:f.name)||(null==r?void 0:r.name));g[n]||(g[n]=t.id)}if(w.length)throw new Error((0,b.sprintf)((0,b.__)("Could not save the following widgets: %s."),w.join(", ")));i.dispatch(p.store).editEntityRecord(ge,pe,e,{widgets:g},{undoIgnore:!0}),r(ye(e)),i.dispatch(p.store).receiveEntityRecords(ge,he,o,void 0)},ye=e=>t=>{let{registry:r}=t;r.dispatch(p.store).saveEditedEntityRecord(ge,pe,e,{throwOnError:!0})};function ke(e,t){return{type:"SET_WIDGET_ID_FOR_CLIENT_ID",clientId:e,widgetId:t}}function Se(e){return{type:"SET_WIDGET_AREAS_OPEN_STATE",widgetAreasOpenState:e}}function Ie(e,t){return{type:"SET_IS_WIDGET_AREA_OPEN",clientId:e,isOpen:t}}function Ae(e){return{type:"SET_IS_INSERTER_OPENED",value:e}}function Ce(e){return{type:"SET_IS_LIST_VIEW_OPENED",isOpen:e}}const Ne=()=>e=>{let{registry:t}=e;t.dispatch(U).disableComplementaryArea(we)},Be=(e,t)=>async r=>{let{dispatch:n,select:i,registry:a}=r;const o=a.select(de.store).getBlockRootClientId(e),s=a.select(de.store).getBlocks().find((e=>{let{attributes:r}=e;return r.id===t})).clientId,l=a.select(de.store).getBlockOrder(s).length;i.getIsWidgetAreaOpen(s)||n.setIsWidgetAreaOpen(s,!0),a.dispatch(de.store).moveBlocksToPosition([e],o,s,l)},xe=()=>async e=>{let{dispatch:t,registry:r}=e;const n={per_page:-1},i=[],a=(await r.resolveSelect(p.store).getEntityRecords(ge,pe,n)).sort(((e,t)=>"wp_inactive_widgets"===e.id?1:"wp_inactive_widgets"===t.id?-1:0));for(const e of a)i.push((0,c.createBlock)("core/widget-area",{id:e.id,name:e.name})),e.widgets.length||t(fe(_e(e.id),[]));const o={};i.forEach(((e,t)=>{o[e.clientId]=0===t})),t(Se(o)),t(fe("widget-areas",i))},We=()=>async e=>{let{dispatch:t,registry:r}=e;const n={per_page:-1,_embed:"about"},i=await r.resolveSelect(p.store).getEntityRecords("root","widget",n),a={};for(const e of i){const t=ue(e);a[e.sidebar]=a[e.sidebar]||[],a[e.sidebar].push(t)}for(const e in a)a.hasOwnProperty(e)&&t(fe(_e(e),a[e]))},Te=(0,d.createRegistrySelector)((e=>()=>{const t=e(p.store).getEntityRecords("root","widget",{per_page:-1,_embed:"about"});return(null==t?void 0:t.reduce(((e,t)=>({...e,[t.id]:t})),{}))||{}})),Le=(0,d.createRegistrySelector)((e=>(t,r)=>e(we).getWidgets()[r])),Pe=(0,d.createRegistrySelector)((e=>()=>{const t={per_page:-1};return e(p.store).getEntityRecords(ge,pe,t)})),Re=(0,d.createRegistrySelector)((e=>(t,r)=>e(we).getWidgetAreas().find((t=>e(p.store).getEditedEntityRecord(ge,he,_e(t.id)).blocks.map((e=>(0,h.getWidgetIdFromBlock)(e))).includes(r))))),Oe=(0,d.createRegistrySelector)((e=>(t,r)=>{const{getBlock:n,getBlockName:i,getBlockParents:a}=e(de.store);return n(a(r).find((e=>"core/widget-area"===i(e))))})),Me=(0,d.createRegistrySelector)((e=>(t,r)=>{let n=e(we).getWidgetAreas();return n?(r&&(n=n.filter((e=>{let{id:t}=e;return r.includes(t)}))),n.filter((t=>{let{id:r}=t;return e(p.store).hasEditsForEntityRecord(ge,he,_e(r))})).map((t=>{let{id:r}=t;return e(p.store).getEditedEntityRecord(ge,pe,r)}))):[]})),De=(0,d.createRegistrySelector)((e=>function(t){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;const n=[],i=e(we).getWidgetAreas();for(const t of i){const i=e(p.store).getEditedEntityRecord(ge,he,_e(t.id));for(const e of i.blocks){var a;"core/legacy-widget"!==e.name||r&&(null===(a=e.attributes)||void 0===a?void 0:a.referenceWidgetName)!==r||n.push(e)}}return n})),Ve=(0,d.createRegistrySelector)((e=>()=>{var t;const r=null===(t=e(we).getWidgetAreas())||void 0===t?void 0:t.map((e=>{let{id:t}=e;return t}));if(!r)return!1;for(const t of r){if(e(p.store).isSavingEntityRecord(ge,pe,t))return!0}const n=[...Object.keys(e(we).getWidgets()),void 0];for(const t of n){if(e(p.store).isSavingEntityRecord("root","widget",t))return!0}return!1})),Fe=(e,t)=>{const{widgetAreasOpenState:r}=e;return!!r[t]};function Ge(e){return!!e.blockInserterPanel}function ze(e){const{rootClientId:t,insertionIndex:r}=e.blockInserterPanel;return{rootClientId:t,insertionIndex:r}}const He=(0,d.createRegistrySelector)((e=>(t,r)=>{const n=e(de.store).getBlocks(),[i]=n;return e(de.store).canInsertBlockType(r,i.clientId)}));function Ue(e){return e.listViewPanel}const $e={reducer:E,selectors:o,resolvers:a,actions:i},je=(0,d.createReduxStore)(we,$e);(0,d.register)(je),f().use((function(e,t){var r;return 0===(null===(r=e.path)||void 0===r?void 0:r.indexOf("/wp/v2/types/widget-area"))?Promise.resolve({}):t(e)}));var Ye=window.wp.hooks;const Ke=(0,ae.createHigherOrderComponent)((e=>t=>{const{clientId:r,name:n}=t,{widgetAreas:i,currentWidgetAreaId:a,canInsertBlockInWidgetArea:o}=(0,d.useSelect)((e=>{var t;if("core/widget-area"===n)return{};const i=e(je),a=i.getParentWidgetAreaBlock(r);return{widgetAreas:i.getWidgetAreas(),currentWidgetAreaId:null==a||null===(t=a.attributes)||void 0===t?void 0:t.id,canInsertBlockInWidgetArea:i.canInsertBlockInWidgetArea(n)}}),[r,n]),{moveBlockToWidgetArea:s}=(0,d.useDispatch)(je),c=(null==i?void 0:i.length)>1,u="core/widget-area"!==n&&c&&o;return(0,l.createElement)(l.Fragment,null,(0,l.createElement)(e,t),u&&(0,l.createElement)(de.BlockControls,null,(0,l.createElement)(h.MoveToWidgetArea,{widgetAreas:i,currentWidgetAreaId:a,onSelect:e=>{s(t.clientId,e)}})))}),"withMoveToWidgetAreaToolbarItem");(0,Ye.addFilter)("editor.BlockEdit","core/edit-widgets/block-edit",Ke);var qe=window.wp.mediaUtils;(0,Ye.addFilter)("editor.MediaUpload","core/edit-widgets/replace-media-upload",(()=>qe.MediaUpload));var Qe=e=>{const[t,r]=(0,l.useState)(!1);return(0,l.useEffect)((()=>{const{ownerDocument:t}=e.current;function n(e){a(e)}function i(){r(!1)}function a(t){e.current.contains(t.target)?r(!0):r(!1)}return t.addEventListener("dragstart",n),t.addEventListener("dragend",i),t.addEventListener("dragenter",a),()=>{t.removeEventListener("dragstart",n),t.removeEventListener("dragend",i),t.removeEventListener("dragenter",a)}}),[]),t};function Je(e){let{id:t}=e;const[r,n,i]=(0,p.useEntityBlockEditor)("root","postType"),a=(0,l.useRef)(),o=Qe(a),s=(0,de.useInnerBlocksProps)({ref:a},{value:r,onInput:n,onChange:i,templateLock:!1,renderAppender:de.InnerBlocks.ButtonBlockAppender});return(0,l.createElement)("div",{"data-widget-area-id":t,className:S()("wp-block-widget-area__inner-blocks block-editor-inner-blocks editor-styles-wrapper",{"wp-block-widget-area__highlight-drop-zone":o})},(0,l.createElement)("div",s))}const Xe=e=>{const[t,r]=(0,l.useState)(!1);return(0,l.useEffect)((()=>{const{ownerDocument:t}=e.current;function n(){r(!0)}function i(){r(!1)}return t.addEventListener("dragstart",n),t.addEventListener("dragend",i),()=>{t.removeEventListener("dragstart",n),t.removeEventListener("dragend",i)}}),[]),t},Ze={name:"core/widget-area",category:"widgets",attributes:{id:{type:"string"},name:{type:"string"}},supports:{html:!1,inserter:!1,customClassName:!1,reusable:!1,__experimentalToolbar:!1,__experimentalParentSelector:!1,__experimentalDisableBlockOverlay:!0},editorStyle:"wp-block-widget-area-editor",style:"wp-block-widget-area"},{name:et}=Ze,tt={title:(0,b.__)("Widget Area"),description:(0,b.__)("A widget area container."),__experimentalLabel:e=>{let{name:t}=e;return t},edit:function(e){let{clientId:t,className:r,attributes:{id:n,name:i}}=e;const a=(0,d.useSelect)((e=>e(je).getIsWidgetAreaOpen(t)),[t]),{setIsWidgetAreaOpen:o}=(0,d.useDispatch)(je),s=(0,l.useRef)(),c=(0,l.useCallback)((e=>o(t,e)),[t]),u=Xe(s),m=Qe(s),[g,h]=(0,l.useState)(!1);return(0,l.useEffect)((()=>{u?m&&!a?(c(!0),h(!0)):!m&&a&&g&&c(!1):h(!1)}),[a,u,m,g]),(0,l.createElement)(I.Panel,{className:r,ref:s},(0,l.createElement)(I.PanelBody,{title:i,opened:a,onToggle:()=>{o(t,!a)},scrollAfterOpen:!u},(e=>{let{opened:t}=e;return(0,l.createElement)(I.__unstableDisclosureContent,{className:"wp-block-widget-area__panel-body-content",visible:t},(0,l.createElement)(p.EntityProvider,{kind:"root",type:"postType",id:`widget-area-${n}`},(0,l.createElement)(Je,{id:n})))})))}};function rt(e){let{text:t,children:r}=e;const n=(0,ae.useCopyToClipboard)(t);return(0,l.createElement)(I.Button,{variant:"secondary",ref:n},r)}function nt(e){let{message:t,error:r}=e;const n=[(0,l.createElement)(rt,{key:"copy-error",text:r.stack},(0,b.__)("Copy Error"))];return(0,l.createElement)(de.Warning,{className:"edit-widgets-error-boundary",actions:n},t)}class it extends l.Component{constructor(){super(...arguments),this.state={error:null}}componentDidCatch(e){(0,Ye.doAction)("editor.ErrorBoundary.errorLogged",e)}static getDerivedStateFromError(e){return{error:e}}render(){return this.state.error?(0,l.createElement)(nt,{message:(0,b.__)("The editor has encountered an unexpected error."),error:this.state.error}):this.props.children}}var at=window.wp.reusableBlocks,ot=window.wp.keyboardShortcuts,st=window.wp.keycodes;function lt(){const{redo:e,undo:t}=(0,d.useDispatch)(p.store),{saveEditedWidgetAreas:r}=(0,d.useDispatch)(je);return(0,ot.useShortcut)("core/edit-widgets/undo",(e=>{t(),e.preventDefault()})),(0,ot.useShortcut)("core/edit-widgets/redo",(t=>{e(),t.preventDefault()})),(0,ot.useShortcut)("core/edit-widgets/save",(e=>{e.preventDefault(),r()})),null}lt.Register=function(){const{registerShortcut:e}=(0,d.useDispatch)(ot.store);return(0,l.useEffect)((()=>{e({name:"core/edit-widgets/undo",category:"global",description:(0,b.__)("Undo your last changes."),keyCombination:{modifier:"primary",character:"z"}}),e({name:"core/edit-widgets/redo",category:"global",description:(0,b.__)("Redo your last undo."),keyCombination:{modifier:"primaryShift",character:"z"},aliases:(0,st.isAppleOS)()?[]:[{modifier:"primary",character:"y"}]}),e({name:"core/edit-widgets/save",category:"global",description:(0,b.__)("Save your changes."),keyCombination:{modifier:"primary",character:"s"}}),e({name:"core/edit-widgets/keyboard-shortcuts",category:"main",description:(0,b.__)("Display these keyboard shortcuts."),keyCombination:{modifier:"access",character:"h"}}),e({name:"core/edit-widgets/next-region",category:"global",description:(0,b.__)("Navigate to the next part of the editor."),keyCombination:{modifier:"ctrl",character:"`"},aliases:[{modifier:"access",character:"n"}]}),e({name:"core/edit-widgets/previous-region",category:"global",description:(0,b.__)("Navigate to the previous part of the editor."),keyCombination:{modifier:"ctrlShift",character:"`"},aliases:[{modifier:"access",character:"p"},{modifier:"ctrlShift",character:"~"}]})}),[e]),null};var ct=lt;var dt=()=>(0,d.useSelect)((e=>{var t;const{getBlockSelectionEnd:r,getBlockName:n}=e(de.store),i=r();if("core/widget-area"===n(i))return i;const{getParentWidgetAreaBlock:a}=e(je),o=a(i),s=null==o?void 0:o.clientId;if(s)return s;const{getEntityRecord:l}=e(p.store),c=l(ge,he,"widget-areas");return null==c||null===(t=c.blocks[0])||void 0===t?void 0:t.clientId}),[]);var ut=window.wp.privateApis;const{lock:mt,unlock:gt}=(0,ut.__dangerousOptInToUnstableAPIsOnlyForCoreModules)("I know using unstable features means my plugin or theme will inevitably break on the next WordPress release.","@wordpress/edit-widgets"),{ExperimentalBlockEditorProvider:pt}=gt(de.privateApis);function ht(e){let{blockEditorSettings:t,children:r,...n}=e;const i=(0,p.useResourcePermissions)("media"),{reusableBlocks:a,isFixedToolbarActive:o,keepCaretInsideBlock:s}=(0,d.useSelect)((e=>({widgetAreas:e(je).getWidgetAreas(),widgets:e(je).getWidgets(),reusableBlocks:[],isFixedToolbarActive:!!e(_.store).get("core/edit-widgets","fixedToolbar"),keepCaretInsideBlock:!!e(_.store).get("core/edit-widgets","keepCaretInsideBlock")})),[]),{setIsInserterOpened:c}=(0,d.useDispatch)(je),u=(0,l.useMemo)((()=>{let e;return i.canCreate&&(e=e=>{let{onError:r,...n}=e;(0,qe.uploadMedia)({wpAllowedMimeTypes:t.allowedMimeTypes,onError:e=>{let{message:t}=e;return r(t)},...n})}),{...t,__experimentalReusableBlocks:a,hasFixedToolbar:o,keepCaretInsideBlock:s,mediaUpload:e,templateLock:"all",__experimentalSetIsInserterOpened:c}}),[t,o,s,i.canCreate,a,c]),m=dt(),[g,h,w]=(0,p.useEntityBlockEditor)(ge,he,{id:"widget-areas"});return(0,l.createElement)(ot.ShortcutProvider,null,(0,l.createElement)(de.BlockEditorKeyboardShortcuts.Register,null),(0,l.createElement)(ct.Register,null),(0,l.createElement)(I.SlotFillProvider,null,(0,l.createElement)(pt,y({value:g,onInput:h,onChange:w,settings:u,useSubRegistry:!1},n),(0,l.createElement)(de.CopyHandler,null,r),(0,l.createElement)(at.ReusableBlocksMenuItems,{rootClientId:m}))))}var _t=(0,l.createElement)(A.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,l.createElement)(A.Path,{fillRule:"evenodd",d:"M10.289 4.836A1 1 0 0111.275 4h1.306a1 1 0 01.987.836l.244 1.466c.787.26 1.503.679 2.108 1.218l1.393-.522a1 1 0 011.216.437l.653 1.13a1 1 0 01-.23 1.273l-1.148.944a6.025 6.025 0 010 2.435l1.149.946a1 1 0 01.23 1.272l-.653 1.13a1 1 0 01-1.216.437l-1.394-.522c-.605.54-1.32.958-2.108 1.218l-.244 1.466a1 1 0 01-.987.836h-1.306a1 1 0 01-.986-.836l-.244-1.466a5.995 5.995 0 01-2.108-1.218l-1.394.522a1 1 0 01-1.217-.436l-.653-1.131a1 1 0 01.23-1.272l1.149-.946a6.026 6.026 0 010-2.435l-1.148-.944a1 1 0 01-.23-1.272l.653-1.131a1 1 0 011.217-.437l1.393.522a5.994 5.994 0 012.108-1.218l.244-1.466zM14.929 12a3 3 0 11-6 0 3 3 0 016 0z",clipRule:"evenodd"}));var wt=(0,l.createElement)(A.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,l.createElement)(A.Path,{d:"M19 8h-1V6h-5v2h-2V6H6v2H5c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-8c0-1.1-.9-2-2-2zm.5 10c0 .3-.2.5-.5.5H5c-.3 0-.5-.2-.5-.5v-8c0-.3.2-.5.5-.5h14c.3 0 .5.2.5.5v8z"})),ft=window.wp.url,Et=window.wp.dom;function bt(e){let{selectedWidgetAreaId:t}=e;const r=(0,d.useSelect)((e=>e(je).getWidgetAreas()),[]),n=(0,l.useMemo)((()=>t&&(null==r?void 0:r.find((e=>e.id===t)))),[t,r]);let i;return i=n?"wp_inactive_widgets"===t?(0,b.__)("Blocks in this Widget Area will not be displayed in your site."):n.description:(0,b.__)("Widget Areas are global parts in your site’s layout that can accept blocks. These vary by theme, but are typically parts like your Sidebar or Footer."),(0,l.createElement)("div",{className:"edit-widgets-widget-areas"},(0,l.createElement)("div",{className:"edit-widgets-widget-areas__top-container"},(0,l.createElement)(de.BlockIcon,{icon:wt}),(0,l.createElement)("div",null,(0,l.createElement)("p",{dangerouslySetInnerHTML:{__html:(0,Et.safeHTML)(i)}}),0===(null==r?void 0:r.length)&&(0,l.createElement)("p",null,(0,b.__)("Your theme does not contain any Widget Areas.")),!n&&(0,l.createElement)(I.Button,{href:(0,ft.addQueryArgs)("customize.php",{"autofocus[panel]":"widgets",return:window.location.pathname}),variant:"tertiary"},(0,b.__)("Manage with live preview")))))}const vt=l.Platform.select({web:!0,native:!1}),yt="edit-widgets/block-inspector",kt="edit-widgets/block-areas";function St(e){let{identifier:t,label:r,isActive:n}=e;const{enableComplementaryArea:i}=(0,d.useDispatch)(U);return(0,l.createElement)(I.Button,{onClick:()=>i(je.name,t),className:S()("edit-widgets-sidebar__panel-tab",{"is-active":n}),"aria-label":n?(0,b.sprintf)((0,b.__)("%s (selected)"),r):r,"data-label":r},r)}function It(){const{enableComplementaryArea:e}=(0,d.useDispatch)(U),{currentArea:t,hasSelectedNonAreaBlock:r,isGeneralSidebarOpen:n,selectedWidgetAreaBlock:i}=(0,d.useSelect)((e=>{const{getSelectedBlock:t,getBlock:r,getBlockParentsByBlockName:n}=e(de.store),{getActiveComplementaryArea:i}=e(U),a=t(),o=i(je.name);let s,l=o;return l||(l=a?yt:kt),a&&(s="core/widget-area"===a.name?a:r(n(a.clientId,"core/widget-area")[0])),{currentArea:l,hasSelectedNonAreaBlock:!(!a||"core/widget-area"===a.name),isGeneralSidebarOpen:!!o,selectedWidgetAreaBlock:s}}),[]);return(0,l.useEffect)((()=>{r&&t===kt&&n&&e("core/edit-widgets",yt),!r&&t===yt&&n&&e("core/edit-widgets",kt)}),[r,e]),(0,l.createElement)(ie,{className:"edit-widgets-sidebar",header:(0,l.createElement)("ul",null,(0,l.createElement)("li",null,(0,l.createElement)(St,{identifier:kt,label:i?i.attributes.name:(0,b.__)("Widget Areas"),isActive:t===kt})),(0,l.createElement)("li",null,(0,l.createElement)(St,{identifier:yt,label:(0,b.__)("Block"),isActive:t===yt}))),headerClassName:"edit-widgets-sidebar__panel-tabs",title:(0,b.__)("Settings"),closeLabel:(0,b.__)("Close settings"),scope:"core/edit-widgets",identifier:t,icon:_t,isActiveByDefault:vt},t===kt&&(0,l.createElement)(bt,{selectedWidgetAreaId:null==i?void 0:i.attributes.id}),t===yt&&(r?(0,l.createElement)(de.BlockInspector,null):(0,l.createElement)("span",{className:"block-editor-block-inspector__no-blocks"},(0,b.__)("No block selected."))))}var At=(0,l.createElement)(A.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,l.createElement)(A.Path,{d:"M18 11.2h-5.2V6h-1.6v5.2H6v1.6h5.2V18h1.6v-5.2H18z"}));var Ct=(0,l.createElement)(A.SVG,{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},(0,l.createElement)(A.Path,{d:"M13.8 5.2H3v1.5h10.8V5.2zm-3.6 12v1.5H21v-1.5H10.2zm7.2-6H6.6v1.5h10.8v-1.5z"}));var Nt=function(){const{hasEditedWidgetAreaIds:e,isSaving:t}=(0,d.useSelect)((e=>{var t;const{getEditedWidgetAreas:r,isSavingWidgetAreas:n}=e(je);return{hasEditedWidgetAreaIds:(null===(t=r())||void 0===t?void 0:t.length)>0,isSaving:n()}}),[]),{saveEditedWidgetAreas:r}=(0,d.useDispatch)(je);return(0,l.createElement)(I.Button,{variant:"primary",isBusy:t,"aria-disabled":t,onClick:t?void 0:r,disabled:!e},t?(0,b.__)("Saving…"):(0,b.__)("Update"))};var Bt=(0,l.createElement)(A.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,l.createElement)(A.Path,{d:"M18.3 11.7c-.6-.6-1.4-.9-2.3-.9H6.7l2.9-3.3-1.1-1-4.5 5L8.5 16l1-1-2.7-2.7H16c.5 0 .9.2 1.3.5 1 1 1 3.4 1 4.5v.3h1.5v-.2c0-1.5 0-4.3-1.5-5.7z"}));var xt=(0,l.createElement)(A.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,l.createElement)(A.Path,{d:"M15.6 6.5l-1.1 1 2.9 3.3H8c-.9 0-1.7.3-2.3.9-1.4 1.5-1.4 4.2-1.4 5.6v.2h1.5v-.3c0-1.1 0-3.5 1-4.5.3-.3.7-.5 1.3-.5h9.2L14.5 15l1.1 1.1 4.6-4.6-4.6-5z"}));function Wt(){const e=(0,d.useSelect)((e=>e(p.store).hasUndo()),[]),{undo:t}=(0,d.useDispatch)(p.store);return(0,l.createElement)(I.ToolbarButton,{icon:(0,b.isRTL)()?xt:Bt,label:(0,b.__)("Undo"),shortcut:st.displayShortcut.primary("z"),"aria-disabled":!e,onClick:e?t:void 0})}function Tt(){const e=(0,st.isAppleOS)()?st.displayShortcut.primaryShift("z"):st.displayShortcut.primary("y"),t=(0,d.useSelect)((e=>e(p.store).hasRedo()),[]),{redo:r}=(0,d.useDispatch)(p.store);return(0,l.createElement)(I.ToolbarButton,{icon:(0,b.isRTL)()?Bt:xt,label:(0,b.__)("Redo"),shortcut:e,"aria-disabled":!t,onClick:t?r:void 0})}var Lt=(0,l.createElement)(A.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,l.createElement)(A.Path,{d:"M18.2 17c0 .7-.6 1.2-1.2 1.2H7c-.7 0-1.2-.6-1.2-1.2V7c0-.7.6-1.2 1.2-1.2h3.2V4.2H7C5.5 4.2 4.2 5.5 4.2 7v10c0 1.5 1.2 2.8 2.8 2.8h10c1.5 0 2.8-1.2 2.8-2.8v-3.6h-1.5V17zM14.9 3v1.5h3.7l-6.4 6.4 1.1 1.1 6.4-6.4v3.7h1.5V3h-6.3z"}));const Pt=[{keyCombination:{modifier:"primary",character:"b"},description:(0,b.__)("Make the selected text bold.")},{keyCombination:{modifier:"primary",character:"i"},description:(0,b.__)("Make the selected text italic.")},{keyCombination:{modifier:"primary",character:"k"},description:(0,b.__)("Convert the selected text into a link.")},{keyCombination:{modifier:"primaryShift",character:"k"},description:(0,b.__)("Remove a link.")},{keyCombination:{character:"[["},description:(0,b.__)("Insert a link to a post or page.")},{keyCombination:{modifier:"primary",character:"u"},description:(0,b.__)("Underline the selected text.")},{keyCombination:{modifier:"access",character:"d"},description:(0,b.__)("Strikethrough the selected text.")},{keyCombination:{modifier:"access",character:"x"},description:(0,b.__)("Make the selected text inline code.")}];function Rt(e){let{keyCombination:t,forceAriaLabel:r}=e;const n=t.modifier?st.displayShortcutList[t.modifier](t.character):t.character,i=t.modifier?st.shortcutAriaLabel[t.modifier](t.character):t.character,a=Array.isArray(n)?n:[n];return(0,l.createElement)("kbd",{className:"edit-widgets-keyboard-shortcut-help-modal__shortcut-key-combination","aria-label":r||i},a.map(((e,t)=>"+"===e?(0,l.createElement)(l.Fragment,{key:t},e):(0,l.createElement)("kbd",{key:t,className:"edit-widgets-keyboard-shortcut-help-modal__shortcut-key"},e))))}var Ot=function(e){let{description:t,keyCombination:r,aliases:n=[],ariaLabel:i}=e;return(0,l.createElement)(l.Fragment,null,(0,l.createElement)("div",{className:"edit-widgets-keyboard-shortcut-help-modal__shortcut-description"},t),(0,l.createElement)("div",{className:"edit-widgets-keyboard-shortcut-help-modal__shortcut-term"},(0,l.createElement)(Rt,{keyCombination:r,forceAriaLabel:i}),n.map(((e,t)=>(0,l.createElement)(Rt,{keyCombination:e,forceAriaLabel:i,key:t})))))};var Mt=function(e){let{name:t}=e;const{keyCombination:r,description:n,aliases:i}=(0,d.useSelect)((e=>{const{getShortcutKeyCombination:r,getShortcutDescription:n,getShortcutAliases:i}=e(ot.store);return{keyCombination:r(t),aliases:i(t),description:n(t)}}),[t]);return r?(0,l.createElement)(Ot,{keyCombination:r,description:n,aliases:i}):null};const Dt=e=>{let{shortcuts:t}=e;return(0,l.createElement)("ul",{className:"edit-widgets-keyboard-shortcut-help-modal__shortcut-list",role:"list"},t.map(((e,t)=>(0,l.createElement)("li",{className:"edit-widgets-keyboard-shortcut-help-modal__shortcut",key:t},"string"==typeof e?(0,l.createElement)(Mt,{name:e}):(0,l.createElement)(Ot,e)))))},Vt=e=>{let{title:t,shortcuts:r,className:n}=e;return(0,l.createElement)("section",{className:S()("edit-widgets-keyboard-shortcut-help-modal__section",n)},!!t&&(0,l.createElement)("h2",{className:"edit-widgets-keyboard-shortcut-help-modal__section-title"},t),(0,l.createElement)(Dt,{shortcuts:r}))},Ft=e=>{let{title:t,categoryName:r,additionalShortcuts:n=[]}=e;const i=(0,d.useSelect)((e=>e(ot.store).getCategoryShortcuts(r)),[r]);return(0,l.createElement)(Vt,{title:t,shortcuts:i.concat(n)})};function Gt(e){let{isModalActive:t,toggleModal:r}=e;return(0,ot.useShortcut)("core/edit-widgets/keyboard-shortcuts",r,{bindGlobal:!0}),t?(0,l.createElement)(I.Modal,{className:"edit-widgets-keyboard-shortcut-help-modal",title:(0,b.__)("Keyboard shortcuts"),onRequestClose:r},(0,l.createElement)(Vt,{className:"edit-widgets-keyboard-shortcut-help-modal__main-shortcuts",shortcuts:["core/edit-widgets/keyboard-shortcuts"]}),(0,l.createElement)(Ft,{title:(0,b.__)("Global shortcuts"),categoryName:"global"}),(0,l.createElement)(Ft,{title:(0,b.__)("Selection shortcuts"),categoryName:"selection"}),(0,l.createElement)(Ft,{title:(0,b.__)("Block shortcuts"),categoryName:"block",additionalShortcuts:[{keyCombination:{character:"/"},description:(0,b.__)("Change the block type after adding a new paragraph."),ariaLabel:(0,b.__)("Forward-slash")}]}),(0,l.createElement)(Vt,{title:(0,b.__)("Text formatting"),shortcuts:Pt})):null}const{Fill:zt,Slot:Ht}=(0,I.createSlotFill)("EditWidgetsToolsMoreMenuGroup");zt.Slot=e=>{let{fillProps:t}=e;return(0,l.createElement)(Ht,{fillProps:t},(e=>e.length>0&&e))};var Ut=zt;function $t(){const[e,t]=(0,l.useState)(!1),r=()=>t(!e);(0,ot.useShortcut)("core/edit-widgets/keyboard-shortcuts",r);const n=(0,ae.useViewportMatch)("medium");return(0,l.createElement)(l.Fragment,null,(0,l.createElement)(ce,null,(e=>(0,l.createElement)(l.Fragment,null,n&&(0,l.createElement)(I.MenuGroup,{label:(0,b._x)("View","noun")},(0,l.createElement)(_.PreferenceToggleMenuItem,{scope:"core/edit-widgets",name:"fixedToolbar",label:(0,b.__)("Top toolbar"),info:(0,b.__)("Access all block and document tools in a single place"),messageActivated:(0,b.__)("Top toolbar activated"),messageDeactivated:(0,b.__)("Top toolbar deactivated")})),(0,l.createElement)(I.MenuGroup,{label:(0,b.__)("Tools")},(0,l.createElement)(I.MenuItem,{onClick:()=>{t(!0)},shortcut:st.displayShortcut.access("h")},(0,b.__)("Keyboard shortcuts")),(0,l.createElement)(_.PreferenceToggleMenuItem,{scope:"core/edit-widgets",name:"welcomeGuide",label:(0,b.__)("Welcome Guide")}),(0,l.createElement)(I.MenuItem,{role:"menuitem",icon:Lt,href:(0,b.__)("https://wordpress.org/support/article/block-based-widgets-editor/"),target:"_blank",rel:"noopener noreferrer"},(0,b.__)("Help"),(0,l.createElement)(I.VisuallyHidden,{as:"span"},(0,b.__)("(opens in a new tab)"))),(0,l.createElement)(Ut.Slot,{fillProps:{onClose:e}})),(0,l.createElement)(I.MenuGroup,{label:(0,b.__)("Preferences")},(0,l.createElement)(_.PreferenceToggleMenuItem,{scope:"core/edit-widgets",name:"keepCaretInsideBlock",label:(0,b.__)("Contain text cursor inside block"),info:(0,b.__)("Aids screen readers by stopping text caret from leaving blocks."),messageActivated:(0,b.__)("Contain text cursor inside block activated"),messageDeactivated:(0,b.__)("Contain text cursor inside block deactivated")}),(0,l.createElement)(_.PreferenceToggleMenuItem,{scope:"core/edit-widgets",name:"themeStyles",info:(0,b.__)("Make the editor look like your theme."),label:(0,b.__)("Use theme styles")}),n&&(0,l.createElement)(_.PreferenceToggleMenuItem,{scope:"core/edit-widgets",name:"showBlockBreadcrumbs",label:(0,b.__)("Display block breadcrumbs"),info:(0,b.__)("Shows block breadcrumbs at the bottom of the editor."),messageActivated:(0,b.__)("Display block breadcrumbs activated"),messageDeactivated:(0,b.__)("Display block breadcrumbs deactivated")}))))),(0,l.createElement)(Gt,{isModalActive:e,toggleModal:r}))}var jt=function(){const e=(0,ae.useViewportMatch)("medium"),t=(0,l.useRef)(),r=dt(),n=(0,d.useSelect)((e=>e(je).getIsWidgetAreaOpen(r)),[r]),{isInserterOpen:i,isListViewOpen:a}=(0,d.useSelect)((e=>{const{isInserterOpened:t,isListViewOpened:r}=e(je);return{isInserterOpen:t(),isListViewOpen:r()}}),[]),{setIsWidgetAreaOpen:o,setIsInserterOpened:s,setIsListViewOpened:c}=(0,d.useDispatch)(je),{selectBlock:u}=(0,d.useDispatch)(de.store),m=(0,l.useCallback)((()=>c(!a)),[c,a]);return(0,l.createElement)(l.Fragment,null,(0,l.createElement)("div",{className:"edit-widgets-header"},(0,l.createElement)("div",{className:"edit-widgets-header__navigable-toolbar-wrapper"},e&&(0,l.createElement)("h1",{className:"edit-widgets-header__title"},(0,b.__)("Widgets")),!e&&(0,l.createElement)(I.VisuallyHidden,{as:"h1",className:"edit-widgets-header__title"},(0,b.__)("Widgets")),(0,l.createElement)(de.NavigableToolbar,{className:"edit-widgets-header-toolbar","aria-label":(0,b.__)("Document tools")},(0,l.createElement)(I.ToolbarItem,{ref:t,as:I.Button,className:"edit-widgets-header-toolbar__inserter-toggle",variant:"primary",isPressed:i,onMouseDown:e=>{e.preventDefault()},onClick:()=>{i?s(!1):(n||(u(r),o(r,!0)),window.requestAnimationFrame((()=>s(!0))))},icon:At,label:(0,b._x)("Toggle block inserter","Generic label for block inserter button")}),e&&(0,l.createElement)(l.Fragment,null,(0,l.createElement)(Wt,null),(0,l.createElement)(Tt,null),(0,l.createElement)(I.ToolbarItem,{as:I.Button,className:"edit-widgets-header-toolbar__list-view-toggle",icon:Ct,isPressed:a,label:(0,b.__)("List View"),onClick:m})))),(0,l.createElement)("div",{className:"edit-widgets-header__actions"},(0,l.createElement)(Nt,null),(0,l.createElement)(te.Slot,{scope:"core/edit-widgets"}),(0,l.createElement)($t,null))))};var Yt=function(){const{removeNotice:e}=(0,d.useDispatch)(v.store),{notices:t}=(0,d.useSelect)((e=>({notices:e(v.store).getNotices()})),[]),r=t.filter((e=>{let{isDismissible:t,type:r}=e;return t&&"default"===r})),n=t.filter((e=>{let{isDismissible:t,type:r}=e;return!t&&"default"===r})),i=t.filter((e=>{let{type:t}=e;return"snackbar"===t}));return(0,l.createElement)(l.Fragment,null,(0,l.createElement)(I.NoticeList,{notices:n,className:"edit-widgets-notices__pinned"}),(0,l.createElement)(I.NoticeList,{notices:r,className:"edit-widgets-notices__dismissible",onRemove:e}),(0,l.createElement)(I.SnackbarList,{notices:i,className:"edit-widgets-notices__snackbar",onRemove:e}))};function Kt(e){let{blockEditorSettings:t}=e;const r=(0,d.useSelect)((e=>!!e(_.store).get("core/edit-widgets","themeStyles")),[]),n=(0,l.useMemo)((()=>r?t.styles:[]),[t,r]);return(0,l.createElement)("div",{className:"edit-widgets-block-editor"},(0,l.createElement)(Yt,null),(0,l.createElement)(de.BlockTools,null,(0,l.createElement)(ct,null),(0,l.createElement)(de.__unstableEditorStyles,{styles:n}),(0,l.createElement)(de.BlockSelectionClearer,null,(0,l.createElement)(de.WritingFlow,null,(0,l.createElement)(de.ObserveTyping,null,(0,l.createElement)(de.BlockList,{className:"edit-widgets-main-block-list"}))))))}var qt=(0,l.createElement)(A.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,l.createElement)(A.Path,{d:"M13 11.8l6.1-6.3-1-1-6.1 6.2-6.1-6.2-1 1 6.1 6.3-6.5 6.7 1 1 6.5-6.6 6.5 6.6 1-1z"}));var Qt=()=>{const e=(0,d.useSelect)((e=>{var t;const{getEntityRecord:r}=e(p.store),n=r(ge,he,"widget-areas");return null==n||null===(t=n.blocks[0])||void 0===t?void 0:t.clientId}),[]);return(0,d.useSelect)((t=>{const{getBlockRootClientId:r,getBlockSelectionEnd:n,getBlockOrder:i,getBlockIndex:a}=t(de.store),o=t(je).__experimentalGetInsertionPoint();if(o.rootClientId)return o;const s=n()||e,l=r(s);return s&&""===l?{rootClientId:s,insertionIndex:i(s).length}:{rootClientId:l,insertionIndex:a(s)+1}}),[e])};function Jt(){const e=(0,ae.useViewportMatch)("medium","<"),{rootClientId:t,insertionIndex:r}=Qt(),{setIsInserterOpened:n}=(0,d.useDispatch)(je),i=(0,l.useCallback)((()=>n(!1)),[n]),a=e?"div":I.VisuallyHidden,[o,s]=(0,ae.__experimentalUseDialog)({onClose:i,focusOnMount:null}),c=(0,l.useRef)();return(0,l.useEffect)((()=>{c.current.focusSearch()}),[]),(0,l.createElement)("div",y({ref:o},s,{className:"edit-widgets-layout__inserter-panel"}),(0,l.createElement)(a,{className:"edit-widgets-layout__inserter-panel-header"},(0,l.createElement)(I.Button,{icon:qt,onClick:i,label:(0,b.__)("Close block inserter")})),(0,l.createElement)("div",{className:"edit-widgets-layout__inserter-panel-content"},(0,l.createElement)(de.__experimentalLibrary,{showInserterHelpPanel:!0,shouldFocusBlock:e,rootClientId:t,__experimentalInsertionIndex:r,ref:c})))}function Xt(){const{setIsListViewOpened:e}=(0,d.useDispatch)(je),t=(0,ae.useFocusOnMount)("firstElement"),r=(0,ae.useFocusReturn)(),n=(0,ae.useFocusReturn)();const i=`edit-widgets-editor__list-view-panel-label-${(0,ae.useInstanceId)(Xt)}`;return(0,l.createElement)("div",{"aria-labelledby":i,className:"edit-widgets-editor__list-view-panel",onKeyDown:function(t){t.keyCode!==st.ESCAPE||t.defaultPrevented||(t.preventDefault(),e(!1))}},(0,l.createElement)("div",{className:"edit-widgets-editor__list-view-panel-header",ref:r},(0,l.createElement)("strong",{id:i},(0,b.__)("List View")),(0,l.createElement)(I.Button,{icon:W,label:(0,b.__)("Close List View Sidebar"),onClick:()=>e(!1)})),(0,l.createElement)("div",{className:"edit-widgets-editor__list-view-panel-content",ref:(0,ae.useMergeRefs)([n,t])},(0,l.createElement)(de.__experimentalListView,null)))}function Zt(){const{isInserterOpen:e,isListViewOpen:t}=(0,d.useSelect)((e=>{const{isInserterOpened:t,isListViewOpened:r}=e(je);return{isInserterOpen:t(),isListViewOpen:r()}}),[]);return e?(0,l.createElement)(Jt,null):t?(0,l.createElement)(Xt,null):null}const er={header:(0,b.__)("Widgets top bar"),body:(0,b.__)("Widgets and blocks"),sidebar:(0,b.__)("Widgets settings"),footer:(0,b.__)("Widgets footer")};var tr=function(e){let{blockEditorSettings:t}=e;const r=(0,ae.useViewportMatch)("medium","<"),n=(0,ae.useViewportMatch)("huge",">="),{setIsInserterOpened:i,setIsListViewOpened:a,closeGeneralSidebar:o}=(0,d.useDispatch)(je),{hasBlockBreadCrumbsEnabled:s,hasSidebarEnabled:c,isInserterOpened:u,isListViewOpened:m,previousShortcut:g,nextShortcut:p}=(0,d.useSelect)((e=>({hasSidebarEnabled:!!e(U).getActiveComplementaryArea(je.name),isInserterOpened:!!e(je).isInserterOpened(),isListViewOpened:!!e(je).isListViewOpened(),hasBlockBreadCrumbsEnabled:!!e(_.store).get("core/edit-widgets","showBlockBreadcrumbs"),previousShortcut:e(ot.store).getAllShortcutKeyCombinations("core/edit-widgets/previous-region"),nextShortcut:e(ot.store).getAllShortcutKeyCombinations("core/edit-widgets/next-region")})),[]);(0,l.useEffect)((()=>{c&&!n&&(i(!1),a(!1))}),[c,n]),(0,l.useEffect)((()=>{!u&&!m||n||o()}),[u,m,n]);const h=m?(0,b.__)("List View"):(0,b.__)("Block Library"),w=m||u;return(0,l.createElement)(se,{labels:{...er,secondarySidebar:h},header:(0,l.createElement)(jt,null),secondarySidebar:w&&(0,l.createElement)(Zt,null),sidebar:c&&(0,l.createElement)(ie.Slot,{scope:"core/edit-widgets"}),content:(0,l.createElement)(l.Fragment,null,(0,l.createElement)(Kt,{blockEditorSettings:t})),footer:s&&!r&&(0,l.createElement)("div",{className:"edit-widgets-layout__footer"},(0,l.createElement)(de.BlockBreadcrumb,{rootLabelText:(0,b.__)("Widgets")})),shortcuts:{previous:g,next:p}})};function rr(){const e=(0,d.useSelect)((e=>{const{getEditedWidgetAreas:t}=e(je),r=t();return(null==r?void 0:r.length)>0}),[]);return(0,l.useEffect)((()=>{const t=t=>{if(e)return t.returnValue=(0,b.__)("You have unsaved changes. If you proceed, they will be lost."),t.returnValue};return window.addEventListener("beforeunload",t),()=>{window.removeEventListener("beforeunload",t)}}),[e]),null}function nr(){var e;const t=(0,d.useSelect)((e=>!!e(_.store).get("core/edit-widgets","welcomeGuide")),[]),{toggle:r}=(0,d.useDispatch)(_.store),n=(0,d.useSelect)((e=>e(je).getWidgetAreas({per_page:-1})),[]);if(!t)return null;const i=null==n?void 0:n.every((e=>"wp_inactive_widgets"===e.id||e.widgets.every((e=>e.startsWith("block-"))))),a=null!==(e=null==n?void 0:n.filter((e=>"wp_inactive_widgets"!==e.id)).length)&&void 0!==e?e:0;return(0,l.createElement)(I.Guide,{className:"edit-widgets-welcome-guide",contentLabel:(0,b.__)("Welcome to block Widgets"),finishButtonText:(0,b.__)("Get started"),onFinish:()=>r("core/edit-widgets","welcomeGuide"),pages:[{image:(0,l.createElement)(ir,{nonAnimatedSrc:"https://s.w.org/images/block-editor/welcome-canvas.svg",animatedSrc:"https://s.w.org/images/block-editor/welcome-canvas.gif"}),content:(0,l.createElement)(l.Fragment,null,(0,l.createElement)("h1",{className:"edit-widgets-welcome-guide__heading"},(0,b.__)("Welcome to block Widgets")),i?(0,l.createElement)(l.Fragment,null,(0,l.createElement)("p",{className:"edit-widgets-welcome-guide__text"},(0,b.sprintf)((0,b._n)("Your theme provides %s “block” area for you to add and edit content. Try adding a search bar, social icons, or other types of blocks here and see how they’ll look on your site.","Your theme provides %s different “block” areas for you to add and edit content. Try adding a search bar, social icons, or other types of blocks here and see how they’ll look on your site.",a),a))):(0,l.createElement)(l.Fragment,null,(0,l.createElement)("p",{className:"edit-widgets-welcome-guide__text"},(0,b.__)("You can now add any block to your site’s widget areas. Don’t worry, all of your favorite widgets still work flawlessly.")),(0,l.createElement)("p",{className:"edit-widgets-welcome-guide__text"},(0,l.createElement)("strong",null,(0,b.__)("Want to stick with the old widgets?"))," ",(0,l.createElement)(I.ExternalLink,{href:(0,b.__)("https://wordpress.org/plugins/classic-widgets/")},(0,b.__)("Get the Classic Widgets plugin.")))))},{image:(0,l.createElement)(ir,{nonAnimatedSrc:"https://s.w.org/images/block-editor/welcome-editor.svg",animatedSrc:"https://s.w.org/images/block-editor/welcome-editor.gif"}),content:(0,l.createElement)(l.Fragment,null,(0,l.createElement)("h1",{className:"edit-widgets-welcome-guide__heading"},(0,b.__)("Make each block your own")),(0,l.createElement)("p",{className:"edit-widgets-welcome-guide__text"},(0,b.__)("Each block comes with its own set of controls for changing things like color, width, and alignment. These will show and hide automatically when you have a block selected.")))},{image:(0,l.createElement)(ir,{nonAnimatedSrc:"https://s.w.org/images/block-editor/welcome-library.svg",animatedSrc:"https://s.w.org/images/block-editor/welcome-library.gif"}),content:(0,l.createElement)(l.Fragment,null,(0,l.createElement)("h1",{className:"edit-widgets-welcome-guide__heading"},(0,b.__)("Get to know the block library")),(0,l.createElement)("p",{className:"edit-widgets-welcome-guide__text"},(0,l.createInterpolateElement)((0,b.__)("All of the blocks available to you live in the block library. You’ll find it wherever you see the <InserterIconImage /> icon."),{InserterIconImage:(0,l.createElement)("img",{className:"edit-widgets-welcome-guide__inserter-icon",alt:(0,b.__)("inserter"),src:"data:image/svg+xml,%3Csvg width='18' height='18' viewBox='0 0 18 18' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='18' height='18' rx='2' fill='%231E1E1E'/%3E%3Cpath d='M9.22727 4V14M4 8.77273H14' stroke='white' stroke-width='1.5'/%3E%3C/svg%3E%0A"})})))},{image:(0,l.createElement)(ir,{nonAnimatedSrc:"https://s.w.org/images/block-editor/welcome-documentation.svg",animatedSrc:"https://s.w.org/images/block-editor/welcome-documentation.gif"}),content:(0,l.createElement)(l.Fragment,null,(0,l.createElement)("h1",{className:"edit-widgets-welcome-guide__heading"},(0,b.__)("Learn how to use the block editor")),(0,l.createElement)("p",{className:"edit-widgets-welcome-guide__text"},(0,b.__)("New to the block editor? Want to learn more about using it? "),(0,l.createElement)(I.ExternalLink,{href:(0,b.__)("https://wordpress.org/support/article/wordpress-editor/")},(0,b.__)("Here's a detailed guide."))))}]})}function ir(e){let{nonAnimatedSrc:t,animatedSrc:r}=e;return(0,l.createElement)("picture",{className:"edit-widgets-welcome-guide__image"},(0,l.createElement)("source",{srcSet:t,media:"(prefers-reduced-motion: reduce)"}),(0,l.createElement)("img",{src:r,width:"312",height:"240",alt:""}))}var ar=function(e){let{blockEditorSettings:t}=e;const{createErrorNotice:r}=(0,d.useDispatch)(v.store);return(0,l.createElement)(it,null,(0,l.createElement)(ht,{blockEditorSettings:t},(0,l.createElement)(tr,{blockEditorSettings:t}),(0,l.createElement)(It,null),(0,l.createElement)(I.Popover.Slot,null),(0,l.createElement)($.PluginArea,{onError:function(e){r((0,b.sprintf)((0,b.__)('The "%s" plugin has encountered an error and cannot be rendered.'),e))}}),(0,l.createElement)(rr,null),(0,l.createElement)(nr,null)))};const or=["core/more","core/freeform","core/template-part","core/block"];function sr(e,t){const r=document.getElementById(e),n=(0,l.createRoot)(r),i=(0,g.__experimentalGetCoreBlocks)().filter((e=>!(or.includes(e.name)||e.name.startsWith("core/post")||e.name.startsWith("core/query")||e.name.startsWith("core/site")||e.name.startsWith("core/navigation"))));return(0,d.dispatch)(_.store).setDefaults("core/edit-widgets",{fixedToolbar:!1,welcomeGuide:!0,showBlockBreadcrumbs:!0,themeStyles:!0}),(0,d.dispatch)(c.store).__experimentalReapplyBlockTypeFilters(),(0,g.registerCoreBlocks)(i),(0,h.registerLegacyWidgetBlock)(),(0,h.registerLegacyWidgetVariations)(t),dr(s),(0,h.registerWidgetGroupBlock)(),t.__experimentalFetchLinkSuggestions=(e,r)=>(0,p.__experimentalFetchLinkSuggestions)(e,r,t),(0,c.setFreeformContentHandlerName)("core/html"),n.render((0,l.createElement)(ar,{blockEditorSettings:t})),n}const lr=sr;function cr(){m()("wp.editWidgets.reinitializeEditor",{since:"6.2",version:"6.3"})}const dr=e=>{if(!e)return;const{metadata:t,settings:r,name:n}=e;t&&(0,c.unstable__bootstrapServerSideBlockDefinitions)({[n]:t}),(0,c.registerBlockType)(n,r)}}(),(window.wp=window.wp||{}).editWidgets=n}(); deprecated.js 0000666 00000011364 15123355174 0007221 0 ustar 00 /******/ (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); }
/******/ }();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"default": function() { return /* binding */ deprecated; }
});
// UNUSED EXPORTS: logged
;// CONCATENATED MODULE: external ["wp","hooks"]
var external_wp_hooks_namespaceObject = window["wp"]["hooks"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/deprecated/build-module/index.js
/**
* WordPress dependencies
*/
/**
* Object map tracking messages which have been logged, for use in ensuring a
* message is only logged once.
*
* @type {Record<string, true | undefined>}
*/
const logged = Object.create(null);
/**
* Logs a message to notify developers about a deprecated feature.
*
* @param {string} feature Name of the deprecated feature.
* @param {Object} [options] Personalisation options
* @param {string} [options.since] Version in which the feature was deprecated.
* @param {string} [options.version] Version in which the feature will be removed.
* @param {string} [options.alternative] Feature to use instead
* @param {string} [options.plugin] Plugin name if it's a plugin feature
* @param {string} [options.link] Link to documentation
* @param {string} [options.hint] Additional message to help transition away from the deprecated feature.
*
* @example
* ```js
* import deprecated from '@wordpress/deprecated';
*
* deprecated( 'Eating meat', {
* since: '2019.01.01'
* version: '2020.01.01',
* alternative: 'vegetables',
* plugin: 'the earth',
* hint: 'You may find it beneficial to transition gradually.',
* } );
*
* // Logs: 'Eating meat is deprecated since version 2019.01.01 and will be removed from the earth in version 2020.01.01. Please use vegetables instead. Note: You may find it beneficial to transition gradually.'
* ```
*/
function deprecated(feature) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const {
since,
version,
alternative,
plugin,
link,
hint
} = options;
const pluginMessage = plugin ? ` from ${plugin}` : '';
const sinceMessage = since ? ` since version ${since}` : '';
const versionMessage = version ? ` and will be removed${pluginMessage} in version ${version}` : '';
const useInsteadMessage = alternative ? ` Please use ${alternative} instead.` : '';
const linkMessage = link ? ` See: ${link}` : '';
const hintMessage = hint ? ` Note: ${hint}` : '';
const message = `${feature} is deprecated${sinceMessage}${versionMessage}.${useInsteadMessage}${linkMessage}${hintMessage}`; // Skip if already logged.
if (message in logged) {
return;
}
/**
* Fires whenever a deprecated feature is encountered
*
* @param {string} feature Name of the deprecated feature.
* @param {?Object} options Personalisation options
* @param {string} options.since Version in which the feature was deprecated.
* @param {?string} options.version Version in which the feature will be removed.
* @param {?string} options.alternative Feature to use instead
* @param {?string} options.plugin Plugin name if it's a plugin feature
* @param {?string} options.link Link to documentation
* @param {?string} options.hint Additional message to help transition away from the deprecated feature.
* @param {?string} message Message sent to console.warn
*/
(0,external_wp_hooks_namespaceObject.doAction)('deprecated', feature, options, message); // eslint-disable-next-line no-console
console.warn(message);
logged[message] = true;
}
/** @typedef {import('utility-types').NonUndefined<Parameters<typeof deprecated>[1]>} DeprecatedOptions */
(window.wp = window.wp || {}).deprecated = __webpack_exports__["default"];
/******/ })()
; primitives.min.js 0000666 00000004710 15123355174 0010073 0 ustar 00 /*! This file is auto-generated */
!function(){var e={7153:function(e,t){var n;
/*!
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];n&&(e=u(e,i(n)))}return e}function i(e){if("string"==typeof e||"number"==typeof e)return e;if("object"!=typeof e)return"";if(Array.isArray(e))return o.apply(null,e);if(e.toString!==Object.prototype.toString&&!e.toString.toString().includes("[native code]"))return e.toString();var t="";for(var n in e)r.call(e,n)&&e[n]&&(t=u(t,n));return t}function u(e,t){return t?e?e+" "+t:e+t:e}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 c},LinearGradient:function(){return p},Path:function(){return a},Polygon:function(){return f},RadialGradient:function(){return d},Rect:function(){return l},SVG:function(){return m},Stop:function(){return v},View:function(){return b}});var e=n(7153),t=n.n(e),o=window.wp.element;const i=e=>(0,o.createElement)("circle",e),u=e=>(0,o.createElement)("g",e),c=e=>(0,o.createElement)("line",e),a=e=>(0,o.createElement)("path",e),f=e=>(0,o.createElement)("polygon",e),l=e=>(0,o.createElement)("rect",e),s=e=>(0,o.createElement)("defs",e),d=e=>(0,o.createElement)("radialGradient",e),p=e=>(0,o.createElement)("linearGradient",e),v=e=>(0,o.createElement)("stop",e),m=e=>{let{className:n,isPressed:r,...i}=e;const u={...i,className:t()(n,{"is-pressed":r})||void 0,"aria-hidden":!0,focusable:!1};return(0,o.createElement)("svg",u)},y="hr",g="blockquote",b="div"}(),(window.wp=window.wp||{}).primitives=r}(); hooks.js 0000666 00000050136 15123355174 0006244 0 ustar 00 /******/ (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__, {
"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
/**
* Validate a namespace string.
*
* @param {string} namespace The namespace to validate - should take the form
* `vendor/plugin/function`.
*
* @return {boolean} Whether the namespace is valid.
*/
function validateNamespace(namespace) {
if ('string' !== typeof namespace || '' === namespace) {
// eslint-disable-next-line no-console
console.error('The namespace must be a non-empty string.');
return false;
}
if (!/^[a-zA-Z][a-zA-Z0-9_.\-\/]*$/.test(namespace)) {
// eslint-disable-next-line no-console
console.error('The namespace can only contain numbers, letters, dashes, periods, underscores and slashes.');
return false;
}
return true;
}
/* harmony default export */ var build_module_validateNamespace = (validateNamespace);
;// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/validateHookName.js
/**
* Validate a hookName string.
*
* @param {string} hookName The hook name to validate. Should be a non empty string containing
* only numbers, letters, dashes, periods and underscores. Also,
* the hook name cannot begin with `__`.
*
* @return {boolean} Whether the hook name is valid.
*/
function validateHookName(hookName) {
if ('string' !== typeof hookName || '' === hookName) {
// eslint-disable-next-line no-console
console.error('The hook name must be a non-empty string.');
return false;
}
if (/^__/.test(hookName)) {
// eslint-disable-next-line no-console
console.error('The hook name cannot begin with `__`.');
return false;
}
if (!/^[a-zA-Z][a-zA-Z0-9_.-]*$/.test(hookName)) {
// eslint-disable-next-line no-console
console.error('The hook name can only contain numbers, letters, dashes, periods and underscores.');
return false;
}
return true;
}
/* harmony default export */ var build_module_validateHookName = (validateHookName);
;// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createAddHook.js
/**
* Internal dependencies
*/
/**
* @callback AddHook
*
* Adds the hook to the appropriate hooks container.
*
* @param {string} hookName Name of hook to add
* @param {string} namespace The unique namespace identifying the callback in the form `vendor/plugin/function`.
* @param {import('.').Callback} callback Function to call when the hook is run
* @param {number} [priority=10] Priority of this hook
*/
/**
* Returns a function which, when invoked, will add a hook.
*
* @param {import('.').Hooks} hooks Hooks instance.
* @param {import('.').StoreKey} storeKey
*
* @return {AddHook} Function that adds a new hook.
*/
function createAddHook(hooks, storeKey) {
return function addHook(hookName, namespace, callback) {
let priority = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 10;
const hooksStore = hooks[storeKey];
if (!build_module_validateHookName(hookName)) {
return;
}
if (!build_module_validateNamespace(namespace)) {
return;
}
if ('function' !== typeof callback) {
// eslint-disable-next-line no-console
console.error('The hook callback must be a function.');
return;
} // Validate numeric priority
if ('number' !== typeof priority) {
// eslint-disable-next-line no-console
console.error('If specified, the hook priority must be a number.');
return;
}
const handler = {
callback,
priority,
namespace
};
if (hooksStore[hookName]) {
// Find the correct insert index of the new hook.
const handlers = hooksStore[hookName].handlers;
/** @type {number} */
let i;
for (i = handlers.length; i > 0; i--) {
if (priority >= handlers[i - 1].priority) {
break;
}
}
if (i === handlers.length) {
// If append, operate via direct assignment.
handlers[i] = handler;
} else {
// Otherwise, insert before index via splice.
handlers.splice(i, 0, handler);
} // We may also be currently executing this hook. If the callback
// we're adding would come after the current callback, there's no
// problem; otherwise we need to increase the execution index of
// any other runs by 1 to account for the added element.
hooksStore.__current.forEach(hookInfo => {
if (hookInfo.name === hookName && hookInfo.currentIndex >= i) {
hookInfo.currentIndex++;
}
});
} else {
// This is the first hook of its type.
hooksStore[hookName] = {
handlers: [handler],
runs: 0
};
}
if (hookName !== 'hookAdded') {
hooks.doAction('hookAdded', hookName, namespace, callback, priority);
}
};
}
/* harmony default export */ var build_module_createAddHook = (createAddHook);
;// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createRemoveHook.js
/**
* Internal dependencies
*/
/**
* @callback RemoveHook
* Removes the specified callback (or all callbacks) from the hook with a given hookName
* and namespace.
*
* @param {string} hookName The name of the hook to modify.
* @param {string} namespace The unique namespace identifying the callback in the
* form `vendor/plugin/function`.
*
* @return {number | undefined} The number of callbacks removed.
*/
/**
* Returns a function which, when invoked, will remove a specified hook or all
* hooks by the given name.
*
* @param {import('.').Hooks} hooks Hooks instance.
* @param {import('.').StoreKey} storeKey
* @param {boolean} [removeAll=false] Whether to remove all callbacks for a hookName,
* without regard to namespace. Used to create
* `removeAll*` functions.
*
* @return {RemoveHook} Function that removes hooks.
*/
function createRemoveHook(hooks, storeKey) {
let removeAll = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
return function removeHook(hookName, namespace) {
const hooksStore = hooks[storeKey];
if (!build_module_validateHookName(hookName)) {
return;
}
if (!removeAll && !build_module_validateNamespace(namespace)) {
return;
} // Bail if no hooks exist by this name.
if (!hooksStore[hookName]) {
return 0;
}
let handlersRemoved = 0;
if (removeAll) {
handlersRemoved = hooksStore[hookName].handlers.length;
hooksStore[hookName] = {
runs: hooksStore[hookName].runs,
handlers: []
};
} else {
// Try to find the specified callback to remove.
const handlers = hooksStore[hookName].handlers;
for (let i = handlers.length - 1; i >= 0; i--) {
if (handlers[i].namespace === namespace) {
handlers.splice(i, 1);
handlersRemoved++; // This callback may also be part of a hook that is
// currently executing. If the callback we're removing
// comes after the current callback, there's no problem;
// otherwise we need to decrease the execution index of any
// other runs by 1 to account for the removed element.
hooksStore.__current.forEach(hookInfo => {
if (hookInfo.name === hookName && hookInfo.currentIndex >= i) {
hookInfo.currentIndex--;
}
});
}
}
}
if (hookName !== 'hookRemoved') {
hooks.doAction('hookRemoved', hookName, namespace);
}
return handlersRemoved;
};
}
/* harmony default export */ var build_module_createRemoveHook = (createRemoveHook);
;// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createHasHook.js
/**
* @callback HasHook
*
* Returns whether any handlers are attached for the given hookName and optional namespace.
*
* @param {string} hookName The name of the hook to check for.
* @param {string} [namespace] Optional. The unique namespace identifying the callback
* in the form `vendor/plugin/function`.
*
* @return {boolean} Whether there are handlers that are attached to the given hook.
*/
/**
* Returns a function which, when invoked, will return whether any handlers are
* attached to a particular hook.
*
* @param {import('.').Hooks} hooks Hooks instance.
* @param {import('.').StoreKey} storeKey
*
* @return {HasHook} Function that returns whether any handlers are
* attached to a particular hook and optional namespace.
*/
function createHasHook(hooks, storeKey) {
return function hasHook(hookName, namespace) {
const hooksStore = hooks[storeKey]; // Use the namespace if provided.
if ('undefined' !== typeof namespace) {
return hookName in hooksStore && hooksStore[hookName].handlers.some(hook => hook.namespace === namespace);
}
return hookName in hooksStore;
};
}
/* harmony default export */ var build_module_createHasHook = (createHasHook);
;// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createRunHook.js
/**
* Returns a function which, when invoked, will execute all callbacks
* registered to a hook of the specified type, optionally returning the final
* value of the call chain.
*
* @param {import('.').Hooks} hooks Hooks instance.
* @param {import('.').StoreKey} storeKey
* @param {boolean} [returnFirstArg=false] Whether each hook callback is expected to
* return its first argument.
*
* @return {(hookName:string, ...args: unknown[]) => unknown} Function that runs hook callbacks.
*/
function createRunHook(hooks, storeKey) {
let returnFirstArg = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
return function runHooks(hookName) {
const hooksStore = hooks[storeKey];
if (!hooksStore[hookName]) {
hooksStore[hookName] = {
handlers: [],
runs: 0
};
}
hooksStore[hookName].runs++;
const handlers = hooksStore[hookName].handlers; // The following code is stripped from production builds.
if (false) {}
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (!handlers || !handlers.length) {
return returnFirstArg ? args[0] : undefined;
}
const hookInfo = {
name: hookName,
currentIndex: 0
};
hooksStore.__current.push(hookInfo);
while (hookInfo.currentIndex < handlers.length) {
const handler = handlers[hookInfo.currentIndex];
const result = handler.callback.apply(null, args);
if (returnFirstArg) {
args[0] = result;
}
hookInfo.currentIndex++;
}
hooksStore.__current.pop();
if (returnFirstArg) {
return args[0];
}
};
}
/* harmony default export */ var build_module_createRunHook = (createRunHook);
;// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createCurrentHook.js
/**
* Returns a function which, when invoked, will return the name of the
* currently running hook, or `null` if no hook of the given type is currently
* running.
*
* @param {import('.').Hooks} hooks Hooks instance.
* @param {import('.').StoreKey} storeKey
*
* @return {() => string | null} Function that returns the current hook name or null.
*/
function createCurrentHook(hooks, storeKey) {
return function currentHook() {
var _hooksStore$__current, _hooksStore$__current2;
const hooksStore = hooks[storeKey];
return (_hooksStore$__current = (_hooksStore$__current2 = hooksStore.__current[hooksStore.__current.length - 1]) === null || _hooksStore$__current2 === void 0 ? void 0 : _hooksStore$__current2.name) !== null && _hooksStore$__current !== void 0 ? _hooksStore$__current : null;
};
}
/* harmony default export */ var build_module_createCurrentHook = (createCurrentHook);
;// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createDoingHook.js
/**
* @callback DoingHook
* Returns whether a hook is currently being executed.
*
* @param {string} [hookName] The name of the hook to check for. If
* omitted, will check for any hook being executed.
*
* @return {boolean} Whether the hook is being executed.
*/
/**
* Returns a function which, when invoked, will return whether a hook is
* currently being executed.
*
* @param {import('.').Hooks} hooks Hooks instance.
* @param {import('.').StoreKey} storeKey
*
* @return {DoingHook} Function that returns whether a hook is currently
* being executed.
*/
function createDoingHook(hooks, storeKey) {
return function doingHook(hookName) {
const hooksStore = hooks[storeKey]; // If the hookName was not passed, check for any current hook.
if ('undefined' === typeof hookName) {
return 'undefined' !== typeof hooksStore.__current[0];
} // Return the __current hook.
return hooksStore.__current[0] ? hookName === hooksStore.__current[0].name : false;
};
}
/* harmony default export */ var build_module_createDoingHook = (createDoingHook);
;// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createDidHook.js
/**
* Internal dependencies
*/
/**
* @callback DidHook
*
* Returns the number of times an action has been fired.
*
* @param {string} hookName The hook name to check.
*
* @return {number | undefined} The number of times the hook has run.
*/
/**
* Returns a function which, when invoked, will return the number of times a
* hook has been called.
*
* @param {import('.').Hooks} hooks Hooks instance.
* @param {import('.').StoreKey} storeKey
*
* @return {DidHook} Function that returns a hook's call count.
*/
function createDidHook(hooks, storeKey) {
return function didHook(hookName) {
const hooksStore = hooks[storeKey];
if (!build_module_validateHookName(hookName)) {
return;
}
return hooksStore[hookName] && hooksStore[hookName].runs ? hooksStore[hookName].runs : 0;
};
}
/* harmony default export */ var build_module_createDidHook = (createDidHook);
;// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/createHooks.js
/**
* Internal dependencies
*/
/**
* Internal class for constructing hooks. Use `createHooks()` function
*
* Note, it is necessary to expose this class to make its type public.
*
* @private
*/
class _Hooks {
constructor() {
/** @type {import('.').Store} actions */
this.actions = Object.create(null);
this.actions.__current = [];
/** @type {import('.').Store} filters */
this.filters = Object.create(null);
this.filters.__current = [];
this.addAction = build_module_createAddHook(this, 'actions');
this.addFilter = build_module_createAddHook(this, 'filters');
this.removeAction = build_module_createRemoveHook(this, 'actions');
this.removeFilter = build_module_createRemoveHook(this, 'filters');
this.hasAction = build_module_createHasHook(this, 'actions');
this.hasFilter = build_module_createHasHook(this, 'filters');
this.removeAllActions = build_module_createRemoveHook(this, 'actions', true);
this.removeAllFilters = build_module_createRemoveHook(this, 'filters', true);
this.doAction = build_module_createRunHook(this, 'actions');
this.applyFilters = build_module_createRunHook(this, 'filters', true);
this.currentAction = build_module_createCurrentHook(this, 'actions');
this.currentFilter = build_module_createCurrentHook(this, 'filters');
this.doingAction = build_module_createDoingHook(this, 'actions');
this.doingFilter = build_module_createDoingHook(this, 'filters');
this.didAction = build_module_createDidHook(this, 'actions');
this.didFilter = build_module_createDidHook(this, 'filters');
}
}
/** @typedef {_Hooks} Hooks */
/**
* Returns an instance of the hooks object.
*
* @return {Hooks} A Hooks instance.
*/
function createHooks() {
return new _Hooks();
}
/* harmony default export */ var build_module_createHooks = (createHooks);
;// CONCATENATED MODULE: ./node_modules/@wordpress/hooks/build-module/index.js
/**
* Internal dependencies
*/
/** @typedef {(...args: any[])=>any} Callback */
/**
* @typedef Handler
* @property {Callback} callback The callback
* @property {string} namespace The namespace
* @property {number} priority The namespace
*/
/**
* @typedef Hook
* @property {Handler[]} handlers Array of handlers
* @property {number} runs Run counter
*/
/**
* @typedef Current
* @property {string} name Hook name
* @property {number} currentIndex The index
*/
/**
* @typedef {Record<string, Hook> & {__current: Current[]}} Store
*/
/**
* @typedef {'actions' | 'filters'} StoreKey
*/
/**
* @typedef {import('./createHooks').Hooks} Hooks
*/
const defaultHooks = build_module_createHooks();
const {
addAction,
addFilter,
removeAction,
removeFilter,
hasAction,
hasFilter,
removeAllActions,
removeAllFilters,
doAction,
applyFilters,
currentAction,
currentFilter,
doingAction,
doingFilter,
didAction,
didFilter,
actions,
filters
} = defaultHooks;
(window.wp = window.wp || {}).hooks = __webpack_exports__;
/******/ })()
; autop.js 0000666 00000037620 15123355174 0006254 0 ustar 00 /******/ (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__ = {};
__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 */ });
/**
* The regular expression for an HTML element.
*
* @type {RegExp}
*/
const htmlSplitRegex = (() => {
/* eslint-disable no-multi-spaces */
const comments = '!' + // Start of comment, after the <.
'(?:' + // Unroll the loop: Consume everything until --> is found.
'-(?!->)' + // Dash not followed by end of comment.
'[^\\-]*' + // Consume non-dashes.
')*' + // Loop possessively.
'(?:-->)?'; // End of comment. If not found, match all input.
const cdata = '!\\[CDATA\\[' + // Start of comment, after the <.
'[^\\]]*' + // Consume non-].
'(?:' + // Unroll the loop: Consume everything until ]]> is found.
'](?!]>)' + // One ] not followed by end of comment.
'[^\\]]*' + // Consume non-].
')*?' + // Loop possessively.
'(?:]]>)?'; // End of comment. If not found, match all input.
const escaped = '(?=' + // Is the element escaped?
'!--' + '|' + '!\\[CDATA\\[' + ')' + '((?=!-)' + // If yes, which type?
comments + '|' + cdata + ')';
const regex = '(' + // Capture the entire match.
'<' + // Find start of element.
'(' + // Conditional expression follows.
escaped + // Find end of escaped element.
'|' + // ... else ...
'[^>]*>?' + // Find end of normal element.
')' + ')';
return new RegExp(regex);
/* eslint-enable no-multi-spaces */
})();
/**
* Separate HTML elements and comments from the text.
*
* @param {string} input The text which has to be formatted.
*
* @return {string[]} The formatted text.
*/
function htmlSplit(input) {
const parts = [];
let workingInput = input;
let match;
while (match = workingInput.match(htmlSplitRegex)) {
// The `match` result, when invoked on a RegExp with the `g` flag (`/foo/g`) will not include `index`.
// If the `g` flag is omitted, `index` is included.
// `htmlSplitRegex` does not have the `g` flag so we can assert it will have an index number.
// Assert `match.index` is a number.
const index =
/** @type {number} */
match.index;
parts.push(workingInput.slice(0, index));
parts.push(match[0]);
workingInput = workingInput.slice(index + match[0].length);
}
if (workingInput.length) {
parts.push(workingInput);
}
return parts;
}
/**
* Replace characters or phrases within HTML elements only.
*
* @param {string} haystack The text which has to be formatted.
* @param {Record<string,string>} replacePairs In the form {from: 'to', …}.
*
* @return {string} The formatted text.
*/
function replaceInHtmlTags(haystack, replacePairs) {
// Find all elements.
const textArr = htmlSplit(haystack);
let changed = false; // Extract all needles.
const needles = Object.keys(replacePairs); // Loop through delimiters (elements) only.
for (let i = 1; i < textArr.length; i += 2) {
for (let j = 0; j < needles.length; j++) {
const needle = needles[j];
if (-1 !== textArr[i].indexOf(needle)) {
textArr[i] = textArr[i].replace(new RegExp(needle, 'g'), replacePairs[needle]);
changed = true; // After one strtr() break out of the foreach loop and look at next element.
break;
}
}
}
if (changed) {
haystack = textArr.join('');
}
return haystack;
}
/**
* Replaces double line-breaks with paragraph elements.
*
* A group of regex replaces used to identify text formatted with newlines and
* replace double line-breaks with HTML paragraph tags. The remaining line-
* breaks after conversion become `<br />` tags, unless br is set to 'false'.
*
* @param {string} text The text which has to be formatted.
* @param {boolean} br Optional. If set, will convert all remaining line-
* breaks after paragraphing. Default true.
*
* @example
*```js
* import { autop } from '@wordpress/autop';
* autop( 'my text' ); // "<p>my text</p>"
* ```
*
* @return {string} Text which has been converted into paragraph tags.
*/
function autop(text) {
let br = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
const preTags = [];
if (text.trim() === '') {
return '';
} // Just to make things a little easier, pad the end.
text = text + '\n';
/*
* Pre tags shouldn't be touched by autop.
* Replace pre tags with placeholders and bring them back after autop.
*/
if (text.indexOf('<pre') !== -1) {
const textParts = text.split('</pre>');
const lastText = textParts.pop();
text = '';
for (let i = 0; i < textParts.length; i++) {
const textPart = textParts[i];
const start = textPart.indexOf('<pre'); // Malformed html?
if (start === -1) {
text += textPart;
continue;
}
const name = '<pre wp-pre-tag-' + i + '></pre>';
preTags.push([name, textPart.substr(start) + '</pre>']);
text += textPart.substr(0, start) + name;
}
text += lastText;
} // Change multiple <br>s into two line breaks, which will turn into paragraphs.
text = text.replace(/<br\s*\/?>\s*<br\s*\/?>/g, '\n\n');
const allBlocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)'; // Add a double line break above block-level opening tags.
text = text.replace(new RegExp('(<' + allBlocks + '[\\s/>])', 'g'), '\n\n$1'); // Add a double line break below block-level closing tags.
text = text.replace(new RegExp('(</' + allBlocks + '>)', 'g'), '$1\n\n'); // Standardize newline characters to "\n".
text = text.replace(/\r\n|\r/g, '\n'); // Find newlines in all elements and add placeholders.
text = replaceInHtmlTags(text, {
'\n': ' <!-- wpnl --> '
}); // Collapse line breaks before and after <option> elements so they don't get autop'd.
if (text.indexOf('<option') !== -1) {
text = text.replace(/\s*<option/g, '<option');
text = text.replace(/<\/option>\s*/g, '</option>');
}
/*
* Collapse line breaks inside <object> elements, before <param> and <embed> elements
* so they don't get autop'd.
*/
if (text.indexOf('</object>') !== -1) {
text = text.replace(/(<object[^>]*>)\s*/g, '$1');
text = text.replace(/\s*<\/object>/g, '</object>');
text = text.replace(/\s*(<\/?(?:param|embed)[^>]*>)\s*/g, '$1');
}
/*
* Collapse line breaks inside <audio> and <video> elements,
* before and after <source> and <track> elements.
*/
if (text.indexOf('<source') !== -1 || text.indexOf('<track') !== -1) {
text = text.replace(/([<\[](?:audio|video)[^>\]]*[>\]])\s*/g, '$1');
text = text.replace(/\s*([<\[]\/(?:audio|video)[>\]])/g, '$1');
text = text.replace(/\s*(<(?:source|track)[^>]*>)\s*/g, '$1');
} // Collapse line breaks before and after <figcaption> elements.
if (text.indexOf('<figcaption') !== -1) {
text = text.replace(/\s*(<figcaption[^>]*>)/, '$1');
text = text.replace(/<\/figcaption>\s*/, '</figcaption>');
} // Remove more than two contiguous line breaks.
text = text.replace(/\n\n+/g, '\n\n'); // Split up the contents into an array of strings, separated by double line breaks.
const texts = text.split(/\n\s*\n/).filter(Boolean); // Reset text prior to rebuilding.
text = ''; // Rebuild the content as a string, wrapping every bit with a <p>.
texts.forEach(textPiece => {
text += '<p>' + textPiece.replace(/^\n*|\n*$/g, '') + '</p>\n';
}); // Under certain strange conditions it could create a P of entirely whitespace.
text = text.replace(/<p>\s*<\/p>/g, ''); // Add a closing <p> inside <div>, <address>, or <form> tag if missing.
text = text.replace(/<p>([^<]+)<\/(div|address|form)>/g, '<p>$1</p></$2>'); // If an opening or closing block element tag is wrapped in a <p>, unwrap it.
text = text.replace(new RegExp('<p>\\s*(</?' + allBlocks + '[^>]*>)\\s*</p>', 'g'), '$1'); // In some cases <li> may get wrapped in <p>, fix them.
text = text.replace(/<p>(<li.+?)<\/p>/g, '$1'); // If a <blockquote> is wrapped with a <p>, move it inside the <blockquote>.
text = text.replace(/<p><blockquote([^>]*)>/gi, '<blockquote$1><p>');
text = text.replace(/<\/blockquote><\/p>/g, '</p></blockquote>'); // If an opening or closing block element tag is preceded by an opening <p> tag, remove it.
text = text.replace(new RegExp('<p>\\s*(</?' + allBlocks + '[^>]*>)', 'g'), '$1'); // If an opening or closing block element tag is followed by a closing <p> tag, remove it.
text = text.replace(new RegExp('(</?' + allBlocks + '[^>]*>)\\s*</p>', 'g'), '$1'); // Optionally insert line breaks.
if (br) {
// Replace newlines that shouldn't be touched with a placeholder.
text = text.replace(/<(script|style).*?<\/\\1>/g, match => match[0].replace(/\n/g, '<WPPreserveNewline />')); // Normalize <br>
text = text.replace(/<br>|<br\/>/g, '<br />'); // Replace any new line characters that aren't preceded by a <br /> with a <br />.
text = text.replace(/(<br \/>)?\s*\n/g, (a, b) => b ? a : '<br />\n'); // Replace newline placeholders with newlines.
text = text.replace(/<WPPreserveNewline \/>/g, '\n');
} // If a <br /> tag is after an opening or closing block tag, remove it.
text = text.replace(new RegExp('(</?' + allBlocks + '[^>]*>)\\s*<br />', 'g'), '$1'); // If a <br /> tag is before a subset of opening or closing block tags, remove it.
text = text.replace(/<br \/>(\s*<\/?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)/g, '$1');
text = text.replace(/\n<\/p>$/g, '</p>'); // Replace placeholder <pre> tags with their original content.
preTags.forEach(preTag => {
const [name, original] = preTag;
text = text.replace(name, original);
}); // Restore newlines in all elements.
if (-1 !== text.indexOf('<!-- wpnl -->')) {
text = text.replace(/\s?<!-- wpnl -->\s?/g, '\n');
}
return text;
}
/**
* Replaces `<p>` tags with two line breaks. "Opposite" of autop().
*
* Replaces `<p>` tags with two line breaks except where the `<p>` has attributes.
* Unifies whitespace. Indents `<li>`, `<dt>` and `<dd>` for better readability.
*
* @param {string} html The content from the editor.
*
* @example
* ```js
* import { removep } from '@wordpress/autop';
* removep( '<p>my text</p>' ); // "my text"
* ```
*
* @return {string} The content with stripped paragraph tags.
*/
function removep(html) {
const blocklist = 'blockquote|ul|ol|li|dl|dt|dd|table|thead|tbody|tfoot|tr|th|td|h[1-6]|fieldset|figure';
const blocklist1 = blocklist + '|div|p';
const blocklist2 = blocklist + '|pre';
/** @type {string[]} */
const preserve = [];
let preserveLinebreaks = false;
let preserveBr = false;
if (!html) {
return '';
} // Protect script and style tags.
if (html.indexOf('<script') !== -1 || html.indexOf('<style') !== -1) {
html = html.replace(/<(script|style)[^>]*>[\s\S]*?<\/\1>/g, match => {
preserve.push(match);
return '<wp-preserve>';
});
} // Protect pre tags.
if (html.indexOf('<pre') !== -1) {
preserveLinebreaks = true;
html = html.replace(/<pre[^>]*>[\s\S]+?<\/pre>/g, a => {
a = a.replace(/<br ?\/?>(\r\n|\n)?/g, '<wp-line-break>');
a = a.replace(/<\/?p( [^>]*)?>(\r\n|\n)?/g, '<wp-line-break>');
return a.replace(/\r?\n/g, '<wp-line-break>');
});
} // Remove line breaks but keep <br> tags inside image captions.
if (html.indexOf('[caption') !== -1) {
preserveBr = true;
html = html.replace(/\[caption[\s\S]+?\[\/caption\]/g, a => {
return a.replace(/<br([^>]*)>/g, '<wp-temp-br$1>').replace(/[\r\n\t]+/, '');
});
} // Normalize white space characters before and after block tags.
html = html.replace(new RegExp('\\s*</(' + blocklist1 + ')>\\s*', 'g'), '</$1>\n');
html = html.replace(new RegExp('\\s*<((?:' + blocklist1 + ')(?: [^>]*)?)>', 'g'), '\n<$1>'); // Mark </p> if it has any attributes.
html = html.replace(/(<p [^>]+>[\s\S]*?)<\/p>/g, '$1</p#>'); // Preserve the first <p> inside a <div>.
html = html.replace(/<div( [^>]*)?>\s*<p>/gi, '<div$1>\n\n'); // Remove paragraph tags.
html = html.replace(/\s*<p>/gi, '');
html = html.replace(/\s*<\/p>\s*/gi, '\n\n'); // Normalize white space chars and remove multiple line breaks.
html = html.replace(/\n[\s\u00a0]+\n/g, '\n\n'); // Replace <br> tags with line breaks.
html = html.replace(/(\s*)<br ?\/?>\s*/gi, (_, space) => {
if (space && space.indexOf('\n') !== -1) {
return '\n\n';
}
return '\n';
}); // Fix line breaks around <div>.
html = html.replace(/\s*<div/g, '\n<div');
html = html.replace(/<\/div>\s*/g, '</div>\n'); // Fix line breaks around caption shortcodes.
html = html.replace(/\s*\[caption([^\[]+)\[\/caption\]\s*/gi, '\n\n[caption$1[/caption]\n\n');
html = html.replace(/caption\]\n\n+\[caption/g, 'caption]\n\n[caption'); // Pad block elements tags with a line break.
html = html.replace(new RegExp('\\s*<((?:' + blocklist2 + ')(?: [^>]*)?)\\s*>', 'g'), '\n<$1>');
html = html.replace(new RegExp('\\s*</(' + blocklist2 + ')>\\s*', 'g'), '</$1>\n'); // Indent <li>, <dt> and <dd> tags.
html = html.replace(/<((li|dt|dd)[^>]*)>/g, ' \t<$1>'); // Fix line breaks around <select> and <option>.
if (html.indexOf('<option') !== -1) {
html = html.replace(/\s*<option/g, '\n<option');
html = html.replace(/\s*<\/select>/g, '\n</select>');
} // Pad <hr> with two line breaks.
if (html.indexOf('<hr') !== -1) {
html = html.replace(/\s*<hr( [^>]*)?>\s*/g, '\n\n<hr$1>\n\n');
} // Remove line breaks in <object> tags.
if (html.indexOf('<object') !== -1) {
html = html.replace(/<object[\s\S]+?<\/object>/g, a => {
return a.replace(/[\r\n]+/g, '');
});
} // Unmark special paragraph closing tags.
html = html.replace(/<\/p#>/g, '</p>\n'); // Pad remaining <p> tags whit a line break.
html = html.replace(/\s*(<p [^>]+>[\s\S]*?<\/p>)/g, '\n$1'); // Trim.
html = html.replace(/^\s+/, '');
html = html.replace(/[\s\u00a0]+$/, '');
if (preserveLinebreaks) {
html = html.replace(/<wp-line-break>/g, '\n');
}
if (preserveBr) {
html = html.replace(/<wp-temp-br([^>]*)>/g, '<br$1>');
} // Restore preserved tags.
if (preserve.length) {
html = html.replace(/<wp-preserve>/g, () => {
return (
/** @type {string} */
preserve.shift()
);
});
}
return html;
}
(window.wp = window.wp || {}).autop = __webpack_exports__;
/******/ })()
; data-controls.min.js 0000666 00000003141 15123355174 0010447 0 ustar 00 /*! This file is auto-generated */
!function(){"use strict";var t={n:function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return t.d(e,{a:e}),e},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]})},o:function(t,n){return Object.prototype.hasOwnProperty.call(t,n)},r:function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},n={};t.r(n),t.d(n,{__unstableAwaitPromise:function(){return d},apiFetch:function(){return u},controls:function(){return p},dispatch:function(){return a},select:function(){return s},syncSelect:function(){return l}});var e=window.wp.apiFetch,r=t.n(e),o=window.wp.data,i=window.wp.deprecated,c=t.n(i);function u(t){return{type:"API_FETCH",request:t}}function s(){return c()("`select` control in `@wordpress/data-controls`",{since:"5.7",alternative:"built-in `resolveSelect` control in `@wordpress/data`"}),o.controls.resolveSelect(...arguments)}function l(){return c()("`syncSelect` control in `@wordpress/data-controls`",{since:"5.7",alternative:"built-in `select` control in `@wordpress/data`"}),o.controls.select(...arguments)}function a(){return c()("`dispatch` control in `@wordpress/data-controls`",{since:"5.7",alternative:"built-in `dispatch` control in `@wordpress/data`"}),o.controls.dispatch(...arguments)}const d=function(t){return{type:"AWAIT_PROMISE",promise:t}},p={AWAIT_PROMISE:t=>{let{promise:n}=t;return n},API_FETCH(t){let{request:n}=t;return r()(n)}};(window.wp=window.wp||{}).dataControls=n}(); media-utils.js 0000666 00000055025 15123355174 0007340 0 ustar 00 /******/ (function() { // webpackBootstrap
/******/ "use strict";
/******/ // The require scope
/******/ var __webpack_require__ = {};
/******/
/************************************************************************/
/******/ /* 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__ = {};
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"MediaUpload": function() { return /* reexport */ media_upload; },
"uploadMedia": function() { return /* reexport */ uploadMedia; }
});
;// CONCATENATED MODULE: external ["wp","element"]
var external_wp_element_namespaceObject = window["wp"]["element"];
;// CONCATENATED MODULE: external ["wp","i18n"]
var external_wp_i18n_namespaceObject = window["wp"]["i18n"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/components/media-upload/index.js
/**
* WordPress dependencies
*/
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
} = window;
return wp.media.view.MediaFrame.Select.extend({
/**
* Enables the Set Featured Image Button.
*
* @param {Object} toolbar toolbar for featured image state
* @return {void}
*/
featuredImageToolbar(toolbar) {
this.createSelectToolbar(toolbar, {
text: wp.media.view.l10n.setFeaturedImage,
state: this.options.state
});
},
/**
* Handle the edit state requirements of selected media item.
*
* @return {void}
*/
editState() {
const selection = this.state('featured-image').get('selection');
const view = new wp.media.view.EditImage({
model: selection.single(),
controller: this
}).render(); // 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.
*
* @return {void}
*/
createStates: function createStates() {
this.on('toolbar:create:featured-image', this.featuredImageToolbar, this);
this.on('content:render:edit-image', this.editState, this);
this.states.add([new wp.media.controller.FeaturedImage(), new wp.media.controller.EditImage({
model: this.options.editImage
})]);
}
});
};
/**
* Prepares the Gallery toolbars and frames.
*
* @return {window.wp.media.view.MediaFrame.Post} The default media workflow.
*/
const getGalleryDetailsMediaFrame = () => {
const {
wp
} = window;
/**
* Custom gallery details frame.
*
* @see https://github.com/xwp/wp-core-media-widgets/blob/905edbccfc2a623b73a93dac803c5335519d7837/wp-admin/js/widgets/media-gallery-widget.js
* @class GalleryDetailsMediaFrame
* @class
*/
return wp.media.view.MediaFrame.Post.extend({
/**
* Set up gallery toolbar.
*
* @return {void}
*/
galleryToolbar() {
const editing = this.state().get('editing');
this.toolbar.set(new wp.media.view.Toolbar({
controller: this,
items: {
insert: {
style: 'primary',
text: editing ? wp.media.view.l10n.updateGallery : wp.media.view.l10n.insertGallery,
priority: 80,
requires: {
library: true
},
/**
* @fires wp.media.controller.State#update
*/
click() {
const controller = this.controller,
state = controller.state();
controller.close();
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.
*
* @return {void}
*/
editState() {
const selection = this.state('gallery').get('selection');
const view = new wp.media.view.EditImage({
model: selection.single(),
controller: this
}).render(); // 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.
*
* @return {void}
*/
createStates: function createStates() {
this.on('toolbar:create:main-gallery', this.galleryToolbar, this);
this.on('content:render:edit-image', this.editState, this);
this.states.add([new wp.media.controller.Library({
id: 'gallery',
title: wp.media.view.l10n.createGalleryTitle,
priority: 40,
toolbar: 'main-gallery',
filterable: 'uploaded',
multiple: 'add',
editable: false,
library: wp.media.query({
type: 'image',
...this.options.library
})
}), new wp.media.controller.EditImage({
model: this.options.editImage
}), new wp.media.controller.GalleryEdit({
library: this.options.selection,
editing: this.options.editing,
menu: 'gallery',
displaySettings: false,
multiple: true
}), new wp.media.controller.GalleryAdd()]);
}
});
}; // 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 !== null && img !== void 0 && img.hasOwnProperty(key)) {
result[key] = img[key];
}
return result;
}, {});
};
const getAttachmentsCollection = ids => {
const {
wp
} = window;
return wp.media.query({
order: 'ASC',
orderby: 'post__in',
post__in: ids,
posts_per_page: -1,
query: true,
type: 'image'
});
};
class MediaUpload extends external_wp_element_namespaceObject.Component {
constructor(_ref) {
let {
allowedTypes,
gallery = false,
unstableFeaturedImageFlow = false,
modalClass,
multiple = false,
title = (0,external_wp_i18n_namespaceObject.__)('Select or Upload Media')
} = _ref;
super(...arguments);
this.openModal = this.openModal.bind(this);
this.onOpen = this.onOpen.bind(this);
this.onSelect = this.onSelect.bind(this);
this.onUpdate = this.onUpdate.bind(this);
this.onClose = this.onClose.bind(this);
const {
wp
} = window;
if (gallery) {
this.buildAndSetGalleryFrame();
} else {
const frameConfig = {
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);
this.frame.on('update', this.onUpdate);
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.
if (value === this.lastGalleryValue) {
return;
}
const {
wp
} = window;
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(),
multiple
});
this.frame = new this.GalleryDetailsMediaFrame({
mimeType: allowedTypes,
state: currentState,
multiple,
selection,
editing: value && value.length ? true : false
});
wp.media.frame = this.frame;
this.initializeListeners();
}
/**
* Initializes the Media Library requirements for the featured image flow.
*
* @return {void}
*/
buildAndSetFeatureImageFrame() {
const {
wp
} = window;
const featuredImageFrame = getFeaturedImageMediaFrame();
const attachments = getAttachmentsCollection(this.props.value);
const selection = new wp.media.model.Selection(attachments.models, {
props: attachments.props.toJSON()
});
this.frame = new featuredImageFrame({
mimeType: this.props.allowedTypes,
state: 'featured-image',
multiple: this.props.multiple,
selection,
editing: this.props.value ? true : false
});
wp.media.frame = this.frame;
}
componentWillUnmount() {
this.frame.remove();
}
onUpdate(selections) {
const {
onSelect,
multiple = false
} = 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.
const attachment = this.frame.state().get('selection').toJSON();
onSelect(multiple ? attachment : attachment[0]);
}
onOpen() {
const {
wp
} = window;
const {
value
} = this.props;
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
// (for galleries) or a (number) singular id (e.g. image block).
const hasMedia = Array.isArray(value) ? !!(value !== null && value !== void 0 && 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.
const attachments = getAttachmentsCollection(valueArray); // Once attachments are loaded, set the current selection.
attachments.more().done(function () {
var _attachments$models;
if (isGallery && attachments !== null && attachments !== void 0 && (_attachments$models = attachments.models) !== null && _attachments$models !== void 0 && _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.
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.
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
;// CONCATENATED MODULE: external ["wp","apiFetch"]
var external_wp_apiFetch_namespaceObject = window["wp"]["apiFetch"];
var external_wp_apiFetch_default = /*#__PURE__*/__webpack_require__.n(external_wp_apiFetch_namespaceObject);
;// CONCATENATED MODULE: external ["wp","blob"]
var external_wp_blob_namespaceObject = window["wp"]["blob"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/utils/upload-media.js
/**
* WordPress dependencies
*/
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.
* Converts { jpg|jpeg|jpe: "image/jpeg" } into [ "image/jpeg", "image/jpg", "image/jpeg", "image/jpe" ]
* The computation of this array instead of directly using the object,
* solves the problem in chrome where mp3 files have audio/mp3 as mime type instead of audio/mpeg.
* https://bugs.chromium.org/p/chromium/issues/detail?id=227004
*
* @param {?Object} wpMimeTypesObject Mime type object received from the server.
* Extensions are keys separated by '|' and values are mime types associated with an extension.
*
* @return {?Array} An array of mime types or the parameter passed if it was "falsy".
*/
function getMimeTypesArray(wpMimeTypesObject) {
if (!wpMimeTypesObject) {
return wpMimeTypesObject;
}
return Object.entries(wpMimeTypesObject).map(_ref => {
let [extensionsString, mime] = _ref;
const [type] = mime.split('/');
const extensions = extensionsString.split('|');
return [mime, ...extensions.map(extension => `${type}/${extension}`)];
}).flat();
}
/**
* Media Upload is used by audio, image, gallery, video, and file blocks to
* handle uploading a media file when a file upload button is activated.
*
* TODO: future enhancement to add an upload indicator.
*
* @param {Object} $0 Parameters object passed to the function.
* @param {?Array} $0.allowedTypes Array with the types of media that can be uploaded, if unset all types are allowed.
* @param {?Object} $0.additionalData Additional data to include in the request.
* @param {Array} $0.filesList List of files.
* @param {?number} $0.maxUploadFileSize Maximum upload size in bytes allowed for the site.
* @param {Function} $0.onError Function called when an error happens.
* @param {Function} $0.onFileChange Function called each time a file or a temporary representation of the file is available.
* @param {?Object} $0.wpAllowedMimeTypes List of allowed mime types and file extensions.
*/
async function uploadMedia(_ref2) {
let {
allowedTypes,
additionalData = {},
filesList,
maxUploadFileSize,
onError = noop,
onFileChange,
wpAllowedMimeTypes = null
} = _ref2;
// Cast filesList to array.
const files = [...filesList];
const filesSet = [];
const setAndUpdateFiles = (idx, value) => {
var _filesSet$idx;
(0,external_wp_blob_namespaceObject.revokeBlobURL)((_filesSet$idx = filesSet[idx]) === null || _filesSet$idx === void 0 ? void 0 : _filesSet$idx.url);
filesSet[idx] = value;
onFileChange(filesSet.filter(Boolean));
}; // Allowed type specified by consumer.
const isAllowedType = fileType => {
if (!allowedTypes) {
return true;
}
return allowedTypes.some(allowedType => {
// If a complete mimetype is specified verify if it matches exactly the mime type of the file.
if (allowedType.includes('/')) {
return allowedType === fileType;
} // Otherwise a general mime type is used and we should verify if the file mimetype starts with it.
return fileType.startsWith(`${allowedType}/`);
});
}; // Allowed types for the current WP_User.
const allowedMimeTypesForUser = getMimeTypesArray(wpAllowedMimeTypes);
const isAllowedMimeTypeForUser = fileType => {
return allowedMimeTypesForUser.includes(fileType);
};
const validFiles = [];
for (const mediaFile of files) {
// Verify if user is allowed to upload this mime type.
// Defer to the server when type not detected.
if (allowedMimeTypesForUser && mediaFile.type && !isAllowedMimeTypeForUser(mediaFile.type)) {
onError({
code: 'MIME_TYPE_NOT_ALLOWED_FOR_USER',
message: (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: file name.
(0,external_wp_i18n_namespaceObject.__)('%s: Sorry, you are not allowed to upload this file type.'), mediaFile.name),
file: mediaFile
});
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.
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, _savedMedia$caption;
const savedMedia = await createMediaFromFile(mediaFile, additionalData); // eslint-disable-next-line camelcase
const {
alt_text,
source_url,
...savedMediaProps
} = savedMedia;
const mediaObject = { ...savedMediaProps,
alt: savedMedia.alt_text,
caption: (_savedMedia$caption$r = (_savedMedia$caption = savedMedia.caption) === null || _savedMedia$caption === void 0 ? void 0 : _savedMedia$caption.raw) !== null && _savedMedia$caption$r !== void 0 ? _savedMedia$caption$r : '',
title: savedMedia.title.raw,
url: savedMedia.source_url
};
setAndUpdateFiles(idx, mediaObject);
} catch (error) {
// 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
(0,external_wp_i18n_namespaceObject.__)('Error while uploading file %s to the media library.'), mediaFile.name);
}
onError({
code: 'GENERAL',
message,
file: mediaFile
});
}
}
}
/**
* @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(_ref3 => {
let [key, value] = _ref3;
return data.append(key, value);
});
}
return external_wp_apiFetch_default()({
path: '/wp/v2/media',
body: data,
method: 'POST'
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/utils/index.js
;// CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/index.js
(window.wp = window.wp || {}).mediaUtils = __webpack_exports__;
/******/ })()
; keycodes.min.js 0000666 00000010465 15123355174 0007512 0 ustar 00 /*! This file is auto-generated */
!function(){"use strict";var t={d:function(n,r){for(var e in r)t.o(r,e)&&!t.o(n,e)&&Object.defineProperty(n,e,{enumerable:!0,get:r[e]})},o:function(t,n){return Object.prototype.hasOwnProperty.call(t,n)},r:function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},n={};t.r(n),t.d(n,{ALT:function(){return P},BACKSPACE:function(){return d},COMMAND:function(){return L},CTRL:function(){return j},DELETE:function(){return S},DOWN:function(){return E},END:function(){return m},ENTER:function(){return p},ESCAPE:function(){return h},F10:function(){return b},HOME:function(){return A},LEFT:function(){return w},PAGEDOWN:function(){return y},PAGEUP:function(){return v},RIGHT:function(){return O},SHIFT:function(){return T},SPACE:function(){return g},TAB:function(){return s},UP:function(){return C},ZERO:function(){return _},displayShortcut:function(){return x},displayShortcutList:function(){return Z},isAppleOS:function(){return a},isKeyboardEvent:function(){return N},modifiers:function(){return k},rawShortcut:function(){return M},shortcutAriaLabel:function(){return D}});var r=function(){return r=Object.assign||function(t){for(var n,r=1,e=arguments.length;r<e;r++)for(var o in n=arguments[r])Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o]);return t},r.apply(this,arguments)};Object.create;Object.create;function e(t){return t.toLowerCase()}var o=[/([a-z0-9])([A-Z])/g,/([A-Z])([A-Z][a-z])/g],i=/[^A-Z0-9]+/gi;function u(t,n,r){return n instanceof RegExp?t.replace(n,r):n.reduce((function(t,n){return t.replace(n,r)}),t)}function c(t){return function(t){return t.charAt(0).toUpperCase()+t.substr(1)}(t.toLowerCase())}function f(t,n){return void 0===n&&(n={}),function(t,n){void 0===n&&(n={});for(var r=n.splitRegexp,c=void 0===r?o:r,f=n.stripRegexp,l=void 0===f?i:f,a=n.transform,d=void 0===a?e:a,s=n.delimiter,p=void 0===s?" ":s,h=u(u(t,c,"$1\0$2"),l,"\0"),g=0,v=h.length;"\0"===h.charAt(g);)g++;for(;"\0"===h.charAt(v-1);)v--;return h.slice(g,v).split("\0").map(d).join(p)}(t,r({delimiter:" ",transform:c},n))}var l=window.wp.i18n;function a(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;if(!t){if("undefined"==typeof window)return!1;t=window}const{platform:n}=t.navigator;return-1!==n.indexOf("Mac")||["iPad","iPhone"].includes(n)}const d=8,s=9,p=13,h=27,g=32,v=33,y=34,m=35,A=36,w=37,C=38,O=39,E=40,S=46,b=121,P="alt",j="ctrl",L="meta",T="shift",_=48;function R(t,n){return Object.fromEntries(Object.entries(t).map((t=>{let[r,e]=t;return[r,n(e)]})))}const k={primary:t=>t()?[L]:[j],primaryShift:t=>t()?[T,L]:[j,T],primaryAlt:t=>t()?[P,L]:[j,P],secondary:t=>t()?[T,P,L]:[j,T,P],access:t=>t()?[j,P]:[T,P],ctrl:()=>[j],alt:()=>[P],ctrlShift:()=>[j,T],shift:()=>[T],shiftAlt:()=>[T,P],undefined:()=>[]},M=R(k,(t=>function(n){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:a;return[...t(r),n.toLowerCase()].join("+")})),Z=R(k,(t=>function(n){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:a;const e=r(),o={[P]:e?"⌥":"Alt",[j]:e?"⌃":"Ctrl",[L]:"⌘",[T]:e?"⇧":"Shift"},i=t(r).reduce(((t,n)=>{var r;const i=null!==(r=o[n])&&void 0!==r?r:n;return e?[...t,i]:[...t,i,"+"]}),[]),u=f(n,{stripRegexp:/[^A-Z0-9~`,\.\\\-]/gi});return[...i,u]})),x=R(Z,(t=>function(n){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:a;return t(n,r).join("")})),D=R(k,(t=>function(n){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:a;const e=r(),o={[T]:"Shift",[L]:e?"Command":"Control",[j]:"Control",[P]:e?"Option":"Alt",",":(0,l.__)("Comma"),".":(0,l.__)("Period"),"`":(0,l.__)("Backtick"),"~":(0,l.__)("Tilde")};return[...t(r),n].map((t=>{var n;return f(null!==(n=o[t])&&void 0!==n?n:t)})).join(e?" ":" + ")}));function K(t){return[P,j,L,T].filter((n=>t[`${n}Key`]))}const N=R(k,(t=>function(n,r){let e=arguments.length>2&&void 0!==arguments[2]?arguments[2]:a;const o=t(e),i=K(n),u={Comma:",",Backslash:"\\",IntlRo:"\\",IntlYen:"\\"},c=o.filter((t=>!i.includes(t))),f=i.filter((t=>!o.includes(t)));if(c.length>0||f.length>0)return!1;let l=n.key.toLowerCase();return r?(n.altKey&&1===r.length&&(l=String.fromCharCode(n.keyCode).toLowerCase()),n.shiftKey&&1===r.length&&u[n.code]&&(l=u[n.code]),"del"===r&&(r="delete"),l===r.toLowerCase()):o.includes(l)}));(window.wp=window.wp||{}).keycodes=n}(); rich-text.min.js 0000666 00000102045 15123355174 0007607 0 ustar 00 /*! This file is auto-generated */
!function(){"use strict";var e={n:function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,{a:n}),n},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,{__UNSTABLE_LINE_SEPARATOR:function(){return E},__experimentalRichText:function(){return Ge},__unstableCreateElement:function(){return T},__unstableFormatEdit:function(){return Ze},__unstableInsertLineSeparator:function(){return Y},__unstableIsEmptyLine:function(){return I},__unstableToDom:function(){return me},__unstableUseRichText:function(){return Ye},applyFormat:function(){return b},concat:function(){return O},create:function(){return _},getActiveFormat:function(){return k},getActiveFormats:function(){return W},getActiveObject:function(){return M},getTextContent:function(){return j},insert:function(){return q},insertObject:function(){return G},isCollapsed:function(){return P},isEmpty:function(){return V},join:function(){return B},registerFormatType:function(){return H},remove:function(){return K},removeFormat:function(){return z},replace:function(){return X},slice:function(){return Z},split:function(){return J},store:function(){return g},toHTMLString:function(){return ve},toggleFormat:function(){return Se},unregisterFormatType:function(){return Le},useAnchor:function(){return Me},useAnchorRef:function(){return ke}});var n={};e.r(n),e.d(n,{getFormatType:function(){return u},getFormatTypeForBareElement:function(){return f},getFormatTypeForClassName:function(){return d},getFormatTypes:function(){return l}});var r={};e.r(r),e.d(r,{addFormatTypes:function(){return m},removeFormatTypes:function(){return p}});var a=window.wp.data;var o=(0,a.combineReducers)({formatTypes:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;switch(t.type){case"ADD_FORMAT_TYPES":return{...e,...t.formatTypes.reduce(((e,t)=>({...e,[t.name]:t})),{})};case"REMOVE_FORMAT_TYPES":return Object.fromEntries(Object.entries(e).filter((e=>{let[n]=e;return!t.names.includes(n)})))}return e}}),i={};function s(e){return[e]}function c(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}const l=function(e,t){var n,r=t||s;function a(e){var t,r,a,o,s,c=n,l=!0;for(t=0;t<e.length;t++){if(r=e[t],!(s=r)||"object"!=typeof s){l=!1;break}c.has(r)?c=c.get(r):(a=new WeakMap,c.set(r,a),c=a)}return c.has(i)||((o=function(){var e={clear:function(){e.head=null}};return e}()).isUniqueByDependants=l,c.set(i,o)),c.get(i)}function o(){n=new WeakMap}function l(){var t,n,o,i,s,l=arguments.length;for(i=new Array(l),o=0;o<l;o++)i[o]=arguments[o];for((t=a(s=r.apply(null,i))).isUniqueByDependants||(t.lastDependants&&!c(s,t.lastDependants,0)&&t.clear(),t.lastDependants=s),n=t.head;n;){if(c(n.args,i,1))return n!==t.head&&(n.prev.next=n.next,n.next&&(n.next.prev=n.prev),n.next=t.head,n.prev=null,t.head.prev=n,t.head=n),n.val;n=n.next}return n={val:e.apply(null,i)},i[0]=null,n.args=i,t.head&&(t.head.prev=n,n.next=t.head),t.head=n,n.val}return l.getDependants=r,l.clear=o,o(),l}((e=>Object.values(e.formatTypes)),(e=>[e.formatTypes]));function u(e,t){return e.formatTypes[t]}function f(e,t){const n=l(e);return n.find((e=>{let{className:n,tagName:r}=e;return null===n&&t===r}))||n.find((e=>{let{className:t,tagName:n}=e;return null===t&&"*"===n}))}function d(e,t){return l(e).find((e=>{let{className:n}=e;return null!==n&&` ${t} `.indexOf(` ${n} `)>=0}))}function m(e){return{type:"ADD_FORMAT_TYPES",formatTypes:Array.isArray(e)?e:[e]}}function p(e){return{type:"REMOVE_FORMAT_TYPES",names:Array.isArray(e)?e:[e]}}const g=(0,a.createReduxStore)("core/rich-text",{reducer:o,selectors:n,actions:r});function h(e,t){if(e===t)return!0;if(!e||!t)return!1;if(e.type!==t.type)return!1;const n=e.attributes,r=t.attributes;if(n===r)return!0;if(!n||!r)return!1;const a=Object.keys(n),o=Object.keys(r);if(a.length!==o.length)return!1;const i=a.length;for(let e=0;e<i;e++){const t=a[e];if(n[t]!==r[t])return!1}return!0}function v(e){const t=e.formats.slice();return t.forEach(((e,n)=>{const r=t[n-1];if(r){const a=e.slice();a.forEach(((e,t)=>{const n=r[t];h(e,n)&&(a[t]=n)})),t[n]=a}})),{...e,formats:t}}function y(e,t,n){return(e=e.slice())[t]=n,e}function b(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.start,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:e.end;const{formats:a,activeFormats:o}=e,i=a.slice();if(n===r){var s;const e=null===(s=i[n])||void 0===s?void 0:s.find((e=>{let{type:n}=e;return n===t.type}));if(e){const a=i[n].indexOf(e);for(;i[n]&&i[n][a]===e;)i[n]=y(i[n],a,t),n--;for(r++;i[r]&&i[r][a]===e;)i[r]=y(i[r],a,t),r++}}else{let e=1/0;for(let a=n;a<r;a++)if(i[a]){i[a]=i[a].filter((e=>{let{type:n}=e;return n!==t.type}));const n=i[a].length;n<e&&(e=n)}else i[a]=[],e=0;for(let a=n;a<r;a++)i[a].splice(e,0,t)}return v({...e,formats:i,activeFormats:[...(null==o?void 0:o.filter((e=>{let{type:n}=e;return n!==t.type})))||[],t]})}function T(e,t){let{implementation:n}=e;return T.body||(T.body=n.createHTMLDocument("").body),T.body.innerHTML=t,T.body}(0,a.register)(g);const E="\u2028",x="";function w(e){let t,{tagName:n,attributes:r}=e;if(r&&r.class&&(t=(0,a.select)(g).getFormatTypeForClassName(r.class),t&&(r.class=` ${r.class} `.replace(` ${t.className} `," ").trim(),r.class||delete r.class)),t||(t=(0,a.select)(g).getFormatTypeForBareElement(n)),!t)return r?{type:n,attributes:r}:{type:n};if(t.__experimentalCreatePrepareEditableTree&&!t.__experimentalCreateOnChangeEditableValue)return null;if(!r)return{type:t.name,tagName:n};const o={},i={},s={...r};for(const e in t.attributes){const n=t.attributes[e];o[e]=s[n],t.__unstableFilterAttributeValue&&(o[e]=t.__unstableFilterAttributeValue(e,o[e])),delete s[n],void 0===o[e]&&delete o[e]}for(const e in s)i[e]=r[e];return{type:t.name,tagName:n,attributes:o,unregisteredAttributes:i}}function _(){let{element:e,text:t,html:n,range:r,multilineTag:a,multilineWrapperTags:o,__unstableIsEditableTree:i,preserveWhiteSpace:s}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return"string"==typeof t&&t.length>0?{formats:Array(t.length),replacements:Array(t.length),text:t}:("string"==typeof n&&n.length>0&&(e=T(document,n)),"object"!=typeof e?{formats:[],replacements:[],text:""}:a?S({element:e,range:r,multilineTag:a,multilineWrapperTags:o,isEditableTree:i,preserveWhiteSpace:s}):R({element:e,range:r,isEditableTree:i,preserveWhiteSpace:s}))}function N(e,t,n,r){if(!n)return;const{parentNode:a}=t,{startContainer:o,startOffset:i,endContainer:s,endOffset:c}=n,l=e.text.length;void 0!==r.start?e.start=l+r.start:t===o&&t.nodeType===t.TEXT_NODE?e.start=l+i:a===o&&t===o.childNodes[i]?e.start=l:a===o&&t===o.childNodes[i-1]?e.start=l+r.text.length:t===o&&(e.start=l),void 0!==r.end?e.end=l+r.end:t===s&&t.nodeType===t.TEXT_NODE?e.end=l+c:a===s&&t===s.childNodes[c-1]?e.end=l+r.text.length:a===s&&t===s.childNodes[c]?e.end=l:t===s&&(e.end=l+c)}function F(e,t,n){if(!t)return;const{startContainer:r,endContainer:a}=t;let{startOffset:o,endOffset:i}=t;return e===r&&(o=n(e.nodeValue.slice(0,o)).length),e===a&&(i=n(e.nodeValue.slice(0,i)).length),{startContainer:r,startOffset:o,endContainer:a,endOffset:i}}function C(e){return e.replace(/[\n\r\t]+/g," ")}function A(e){return e.replace(new RegExp("[\ufeff]","gu"),"")}function R(e){let{element:t,range:n,multilineTag:r,multilineWrapperTags:a,currentWrapperTags:o=[],isEditableTree:i,preserveWhiteSpace:s}=e;const c={formats:[],replacements:[],text:""};if(!t)return c;if(!t.hasChildNodes())return N(c,t,n,{formats:[],replacements:[],text:""}),c;const l=t.childNodes.length;for(let u=0;u<l;u++){const f=t.childNodes[u],d=f.nodeName.toLowerCase();if(f.nodeType===f.TEXT_NODE){let g=A;s||(g=e=>A(C(e)));const h=g(f.nodeValue);n=F(f,n,g),N(c,f,n,{text:h}),c.formats.length+=h.length,c.replacements.length+=h.length,c.text+=h;continue}if(f.nodeType!==f.ELEMENT_NODE)continue;if(i&&(f.getAttribute("data-rich-text-placeholder")||"br"===d&&!f.getAttribute("data-rich-text-line-break"))){N(c,f,n,{formats:[],replacements:[],text:""});continue}if("script"===d){const v={formats:[,],replacements:[{type:d,attributes:{"data-rich-text-script":f.getAttribute("data-rich-text-script")||encodeURIComponent(f.innerHTML)}}],text:x};N(c,f,n,v),D(c,v);continue}if("br"===d){N(c,f,n,{formats:[],replacements:[],text:""}),D(c,_({text:"\n"}));continue}const m=w({tagName:d,attributes:L({element:f})});if(a&&-1!==a.indexOf(d)){const y=S({element:f,range:n,multilineTag:r,multilineWrapperTags:a,currentWrapperTags:[...o,m],isEditableTree:i,preserveWhiteSpace:s});N(c,f,n,y),D(c,y);continue}const p=R({element:f,range:n,multilineTag:r,multilineWrapperTags:a,isEditableTree:i,preserveWhiteSpace:s});if(N(c,f,n,p),m)if(0===p.text.length)m.attributes&&D(c,{formats:[,],replacements:[m],text:x});else{function b(e){if(b.formats===e)return b.newFormats;const t=e?[m,...e]:[m];return b.formats=e,b.newFormats=t,t}b.newFormats=[m],D(c,{...p,formats:Array.from(p.formats,b)})}else D(c,p)}return c}function S(e){let{element:t,range:n,multilineTag:r,multilineWrapperTags:a,currentWrapperTags:o=[],isEditableTree:i,preserveWhiteSpace:s}=e;const c={formats:[],replacements:[],text:""};if(!t||!t.hasChildNodes())return c;const l=t.children.length;for(let e=0;e<l;e++){const l=t.children[e];if(l.nodeName.toLowerCase()!==r)continue;const u=R({element:l,range:n,multilineTag:r,multilineWrapperTags:a,currentWrapperTags:o,isEditableTree:i,preserveWhiteSpace:s});(0!==e||o.length>0)&&D(c,{formats:[,],replacements:o.length>0?[o]:[,],text:E}),N(c,l,n,u),D(c,u)}return c}function L(e){let{element:t}=e;if(!t.hasAttributes())return;const n=t.attributes.length;let r;for(let e=0;e<n;e++){const{name:n,value:a}=t.attributes[e];if(0===n.indexOf("data-rich-text-"))continue;r=r||{},r[/^on/i.test(n)?"data-disable-rich-text-"+n:n]=a}return r}function D(e,t){return e.formats=e.formats.concat(t.formats),e.replacements=e.replacements.concat(t.replacements),e.text+=t.text,e}function O(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return v(t.reduce(D,_()))}function W(e){let{formats:t,start:n,end:r,activeFormats:a}=e,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];if(void 0===n)return o;if(n===r){if(a)return a;const e=t[n-1]||o,r=t[n]||o;return e.length<r.length?e:r}return t[n]||o}function k(e,t){var n;return null===(n=W(e))||void 0===n?void 0:n.find((e=>{let{type:n}=e;return n===t}))}function M(e){let{start:t,end:n,replacements:r,text:a}=e;if(t+1===n&&a[t]===x)return r[t]}const $=new RegExp(`[${E}]`,"g");function j(e){let{text:t}=e;return t.replace($,(e=>e===x?"":"\n"))}function P(e){let{start:t,end:n}=e;if(void 0!==t&&void 0!==n)return t===n}function V(e){let{text:t}=e;return 0===t.length}function I(e){let{text:t,start:n,end:r}=e;return n===r&&(0===t.length||(0===n&&t.slice(0,1)===E||(n===t.length&&t.slice(-1)===E||t.slice(n-1,r+1)===`${E}${E}`)))}function B(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";return"string"==typeof t&&(t=_({text:t})),v(e.reduce(((e,n)=>{let{formats:r,replacements:a,text:o}=n;return{formats:e.formats.concat(t.formats,r),replacements:e.replacements.concat(t.replacements,a),text:e.text+t.text+o}})))}function H(e,t){if("string"==typeof(t={name:e,...t}).name)if(/^[a-z][a-z0-9-]*\/[a-z][a-z0-9-]*$/.test(t.name))if((0,a.select)(g).getFormatType(t.name))window.console.error('Format "'+t.name+'" is already registered.');else if("string"==typeof t.tagName&&""!==t.tagName)if("string"==typeof t.className&&""!==t.className||null===t.className)if(/^[_a-zA-Z]+[a-zA-Z0-9-]*$/.test(t.className)){if(null===t.className){const e=(0,a.select)(g).getFormatTypeForBareElement(t.tagName);if(e&&"core/unknown"!==e.name)return void window.console.error(`Format "${e.name}" is already registered to handle bare tag name "${t.tagName}".`)}else{const e=(0,a.select)(g).getFormatTypeForClassName(t.className);if(e)return void window.console.error(`Format "${e.name}" is already registered to handle class name "${t.className}".`)}if("title"in t&&""!==t.title)if("keywords"in t&&t.keywords.length>3)window.console.error('The format "'+t.name+'" can have a maximum of 3 keywords.');else{if("string"==typeof t.title)return(0,a.dispatch)(g).addFormatTypes(t),t;window.console.error("Format titles must be strings.")}else window.console.error('The format "'+t.name+'" must have a title.')}else window.console.error("A class name must begin with a letter, followed by any number of hyphens, letters, or numbers.");else window.console.error("Format class names must be a string, or null to handle bare elements.");else window.console.error("Format tag names must be a string.");else window.console.error("Format names must contain a namespace prefix, include only lowercase alphanumeric characters or dashes, and start with a letter. Example: my-plugin/my-custom-format");else window.console.error("Format names must be strings.")}function z(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.start,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:e.end;const{formats:a,activeFormats:o}=e,i=a.slice();if(n===r){var s;const e=null===(s=i[n])||void 0===s?void 0:s.find((e=>{let{type:n}=e;return n===t}));if(e){for(;null!==(c=i[n])&&void 0!==c&&c.find((t=>t===e));){var c;U(i,n,t),n--}for(r++;null!==(l=i[r])&&void 0!==l&&l.find((t=>t===e));){var l;U(i,r,t),r++}}}else for(let e=n;e<r;e++)i[e]&&U(i,e,t);return v({...e,formats:i,activeFormats:(null==o?void 0:o.filter((e=>{let{type:n}=e;return n!==t})))||[]})}function U(e,t,n){const r=e[t].filter((e=>{let{type:t}=e;return t!==n}));r.length?e[t]=r:delete e[t]}function q(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.start,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:e.end;const{formats:a,replacements:o,text:i}=e;"string"==typeof t&&(t=_({text:t}));const s=n+t.text.length;return v({formats:a.slice(0,n).concat(t.formats,a.slice(r)),replacements:o.slice(0,n).concat(t.replacements,o.slice(r)),text:i.slice(0,n)+t.text+i.slice(r),start:s,end:s})}function K(e,t,n){return q(e,_(),t,n)}function X(e,t,n){let{formats:r,replacements:a,text:o,start:i,end:s}=e;return o=o.replace(t,(function(e){for(var t=arguments.length,o=new Array(t>1?t-1:0),c=1;c<t;c++)o[c-1]=arguments[c];const l=o[o.length-2];let u,f,d=n;return"function"==typeof d&&(d=n(e,...o)),"object"==typeof d?(u=d.formats,f=d.replacements,d=d.text):(u=Array(d.length),f=Array(d.length),r[l]&&(u=u.fill(r[l]))),r=r.slice(0,l).concat(u,r.slice(l+e.length)),a=a.slice(0,l).concat(f,a.slice(l+e.length)),i&&(i=s=l+d.length),d})),v({formats:r,replacements:a,text:o,start:i,end:s})}function Y(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.start,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.end;const r=e.text.slice(0,t),a=r.lastIndexOf(E),o=e.replacements[a];let i=[,];o&&(i=[o]);const s={formats:[,],replacements:i,text:E};return q(e,s,t,n)}function G(e,t,n,r){return q(e,{formats:[,],replacements:[t],text:x},n,r)}function Z(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.start,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.end;const{formats:r,replacements:a,text:o}=e;return void 0===t||void 0===n?{...e}:{formats:r.slice(t,n),replacements:a.slice(t,n),text:o.slice(t,n)}}function J(e,t){let{formats:n,replacements:r,text:a,start:o,end:i}=e;if("string"!=typeof t)return Q(...arguments);let s=0;return a.split(t).map((e=>{const a=s,c={formats:n.slice(a,a+e.length),replacements:r.slice(a,a+e.length),text:e};return s+=t.length+e.length,void 0!==o&&void 0!==i&&(o>=a&&o<s?c.start=o-a:o<a&&i>a&&(c.start=0),i>=a&&i<s?c.end=i-a:o<s&&i>s&&(c.end=e.length)),c}))}function Q(e){let{formats:t,replacements:n,text:r,start:a,end:o}=e,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:a,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:o;if(void 0===a||void 0===o)return;const c={formats:t.slice(0,i),replacements:n.slice(0,i),text:r.slice(0,i)},l={formats:t.slice(s),replacements:n.slice(s),text:r.slice(s),start:0,end:0};return[X(c,/\u2028+$/,""),X(l,/^\u2028+/,"")]}function ee(e,t){if(t)return e;const n={};for(const t in e){let r=t;t.startsWith("data-disable-rich-text-")&&(r=t.slice("data-disable-rich-text-".length)),n[r]=e[t]}return n}function te(e){let{type:t,tagName:n,attributes:r,unregisteredAttributes:o,object:i,boundaryClass:s,isEditableTree:c}=e;const l=(u=t,(0,a.select)(g).getFormatType(u));var u;let f={};if(s&&(f["data-rich-text-format-boundary"]="true"),!l)return r&&(f={...r,...f}),{type:t,attributes:ee(f,c),object:i};f={...o,...f};for(const e in r){const t=!!l.attributes&&l.attributes[e];t?f[t]=r[e]:f[e]=r[e]}return l.className&&(f.class?f.class=`${l.className} ${f.class}`:f.class=l.className),{type:"*"===l.tagName?n:l.tagName,object:l.object,attributes:ee(f,c)}}function ne(e,t,n){do{if(e[n]!==t[n])return!1}while(n--);return!0}function re(e){let{value:t,multilineTag:n,preserveWhiteSpace:r,createEmpty:a,append:o,getLastChild:i,getParent:s,isText:c,getText:l,remove:u,appendText:f,onStartIndex:d,onEndIndex:m,isEditableTree:p,placeholder:g}=e;const{formats:h,replacements:v,text:y,start:b,end:T}=t,w=h.length+1,_=a(),N={type:n},F=W(t),C=F[F.length-1];let A,R,S;n?(o(o(_,{type:n}),""),R=A=[N]):o(_,"");for(let e=0;e<w;e++){const t=y.charAt(e),a=p&&(!S||S===E||"\n"===S);let w=h[e];n&&(w=t===E?A=(v[e]||[]).reduce(((e,t)=>(e.push(t,N),e)),[N]):[...A,...w||[]]);let F=i(_);if(a&&t===E){let e=F;for(;!c(e);)e=i(e);o(s(e),"\ufeff")}if(S===E){let t=F;for(;!c(t);)t=i(t);d&&b===e&&d(_,t),m&&T===e&&m(_,t)}if(w&&w.forEach(((e,n)=>{if(F&&R&&ne(w,R,n)&&(t!==E||w.length-1!==n))return void(F=i(F));const{type:r,tagName:a,attributes:f,unregisteredAttributes:d}=e,m=p&&t!==E&&e===C,g=s(F),h=o(g,te({type:r,tagName:a,attributes:f,unregisteredAttributes:d,boundaryClass:m,isEditableTree:p}));c(F)&&0===l(F).length&&u(F),F=o(h,"")})),t!==E){var L;if(0===e&&(d&&0===b&&d(_,F),m&&0===T&&m(_,F)),t===x)p||"script"!==(null===(L=v[e])||void 0===L?void 0:L.type)?F=o(s(F),te({...v[e],object:!0,isEditableTree:p})):(F=o(s(F),te({type:"script",isEditableTree:p})),o(F,{html:decodeURIComponent(v[e].attributes["data-rich-text-script"])})),F=o(s(F),"");else r||"\n"!==t?c(F)?f(F,t):F=o(s(F),t):(F=o(s(F),{type:"br",attributes:p?{"data-rich-text-line-break":"true"}:void 0,object:!0}),F=o(s(F),""));d&&b===e+1&&d(_,F),m&&T===e+1&&m(_,F),a&&e===y.length&&(o(s(F),"\ufeff"),g&&0===y.length&&o(s(F),{type:"span",attributes:{"data-rich-text-placeholder":g,contenteditable:"false",style:"pointer-events:none;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;"}})),R=w,S=t}else R=w,S=t}return _}function ae(e,t,n){const r=e.parentNode;let a=0;for(;e=e.previousSibling;)a++;return n=[a,...n],r!==t&&(n=ae(r,t,n)),n}function oe(e,t){for(t=[...t];e&&t.length>1;)e=e.childNodes[t.shift()];return{node:e,offset:t[0]}}function ie(e,t){"string"==typeof t&&(t=e.ownerDocument.createTextNode(t));const{type:n,attributes:r}=t;if(n){t=e.ownerDocument.createElement(n);for(const e in r)t.setAttribute(e,r[e])}return e.appendChild(t)}function se(e,t){e.appendData(t)}function ce(e){let{lastChild:t}=e;return t}function le(e){let{parentNode:t}=e;return t}function ue(e){return e.nodeType===e.TEXT_NODE}function fe(e){let{nodeValue:t}=e;return t}function de(e){return e.parentNode.removeChild(e)}function me(e){let{value:t,multilineTag:n,prepareEditableTree:r,isEditableTree:a=!0,placeholder:o,doc:i=document}=e,s=[],c=[];r&&(t={...t,formats:r(t)});return{body:re({value:t,multilineTag:n,createEmpty:()=>T(i,""),append:ie,getLastChild:ce,getParent:le,isText:ue,getText:fe,remove:de,appendText:se,onStartIndex(e,t){s=ae(t,e,[t.nodeValue.length])},onEndIndex(e,t){c=ae(t,e,[t.nodeValue.length])},isEditableTree:a,placeholder:o}),selection:{startPath:s,endPath:c}}}function pe(e){let{value:t,current:n,multilineTag:r,prepareEditableTree:a,__unstableDomOnly:o,placeholder:i}=e;const{body:s,selection:c}=me({value:t,multilineTag:r,prepareEditableTree:a,placeholder:i,doc:n.ownerDocument});ge(s,n),void 0===t.start||o||function(e,t){let{startPath:n,endPath:r}=e;const{node:a,offset:o}=oe(t,n),{node:i,offset:s}=oe(t,r),{ownerDocument:c}=t,{defaultView:l}=c,u=l.getSelection(),f=c.createRange();f.setStart(a,o),f.setEnd(i,s);const{activeElement:d}=c;if(u.rangeCount>0){if(m=f,p=u.getRangeAt(0),m.startContainer===p.startContainer&&m.startOffset===p.startOffset&&m.endContainer===p.endContainer&&m.endOffset===p.endOffset)return;u.removeAllRanges()}var m,p;u.addRange(f),d!==c.activeElement&&d instanceof l.HTMLElement&&d.focus()}(c,n)}function ge(e,t){let n,r=0;for(;n=e.firstChild;){const a=t.childNodes[r];if(a)if(a.isEqualNode(n))e.removeChild(n);else if(a.nodeName!==n.nodeName||a.nodeType===a.TEXT_NODE&&a.data!==n.data)t.replaceChild(n,a);else{const t=a.attributes,r=n.attributes;if(t){let e=t.length;for(;e--;){const{name:r}=t[e];n.getAttribute(r)||a.removeAttribute(r)}}if(r)for(let e=0;e<r.length;e++){const{name:t,value:n}=r[e];a.getAttribute(t)!==n&&a.setAttribute(t,n)}ge(n,a),e.removeChild(n)}else t.appendChild(n);r++}for(;t.childNodes[r];)t.removeChild(t.childNodes[r])}var he=window.wp.escapeHtml;function ve(e){let{value:t,multilineTag:n,preserveWhiteSpace:r}=e;return Ce(re({value:t,multilineTag:n,preserveWhiteSpace:r,createEmpty:ye,append:Te,getLastChild:be,getParent:xe,isText:we,getText:_e,remove:Ne,appendText:Ee}).children)}function ye(){return{}}function be(e){let{children:t}=e;return t&&t[t.length-1]}function Te(e,t){return"string"==typeof t&&(t={text:t}),t.parent=e,e.children=e.children||[],e.children.push(t),t}function Ee(e,t){e.text+=t}function xe(e){let{parent:t}=e;return t}function we(e){let{text:t}=e;return"string"==typeof t}function _e(e){let{text:t}=e;return t}function Ne(e){const t=e.parent.children.indexOf(e);return-1!==t&&e.parent.children.splice(t,1),e}function Fe(e){let{type:t,attributes:n,object:r,children:a}=e,o="";for(const e in n)(0,he.isValidAttributeName)(e)&&(o+=` ${e}="${(0,he.escapeAttribute)(n[e])}"`);return r?`<${t}${o}>`:`<${t}${o}>${Ce(a)}</${t}>`}function Ce(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return e.map((e=>void 0!==e.html?e.html:void 0===e.text?Fe(e):(0,he.escapeEditableHTML)(e.text))).join("")}var Ae=window.wp.a11y,Re=window.wp.i18n;function Se(e,t){return k(e,t.type)?(t.title&&(0,Ae.speak)((0,Re.sprintf)((0,Re.__)("%s removed."),t.title),"assertive"),z(e,t.type)):(t.title&&(0,Ae.speak)((0,Re.sprintf)((0,Re.__)("%s applied."),t.title),"assertive"),b(e,t))}function Le(e){const t=(0,a.select)(g).getFormatType(e);if(t)return(0,a.dispatch)(g).removeFormatTypes(e),t;window.console.error(`Format ${e} is not registered.`)}var De=window.wp.element,Oe=window.wp.deprecated,We=e.n(Oe);function ke(e){let{ref:t,value:n,settings:r={}}=e;We()("`useAnchorRef` hook",{since:"6.1",alternative:"`useAnchor` hook"});const{tagName:a,className:o,name:i}=r,s=i?k(n,i):void 0;return(0,De.useMemo)((()=>{if(!t.current)return;const{ownerDocument:{defaultView:e}}=t.current,n=e.getSelection();if(!n.rangeCount)return;const r=n.getRangeAt(0);if(!s)return r;let i=r.startContainer;for(i=i.nextElementSibling||i;i.nodeType!==i.ELEMENT_NODE;)i=i.parentNode;return i.closest(a+(o?"."+o:""))}),[s,n.start,n.end,a,o])}function Me(e){let{editableContentElement:t,value:n,settings:r={}}=e;const{tagName:a,className:o,name:i}=r,s=i?k(n,i):void 0;return(0,De.useMemo)((()=>{if(!t)return;const{ownerDocument:{defaultView:e}}=t,n=e.getSelection();if(!n.rangeCount)return;const r=null==t?void 0:t.contains(null==n?void 0:n.anchorNode),i=n.getRangeAt(0);if(!s)return{ownerDocument:i.startContainer.ownerDocument,getBoundingClientRect(){return r?i.getBoundingClientRect():t.getBoundingClientRect()}};let c=i.startContainer;for(c=c.nextElementSibling||c;c.nodeType!==c.ELEMENT_NODE;)c=c.parentNode;return c.closest(a+(o?"."+o:""))}),[t,s,n.start,n.end,a,o])}var $e=window.wp.compose;function je(e){let{record:t}=e;const n=(0,De.useRef)(),{activeFormats:r=[]}=t.current;return(0,De.useEffect)((()=>{if(!r||!r.length)return;const e="*[data-rich-text-format-boundary]",t=n.current.querySelector(e);if(!t)return;const{ownerDocument:a}=t,{defaultView:o}=a,i=`${`.rich-text:focus ${e}`} {${`background-color: ${o.getComputedStyle(t).color.replace(")",", 0.2)").replace("rgb","rgba")}`}}`,s="rich-text-boundary-style";let c=a.getElementById(s);c||(c=a.createElement("style"),c.id=s,a.head.appendChild(c)),c.innerHTML!==i&&(c.innerHTML=i)}),[r]),n}function Pe(e){const t=(0,De.useRef)(e);return t.current=e,(0,$e.useRefEffect)((e=>{function n(n){const{record:r,multilineTag:a,preserveWhiteSpace:o}=t.current;if(P(r.current)||!e.contains(e.ownerDocument.activeElement))return;const i=Z(r.current),s=j(i),c=ve({value:i,multilineTag:a,preserveWhiteSpace:o});n.clipboardData.setData("text/plain",s),n.clipboardData.setData("text/html",c),n.clipboardData.setData("rich-text","true"),n.clipboardData.setData("rich-text-multi-line-tag",a||""),n.preventDefault()}return e.addEventListener("copy",n),()=>{e.removeEventListener("copy",n)}}),[])}var Ve=window.wp.keycodes;const Ie=[];function Be(e){const[,t]=(0,De.useReducer)((()=>({}))),n=(0,De.useRef)(e);return n.current=e,(0,$e.useRefEffect)((e=>{function r(r){const{keyCode:a,shiftKey:o,altKey:i,metaKey:s,ctrlKey:c}=r;if(o||i||s||c||a!==Ve.LEFT&&a!==Ve.RIGHT)return;const{record:l,applyRecord:u}=n.current,{text:f,formats:d,start:m,end:p,activeFormats:g=[]}=l.current,h=P(l.current),{ownerDocument:v}=e,{defaultView:y}=v,{direction:b}=y.getComputedStyle(e),T="rtl"===b?Ve.RIGHT:Ve.LEFT,E=r.keyCode===T;if(h&&0===g.length){if(0===m&&E)return;if(p===f.length&&!E)return}if(!h)return;const x=d[m-1]||Ie,w=d[m]||Ie,_=E?x:w,N=g.every(((e,t)=>e===_[t]));let F=g.length;if(N?F<_.length&&F++:F--,F===g.length)return void(l.current._newActiveFormats=_);r.preventDefault();const C=(N?_:E?w:x).slice(0,F),A={...l.current,activeFormats:C};l.current=A,u(A),t()}return e.addEventListener("keydown",r),()=>{e.removeEventListener("keydown",r)}}),[])}const He=new Set(["insertParagraph","insertOrderedList","insertUnorderedList","insertHorizontalRule","insertLink"]),ze=[],Ue="data-rich-text-placeholder";function qe(e){const t=(0,De.useRef)(e);return t.current=e,(0,$e.useRefEffect)((e=>{const{ownerDocument:n}=e,{defaultView:r}=n;let a,o=!1;function i(e){if(o)return;let n;e&&(n=e.inputType);const{record:r,applyRecord:a,createRecord:i,handleChange:s}=t.current;if(n&&(0===n.indexOf("format")||He.has(n)))return void a(r.current);const c=i(),{start:l,activeFormats:u=[]}=r.current,f=function(e){let{value:t,start:n,end:r,formats:a}=e;const o=Math.min(n,r),i=Math.max(n,r),s=t.formats[o-1]||[],c=t.formats[i]||[];for(t.activeFormats=a.map(((e,t)=>{if(s[t]){if(h(e,s[t]))return s[t]}else if(c[t]&&h(e,c[t]))return c[t];return e}));--r>=n;)t.activeFormats.length>0?t.formats[r]=t.activeFormats:delete t.formats[r];return t}({value:c,start:l,end:c.start,formats:u});s(f)}function s(a){const{record:s,applyRecord:c,createRecord:l,isSelected:u,onSelectionChange:f}=t.current;if("true"!==e.contentEditable)return;if(n.activeElement!==e){if("true"!==n.activeElement.contentEditable)return;if(!n.activeElement.contains(e))return;const t=r.getSelection(),{anchorNode:a,focusNode:o}=t;if(e.contains(a)&&e!==a&&e.contains(o)&&e!==o){const{start:e,end:t}=l();s.current.activeFormats=ze,f(e,t)}else if(e.contains(a)&&e!==a){const{start:e,end:t=e}=l();s.current.activeFormats=ze,f(t)}else if(e.contains(o)){const{start:e,end:t=e}=l();s.current.activeFormats=ze,f(void 0,t)}return}if("selectionchange"!==a.type&&!u)return;if(o)return;const{start:d,end:m,text:p}=l(),g=s.current;if(p!==g.text)return void i();if(d===g.start&&m===g.end)return void(0===g.text.length&&0===d&&function(e){const t=e.getSelection(),{anchorNode:n,anchorOffset:r}=t;if(n.nodeType!==n.ELEMENT_NODE)return;const a=n.childNodes[r];a&&a.nodeType===a.ELEMENT_NODE&&a.hasAttribute(Ue)&&t.collapseToStart()}(r));const h={...g,start:d,end:m,activeFormats:g._newActiveFormats,_newActiveFormats:void 0},v=W(h,ze);h.activeFormats=v,s.current=h,c(h,{domOnly:!0}),f(d,m)}function c(){var t;o=!0,n.removeEventListener("selectionchange",s),null===(t=e.querySelector(`[${Ue}]`))||void 0===t||t.remove()}function l(){o=!1,i({inputType:"insertText"}),n.addEventListener("selectionchange",s)}function u(){const{record:n,isSelected:o,onSelectionChange:i,applyRecord:c}=t.current;if(!e.parentElement.closest('[contenteditable="true"]')){if(o)c(n.current),i(n.current.start,n.current.end);else{const e=void 0;n.current={...n.current,start:e,end:e,activeFormats:ze},i(e,e)}a=r.requestAnimationFrame(s)}}return e.addEventListener("input",i),e.addEventListener("compositionstart",c),e.addEventListener("compositionend",l),e.addEventListener("focus",u),e.addEventListener("keyup",s),e.addEventListener("mouseup",s),e.addEventListener("touchend",s),n.addEventListener("selectionchange",s),()=>{e.removeEventListener("input",i),e.removeEventListener("compositionstart",c),e.removeEventListener("compositionend",l),e.removeEventListener("focus",u),e.removeEventListener("keyup",s),e.removeEventListener("mouseup",s),e.removeEventListener("touchend",s),n.removeEventListener("selectionchange",s),r.cancelAnimationFrame(a)}}),[])}function Ke(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const{replacements:n,text:r,start:a,end:o}=e,i=P(e);let s,c=a-1,l=i?a-1:a,u=o;if(t||(c=o,l=a,u=i?o+1:o),r[c]===E){if(i&&n[c]&&n[c].length){const t=n.slice();t[c]=n[c].slice(0,-1),s={...e,replacements:t}}else s=K(e,l,u);return s}}function Xe(e){const t=(0,De.useRef)(e);return t.current=e,(0,$e.useRefEffect)((e=>{function n(e){const{keyCode:n}=e,{createRecord:r,handleChange:a,multilineTag:o}=t.current;if(e.defaultPrevented)return;if(n!==Ve.DELETE&&n!==Ve.BACKSPACE)return;const i=r(),{start:s,end:c,text:l}=i,u=n===Ve.BACKSPACE;if(0===s&&0!==c&&c===l.length)return a(K(i)),void e.preventDefault();if(o){let t;t=u&&0===i.start&&0===i.end&&I(i)?Ke(i,!u):Ke(i,u),t&&(a(t),e.preventDefault())}}return e.addEventListener("keydown",n),()=>{e.removeEventListener("keydown",n)}}),[])}function Ye(e){let{value:t="",selectionStart:n,selectionEnd:r,placeholder:o,preserveWhiteSpace:i,onSelectionChange:s,onChange:c,__unstableMultilineTag:l,__unstableDisableFormats:u,__unstableIsSelected:f,__unstableDependencies:d=[],__unstableAfterParse:m,__unstableBeforeSerialize:p,__unstableAddInvisibleFormats:g}=e;const h=(0,a.useRegistry)(),[,v]=(0,De.useReducer)((()=>({}))),y=(0,De.useRef)();function b(){const{ownerDocument:{defaultView:e}}=y.current,t=e.getSelection(),n=t.rangeCount>0?t.getRangeAt(0):null;return _({element:y.current,range:n,multilineTag:l,multilineWrapperTags:"li"===l?["ul","ol"]:void 0,__unstableIsEditableTree:!0,preserveWhiteSpace:i})}function T(e){let{domOnly:t}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};pe({value:e,current:y.current,multilineTag:l,multilineWrapperTags:"li"===l?["ul","ol"]:void 0,prepareEditableTree:g,__unstableDomOnly:t,placeholder:o})}const E=(0,De.useRef)(t),x=(0,De.useRef)();function w(){E.current=t,x.current=_({html:t,multilineTag:l,multilineWrapperTags:"li"===l?["ul","ol"]:void 0,preserveWhiteSpace:i}),u&&(x.current.formats=Array(t.length),x.current.replacements=Array(t.length)),m&&(x.current.formats=m(x.current)),x.current.start=n,x.current.end=r}const N=(0,De.useRef)(!1);if(x.current)n===x.current.start&&r===x.current.end||(N.current=f,x.current={...x.current,start:n,end:r});else{var F,C,A;w();"core/text-color"===(null===(F=x.current)||void 0===F||null===(C=F.formats[0])||void 0===C||null===(A=C[0])||void 0===A?void 0:A.type)&&function(e){x.current=e,E.current=ve({value:p?{...e,formats:p(e)}:e,multilineTag:l,preserveWhiteSpace:i});const{formats:t,text:n}=e;h.batch((()=>{c(E.current,{__unstableFormats:t,__unstableText:n})})),v()}(x.current)}function R(e){x.current=e,T(e),E.current=u?e.text:ve({value:p?{...e,formats:p(e)}:e,multilineTag:l,preserveWhiteSpace:i});const{start:t,end:n,formats:r,text:a}=e;h.batch((()=>{s(t,n),c(E.current,{__unstableFormats:r,__unstableText:a})})),v()}function S(){w(),T(x.current)}const L=(0,De.useRef)(!1);(0,De.useLayoutEffect)((()=>{L.current&&t!==E.current&&(S(),v())}),[t]),(0,De.useLayoutEffect)((()=>{N.current&&(y.current.ownerDocument.activeElement!==y.current&&y.current.focus(),S(),N.current=!1)}),[N.current]);const D=(0,$e.useMergeRefs)([y,(0,De.useCallback)((e=>{e&&(e.style.whiteSpace="pre-wrap",e.style.minWidth="1px")}),[]),je({record:x}),Pe({record:x,multilineTag:l,preserveWhiteSpace:i}),(0,$e.useRefEffect)((e=>{function t(t){const{target:n}=t;if(n===e||n.textContent)return;const{ownerDocument:r}=n,{defaultView:a}=r,o=r.createRange(),i=a.getSelection();o.selectNode(n),i.removeAllRanges(),i.addRange(o)}return e.addEventListener("click",t),()=>{e.removeEventListener("click",t)}}),[]),Be({record:x,applyRecord:T}),Xe({createRecord:b,handleChange:R,multilineTag:l}),qe({record:x,applyRecord:T,createRecord:b,handleChange:R,isSelected:f,onSelectionChange:s}),(0,$e.useRefEffect)((()=>{S(),L.current=!0}),[o,...d])]);return{value:x.current,getValue:()=>x.current,onChange:R,ref:D}}function Ge(){}function Ze(e){let{formatTypes:t,onChange:n,onFocus:r,value:a,forwardedRef:o}=e;return t.map((e=>{const{name:t,edit:i}=e;if(!i)return null;const s=k(a,t),c=void 0!==s,l=M(a),u=void 0!==l&&l.type===t;return(0,De.createElement)(i,{key:t,isActive:c,activeAttributes:c&&s.attributes||{},isObjectActive:u,activeObjectAttributes:u&&l.attributes||{},value:a,onChange:n,onFocus:r,contentRef:o})}))}(window.wp=window.wp||{}).richText=t}(); annotations.min.js 0000666 00000016125 15123355174 0010240 0 ustar 00 /*! 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,{store:function(){return B}});var n={};e.r(n),e.d(n,{__experimentalGetAllAnnotationsForBlock:function(){return N},__experimentalGetAnnotations:function(){return w},__experimentalGetAnnotationsForBlock:function(){return b},__experimentalGetAnnotationsForRichText:function(){return O}});var r={};e.r(r),e.d(r,{__experimentalAddAnnotation:function(){return F},__experimentalRemoveAnnotation:function(){return G},__experimentalRemoveAnnotationsBySource:function(){return j},__experimentalUpdateAnnotationRange:function(){return V}});var o=window.wp.richText,a=window.wp.i18n;const i="core/annotations",u="core/annotation",l="annotation-text-";const c={name:u,title:(0,a.__)("Annotation"),tagName:"mark",className:"annotation-text",attributes:{className:"class",id:"id"},edit(){return null},__experimentalGetPropsForEditableTreePreparation(e,t){let{richTextIdentifier:n,blockClientId:r}=t;return{annotations:e(i).__experimentalGetAnnotationsForRichText(r,n)}},__experimentalCreatePrepareEditableTree(e){let{annotations:t}=e;return(e,n)=>{if(0===t.length)return e;let r={formats:e,text:n};return r=function(e){return(arguments.length>1&&void 0!==arguments[1]?arguments[1]:[]).forEach((t=>{let{start:n,end:r}=t;n>e.text.length&&(n=e.text.length),r>e.text.length&&(r=e.text.length);const a=l+t.source,i=l+t.id;e=(0,o.applyFormat)(e,{type:u,attributes:{className:a,id:i}},n,r)})),e}(r,t),r.formats}},__experimentalGetPropsForEditableTreeChangeHandler(e){return{removeAnnotation:e(i).__experimentalRemoveAnnotation,updateAnnotationRange:e(i).__experimentalUpdateAnnotationRange}},__experimentalCreateOnChangeEditableValue(e){return t=>{const n=function(e){const t={};return e.forEach(((e,n)=>{(e=(e=e||[]).filter((e=>e.type===u))).forEach((e=>{let{id:r}=e.attributes;r=r.replace(l,""),t.hasOwnProperty(r)||(t[r]={start:n}),t[r].end=n+1}))})),t}(t),{removeAnnotation:r,updateAnnotationRange:o,annotations:a}=e;!function(e,t,n){let{removeAnnotation:r,updateAnnotationRange:o}=n;e.forEach((e=>{const n=t[e.id];if(!n)return void r(e.id);const{start:a,end:i}=e;a===n.start&&i===n.end||o(e.id,n.start,n.end)}))}(a,n,{removeAnnotation:r,updateAnnotationRange:o})}}},{name:s,...d}=c;(0,o.registerFormatType)(s,d);var p=window.wp.hooks,f=window.wp.data;function v(e,t){const n=e.filter(t);return e.length===n.length?e:n}(0,p.addFilter)("editor.BlockListBlock","core/annotations",(e=>(0,f.withSelect)(((e,t)=>{let{clientId:n,className:r}=t;return{className:e(i).__experimentalGetAnnotationsForBlock(n).map((e=>"is-annotated-by-"+e.source)).concat(r).filter(Boolean).join(" ")}}))(e)));const g=(e,t)=>Object.entries(e).reduce(((e,n)=>{let[r,o]=n;return{...e,[r]:t(o)}}),{});function m(e){return"number"==typeof e.start&&"number"==typeof e.end&&e.start<=e.end}var h=function(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;switch(n.type){case"ANNOTATION_ADD":const r=n.blockClientId,o={id:n.id,blockClientId:r,richTextIdentifier:n.richTextIdentifier,source:n.source,selector:n.selector,range:n.range};if("range"===o.selector&&!m(o.range))return t;const a=null!==(e=null==t?void 0:t[r])&&void 0!==e?e:[];return{...t,[r]:[...a,o]};case"ANNOTATION_REMOVE":return g(t,(e=>v(e,(e=>e.id!==n.annotationId))));case"ANNOTATION_UPDATE_RANGE":return g(t,(e=>{let t=!1;const r=e.map((e=>e.id===n.annotationId?(t=!0,{...e,range:{start:n.start,end:n.end}}):e));return t?r:e}));case"ANNOTATION_REMOVE_SOURCE":return g(t,(e=>v(e,(e=>e.source!==n.source))))}return t},_={};function A(e){return[e]}function y(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 x(e,t){var n,r=t||A;function o(e){var t,r,o,a,i,u=n,l=!0;for(t=0;t<e.length;t++){if(r=e[t],!(i=r)||"object"!=typeof i){l=!1;break}u.has(r)?u=u.get(r):(o=new WeakMap,u.set(r,o),u=o)}return u.has(_)||((a=function(){var e={clear:function(){e.head=null}};return e}()).isUniqueByDependants=l,u.set(_,a)),u.get(_)}function a(){n=new WeakMap}function i(){var t,n,a,i,u,l=arguments.length;for(i=new Array(l),a=0;a<l;a++)i[a]=arguments[a];for((t=o(u=r.apply(null,i))).isUniqueByDependants||(t.lastDependants&&!y(u,t.lastDependants,0)&&t.clear(),t.lastDependants=u),n=t.head;n;){if(y(n.args,i,1))return n!==t.head&&(n.prev.next=n.next,n.next&&(n.next.prev=n.prev),n.next=t.head,n.prev=null,t.head.prev=n,t.head=n),n.val;n=n.next}return n={val:e.apply(null,i)},i[0]=null,n.args=i,t.head&&(t.head.prev=n,n.next=t.head),t.head=n,n.val}return i.getDependants=r,i.clear=a,a(),i}const T=[],b=x(((e,t)=>{var n;return(null!==(n=null==e?void 0:e[t])&&void 0!==n?n:[]).filter((e=>"block"===e.selector))}),((e,t)=>{var n;return[null!==(n=null==e?void 0:e[t])&&void 0!==n?n:T]}));function N(e,t){var n;return null!==(n=null==e?void 0:e[t])&&void 0!==n?n:T}const O=x(((e,t,n)=>{var r;return(null!==(r=null==e?void 0:e[t])&&void 0!==r?r:[]).filter((e=>"range"===e.selector&&n===e.richTextIdentifier)).map((e=>{const{range:t,...n}=e;return{...t,...n}}))}),((e,t)=>{var n;return[null!==(n=null==e?void 0:e[t])&&void 0!==n?n:T]}));function w(e){return Object.values(e).flat()}var I,R=new Uint8Array(16);function E(){if(!I&&!(I="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return I(R)}var k=/^(?:[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;for(var C=function(e){return"string"==typeof e&&k.test(e)},D=[],S=0;S<256;++S)D.push((S+256).toString(16).substr(1));var P=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=(D[e[t+0]]+D[e[t+1]]+D[e[t+2]]+D[e[t+3]]+"-"+D[e[t+4]]+D[e[t+5]]+"-"+D[e[t+6]]+D[e[t+7]]+"-"+D[e[t+8]]+D[e[t+9]]+"-"+D[e[t+10]]+D[e[t+11]]+D[e[t+12]]+D[e[t+13]]+D[e[t+14]]+D[e[t+15]]).toLowerCase();if(!C(n))throw TypeError("Stringified UUID is invalid");return n};var U=function(e,t,n){var r=(e=e||{}).random||(e.rng||E)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t){n=n||0;for(var o=0;o<16;++o)t[n+o]=r[o];return t}return P(r)};function F(e){let{blockClientId:t,richTextIdentifier:n=null,range:r=null,selector:o="range",source:a="default",id:i=U()}=e;const u={type:"ANNOTATION_ADD",id:i,blockClientId:t,richTextIdentifier:n,source:a,selector:o};return"range"===o&&(u.range=r),u}function G(e){return{type:"ANNOTATION_REMOVE",annotationId:e}}function V(e,t,n){return{type:"ANNOTATION_UPDATE_RANGE",annotationId:e,start:t,end:n}}function j(e){return{type:"ANNOTATION_REMOVE_SOURCE",source:e}}const B=(0,f.createReduxStore)(i,{reducer:h,selectors:n,actions:r});(0,f.register)(B),(window.wp=window.wp||{}).annotations=t}(); components.js 0000666 00010510312 15123355174 0007304 0 ustar 00 /******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 1345:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var util = __webpack_require__(5022);
function scrollIntoView(elem, container, config) {
config = config || {};
// document 归一化到 window
if (container.nodeType === 9) {
container = util.getWindow(container);
}
var allowHorizontalScroll = config.allowHorizontalScroll;
var onlyScrollIfNeeded = config.onlyScrollIfNeeded;
var alignWithTop = config.alignWithTop;
var alignWithLeft = config.alignWithLeft;
var offsetTop = config.offsetTop || 0;
var offsetLeft = config.offsetLeft || 0;
var offsetBottom = config.offsetBottom || 0;
var offsetRight = config.offsetRight || 0;
allowHorizontalScroll = allowHorizontalScroll === undefined ? true : allowHorizontalScroll;
var isWin = util.isWindow(container);
var elemOffset = util.offset(elem);
var eh = util.outerHeight(elem);
var ew = util.outerWidth(elem);
var containerOffset = undefined;
var ch = undefined;
var cw = undefined;
var containerScroll = undefined;
var diffTop = undefined;
var diffBottom = undefined;
var win = undefined;
var winScroll = undefined;
var ww = undefined;
var wh = undefined;
if (isWin) {
win = container;
wh = util.height(win);
ww = util.width(win);
winScroll = {
left: util.scrollLeft(win),
top: util.scrollTop(win)
};
// elem 相对 container 可视视窗的距离
diffTop = {
left: elemOffset.left - winScroll.left - offsetLeft,
top: elemOffset.top - winScroll.top - offsetTop
};
diffBottom = {
left: elemOffset.left + ew - (winScroll.left + ww) + offsetRight,
top: elemOffset.top + eh - (winScroll.top + wh) + offsetBottom
};
containerScroll = winScroll;
} else {
containerOffset = util.offset(container);
ch = container.clientHeight;
cw = container.clientWidth;
containerScroll = {
left: container.scrollLeft,
top: container.scrollTop
};
// elem 相对 container 可视视窗的距离
// 注意边框, offset 是边框到根节点
diffTop = {
left: elemOffset.left - (containerOffset.left + (parseFloat(util.css(container, 'borderLeftWidth')) || 0)) - offsetLeft,
top: elemOffset.top - (containerOffset.top + (parseFloat(util.css(container, 'borderTopWidth')) || 0)) - offsetTop
};
diffBottom = {
left: elemOffset.left + ew - (containerOffset.left + cw + (parseFloat(util.css(container, 'borderRightWidth')) || 0)) + offsetRight,
top: elemOffset.top + eh - (containerOffset.top + ch + (parseFloat(util.css(container, 'borderBottomWidth')) || 0)) + offsetBottom
};
}
if (diffTop.top < 0 || diffBottom.top > 0) {
// 强制向上
if (alignWithTop === true) {
util.scrollTop(container, containerScroll.top + diffTop.top);
} else if (alignWithTop === false) {
util.scrollTop(container, containerScroll.top + diffBottom.top);
} else {
// 自动调整
if (diffTop.top < 0) {
util.scrollTop(container, containerScroll.top + diffTop.top);
} else {
util.scrollTop(container, containerScroll.top + diffBottom.top);
}
}
} else {
if (!onlyScrollIfNeeded) {
alignWithTop = alignWithTop === undefined ? true : !!alignWithTop;
if (alignWithTop) {
util.scrollTop(container, containerScroll.top + diffTop.top);
} else {
util.scrollTop(container, containerScroll.top + diffBottom.top);
}
}
}
if (allowHorizontalScroll) {
if (diffTop.left < 0 || diffBottom.left > 0) {
// 强制向上
if (alignWithLeft === true) {
util.scrollLeft(container, containerScroll.left + diffTop.left);
} else if (alignWithLeft === false) {
util.scrollLeft(container, containerScroll.left + diffBottom.left);
} else {
// 自动调整
if (diffTop.left < 0) {
util.scrollLeft(container, containerScroll.left + diffTop.left);
} else {
util.scrollLeft(container, containerScroll.left + diffBottom.left);
}
}
} else {
if (!onlyScrollIfNeeded) {
alignWithLeft = alignWithLeft === undefined ? true : !!alignWithLeft;
if (alignWithLeft) {
util.scrollLeft(container, containerScroll.left + diffTop.left);
} else {
util.scrollLeft(container, containerScroll.left + diffBottom.left);
}
}
}
}
}
module.exports = scrollIntoView;
/***/ }),
/***/ 5425:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(1345);
/***/ }),
/***/ 5022:
/***/ (function(module) {
"use strict";
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
var RE_NUM = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source;
function getClientPosition(elem) {
var box = undefined;
var x = undefined;
var y = undefined;
var doc = elem.ownerDocument;
var body = doc.body;
var docElem = doc && doc.documentElement;
// 根据 GBS 最新数据,A-Grade Browsers 都已支持 getBoundingClientRect 方法,不用再考虑传统的实现方式
box = elem.getBoundingClientRect();
// 注:jQuery 还考虑减去 docElem.clientLeft/clientTop
// 但测试发现,这样反而会导致当 html 和 body 有边距/边框样式时,获取的值不正确
// 此外,ie6 会忽略 html 的 margin 值,幸运地是没有谁会去设置 html 的 margin
x = box.left;
y = box.top;
// In IE, most of the time, 2 extra pixels are added to the top and left
// due to the implicit 2-pixel inset border. In IE6/7 quirks mode and
// IE6 standards mode, this border can be overridden by setting the
// document element's border to zero -- thus, we cannot rely on the
// offset always being 2 pixels.
// In quirks mode, the offset can be determined by querying the body's
// clientLeft/clientTop, but in standards mode, it is found by querying
// the document element's clientLeft/clientTop. Since we already called
// getClientBoundingRect we have already forced a reflow, so it is not
// too expensive just to query them all.
// ie 下应该减去窗口的边框吧,毕竟默认 absolute 都是相对窗口定位的
// 窗口边框标准是设 documentElement ,quirks 时设置 body
// 最好禁止在 body 和 html 上边框 ,但 ie < 9 html 默认有 2px ,减去
// 但是非 ie 不可能设置窗口边框,body html 也不是窗口 ,ie 可以通过 html,body 设置
// 标准 ie 下 docElem.clientTop 就是 border-top
// ie7 html 即窗口边框改变不了。永远为 2
// 但标准 firefox/chrome/ie9 下 docElem.clientTop 是窗口边框,即使设了 border-top 也为 0
x -= docElem.clientLeft || body.clientLeft || 0;
y -= docElem.clientTop || body.clientTop || 0;
return {
left: x,
top: y
};
}
function getScroll(w, top) {
var ret = w['page' + (top ? 'Y' : 'X') + 'Offset'];
var method = 'scroll' + (top ? 'Top' : 'Left');
if (typeof ret !== 'number') {
var d = w.document;
// ie6,7,8 standard mode
ret = d.documentElement[method];
if (typeof ret !== 'number') {
// quirks mode
ret = d.body[method];
}
}
return ret;
}
function getScrollLeft(w) {
return getScroll(w);
}
function getScrollTop(w) {
return getScroll(w, true);
}
function getOffset(el) {
var pos = getClientPosition(el);
var doc = el.ownerDocument;
var w = doc.defaultView || doc.parentWindow;
pos.left += getScrollLeft(w);
pos.top += getScrollTop(w);
return pos;
}
function _getComputedStyle(elem, name, computedStyle_) {
var val = '';
var d = elem.ownerDocument;
var computedStyle = computedStyle_ || d.defaultView.getComputedStyle(elem, null);
// https://github.com/kissyteam/kissy/issues/61
if (computedStyle) {
val = computedStyle.getPropertyValue(name) || computedStyle[name];
}
return val;
}
var _RE_NUM_NO_PX = new RegExp('^(' + RE_NUM + ')(?!px)[a-z%]+$', 'i');
var RE_POS = /^(top|right|bottom|left)$/;
var CURRENT_STYLE = 'currentStyle';
var RUNTIME_STYLE = 'runtimeStyle';
var LEFT = 'left';
var PX = 'px';
function _getComputedStyleIE(elem, name) {
// currentStyle maybe null
// http://msdn.microsoft.com/en-us/library/ms535231.aspx
var ret = elem[CURRENT_STYLE] && elem[CURRENT_STYLE][name];
// 当 width/height 设置为百分比时,通过 pixelLeft 方式转换的 width/height 值
// 一开始就处理了! CUSTOM_STYLE.height,CUSTOM_STYLE.width ,cssHook 解决@2011-08-19
// 在 ie 下不对,需要直接用 offset 方式
// borderWidth 等值也有问题,但考虑到 borderWidth 设为百分比的概率很小,这里就不考虑了
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// exclude left right for relativity
if (_RE_NUM_NO_PX.test(ret) && !RE_POS.test(name)) {
// Remember the original values
var style = elem.style;
var left = style[LEFT];
var rsLeft = elem[RUNTIME_STYLE][LEFT];
// prevent flashing of content
elem[RUNTIME_STYLE][LEFT] = elem[CURRENT_STYLE][LEFT];
// Put in the new values to get a computed value out
style[LEFT] = name === 'fontSize' ? '1em' : ret || 0;
ret = style.pixelLeft + PX;
// Revert the changed values
style[LEFT] = left;
elem[RUNTIME_STYLE][LEFT] = rsLeft;
}
return ret === '' ? 'auto' : ret;
}
var getComputedStyleX = undefined;
if (typeof window !== 'undefined') {
getComputedStyleX = window.getComputedStyle ? _getComputedStyle : _getComputedStyleIE;
}
function each(arr, fn) {
for (var i = 0; i < arr.length; i++) {
fn(arr[i]);
}
}
function isBorderBoxFn(elem) {
return getComputedStyleX(elem, 'boxSizing') === 'border-box';
}
var BOX_MODELS = ['margin', 'border', 'padding'];
var CONTENT_INDEX = -1;
var PADDING_INDEX = 2;
var BORDER_INDEX = 1;
var MARGIN_INDEX = 0;
function swap(elem, options, callback) {
var old = {};
var style = elem.style;
var name = undefined;
// Remember the old values, and insert the new ones
for (name in options) {
if (options.hasOwnProperty(name)) {
old[name] = style[name];
style[name] = options[name];
}
}
callback.call(elem);
// Revert the old values
for (name in options) {
if (options.hasOwnProperty(name)) {
style[name] = old[name];
}
}
}
function getPBMWidth(elem, props, which) {
var value = 0;
var prop = undefined;
var j = undefined;
var i = undefined;
for (j = 0; j < props.length; j++) {
prop = props[j];
if (prop) {
for (i = 0; i < which.length; i++) {
var cssProp = undefined;
if (prop === 'border') {
cssProp = prop + which[i] + 'Width';
} else {
cssProp = prop + which[i];
}
value += parseFloat(getComputedStyleX(elem, cssProp)) || 0;
}
}
}
return value;
}
/**
* A crude way of determining if an object is a window
* @member util
*/
function isWindow(obj) {
// must use == for ie8
/* eslint eqeqeq:0 */
return obj != null && obj == obj.window;
}
var domUtils = {};
each(['Width', 'Height'], function (name) {
domUtils['doc' + name] = function (refWin) {
var d = refWin.document;
return Math.max(
// firefox chrome documentElement.scrollHeight< body.scrollHeight
// ie standard mode : documentElement.scrollHeight> body.scrollHeight
d.documentElement['scroll' + name],
// quirks : documentElement.scrollHeight 最大等于可视窗口多一点?
d.body['scroll' + name], domUtils['viewport' + name](d));
};
domUtils['viewport' + name] = function (win) {
// pc browser includes scrollbar in window.innerWidth
var prop = 'client' + name;
var doc = win.document;
var body = doc.body;
var documentElement = doc.documentElement;
var documentElementProp = documentElement[prop];
// 标准模式取 documentElement
// backcompat 取 body
return doc.compatMode === 'CSS1Compat' && documentElementProp || body && body[prop] || documentElementProp;
};
});
/*
得到元素的大小信息
@param elem
@param name
@param {String} [extra] 'padding' : (css width) + padding
'border' : (css width) + padding + border
'margin' : (css width) + padding + border + margin
*/
function getWH(elem, name, extra) {
if (isWindow(elem)) {
return name === 'width' ? domUtils.viewportWidth(elem) : domUtils.viewportHeight(elem);
} else if (elem.nodeType === 9) {
return name === 'width' ? domUtils.docWidth(elem) : domUtils.docHeight(elem);
}
var which = name === 'width' ? ['Left', 'Right'] : ['Top', 'Bottom'];
var borderBoxValue = name === 'width' ? elem.offsetWidth : elem.offsetHeight;
var computedStyle = getComputedStyleX(elem);
var isBorderBox = isBorderBoxFn(elem, computedStyle);
var cssBoxValue = 0;
if (borderBoxValue == null || borderBoxValue <= 0) {
borderBoxValue = undefined;
// Fall back to computed then un computed css if necessary
cssBoxValue = getComputedStyleX(elem, name);
if (cssBoxValue == null || Number(cssBoxValue) < 0) {
cssBoxValue = elem.style[name] || 0;
}
// Normalize '', auto, and prepare for extra
cssBoxValue = parseFloat(cssBoxValue) || 0;
}
if (extra === undefined) {
extra = isBorderBox ? BORDER_INDEX : CONTENT_INDEX;
}
var borderBoxValueOrIsBorderBox = borderBoxValue !== undefined || isBorderBox;
var val = borderBoxValue || cssBoxValue;
if (extra === CONTENT_INDEX) {
if (borderBoxValueOrIsBorderBox) {
return val - getPBMWidth(elem, ['border', 'padding'], which, computedStyle);
}
return cssBoxValue;
}
if (borderBoxValueOrIsBorderBox) {
var padding = extra === PADDING_INDEX ? -getPBMWidth(elem, ['border'], which, computedStyle) : getPBMWidth(elem, ['margin'], which, computedStyle);
return val + (extra === BORDER_INDEX ? 0 : padding);
}
return cssBoxValue + getPBMWidth(elem, BOX_MODELS.slice(extra), which, computedStyle);
}
var cssShow = {
position: 'absolute',
visibility: 'hidden',
display: 'block'
};
// fix #119 : https://github.com/kissyteam/kissy/issues/119
function getWHIgnoreDisplay(elem) {
var val = undefined;
var args = arguments;
// in case elem is window
// elem.offsetWidth === undefined
if (elem.offsetWidth !== 0) {
val = getWH.apply(undefined, args);
} else {
swap(elem, cssShow, function () {
val = getWH.apply(undefined, args);
});
}
return val;
}
function css(el, name, v) {
var value = v;
if ((typeof name === 'undefined' ? 'undefined' : _typeof(name)) === 'object') {
for (var i in name) {
if (name.hasOwnProperty(i)) {
css(el, i, name[i]);
}
}
return undefined;
}
if (typeof value !== 'undefined') {
if (typeof value === 'number') {
value += 'px';
}
el.style[name] = value;
return undefined;
}
return getComputedStyleX(el, name);
}
each(['width', 'height'], function (name) {
var first = name.charAt(0).toUpperCase() + name.slice(1);
domUtils['outer' + first] = function (el, includeMargin) {
return el && getWHIgnoreDisplay(el, name, includeMargin ? MARGIN_INDEX : BORDER_INDEX);
};
var which = name === 'width' ? ['Left', 'Right'] : ['Top', 'Bottom'];
domUtils[name] = function (elem, val) {
if (val !== undefined) {
if (elem) {
var computedStyle = getComputedStyleX(elem);
var isBorderBox = isBorderBoxFn(elem);
if (isBorderBox) {
val += getPBMWidth(elem, ['padding', 'border'], which, computedStyle);
}
return css(elem, name, val);
}
return undefined;
}
return elem && getWHIgnoreDisplay(elem, name, CONTENT_INDEX);
};
});
// 设置 elem 相对 elem.ownerDocument 的坐标
function setOffset(elem, offset) {
// set position first, in-case top/left are set even on static elem
if (css(elem, 'position') === 'static') {
elem.style.position = 'relative';
}
var old = getOffset(elem);
var ret = {};
var current = undefined;
var key = undefined;
for (key in offset) {
if (offset.hasOwnProperty(key)) {
current = parseFloat(css(elem, key)) || 0;
ret[key] = current + offset[key] - old[key];
}
}
css(elem, ret);
}
module.exports = _extends({
getWindow: function getWindow(node) {
var doc = node.ownerDocument || node;
return doc.defaultView || doc.parentWindow;
},
offset: function offset(el, value) {
if (typeof value !== 'undefined') {
setOffset(el, value);
} else {
return getOffset(el);
}
},
isWindow: isWindow,
each: each,
css: css,
clone: function clone(obj) {
var ret = {};
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
ret[i] = obj[i];
}
}
var overflow = obj.overflow;
if (overflow) {
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
ret.overflow[i] = obj.overflow[i];
}
}
}
return ret;
},
scrollLeft: function scrollLeft(w, v) {
if (isWindow(w)) {
if (v === undefined) {
return getScrollLeft(w);
}
window.scrollTo(v, getScrollTop(w));
} else {
if (v === undefined) {
return w.scrollLeft;
}
w.scrollLeft = v;
}
},
scrollTop: function scrollTop(w, v) {
if (isWindow(w)) {
if (v === undefined) {
return getScrollTop(w);
}
window.scrollTo(getScrollLeft(w), v);
} else {
if (v === undefined) {
return w.scrollTop;
}
w.scrollTop = v;
}
},
viewportWidth: 0,
viewportHeight: 0
}, domUtils);
/***/ }),
/***/ 9214:
/***/ (function(__unused_webpack_module, exports) {
"use strict";
var __webpack_unused_export__;
/** @license React v17.0.2
* react-is.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var b=60103,c=60106,d=60107,e=60108,f=60114,g=60109,h=60110,k=60112,l=60113,m=60120,n=60115,p=60116,q=60121,r=60122,u=60117,v=60129,w=60131;
if("function"===typeof Symbol&&Symbol.for){var x=Symbol.for;b=x("react.element");c=x("react.portal");d=x("react.fragment");e=x("react.strict_mode");f=x("react.profiler");g=x("react.provider");h=x("react.context");k=x("react.forward_ref");l=x("react.suspense");m=x("react.suspense_list");n=x("react.memo");p=x("react.lazy");q=x("react.block");r=x("react.server.block");u=x("react.fundamental");v=x("react.debug_trace_mode");w=x("react.legacy_hidden")}
function y(a){if("object"===typeof a&&null!==a){var t=a.$$typeof;switch(t){case b:switch(a=a.type,a){case d:case f:case e:case l:case m:return a;default:switch(a=a&&a.$$typeof,a){case h:case k:case p:case n:case g:return a;default:return t}}case c:return t}}}var z=g,A=b,B=k,C=d,D=p,E=n,F=c,G=f,H=e,I=l;__webpack_unused_export__=h;__webpack_unused_export__=z;__webpack_unused_export__=A;__webpack_unused_export__=B;__webpack_unused_export__=C;__webpack_unused_export__=D;__webpack_unused_export__=E;__webpack_unused_export__=F;__webpack_unused_export__=G;__webpack_unused_export__=H;
__webpack_unused_export__=I;__webpack_unused_export__=function(){return!1};__webpack_unused_export__=function(){return!1};__webpack_unused_export__=function(a){return y(a)===h};__webpack_unused_export__=function(a){return y(a)===g};__webpack_unused_export__=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===b};__webpack_unused_export__=function(a){return y(a)===k};__webpack_unused_export__=function(a){return y(a)===d};__webpack_unused_export__=function(a){return y(a)===p};__webpack_unused_export__=function(a){return y(a)===n};
__webpack_unused_export__=function(a){return y(a)===c};__webpack_unused_export__=function(a){return y(a)===f};__webpack_unused_export__=function(a){return y(a)===e};__webpack_unused_export__=function(a){return y(a)===l};__webpack_unused_export__=function(a){return"string"===typeof a||"function"===typeof a||a===d||a===f||a===v||a===e||a===l||a===m||a===w||"object"===typeof a&&null!==a&&(a.$$typeof===p||a.$$typeof===n||a.$$typeof===g||a.$$typeof===h||a.$$typeof===k||a.$$typeof===u||a.$$typeof===q||a[0]===r)?!0:!1};
__webpack_unused_export__=y;
/***/ }),
/***/ 2797:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
if (true) {
/* unused reexport */ __webpack_require__(9214);
} else {}
/***/ }),
/***/ 5619:
/***/ (function(module) {
"use strict";
// do not edit .js files directly - edit src/index.jst
var envHasBigInt64Array = typeof BigInt64Array !== 'undefined';
module.exports = function equal(a, b) {
if (a === b) return true;
if (a && b && typeof a == 'object' && typeof b == 'object') {
if (a.constructor !== b.constructor) return false;
var length, i, keys;
if (Array.isArray(a)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (!equal(a[i], b[i])) return false;
return true;
}
if ((a instanceof Map) && (b instanceof Map)) {
if (a.size !== b.size) return false;
for (i of a.entries())
if (!b.has(i[0])) return false;
for (i of a.entries())
if (!equal(i[1], b.get(i[0]))) return false;
return true;
}
if ((a instanceof Set) && (b instanceof Set)) {
if (a.size !== b.size) return false;
for (i of a.entries())
if (!b.has(i[0])) return false;
return true;
}
if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (a[i] !== b[i]) return false;
return true;
}
if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) return false;
for (i = length; i-- !== 0;)
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
for (i = length; i-- !== 0;) {
var key = keys[i];
if (!equal(a[key], b[key])) return false;
}
return true;
}
// true if both NaN, false otherwise
return a!==a && b!==b;
};
/***/ }),
/***/ 7115:
/***/ (function(__unused_webpack_module, exports) {
// Copyright (c) 2014 Rafael Caricio. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var GradientParser = {};
GradientParser.parse = (function() {
var tokens = {
linearGradient: /^(\-(webkit|o|ms|moz)\-)?(linear\-gradient)/i,
repeatingLinearGradient: /^(\-(webkit|o|ms|moz)\-)?(repeating\-linear\-gradient)/i,
radialGradient: /^(\-(webkit|o|ms|moz)\-)?(radial\-gradient)/i,
repeatingRadialGradient: /^(\-(webkit|o|ms|moz)\-)?(repeating\-radial\-gradient)/i,
sideOrCorner: /^to (left (top|bottom)|right (top|bottom)|left|right|top|bottom)/i,
extentKeywords: /^(closest\-side|closest\-corner|farthest\-side|farthest\-corner|contain|cover)/,
positionKeywords: /^(left|center|right|top|bottom)/i,
pixelValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))px/,
percentageValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))\%/,
emValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))em/,
angleValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))deg/,
startCall: /^\(/,
endCall: /^\)/,
comma: /^,/,
hexColor: /^\#([0-9a-fA-F]+)/,
literalColor: /^([a-zA-Z]+)/,
rgbColor: /^rgb/i,
rgbaColor: /^rgba/i,
number: /^(([0-9]*\.[0-9]+)|([0-9]+\.?))/
};
var input = '';
function error(msg) {
var err = new Error(input + ': ' + msg);
err.source = input;
throw err;
}
function getAST() {
var ast = matchListDefinitions();
if (input.length > 0) {
error('Invalid input not EOF');
}
return ast;
}
function matchListDefinitions() {
return matchListing(matchDefinition);
}
function matchDefinition() {
return matchGradient(
'linear-gradient',
tokens.linearGradient,
matchLinearOrientation) ||
matchGradient(
'repeating-linear-gradient',
tokens.repeatingLinearGradient,
matchLinearOrientation) ||
matchGradient(
'radial-gradient',
tokens.radialGradient,
matchListRadialOrientations) ||
matchGradient(
'repeating-radial-gradient',
tokens.repeatingRadialGradient,
matchListRadialOrientations);
}
function matchGradient(gradientType, pattern, orientationMatcher) {
return matchCall(pattern, function(captures) {
var orientation = orientationMatcher();
if (orientation) {
if (!scan(tokens.comma)) {
error('Missing comma before color stops');
}
}
return {
type: gradientType,
orientation: orientation,
colorStops: matchListing(matchColorStop)
};
});
}
function matchCall(pattern, callback) {
var captures = scan(pattern);
if (captures) {
if (!scan(tokens.startCall)) {
error('Missing (');
}
result = callback(captures);
if (!scan(tokens.endCall)) {
error('Missing )');
}
return result;
}
}
function matchLinearOrientation() {
return matchSideOrCorner() ||
matchAngle();
}
function matchSideOrCorner() {
return match('directional', tokens.sideOrCorner, 1);
}
function matchAngle() {
return match('angular', tokens.angleValue, 1);
}
function matchListRadialOrientations() {
var radialOrientations,
radialOrientation = matchRadialOrientation(),
lookaheadCache;
if (radialOrientation) {
radialOrientations = [];
radialOrientations.push(radialOrientation);
lookaheadCache = input;
if (scan(tokens.comma)) {
radialOrientation = matchRadialOrientation();
if (radialOrientation) {
radialOrientations.push(radialOrientation);
} else {
input = lookaheadCache;
}
}
}
return radialOrientations;
}
function matchRadialOrientation() {
var radialType = matchCircle() ||
matchEllipse();
if (radialType) {
radialType.at = matchAtPosition();
} else {
var defaultPosition = matchPositioning();
if (defaultPosition) {
radialType = {
type: 'default-radial',
at: defaultPosition
};
}
}
return radialType;
}
function matchCircle() {
var circle = match('shape', /^(circle)/i, 0);
if (circle) {
circle.style = matchLength() || matchExtentKeyword();
}
return circle;
}
function matchEllipse() {
var ellipse = match('shape', /^(ellipse)/i, 0);
if (ellipse) {
ellipse.style = matchDistance() || matchExtentKeyword();
}
return ellipse;
}
function matchExtentKeyword() {
return match('extent-keyword', tokens.extentKeywords, 1);
}
function matchAtPosition() {
if (match('position', /^at/, 0)) {
var positioning = matchPositioning();
if (!positioning) {
error('Missing positioning value');
}
return positioning;
}
}
function matchPositioning() {
var location = matchCoordinates();
if (location.x || location.y) {
return {
type: 'position',
value: location
};
}
}
function matchCoordinates() {
return {
x: matchDistance(),
y: matchDistance()
};
}
function matchListing(matcher) {
var captures = matcher(),
result = [];
if (captures) {
result.push(captures);
while (scan(tokens.comma)) {
captures = matcher();
if (captures) {
result.push(captures);
} else {
error('One extra comma');
}
}
}
return result;
}
function matchColorStop() {
var color = matchColor();
if (!color) {
error('Expected color definition');
}
color.length = matchDistance();
return color;
}
function matchColor() {
return matchHexColor() ||
matchRGBAColor() ||
matchRGBColor() ||
matchLiteralColor();
}
function matchLiteralColor() {
return match('literal', tokens.literalColor, 0);
}
function matchHexColor() {
return match('hex', tokens.hexColor, 1);
}
function matchRGBColor() {
return matchCall(tokens.rgbColor, function() {
return {
type: 'rgb',
value: matchListing(matchNumber)
};
});
}
function matchRGBAColor() {
return matchCall(tokens.rgbaColor, function() {
return {
type: 'rgba',
value: matchListing(matchNumber)
};
});
}
function matchNumber() {
return scan(tokens.number)[1];
}
function matchDistance() {
return match('%', tokens.percentageValue, 1) ||
matchPositionKeyword() ||
matchLength();
}
function matchPositionKeyword() {
return match('position-keyword', tokens.positionKeywords, 1);
}
function matchLength() {
return match('px', tokens.pixelValue, 1) ||
match('em', tokens.emValue, 1);
}
function match(type, pattern, captureIndex) {
var captures = scan(pattern);
if (captures) {
return {
type: type,
value: captures[captureIndex]
};
}
}
function scan(regexp) {
var captures,
blankCaptures;
blankCaptures = /^[\n\r\t\s]+/.exec(input);
if (blankCaptures) {
consume(blankCaptures[0].length);
}
captures = regexp.exec(input);
if (captures) {
consume(captures[0].length);
}
return captures;
}
function consume(size) {
input = input.substr(size);
}
return function(code) {
input = code.toString();
return getAST();
};
})();
exports.parse = (GradientParser || {}).parse;
/***/ }),
/***/ 3138:
/***/ (function(module) {
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __nested_webpack_require_187__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __nested_webpack_require_187__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __nested_webpack_require_187__.m = modules;
/******/
/******/ // expose the module cache
/******/ __nested_webpack_require_187__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __nested_webpack_require_187__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __nested_webpack_require_187__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __nested_webpack_require_1468__) {
module.exports = __nested_webpack_require_1468__(1);
/***/ }),
/* 1 */
/***/ (function(module, exports, __nested_webpack_require_1587__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _utils = __nested_webpack_require_1587__(2);
Object.defineProperty(exports, 'combineChunks', {
enumerable: true,
get: function get() {
return _utils.combineChunks;
}
});
Object.defineProperty(exports, 'fillInChunks', {
enumerable: true,
get: function get() {
return _utils.fillInChunks;
}
});
Object.defineProperty(exports, 'findAll', {
enumerable: true,
get: function get() {
return _utils.findAll;
}
});
Object.defineProperty(exports, 'findChunks', {
enumerable: true,
get: function get() {
return _utils.findChunks;
}
});
/***/ }),
/* 2 */
/***/ (function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* Creates an array of chunk objects representing both higlightable and non highlightable pieces of text that match each search word.
* @return Array of "chunks" (where a Chunk is { start:number, end:number, highlight:boolean })
*/
var findAll = exports.findAll = function findAll(_ref) {
var autoEscape = _ref.autoEscape,
_ref$caseSensitive = _ref.caseSensitive,
caseSensitive = _ref$caseSensitive === undefined ? false : _ref$caseSensitive,
_ref$findChunks = _ref.findChunks,
findChunks = _ref$findChunks === undefined ? defaultFindChunks : _ref$findChunks,
sanitize = _ref.sanitize,
searchWords = _ref.searchWords,
textToHighlight = _ref.textToHighlight;
return fillInChunks({
chunksToHighlight: combineChunks({
chunks: findChunks({
autoEscape: autoEscape,
caseSensitive: caseSensitive,
sanitize: sanitize,
searchWords: searchWords,
textToHighlight: textToHighlight
})
}),
totalLength: textToHighlight ? textToHighlight.length : 0
});
};
/**
* Takes an array of {start:number, end:number} objects and combines chunks that overlap into single chunks.
* @return {start:number, end:number}[]
*/
var combineChunks = exports.combineChunks = function combineChunks(_ref2) {
var chunks = _ref2.chunks;
chunks = chunks.sort(function (first, second) {
return first.start - second.start;
}).reduce(function (processedChunks, nextChunk) {
// First chunk just goes straight in the array...
if (processedChunks.length === 0) {
return [nextChunk];
} else {
// ... subsequent chunks get checked to see if they overlap...
var prevChunk = processedChunks.pop();
if (nextChunk.start <= prevChunk.end) {
// It may be the case that prevChunk completely surrounds nextChunk, so take the
// largest of the end indeces.
var endIndex = Math.max(prevChunk.end, nextChunk.end);
processedChunks.push({ highlight: false, start: prevChunk.start, end: endIndex });
} else {
processedChunks.push(prevChunk, nextChunk);
}
return processedChunks;
}
}, []);
return chunks;
};
/**
* Examine text for any matches.
* If we find matches, add them to the returned array as a "chunk" object ({start:number, end:number}).
* @return {start:number, end:number}[]
*/
var defaultFindChunks = function defaultFindChunks(_ref3) {
var autoEscape = _ref3.autoEscape,
caseSensitive = _ref3.caseSensitive,
_ref3$sanitize = _ref3.sanitize,
sanitize = _ref3$sanitize === undefined ? defaultSanitize : _ref3$sanitize,
searchWords = _ref3.searchWords,
textToHighlight = _ref3.textToHighlight;
textToHighlight = sanitize(textToHighlight);
return searchWords.filter(function (searchWord) {
return searchWord;
}) // Remove empty words
.reduce(function (chunks, searchWord) {
searchWord = sanitize(searchWord);
if (autoEscape) {
searchWord = escapeRegExpFn(searchWord);
}
var regex = new RegExp(searchWord, caseSensitive ? 'g' : 'gi');
var match = void 0;
while (match = regex.exec(textToHighlight)) {
var _start = match.index;
var _end = regex.lastIndex;
// We do not return zero-length matches
if (_end > _start) {
chunks.push({ highlight: false, start: _start, end: _end });
}
// Prevent browsers like Firefox from getting stuck in an infinite loop
// See http://www.regexguru.com/2008/04/watch-out-for-zero-length-matches/
if (match.index === regex.lastIndex) {
regex.lastIndex++;
}
}
return chunks;
}, []);
};
// Allow the findChunks to be overridden in findAll,
// but for backwards compatibility we export as the old name
exports.findChunks = defaultFindChunks;
/**
* Given a set of chunks to highlight, create an additional set of chunks
* to represent the bits of text between the highlighted text.
* @param chunksToHighlight {start:number, end:number}[]
* @param totalLength number
* @return {start:number, end:number, highlight:boolean}[]
*/
var fillInChunks = exports.fillInChunks = function fillInChunks(_ref4) {
var chunksToHighlight = _ref4.chunksToHighlight,
totalLength = _ref4.totalLength;
var allChunks = [];
var append = function append(start, end, highlight) {
if (end - start > 0) {
allChunks.push({
start: start,
end: end,
highlight: highlight
});
}
};
if (chunksToHighlight.length === 0) {
append(0, totalLength, false);
} else {
var lastIndex = 0;
chunksToHighlight.forEach(function (chunk) {
append(lastIndex, chunk.start, false);
append(chunk.start, chunk.end, true);
lastIndex = chunk.end;
});
append(lastIndex, totalLength, false);
}
return allChunks;
};
function defaultSanitize(string) {
return string;
}
function escapeRegExpFn(string) {
return string.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}
/***/ })
/******/ ]);
/***/ }),
/***/ 1281:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var reactIs = __webpack_require__(338);
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var REACT_STATICS = {
childContextTypes: true,
contextType: true,
contextTypes: true,
defaultProps: true,
displayName: true,
getDefaultProps: true,
getDerivedStateFromError: true,
getDerivedStateFromProps: true,
mixins: true,
propTypes: true,
type: true
};
var KNOWN_STATICS = {
name: true,
length: true,
prototype: true,
caller: true,
callee: true,
arguments: true,
arity: true
};
var FORWARD_REF_STATICS = {
'$$typeof': true,
render: true,
defaultProps: true,
displayName: true,
propTypes: true
};
var MEMO_STATICS = {
'$$typeof': true,
compare: true,
defaultProps: true,
displayName: true,
propTypes: true,
type: true
};
var TYPE_STATICS = {};
TYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;
TYPE_STATICS[reactIs.Memo] = MEMO_STATICS;
function getStatics(component) {
// React v16.11 and below
if (reactIs.isMemo(component)) {
return MEMO_STATICS;
} // React v16.12 and above
return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;
}
var defineProperty = Object.defineProperty;
var getOwnPropertyNames = Object.getOwnPropertyNames;
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var getPrototypeOf = Object.getPrototypeOf;
var objectPrototype = Object.prototype;
function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {
if (typeof sourceComponent !== 'string') {
// don't hoist over string (html) components
if (objectPrototype) {
var inheritedComponent = getPrototypeOf(sourceComponent);
if (inheritedComponent && inheritedComponent !== objectPrototype) {
hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);
}
}
var keys = getOwnPropertyNames(sourceComponent);
if (getOwnPropertySymbols) {
keys = keys.concat(getOwnPropertySymbols(sourceComponent));
}
var targetStatics = getStatics(targetComponent);
var sourceStatics = getStatics(sourceComponent);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {
var descriptor = getOwnPropertyDescriptor(sourceComponent, key);
try {
// Avoid failures from read-only properties
defineProperty(targetComponent, key, descriptor);
} catch (e) {}
}
}
}
return targetComponent;
}
module.exports = hoistNonReactStatics;
/***/ }),
/***/ 9756:
/***/ (function(module) {
/**
* Memize options object.
*
* @typedef MemizeOptions
*
* @property {number} [maxSize] Maximum size of the cache.
*/
/**
* Internal cache entry.
*
* @typedef MemizeCacheNode
*
* @property {?MemizeCacheNode|undefined} [prev] Previous node.
* @property {?MemizeCacheNode|undefined} [next] Next node.
* @property {Array<*>} args Function arguments for cache
* entry.
* @property {*} val Function result.
*/
/**
* Properties of the enhanced function for controlling cache.
*
* @typedef MemizeMemoizedFunction
*
* @property {()=>void} clear Clear the cache.
*/
/**
* Accepts a function to be memoized, and returns a new memoized function, with
* optional options.
*
* @template {Function} F
*
* @param {F} fn Function to memoize.
* @param {MemizeOptions} [options] Options object.
*
* @return {F & MemizeMemoizedFunction} Memoized function.
*/
function memize( fn, options ) {
var size = 0;
/** @type {?MemizeCacheNode|undefined} */
var head;
/** @type {?MemizeCacheNode|undefined} */
var tail;
options = options || {};
function memoized( /* ...args */ ) {
var node = head,
len = arguments.length,
args, i;
searchCache: while ( node ) {
// Perform a shallow equality test to confirm that whether the node
// under test is a candidate for the arguments passed. Two arrays
// are shallowly equal if their length matches and each entry is
// strictly equal between the two sets. Avoid abstracting to a
// function which could incur an arguments leaking deoptimization.
// Check whether node arguments match arguments length
if ( node.args.length !== arguments.length ) {
node = node.next;
continue;
}
// Check whether node arguments match arguments values
for ( i = 0; i < len; i++ ) {
if ( node.args[ i ] !== arguments[ i ] ) {
node = node.next;
continue searchCache;
}
}
// At this point we can assume we've found a match
// Surface matched node to head if not already
if ( node !== head ) {
// As tail, shift to previous. Must only shift if not also
// head, since if both head and tail, there is no previous.
if ( node === tail ) {
tail = node.prev;
}
// Adjust siblings to point to each other. If node was tail,
// this also handles new tail's empty `next` assignment.
/** @type {MemizeCacheNode} */ ( node.prev ).next = node.next;
if ( node.next ) {
node.next.prev = node.prev;
}
node.next = head;
node.prev = null;
/** @type {MemizeCacheNode} */ ( head ).prev = node;
head = node;
}
// Return immediately
return node.val;
}
// No cached value found. Continue to insertion phase:
// Create a copy of arguments (avoid leaking deoptimization)
args = new Array( len );
for ( i = 0; i < len; i++ ) {
args[ i ] = arguments[ i ];
}
node = {
args: args,
// Generate the result from original function
val: fn.apply( null, args ),
};
// Don't need to check whether node is already head, since it would
// have been returned above already if it was
// Shift existing head down list
if ( head ) {
head.prev = node;
node.next = head;
} else {
// If no head, follows that there's no tail (at initial or reset)
tail = node;
}
// Trim tail if we're reached max size and are pending cache insertion
if ( size === /** @type {MemizeOptions} */ ( options ).maxSize ) {
tail = /** @type {MemizeCacheNode} */ ( tail ).prev;
/** @type {MemizeCacheNode} */ ( tail ).next = null;
} else {
size++;
}
head = node;
return node.val;
}
memoized.clear = function() {
head = null;
tail = null;
size = 0;
};
if ( false ) {}
// Ignore reason: There's not a clear solution to create an intersection of
// the function with additional properties, where the goal is to retain the
// function signature of the incoming argument and add control properties
// on the return value.
// @ts-ignore
return memoized;
}
module.exports = memize;
/***/ }),
/***/ 5372:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = __webpack_require__(9567);
function emptyFunction() {}
function emptyFunctionWithReset() {}
emptyFunctionWithReset.resetWarningCache = emptyFunction;
module.exports = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
if (secret === ReactPropTypesSecret) {
// It is still safe when called from React.
return;
}
var err = new Error(
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use PropTypes.checkPropTypes() to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
err.name = 'Invariant Violation';
throw err;
};
shim.isRequired = shim;
function getShim() {
return shim;
};
// Important!
// Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
var ReactPropTypes = {
array: shim,
bigint: shim,
bool: shim,
func: shim,
number: shim,
object: shim,
string: shim,
symbol: shim,
any: shim,
arrayOf: getShim,
element: shim,
elementType: shim,
instanceOf: getShim,
node: shim,
objectOf: getShim,
oneOf: getShim,
oneOfType: getShim,
shape: getShim,
exact: getShim,
checkPropTypes: emptyFunctionWithReset,
resetWarningCache: emptyFunction
};
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
/***/ }),
/***/ 2652:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
if (false) { var throwOnDirectAccess, ReactIs; } else {
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
module.exports = __webpack_require__(5372)();
}
/***/ }),
/***/ 9567:
/***/ (function(module) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
module.exports = ReactPropTypesSecret;
/***/ }),
/***/ 4821:
/***/ (function(__unused_webpack_module, exports) {
"use strict";
/** @license React v16.13.1
* react-is.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var b="function"===typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.concurrent_mode"):60111,n=b?Symbol.for("react.forward_ref"):60112,p=b?Symbol.for("react.suspense"):60113,q=b?
Symbol.for("react.suspense_list"):60120,r=b?Symbol.for("react.memo"):60115,t=b?Symbol.for("react.lazy"):60116,v=b?Symbol.for("react.block"):60121,w=b?Symbol.for("react.fundamental"):60117,x=b?Symbol.for("react.responder"):60118,y=b?Symbol.for("react.scope"):60119;
function z(a){if("object"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;exports.Fragment=e;exports.Lazy=t;exports.Memo=r;exports.Portal=d;
exports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isAsyncMode=function(a){return A(a)||z(a)===l};exports.isConcurrentMode=A;exports.isContextConsumer=function(a){return z(a)===k};exports.isContextProvider=function(a){return z(a)===h};exports.isElement=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return z(a)===n};exports.isFragment=function(a){return z(a)===e};exports.isLazy=function(a){return z(a)===t};
exports.isMemo=function(a){return z(a)===r};exports.isPortal=function(a){return z(a)===d};exports.isProfiler=function(a){return z(a)===g};exports.isStrictMode=function(a){return z(a)===f};exports.isSuspense=function(a){return z(a)===p};
exports.isValidElementType=function(a){return"string"===typeof a||"function"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||"object"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)};exports.typeOf=z;
/***/ }),
/***/ 338:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
if (true) {
module.exports = __webpack_require__(4821);
} else {}
/***/ }),
/***/ 4793:
/***/ (function(module) {
var characterMap = {
"À": "A",
"Á": "A",
"Â": "A",
"Ã": "A",
"Ä": "A",
"Å": "A",
"Ấ": "A",
"Ắ": "A",
"Ẳ": "A",
"Ẵ": "A",
"Ặ": "A",
"Æ": "AE",
"Ầ": "A",
"Ằ": "A",
"Ȃ": "A",
"Ç": "C",
"Ḉ": "C",
"È": "E",
"É": "E",
"Ê": "E",
"Ë": "E",
"Ế": "E",
"Ḗ": "E",
"Ề": "E",
"Ḕ": "E",
"Ḝ": "E",
"Ȇ": "E",
"Ì": "I",
"Í": "I",
"Î": "I",
"Ï": "I",
"Ḯ": "I",
"Ȋ": "I",
"Ð": "D",
"Ñ": "N",
"Ò": "O",
"Ó": "O",
"Ô": "O",
"Õ": "O",
"Ö": "O",
"Ø": "O",
"Ố": "O",
"Ṍ": "O",
"Ṓ": "O",
"Ȏ": "O",
"Ù": "U",
"Ú": "U",
"Û": "U",
"Ü": "U",
"Ý": "Y",
"à": "a",
"á": "a",
"â": "a",
"ã": "a",
"ä": "a",
"å": "a",
"ấ": "a",
"ắ": "a",
"ẳ": "a",
"ẵ": "a",
"ặ": "a",
"æ": "ae",
"ầ": "a",
"ằ": "a",
"ȃ": "a",
"ç": "c",
"ḉ": "c",
"è": "e",
"é": "e",
"ê": "e",
"ë": "e",
"ế": "e",
"ḗ": "e",
"ề": "e",
"ḕ": "e",
"ḝ": "e",
"ȇ": "e",
"ì": "i",
"í": "i",
"î": "i",
"ï": "i",
"ḯ": "i",
"ȋ": "i",
"ð": "d",
"ñ": "n",
"ò": "o",
"ó": "o",
"ô": "o",
"õ": "o",
"ö": "o",
"ø": "o",
"ố": "o",
"ṍ": "o",
"ṓ": "o",
"ȏ": "o",
"ù": "u",
"ú": "u",
"û": "u",
"ü": "u",
"ý": "y",
"ÿ": "y",
"Ā": "A",
"ā": "a",
"Ă": "A",
"ă": "a",
"Ą": "A",
"ą": "a",
"Ć": "C",
"ć": "c",
"Ĉ": "C",
"ĉ": "c",
"Ċ": "C",
"ċ": "c",
"Č": "C",
"č": "c",
"C̆": "C",
"c̆": "c",
"Ď": "D",
"ď": "d",
"Đ": "D",
"đ": "d",
"Ē": "E",
"ē": "e",
"Ĕ": "E",
"ĕ": "e",
"Ė": "E",
"ė": "e",
"Ę": "E",
"ę": "e",
"Ě": "E",
"ě": "e",
"Ĝ": "G",
"Ǵ": "G",
"ĝ": "g",
"ǵ": "g",
"Ğ": "G",
"ğ": "g",
"Ġ": "G",
"ġ": "g",
"Ģ": "G",
"ģ": "g",
"Ĥ": "H",
"ĥ": "h",
"Ħ": "H",
"ħ": "h",
"Ḫ": "H",
"ḫ": "h",
"Ĩ": "I",
"ĩ": "i",
"Ī": "I",
"ī": "i",
"Ĭ": "I",
"ĭ": "i",
"Į": "I",
"į": "i",
"İ": "I",
"ı": "i",
"IJ": "IJ",
"ij": "ij",
"Ĵ": "J",
"ĵ": "j",
"Ķ": "K",
"ķ": "k",
"Ḱ": "K",
"ḱ": "k",
"K̆": "K",
"k̆": "k",
"Ĺ": "L",
"ĺ": "l",
"Ļ": "L",
"ļ": "l",
"Ľ": "L",
"ľ": "l",
"Ŀ": "L",
"ŀ": "l",
"Ł": "l",
"ł": "l",
"Ḿ": "M",
"ḿ": "m",
"M̆": "M",
"m̆": "m",
"Ń": "N",
"ń": "n",
"Ņ": "N",
"ņ": "n",
"Ň": "N",
"ň": "n",
"ʼn": "n",
"N̆": "N",
"n̆": "n",
"Ō": "O",
"ō": "o",
"Ŏ": "O",
"ŏ": "o",
"Ő": "O",
"ő": "o",
"Œ": "OE",
"œ": "oe",
"P̆": "P",
"p̆": "p",
"Ŕ": "R",
"ŕ": "r",
"Ŗ": "R",
"ŗ": "r",
"Ř": "R",
"ř": "r",
"R̆": "R",
"r̆": "r",
"Ȓ": "R",
"ȓ": "r",
"Ś": "S",
"ś": "s",
"Ŝ": "S",
"ŝ": "s",
"Ş": "S",
"Ș": "S",
"ș": "s",
"ş": "s",
"Š": "S",
"š": "s",
"ß": "ss",
"Ţ": "T",
"ţ": "t",
"ț": "t",
"Ț": "T",
"Ť": "T",
"ť": "t",
"Ŧ": "T",
"ŧ": "t",
"T̆": "T",
"t̆": "t",
"Ũ": "U",
"ũ": "u",
"Ū": "U",
"ū": "u",
"Ŭ": "U",
"ŭ": "u",
"Ů": "U",
"ů": "u",
"Ű": "U",
"ű": "u",
"Ų": "U",
"ų": "u",
"Ȗ": "U",
"ȗ": "u",
"V̆": "V",
"v̆": "v",
"Ŵ": "W",
"ŵ": "w",
"Ẃ": "W",
"ẃ": "w",
"X̆": "X",
"x̆": "x",
"Ŷ": "Y",
"ŷ": "y",
"Ÿ": "Y",
"Y̆": "Y",
"y̆": "y",
"Ź": "Z",
"ź": "z",
"Ż": "Z",
"ż": "z",
"Ž": "Z",
"ž": "z",
"ſ": "s",
"ƒ": "f",
"Ơ": "O",
"ơ": "o",
"Ư": "U",
"ư": "u",
"Ǎ": "A",
"ǎ": "a",
"Ǐ": "I",
"ǐ": "i",
"Ǒ": "O",
"ǒ": "o",
"Ǔ": "U",
"ǔ": "u",
"Ǖ": "U",
"ǖ": "u",
"Ǘ": "U",
"ǘ": "u",
"Ǚ": "U",
"ǚ": "u",
"Ǜ": "U",
"ǜ": "u",
"Ứ": "U",
"ứ": "u",
"Ṹ": "U",
"ṹ": "u",
"Ǻ": "A",
"ǻ": "a",
"Ǽ": "AE",
"ǽ": "ae",
"Ǿ": "O",
"ǿ": "o",
"Þ": "TH",
"þ": "th",
"Ṕ": "P",
"ṕ": "p",
"Ṥ": "S",
"ṥ": "s",
"X́": "X",
"x́": "x",
"Ѓ": "Г",
"ѓ": "г",
"Ќ": "К",
"ќ": "к",
"A̋": "A",
"a̋": "a",
"E̋": "E",
"e̋": "e",
"I̋": "I",
"i̋": "i",
"Ǹ": "N",
"ǹ": "n",
"Ồ": "O",
"ồ": "o",
"Ṑ": "O",
"ṑ": "o",
"Ừ": "U",
"ừ": "u",
"Ẁ": "W",
"ẁ": "w",
"Ỳ": "Y",
"ỳ": "y",
"Ȁ": "A",
"ȁ": "a",
"Ȅ": "E",
"ȅ": "e",
"Ȉ": "I",
"ȉ": "i",
"Ȍ": "O",
"ȍ": "o",
"Ȑ": "R",
"ȑ": "r",
"Ȕ": "U",
"ȕ": "u",
"B̌": "B",
"b̌": "b",
"Č̣": "C",
"č̣": "c",
"Ê̌": "E",
"ê̌": "e",
"F̌": "F",
"f̌": "f",
"Ǧ": "G",
"ǧ": "g",
"Ȟ": "H",
"ȟ": "h",
"J̌": "J",
"ǰ": "j",
"Ǩ": "K",
"ǩ": "k",
"M̌": "M",
"m̌": "m",
"P̌": "P",
"p̌": "p",
"Q̌": "Q",
"q̌": "q",
"Ř̩": "R",
"ř̩": "r",
"Ṧ": "S",
"ṧ": "s",
"V̌": "V",
"v̌": "v",
"W̌": "W",
"w̌": "w",
"X̌": "X",
"x̌": "x",
"Y̌": "Y",
"y̌": "y",
"A̧": "A",
"a̧": "a",
"B̧": "B",
"b̧": "b",
"Ḑ": "D",
"ḑ": "d",
"Ȩ": "E",
"ȩ": "e",
"Ɛ̧": "E",
"ɛ̧": "e",
"Ḩ": "H",
"ḩ": "h",
"I̧": "I",
"i̧": "i",
"Ɨ̧": "I",
"ɨ̧": "i",
"M̧": "M",
"m̧": "m",
"O̧": "O",
"o̧": "o",
"Q̧": "Q",
"q̧": "q",
"U̧": "U",
"u̧": "u",
"X̧": "X",
"x̧": "x",
"Z̧": "Z",
"z̧": "z",
"й":"и",
"Й":"И",
"ё":"е",
"Ё":"Е",
};
var chars = Object.keys(characterMap).join('|');
var allAccents = new RegExp(chars, 'g');
var firstAccent = new RegExp(chars, '');
function matcher(match) {
return characterMap[match];
}
var removeAccents = function(string) {
return string.replace(allAccents, matcher);
};
var hasAccents = function(string) {
return !!string.match(firstAccent);
};
module.exports = removeAccents;
module.exports.has = hasAccents;
module.exports.remove = removeAccents;
/***/ }),
/***/ 7755:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
/**
* @license React
* use-sync-external-store-shim.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var e=__webpack_require__(9196);function h(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var k="function"===typeof Object.is?Object.is:h,l=e.useState,m=e.useEffect,n=e.useLayoutEffect,p=e.useDebugValue;function q(a,b){var d=b(),f=l({inst:{value:d,getSnapshot:b}}),c=f[0].inst,g=f[1];n(function(){c.value=d;c.getSnapshot=b;r(c)&&g({inst:c})},[a,d,b]);m(function(){r(c)&&g({inst:c});return a(function(){r(c)&&g({inst:c})})},[a]);p(d);return d}
function r(a){var b=a.getSnapshot;a=a.value;try{var d=b();return!k(a,d)}catch(f){return!0}}function t(a,b){return b()}var u="undefined"===typeof window||"undefined"===typeof window.document||"undefined"===typeof window.document.createElement?t:q;exports.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:u;
/***/ }),
/***/ 635:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
if (true) {
module.exports = __webpack_require__(7755);
} else {}
/***/ }),
/***/ 9196:
/***/ (function(module) {
"use strict";
module.exports = window["React"];
/***/ }),
/***/ 7153:
/***/ (function(module, exports) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2018 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
'use strict';
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = '';
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
classes = appendClass(classes, parseValue(arg));
}
}
return classes;
}
function parseValue (arg) {
if (typeof arg === 'string' || typeof arg === 'number') {
return arg;
}
if (typeof arg !== 'object') {
return '';
}
if (Array.isArray(arg)) {
return classNames.apply(null, arg);
}
if (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes('[native code]')) {
return arg.toString();
}
var classes = '';
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes = appendClass(classes, key);
}
}
return classes;
}
function appendClass (value, newClass) {
if (!newClass) {
return value;
}
if (value) {
return value + ' ' + newClass;
}
return value + newClass;
}
if ( true && module.exports) {
classNames.default = classNames;
module.exports = classNames;
} else if (true) {
// register as 'classnames', consistent with npm package name
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () {
return classNames;
}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
}());
/***/ })
/******/ });
/************************************************************************/
/******/ // 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 });
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/nonce */
/******/ !function() {
/******/ __webpack_require__.nc = undefined;
/******/ }();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be in strict mode.
!function() {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"AnglePickerControl": function() { return /* reexport */ AnglePickerControl; },
"Animate": function() { return /* reexport */ Animate; },
"Autocomplete": function() { return /* reexport */ Autocomplete; },
"BaseControl": function() { return /* reexport */ base_control; },
"BlockQuotation": function() { return /* reexport */ external_wp_primitives_namespaceObject.BlockQuotation; },
"Button": function() { return /* reexport */ build_module_button; },
"ButtonGroup": function() { return /* reexport */ button_group; },
"Card": function() { return /* reexport */ card_component; },
"CardBody": function() { return /* reexport */ card_body_component; },
"CardDivider": function() { return /* reexport */ card_divider_component; },
"CardFooter": function() { return /* reexport */ card_footer_component; },
"CardHeader": function() { return /* reexport */ card_header_component; },
"CardMedia": function() { return /* reexport */ card_media_component; },
"CheckboxControl": function() { return /* reexport */ checkbox_control; },
"Circle": function() { return /* reexport */ external_wp_primitives_namespaceObject.Circle; },
"ClipboardButton": function() { return /* reexport */ ClipboardButton; },
"ColorIndicator": function() { return /* reexport */ color_indicator; },
"ColorPalette": function() { return /* reexport */ color_palette; },
"ColorPicker": function() { return /* reexport */ LegacyAdapter; },
"ComboboxControl": function() { return /* reexport */ combobox_control; },
"CustomGradientPicker": function() { return /* reexport */ CustomGradientPicker; },
"CustomSelectControl": function() { return /* reexport */ StableCustomSelectControl; },
"Dashicon": function() { return /* reexport */ dashicon; },
"DatePicker": function() { return /* reexport */ date; },
"DateTimePicker": function() { return /* reexport */ build_module_date_time; },
"Disabled": function() { return /* reexport */ disabled; },
"Draggable": function() { return /* reexport */ draggable; },
"DropZone": function() { return /* reexport */ drop_zone; },
"DropZoneProvider": function() { return /* reexport */ DropZoneProvider; },
"Dropdown": function() { return /* reexport */ dropdown; },
"DropdownMenu": function() { return /* reexport */ dropdown_menu; },
"DuotonePicker": function() { return /* reexport */ duotone_picker; },
"DuotoneSwatch": function() { return /* reexport */ duotone_swatch; },
"ExternalLink": function() { return /* reexport */ external_link; },
"Fill": function() { return /* reexport */ slot_fill_Fill; },
"Flex": function() { return /* reexport */ flex_component; },
"FlexBlock": function() { return /* reexport */ flex_block_component; },
"FlexItem": function() { return /* reexport */ flex_item_component; },
"FocalPointPicker": function() { return /* reexport */ focal_point_picker; },
"FocusReturnProvider": function() { return /* reexport */ with_focus_return_Provider; },
"FocusableIframe": function() { return /* reexport */ FocusableIframe; },
"FontSizePicker": function() { return /* reexport */ font_size_picker; },
"FormFileUpload": function() { return /* reexport */ form_file_upload; },
"FormToggle": function() { return /* reexport */ form_toggle; },
"FormTokenField": function() { return /* reexport */ form_token_field; },
"G": function() { return /* reexport */ external_wp_primitives_namespaceObject.G; },
"GradientPicker": function() { return /* reexport */ GradientPicker; },
"Guide": function() { return /* reexport */ Guide; },
"GuidePage": function() { return /* reexport */ GuidePage; },
"HorizontalRule": function() { return /* reexport */ external_wp_primitives_namespaceObject.HorizontalRule; },
"Icon": function() { return /* reexport */ build_module_icon; },
"IconButton": function() { return /* reexport */ deprecated; },
"IsolatedEventContainer": function() { return /* reexport */ isolated_event_container; },
"KeyboardShortcuts": function() { return /* reexport */ keyboard_shortcuts; },
"Line": function() { return /* reexport */ external_wp_primitives_namespaceObject.Line; },
"MenuGroup": function() { return /* reexport */ menu_group; },
"MenuItem": function() { return /* reexport */ menu_item; },
"MenuItemsChoice": function() { return /* reexport */ MenuItemsChoice; },
"Modal": function() { return /* reexport */ modal; },
"NavigableMenu": function() { return /* reexport */ navigable_container_menu; },
"Notice": function() { return /* reexport */ build_module_notice; },
"NoticeList": function() { return /* reexport */ list; },
"Panel": function() { return /* reexport */ panel; },
"PanelBody": function() { return /* reexport */ body; },
"PanelHeader": function() { return /* reexport */ panel_header; },
"PanelRow": function() { return /* reexport */ row; },
"Path": function() { return /* reexport */ external_wp_primitives_namespaceObject.Path; },
"Placeholder": function() { return /* reexport */ placeholder; },
"Polygon": function() { return /* reexport */ external_wp_primitives_namespaceObject.Polygon; },
"Popover": function() { return /* reexport */ popover; },
"QueryControls": function() { return /* reexport */ query_controls; },
"RadioControl": function() { return /* reexport */ radio_control; },
"RangeControl": function() { return /* reexport */ range_control; },
"Rect": function() { return /* reexport */ external_wp_primitives_namespaceObject.Rect; },
"ResizableBox": function() { return /* reexport */ resizable_box; },
"ResponsiveWrapper": function() { return /* reexport */ responsive_wrapper; },
"SVG": function() { return /* reexport */ external_wp_primitives_namespaceObject.SVG; },
"SandBox": function() { return /* reexport */ sandbox; },
"ScrollLock": function() { return /* reexport */ scroll_lock; },
"SearchControl": function() { return /* reexport */ search_control; },
"SelectControl": function() { return /* reexport */ select_control; },
"Slot": function() { return /* reexport */ slot_fill_Slot; },
"SlotFillProvider": function() { return /* reexport */ Provider; },
"Snackbar": function() { return /* reexport */ snackbar; },
"SnackbarList": function() { return /* reexport */ snackbar_list; },
"Spinner": function() { return /* reexport */ spinner; },
"TabPanel": function() { return /* reexport */ tab_panel; },
"TabbableContainer": function() { return /* reexport */ tabbable; },
"TextControl": function() { return /* reexport */ text_control; },
"TextHighlight": function() { return /* reexport */ text_highlight; },
"TextareaControl": function() { return /* reexport */ textarea_control; },
"TimePicker": function() { return /* reexport */ time; },
"Tip": function() { return /* reexport */ build_module_tip; },
"ToggleControl": function() { return /* reexport */ toggle_control; },
"Toolbar": function() { return /* reexport */ toolbar; },
"ToolbarButton": function() { return /* reexport */ toolbar_button; },
"ToolbarDropdownMenu": function() { return /* reexport */ toolbar_dropdown_menu; },
"ToolbarGroup": function() { return /* reexport */ toolbar_group; },
"ToolbarItem": function() { return /* reexport */ toolbar_item; },
"Tooltip": function() { return /* reexport */ tooltip; },
"TreeSelect": function() { return /* reexport */ tree_select; },
"VisuallyHidden": function() { return /* reexport */ visually_hidden_component; },
"__experimentalAlignmentMatrixControl": function() { return /* reexport */ alignment_matrix_control; },
"__experimentalApplyValueToSides": function() { return /* reexport */ applyValueToSides; },
"__experimentalBorderBoxControl": function() { return /* reexport */ border_box_control_component; },
"__experimentalBorderControl": function() { return /* reexport */ border_control_component; },
"__experimentalBoxControl": function() { return /* reexport */ BoxControl; },
"__experimentalConfirmDialog": function() { return /* reexport */ confirm_dialog_component; },
"__experimentalDimensionControl": function() { return /* reexport */ dimension_control; },
"__experimentalDivider": function() { return /* reexport */ divider_component; },
"__experimentalDropdownContentWrapper": function() { return /* reexport */ dropdown_content_wrapper; },
"__experimentalElevation": function() { return /* reexport */ elevation_component; },
"__experimentalGrid": function() { return /* reexport */ grid_component; },
"__experimentalHStack": function() { return /* reexport */ h_stack_component; },
"__experimentalHasSplitBorders": function() { return /* reexport */ hasSplitBorders; },
"__experimentalHeading": function() { return /* reexport */ heading_component; },
"__experimentalInputControl": function() { return /* reexport */ input_control; },
"__experimentalInputControlPrefixWrapper": function() { return /* reexport */ input_prefix_wrapper; },
"__experimentalInputControlSuffixWrapper": function() { return /* reexport */ input_suffix_wrapper; },
"__experimentalIsDefinedBorder": function() { return /* reexport */ isDefinedBorder; },
"__experimentalIsEmptyBorder": function() { return /* reexport */ isEmptyBorder; },
"__experimentalItem": function() { return /* reexport */ item_component; },
"__experimentalItemGroup": function() { return /* reexport */ item_group_component; },
"__experimentalNavigation": function() { return /* reexport */ Navigation; },
"__experimentalNavigationBackButton": function() { return /* reexport */ back_button; },
"__experimentalNavigationGroup": function() { return /* reexport */ NavigationGroup; },
"__experimentalNavigationItem": function() { return /* reexport */ NavigationItem; },
"__experimentalNavigationMenu": function() { return /* reexport */ NavigationMenu; },
"__experimentalNavigatorBackButton": function() { return /* reexport */ navigator_back_button_component; },
"__experimentalNavigatorButton": function() { return /* reexport */ navigator_button_component; },
"__experimentalNavigatorProvider": function() { return /* reexport */ navigator_provider_component; },
"__experimentalNavigatorScreen": function() { return /* reexport */ navigator_screen_component; },
"__experimentalNavigatorToParentButton": function() { return /* reexport */ navigator_to_parent_button_component; },
"__experimentalNumberControl": function() { return /* reexport */ number_control; },
"__experimentalPaletteEdit": function() { return /* reexport */ PaletteEdit; },
"__experimentalParseQuantityAndUnitFromRawValue": function() { return /* reexport */ parseQuantityAndUnitFromRawValue; },
"__experimentalRadio": function() { return /* reexport */ radio_group_radio; },
"__experimentalRadioGroup": function() { return /* reexport */ radio_group; },
"__experimentalScrollable": function() { return /* reexport */ scrollable_component; },
"__experimentalSpacer": function() { return /* reexport */ spacer_component; },
"__experimentalStyleProvider": function() { return /* reexport */ style_provider; },
"__experimentalSurface": function() { return /* reexport */ surface_component; },
"__experimentalText": function() { return /* reexport */ text_component; },
"__experimentalToggleGroupControl": function() { return /* reexport */ toggle_group_control_component; },
"__experimentalToggleGroupControlOption": function() { return /* reexport */ toggle_group_control_option_component; },
"__experimentalToggleGroupControlOptionIcon": function() { return /* reexport */ toggle_group_control_option_icon_component; },
"__experimentalToolbarContext": function() { return /* reexport */ toolbar_context; },
"__experimentalToolsPanel": function() { return /* reexport */ tools_panel_component; },
"__experimentalToolsPanelContext": function() { return /* reexport */ ToolsPanelContext; },
"__experimentalToolsPanelItem": function() { return /* reexport */ tools_panel_item_component; },
"__experimentalTreeGrid": function() { return /* reexport */ tree_grid; },
"__experimentalTreeGridCell": function() { return /* reexport */ cell; },
"__experimentalTreeGridItem": function() { return /* reexport */ tree_grid_item; },
"__experimentalTreeGridRow": function() { return /* reexport */ tree_grid_row; },
"__experimentalTruncate": function() { return /* reexport */ truncate_component; },
"__experimentalUnitControl": function() { return /* reexport */ unit_control; },
"__experimentalUseCustomUnits": function() { return /* reexport */ useCustomUnits; },
"__experimentalUseNavigator": function() { return /* reexport */ use_navigator; },
"__experimentalUseSlot": function() { return /* reexport */ useSlot; },
"__experimentalUseSlotFills": function() { return /* reexport */ useSlotFills; },
"__experimentalVStack": function() { return /* reexport */ v_stack_component; },
"__experimentalView": function() { return /* reexport */ component; },
"__experimentalZStack": function() { return /* reexport */ z_stack_component; },
"__unstableAnimatePresence": function() { return /* reexport */ AnimatePresence; },
"__unstableComposite": function() { return /* reexport */ Composite; },
"__unstableCompositeGroup": function() { return /* reexport */ CompositeGroup; },
"__unstableCompositeItem": function() { return /* reexport */ CompositeItem; },
"__unstableDisclosureContent": function() { return /* reexport */ DisclosureContent; },
"__unstableGetAnimateClassName": function() { return /* reexport */ getAnimateClassName; },
"__unstableMotion": function() { return /* reexport */ motion; },
"__unstableUseAutocompleteProps": function() { return /* reexport */ useAutocompleteProps; },
"__unstableUseCompositeState": function() { return /* reexport */ useCompositeState; },
"__unstableUseNavigateRegions": function() { return /* reexport */ useNavigateRegions; },
"createSlotFill": function() { return /* reexport */ createSlotFill; },
"navigateRegions": function() { return /* reexport */ navigate_regions; },
"privateApis": function() { return /* reexport */ privateApis; },
"useBaseControlProps": function() { return /* reexport */ useBaseControlProps; },
"withConstrainedTabbing": function() { return /* reexport */ with_constrained_tabbing; },
"withFallbackStyles": function() { return /* reexport */ with_fallback_styles; },
"withFilters": function() { return /* reexport */ withFilters; },
"withFocusOutside": function() { return /* reexport */ with_focus_outside; },
"withFocusReturn": function() { return /* reexport */ with_focus_return; },
"withNotices": function() { return /* reexport */ with_notices; },
"withSpokenMessages": function() { return /* reexport */ with_spoken_messages; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/components/build-module/text/styles.js
var text_styles_namespaceObject = {};
__webpack_require__.r(text_styles_namespaceObject);
__webpack_require__.d(text_styles_namespaceObject, {
"Text": function() { return Text; },
"block": function() { return styles_block; },
"destructive": function() { return destructive; },
"highlighterText": function() { return highlighterText; },
"muted": function() { return muted; },
"positive": function() { return positive; },
"upperCase": function() { return upperCase; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/components/build-module/ui/tooltip/styles.js
var tooltip_styles_namespaceObject = {};
__webpack_require__.r(tooltip_styles_namespaceObject);
__webpack_require__.d(tooltip_styles_namespaceObject, {
"TooltipContent": function() { return TooltipContent; },
"TooltipPopoverView": function() { return TooltipPopoverView; },
"TooltipShortcut": function() { return TooltipShortcut; },
"noOutline": function() { return noOutline; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/components/build-module/toggle-group-control/toggle-group-control-option-base/styles.js
var toggle_group_control_option_base_styles_namespaceObject = {};
__webpack_require__.r(toggle_group_control_option_base_styles_namespaceObject);
__webpack_require__.d(toggle_group_control_option_base_styles_namespaceObject, {
"ButtonContentView": function() { return ButtonContentView; },
"LabelView": function() { return LabelView; },
"buttonView": function() { return buttonView; },
"labelBlock": function() { return labelBlock; }
});
;// CONCATENATED MODULE: external ["wp","primitives"]
var external_wp_primitives_namespaceObject = window["wp"]["primitives"];
;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/extends.js
function extends_extends() {
return extends_extends = Object.assign ? Object.assign.bind() : function (n) {
for (var e = 1; e < arguments.length; e++) {
var t = arguments[e];
for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
}
return n;
}, extends_extends.apply(null, arguments);
}
;// CONCATENATED MODULE: external ["wp","element"]
var external_wp_element_namespaceObject = window["wp"]["element"];
// EXTERNAL MODULE: ./node_modules/classnames/index.js
var classnames = __webpack_require__(7153);
var classnames_default = /*#__PURE__*/__webpack_require__.n(classnames);
;// CONCATENATED MODULE: external ["wp","i18n"]
var external_wp_i18n_namespaceObject = window["wp"]["i18n"];
;// CONCATENATED MODULE: external ["wp","compose"]
var external_wp_compose_namespaceObject = window["wp"]["compose"];
;// CONCATENATED MODULE: ./node_modules/reakit/es/_rollupPluginBabelHelpers-1f0bf8c2.js
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _createForOfIteratorHelperLoose(o, allowArrayLike) {
var it;
if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
return function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
it = o[Symbol.iterator]();
return it.next.bind(it);
}
// EXTERNAL MODULE: external "React"
var external_React_ = __webpack_require__(9196);
var external_React_default = /*#__PURE__*/__webpack_require__.n(external_React_);
;// CONCATENATED MODULE: ./node_modules/reakit-system/es/_rollupPluginBabelHelpers-0c84a174.js
function _rollupPluginBabelHelpers_0c84a174_defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _rollupPluginBabelHelpers_0c84a174_ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _rollupPluginBabelHelpers_0c84a174_objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
_rollupPluginBabelHelpers_0c84a174_ownKeys(Object(source), true).forEach(function (key) {
_rollupPluginBabelHelpers_0c84a174_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
_rollupPluginBabelHelpers_0c84a174_ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function _rollupPluginBabelHelpers_0c84a174_objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _rollupPluginBabelHelpers_0c84a174_unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _rollupPluginBabelHelpers_0c84a174_arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _rollupPluginBabelHelpers_0c84a174_arrayLikeToArray(o, minLen);
}
function _rollupPluginBabelHelpers_0c84a174_arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _rollupPluginBabelHelpers_0c84a174_createForOfIteratorHelperLoose(o, allowArrayLike) {
var it;
if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
if (Array.isArray(o) || (it = _rollupPluginBabelHelpers_0c84a174_unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
return function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
it = o[Symbol.iterator]();
return it.next.bind(it);
}
;// CONCATENATED MODULE: ./node_modules/reakit-system/es/SystemContext.js
var SystemContext = /*#__PURE__*/(0,external_React_.createContext)({});
;// CONCATENATED MODULE: ./node_modules/reakit-system/es/useCreateElement.js
function isRenderProp(children) {
return typeof children === "function";
}
/**
* Custom hook that will call `children` if it's a function. If
* `useCreateElement` has been passed to the context, it'll be used instead.
*
* @example
* import React from "react";
* import { SystemProvider, useCreateElement } from "reakit-system";
*
* const system = {
* useCreateElement(type, props, children = props.children) {
* // very similar to what `useCreateElement` does already
* if (typeof children === "function") {
* const { children: _, ...rest } = props;
* return children(rest);
* }
* return React.createElement(type, props, children);
* },
* };
*
* function Component(props) {
* return useCreateElement("div", props);
* }
*
* function App() {
* return (
* <SystemProvider unstable_system={system}>
* <Component url="url">{({ url }) => <a href={url}>link</a>}</Component>
* </SystemProvider>
* );
* }
*/
var useCreateElement = function useCreateElement(type, props, children) {
if (children === void 0) {
children = props.children;
}
var context = (0,external_React_.useContext)(SystemContext);
if (context.useCreateElement) {
return context.useCreateElement(type, props, children);
}
if (typeof type === "string" && isRenderProp(children)) {
var _ = props.children,
rest = _rollupPluginBabelHelpers_0c84a174_objectWithoutPropertiesLoose(props, ["children"]);
return children(rest);
}
return /*#__PURE__*/(0,external_React_.createElement)(type, props, children);
};
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/_rollupPluginBabelHelpers-1f0bf8c2.js
function _rollupPluginBabelHelpers_1f0bf8c2_defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _rollupPluginBabelHelpers_1f0bf8c2_ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _rollupPluginBabelHelpers_1f0bf8c2_objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
_rollupPluginBabelHelpers_1f0bf8c2_ownKeys(Object(source), true).forEach(function (key) {
_rollupPluginBabelHelpers_1f0bf8c2_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
_rollupPluginBabelHelpers_1f0bf8c2_ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function _rollupPluginBabelHelpers_1f0bf8c2_objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _rollupPluginBabelHelpers_1f0bf8c2_unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _rollupPluginBabelHelpers_1f0bf8c2_arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _rollupPluginBabelHelpers_1f0bf8c2_arrayLikeToArray(o, minLen);
}
function _rollupPluginBabelHelpers_1f0bf8c2_arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _rollupPluginBabelHelpers_1f0bf8c2_createForOfIteratorHelperLoose(o, allowArrayLike) {
var it;
if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
if (Array.isArray(o) || (it = _rollupPluginBabelHelpers_1f0bf8c2_unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
return function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
it = o[Symbol.iterator]();
return it.next.bind(it);
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/isObject.js
/**
* Checks whether `arg` is an object or not.
*
* @returns {boolean}
*/
function isObject_isObject(arg) {
return typeof arg === "object" && arg != null;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/isPlainObject.js
/**
* Checks whether `arg` is a plain object or not.
*
* @returns {boolean}
*/
function isPlainObject(arg) {
var _proto$constructor;
if (!isObject_isObject(arg)) return false;
var proto = Object.getPrototypeOf(arg);
if (proto == null) return true;
return ((_proto$constructor = proto.constructor) === null || _proto$constructor === void 0 ? void 0 : _proto$constructor.toString()) === Object.toString();
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/splitProps.js
/**
* Splits an object (`props`) into a tuple where the first item is an object
* with the passed `keys`, and the second item is an object with these keys
* omitted.
*
* @deprecated will be removed in version 2
*
* @example
* import { splitProps } from "reakit-utils";
*
* splitProps({ a: "a", b: "b" }, ["a"]); // [{ a: "a" }, { b: "b" }]
*/
function __deprecatedSplitProps(props, keys) {
var propsKeys = Object.keys(props);
var picked = {};
var omitted = {};
for (var _i = 0, _propsKeys = propsKeys; _i < _propsKeys.length; _i++) {
var key = _propsKeys[_i];
if (keys.indexOf(key) >= 0) {
picked[key] = props[key];
} else {
omitted[key] = props[key];
}
}
return [picked, omitted];
}
/**
* Splits an object (`props`) into a tuple where the first item
* is the `state` property, and the second item is the rest of the properties.
*
* It is also backward compatible with version 1. If `keys` are passed then
* splits an object (`props`) into a tuple where the first item is an object
* with the passed `keys`, and the second item is an object with these keys
* omitted.
*
* @example
* import { splitProps } from "reakit-utils";
*
* splitProps({ a: "a", b: "b" }, ["a"]); // [{ a: "a" }, { b: "b" }]
*
* @example
* import { splitProps } from "reakit-utils";
*
* splitProps({ state: { a: "a" }, b: "b" }); // [{ a: "a" }, { b: "b" }]
*/
function splitProps(props, keys) {
if (keys === void 0) {
keys = [];
}
if (!isPlainObject(props.state)) {
return __deprecatedSplitProps(props, keys);
}
var _deprecatedSplitProp = __deprecatedSplitProps(props, [].concat(keys, ["state"])),
picked = _deprecatedSplitProp[0],
omitted = _deprecatedSplitProp[1];
var state = picked.state,
restPicked = _rollupPluginBabelHelpers_1f0bf8c2_objectWithoutPropertiesLoose(picked, ["state"]);
return [_rollupPluginBabelHelpers_1f0bf8c2_objectSpread2(_rollupPluginBabelHelpers_1f0bf8c2_objectSpread2({}, state), restPicked), omitted];
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/shallowEqual.js
/**
* Compares two objects.
*
* @example
* import { shallowEqual } from "reakit-utils";
*
* shallowEqual({ a: "a" }, {}); // false
* shallowEqual({ a: "a" }, { b: "b" }); // false
* shallowEqual({ a: "a" }, { a: "a" }); // true
* shallowEqual({ a: "a" }, { a: "a", b: "b" }); // false
*/
function shallowEqual(objA, objB) {
if (objA === objB) return true;
if (!objA) return false;
if (!objB) return false;
if (typeof objA !== "object") return false;
if (typeof objB !== "object") return false;
var aKeys = Object.keys(objA);
var bKeys = Object.keys(objB);
var length = aKeys.length;
if (bKeys.length !== length) return false;
for (var _i = 0, _aKeys = aKeys; _i < _aKeys.length; _i++) {
var key = _aKeys[_i];
if (objA[key] !== objB[key]) {
return false;
}
}
return true;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/normalizePropsAreEqual.js
/**
* This higher order functions take `propsAreEqual` function and
* returns a new function which normalizes the props.
*
* Normalizing in our case is making sure the `propsAreEqual` works with
* both version 1 (object spreading) and version 2 (state object) state passing.
*
* To achieve this, the returned function in case of a state object
* will spread the state object in both `prev` and `next props.
*
* Other case it just returns the function as is which makes sure
* that we are still backward compatible
*/
function normalizePropsAreEqual(propsAreEqual) {
if (propsAreEqual.name === "normalizePropsAreEqualInner") {
return propsAreEqual;
}
return function normalizePropsAreEqualInner(prev, next) {
if (!isPlainObject(prev.state) || !isPlainObject(next.state)) {
return propsAreEqual(prev, next);
}
return propsAreEqual(_rollupPluginBabelHelpers_1f0bf8c2_objectSpread2(_rollupPluginBabelHelpers_1f0bf8c2_objectSpread2({}, prev.state), prev), _rollupPluginBabelHelpers_1f0bf8c2_objectSpread2(_rollupPluginBabelHelpers_1f0bf8c2_objectSpread2({}, next.state), next));
};
}
;// CONCATENATED MODULE: ./node_modules/reakit-system/es/createComponent.js
function forwardRef(component) {
return /*#__PURE__*/(0,external_React_.forwardRef)(component);
}
function memo(component, propsAreEqual) {
return /*#__PURE__*/(0,external_React_.memo)(component, propsAreEqual);
}
/**
* Creates a React component.
*
* @example
* import { createComponent } from "reakit-system";
*
* const A = createComponent({ as: "a" });
*
* @param options
*/
function createComponent(_ref) {
var type = _ref.as,
useHook = _ref.useHook,
shouldMemo = _ref.memo,
_ref$propsAreEqual = _ref.propsAreEqual,
propsAreEqual = _ref$propsAreEqual === void 0 ? useHook === null || useHook === void 0 ? void 0 : useHook.unstable_propsAreEqual : _ref$propsAreEqual,
_ref$keys = _ref.keys,
keys = _ref$keys === void 0 ? (useHook === null || useHook === void 0 ? void 0 : useHook.__keys) || [] : _ref$keys,
_ref$useCreateElement = _ref.useCreateElement,
useCreateElement$1 = _ref$useCreateElement === void 0 ? useCreateElement : _ref$useCreateElement;
var Comp = function Comp(_ref2, ref) {
var _ref2$as = _ref2.as,
as = _ref2$as === void 0 ? type : _ref2$as,
props = _rollupPluginBabelHelpers_0c84a174_objectWithoutPropertiesLoose(_ref2, ["as"]);
if (useHook) {
var _as$render;
var _splitProps = splitProps(props, keys),
_options = _splitProps[0],
htmlProps = _splitProps[1];
var _useHook = useHook(_options, _rollupPluginBabelHelpers_0c84a174_objectSpread2({
ref: ref
}, htmlProps)),
wrapElement = _useHook.wrapElement,
elementProps = _rollupPluginBabelHelpers_0c84a174_objectWithoutPropertiesLoose(_useHook, ["wrapElement"]); // @ts-ignore
var asKeys = ((_as$render = as.render) === null || _as$render === void 0 ? void 0 : _as$render.__keys) || as.__keys;
var asOptions = asKeys && splitProps(props, asKeys)[0];
var allProps = asOptions ? _rollupPluginBabelHelpers_0c84a174_objectSpread2(_rollupPluginBabelHelpers_0c84a174_objectSpread2({}, elementProps), asOptions) : elementProps;
var _element = useCreateElement$1(as, allProps);
if (wrapElement) {
return wrapElement(_element);
}
return _element;
}
return useCreateElement$1(as, _rollupPluginBabelHelpers_0c84a174_objectSpread2({
ref: ref
}, props));
};
if (false) {}
Comp = forwardRef(Comp);
if (shouldMemo) {
Comp = memo(Comp, propsAreEqual && normalizePropsAreEqual(propsAreEqual));
}
Comp.__keys = keys;
Comp.unstable_propsAreEqual = normalizePropsAreEqual(propsAreEqual || shallowEqual);
return Comp;
}
;// CONCATENATED MODULE: ./node_modules/reakit-system/es/useToken.js
/**
* React custom hook that returns the value of any token defined in the
* SystemContext. It's mainly used internally in [`useOptions`](#useoptions)
* and [`useProps`](#useprops).
*
* @example
* import { SystemProvider, useToken } from "reakit-system";
*
* const system = {
* token: "value",
* };
*
* function Component(props) {
* const token = useToken("token", "default value");
* return <div {...props}>{token}</div>;
* }
*
* function App() {
* return (
* <SystemProvider unstable_system={system}>
* <Component />
* </SystemProvider>
* );
* }
*/
function useToken(token, defaultValue) {
(0,external_React_.useDebugValue)(token);
var context = (0,external_React_.useContext)(SystemContext);
return context[token] != null ? context[token] : defaultValue;
}
;// CONCATENATED MODULE: ./node_modules/reakit-system/es/useProps.js
/**
* React custom hook that returns the props returned by a given
* `use${name}Props` in the SystemContext.
*
* @example
* import { SystemProvider, useProps } from "reakit-system";
*
* const system = {
* useAProps(options, htmlProps) {
* return {
* ...htmlProps,
* href: options.url,
* };
* },
* };
*
* function A({ url, ...htmlProps }) {
* const props = useProps("A", { url }, htmlProps);
* return <a {...props} />;
* }
*
* function App() {
* return (
* <SystemProvider unstable_system={system}>
* <A url="url">It will convert url into href in useAProps</A>
* </SystemProvider>
* );
* }
*/
function useProps(name, options, htmlProps) {
if (options === void 0) {
options = {};
}
if (htmlProps === void 0) {
htmlProps = {};
}
var hookName = "use" + name + "Props";
(0,external_React_.useDebugValue)(hookName);
var useHook = useToken(hookName);
if (useHook) {
return useHook(options, htmlProps);
}
return htmlProps;
}
;// CONCATENATED MODULE: ./node_modules/reakit-system/es/useOptions.js
/**
* React custom hook that returns the options returned by a given
* `use${name}Options` in the SystemContext.
*
* @example
* import React from "react";
* import { SystemProvider, useOptions } from "reakit-system";
*
* const system = {
* useAOptions(options, htmlProps) {
* return {
* ...options,
* url: htmlProps.href,
* };
* },
* };
*
* function A({ url, ...htmlProps }) {
* const options = useOptions("A", { url }, htmlProps);
* return <a href={options.url} {...htmlProps} />;
* }
*
* function App() {
* return (
* <SystemProvider unstable_system={system}>
* <A href="url">
* It will convert href into url in useAOptions and then url into href in A
* </A>
* </SystemProvider>
* );
* }
*/
function useOptions(name, options, htmlProps) {
if (options === void 0) {
options = {};
}
if (htmlProps === void 0) {
htmlProps = {};
}
var hookName = "use" + name + "Options";
(0,external_React_.useDebugValue)(hookName);
var useHook = useToken(hookName);
if (useHook) {
return _rollupPluginBabelHelpers_0c84a174_objectSpread2(_rollupPluginBabelHelpers_0c84a174_objectSpread2({}, options), useHook(options, htmlProps));
}
return options;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/toArray.js
/**
* Transforms `arg` into an array if it's not already.
*
* @example
* import { toArray } from "reakit-utils";
*
* toArray("a"); // ["a"]
* toArray(["a"]); // ["a"]
*/
function toArray(arg) {
if (Array.isArray(arg)) {
return arg;
}
return typeof arg !== "undefined" ? [arg] : [];
}
;// CONCATENATED MODULE: ./node_modules/reakit-system/es/createHook.js
/**
* Creates a React custom hook that will return component props.
*
* @example
* import { createHook } from "reakit-system";
*
* const useA = createHook({
* name: "A",
* keys: ["url"], // custom props/options keys
* useProps(options, htmlProps) {
* return {
* ...htmlProps,
* href: options.url,
* };
* },
* });
*
* function A({ url, ...htmlProps }) {
* const props = useA({ url }, htmlProps);
* return <a {...props} />;
* }
*
* @param options
*/
function createHook(options) {
var _options$useState, _composedHooks$;
var composedHooks = toArray(options.compose);
var __useOptions = function __useOptions(hookOptions, htmlProps) {
// Call the current hook's useOptions first
if (options.useOptions) {
hookOptions = options.useOptions(hookOptions, htmlProps);
} // If there's name, call useOptions from the system context
if (options.name) {
hookOptions = useOptions(options.name, hookOptions, htmlProps);
} // Run composed hooks useOptions
if (options.compose) {
for (var _iterator = _rollupPluginBabelHelpers_0c84a174_createForOfIteratorHelperLoose(composedHooks), _step; !(_step = _iterator()).done;) {
var hook = _step.value;
hookOptions = hook.__useOptions(hookOptions, htmlProps);
}
}
return hookOptions;
};
var useHook = function useHook(hookOptions, htmlProps, unstable_ignoreUseOptions) {
if (hookOptions === void 0) {
hookOptions = {};
}
if (htmlProps === void 0) {
htmlProps = {};
}
if (unstable_ignoreUseOptions === void 0) {
unstable_ignoreUseOptions = false;
}
// This won't execute when useHook was called from within another useHook
if (!unstable_ignoreUseOptions) {
hookOptions = __useOptions(hookOptions, htmlProps);
} // Call the current hook's useProps
if (options.useProps) {
htmlProps = options.useProps(hookOptions, htmlProps);
} // If there's name, call useProps from the system context
if (options.name) {
htmlProps = useProps(options.name, hookOptions, htmlProps);
}
if (options.compose) {
if (options.useComposeOptions) {
hookOptions = options.useComposeOptions(hookOptions, htmlProps);
}
if (options.useComposeProps) {
htmlProps = options.useComposeProps(hookOptions, htmlProps);
} else {
for (var _iterator2 = _rollupPluginBabelHelpers_0c84a174_createForOfIteratorHelperLoose(composedHooks), _step2; !(_step2 = _iterator2()).done;) {
var hook = _step2.value;
htmlProps = hook(hookOptions, htmlProps, true);
}
}
} // Remove undefined values from htmlProps
var finalHTMLProps = {};
var definedHTMLProps = htmlProps || {};
for (var prop in definedHTMLProps) {
if (definedHTMLProps[prop] !== undefined) {
finalHTMLProps[prop] = definedHTMLProps[prop];
}
}
return finalHTMLProps;
};
useHook.__useOptions = __useOptions;
var composedKeys = composedHooks.reduce(function (keys, hook) {
keys.push.apply(keys, hook.__keys || []);
return keys;
}, []); // It's used by createComponent to split option props (keys) and html props
useHook.__keys = [].concat(composedKeys, ((_options$useState = options.useState) === null || _options$useState === void 0 ? void 0 : _options$useState.__keys) || [], options.keys || []);
useHook.unstable_propsAreEqual = options.propsAreEqual || ((_composedHooks$ = composedHooks[0]) === null || _composedHooks$ === void 0 ? void 0 : _composedHooks$.unstable_propsAreEqual) || shallowEqual;
if (false) {}
return useHook;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/useForkRef.js
// https://github.com/mui-org/material-ui/blob/2bcc874cf07b81202968f769cb9c2398c7c11311/packages/material-ui/src/utils/useForkRef.js
function setRef(ref, value) {
if (value === void 0) {
value = null;
}
if (!ref) return;
if (typeof ref === "function") {
ref(value);
} else {
ref.current = value;
}
}
/**
* Merges up to two React Refs into a single memoized function React Ref so you
* can pass it to an element.
*
* @example
* import React from "react";
* import { useForkRef } from "reakit-utils";
*
* const Component = React.forwardRef((props, ref) => {
* const internalRef = React.useRef();
* return <div {...props} ref={useForkRef(internalRef, ref)} />;
* });
*/
function useForkRef(refA, refB) {
return (0,external_React_.useMemo)(function () {
if (refA == null && refB == null) {
return null;
}
return function (value) {
setRef(refA, value);
setRef(refB, value);
};
}, [refA, refB]);
}
;// CONCATENATED MODULE: ./node_modules/reakit-warning/es/useWarning.js
function isRefObject(ref) {
return isObject(ref) && "current" in ref;
}
/**
* Logs `messages` to the console using `console.warn` based on a `condition`.
* This should be used inside components.
*/
function useWarning(condition) {
for (var _len = arguments.length, messages = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
messages[_key - 1] = arguments[_key];
}
if (false) {}
}
;// CONCATENATED MODULE: ./node_modules/reakit-warning/es/index.js
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/getDocument.js
/**
* Returns `element.ownerDocument || document`.
*/
function getDocument(element) {
return element ? element.ownerDocument || element : document;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/getWindow.js
// Thanks to Fluent UI for doing the [research on IE11 memory leak](https://github.com/microsoft/fluentui/pull/9010#issuecomment-490768427)
var _window; // Note: Accessing "window" in IE11 is somewhat expensive, and calling "typeof window"
// hits a memory leak, whereas aliasing it and calling "typeof _window" does not.
// Caching the window value at the file scope lets us minimize the impact.
try {
_window = window;
} catch (e) {
/* no-op */
}
/**
* Returns `element.ownerDocument.defaultView || window`.
*/
function getWindow(element) {
if (!element) {
return _window;
}
return getDocument(element).defaultView || _window;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/canUseDOM.js
function checkIsBrowser() {
var _window = getWindow();
return Boolean(typeof _window !== "undefined" && _window.document && _window.document.createElement);
}
/**
* It's `true` if it is running in a browser environment or `false` if it is not (SSR).
*
* @example
* import { canUseDOM } from "reakit-utils";
*
* const title = canUseDOM ? document.title : "";
*/
var canUseDOM = checkIsBrowser();
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/useIsomorphicEffect.js
/**
* `React.useLayoutEffect` that fallbacks to `React.useEffect` on server side
* rendering.
*/
var useIsomorphicEffect = !canUseDOM ? external_React_.useEffect : external_React_.useLayoutEffect;
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/useLiveRef.js
/**
* A `React.Ref` that keeps track of the passed `value`.
*/
function useLiveRef(value) {
var ref = (0,external_React_.useRef)(value);
useIsomorphicEffect(function () {
ref.current = value;
});
return ref;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/isSelfTarget.js
/**
* Returns `true` if `event.target` and `event.currentTarget` are the same.
*/
function isSelfTarget(event) {
return event.target === event.currentTarget;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/getActiveElement.js
/**
* Returns `element.ownerDocument.activeElement`.
*/
function getActiveElement_getActiveElement(element) {
var _getDocument = getDocument(element),
activeElement = _getDocument.activeElement;
if (!(activeElement !== null && activeElement !== void 0 && activeElement.nodeName)) {
// In IE11, activeElement might be an empty object if we're interacting
// with elements inside of an iframe.
return null;
}
return activeElement;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/contains.js
/**
* Similar to `Element.prototype.contains`, but a little bit faster when
* `element` is the same as `child`.
*
* @example
* import { contains } from "reakit-utils";
*
* contains(document.getElementById("parent"), document.getElementById("child"));
*/
function contains(parent, child) {
return parent === child || parent.contains(child);
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/hasFocusWithin.js
/**
* Checks if `element` has focus within. Elements that are referenced by
* `aria-activedescendant` are also considered.
*
* @example
* import { hasFocusWithin } from "reakit-utils";
*
* hasFocusWithin(document.getElementById("id"));
*/
function hasFocusWithin(element) {
var activeElement = getActiveElement_getActiveElement(element);
if (!activeElement) return false;
if (contains(element, activeElement)) return true;
var activeDescendant = activeElement.getAttribute("aria-activedescendant");
if (!activeDescendant) return false;
if (activeDescendant === element.id) return true;
return !!element.querySelector("#" + activeDescendant);
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/isPortalEvent.js
/**
* Returns `true` if `event` has been fired within a React Portal element.
*/
function isPortalEvent(event) {
return !contains(event.currentTarget, event.target);
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/isButton.js
var buttonInputTypes = ["button", "color", "file", "image", "reset", "submit"];
/**
* Checks whether `element` is a native HTML button element.
*
* @example
* import { isButton } from "reakit-utils";
*
* isButton(document.querySelector("button")); // true
* isButton(document.querySelector("input[type='button']")); // true
* isButton(document.querySelector("div")); // false
* isButton(document.querySelector("input[type='text']")); // false
* isButton(document.querySelector("div[role='button']")); // false
*
* @returns {boolean}
*/
function isButton(element) {
if (element.tagName === "BUTTON") return true;
if (element.tagName === "INPUT") {
var input = element;
return buttonInputTypes.indexOf(input.type) !== -1;
}
return false;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/dom.js
/**
* Checks if a given string exists in the user agent string.
*/
function isUA(string) {
if (!canUseDOM) return false;
return window.navigator.userAgent.indexOf(string) !== -1;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/matches.js
/**
* Ponyfill for `Element.prototype.matches`
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/matches
*/
function matches(element, selectors) {
if ("matches" in element) {
return element.matches(selectors);
}
if ("msMatchesSelector" in element) {
return element.msMatchesSelector(selectors);
}
return element.webkitMatchesSelector(selectors);
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/tabbable.js
/** @module tabbable */
var selector = "input:not([type='hidden']):not([disabled]), select:not([disabled]), " + "textarea:not([disabled]), a[href], button:not([disabled]), [tabindex], " + "iframe, object, embed, area[href], audio[controls], video[controls], " + "[contenteditable]:not([contenteditable='false'])";
function isVisible(element) {
var htmlElement = element;
return htmlElement.offsetWidth > 0 || htmlElement.offsetHeight > 0 || element.getClientRects().length > 0;
}
function hasNegativeTabIndex(element) {
var tabIndex = parseInt(element.getAttribute("tabindex") || "0", 10);
return tabIndex < 0;
}
/**
* Checks whether `element` is focusable or not.
*
* @memberof tabbable
*
* @example
* import { isFocusable } from "reakit-utils";
*
* isFocusable(document.querySelector("input")); // true
* isFocusable(document.querySelector("input[tabindex='-1']")); // true
* isFocusable(document.querySelector("input[hidden]")); // false
* isFocusable(document.querySelector("input:disabled")); // false
*/
function isFocusable(element) {
return matches(element, selector) && isVisible(element);
}
/**
* Checks whether `element` is tabbable or not.
*
* @memberof tabbable
*
* @example
* import { isTabbable } from "reakit-utils";
*
* isTabbable(document.querySelector("input")); // true
* isTabbable(document.querySelector("input[tabindex='-1']")); // false
* isTabbable(document.querySelector("input[hidden]")); // false
* isTabbable(document.querySelector("input:disabled")); // false
*/
function isTabbable(element) {
return isFocusable(element) && !hasNegativeTabIndex(element);
}
/**
* Returns all the focusable elements in `container`.
*
* @memberof tabbable
*
* @param {Element} container
*
* @returns {Element[]}
*/
function getAllFocusableIn(container) {
var allFocusable = Array.from(container.querySelectorAll(selector));
allFocusable.unshift(container);
return allFocusable.filter(isFocusable);
}
/**
* Returns the first focusable element in `container`.
*
* @memberof tabbable
*
* @param {Element} container
*
* @returns {Element|null}
*/
function getFirstFocusableIn(container) {
var _getAllFocusableIn = getAllFocusableIn(container),
first = _getAllFocusableIn[0];
return first || null;
}
/**
* Returns all the tabbable elements in `container`, including the container
* itself.
*
* @memberof tabbable
*
* @param {Element} container
* @param fallbackToFocusable If `true`, it'll return focusable elements if there are no tabbable ones.
*
* @returns {Element[]}
*/
function getAllTabbableIn(container, fallbackToFocusable) {
var allFocusable = Array.from(container.querySelectorAll(selector));
var allTabbable = allFocusable.filter(isTabbable);
if (isTabbable(container)) {
allTabbable.unshift(container);
}
if (!allTabbable.length && fallbackToFocusable) {
return allFocusable;
}
return allTabbable;
}
/**
* Returns the first tabbable element in `container`, including the container
* itself if it's tabbable.
*
* @memberof tabbable
*
* @param {Element} container
* @param fallbackToFocusable If `true`, it'll return the first focusable element if there are no tabbable ones.
*
* @returns {Element|null}
*/
function getFirstTabbableIn(container, fallbackToFocusable) {
var _getAllTabbableIn = getAllTabbableIn(container, fallbackToFocusable),
first = _getAllTabbableIn[0];
return first || null;
}
/**
* Returns the last tabbable element in `container`, including the container
* itself if it's tabbable.
*
* @memberof tabbable
*
* @param {Element} container
* @param fallbackToFocusable If `true`, it'll return the last focusable element if there are no tabbable ones.
*
* @returns {Element|null}
*/
function getLastTabbableIn(container, fallbackToFocusable) {
var allTabbable = getAllTabbableIn(container, fallbackToFocusable);
return allTabbable[allTabbable.length - 1] || null;
}
/**
* Returns the next tabbable element in `container`.
*
* @memberof tabbable
*
* @param {Element} container
* @param fallbackToFocusable If `true`, it'll return the next focusable element if there are no tabbable ones.
*
* @returns {Element|null}
*/
function getNextTabbableIn(container, fallbackToFocusable) {
var activeElement = getActiveElement(container);
var allFocusable = getAllFocusableIn(container);
var index = allFocusable.indexOf(activeElement);
var slice = allFocusable.slice(index + 1);
return slice.find(isTabbable) || allFocusable.find(isTabbable) || (fallbackToFocusable ? slice[0] : null);
}
/**
* Returns the previous tabbable element in `container`.
*
* @memberof tabbable
*
* @param {Element} container
* @param fallbackToFocusable If `true`, it'll return the previous focusable element if there are no tabbable ones.
*
* @returns {Element|null}
*/
function getPreviousTabbableIn(container, fallbackToFocusable) {
var activeElement = getActiveElement(container);
var allFocusable = getAllFocusableIn(container).reverse();
var index = allFocusable.indexOf(activeElement);
var slice = allFocusable.slice(index + 1);
return slice.find(isTabbable) || allFocusable.find(isTabbable) || (fallbackToFocusable ? slice[0] : null);
}
/**
* Returns the closest focusable element.
*
* @memberof tabbable
*
* @param {Element} container
*
* @returns {Element|null}
*/
function getClosestFocusable(element) {
while (element && !isFocusable(element)) {
element = closest(element, selector);
}
return element;
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/Role/Role.js
// Automatically generated
var ROLE_KEYS = ["unstable_system"];
var useRole = createHook({
name: "Role",
keys: ROLE_KEYS,
propsAreEqual: function propsAreEqual(prev, next) {
var prevSystem = prev.unstable_system,
prevProps = _objectWithoutPropertiesLoose(prev, ["unstable_system"]);
var nextSystem = next.unstable_system,
nextProps = _objectWithoutPropertiesLoose(next, ["unstable_system"]);
if (prevSystem !== nextSystem && !shallowEqual(prevSystem, nextSystem)) {
return false;
}
return shallowEqual(prevProps, nextProps);
}
});
var Role = createComponent({
as: "div",
useHook: useRole
});
;// CONCATENATED MODULE: ./node_modules/reakit/es/Tabbable/Tabbable.js
// Automatically generated
var TABBABLE_KEYS = ["disabled", "focusable"];
var isSafariOrFirefoxOnMac = isUA("Mac") && !isUA("Chrome") && (isUA("Safari") || isUA("Firefox"));
function focusIfNeeded(element) {
if (!hasFocusWithin(element) && isFocusable(element)) {
element.focus();
}
}
function isNativeTabbable(element) {
return ["BUTTON", "INPUT", "SELECT", "TEXTAREA", "A"].includes(element.tagName);
}
function supportsDisabledAttribute(element) {
return ["BUTTON", "INPUT", "SELECT", "TEXTAREA"].includes(element.tagName);
}
function getTabIndex(trulyDisabled, nativeTabbable, supportsDisabled, htmlTabIndex) {
if (trulyDisabled) {
if (nativeTabbable && !supportsDisabled) {
// Anchor, audio and video tags don't support the `disabled` attribute.
// We must pass tabIndex={-1} so they don't receive focus on tab.
return -1;
} // Elements that support the `disabled` attribute don't need tabIndex.
return undefined;
}
if (nativeTabbable) {
// If the element is enabled and it's natively tabbable, we don't need to
// specify a tabIndex attribute unless it's explicitly set by the user.
return htmlTabIndex;
} // If the element is enabled and is not natively tabbable, we have to
// fallback tabIndex={0}.
return htmlTabIndex || 0;
}
function useDisableEvent(htmlEventRef, disabled) {
return (0,external_React_.useCallback)(function (event) {
var _htmlEventRef$current;
(_htmlEventRef$current = htmlEventRef.current) === null || _htmlEventRef$current === void 0 ? void 0 : _htmlEventRef$current.call(htmlEventRef, event);
if (event.defaultPrevented) return;
if (disabled) {
event.stopPropagation();
event.preventDefault();
}
}, [htmlEventRef, disabled]);
}
var useTabbable = createHook({
name: "Tabbable",
compose: useRole,
keys: TABBABLE_KEYS,
useOptions: function useOptions(options, _ref) {
var disabled = _ref.disabled;
return _objectSpread2({
disabled: disabled
}, options);
},
useProps: function useProps(options, _ref2) {
var htmlRef = _ref2.ref,
htmlTabIndex = _ref2.tabIndex,
htmlOnClickCapture = _ref2.onClickCapture,
htmlOnMouseDownCapture = _ref2.onMouseDownCapture,
htmlOnMouseDown = _ref2.onMouseDown,
htmlOnKeyPressCapture = _ref2.onKeyPressCapture,
htmlStyle = _ref2.style,
htmlProps = _objectWithoutPropertiesLoose(_ref2, ["ref", "tabIndex", "onClickCapture", "onMouseDownCapture", "onMouseDown", "onKeyPressCapture", "style"]);
var ref = (0,external_React_.useRef)(null);
var onClickCaptureRef = useLiveRef(htmlOnClickCapture);
var onMouseDownCaptureRef = useLiveRef(htmlOnMouseDownCapture);
var onMouseDownRef = useLiveRef(htmlOnMouseDown);
var onKeyPressCaptureRef = useLiveRef(htmlOnKeyPressCapture);
var trulyDisabled = !!options.disabled && !options.focusable;
var _React$useState = (0,external_React_.useState)(true),
nativeTabbable = _React$useState[0],
setNativeTabbable = _React$useState[1];
var _React$useState2 = (0,external_React_.useState)(true),
supportsDisabled = _React$useState2[0],
setSupportsDisabled = _React$useState2[1];
var style = options.disabled ? _objectSpread2({
pointerEvents: "none"
}, htmlStyle) : htmlStyle;
useIsomorphicEffect(function () {
var tabbable = ref.current;
if (!tabbable) {
false ? 0 : void 0;
return;
}
if (!isNativeTabbable(tabbable)) {
setNativeTabbable(false);
}
if (!supportsDisabledAttribute(tabbable)) {
setSupportsDisabled(false);
}
}, []);
var onClickCapture = useDisableEvent(onClickCaptureRef, options.disabled);
var onMouseDownCapture = useDisableEvent(onMouseDownCaptureRef, options.disabled);
var onKeyPressCapture = useDisableEvent(onKeyPressCaptureRef, options.disabled);
var onMouseDown = (0,external_React_.useCallback)(function (event) {
var _onMouseDownRef$curre;
(_onMouseDownRef$curre = onMouseDownRef.current) === null || _onMouseDownRef$curre === void 0 ? void 0 : _onMouseDownRef$curre.call(onMouseDownRef, event);
var element = event.currentTarget;
if (event.defaultPrevented) return; // Safari and Firefox on MacOS don't focus on buttons on mouse down
// like other browsers/platforms. Instead, they focus on the closest
// focusable ancestor element, which is ultimately the body element. So
// we make sure to give focus to the tabbable element on mouse down so
// it works consistently across browsers.
if (!isSafariOrFirefoxOnMac) return;
if (isPortalEvent(event)) return;
if (!isButton(element)) return; // We can't focus right away after on mouse down, otherwise it would
// prevent drag events from happening. So we schedule the focus to the
// next animation frame.
var raf = requestAnimationFrame(function () {
element.removeEventListener("mouseup", focusImmediately, true);
focusIfNeeded(element);
}); // If mouseUp happens before the next animation frame (which is common
// on touch screens or by just tapping the trackpad on MacBook's), we
// cancel the animation frame and immediately focus on the element.
var focusImmediately = function focusImmediately() {
cancelAnimationFrame(raf);
focusIfNeeded(element);
}; // By listening to the event in the capture phase, we make sure the
// focus event is fired before the onMouseUp and onMouseUpCapture React
// events, which is aligned with the default browser behavior.
element.addEventListener("mouseup", focusImmediately, {
once: true,
capture: true
});
}, []);
return _objectSpread2({
ref: useForkRef(ref, htmlRef),
style: style,
tabIndex: getTabIndex(trulyDisabled, nativeTabbable, supportsDisabled, htmlTabIndex),
disabled: trulyDisabled && supportsDisabled ? true : undefined,
"aria-disabled": options.disabled ? true : undefined,
onClickCapture: onClickCapture,
onMouseDownCapture: onMouseDownCapture,
onMouseDown: onMouseDown,
onKeyPressCapture: onKeyPressCapture
}, htmlProps);
}
});
var Tabbable = createComponent({
as: "div",
useHook: useTabbable
});
;// CONCATENATED MODULE: ./node_modules/reakit/es/Clickable/Clickable.js
// Automatically generated
var CLICKABLE_KEYS = ["unstable_clickOnEnter", "unstable_clickOnSpace"];
function isNativeClick(event) {
var element = event.currentTarget;
if (!event.isTrusted) return false; // istanbul ignore next: can't test trusted events yet
return isButton(element) || element.tagName === "INPUT" || element.tagName === "TEXTAREA" || element.tagName === "A" || element.tagName === "SELECT";
}
var useClickable = createHook({
name: "Clickable",
compose: useTabbable,
keys: CLICKABLE_KEYS,
useOptions: function useOptions(_ref) {
var _ref$unstable_clickOn = _ref.unstable_clickOnEnter,
unstable_clickOnEnter = _ref$unstable_clickOn === void 0 ? true : _ref$unstable_clickOn,
_ref$unstable_clickOn2 = _ref.unstable_clickOnSpace,
unstable_clickOnSpace = _ref$unstable_clickOn2 === void 0 ? true : _ref$unstable_clickOn2,
options = _objectWithoutPropertiesLoose(_ref, ["unstable_clickOnEnter", "unstable_clickOnSpace"]);
return _objectSpread2({
unstable_clickOnEnter: unstable_clickOnEnter,
unstable_clickOnSpace: unstable_clickOnSpace
}, options);
},
useProps: function useProps(options, _ref2) {
var htmlOnKeyDown = _ref2.onKeyDown,
htmlOnKeyUp = _ref2.onKeyUp,
htmlProps = _objectWithoutPropertiesLoose(_ref2, ["onKeyDown", "onKeyUp"]);
var _React$useState = (0,external_React_.useState)(false),
active = _React$useState[0],
setActive = _React$useState[1];
var onKeyDownRef = useLiveRef(htmlOnKeyDown);
var onKeyUpRef = useLiveRef(htmlOnKeyUp);
var onKeyDown = (0,external_React_.useCallback)(function (event) {
var _onKeyDownRef$current;
(_onKeyDownRef$current = onKeyDownRef.current) === null || _onKeyDownRef$current === void 0 ? void 0 : _onKeyDownRef$current.call(onKeyDownRef, event);
if (event.defaultPrevented) return;
if (options.disabled) return;
if (event.metaKey) return;
if (!isSelfTarget(event)) return;
var isEnter = options.unstable_clickOnEnter && event.key === "Enter";
var isSpace = options.unstable_clickOnSpace && event.key === " ";
if (isEnter || isSpace) {
if (isNativeClick(event)) return;
event.preventDefault();
if (isEnter) {
event.currentTarget.click();
} else if (isSpace) {
setActive(true);
}
}
}, [options.disabled, options.unstable_clickOnEnter, options.unstable_clickOnSpace]);
var onKeyUp = (0,external_React_.useCallback)(function (event) {
var _onKeyUpRef$current;
(_onKeyUpRef$current = onKeyUpRef.current) === null || _onKeyUpRef$current === void 0 ? void 0 : _onKeyUpRef$current.call(onKeyUpRef, event);
if (event.defaultPrevented) return;
if (options.disabled) return;
if (event.metaKey) return;
var isSpace = options.unstable_clickOnSpace && event.key === " ";
if (active && isSpace) {
setActive(false);
event.currentTarget.click();
}
}, [options.disabled, options.unstable_clickOnSpace, active]);
return _objectSpread2({
"data-active": active || undefined,
onKeyDown: onKeyDown,
onKeyUp: onKeyUp
}, htmlProps);
}
});
var Clickable = createComponent({
as: "button",
memo: true,
useHook: useClickable
});
;// CONCATENATED MODULE: ./node_modules/reakit/es/getCurrentId-5aa9849e.js
function findFirstEnabledItem(items, excludeId) {
if (excludeId) {
return items.find(function (item) {
return !item.disabled && item.id !== excludeId;
});
}
return items.find(function (item) {
return !item.disabled;
});
}
function getCurrentId(options, passedId) {
var _findFirstEnabledItem;
if (passedId || passedId === null) {
return passedId;
}
if (options.currentId || options.currentId === null) {
return options.currentId;
}
return (_findFirstEnabledItem = findFirstEnabledItem(options.items || [])) === null || _findFirstEnabledItem === void 0 ? void 0 : _findFirstEnabledItem.id;
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/__keys-6742f591.js
// Automatically generated
var COMPOSITE_STATE_KEYS = ["baseId", "unstable_idCountRef", "setBaseId", "unstable_virtual", "rtl", "orientation", "items", "groups", "currentId", "loop", "wrap", "shift", "unstable_moves", "unstable_hasActiveWidget", "unstable_includesBaseElement", "registerItem", "unregisterItem", "registerGroup", "unregisterGroup", "move", "next", "previous", "up", "down", "first", "last", "sort", "unstable_setVirtual", "setRTL", "setOrientation", "setCurrentId", "setLoop", "setWrap", "setShift", "reset", "unstable_setIncludesBaseElement", "unstable_setHasActiveWidget"];
var COMPOSITE_KEYS = COMPOSITE_STATE_KEYS;
var COMPOSITE_GROUP_KEYS = COMPOSITE_KEYS;
var COMPOSITE_ITEM_KEYS = COMPOSITE_GROUP_KEYS;
var COMPOSITE_ITEM_WIDGET_KEYS = (/* unused pure expression or super */ null && (COMPOSITE_ITEM_KEYS));
;// CONCATENATED MODULE: ./node_modules/reakit/es/userFocus-e16425e3.js
function userFocus(element) {
element.userFocus = true;
element.focus();
element.userFocus = false;
}
function hasUserFocus(element) {
return !!element.userFocus;
}
function setUserFocus(element, value) {
element.userFocus = value;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/isTextField.js
/**
* Check whether the given element is a text field, where text field is defined
* by the ability to select within the input, or that it is contenteditable.
*
* @example
* import { isTextField } from "reakit-utils";
*
* isTextField(document.querySelector("div")); // false
* isTextField(document.querySelector("input")); // true
* isTextField(document.querySelector("input[type='button']")); // false
* isTextField(document.querySelector("textarea")); // true
* isTextField(document.querySelector("div[contenteditable='true']")); // true
*/
function isTextField(element) {
try {
var isTextInput = element instanceof HTMLInputElement && element.selectionStart !== null;
var isTextArea = element.tagName === "TEXTAREA";
var isContentEditable = element.contentEditable === "true";
return isTextInput || isTextArea || isContentEditable || false;
} catch (error) {
// Safari throws an exception when trying to get `selectionStart`
// on non-text <input> elements (which, understandably, don't
// have the text selection API). We catch this via a try/catch
// block, as opposed to a more explicit check of the element's
// input types, because of Safari's non-standard behavior. This
// also means we don't have to worry about the list of input
// types that support `selectionStart` changing as the HTML spec
// evolves over time.
return false;
}
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/hasFocus.js
/**
* Checks if `element` has focus. Elements that are referenced by
* `aria-activedescendant` are also considered.
*
* @example
* import { hasFocus } from "reakit-utils";
*
* hasFocus(document.getElementById("id"));
*/
function hasFocus(element) {
var activeElement = getActiveElement_getActiveElement(element);
if (!activeElement) return false;
if (activeElement === element) return true;
var activeDescendant = activeElement.getAttribute("aria-activedescendant");
if (!activeDescendant) return false;
return activeDescendant === element.id;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/ensureFocus.js
/**
* Ensures `element` will receive focus if it's not already.
*
* @example
* import { ensureFocus } from "reakit-utils";
*
* ensureFocus(document.activeElement); // does nothing
*
* const element = document.querySelector("input");
*
* ensureFocus(element); // focuses element
* ensureFocus(element, { preventScroll: true }); // focuses element preventing scroll jump
*
* function isActive(el) {
* return el.dataset.active === "true";
* }
*
* ensureFocus(document.querySelector("[data-active='true']"), { isActive }); // does nothing
*
* @returns {number} `requestAnimationFrame` call ID so it can be passed to `cancelAnimationFrame` if needed.
*/
function ensureFocus(element, _temp) {
var _ref = _temp === void 0 ? {} : _temp,
preventScroll = _ref.preventScroll,
_ref$isActive = _ref.isActive,
isActive = _ref$isActive === void 0 ? hasFocus : _ref$isActive;
if (isActive(element)) return -1;
element.focus({
preventScroll: preventScroll
});
if (isActive(element)) return -1;
return requestAnimationFrame(function () {
element.focus({
preventScroll: preventScroll
});
});
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/Id/IdProvider.js
var defaultPrefix = "id";
function generateRandomString(prefix) {
if (prefix === void 0) {
prefix = defaultPrefix;
}
return "" + (prefix ? prefix + "-" : "") + Math.random().toString(32).substr(2, 6);
}
var unstable_IdContext = /*#__PURE__*/(0,external_React_.createContext)(generateRandomString);
function unstable_IdProvider(_ref) {
var children = _ref.children,
_ref$prefix = _ref.prefix,
prefix = _ref$prefix === void 0 ? defaultPrefix : _ref$prefix;
var count = useRef(0);
var generateId = useCallback(function (localPrefix) {
if (localPrefix === void 0) {
localPrefix = prefix;
}
return "" + (localPrefix ? localPrefix + "-" : "") + ++count.current;
}, [prefix]);
return /*#__PURE__*/createElement(unstable_IdContext.Provider, {
value: generateId
}, children);
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/Id/Id.js
// Automatically generated
var ID_STATE_KEYS = ["baseId", "unstable_idCountRef", "setBaseId"];
var ID_KEYS = [].concat(ID_STATE_KEYS, ["id"]);
var unstable_useId = createHook({
keys: ID_KEYS,
useOptions: function useOptions(options, htmlProps) {
var generateId = (0,external_React_.useContext)(unstable_IdContext);
var _React$useState = (0,external_React_.useState)(function () {
// This comes from useIdState
if (options.unstable_idCountRef) {
options.unstable_idCountRef.current += 1;
return "-" + options.unstable_idCountRef.current;
} // If there's no useIdState, we check if `baseId` was passed (as a prop,
// not from useIdState).
if (options.baseId) {
return "-" + generateId("");
}
return "";
}),
suffix = _React$useState[0]; // `baseId` will be the prop passed directly as a prop or via useIdState.
// If there's neither, then it'll fallback to Context's generateId.
// This generateId can result in a sequential ID (if there's a Provider)
// or a random string (without Provider).
var baseId = (0,external_React_.useMemo)(function () {
return options.baseId || generateId();
}, [options.baseId, generateId]);
var id = htmlProps.id || options.id || "" + baseId + suffix;
return _objectSpread2(_objectSpread2({}, options), {}, {
id: id
});
},
useProps: function useProps(options, htmlProps) {
return _objectSpread2({
id: options.id
}, htmlProps);
}
});
var unstable_Id = createComponent({
as: "div",
useHook: unstable_useId
});
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/createEvent.js
/**
* Creates an `Event` in a way that also works on IE 11.
*
* @example
* import { createEvent } from "reakit-utils";
*
* const el = document.getElementById("id");
* el.dispatchEvent(createEvent(el, "blur", { bubbles: false }));
*/
function createEvent(element, type, eventInit) {
if (typeof Event === "function") {
return new Event(type, eventInit);
} // IE 11 doesn't support Event constructors
var event = getDocument(element).createEvent("Event");
event.initEvent(type, eventInit === null || eventInit === void 0 ? void 0 : eventInit.bubbles, eventInit === null || eventInit === void 0 ? void 0 : eventInit.cancelable);
return event;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/fireEvent.js
/**
* Creates and dispatches `Event` in a way that also works on IE 11.
*
* @example
* import { fireEvent } from "reakit-utils";
*
* fireEvent(document.getElementById("id"), "blur", {
* bubbles: true,
* cancelable: true,
* });
*/
function fireEvent(element, type, eventInit) {
return element.dispatchEvent(createEvent(element, type, eventInit));
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/setTextFieldValue-0a221f4e.js
function setTextFieldValue(element, value) {
if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {
var _Object$getOwnPropert;
var proto = Object.getPrototypeOf(element);
var setValue = (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(proto, "value")) === null || _Object$getOwnPropert === void 0 ? void 0 : _Object$getOwnPropert.set;
if (setValue) {
setValue.call(element, value);
fireEvent(element, "input", {
bubbles: true
});
}
}
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/Composite/CompositeItem.js
function getWidget(itemElement) {
return itemElement.querySelector("[data-composite-item-widget]");
}
function useItem(options) {
return (0,external_React_.useMemo)(function () {
var _options$items;
return (_options$items = options.items) === null || _options$items === void 0 ? void 0 : _options$items.find(function (item) {
return options.id && item.id === options.id;
});
}, [options.items, options.id]);
}
function targetIsAnotherItem(event, items) {
if (isSelfTarget(event)) return false;
for (var _iterator = _createForOfIteratorHelperLoose(items), _step; !(_step = _iterator()).done;) {
var item = _step.value;
if (item.ref.current === event.target) {
return true;
}
}
return false;
}
var useCompositeItem = createHook({
name: "CompositeItem",
compose: [useClickable, unstable_useId],
keys: COMPOSITE_ITEM_KEYS,
propsAreEqual: function propsAreEqual(prev, next) {
if (!next.id || prev.id !== next.id) {
return useClickable.unstable_propsAreEqual(prev, next);
}
var prevCurrentId = prev.currentId,
prevMoves = prev.unstable_moves,
prevProps = _objectWithoutPropertiesLoose(prev, ["currentId", "unstable_moves"]);
var nextCurrentId = next.currentId,
nextMoves = next.unstable_moves,
nextProps = _objectWithoutPropertiesLoose(next, ["currentId", "unstable_moves"]);
if (nextCurrentId !== prevCurrentId) {
if (next.id === nextCurrentId || next.id === prevCurrentId) {
return false;
}
} else if (prevMoves !== nextMoves) {
return false;
}
return useClickable.unstable_propsAreEqual(prevProps, nextProps);
},
useOptions: function useOptions(options) {
return _objectSpread2(_objectSpread2({}, options), {}, {
id: options.id,
currentId: getCurrentId(options),
unstable_clickOnSpace: options.unstable_hasActiveWidget ? false : options.unstable_clickOnSpace
});
},
useProps: function useProps(options, _ref) {
var _options$items2;
var htmlRef = _ref.ref,
_ref$tabIndex = _ref.tabIndex,
htmlTabIndex = _ref$tabIndex === void 0 ? 0 : _ref$tabIndex,
htmlOnMouseDown = _ref.onMouseDown,
htmlOnFocus = _ref.onFocus,
htmlOnBlurCapture = _ref.onBlurCapture,
htmlOnKeyDown = _ref.onKeyDown,
htmlOnClick = _ref.onClick,
htmlProps = _objectWithoutPropertiesLoose(_ref, ["ref", "tabIndex", "onMouseDown", "onFocus", "onBlurCapture", "onKeyDown", "onClick"]);
var ref = (0,external_React_.useRef)(null);
var id = options.id;
var trulyDisabled = options.disabled && !options.focusable;
var isCurrentItem = options.currentId === id;
var isCurrentItemRef = useLiveRef(isCurrentItem);
var hasFocusedComposite = (0,external_React_.useRef)(false);
var item = useItem(options);
var onMouseDownRef = useLiveRef(htmlOnMouseDown);
var onFocusRef = useLiveRef(htmlOnFocus);
var onBlurCaptureRef = useLiveRef(htmlOnBlurCapture);
var onKeyDownRef = useLiveRef(htmlOnKeyDown);
var onClickRef = useLiveRef(htmlOnClick);
var shouldTabIndex = !options.unstable_virtual && !options.unstable_hasActiveWidget && isCurrentItem || // We don't want to set tabIndex="-1" when using CompositeItem as a
// standalone component, without state props.
!((_options$items2 = options.items) !== null && _options$items2 !== void 0 && _options$items2.length);
(0,external_React_.useEffect)(function () {
var _options$registerItem;
if (!id) return undefined;
(_options$registerItem = options.registerItem) === null || _options$registerItem === void 0 ? void 0 : _options$registerItem.call(options, {
id: id,
ref: ref,
disabled: !!trulyDisabled
});
return function () {
var _options$unregisterIt;
(_options$unregisterIt = options.unregisterItem) === null || _options$unregisterIt === void 0 ? void 0 : _options$unregisterIt.call(options, id);
};
}, [id, trulyDisabled, options.registerItem, options.unregisterItem]);
(0,external_React_.useEffect)(function () {
var element = ref.current;
if (!element) {
false ? 0 : void 0;
return;
} // `moves` will be incremented whenever next, previous, up, down, first,
// last or move have been called. This means that the composite item will
// be focused whenever some of these functions are called. We're using
// isCurrentItemRef instead of isCurrentItem because we don't want to
// focus the item if isCurrentItem changes (and options.moves doesn't).
if (options.unstable_moves && isCurrentItemRef.current) {
userFocus(element);
}
}, [options.unstable_moves]);
var onMouseDown = (0,external_React_.useCallback)(function (event) {
var _onMouseDownRef$curre;
(_onMouseDownRef$curre = onMouseDownRef.current) === null || _onMouseDownRef$curre === void 0 ? void 0 : _onMouseDownRef$curre.call(onMouseDownRef, event);
setUserFocus(event.currentTarget, true);
}, []);
var onFocus = (0,external_React_.useCallback)(function (event) {
var _onFocusRef$current, _options$setCurrentId;
var shouldFocusComposite = hasUserFocus(event.currentTarget);
setUserFocus(event.currentTarget, false);
(_onFocusRef$current = onFocusRef.current) === null || _onFocusRef$current === void 0 ? void 0 : _onFocusRef$current.call(onFocusRef, event);
if (event.defaultPrevented) return;
if (isPortalEvent(event)) return;
if (!id) return;
if (targetIsAnotherItem(event, options.items)) return;
(_options$setCurrentId = options.setCurrentId) === null || _options$setCurrentId === void 0 ? void 0 : _options$setCurrentId.call(options, id); // When using aria-activedescendant, we want to make sure that the
// composite container receives focus, not the composite item.
// But we don't want to do this if the target is another focusable
// element inside the composite item, such as CompositeItemWidget.
if (shouldFocusComposite && options.unstable_virtual && options.baseId && isSelfTarget(event)) {
var target = event.target;
var composite = getDocument(target).getElementById(options.baseId);
if (composite) {
hasFocusedComposite.current = true;
ensureFocus(composite);
}
}
}, [id, options.items, options.setCurrentId, options.unstable_virtual, options.baseId]);
var onBlurCapture = (0,external_React_.useCallback)(function (event) {
var _onBlurCaptureRef$cur;
(_onBlurCaptureRef$cur = onBlurCaptureRef.current) === null || _onBlurCaptureRef$cur === void 0 ? void 0 : _onBlurCaptureRef$cur.call(onBlurCaptureRef, event);
if (event.defaultPrevented) return;
if (options.unstable_virtual && hasFocusedComposite.current) {
// When hasFocusedComposite is true, composite has been focused right
// after focusing this item. This is an intermediate blur event, so
// we ignore it.
hasFocusedComposite.current = false;
event.preventDefault();
event.stopPropagation();
}
}, [options.unstable_virtual]);
var onKeyDown = (0,external_React_.useCallback)(function (event) {
var _onKeyDownRef$current;
if (!isSelfTarget(event)) return;
var isVertical = options.orientation !== "horizontal";
var isHorizontal = options.orientation !== "vertical";
var isGrid = !!(item !== null && item !== void 0 && item.groupId);
var keyMap = {
ArrowUp: (isGrid || isVertical) && options.up,
ArrowRight: (isGrid || isHorizontal) && options.next,
ArrowDown: (isGrid || isVertical) && options.down,
ArrowLeft: (isGrid || isHorizontal) && options.previous,
Home: function Home() {
if (!isGrid || event.ctrlKey) {
var _options$first;
(_options$first = options.first) === null || _options$first === void 0 ? void 0 : _options$first.call(options);
} else {
var _options$previous;
(_options$previous = options.previous) === null || _options$previous === void 0 ? void 0 : _options$previous.call(options, true);
}
},
End: function End() {
if (!isGrid || event.ctrlKey) {
var _options$last;
(_options$last = options.last) === null || _options$last === void 0 ? void 0 : _options$last.call(options);
} else {
var _options$next;
(_options$next = options.next) === null || _options$next === void 0 ? void 0 : _options$next.call(options, true);
}
},
PageUp: function PageUp() {
if (isGrid) {
var _options$up;
(_options$up = options.up) === null || _options$up === void 0 ? void 0 : _options$up.call(options, true);
} else {
var _options$first2;
(_options$first2 = options.first) === null || _options$first2 === void 0 ? void 0 : _options$first2.call(options);
}
},
PageDown: function PageDown() {
if (isGrid) {
var _options$down;
(_options$down = options.down) === null || _options$down === void 0 ? void 0 : _options$down.call(options, true);
} else {
var _options$last2;
(_options$last2 = options.last) === null || _options$last2 === void 0 ? void 0 : _options$last2.call(options);
}
}
};
var action = keyMap[event.key];
if (action) {
event.preventDefault();
action();
return;
}
(_onKeyDownRef$current = onKeyDownRef.current) === null || _onKeyDownRef$current === void 0 ? void 0 : _onKeyDownRef$current.call(onKeyDownRef, event);
if (event.defaultPrevented) return;
if (event.key.length === 1 && event.key !== " ") {
var widget = getWidget(event.currentTarget);
if (widget && isTextField(widget)) {
widget.focus();
setTextFieldValue(widget, "");
}
} else if (event.key === "Delete" || event.key === "Backspace") {
var _widget = getWidget(event.currentTarget);
if (_widget && isTextField(_widget)) {
event.preventDefault();
setTextFieldValue(_widget, "");
}
}
}, [options.orientation, item, options.up, options.next, options.down, options.previous, options.first, options.last]);
var onClick = (0,external_React_.useCallback)(function (event) {
var _onClickRef$current;
(_onClickRef$current = onClickRef.current) === null || _onClickRef$current === void 0 ? void 0 : _onClickRef$current.call(onClickRef, event);
if (event.defaultPrevented) return;
var element = event.currentTarget;
var widget = getWidget(element);
if (widget && !hasFocusWithin(widget)) {
// If there's a widget inside the composite item, we make sure it's
// focused when pressing enter, space or clicking on the composite item.
widget.focus();
}
}, []);
return _objectSpread2({
ref: useForkRef(ref, htmlRef),
id: id,
tabIndex: shouldTabIndex ? htmlTabIndex : -1,
"aria-selected": options.unstable_virtual && isCurrentItem ? true : undefined,
onMouseDown: onMouseDown,
onFocus: onFocus,
onBlurCapture: onBlurCapture,
onKeyDown: onKeyDown,
onClick: onClick
}, htmlProps);
}
});
var CompositeItem = createComponent({
as: "button",
memo: true,
useHook: useCompositeItem
});
;// CONCATENATED MODULE: ./node_modules/@floating-ui/utils/dist/floating-ui.utils.mjs
/**
* Custom positioning reference element.
* @see https://floating-ui.com/docs/virtual-elements
*/
const floating_ui_utils_sides = (/* unused pure expression or super */ null && (['top', 'right', 'bottom', 'left']));
const alignments = (/* unused pure expression or super */ null && (['start', 'end']));
const floating_ui_utils_placements = /*#__PURE__*/(/* unused pure expression or super */ null && (floating_ui_utils_sides.reduce((acc, side) => acc.concat(side, side + "-" + alignments[0], side + "-" + alignments[1]), [])));
const floating_ui_utils_min = Math.min;
const floating_ui_utils_max = Math.max;
const round = Math.round;
const floor = Math.floor;
const createCoords = v => ({
x: v,
y: v
});
const oppositeSideMap = {
left: 'right',
right: 'left',
bottom: 'top',
top: 'bottom'
};
const oppositeAlignmentMap = {
start: 'end',
end: 'start'
};
function clamp(start, value, end) {
return floating_ui_utils_max(start, floating_ui_utils_min(value, end));
}
function floating_ui_utils_evaluate(value, param) {
return typeof value === 'function' ? value(param) : value;
}
function floating_ui_utils_getSide(placement) {
return placement.split('-')[0];
}
function floating_ui_utils_getAlignment(placement) {
return placement.split('-')[1];
}
function floating_ui_utils_getOppositeAxis(axis) {
return axis === 'x' ? 'y' : 'x';
}
function getAxisLength(axis) {
return axis === 'y' ? 'height' : 'width';
}
function floating_ui_utils_getSideAxis(placement) {
return ['top', 'bottom'].includes(floating_ui_utils_getSide(placement)) ? 'y' : 'x';
}
function getAlignmentAxis(placement) {
return floating_ui_utils_getOppositeAxis(floating_ui_utils_getSideAxis(placement));
}
function floating_ui_utils_getAlignmentSides(placement, rects, rtl) {
if (rtl === void 0) {
rtl = false;
}
const alignment = floating_ui_utils_getAlignment(placement);
const alignmentAxis = getAlignmentAxis(placement);
const length = getAxisLength(alignmentAxis);
let mainAlignmentSide = alignmentAxis === 'x' ? alignment === (rtl ? 'end' : 'start') ? 'right' : 'left' : alignment === 'start' ? 'bottom' : 'top';
if (rects.reference[length] > rects.floating[length]) {
mainAlignmentSide = getOppositePlacement(mainAlignmentSide);
}
return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)];
}
function getExpandedPlacements(placement) {
const oppositePlacement = getOppositePlacement(placement);
return [floating_ui_utils_getOppositeAlignmentPlacement(placement), oppositePlacement, floating_ui_utils_getOppositeAlignmentPlacement(oppositePlacement)];
}
function floating_ui_utils_getOppositeAlignmentPlacement(placement) {
return placement.replace(/start|end/g, alignment => oppositeAlignmentMap[alignment]);
}
function getSideList(side, isStart, rtl) {
const lr = ['left', 'right'];
const rl = ['right', 'left'];
const tb = ['top', 'bottom'];
const bt = ['bottom', 'top'];
switch (side) {
case 'top':
case 'bottom':
if (rtl) return isStart ? rl : lr;
return isStart ? lr : rl;
case 'left':
case 'right':
return isStart ? tb : bt;
default:
return [];
}
}
function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) {
const alignment = floating_ui_utils_getAlignment(placement);
let list = getSideList(floating_ui_utils_getSide(placement), direction === 'start', rtl);
if (alignment) {
list = list.map(side => side + "-" + alignment);
if (flipAlignment) {
list = list.concat(list.map(floating_ui_utils_getOppositeAlignmentPlacement));
}
}
return list;
}
function getOppositePlacement(placement) {
return placement.replace(/left|right|bottom|top/g, side => oppositeSideMap[side]);
}
function expandPaddingObject(padding) {
return {
top: 0,
right: 0,
bottom: 0,
left: 0,
...padding
};
}
function floating_ui_utils_getPaddingObject(padding) {
return typeof padding !== 'number' ? expandPaddingObject(padding) : {
top: padding,
right: padding,
bottom: padding,
left: padding
};
}
function floating_ui_utils_rectToClientRect(rect) {
const {
x,
y,
width,
height
} = rect;
return {
width,
height,
top: y,
left: x,
right: x + width,
bottom: y + height,
x,
y
};
}
;// CONCATENATED MODULE: ./node_modules/@floating-ui/core/dist/floating-ui.core.mjs
function computeCoordsFromPlacement(_ref, placement, rtl) {
let {
reference,
floating
} = _ref;
const sideAxis = floating_ui_utils_getSideAxis(placement);
const alignmentAxis = getAlignmentAxis(placement);
const alignLength = getAxisLength(alignmentAxis);
const side = floating_ui_utils_getSide(placement);
const isVertical = sideAxis === 'y';
const commonX = reference.x + reference.width / 2 - floating.width / 2;
const commonY = reference.y + reference.height / 2 - floating.height / 2;
const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2;
let coords;
switch (side) {
case 'top':
coords = {
x: commonX,
y: reference.y - floating.height
};
break;
case 'bottom':
coords = {
x: commonX,
y: reference.y + reference.height
};
break;
case 'right':
coords = {
x: reference.x + reference.width,
y: commonY
};
break;
case 'left':
coords = {
x: reference.x - floating.width,
y: commonY
};
break;
default:
coords = {
x: reference.x,
y: reference.y
};
}
switch (floating_ui_utils_getAlignment(placement)) {
case 'start':
coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1);
break;
case 'end':
coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1);
break;
}
return coords;
}
/**
* Computes the `x` and `y` coordinates that will place the floating element
* next to a given reference element.
*
* This export does not have any `platform` interface logic. You will need to
* write one for the platform you are using Floating UI with.
*/
const computePosition = async (reference, floating, config) => {
const {
placement = 'bottom',
strategy = 'absolute',
middleware = [],
platform
} = config;
const validMiddleware = middleware.filter(Boolean);
const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating));
let rects = await platform.getElementRects({
reference,
floating,
strategy
});
let {
x,
y
} = computeCoordsFromPlacement(rects, placement, rtl);
let statefulPlacement = placement;
let middlewareData = {};
let resetCount = 0;
for (let i = 0; i < validMiddleware.length; i++) {
const {
name,
fn
} = validMiddleware[i];
const {
x: nextX,
y: nextY,
data,
reset
} = await fn({
x,
y,
initialPlacement: placement,
placement: statefulPlacement,
strategy,
middlewareData,
rects,
platform,
elements: {
reference,
floating
}
});
x = nextX != null ? nextX : x;
y = nextY != null ? nextY : y;
middlewareData = {
...middlewareData,
[name]: {
...middlewareData[name],
...data
}
};
if (reset && resetCount <= 50) {
resetCount++;
if (typeof reset === 'object') {
if (reset.placement) {
statefulPlacement = reset.placement;
}
if (reset.rects) {
rects = reset.rects === true ? await platform.getElementRects({
reference,
floating,
strategy
}) : reset.rects;
}
({
x,
y
} = computeCoordsFromPlacement(rects, statefulPlacement, rtl));
}
i = -1;
}
}
return {
x,
y,
placement: statefulPlacement,
strategy,
middlewareData
};
};
/**
* Resolves with an object of overflow side offsets that determine how much the
* element is overflowing a given clipping boundary on each side.
* - positive = overflowing the boundary by that number of pixels
* - negative = how many pixels left before it will overflow
* - 0 = lies flush with the boundary
* @see https://floating-ui.com/docs/detectOverflow
*/
async function detectOverflow(state, options) {
var _await$platform$isEle;
if (options === void 0) {
options = {};
}
const {
x,
y,
platform,
rects,
elements,
strategy
} = state;
const {
boundary = 'clippingAncestors',
rootBoundary = 'viewport',
elementContext = 'floating',
altBoundary = false,
padding = 0
} = floating_ui_utils_evaluate(options, state);
const paddingObject = floating_ui_utils_getPaddingObject(padding);
const altContext = elementContext === 'floating' ? 'reference' : 'floating';
const element = elements[altBoundary ? altContext : elementContext];
const clippingClientRect = floating_ui_utils_rectToClientRect(await platform.getClippingRect({
element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || (await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating))),
boundary,
rootBoundary,
strategy
}));
const rect = elementContext === 'floating' ? {
x,
y,
width: rects.floating.width,
height: rects.floating.height
} : rects.reference;
const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating));
const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || {
x: 1,
y: 1
} : {
x: 1,
y: 1
};
const elementClientRect = floating_ui_utils_rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({
elements,
rect,
offsetParent,
strategy
}) : rect);
return {
top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y,
bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y,
left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x,
right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x
};
}
/**
* Provides data to position an inner element of the floating element so that it
* appears centered to the reference element.
* @see https://floating-ui.com/docs/arrow
*/
const arrow = options => ({
name: 'arrow',
options,
async fn(state) {
const {
x,
y,
placement,
rects,
platform,
elements,
middlewareData
} = state;
// Since `element` is required, we don't Partial<> the type.
const {
element,
padding = 0
} = floating_ui_utils_evaluate(options, state) || {};
if (element == null) {
return {};
}
const paddingObject = floating_ui_utils_getPaddingObject(padding);
const coords = {
x,
y
};
const axis = getAlignmentAxis(placement);
const length = getAxisLength(axis);
const arrowDimensions = await platform.getDimensions(element);
const isYAxis = axis === 'y';
const minProp = isYAxis ? 'top' : 'left';
const maxProp = isYAxis ? 'bottom' : 'right';
const clientProp = isYAxis ? 'clientHeight' : 'clientWidth';
const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length];
const startDiff = coords[axis] - rects.reference[axis];
const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element));
let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0;
// DOM platform can return `window` as the `offsetParent`.
if (!clientSize || !(await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent)))) {
clientSize = elements.floating[clientProp] || rects.floating[length];
}
const centerToReference = endDiff / 2 - startDiff / 2;
// If the padding is large enough that it causes the arrow to no longer be
// centered, modify the padding so that it is centered.
const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1;
const minPadding = floating_ui_utils_min(paddingObject[minProp], largestPossiblePadding);
const maxPadding = floating_ui_utils_min(paddingObject[maxProp], largestPossiblePadding);
// Make sure the arrow doesn't overflow the floating element if the center
// point is outside the floating element's bounds.
const min$1 = minPadding;
const max = clientSize - arrowDimensions[length] - maxPadding;
const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference;
const offset = clamp(min$1, center, max);
// If the reference is small enough that the arrow's padding causes it to
// to point to nothing for an aligned placement, adjust the offset of the
// floating element itself. To ensure `shift()` continues to take action,
// a single reset is performed when this is true.
const shouldAddOffset = !middlewareData.arrow && floating_ui_utils_getAlignment(placement) != null && center !== offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0;
const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max : 0;
return {
[axis]: coords[axis] + alignmentOffset,
data: {
[axis]: offset,
centerOffset: center - offset - alignmentOffset,
...(shouldAddOffset && {
alignmentOffset
})
},
reset: shouldAddOffset
};
}
});
function getPlacementList(alignment, autoAlignment, allowedPlacements) {
const allowedPlacementsSortedByAlignment = alignment ? [...allowedPlacements.filter(placement => getAlignment(placement) === alignment), ...allowedPlacements.filter(placement => getAlignment(placement) !== alignment)] : allowedPlacements.filter(placement => getSide(placement) === placement);
return allowedPlacementsSortedByAlignment.filter(placement => {
if (alignment) {
return getAlignment(placement) === alignment || (autoAlignment ? getOppositeAlignmentPlacement(placement) !== placement : false);
}
return true;
});
}
/**
* Optimizes the visibility of the floating element by choosing the placement
* that has the most space available automatically, without needing to specify a
* preferred placement. Alternative to `flip`.
* @see https://floating-ui.com/docs/autoPlacement
*/
const autoPlacement = function (options) {
if (options === void 0) {
options = {};
}
return {
name: 'autoPlacement',
options,
async fn(state) {
var _middlewareData$autoP, _middlewareData$autoP2, _placementsThatFitOnE;
const {
rects,
middlewareData,
placement,
platform,
elements
} = state;
const {
crossAxis = false,
alignment,
allowedPlacements = placements,
autoAlignment = true,
...detectOverflowOptions
} = evaluate(options, state);
const placements$1 = alignment !== undefined || allowedPlacements === placements ? getPlacementList(alignment || null, autoAlignment, allowedPlacements) : allowedPlacements;
const overflow = await detectOverflow(state, detectOverflowOptions);
const currentIndex = ((_middlewareData$autoP = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP.index) || 0;
const currentPlacement = placements$1[currentIndex];
if (currentPlacement == null) {
return {};
}
const alignmentSides = getAlignmentSides(currentPlacement, rects, await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)));
// Make `computeCoords` start from the right place.
if (placement !== currentPlacement) {
return {
reset: {
placement: placements$1[0]
}
};
}
const currentOverflows = [overflow[getSide(currentPlacement)], overflow[alignmentSides[0]], overflow[alignmentSides[1]]];
const allOverflows = [...(((_middlewareData$autoP2 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP2.overflows) || []), {
placement: currentPlacement,
overflows: currentOverflows
}];
const nextPlacement = placements$1[currentIndex + 1];
// There are more placements to check.
if (nextPlacement) {
return {
data: {
index: currentIndex + 1,
overflows: allOverflows
},
reset: {
placement: nextPlacement
}
};
}
const placementsSortedByMostSpace = allOverflows.map(d => {
const alignment = getAlignment(d.placement);
return [d.placement, alignment && crossAxis ?
// Check along the mainAxis and main crossAxis side.
d.overflows.slice(0, 2).reduce((acc, v) => acc + v, 0) :
// Check only the mainAxis.
d.overflows[0], d.overflows];
}).sort((a, b) => a[1] - b[1]);
const placementsThatFitOnEachSide = placementsSortedByMostSpace.filter(d => d[2].slice(0,
// Aligned placements should not check their opposite crossAxis
// side.
getAlignment(d[0]) ? 2 : 3).every(v => v <= 0));
const resetPlacement = ((_placementsThatFitOnE = placementsThatFitOnEachSide[0]) == null ? void 0 : _placementsThatFitOnE[0]) || placementsSortedByMostSpace[0][0];
if (resetPlacement !== placement) {
return {
data: {
index: currentIndex + 1,
overflows: allOverflows
},
reset: {
placement: resetPlacement
}
};
}
return {};
}
};
};
/**
* Optimizes the visibility of the floating element by flipping the `placement`
* in order to keep it in view when the preferred placement(s) will overflow the
* clipping boundary. Alternative to `autoPlacement`.
* @see https://floating-ui.com/docs/flip
*/
const flip = function (options) {
if (options === void 0) {
options = {};
}
return {
name: 'flip',
options,
async fn(state) {
var _middlewareData$arrow, _middlewareData$flip;
const {
placement,
middlewareData,
rects,
initialPlacement,
platform,
elements
} = state;
const {
mainAxis: checkMainAxis = true,
crossAxis: checkCrossAxis = true,
fallbackPlacements: specifiedFallbackPlacements,
fallbackStrategy = 'bestFit',
fallbackAxisSideDirection = 'none',
flipAlignment = true,
...detectOverflowOptions
} = floating_ui_utils_evaluate(options, state);
// If a reset by the arrow was caused due to an alignment offset being
// added, we should skip any logic now since `flip()` has already done its
// work.
// https://github.com/floating-ui/floating-ui/issues/2549#issuecomment-1719601643
if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
return {};
}
const side = floating_ui_utils_getSide(placement);
const isBasePlacement = floating_ui_utils_getSide(initialPlacement) === initialPlacement;
const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));
const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement));
if (!specifiedFallbackPlacements && fallbackAxisSideDirection !== 'none') {
fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl));
}
const placements = [initialPlacement, ...fallbackPlacements];
const overflow = await detectOverflow(state, detectOverflowOptions);
const overflows = [];
let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [];
if (checkMainAxis) {
overflows.push(overflow[side]);
}
if (checkCrossAxis) {
const sides = floating_ui_utils_getAlignmentSides(placement, rects, rtl);
overflows.push(overflow[sides[0]], overflow[sides[1]]);
}
overflowsData = [...overflowsData, {
placement,
overflows
}];
// One or more sides is overflowing.
if (!overflows.every(side => side <= 0)) {
var _middlewareData$flip2, _overflowsData$filter;
const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1;
const nextPlacement = placements[nextIndex];
if (nextPlacement) {
// Try next placement and re-run the lifecycle.
return {
data: {
index: nextIndex,
overflows: overflowsData
},
reset: {
placement: nextPlacement
}
};
}
// First, find the candidates that fit on the mainAxis side of overflow,
// then find the placement that fits the best on the main crossAxis side.
let resetPlacement = (_overflowsData$filter = overflowsData.filter(d => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement;
// Otherwise fallback.
if (!resetPlacement) {
switch (fallbackStrategy) {
case 'bestFit':
{
var _overflowsData$map$so;
const placement = (_overflowsData$map$so = overflowsData.map(d => [d.placement, d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$map$so[0];
if (placement) {
resetPlacement = placement;
}
break;
}
case 'initialPlacement':
resetPlacement = initialPlacement;
break;
}
}
if (placement !== resetPlacement) {
return {
reset: {
placement: resetPlacement
}
};
}
}
return {};
}
};
};
function getSideOffsets(overflow, rect) {
return {
top: overflow.top - rect.height,
right: overflow.right - rect.width,
bottom: overflow.bottom - rect.height,
left: overflow.left - rect.width
};
}
function isAnySideFullyClipped(overflow) {
return sides.some(side => overflow[side] >= 0);
}
/**
* Provides data to hide the floating element in applicable situations, such as
* when it is not in the same clipping context as the reference element.
* @see https://floating-ui.com/docs/hide
*/
const hide = function (options) {
if (options === void 0) {
options = {};
}
return {
name: 'hide',
options,
async fn(state) {
const {
rects
} = state;
const {
strategy = 'referenceHidden',
...detectOverflowOptions
} = evaluate(options, state);
switch (strategy) {
case 'referenceHidden':
{
const overflow = await detectOverflow(state, {
...detectOverflowOptions,
elementContext: 'reference'
});
const offsets = getSideOffsets(overflow, rects.reference);
return {
data: {
referenceHiddenOffsets: offsets,
referenceHidden: isAnySideFullyClipped(offsets)
}
};
}
case 'escaped':
{
const overflow = await detectOverflow(state, {
...detectOverflowOptions,
altBoundary: true
});
const offsets = getSideOffsets(overflow, rects.floating);
return {
data: {
escapedOffsets: offsets,
escaped: isAnySideFullyClipped(offsets)
}
};
}
default:
{
return {};
}
}
}
};
};
function getBoundingRect(rects) {
const minX = min(...rects.map(rect => rect.left));
const minY = min(...rects.map(rect => rect.top));
const maxX = max(...rects.map(rect => rect.right));
const maxY = max(...rects.map(rect => rect.bottom));
return {
x: minX,
y: minY,
width: maxX - minX,
height: maxY - minY
};
}
function getRectsByLine(rects) {
const sortedRects = rects.slice().sort((a, b) => a.y - b.y);
const groups = [];
let prevRect = null;
for (let i = 0; i < sortedRects.length; i++) {
const rect = sortedRects[i];
if (!prevRect || rect.y - prevRect.y > prevRect.height / 2) {
groups.push([rect]);
} else {
groups[groups.length - 1].push(rect);
}
prevRect = rect;
}
return groups.map(rect => rectToClientRect(getBoundingRect(rect)));
}
/**
* Provides improved positioning for inline reference elements that can span
* over multiple lines, such as hyperlinks or range selections.
* @see https://floating-ui.com/docs/inline
*/
const inline = function (options) {
if (options === void 0) {
options = {};
}
return {
name: 'inline',
options,
async fn(state) {
const {
placement,
elements,
rects,
platform,
strategy
} = state;
// A MouseEvent's client{X,Y} coords can be up to 2 pixels off a
// ClientRect's bounds, despite the event listener being triggered. A
// padding of 2 seems to handle this issue.
const {
padding = 2,
x,
y
} = evaluate(options, state);
const nativeClientRects = Array.from((await (platform.getClientRects == null ? void 0 : platform.getClientRects(elements.reference))) || []);
const clientRects = getRectsByLine(nativeClientRects);
const fallback = rectToClientRect(getBoundingRect(nativeClientRects));
const paddingObject = getPaddingObject(padding);
function getBoundingClientRect() {
// There are two rects and they are disjoined.
if (clientRects.length === 2 && clientRects[0].left > clientRects[1].right && x != null && y != null) {
// Find the first rect in which the point is fully inside.
return clientRects.find(rect => x > rect.left - paddingObject.left && x < rect.right + paddingObject.right && y > rect.top - paddingObject.top && y < rect.bottom + paddingObject.bottom) || fallback;
}
// There are 2 or more connected rects.
if (clientRects.length >= 2) {
if (getSideAxis(placement) === 'y') {
const firstRect = clientRects[0];
const lastRect = clientRects[clientRects.length - 1];
const isTop = getSide(placement) === 'top';
const top = firstRect.top;
const bottom = lastRect.bottom;
const left = isTop ? firstRect.left : lastRect.left;
const right = isTop ? firstRect.right : lastRect.right;
const width = right - left;
const height = bottom - top;
return {
top,
bottom,
left,
right,
width,
height,
x: left,
y: top
};
}
const isLeftSide = getSide(placement) === 'left';
const maxRight = max(...clientRects.map(rect => rect.right));
const minLeft = min(...clientRects.map(rect => rect.left));
const measureRects = clientRects.filter(rect => isLeftSide ? rect.left === minLeft : rect.right === maxRight);
const top = measureRects[0].top;
const bottom = measureRects[measureRects.length - 1].bottom;
const left = minLeft;
const right = maxRight;
const width = right - left;
const height = bottom - top;
return {
top,
bottom,
left,
right,
width,
height,
x: left,
y: top
};
}
return fallback;
}
const resetRects = await platform.getElementRects({
reference: {
getBoundingClientRect
},
floating: elements.floating,
strategy
});
if (rects.reference.x !== resetRects.reference.x || rects.reference.y !== resetRects.reference.y || rects.reference.width !== resetRects.reference.width || rects.reference.height !== resetRects.reference.height) {
return {
reset: {
rects: resetRects
}
};
}
return {};
}
};
};
// For type backwards-compatibility, the `OffsetOptions` type was also
// Derivable.
async function convertValueToCoords(state, options) {
const {
placement,
platform,
elements
} = state;
const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));
const side = floating_ui_utils_getSide(placement);
const alignment = floating_ui_utils_getAlignment(placement);
const isVertical = floating_ui_utils_getSideAxis(placement) === 'y';
const mainAxisMulti = ['left', 'top'].includes(side) ? -1 : 1;
const crossAxisMulti = rtl && isVertical ? -1 : 1;
const rawValue = floating_ui_utils_evaluate(options, state);
// eslint-disable-next-line prefer-const
let {
mainAxis,
crossAxis,
alignmentAxis
} = typeof rawValue === 'number' ? {
mainAxis: rawValue,
crossAxis: 0,
alignmentAxis: null
} : {
mainAxis: 0,
crossAxis: 0,
alignmentAxis: null,
...rawValue
};
if (alignment && typeof alignmentAxis === 'number') {
crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis;
}
return isVertical ? {
x: crossAxis * crossAxisMulti,
y: mainAxis * mainAxisMulti
} : {
x: mainAxis * mainAxisMulti,
y: crossAxis * crossAxisMulti
};
}
/**
* Modifies the placement by translating the floating element along the
* specified axes.
* A number (shorthand for `mainAxis` or distance), or an axes configuration
* object may be passed.
* @see https://floating-ui.com/docs/offset
*/
const offset = function (options) {
if (options === void 0) {
options = 0;
}
return {
name: 'offset',
options,
async fn(state) {
var _middlewareData$offse, _middlewareData$arrow;
const {
x,
y,
placement,
middlewareData
} = state;
const diffCoords = await convertValueToCoords(state, options);
// If the placement is the same and the arrow caused an alignment offset
// then we don't need to change the positioning coordinates.
if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
return {};
}
return {
x: x + diffCoords.x,
y: y + diffCoords.y,
data: {
...diffCoords,
placement
}
};
}
};
};
/**
* Optimizes the visibility of the floating element by shifting it in order to
* keep it in view when it will overflow the clipping boundary.
* @see https://floating-ui.com/docs/shift
*/
const shift = function (options) {
if (options === void 0) {
options = {};
}
return {
name: 'shift',
options,
async fn(state) {
const {
x,
y,
placement
} = state;
const {
mainAxis: checkMainAxis = true,
crossAxis: checkCrossAxis = false,
limiter = {
fn: _ref => {
let {
x,
y
} = _ref;
return {
x,
y
};
}
},
...detectOverflowOptions
} = floating_ui_utils_evaluate(options, state);
const coords = {
x,
y
};
const overflow = await detectOverflow(state, detectOverflowOptions);
const crossAxis = floating_ui_utils_getSideAxis(floating_ui_utils_getSide(placement));
const mainAxis = floating_ui_utils_getOppositeAxis(crossAxis);
let mainAxisCoord = coords[mainAxis];
let crossAxisCoord = coords[crossAxis];
if (checkMainAxis) {
const minSide = mainAxis === 'y' ? 'top' : 'left';
const maxSide = mainAxis === 'y' ? 'bottom' : 'right';
const min = mainAxisCoord + overflow[minSide];
const max = mainAxisCoord - overflow[maxSide];
mainAxisCoord = clamp(min, mainAxisCoord, max);
}
if (checkCrossAxis) {
const minSide = crossAxis === 'y' ? 'top' : 'left';
const maxSide = crossAxis === 'y' ? 'bottom' : 'right';
const min = crossAxisCoord + overflow[minSide];
const max = crossAxisCoord - overflow[maxSide];
crossAxisCoord = clamp(min, crossAxisCoord, max);
}
const limitedCoords = limiter.fn({
...state,
[mainAxis]: mainAxisCoord,
[crossAxis]: crossAxisCoord
});
return {
...limitedCoords,
data: {
x: limitedCoords.x - x,
y: limitedCoords.y - y
}
};
}
};
};
/**
* Built-in `limiter` that will stop `shift()` at a certain point.
*/
const limitShift = function (options) {
if (options === void 0) {
options = {};
}
return {
options,
fn(state) {
const {
x,
y,
placement,
rects,
middlewareData
} = state;
const {
offset = 0,
mainAxis: checkMainAxis = true,
crossAxis: checkCrossAxis = true
} = evaluate(options, state);
const coords = {
x,
y
};
const crossAxis = getSideAxis(placement);
const mainAxis = getOppositeAxis(crossAxis);
let mainAxisCoord = coords[mainAxis];
let crossAxisCoord = coords[crossAxis];
const rawOffset = evaluate(offset, state);
const computedOffset = typeof rawOffset === 'number' ? {
mainAxis: rawOffset,
crossAxis: 0
} : {
mainAxis: 0,
crossAxis: 0,
...rawOffset
};
if (checkMainAxis) {
const len = mainAxis === 'y' ? 'height' : 'width';
const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis;
const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis;
if (mainAxisCoord < limitMin) {
mainAxisCoord = limitMin;
} else if (mainAxisCoord > limitMax) {
mainAxisCoord = limitMax;
}
}
if (checkCrossAxis) {
var _middlewareData$offse, _middlewareData$offse2;
const len = mainAxis === 'y' ? 'width' : 'height';
const isOriginSide = ['top', 'left'].includes(getSide(placement));
const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis);
const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0);
if (crossAxisCoord < limitMin) {
crossAxisCoord = limitMin;
} else if (crossAxisCoord > limitMax) {
crossAxisCoord = limitMax;
}
}
return {
[mainAxis]: mainAxisCoord,
[crossAxis]: crossAxisCoord
};
}
};
};
/**
* Provides data that allows you to change the size of the floating element —
* for instance, prevent it from overflowing the clipping boundary or match the
* width of the reference element.
* @see https://floating-ui.com/docs/size
*/
const size = function (options) {
if (options === void 0) {
options = {};
}
return {
name: 'size',
options,
async fn(state) {
const {
placement,
rects,
platform,
elements
} = state;
const {
apply = () => {},
...detectOverflowOptions
} = floating_ui_utils_evaluate(options, state);
const overflow = await detectOverflow(state, detectOverflowOptions);
const side = floating_ui_utils_getSide(placement);
const alignment = floating_ui_utils_getAlignment(placement);
const isYAxis = floating_ui_utils_getSideAxis(placement) === 'y';
const {
width,
height
} = rects.floating;
let heightSide;
let widthSide;
if (side === 'top' || side === 'bottom') {
heightSide = side;
widthSide = alignment === ((await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))) ? 'start' : 'end') ? 'left' : 'right';
} else {
widthSide = side;
heightSide = alignment === 'end' ? 'top' : 'bottom';
}
const maximumClippingHeight = height - overflow.top - overflow.bottom;
const maximumClippingWidth = width - overflow.left - overflow.right;
const overflowAvailableHeight = floating_ui_utils_min(height - overflow[heightSide], maximumClippingHeight);
const overflowAvailableWidth = floating_ui_utils_min(width - overflow[widthSide], maximumClippingWidth);
const noShift = !state.middlewareData.shift;
let availableHeight = overflowAvailableHeight;
let availableWidth = overflowAvailableWidth;
if (isYAxis) {
availableWidth = alignment || noShift ? floating_ui_utils_min(overflowAvailableWidth, maximumClippingWidth) : maximumClippingWidth;
} else {
availableHeight = alignment || noShift ? floating_ui_utils_min(overflowAvailableHeight, maximumClippingHeight) : maximumClippingHeight;
}
if (noShift && !alignment) {
const xMin = floating_ui_utils_max(overflow.left, 0);
const xMax = floating_ui_utils_max(overflow.right, 0);
const yMin = floating_ui_utils_max(overflow.top, 0);
const yMax = floating_ui_utils_max(overflow.bottom, 0);
if (isYAxis) {
availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : floating_ui_utils_max(overflow.left, overflow.right));
} else {
availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : floating_ui_utils_max(overflow.top, overflow.bottom));
}
}
await apply({
...state,
availableWidth,
availableHeight
});
const nextDimensions = await platform.getDimensions(elements.floating);
if (width !== nextDimensions.width || height !== nextDimensions.height) {
return {
reset: {
rects: true
}
};
}
return {};
}
};
};
;// CONCATENATED MODULE: ./node_modules/@floating-ui/utils/dist/floating-ui.utils.dom.mjs
function getNodeName(node) {
if (isNode(node)) {
return (node.nodeName || '').toLowerCase();
}
// Mocked nodes in testing environments may not be instances of Node. By
// returning `#document` an infinite loop won't occur.
// https://github.com/floating-ui/floating-ui/issues/2317
return '#document';
}
function floating_ui_utils_dom_getWindow(node) {
var _node$ownerDocument;
return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;
}
function getDocumentElement(node) {
var _ref;
return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;
}
function isNode(value) {
return value instanceof Node || value instanceof floating_ui_utils_dom_getWindow(value).Node;
}
function isElement(value) {
return value instanceof Element || value instanceof floating_ui_utils_dom_getWindow(value).Element;
}
function isHTMLElement(value) {
return value instanceof HTMLElement || value instanceof floating_ui_utils_dom_getWindow(value).HTMLElement;
}
function isShadowRoot(value) {
// Browsers without `ShadowRoot` support.
if (typeof ShadowRoot === 'undefined') {
return false;
}
return value instanceof ShadowRoot || value instanceof floating_ui_utils_dom_getWindow(value).ShadowRoot;
}
function isOverflowElement(element) {
const {
overflow,
overflowX,
overflowY,
display
} = floating_ui_utils_dom_getComputedStyle(element);
return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !['inline', 'contents'].includes(display);
}
function isTableElement(element) {
return ['table', 'td', 'th'].includes(getNodeName(element));
}
function isContainingBlock(element) {
const webkit = isWebKit();
const css = floating_ui_utils_dom_getComputedStyle(element);
// https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block
return css.transform !== 'none' || css.perspective !== 'none' || (css.containerType ? css.containerType !== 'normal' : false) || !webkit && (css.backdropFilter ? css.backdropFilter !== 'none' : false) || !webkit && (css.filter ? css.filter !== 'none' : false) || ['transform', 'perspective', 'filter'].some(value => (css.willChange || '').includes(value)) || ['paint', 'layout', 'strict', 'content'].some(value => (css.contain || '').includes(value));
}
function getContainingBlock(element) {
let currentNode = getParentNode(element);
while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {
if (isContainingBlock(currentNode)) {
return currentNode;
}
currentNode = getParentNode(currentNode);
}
return null;
}
function isWebKit() {
if (typeof CSS === 'undefined' || !CSS.supports) return false;
return CSS.supports('-webkit-backdrop-filter', 'none');
}
function isLastTraversableNode(node) {
return ['html', 'body', '#document'].includes(getNodeName(node));
}
function floating_ui_utils_dom_getComputedStyle(element) {
return floating_ui_utils_dom_getWindow(element).getComputedStyle(element);
}
function getNodeScroll(element) {
if (isElement(element)) {
return {
scrollLeft: element.scrollLeft,
scrollTop: element.scrollTop
};
}
return {
scrollLeft: element.pageXOffset,
scrollTop: element.pageYOffset
};
}
function getParentNode(node) {
if (getNodeName(node) === 'html') {
return node;
}
const result =
// Step into the shadow DOM of the parent of a slotted node.
node.assignedSlot ||
// DOM Element detected.
node.parentNode ||
// ShadowRoot detected.
isShadowRoot(node) && node.host ||
// Fallback.
getDocumentElement(node);
return isShadowRoot(result) ? result.host : result;
}
function getNearestOverflowAncestor(node) {
const parentNode = getParentNode(node);
if (isLastTraversableNode(parentNode)) {
return node.ownerDocument ? node.ownerDocument.body : node.body;
}
if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) {
return parentNode;
}
return getNearestOverflowAncestor(parentNode);
}
function getOverflowAncestors(node, list, traverseIframes) {
var _node$ownerDocument2;
if (list === void 0) {
list = [];
}
if (traverseIframes === void 0) {
traverseIframes = true;
}
const scrollableAncestor = getNearestOverflowAncestor(node);
const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);
const win = floating_ui_utils_dom_getWindow(scrollableAncestor);
if (isBody) {
return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], win.frameElement && traverseIframes ? getOverflowAncestors(win.frameElement) : []);
}
return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));
}
;// CONCATENATED MODULE: ./node_modules/@floating-ui/dom/dist/floating-ui.dom.mjs
function getCssDimensions(element) {
const css = floating_ui_utils_dom_getComputedStyle(element);
// In testing environments, the `width` and `height` properties are empty
// strings for SVG elements, returning NaN. Fallback to `0` in this case.
let width = parseFloat(css.width) || 0;
let height = parseFloat(css.height) || 0;
const hasOffset = isHTMLElement(element);
const offsetWidth = hasOffset ? element.offsetWidth : width;
const offsetHeight = hasOffset ? element.offsetHeight : height;
const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight;
if (shouldFallback) {
width = offsetWidth;
height = offsetHeight;
}
return {
width,
height,
$: shouldFallback
};
}
function unwrapElement(element) {
return !isElement(element) ? element.contextElement : element;
}
function getScale(element) {
const domElement = unwrapElement(element);
if (!isHTMLElement(domElement)) {
return createCoords(1);
}
const rect = domElement.getBoundingClientRect();
const {
width,
height,
$
} = getCssDimensions(domElement);
let x = ($ ? round(rect.width) : rect.width) / width;
let y = ($ ? round(rect.height) : rect.height) / height;
// 0, NaN, or Infinity should always fallback to 1.
if (!x || !Number.isFinite(x)) {
x = 1;
}
if (!y || !Number.isFinite(y)) {
y = 1;
}
return {
x,
y
};
}
const noOffsets = /*#__PURE__*/createCoords(0);
function getVisualOffsets(element) {
const win = floating_ui_utils_dom_getWindow(element);
if (!isWebKit() || !win.visualViewport) {
return noOffsets;
}
return {
x: win.visualViewport.offsetLeft,
y: win.visualViewport.offsetTop
};
}
function shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) {
if (isFixed === void 0) {
isFixed = false;
}
if (!floatingOffsetParent || isFixed && floatingOffsetParent !== floating_ui_utils_dom_getWindow(element)) {
return false;
}
return isFixed;
}
function getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) {
if (includeScale === void 0) {
includeScale = false;
}
if (isFixedStrategy === void 0) {
isFixedStrategy = false;
}
const clientRect = element.getBoundingClientRect();
const domElement = unwrapElement(element);
let scale = createCoords(1);
if (includeScale) {
if (offsetParent) {
if (isElement(offsetParent)) {
scale = getScale(offsetParent);
}
} else {
scale = getScale(element);
}
}
const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0);
let x = (clientRect.left + visualOffsets.x) / scale.x;
let y = (clientRect.top + visualOffsets.y) / scale.y;
let width = clientRect.width / scale.x;
let height = clientRect.height / scale.y;
if (domElement) {
const win = floating_ui_utils_dom_getWindow(domElement);
const offsetWin = offsetParent && isElement(offsetParent) ? floating_ui_utils_dom_getWindow(offsetParent) : offsetParent;
let currentWin = win;
let currentIFrame = currentWin.frameElement;
while (currentIFrame && offsetParent && offsetWin !== currentWin) {
const iframeScale = getScale(currentIFrame);
const iframeRect = currentIFrame.getBoundingClientRect();
const css = floating_ui_utils_dom_getComputedStyle(currentIFrame);
const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x;
const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y;
x *= iframeScale.x;
y *= iframeScale.y;
width *= iframeScale.x;
height *= iframeScale.y;
x += left;
y += top;
currentWin = floating_ui_utils_dom_getWindow(currentIFrame);
currentIFrame = currentWin.frameElement;
}
}
return floating_ui_utils_rectToClientRect({
width,
height,
x,
y
});
}
const topLayerSelectors = [':popover-open', ':modal'];
function isTopLayer(element) {
return topLayerSelectors.some(selector => {
try {
return element.matches(selector);
} catch (e) {
return false;
}
});
}
function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) {
let {
elements,
rect,
offsetParent,
strategy
} = _ref;
const isFixed = strategy === 'fixed';
const documentElement = getDocumentElement(offsetParent);
const topLayer = elements ? isTopLayer(elements.floating) : false;
if (offsetParent === documentElement || topLayer && isFixed) {
return rect;
}
let scroll = {
scrollLeft: 0,
scrollTop: 0
};
let scale = createCoords(1);
const offsets = createCoords(0);
const isOffsetParentAnElement = isHTMLElement(offsetParent);
if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {
scroll = getNodeScroll(offsetParent);
}
if (isHTMLElement(offsetParent)) {
const offsetRect = getBoundingClientRect(offsetParent);
scale = getScale(offsetParent);
offsets.x = offsetRect.x + offsetParent.clientLeft;
offsets.y = offsetRect.y + offsetParent.clientTop;
}
}
return {
width: rect.width * scale.x,
height: rect.height * scale.y,
x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x,
y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y
};
}
function getClientRects(element) {
return Array.from(element.getClientRects());
}
function getWindowScrollBarX(element) {
// If <html> has a CSS width greater than the viewport, then this will be
// incorrect for RTL.
return getBoundingClientRect(getDocumentElement(element)).left + getNodeScroll(element).scrollLeft;
}
// Gets the entire size of the scrollable document area, even extending outside
// of the `<html>` and `<body>` rect bounds if horizontally scrollable.
function getDocumentRect(element) {
const html = getDocumentElement(element);
const scroll = getNodeScroll(element);
const body = element.ownerDocument.body;
const width = floating_ui_utils_max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth);
const height = floating_ui_utils_max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight);
let x = -scroll.scrollLeft + getWindowScrollBarX(element);
const y = -scroll.scrollTop;
if (floating_ui_utils_dom_getComputedStyle(body).direction === 'rtl') {
x += floating_ui_utils_max(html.clientWidth, body.clientWidth) - width;
}
return {
width,
height,
x,
y
};
}
function getViewportRect(element, strategy) {
const win = floating_ui_utils_dom_getWindow(element);
const html = getDocumentElement(element);
const visualViewport = win.visualViewport;
let width = html.clientWidth;
let height = html.clientHeight;
let x = 0;
let y = 0;
if (visualViewport) {
width = visualViewport.width;
height = visualViewport.height;
const visualViewportBased = isWebKit();
if (!visualViewportBased || visualViewportBased && strategy === 'fixed') {
x = visualViewport.offsetLeft;
y = visualViewport.offsetTop;
}
}
return {
width,
height,
x,
y
};
}
// Returns the inner client rect, subtracting scrollbars if present.
function getInnerBoundingClientRect(element, strategy) {
const clientRect = getBoundingClientRect(element, true, strategy === 'fixed');
const top = clientRect.top + element.clientTop;
const left = clientRect.left + element.clientLeft;
const scale = isHTMLElement(element) ? getScale(element) : createCoords(1);
const width = element.clientWidth * scale.x;
const height = element.clientHeight * scale.y;
const x = left * scale.x;
const y = top * scale.y;
return {
width,
height,
x,
y
};
}
function getClientRectFromClippingAncestor(element, clippingAncestor, strategy) {
let rect;
if (clippingAncestor === 'viewport') {
rect = getViewportRect(element, strategy);
} else if (clippingAncestor === 'document') {
rect = getDocumentRect(getDocumentElement(element));
} else if (isElement(clippingAncestor)) {
rect = getInnerBoundingClientRect(clippingAncestor, strategy);
} else {
const visualOffsets = getVisualOffsets(element);
rect = {
...clippingAncestor,
x: clippingAncestor.x - visualOffsets.x,
y: clippingAncestor.y - visualOffsets.y
};
}
return floating_ui_utils_rectToClientRect(rect);
}
function hasFixedPositionAncestor(element, stopNode) {
const parentNode = getParentNode(element);
if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) {
return false;
}
return floating_ui_utils_dom_getComputedStyle(parentNode).position === 'fixed' || hasFixedPositionAncestor(parentNode, stopNode);
}
// A "clipping ancestor" is an `overflow` element with the characteristic of
// clipping (or hiding) child elements. This returns all clipping ancestors
// of the given element up the tree.
function getClippingElementAncestors(element, cache) {
const cachedResult = cache.get(element);
if (cachedResult) {
return cachedResult;
}
let result = getOverflowAncestors(element, [], false).filter(el => isElement(el) && getNodeName(el) !== 'body');
let currentContainingBlockComputedStyle = null;
const elementIsFixed = floating_ui_utils_dom_getComputedStyle(element).position === 'fixed';
let currentNode = elementIsFixed ? getParentNode(element) : element;
// https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block
while (isElement(currentNode) && !isLastTraversableNode(currentNode)) {
const computedStyle = floating_ui_utils_dom_getComputedStyle(currentNode);
const currentNodeIsContaining = isContainingBlock(currentNode);
if (!currentNodeIsContaining && computedStyle.position === 'fixed') {
currentContainingBlockComputedStyle = null;
}
const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === 'static' && !!currentContainingBlockComputedStyle && ['absolute', 'fixed'].includes(currentContainingBlockComputedStyle.position) || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode);
if (shouldDropCurrentNode) {
// Drop non-containing blocks.
result = result.filter(ancestor => ancestor !== currentNode);
} else {
// Record last containing block for next iteration.
currentContainingBlockComputedStyle = computedStyle;
}
currentNode = getParentNode(currentNode);
}
cache.set(element, result);
return result;
}
// Gets the maximum area that the element is visible in due to any number of
// clipping ancestors.
function getClippingRect(_ref) {
let {
element,
boundary,
rootBoundary,
strategy
} = _ref;
const elementClippingAncestors = boundary === 'clippingAncestors' ? isTopLayer(element) ? [] : getClippingElementAncestors(element, this._c) : [].concat(boundary);
const clippingAncestors = [...elementClippingAncestors, rootBoundary];
const firstClippingAncestor = clippingAncestors[0];
const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => {
const rect = getClientRectFromClippingAncestor(element, clippingAncestor, strategy);
accRect.top = floating_ui_utils_max(rect.top, accRect.top);
accRect.right = floating_ui_utils_min(rect.right, accRect.right);
accRect.bottom = floating_ui_utils_min(rect.bottom, accRect.bottom);
accRect.left = floating_ui_utils_max(rect.left, accRect.left);
return accRect;
}, getClientRectFromClippingAncestor(element, firstClippingAncestor, strategy));
return {
width: clippingRect.right - clippingRect.left,
height: clippingRect.bottom - clippingRect.top,
x: clippingRect.left,
y: clippingRect.top
};
}
function getDimensions(element) {
const {
width,
height
} = getCssDimensions(element);
return {
width,
height
};
}
function getRectRelativeToOffsetParent(element, offsetParent, strategy) {
const isOffsetParentAnElement = isHTMLElement(offsetParent);
const documentElement = getDocumentElement(offsetParent);
const isFixed = strategy === 'fixed';
const rect = getBoundingClientRect(element, true, isFixed, offsetParent);
let scroll = {
scrollLeft: 0,
scrollTop: 0
};
const offsets = createCoords(0);
if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {
scroll = getNodeScroll(offsetParent);
}
if (isOffsetParentAnElement) {
const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent);
offsets.x = offsetRect.x + offsetParent.clientLeft;
offsets.y = offsetRect.y + offsetParent.clientTop;
} else if (documentElement) {
offsets.x = getWindowScrollBarX(documentElement);
}
}
const x = rect.left + scroll.scrollLeft - offsets.x;
const y = rect.top + scroll.scrollTop - offsets.y;
return {
x,
y,
width: rect.width,
height: rect.height
};
}
function isStaticPositioned(element) {
return floating_ui_utils_dom_getComputedStyle(element).position === 'static';
}
function getTrueOffsetParent(element, polyfill) {
if (!isHTMLElement(element) || floating_ui_utils_dom_getComputedStyle(element).position === 'fixed') {
return null;
}
if (polyfill) {
return polyfill(element);
}
return element.offsetParent;
}
// Gets the closest ancestor positioned element. Handles some edge cases,
// such as table ancestors and cross browser bugs.
function getOffsetParent(element, polyfill) {
const win = floating_ui_utils_dom_getWindow(element);
if (isTopLayer(element)) {
return win;
}
if (!isHTMLElement(element)) {
let svgOffsetParent = getParentNode(element);
while (svgOffsetParent && !isLastTraversableNode(svgOffsetParent)) {
if (isElement(svgOffsetParent) && !isStaticPositioned(svgOffsetParent)) {
return svgOffsetParent;
}
svgOffsetParent = getParentNode(svgOffsetParent);
}
return win;
}
let offsetParent = getTrueOffsetParent(element, polyfill);
while (offsetParent && isTableElement(offsetParent) && isStaticPositioned(offsetParent)) {
offsetParent = getTrueOffsetParent(offsetParent, polyfill);
}
if (offsetParent && isLastTraversableNode(offsetParent) && isStaticPositioned(offsetParent) && !isContainingBlock(offsetParent)) {
return win;
}
return offsetParent || getContainingBlock(element) || win;
}
const getElementRects = async function (data) {
const getOffsetParentFn = this.getOffsetParent || getOffsetParent;
const getDimensionsFn = this.getDimensions;
const floatingDimensions = await getDimensionsFn(data.floating);
return {
reference: getRectRelativeToOffsetParent(data.reference, await getOffsetParentFn(data.floating), data.strategy),
floating: {
x: 0,
y: 0,
width: floatingDimensions.width,
height: floatingDimensions.height
}
};
};
function isRTL(element) {
return floating_ui_utils_dom_getComputedStyle(element).direction === 'rtl';
}
const platform = {
convertOffsetParentRelativeRectToViewportRelativeRect,
getDocumentElement: getDocumentElement,
getClippingRect,
getOffsetParent,
getElementRects,
getClientRects,
getDimensions,
getScale,
isElement: isElement,
isRTL
};
// https://samthor.au/2021/observing-dom/
function observeMove(element, onMove) {
let io = null;
let timeoutId;
const root = getDocumentElement(element);
function cleanup() {
var _io;
clearTimeout(timeoutId);
(_io = io) == null || _io.disconnect();
io = null;
}
function refresh(skip, threshold) {
if (skip === void 0) {
skip = false;
}
if (threshold === void 0) {
threshold = 1;
}
cleanup();
const {
left,
top,
width,
height
} = element.getBoundingClientRect();
if (!skip) {
onMove();
}
if (!width || !height) {
return;
}
const insetTop = floor(top);
const insetRight = floor(root.clientWidth - (left + width));
const insetBottom = floor(root.clientHeight - (top + height));
const insetLeft = floor(left);
const rootMargin = -insetTop + "px " + -insetRight + "px " + -insetBottom + "px " + -insetLeft + "px";
const options = {
rootMargin,
threshold: floating_ui_utils_max(0, floating_ui_utils_min(1, threshold)) || 1
};
let isFirstUpdate = true;
function handleObserve(entries) {
const ratio = entries[0].intersectionRatio;
if (ratio !== threshold) {
if (!isFirstUpdate) {
return refresh();
}
if (!ratio) {
// If the reference is clipped, the ratio is 0. Throttle the refresh
// to prevent an infinite loop of updates.
timeoutId = setTimeout(() => {
refresh(false, 1e-7);
}, 1000);
} else {
refresh(false, ratio);
}
}
isFirstUpdate = false;
}
// Older browsers don't support a `document` as the root and will throw an
// error.
try {
io = new IntersectionObserver(handleObserve, {
...options,
// Handle <iframe>s
root: root.ownerDocument
});
} catch (e) {
io = new IntersectionObserver(handleObserve, options);
}
io.observe(element);
}
refresh(true);
return cleanup;
}
/**
* Automatically updates the position of the floating element when necessary.
* Should only be called when the floating element is mounted on the DOM or
* visible on the screen.
* @returns cleanup function that should be invoked when the floating element is
* removed from the DOM or hidden from the screen.
* @see https://floating-ui.com/docs/autoUpdate
*/
function autoUpdate(reference, floating, update, options) {
if (options === void 0) {
options = {};
}
const {
ancestorScroll = true,
ancestorResize = true,
elementResize = typeof ResizeObserver === 'function',
layoutShift = typeof IntersectionObserver === 'function',
animationFrame = false
} = options;
const referenceEl = unwrapElement(reference);
const ancestors = ancestorScroll || ancestorResize ? [...(referenceEl ? getOverflowAncestors(referenceEl) : []), ...getOverflowAncestors(floating)] : [];
ancestors.forEach(ancestor => {
ancestorScroll && ancestor.addEventListener('scroll', update, {
passive: true
});
ancestorResize && ancestor.addEventListener('resize', update);
});
const cleanupIo = referenceEl && layoutShift ? observeMove(referenceEl, update) : null;
let reobserveFrame = -1;
let resizeObserver = null;
if (elementResize) {
resizeObserver = new ResizeObserver(_ref => {
let [firstEntry] = _ref;
if (firstEntry && firstEntry.target === referenceEl && resizeObserver) {
// Prevent update loops when using the `size` middleware.
// https://github.com/floating-ui/floating-ui/issues/1740
resizeObserver.unobserve(floating);
cancelAnimationFrame(reobserveFrame);
reobserveFrame = requestAnimationFrame(() => {
var _resizeObserver;
(_resizeObserver = resizeObserver) == null || _resizeObserver.observe(floating);
});
}
update();
});
if (referenceEl && !animationFrame) {
resizeObserver.observe(referenceEl);
}
resizeObserver.observe(floating);
}
let frameId;
let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null;
if (animationFrame) {
frameLoop();
}
function frameLoop() {
const nextRefRect = getBoundingClientRect(reference);
if (prevRefRect && (nextRefRect.x !== prevRefRect.x || nextRefRect.y !== prevRefRect.y || nextRefRect.width !== prevRefRect.width || nextRefRect.height !== prevRefRect.height)) {
update();
}
prevRefRect = nextRefRect;
frameId = requestAnimationFrame(frameLoop);
}
update();
return () => {
var _resizeObserver2;
ancestors.forEach(ancestor => {
ancestorScroll && ancestor.removeEventListener('scroll', update);
ancestorResize && ancestor.removeEventListener('resize', update);
});
cleanupIo == null || cleanupIo();
(_resizeObserver2 = resizeObserver) == null || _resizeObserver2.disconnect();
resizeObserver = null;
if (animationFrame) {
cancelAnimationFrame(frameId);
}
};
}
/**
* Resolves with an object of overflow side offsets that determine how much the
* element is overflowing a given clipping boundary on each side.
* - positive = overflowing the boundary by that number of pixels
* - negative = how many pixels left before it will overflow
* - 0 = lies flush with the boundary
* @see https://floating-ui.com/docs/detectOverflow
*/
const floating_ui_dom_detectOverflow = (/* unused pure expression or super */ null && (detectOverflow$1));
/**
* Modifies the placement by translating the floating element along the
* specified axes.
* A number (shorthand for `mainAxis` or distance), or an axes configuration
* object may be passed.
* @see https://floating-ui.com/docs/offset
*/
const floating_ui_dom_offset = offset;
/**
* Optimizes the visibility of the floating element by choosing the placement
* that has the most space available automatically, without needing to specify a
* preferred placement. Alternative to `flip`.
* @see https://floating-ui.com/docs/autoPlacement
*/
const floating_ui_dom_autoPlacement = (/* unused pure expression or super */ null && (autoPlacement$1));
/**
* Optimizes the visibility of the floating element by shifting it in order to
* keep it in view when it will overflow the clipping boundary.
* @see https://floating-ui.com/docs/shift
*/
const floating_ui_dom_shift = shift;
/**
* Optimizes the visibility of the floating element by flipping the `placement`
* in order to keep it in view when the preferred placement(s) will overflow the
* clipping boundary. Alternative to `autoPlacement`.
* @see https://floating-ui.com/docs/flip
*/
const floating_ui_dom_flip = flip;
/**
* Provides data that allows you to change the size of the floating element —
* for instance, prevent it from overflowing the clipping boundary or match the
* width of the reference element.
* @see https://floating-ui.com/docs/size
*/
const floating_ui_dom_size = size;
/**
* Provides data to hide the floating element in applicable situations, such as
* when it is not in the same clipping context as the reference element.
* @see https://floating-ui.com/docs/hide
*/
const floating_ui_dom_hide = (/* unused pure expression or super */ null && (hide$1));
/**
* Provides data to position an inner element of the floating element so that it
* appears centered to the reference element.
* @see https://floating-ui.com/docs/arrow
*/
const floating_ui_dom_arrow = arrow;
/**
* Provides improved positioning for inline reference elements that can span
* over multiple lines, such as hyperlinks or range selections.
* @see https://floating-ui.com/docs/inline
*/
const floating_ui_dom_inline = (/* unused pure expression or super */ null && (inline$1));
/**
* Built-in `limiter` that will stop `shift()` at a certain point.
*/
const floating_ui_dom_limitShift = (/* unused pure expression or super */ null && (limitShift$1));
/**
* Computes the `x` and `y` coordinates that will place the floating element
* next to a given reference element.
*/
const floating_ui_dom_computePosition = (reference, floating, options) => {
// This caches the expensive `getClippingElementAncestors` function so that
// multiple lifecycle resets re-use the same result. It only lives for a
// single call. If other functions become expensive, we can add them as well.
const cache = new Map();
const mergedOptions = {
platform,
...options
};
const platformWithCache = {
...mergedOptions.platform,
_c: cache
};
return computePosition(reference, floating, {
...mergedOptions,
platform: platformWithCache
});
};
;// CONCATENATED MODULE: external "ReactDOM"
var external_ReactDOM_namespaceObject = window["ReactDOM"];
;// CONCATENATED MODULE: ./node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.esm.js
var index = typeof document !== 'undefined' ? external_React_.useLayoutEffect : external_React_.useEffect;
// Fork of `fast-deep-equal` that only does the comparisons we need and compares
// functions
function deepEqual(a, b) {
if (a === b) {
return true;
}
if (typeof a !== typeof b) {
return false;
}
if (typeof a === 'function' && a.toString() === b.toString()) {
return true;
}
let length, i, keys;
if (a && b && typeof a == 'object') {
if (Array.isArray(a)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;) {
if (!deepEqual(a[i], b[i])) {
return false;
}
}
return true;
}
keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) {
return false;
}
for (i = length; i-- !== 0;) {
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) {
return false;
}
}
for (i = length; i-- !== 0;) {
const key = keys[i];
if (key === '_owner' && a.$$typeof) {
continue;
}
if (!deepEqual(a[key], b[key])) {
return false;
}
}
return true;
}
return a !== a && b !== b;
}
function useLatestRef(value) {
const ref = external_React_.useRef(value);
index(() => {
ref.current = value;
});
return ref;
}
function useFloating(_temp) {
let {
middleware,
placement = 'bottom',
strategy = 'absolute',
whileElementsMounted
} = _temp === void 0 ? {} : _temp;
const [data, setData] = external_React_.useState({
// Setting these to `null` will allow the consumer to determine if
// `computePosition()` has run yet
x: null,
y: null,
strategy,
placement,
middlewareData: {}
});
const [latestMiddleware, setLatestMiddleware] = external_React_.useState(middleware);
if (!deepEqual(latestMiddleware == null ? void 0 : latestMiddleware.map(_ref => {
let {
name,
options
} = _ref;
return {
name,
options
};
}), middleware == null ? void 0 : middleware.map(_ref2 => {
let {
name,
options
} = _ref2;
return {
name,
options
};
}))) {
setLatestMiddleware(middleware);
}
const reference = external_React_.useRef(null);
const floating = external_React_.useRef(null);
const cleanupRef = external_React_.useRef(null);
const dataRef = external_React_.useRef(data);
const whileElementsMountedRef = useLatestRef(whileElementsMounted);
const update = external_React_.useCallback(() => {
if (!reference.current || !floating.current) {
return;
}
floating_ui_dom_computePosition(reference.current, floating.current, {
middleware: latestMiddleware,
placement,
strategy
}).then(data => {
if (isMountedRef.current && !deepEqual(dataRef.current, data)) {
dataRef.current = data;
external_ReactDOM_namespaceObject.flushSync(() => {
setData(data);
});
}
});
}, [latestMiddleware, placement, strategy]);
index(() => {
// Skip first update
if (isMountedRef.current) {
update();
}
}, [update]);
const isMountedRef = external_React_.useRef(false);
index(() => {
isMountedRef.current = true;
return () => {
isMountedRef.current = false;
};
}, []);
const runElementMountCallback = external_React_.useCallback(() => {
if (typeof cleanupRef.current === 'function') {
cleanupRef.current();
cleanupRef.current = null;
}
if (reference.current && floating.current) {
if (whileElementsMountedRef.current) {
const cleanupFn = whileElementsMountedRef.current(reference.current, floating.current, update);
cleanupRef.current = cleanupFn;
} else {
update();
}
}
}, [update, whileElementsMountedRef]);
const setReference = external_React_.useCallback(node => {
reference.current = node;
runElementMountCallback();
}, [runElementMountCallback]);
const setFloating = external_React_.useCallback(node => {
floating.current = node;
runElementMountCallback();
}, [runElementMountCallback]);
const refs = external_React_.useMemo(() => ({
reference,
floating
}), []);
return external_React_.useMemo(() => ({ ...data,
update,
refs,
reference: setReference,
floating: setFloating
}), [data, update, refs, setReference, setFloating]);
}
/**
* Positions an inner element of the floating element such that it is centered
* to the reference element.
* This wraps the core `arrow` middleware to allow React refs as the element.
* @see https://floating-ui.com/docs/arrow
*/
const floating_ui_react_dom_esm_arrow = options => {
const {
element,
padding
} = options;
function isRef(value) {
return Object.prototype.hasOwnProperty.call(value, 'current');
}
return {
name: 'arrow',
options,
fn(args) {
if (isRef(element)) {
if (element.current != null) {
return floating_ui_dom_arrow({
element: element.current,
padding
}).fn(args);
}
return {};
} else if (element) {
return floating_ui_dom_arrow({
element,
padding
}).fn(args);
}
return {};
}
};
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/is-browser.mjs
const isBrowser = typeof document !== "undefined";
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/reduced-motion/state.mjs
// Does this device prefer reduced motion? Returns `null` server-side.
const prefersReducedMotion = { current: null };
const hasReducedMotionListener = { current: false };
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/reduced-motion/index.mjs
function initPrefersReducedMotion() {
hasReducedMotionListener.current = true;
if (!isBrowser)
return;
if (window.matchMedia) {
const motionMediaQuery = window.matchMedia("(prefers-reduced-motion)");
const setReducedMotionPreferences = () => (prefersReducedMotion.current = motionMediaQuery.matches);
motionMediaQuery.addListener(setReducedMotionPreferences);
setReducedMotionPreferences();
}
else {
prefersReducedMotion.current = false;
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/reduced-motion/use-reduced-motion.mjs
/**
* A hook that returns `true` if we should be using reduced motion based on the current device's Reduced Motion setting.
*
* This can be used to implement changes to your UI based on Reduced Motion. For instance, replacing motion-sickness inducing
* `x`/`y` animations with `opacity`, disabling the autoplay of background videos, or turning off parallax motion.
*
* It will actively respond to changes and re-render your components with the latest setting.
*
* ```jsx
* export function Sidebar({ isOpen }) {
* const shouldReduceMotion = useReducedMotion()
* const closedX = shouldReduceMotion ? 0 : "-100%"
*
* return (
* <motion.div animate={{
* opacity: isOpen ? 1 : 0,
* x: isOpen ? 0 : closedX
* }} />
* )
* }
* ```
*
* @return boolean
*
* @public
*/
function useReducedMotion() {
/**
* Lazy initialisation of prefersReducedMotion
*/
!hasReducedMotionListener.current && initPrefersReducedMotion();
const [shouldReduceMotion] = (0,external_React_.useState)(prefersReducedMotion.current);
/**
* TODO See if people miss automatically updating shouldReduceMotion setting
*/
return shouldReduceMotion;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/context/MotionConfigContext.mjs
/**
* @public
*/
const MotionConfigContext = (0,external_React_.createContext)({
transformPagePoint: (p) => p,
isStatic: false,
reducedMotion: "never",
});
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/context/MotionContext/index.mjs
const MotionContext = (0,external_React_.createContext)({});
function useVisualElementContext() {
return (0,external_React_.useContext)(MotionContext).visualElement;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/context/PresenceContext.mjs
/**
* @public
*/
const PresenceContext_PresenceContext = (0,external_React_.createContext)(null);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/use-isomorphic-effect.mjs
const useIsomorphicLayoutEffect = isBrowser ? external_React_.useLayoutEffect : external_React_.useEffect;
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/context/LazyContext.mjs
const LazyContext = (0,external_React_.createContext)({ strict: false });
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/utils/use-visual-element.mjs
function useVisualElement(Component, visualState, props, createVisualElement) {
const parent = useVisualElementContext();
const lazyContext = (0,external_React_.useContext)(LazyContext);
const presenceContext = (0,external_React_.useContext)(PresenceContext_PresenceContext);
const reducedMotionConfig = (0,external_React_.useContext)(MotionConfigContext).reducedMotion;
const visualElementRef = (0,external_React_.useRef)();
/**
* If we haven't preloaded a renderer, check to see if we have one lazy-loaded
*/
createVisualElement = createVisualElement || lazyContext.renderer;
if (!visualElementRef.current && createVisualElement) {
visualElementRef.current = createVisualElement(Component, {
visualState,
parent,
props,
presenceId: presenceContext ? presenceContext.id : undefined,
blockInitialAnimation: presenceContext
? presenceContext.initial === false
: false,
reducedMotionConfig,
});
}
const visualElement = visualElementRef.current;
useIsomorphicLayoutEffect(() => {
visualElement && visualElement.render();
});
/**
* If we have optimised appear animations to handoff from, trigger animateChanges
* from a synchronous useLayoutEffect to ensure there's no flash of incorrectly
* styled component in the event of a hydration error.
*/
useIsomorphicLayoutEffect(() => {
if (visualElement && visualElement.animationState) {
visualElement.animationState.animateChanges();
}
});
useIsomorphicLayoutEffect(() => () => visualElement && visualElement.notify("Unmount"), []);
return visualElement;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/is-ref-object.mjs
function is_ref_object_isRefObject(ref) {
return (typeof ref === "object" &&
Object.prototype.hasOwnProperty.call(ref, "current"));
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/utils/use-motion-ref.mjs
/**
* Creates a ref function that, when called, hydrates the provided
* external ref and VisualElement.
*/
function useMotionRef(visualState, visualElement, externalRef) {
return (0,external_React_.useCallback)((instance) => {
instance && visualState.mount && visualState.mount(instance);
if (visualElement) {
instance
? visualElement.mount(instance)
: visualElement.unmount();
}
if (externalRef) {
if (typeof externalRef === "function") {
externalRef(instance);
}
else if (is_ref_object_isRefObject(externalRef)) {
externalRef.current = instance;
}
}
},
/**
* Only pass a new ref callback to React if we've received a visual element
* factory. Otherwise we'll be mounting/remounting every time externalRef
* or other dependencies change.
*/
[visualElement]);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/utils/is-variant-label.mjs
/**
* Decides if the supplied variable is variant label
*/
function isVariantLabel(v) {
return typeof v === "string" || Array.isArray(v);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/utils/is-animation-controls.mjs
function isAnimationControls(v) {
return typeof v === "object" && typeof v.start === "function";
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/utils/is-controlling-variants.mjs
const variantProps = [
"initial",
"animate",
"exit",
"whileHover",
"whileDrag",
"whileTap",
"whileFocus",
"whileInView",
];
function isControllingVariants(props) {
return (isAnimationControls(props.animate) ||
variantProps.some((name) => isVariantLabel(props[name])));
}
function isVariantNode(props) {
return Boolean(isControllingVariants(props) || props.variants);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/context/MotionContext/utils.mjs
function getCurrentTreeVariants(props, context) {
if (isControllingVariants(props)) {
const { initial, animate } = props;
return {
initial: initial === false || isVariantLabel(initial)
? initial
: undefined,
animate: isVariantLabel(animate) ? animate : undefined,
};
}
return props.inherit !== false ? context : {};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/context/MotionContext/create.mjs
function useCreateMotionContext(props) {
const { initial, animate } = getCurrentTreeVariants(props, (0,external_React_.useContext)(MotionContext));
return (0,external_React_.useMemo)(() => ({ initial, animate }), [variantLabelsAsDependency(initial), variantLabelsAsDependency(animate)]);
}
function variantLabelsAsDependency(prop) {
return Array.isArray(prop) ? prop.join(" ") : prop;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/features/definitions.mjs
const createDefinition = (propNames) => ({
isEnabled: (props) => propNames.some((name) => !!props[name]),
});
const featureDefinitions = {
measureLayout: createDefinition(["layout", "layoutId", "drag"]),
animation: createDefinition([
"animate",
"exit",
"variants",
"whileHover",
"whileTap",
"whileFocus",
"whileDrag",
"whileInView",
]),
exit: createDefinition(["exit"]),
drag: createDefinition(["drag", "dragControls"]),
focus: createDefinition(["whileFocus"]),
hover: createDefinition(["whileHover", "onHoverStart", "onHoverEnd"]),
tap: createDefinition(["whileTap", "onTap", "onTapStart", "onTapCancel"]),
pan: createDefinition([
"onPan",
"onPanStart",
"onPanSessionStart",
"onPanEnd",
]),
inView: createDefinition([
"whileInView",
"onViewportEnter",
"onViewportLeave",
]),
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/features/load-features.mjs
function loadFeatures(features) {
for (const key in features) {
if (key === "projectionNodeConstructor") {
featureDefinitions.projectionNodeConstructor = features[key];
}
else {
featureDefinitions[key].Component = features[key];
}
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/use-constant.mjs
/**
* Creates a constant value over the lifecycle of a component.
*
* Even if `useMemo` is provided an empty array as its final argument, it doesn't offer
* a guarantee that it won't re-run for performance reasons later on. By using `useConstant`
* you can ensure that initialisers don't execute twice or more.
*/
function useConstant(init) {
const ref = (0,external_React_.useRef)(null);
if (ref.current === null) {
ref.current = init();
}
return ref.current;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/node/state.mjs
/**
* This should only ever be modified on the client otherwise it'll
* persist through server requests. If we need instanced states we
* could lazy-init via root.
*/
const globalProjectionState = {
/**
* Global flag as to whether the tree has animated since the last time
* we resized the window
*/
hasAnimatedSinceResize: true,
/**
* We set this to true once, on the first update. Any nodes added to the tree beyond that
* update will be given a `data-projection-id` attribute.
*/
hasEverUpdated: false,
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/node/id.mjs
let id = 1;
function useProjectionId() {
return useConstant(() => {
if (globalProjectionState.hasEverUpdated) {
return id++;
}
});
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/context/LayoutGroupContext.mjs
const LayoutGroupContext = (0,external_React_.createContext)({});
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/utils/VisualElementHandler.mjs
class VisualElementHandler extends external_React_.Component {
/**
* Update visual element props as soon as we know this update is going to be commited.
*/
getSnapshotBeforeUpdate() {
const { visualElement, props } = this.props;
if (visualElement)
visualElement.setProps(props);
return null;
}
componentDidUpdate() { }
render() {
return this.props.children;
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/context/SwitchLayoutGroupContext.mjs
/**
* Internal, exported only for usage in Framer
*/
const SwitchLayoutGroupContext = (0,external_React_.createContext)({});
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/utils/symbol.mjs
const motionComponentSymbol = Symbol.for("motionComponentSymbol");
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/index.mjs
/**
* Create a `motion` component.
*
* This function accepts a Component argument, which can be either a string (ie "div"
* for `motion.div`), or an actual React component.
*
* Alongside this is a config option which provides a way of rendering the provided
* component "offline", or outside the React render cycle.
*/
function motion_createMotionComponent({ preloadedFeatures, createVisualElement, projectionNodeConstructor, useRender, useVisualState, Component, }) {
preloadedFeatures && loadFeatures(preloadedFeatures);
function MotionComponent(props, externalRef) {
const configAndProps = {
...(0,external_React_.useContext)(MotionConfigContext),
...props,
layoutId: useLayoutId(props),
};
const { isStatic } = configAndProps;
let features = null;
const context = useCreateMotionContext(props);
/**
* Create a unique projection ID for this component. If a new component is added
* during a layout animation we'll use this to query the DOM and hydrate its ref early, allowing
* us to measure it as soon as any layout effect flushes pending layout animations.
*
* Performance note: It'd be better not to have to search the DOM for these elements.
* For newly-entering components it could be enough to only correct treeScale, in which
* case we could mount in a scale-correction mode. This wouldn't be enough for
* shared element transitions however. Perhaps for those we could revert to a root node
* that gets forceRendered and layout animations are triggered on its layout effect.
*/
const projectionId = isStatic ? undefined : useProjectionId();
/**
*
*/
const visualState = useVisualState(props, isStatic);
if (!isStatic && isBrowser) {
/**
* Create a VisualElement for this component. A VisualElement provides a common
* interface to renderer-specific APIs (ie DOM/Three.js etc) as well as
* providing a way of rendering to these APIs outside of the React render loop
* for more performant animations and interactions
*/
context.visualElement = useVisualElement(Component, visualState, configAndProps, createVisualElement);
/**
* Load Motion gesture and animation features. These are rendered as renderless
* components so each feature can optionally make use of React lifecycle methods.
*/
const lazyStrictMode = (0,external_React_.useContext)(LazyContext).strict;
const initialLayoutGroupConfig = (0,external_React_.useContext)(SwitchLayoutGroupContext);
if (context.visualElement) {
features = context.visualElement.loadFeatures(
// Note: Pass the full new combined props to correctly re-render dynamic feature components.
configAndProps, lazyStrictMode, preloadedFeatures, projectionId, projectionNodeConstructor ||
featureDefinitions.projectionNodeConstructor, initialLayoutGroupConfig);
}
}
/**
* The mount order and hierarchy is specific to ensure our element ref
* is hydrated by the time features fire their effects.
*/
return (external_React_.createElement(VisualElementHandler, { visualElement: context.visualElement, props: configAndProps },
features,
external_React_.createElement(MotionContext.Provider, { value: context }, useRender(Component, props, projectionId, useMotionRef(visualState, context.visualElement, externalRef), visualState, isStatic, context.visualElement))));
}
const ForwardRefComponent = (0,external_React_.forwardRef)(MotionComponent);
ForwardRefComponent[motionComponentSymbol] = Component;
return ForwardRefComponent;
}
function useLayoutId({ layoutId }) {
const layoutGroupId = (0,external_React_.useContext)(LayoutGroupContext).id;
return layoutGroupId && layoutId !== undefined
? layoutGroupId + "-" + layoutId
: layoutId;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/motion-proxy.mjs
/**
* Convert any React component into a `motion` component. The provided component
* **must** use `React.forwardRef` to the underlying DOM component you want to animate.
*
* ```jsx
* const Component = React.forwardRef((props, ref) => {
* return <div ref={ref} />
* })
*
* const MotionComponent = motion(Component)
* ```
*
* @public
*/
function createMotionProxy(createConfig) {
function custom(Component, customMotionComponentConfig = {}) {
return motion_createMotionComponent(createConfig(Component, customMotionComponentConfig));
}
if (typeof Proxy === "undefined") {
return custom;
}
/**
* A cache of generated `motion` components, e.g `motion.div`, `motion.input` etc.
* Rather than generating them anew every render.
*/
const componentCache = new Map();
return new Proxy(custom, {
/**
* Called when `motion` is referenced with a prop: `motion.div`, `motion.input` etc.
* The prop name is passed through as `key` and we can use that to generate a `motion`
* DOM component with that name.
*/
get: (_target, key) => {
/**
* If this element doesn't exist in the component cache, create it and cache.
*/
if (!componentCache.has(key)) {
componentCache.set(key, custom(key));
}
return componentCache.get(key);
},
});
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/lowercase-elements.mjs
/**
* We keep these listed seperately as we use the lowercase tag names as part
* of the runtime bundle to detect SVG components
*/
const lowercaseSVGElements = [
"animate",
"circle",
"defs",
"desc",
"ellipse",
"g",
"image",
"line",
"filter",
"marker",
"mask",
"metadata",
"path",
"pattern",
"polygon",
"polyline",
"rect",
"stop",
"switch",
"symbol",
"svg",
"text",
"tspan",
"use",
"view",
];
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/utils/is-svg-component.mjs
function isSVGComponent(Component) {
if (
/**
* If it's not a string, it's a custom React component. Currently we only support
* HTML custom React components.
*/
typeof Component !== "string" ||
/**
* If it contains a dash, the element is a custom HTML webcomponent.
*/
Component.includes("-")) {
return false;
}
else if (
/**
* If it's in our list of lowercase SVG tags, it's an SVG component
*/
lowercaseSVGElements.indexOf(Component) > -1 ||
/**
* If it contains a capital letter, it's an SVG component
*/
/[A-Z]/.test(Component)) {
return true;
}
return false;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/styles/scale-correction.mjs
const scaleCorrectors = {};
function addScaleCorrector(correctors) {
Object.assign(scaleCorrectors, correctors);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/html/utils/transform.mjs
/**
* Generate a list of every possible transform key.
*/
const transformPropOrder = [
"transformPerspective",
"x",
"y",
"z",
"translateX",
"translateY",
"translateZ",
"scale",
"scaleX",
"scaleY",
"rotate",
"rotateX",
"rotateY",
"rotateZ",
"skew",
"skewX",
"skewY",
];
/**
* A quick lookup for transform props.
*/
const transformProps = new Set(transformPropOrder);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/utils/is-forced-motion-value.mjs
function isForcedMotionValue(key, { layout, layoutId }) {
return (transformProps.has(key) ||
key.startsWith("origin") ||
((layout || layoutId !== undefined) &&
(!!scaleCorrectors[key] || key === "opacity")));
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/utils/is-motion-value.mjs
const isMotionValue = (value) => !!(value === null || value === void 0 ? void 0 : value.getVelocity);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/html/utils/build-transform.mjs
const translateAlias = {
x: "translateX",
y: "translateY",
z: "translateZ",
transformPerspective: "perspective",
};
/**
* A function to use with Array.sort to sort transform keys by their default order.
*/
const sortTransformProps = (a, b) => transformPropOrder.indexOf(a) - transformPropOrder.indexOf(b);
/**
* Build a CSS transform style from individual x/y/scale etc properties.
*
* This outputs with a default order of transforms/scales/rotations, this can be customised by
* providing a transformTemplate function.
*/
function buildTransform({ transform, transformKeys, }, { enableHardwareAcceleration = true, allowTransformNone = true, }, transformIsDefault, transformTemplate) {
// The transform string we're going to build into.
let transformString = "";
// Transform keys into their default order - this will determine the output order.
transformKeys.sort(sortTransformProps);
// Loop over each transform and build them into transformString
for (const key of transformKeys) {
transformString += `${translateAlias[key] || key}(${transform[key]}) `;
}
if (enableHardwareAcceleration && !transform.z) {
transformString += "translateZ(0)";
}
transformString = transformString.trim();
// If we have a custom `transform` template, pass our transform values and
// generated transformString to that before returning
if (transformTemplate) {
transformString = transformTemplate(transform, transformIsDefault ? "" : transformString);
}
else if (allowTransformNone && transformIsDefault) {
transformString = "none";
}
return transformString;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/utils/is-css-variable.mjs
/**
* Returns true if the provided key is a CSS variable
*/
function isCSSVariable(key) {
return key.startsWith("--");
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/value-types/get-as-type.mjs
/**
* Provided a value and a ValueType, returns the value as that value type.
*/
const getValueAsType = (value, type) => {
return type && typeof value === "number"
? type.transform(value)
: value;
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/clamp.mjs
const clamp_clamp = (min, max, v) => Math.min(Math.max(v, min), max);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/types/numbers/index.mjs
const number = {
test: (v) => typeof v === "number",
parse: parseFloat,
transform: (v) => v,
};
const alpha = {
...number,
transform: (v) => clamp_clamp(0, 1, v),
};
const scale = {
...number,
default: 1,
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/types/utils.mjs
/**
* TODO: When we move from string as a source of truth to data models
* everything in this folder should probably be referred to as models vs types
*/
// If this number is a decimal, make it just five decimal places
// to avoid exponents
const sanitize = (v) => Math.round(v * 100000) / 100000;
const floatRegex = /(-)?([\d]*\.?[\d])+/g;
const colorRegex = /(#[0-9a-f]{6}|#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))/gi;
const singleColorRegex = /^(#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))$/i;
function isString(v) {
return typeof v === "string";
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/types/numbers/units.mjs
const createUnitType = (unit) => ({
test: (v) => isString(v) && v.endsWith(unit) && v.split(" ").length === 1,
parse: parseFloat,
transform: (v) => `${v}${unit}`,
});
const degrees = createUnitType("deg");
const percent = createUnitType("%");
const px = createUnitType("px");
const vh = createUnitType("vh");
const vw = createUnitType("vw");
const progressPercentage = {
...percent,
parse: (v) => percent.parse(v) / 100,
transform: (v) => percent.transform(v * 100),
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/value-types/type-int.mjs
const type_int_int = {
...number,
transform: Math.round,
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/value-types/number.mjs
const numberValueTypes = {
// Border props
borderWidth: px,
borderTopWidth: px,
borderRightWidth: px,
borderBottomWidth: px,
borderLeftWidth: px,
borderRadius: px,
radius: px,
borderTopLeftRadius: px,
borderTopRightRadius: px,
borderBottomRightRadius: px,
borderBottomLeftRadius: px,
// Positioning props
width: px,
maxWidth: px,
height: px,
maxHeight: px,
size: px,
top: px,
right: px,
bottom: px,
left: px,
// Spacing props
padding: px,
paddingTop: px,
paddingRight: px,
paddingBottom: px,
paddingLeft: px,
margin: px,
marginTop: px,
marginRight: px,
marginBottom: px,
marginLeft: px,
// Transform props
rotate: degrees,
rotateX: degrees,
rotateY: degrees,
rotateZ: degrees,
scale: scale,
scaleX: scale,
scaleY: scale,
scaleZ: scale,
skew: degrees,
skewX: degrees,
skewY: degrees,
distance: px,
translateX: px,
translateY: px,
translateZ: px,
x: px,
y: px,
z: px,
perspective: px,
transformPerspective: px,
opacity: alpha,
originX: progressPercentage,
originY: progressPercentage,
originZ: px,
// Misc
zIndex: type_int_int,
// SVG
fillOpacity: alpha,
strokeOpacity: alpha,
numOctaves: type_int_int,
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/html/utils/build-styles.mjs
function buildHTMLStyles(state, latestValues, options, transformTemplate) {
const { style, vars, transform, transformKeys, transformOrigin } = state;
transformKeys.length = 0;
// Track whether we encounter any transform or transformOrigin values.
let hasTransform = false;
let hasTransformOrigin = false;
// Does the calculated transform essentially equal "none"?
let transformIsNone = true;
/**
* Loop over all our latest animated values and decide whether to handle them
* as a style or CSS variable.
*
* Transforms and transform origins are kept seperately for further processing.
*/
for (const key in latestValues) {
const value = latestValues[key];
/**
* If this is a CSS variable we don't do any further processing.
*/
if (isCSSVariable(key)) {
vars[key] = value;
continue;
}
// Convert the value to its default value type, ie 0 -> "0px"
const valueType = numberValueTypes[key];
const valueAsType = getValueAsType(value, valueType);
if (transformProps.has(key)) {
// If this is a transform, flag to enable further transform processing
hasTransform = true;
transform[key] = valueAsType;
transformKeys.push(key);
// If we already know we have a non-default transform, early return
if (!transformIsNone)
continue;
// Otherwise check to see if this is a default transform
if (value !== (valueType.default || 0))
transformIsNone = false;
}
else if (key.startsWith("origin")) {
// If this is a transform origin, flag and enable further transform-origin processing
hasTransformOrigin = true;
transformOrigin[key] = valueAsType;
}
else {
style[key] = valueAsType;
}
}
if (!latestValues.transform) {
if (hasTransform || transformTemplate) {
style.transform = buildTransform(state, options, transformIsNone, transformTemplate);
}
else if (style.transform) {
/**
* If we have previously created a transform but currently don't have any,
* reset transform style to none.
*/
style.transform = "none";
}
}
/**
* Build a transformOrigin style. Uses the same defaults as the browser for
* undefined origins.
*/
if (hasTransformOrigin) {
const { originX = "50%", originY = "50%", originZ = 0, } = transformOrigin;
style.transformOrigin = `${originX} ${originY} ${originZ}`;
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/html/utils/create-render-state.mjs
const createHtmlRenderState = () => ({
style: {},
transform: {},
transformKeys: [],
transformOrigin: {},
vars: {},
});
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/html/use-props.mjs
function copyRawValuesOnly(target, source, props) {
for (const key in source) {
if (!isMotionValue(source[key]) && !isForcedMotionValue(key, props)) {
target[key] = source[key];
}
}
}
function useInitialMotionValues({ transformTemplate }, visualState, isStatic) {
return (0,external_React_.useMemo)(() => {
const state = createHtmlRenderState();
buildHTMLStyles(state, visualState, { enableHardwareAcceleration: !isStatic }, transformTemplate);
return Object.assign({}, state.vars, state.style);
}, [visualState]);
}
function useStyle(props, visualState, isStatic) {
const styleProp = props.style || {};
const style = {};
/**
* Copy non-Motion Values straight into style
*/
copyRawValuesOnly(style, styleProp, props);
Object.assign(style, useInitialMotionValues(props, visualState, isStatic));
return props.transformValues ? props.transformValues(style) : style;
}
function useHTMLProps(props, visualState, isStatic) {
// The `any` isn't ideal but it is the type of createElement props argument
const htmlProps = {};
const style = useStyle(props, visualState, isStatic);
if (props.drag && props.dragListener !== false) {
// Disable the ghost element when a user drags
htmlProps.draggable = false;
// Disable text selection
style.userSelect =
style.WebkitUserSelect =
style.WebkitTouchCallout =
"none";
// Disable scrolling on the draggable direction
style.touchAction =
props.drag === true
? "none"
: `pan-${props.drag === "x" ? "y" : "x"}`;
}
htmlProps.style = style;
return htmlProps;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/utils/valid-prop.mjs
const animationProps = [
"animate",
"exit",
"variants",
"whileHover",
"whileTap",
"whileFocus",
"whileDrag",
"whileInView",
];
const tapProps = ["whileTap", "onTap", "onTapStart", "onTapCancel"];
const panProps = ["onPan", "onPanStart", "onPanSessionStart", "onPanEnd"];
const inViewProps = [
"whileInView",
"onViewportEnter",
"onViewportLeave",
"viewport",
];
/**
* A list of all valid MotionProps.
*
* @privateRemarks
* This doesn't throw if a `MotionProp` name is missing - it should.
*/
const validMotionProps = new Set([
"initial",
"style",
"values",
"variants",
"transition",
"transformTemplate",
"transformValues",
"custom",
"inherit",
"layout",
"layoutId",
"layoutDependency",
"onLayoutAnimationStart",
"onLayoutAnimationComplete",
"onLayoutMeasure",
"onBeforeLayoutMeasure",
"onAnimationStart",
"onAnimationComplete",
"onUpdate",
"onDragStart",
"onDrag",
"onDragEnd",
"onMeasureDragConstraints",
"onDirectionLock",
"onDragTransitionEnd",
"drag",
"dragControls",
"dragListener",
"dragConstraints",
"dragDirectionLock",
"dragSnapToOrigin",
"_dragX",
"_dragY",
"dragElastic",
"dragMomentum",
"dragPropagation",
"dragTransition",
"onHoverStart",
"onHoverEnd",
"layoutScroll",
...inViewProps,
...tapProps,
...animationProps,
...panProps,
]);
/**
* Check whether a prop name is a valid `MotionProp` key.
*
* @param key - Name of the property to check
* @returns `true` is key is a valid `MotionProp`.
*
* @public
*/
function isValidMotionProp(key) {
return validMotionProps.has(key);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/utils/filter-props.mjs
let shouldForward = (key) => !isValidMotionProp(key);
function loadExternalIsValidProp(isValidProp) {
if (!isValidProp)
return;
// Explicitly filter our events
shouldForward = (key) => key.startsWith("on") ? !isValidMotionProp(key) : isValidProp(key);
}
/**
* Emotion and Styled Components both allow users to pass through arbitrary props to their components
* to dynamically generate CSS. They both use the `@emotion/is-prop-valid` package to determine which
* of these should be passed to the underlying DOM node.
*
* However, when styling a Motion component `styled(motion.div)`, both packages pass through *all* props
* as it's seen as an arbitrary component rather than a DOM node. Motion only allows arbitrary props
* passed through the `custom` prop so it doesn't *need* the payload or computational overhead of
* `@emotion/is-prop-valid`, however to fix this problem we need to use it.
*
* By making it an optionalDependency we can offer this functionality only in the situations where it's
* actually required.
*/
try {
/**
* We attempt to import this package but require won't be defined in esm environments, in that case
* isPropValid will have to be provided via `MotionContext`. In a 6.0.0 this should probably be removed
* in favour of explicit injection.
*/
loadExternalIsValidProp(require("@emotion/is-prop-valid").default);
}
catch (_a) {
// We don't need to actually do anything here - the fallback is the existing `isPropValid`.
}
function filterProps(props, isDom, forwardMotionProps) {
const filteredProps = {};
for (const key in props) {
if (shouldForward(key) ||
(forwardMotionProps === true && isValidMotionProp(key)) ||
(!isDom && !isValidMotionProp(key)) ||
// If trying to use native HTML drag events, forward drag listeners
(props["draggable"] && key.startsWith("onDrag"))) {
filteredProps[key] = props[key];
}
}
return filteredProps;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/utils/transform-origin.mjs
function calcOrigin(origin, offset, size) {
return typeof origin === "string"
? origin
: px.transform(offset + size * origin);
}
/**
* The SVG transform origin defaults are different to CSS and is less intuitive,
* so we use the measured dimensions of the SVG to reconcile these.
*/
function calcSVGTransformOrigin(dimensions, originX, originY) {
const pxOriginX = calcOrigin(originX, dimensions.x, dimensions.width);
const pxOriginY = calcOrigin(originY, dimensions.y, dimensions.height);
return `${pxOriginX} ${pxOriginY}`;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/utils/path.mjs
const dashKeys = {
offset: "stroke-dashoffset",
array: "stroke-dasharray",
};
const camelKeys = {
offset: "strokeDashoffset",
array: "strokeDasharray",
};
/**
* Build SVG path properties. Uses the path's measured length to convert
* our custom pathLength, pathSpacing and pathOffset into stroke-dashoffset
* and stroke-dasharray attributes.
*
* This function is mutative to reduce per-frame GC.
*/
function buildSVGPath(attrs, length, spacing = 1, offset = 0, useDashCase = true) {
// Normalise path length by setting SVG attribute pathLength to 1
attrs.pathLength = 1;
// We use dash case when setting attributes directly to the DOM node and camel case
// when defining props on a React component.
const keys = useDashCase ? dashKeys : camelKeys;
// Build the dash offset
attrs[keys.offset] = px.transform(-offset);
// Build the dash array
const pathLength = px.transform(length);
const pathSpacing = px.transform(spacing);
attrs[keys.array] = `${pathLength} ${pathSpacing}`;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/utils/build-attrs.mjs
/**
* Build SVG visual attrbutes, like cx and style.transform
*/
function buildSVGAttrs(state, { attrX, attrY, originX, originY, pathLength, pathSpacing = 1, pathOffset = 0,
// This is object creation, which we try to avoid per-frame.
...latest }, options, isSVGTag, transformTemplate) {
buildHTMLStyles(state, latest, options, transformTemplate);
/**
* For svg tags we just want to make sure viewBox is animatable and treat all the styles
* as normal HTML tags.
*/
if (isSVGTag) {
if (state.style.viewBox) {
state.attrs.viewBox = state.style.viewBox;
}
return;
}
state.attrs = state.style;
state.style = {};
const { attrs, style, dimensions } = state;
/**
* However, we apply transforms as CSS transforms. So if we detect a transform we take it from attrs
* and copy it into style.
*/
if (attrs.transform) {
if (dimensions)
style.transform = attrs.transform;
delete attrs.transform;
}
// Parse transformOrigin
if (dimensions &&
(originX !== undefined || originY !== undefined || style.transform)) {
style.transformOrigin = calcSVGTransformOrigin(dimensions, originX !== undefined ? originX : 0.5, originY !== undefined ? originY : 0.5);
}
// Treat x/y not as shortcuts but as actual attributes
if (attrX !== undefined)
attrs.x = attrX;
if (attrY !== undefined)
attrs.y = attrY;
// Build SVG path if one has been defined
if (pathLength !== undefined) {
buildSVGPath(attrs, pathLength, pathSpacing, pathOffset, false);
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/utils/create-render-state.mjs
const createSvgRenderState = () => ({
...createHtmlRenderState(),
attrs: {},
});
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/utils/is-svg-tag.mjs
const isSVGTag = (tag) => typeof tag === "string" && tag.toLowerCase() === "svg";
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/use-props.mjs
function useSVGProps(props, visualState, _isStatic, Component) {
const visualProps = (0,external_React_.useMemo)(() => {
const state = createSvgRenderState();
buildSVGAttrs(state, visualState, { enableHardwareAcceleration: false }, isSVGTag(Component), props.transformTemplate);
return {
...state.attrs,
style: { ...state.style },
};
}, [visualState]);
if (props.style) {
const rawStyles = {};
copyRawValuesOnly(rawStyles, props.style, props);
visualProps.style = { ...rawStyles, ...visualProps.style };
}
return visualProps;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/use-render.mjs
function createUseRender(forwardMotionProps = false) {
const useRender = (Component, props, projectionId, ref, { latestValues }, isStatic) => {
const useVisualProps = isSVGComponent(Component)
? useSVGProps
: useHTMLProps;
const visualProps = useVisualProps(props, latestValues, isStatic, Component);
const filteredProps = filterProps(props, typeof Component === "string", forwardMotionProps);
const elementProps = {
...filteredProps,
...visualProps,
ref,
};
if (projectionId) {
elementProps["data-projection-id"] = projectionId;
}
return (0,external_React_.createElement)(Component, elementProps);
};
return useRender;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/utils/camel-to-dash.mjs
/**
* Convert camelCase to dash-case properties.
*/
const camelToDash = (str) => str.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/html/utils/render.mjs
function renderHTML(element, { style, vars }, styleProp, projection) {
Object.assign(element.style, style, projection && projection.getProjectionStyles(styleProp));
// Loop over any CSS variables and assign those.
for (const key in vars) {
element.style.setProperty(key, vars[key]);
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/utils/camel-case-attrs.mjs
/**
* A set of attribute names that are always read/written as camel case.
*/
const camelCaseAttributes = new Set([
"baseFrequency",
"diffuseConstant",
"kernelMatrix",
"kernelUnitLength",
"keySplines",
"keyTimes",
"limitingConeAngle",
"markerHeight",
"markerWidth",
"numOctaves",
"targetX",
"targetY",
"surfaceScale",
"specularConstant",
"specularExponent",
"stdDeviation",
"tableValues",
"viewBox",
"gradientTransform",
"pathLength",
"startOffset",
"textLength",
"lengthAdjust",
]);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/utils/render.mjs
function renderSVG(element, renderState, _styleProp, projection) {
renderHTML(element, renderState, undefined, projection);
for (const key in renderState.attrs) {
element.setAttribute(!camelCaseAttributes.has(key) ? camelToDash(key) : key, renderState.attrs[key]);
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/html/utils/scrape-motion-values.mjs
function scrapeMotionValuesFromProps(props) {
const { style } = props;
const newValues = {};
for (const key in style) {
if (isMotionValue(style[key]) || isForcedMotionValue(key, props)) {
newValues[key] = style[key];
}
}
return newValues;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/utils/scrape-motion-values.mjs
function scrape_motion_values_scrapeMotionValuesFromProps(props) {
const newValues = scrapeMotionValuesFromProps(props);
for (const key in props) {
if (isMotionValue(props[key])) {
const targetKey = key === "x" || key === "y" ? "attr" + key.toUpperCase() : key;
newValues[targetKey] = props[key];
}
}
return newValues;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/utils/resolve-variants.mjs
function resolveVariantFromProps(props, definition, custom, currentValues = {}, currentVelocity = {}) {
/**
* If the variant definition is a function, resolve.
*/
if (typeof definition === "function") {
definition = definition(custom !== undefined ? custom : props.custom, currentValues, currentVelocity);
}
/**
* If the variant definition is a variant label, or
* the function returned a variant label, resolve.
*/
if (typeof definition === "string") {
definition = props.variants && props.variants[definition];
}
/**
* At this point we've resolved both functions and variant labels,
* but the resolved variant label might itself have been a function.
* If so, resolve. This can only have returned a valid target object.
*/
if (typeof definition === "function") {
definition = definition(custom !== undefined ? custom : props.custom, currentValues, currentVelocity);
}
return definition;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/utils/is-keyframes-target.mjs
const isKeyframesTarget = (v) => {
return Array.isArray(v);
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/resolve-value.mjs
const isCustomValue = (v) => {
return Boolean(v && typeof v === "object" && v.mix && v.toValue);
};
const resolveFinalValueInKeyframes = (v) => {
// TODO maybe throw if v.length - 1 is placeholder token?
return isKeyframesTarget(v) ? v[v.length - 1] || 0 : v;
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/utils/resolve-motion-value.mjs
/**
* If the provided value is a MotionValue, this returns the actual value, otherwise just the value itself
*
* TODO: Remove and move to library
*/
function resolveMotionValue(value) {
const unwrappedValue = isMotionValue(value) ? value.get() : value;
return isCustomValue(unwrappedValue)
? unwrappedValue.toValue()
: unwrappedValue;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/utils/use-visual-state.mjs
function makeState({ scrapeMotionValuesFromProps, createRenderState, onMount, }, props, context, presenceContext) {
const state = {
latestValues: makeLatestValues(props, context, presenceContext, scrapeMotionValuesFromProps),
renderState: createRenderState(),
};
if (onMount) {
state.mount = (instance) => onMount(props, instance, state);
}
return state;
}
const makeUseVisualState = (config) => (props, isStatic) => {
const context = (0,external_React_.useContext)(MotionContext);
const presenceContext = (0,external_React_.useContext)(PresenceContext_PresenceContext);
const make = () => makeState(config, props, context, presenceContext);
return isStatic ? make() : useConstant(make);
};
function makeLatestValues(props, context, presenceContext, scrapeMotionValues) {
const values = {};
const motionValues = scrapeMotionValues(props);
for (const key in motionValues) {
values[key] = resolveMotionValue(motionValues[key]);
}
let { initial, animate } = props;
const isControllingVariants$1 = isControllingVariants(props);
const isVariantNode$1 = isVariantNode(props);
if (context &&
isVariantNode$1 &&
!isControllingVariants$1 &&
props.inherit !== false) {
if (initial === undefined)
initial = context.initial;
if (animate === undefined)
animate = context.animate;
}
let isInitialAnimationBlocked = presenceContext
? presenceContext.initial === false
: false;
isInitialAnimationBlocked = isInitialAnimationBlocked || initial === false;
const variantToSet = isInitialAnimationBlocked ? animate : initial;
if (variantToSet &&
typeof variantToSet !== "boolean" &&
!isAnimationControls(variantToSet)) {
const list = Array.isArray(variantToSet) ? variantToSet : [variantToSet];
list.forEach((definition) => {
const resolved = resolveVariantFromProps(props, definition);
if (!resolved)
return;
const { transitionEnd, transition, ...target } = resolved;
for (const key in target) {
let valueTarget = target[key];
if (Array.isArray(valueTarget)) {
/**
* Take final keyframe if the initial animation is blocked because
* we want to initialise at the end of that blocked animation.
*/
const index = isInitialAnimationBlocked
? valueTarget.length - 1
: 0;
valueTarget = valueTarget[index];
}
if (valueTarget !== null) {
values[key] = valueTarget;
}
}
for (const key in transitionEnd)
values[key] = transitionEnd[key];
});
}
return values;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/config-motion.mjs
const svgMotionConfig = {
useVisualState: makeUseVisualState({
scrapeMotionValuesFromProps: scrape_motion_values_scrapeMotionValuesFromProps,
createRenderState: createSvgRenderState,
onMount: (props, instance, { renderState, latestValues }) => {
try {
renderState.dimensions =
typeof instance.getBBox ===
"function"
? instance.getBBox()
: instance.getBoundingClientRect();
}
catch (e) {
// Most likely trying to measure an unrendered element under Firefox
renderState.dimensions = {
x: 0,
y: 0,
width: 0,
height: 0,
};
}
buildSVGAttrs(renderState, latestValues, { enableHardwareAcceleration: false }, isSVGTag(instance.tagName), props.transformTemplate);
renderSVG(instance, renderState);
},
}),
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/html/config-motion.mjs
const htmlMotionConfig = {
useVisualState: makeUseVisualState({
scrapeMotionValuesFromProps: scrapeMotionValuesFromProps,
createRenderState: createHtmlRenderState,
}),
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/utils/create-config.mjs
function create_config_createDomMotionConfig(Component, { forwardMotionProps = false }, preloadedFeatures, createVisualElement, projectionNodeConstructor) {
const baseConfig = isSVGComponent(Component)
? svgMotionConfig
: htmlMotionConfig;
return {
...baseConfig,
preloadedFeatures,
useRender: createUseRender(forwardMotionProps),
createVisualElement,
projectionNodeConstructor,
Component,
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/utils/types.mjs
var AnimationType;
(function (AnimationType) {
AnimationType["Animate"] = "animate";
AnimationType["Hover"] = "whileHover";
AnimationType["Tap"] = "whileTap";
AnimationType["Drag"] = "whileDrag";
AnimationType["Focus"] = "whileFocus";
AnimationType["InView"] = "whileInView";
AnimationType["Exit"] = "exit";
})(AnimationType || (AnimationType = {}));
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/events/use-dom-event.mjs
function addDomEvent(target, eventName, handler, options = { passive: true }) {
target.addEventListener(eventName, handler, options);
return () => target.removeEventListener(eventName, handler);
}
/**
* Attaches an event listener directly to the provided DOM element.
*
* Bypassing React's event system can be desirable, for instance when attaching non-passive
* event handlers.
*
* ```jsx
* const ref = useRef(null)
*
* useDomEvent(ref, 'wheel', onWheel, { passive: false })
*
* return <div ref={ref} />
* ```
*
* @param ref - React.RefObject that's been provided to the element you want to bind the listener to.
* @param eventName - Name of the event you want listen for.
* @param handler - Function to fire when receiving the event.
* @param options - Options to pass to `Event.addEventListener`.
*
* @public
*/
function useDomEvent(ref, eventName, handler, options) {
(0,external_React_.useEffect)(() => {
const element = ref.current;
if (handler && element) {
return addDomEvent(element, eventName, handler, options);
}
}, [ref, eventName, handler, options]);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/gestures/use-focus-gesture.mjs
/**
*
* @param props
* @param ref
* @internal
*/
function useFocusGesture({ whileFocus, visualElement, }) {
const { animationState } = visualElement;
const onFocus = () => {
animationState && animationState.setActive(AnimationType.Focus, true);
};
const onBlur = () => {
animationState && animationState.setActive(AnimationType.Focus, false);
};
useDomEvent(visualElement, "focus", whileFocus ? onFocus : undefined);
useDomEvent(visualElement, "blur", whileFocus ? onBlur : undefined);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/gestures/utils/event-type.mjs
function isMouseEvent(event) {
// PointerEvent inherits from MouseEvent so we can't use a straight instanceof check.
if (typeof PointerEvent !== "undefined" && event instanceof PointerEvent) {
return !!(event.pointerType === "mouse");
}
return event instanceof MouseEvent;
}
function isTouchEvent(event) {
const hasTouches = !!event.touches;
return hasTouches;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/events/event-info.mjs
/**
* Filters out events not attached to the primary pointer (currently left mouse button)
* @param eventHandler
*/
function filterPrimaryPointer(eventHandler) {
return (event) => {
const isMouseEvent = event instanceof MouseEvent;
const isPrimaryPointer = !isMouseEvent ||
(isMouseEvent && event.button === 0);
if (isPrimaryPointer) {
eventHandler(event);
}
};
}
const defaultPagePoint = { pageX: 0, pageY: 0 };
function pointFromTouch(e, pointType = "page") {
const primaryTouch = e.touches[0] || e.changedTouches[0];
const point = primaryTouch || defaultPagePoint;
return {
x: point[pointType + "X"],
y: point[pointType + "Y"],
};
}
function pointFromMouse(point, pointType = "page") {
return {
x: point[pointType + "X"],
y: point[pointType + "Y"],
};
}
function extractEventInfo(event, pointType = "page") {
return {
point: isTouchEvent(event)
? pointFromTouch(event, pointType)
: pointFromMouse(event, pointType),
};
}
const wrapHandler = (handler, shouldFilterPrimaryPointer = false) => {
const listener = (event) => handler(event, extractEventInfo(event));
return shouldFilterPrimaryPointer
? filterPrimaryPointer(listener)
: listener;
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/events/utils.mjs
// We check for event support via functions in case they've been mocked by a testing suite.
const supportsPointerEvents = () => isBrowser && window.onpointerdown === null;
const supportsTouchEvents = () => isBrowser && window.ontouchstart === null;
const supportsMouseEvents = () => isBrowser && window.onmousedown === null;
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/events/use-pointer-event.mjs
const mouseEventNames = {
pointerdown: "mousedown",
pointermove: "mousemove",
pointerup: "mouseup",
pointercancel: "mousecancel",
pointerover: "mouseover",
pointerout: "mouseout",
pointerenter: "mouseenter",
pointerleave: "mouseleave",
};
const touchEventNames = {
pointerdown: "touchstart",
pointermove: "touchmove",
pointerup: "touchend",
pointercancel: "touchcancel",
};
function getPointerEventName(name) {
if (supportsPointerEvents()) {
return name;
}
else if (supportsTouchEvents()) {
return touchEventNames[name];
}
else if (supportsMouseEvents()) {
return mouseEventNames[name];
}
return name;
}
function addPointerEvent(target, eventName, handler, options) {
return addDomEvent(target, getPointerEventName(eventName), wrapHandler(handler, eventName === "pointerdown"), options);
}
function usePointerEvent(ref, eventName, handler, options) {
return useDomEvent(ref, getPointerEventName(eventName), handler && wrapHandler(handler, eventName === "pointerdown"), options);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/gestures/drag/utils/lock.mjs
function createLock(name) {
let lock = null;
return () => {
const openLock = () => {
lock = null;
};
if (lock === null) {
lock = name;
return openLock;
}
return false;
};
}
const globalHorizontalLock = createLock("dragHorizontal");
const globalVerticalLock = createLock("dragVertical");
function getGlobalLock(drag) {
let lock = false;
if (drag === "y") {
lock = globalVerticalLock();
}
else if (drag === "x") {
lock = globalHorizontalLock();
}
else {
const openHorizontal = globalHorizontalLock();
const openVertical = globalVerticalLock();
if (openHorizontal && openVertical) {
lock = () => {
openHorizontal();
openVertical();
};
}
else {
// Release the locks because we don't use them
if (openHorizontal)
openHorizontal();
if (openVertical)
openVertical();
}
}
return lock;
}
function isDragActive() {
// Check the gesture lock - if we get it, it means no drag gesture is active
// and we can safely fire the tap gesture.
const openGestureLock = getGlobalLock(true);
if (!openGestureLock)
return true;
openGestureLock();
return false;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/gestures/use-hover-gesture.mjs
function createHoverEvent(visualElement, isActive, callback) {
return (event, info) => {
if (!isMouseEvent(event) || isDragActive())
return;
/**
* Ensure we trigger animations before firing event callback
*/
if (visualElement.animationState) {
visualElement.animationState.setActive(AnimationType.Hover, isActive);
}
callback && callback(event, info);
};
}
function useHoverGesture({ onHoverStart, onHoverEnd, whileHover, visualElement, }) {
usePointerEvent(visualElement, "pointerenter", onHoverStart || whileHover
? createHoverEvent(visualElement, true, onHoverStart)
: undefined, { passive: !onHoverStart });
usePointerEvent(visualElement, "pointerleave", onHoverEnd || whileHover
? createHoverEvent(visualElement, false, onHoverEnd)
: undefined, { passive: !onHoverEnd });
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/gestures/utils/is-node-or-child.mjs
/**
* Recursively traverse up the tree to check whether the provided child node
* is the parent or a descendant of it.
*
* @param parent - Element to find
* @param child - Element to test against parent
*/
const isNodeOrChild = (parent, child) => {
if (!child) {
return false;
}
else if (parent === child) {
return true;
}
else {
return isNodeOrChild(parent, child.parentElement);
}
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/use-unmount-effect.mjs
function useUnmountEffect(callback) {
return (0,external_React_.useEffect)(() => () => callback(), []);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/pipe.mjs
/**
* Pipe
* Compose other transformers to run linearily
* pipe(min(20), max(40))
* @param {...functions} transformers
* @return {function}
*/
const combineFunctions = (a, b) => (v) => b(a(v));
const pipe = (...transformers) => transformers.reduce(combineFunctions);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/gestures/use-tap-gesture.mjs
/**
* @param handlers -
* @internal
*/
function useTapGesture({ onTap, onTapStart, onTapCancel, whileTap, visualElement, }) {
const hasPressListeners = onTap || onTapStart || onTapCancel || whileTap;
const isPressing = (0,external_React_.useRef)(false);
const cancelPointerEndListeners = (0,external_React_.useRef)(null);
/**
* Only set listener to passive if there are no external listeners.
*/
const eventOptions = {
passive: !(onTapStart || onTap || onTapCancel || onPointerDown),
};
function removePointerEndListener() {
cancelPointerEndListeners.current && cancelPointerEndListeners.current();
cancelPointerEndListeners.current = null;
}
function checkPointerEnd() {
removePointerEndListener();
isPressing.current = false;
visualElement.animationState &&
visualElement.animationState.setActive(AnimationType.Tap, false);
return !isDragActive();
}
function onPointerUp(event, info) {
if (!checkPointerEnd())
return;
/**
* We only count this as a tap gesture if the event.target is the same
* as, or a child of, this component's element
*/
!isNodeOrChild(visualElement.current, event.target)
? onTapCancel && onTapCancel(event, info)
: onTap && onTap(event, info);
}
function onPointerCancel(event, info) {
if (!checkPointerEnd())
return;
onTapCancel && onTapCancel(event, info);
}
function onPointerDown(event, info) {
removePointerEndListener();
if (isPressing.current)
return;
isPressing.current = true;
cancelPointerEndListeners.current = pipe(addPointerEvent(window, "pointerup", onPointerUp, eventOptions), addPointerEvent(window, "pointercancel", onPointerCancel, eventOptions));
/**
* Ensure we trigger animations before firing event callback
*/
visualElement.animationState &&
visualElement.animationState.setActive(AnimationType.Tap, true);
onTapStart && onTapStart(event, info);
}
usePointerEvent(visualElement, "pointerdown", hasPressListeners ? onPointerDown : undefined, eventOptions);
useUnmountEffect(removePointerEndListener);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/process.mjs
/**
* Browser-safe usage of process
*/
const defaultEnvironment = "production";
const env = typeof process === "undefined" || process.env === undefined
? defaultEnvironment
: "production" || 0;
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/warn-once.mjs
const warned = new Set();
function warnOnce(condition, message, element) {
if (condition || warned.has(message))
return;
console.warn(message);
if (element)
console.warn(element);
warned.add(message);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/features/viewport/observers.mjs
/**
* Map an IntersectionHandler callback to an element. We only ever make one handler for one
* element, so even though these handlers might all be triggered by different
* observers, we can keep them in the same map.
*/
const observerCallbacks = new WeakMap();
/**
* Multiple observers can be created for multiple element/document roots. Each with
* different settings. So here we store dictionaries of observers to each root,
* using serialised settings (threshold/margin) as lookup keys.
*/
const observers = new WeakMap();
const fireObserverCallback = (entry) => {
const callback = observerCallbacks.get(entry.target);
callback && callback(entry);
};
const fireAllObserverCallbacks = (entries) => {
entries.forEach(fireObserverCallback);
};
function initIntersectionObserver({ root, ...options }) {
const lookupRoot = root || document;
/**
* If we don't have an observer lookup map for this root, create one.
*/
if (!observers.has(lookupRoot)) {
observers.set(lookupRoot, {});
}
const rootObservers = observers.get(lookupRoot);
const key = JSON.stringify(options);
/**
* If we don't have an observer for this combination of root and settings,
* create one.
*/
if (!rootObservers[key]) {
rootObservers[key] = new IntersectionObserver(fireAllObserverCallbacks, { root, ...options });
}
return rootObservers[key];
}
function observeIntersection(element, options, callback) {
const rootInteresectionObserver = initIntersectionObserver(options);
observerCallbacks.set(element, callback);
rootInteresectionObserver.observe(element);
return () => {
observerCallbacks.delete(element);
rootInteresectionObserver.unobserve(element);
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/features/viewport/use-viewport.mjs
function useViewport({ visualElement, whileInView, onViewportEnter, onViewportLeave, viewport = {}, }) {
const state = (0,external_React_.useRef)({
hasEnteredView: false,
isInView: false,
});
let shouldObserve = Boolean(whileInView || onViewportEnter || onViewportLeave);
if (viewport.once && state.current.hasEnteredView)
shouldObserve = false;
const useObserver = typeof IntersectionObserver === "undefined"
? useMissingIntersectionObserver
: useIntersectionObserver;
useObserver(shouldObserve, state.current, visualElement, viewport);
}
const thresholdNames = {
some: 0,
all: 1,
};
function useIntersectionObserver(shouldObserve, state, visualElement, { root, margin: rootMargin, amount = "some", once }) {
(0,external_React_.useEffect)(() => {
if (!shouldObserve || !visualElement.current)
return;
const options = {
root: root === null || root === void 0 ? void 0 : root.current,
rootMargin,
threshold: typeof amount === "number" ? amount : thresholdNames[amount],
};
const intersectionCallback = (entry) => {
const { isIntersecting } = entry;
/**
* If there's been no change in the viewport state, early return.
*/
if (state.isInView === isIntersecting)
return;
state.isInView = isIntersecting;
/**
* Handle hasEnteredView. If this is only meant to run once, and
* element isn't visible, early return. Otherwise set hasEnteredView to true.
*/
if (once && !isIntersecting && state.hasEnteredView) {
return;
}
else if (isIntersecting) {
state.hasEnteredView = true;
}
if (visualElement.animationState) {
visualElement.animationState.setActive(AnimationType.InView, isIntersecting);
}
/**
* Use the latest committed props rather than the ones in scope
* when this observer is created
*/
const props = visualElement.getProps();
const callback = isIntersecting
? props.onViewportEnter
: props.onViewportLeave;
callback && callback(entry);
};
return observeIntersection(visualElement.current, options, intersectionCallback);
}, [shouldObserve, root, rootMargin, amount]);
}
/**
* If IntersectionObserver is missing, we activate inView and fire onViewportEnter
* on mount. This way, the page will be in the state the author expects users
* to see it in for everyone.
*/
function useMissingIntersectionObserver(shouldObserve, state, visualElement, { fallback = true }) {
(0,external_React_.useEffect)(() => {
if (!shouldObserve || !fallback)
return;
if (env !== "production") {
warnOnce(false, "IntersectionObserver not available on this device. whileInView animations will trigger on mount.");
}
/**
* Fire this in an rAF because, at this point, the animation state
* won't have flushed for the first time and there's certain logic in
* there that behaves differently on the initial animation.
*
* This hook should be quite rarely called so setting this in an rAF
* is preferred to changing the behaviour of the animation state.
*/
requestAnimationFrame(() => {
state.hasEnteredView = true;
const { onViewportEnter } = visualElement.getProps();
onViewportEnter && onViewportEnter(null);
if (visualElement.animationState) {
visualElement.animationState.setActive(AnimationType.InView, true);
}
});
}, [shouldObserve]);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/utils/make-renderless-component.mjs
const makeRenderlessComponent = (hook) => (props) => {
hook(props);
return null;
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/features/gestures.mjs
const gestureAnimations = {
inView: makeRenderlessComponent(useViewport),
tap: makeRenderlessComponent(useTapGesture),
focus: makeRenderlessComponent(useFocusGesture),
hover: makeRenderlessComponent(useHoverGesture),
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/components/AnimatePresence/use-presence.mjs
/**
* When a component is the child of `AnimatePresence`, it can use `usePresence`
* to access information about whether it's still present in the React tree.
*
* ```jsx
* import { usePresence } from "framer-motion"
*
* export const Component = () => {
* const [isPresent, safeToRemove] = usePresence()
*
* useEffect(() => {
* !isPresent && setTimeout(safeToRemove, 1000)
* }, [isPresent])
*
* return <div />
* }
* ```
*
* If `isPresent` is `false`, it means that a component has been removed the tree, but
* `AnimatePresence` won't really remove it until `safeToRemove` has been called.
*
* @public
*/
function usePresence() {
const context = (0,external_React_.useContext)(PresenceContext_PresenceContext);
if (context === null)
return [true, null];
const { isPresent, onExitComplete, register } = context;
// It's safe to call the following hooks conditionally (after an early return) because the context will always
// either be null or non-null for the lifespan of the component.
// Replace with useId when released in React
const id = (0,external_React_.useId)();
(0,external_React_.useEffect)(() => register(id), []);
const safeToRemove = () => onExitComplete && onExitComplete(id);
return !isPresent && onExitComplete ? [false, safeToRemove] : [true];
}
/**
* Similar to `usePresence`, except `useIsPresent` simply returns whether or not the component is present.
* There is no `safeToRemove` function.
*
* ```jsx
* import { useIsPresent } from "framer-motion"
*
* export const Component = () => {
* const isPresent = useIsPresent()
*
* useEffect(() => {
* !isPresent && console.log("I've been removed!")
* }, [isPresent])
*
* return <div />
* }
* ```
*
* @public
*/
function useIsPresent() {
return isPresent(useContext(PresenceContext));
}
function isPresent(context) {
return context === null ? true : context.isPresent;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/shallow-compare.mjs
function shallowCompare(next, prev) {
if (!Array.isArray(prev))
return false;
const prevLength = prev.length;
if (prevLength !== next.length)
return false;
for (let i = 0; i < prevLength; i++) {
if (prev[i] !== next[i])
return false;
}
return true;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/is-numerical-string.mjs
/**
* Check if value is a numerical string, ie a string that is purely a number eg "100" or "-100.1"
*/
const isNumericalString = (v) => /^\-?\d*\.?\d+$/.test(v);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/is-zero-value-string.mjs
/**
* Check if the value is a zero value string like "0px" or "0%"
*/
const isZeroValueString = (v) => /^0[^.\s]+$/.test(v);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/frameloop/data.mjs
const frameData = {
delta: 0,
timestamp: 0,
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/frameloop/on-next-frame.mjs
/*
Detect and load appropriate clock setting for the execution environment
*/
const defaultTimestep = (1 / 60) * 1000;
const getCurrentTime = typeof performance !== "undefined"
? () => performance.now()
: () => Date.now();
const onNextFrame = typeof window !== "undefined"
? (callback) => window.requestAnimationFrame(callback)
: (callback) => setTimeout(() => callback(getCurrentTime()), defaultTimestep);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/frameloop/create-render-step.mjs
function createRenderStep(runNextFrame) {
/**
* We create and reuse two arrays, one to queue jobs for the current frame
* and one for the next. We reuse to avoid triggering GC after x frames.
*/
let toRun = [];
let toRunNextFrame = [];
/**
*
*/
let numToRun = 0;
/**
* Track whether we're currently processing jobs in this step. This way
* we can decide whether to schedule new jobs for this frame or next.
*/
let isProcessing = false;
let flushNextFrame = false;
/**
* A set of processes which were marked keepAlive when scheduled.
*/
const toKeepAlive = new WeakSet();
const step = {
/**
* Schedule a process to run on the next frame.
*/
schedule: (callback, keepAlive = false, immediate = false) => {
const addToCurrentFrame = immediate && isProcessing;
const buffer = addToCurrentFrame ? toRun : toRunNextFrame;
if (keepAlive)
toKeepAlive.add(callback);
// If the buffer doesn't already contain this callback, add it
if (buffer.indexOf(callback) === -1) {
buffer.push(callback);
// If we're adding it to the currently running buffer, update its measured size
if (addToCurrentFrame && isProcessing)
numToRun = toRun.length;
}
return callback;
},
/**
* Cancel the provided callback from running on the next frame.
*/
cancel: (callback) => {
const index = toRunNextFrame.indexOf(callback);
if (index !== -1)
toRunNextFrame.splice(index, 1);
toKeepAlive.delete(callback);
},
/**
* Execute all schedule callbacks.
*/
process: (frameData) => {
/**
* If we're already processing we've probably been triggered by a flushSync
* inside an existing process. Instead of executing, mark flushNextFrame
* as true and ensure we flush the following frame at the end of this one.
*/
if (isProcessing) {
flushNextFrame = true;
return;
}
isProcessing = true;
[toRun, toRunNextFrame] = [toRunNextFrame, toRun];
// Clear the next frame list
toRunNextFrame.length = 0;
// Execute this frame
numToRun = toRun.length;
if (numToRun) {
for (let i = 0; i < numToRun; i++) {
const callback = toRun[i];
callback(frameData);
if (toKeepAlive.has(callback)) {
step.schedule(callback);
runNextFrame();
}
}
}
isProcessing = false;
if (flushNextFrame) {
flushNextFrame = false;
step.process(frameData);
}
},
};
return step;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/frameloop/index.mjs
const maxElapsed = 40;
let useDefaultElapsed = true;
let runNextFrame = false;
let isProcessing = false;
const stepsOrder = [
"read",
"update",
"preRender",
"render",
"postRender",
];
const steps = stepsOrder.reduce((acc, key) => {
acc[key] = createRenderStep(() => (runNextFrame = true));
return acc;
}, {});
const sync = stepsOrder.reduce((acc, key) => {
const step = steps[key];
acc[key] = (process, keepAlive = false, immediate = false) => {
if (!runNextFrame)
startLoop();
return step.schedule(process, keepAlive, immediate);
};
return acc;
}, {});
const cancelSync = stepsOrder.reduce((acc, key) => {
acc[key] = steps[key].cancel;
return acc;
}, {});
const flushSync = stepsOrder.reduce((acc, key) => {
acc[key] = () => steps[key].process(frameData);
return acc;
}, {});
const processStep = (stepId) => steps[stepId].process(frameData);
const processFrame = (timestamp) => {
runNextFrame = false;
frameData.delta = useDefaultElapsed
? defaultTimestep
: Math.max(Math.min(timestamp - frameData.timestamp, maxElapsed), 1);
frameData.timestamp = timestamp;
isProcessing = true;
stepsOrder.forEach(processStep);
isProcessing = false;
if (runNextFrame) {
useDefaultElapsed = false;
onNextFrame(processFrame);
}
};
const startLoop = () => {
runNextFrame = true;
useDefaultElapsed = true;
if (!isProcessing)
onNextFrame(processFrame);
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/array.mjs
function addUniqueItem(arr, item) {
if (arr.indexOf(item) === -1)
arr.push(item);
}
function removeItem(arr, item) {
const index = arr.indexOf(item);
if (index > -1)
arr.splice(index, 1);
}
// Adapted from array-move
function moveItem([...arr], fromIndex, toIndex) {
const startIndex = fromIndex < 0 ? arr.length + fromIndex : fromIndex;
if (startIndex >= 0 && startIndex < arr.length) {
const endIndex = toIndex < 0 ? arr.length + toIndex : toIndex;
const [item] = arr.splice(fromIndex, 1);
arr.splice(endIndex, 0, item);
}
return arr;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/subscription-manager.mjs
class SubscriptionManager {
constructor() {
this.subscriptions = [];
}
add(handler) {
addUniqueItem(this.subscriptions, handler);
return () => removeItem(this.subscriptions, handler);
}
notify(a, b, c) {
const numSubscriptions = this.subscriptions.length;
if (!numSubscriptions)
return;
if (numSubscriptions === 1) {
/**
* If there's only a single handler we can just call it without invoking a loop.
*/
this.subscriptions[0](a, b, c);
}
else {
for (let i = 0; i < numSubscriptions; i++) {
/**
* Check whether the handler exists before firing as it's possible
* the subscriptions were modified during this loop running.
*/
const handler = this.subscriptions[i];
handler && handler(a, b, c);
}
}
}
getSize() {
return this.subscriptions.length;
}
clear() {
this.subscriptions.length = 0;
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/velocity-per-second.mjs
/*
Convert velocity into velocity per second
@param [number]: Unit per frame
@param [number]: Frame duration in ms
*/
function velocityPerSecond(velocity, frameDuration) {
return frameDuration ? velocity * (1000 / frameDuration) : 0;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/index.mjs
const isFloat = (value) => {
return !isNaN(parseFloat(value));
};
/**
* `MotionValue` is used to track the state and velocity of motion values.
*
* @public
*/
class MotionValue {
/**
* @param init - The initiating value
* @param config - Optional configuration options
*
* - `transformer`: A function to transform incoming values with.
*
* @internal
*/
constructor(init, options = {}) {
/**
* This will be replaced by the build step with the latest version number.
* When MotionValues are provided to motion components, warn if versions are mixed.
*/
this.version = "7.10.3";
/**
* Duration, in milliseconds, since last updating frame.
*
* @internal
*/
this.timeDelta = 0;
/**
* Timestamp of the last time this `MotionValue` was updated.
*
* @internal
*/
this.lastUpdated = 0;
/**
* Tracks whether this value can output a velocity. Currently this is only true
* if the value is numerical, but we might be able to widen the scope here and support
* other value types.
*
* @internal
*/
this.canTrackVelocity = false;
/**
* An object containing a SubscriptionManager for each active event.
*/
this.events = {};
this.updateAndNotify = (v, render = true) => {
this.prev = this.current;
this.current = v;
// Update timestamp
const { delta, timestamp } = frameData;
if (this.lastUpdated !== timestamp) {
this.timeDelta = delta;
this.lastUpdated = timestamp;
sync.postRender(this.scheduleVelocityCheck);
}
// Update update subscribers
if (this.prev !== this.current && this.events.change) {
this.events.change.notify(this.current);
}
// Update velocity subscribers
if (this.events.velocityChange) {
this.events.velocityChange.notify(this.getVelocity());
}
// Update render subscribers
if (render && this.events.renderRequest) {
this.events.renderRequest.notify(this.current);
}
};
/**
* Schedule a velocity check for the next frame.
*
* This is an instanced and bound function to prevent generating a new
* function once per frame.
*
* @internal
*/
this.scheduleVelocityCheck = () => sync.postRender(this.velocityCheck);
/**
* Updates `prev` with `current` if the value hasn't been updated this frame.
* This ensures velocity calculations return `0`.
*
* This is an instanced and bound function to prevent generating a new
* function once per frame.
*
* @internal
*/
this.velocityCheck = ({ timestamp }) => {
if (timestamp !== this.lastUpdated) {
this.prev = this.current;
if (this.events.velocityChange) {
this.events.velocityChange.notify(this.getVelocity());
}
}
};
this.hasAnimated = false;
this.prev = this.current = init;
this.canTrackVelocity = isFloat(this.current);
this.owner = options.owner;
}
/**
* Adds a function that will be notified when the `MotionValue` is updated.
*
* It returns a function that, when called, will cancel the subscription.
*
* When calling `onChange` inside a React component, it should be wrapped with the
* `useEffect` hook. As it returns an unsubscribe function, this should be returned
* from the `useEffect` function to ensure you don't add duplicate subscribers..
*
* ```jsx
* export const MyComponent = () => {
* const x = useMotionValue(0)
* const y = useMotionValue(0)
* const opacity = useMotionValue(1)
*
* useEffect(() => {
* function updateOpacity() {
* const maxXY = Math.max(x.get(), y.get())
* const newOpacity = transform(maxXY, [0, 100], [1, 0])
* opacity.set(newOpacity)
* }
*
* const unsubscribeX = x.on("change", updateOpacity)
* const unsubscribeY = y.on("change", updateOpacity)
*
* return () => {
* unsubscribeX()
* unsubscribeY()
* }
* }, [])
*
* return <motion.div style={{ x }} />
* }
* ```
*
* @privateRemarks
*
* We could look into a `useOnChange` hook if the above lifecycle management proves confusing.
*
* ```jsx
* useOnChange(x, () => {})
* ```
*
* @param subscriber - A function that receives the latest value.
* @returns A function that, when called, will cancel this subscription.
*
* @deprecated
*/
onChange(subscription) {
return this.on("change", subscription);
}
on(eventName, callback) {
if (!this.events[eventName]) {
this.events[eventName] = new SubscriptionManager();
}
return this.events[eventName].add(callback);
}
clearListeners() {
for (const eventManagers in this.events) {
this.events[eventManagers].clear();
}
}
/**
* Attaches a passive effect to the `MotionValue`.
*
* @internal
*/
attach(passiveEffect) {
this.passiveEffect = passiveEffect;
}
/**
* Sets the state of the `MotionValue`.
*
* @remarks
*
* ```jsx
* const x = useMotionValue(0)
* x.set(10)
* ```
*
* @param latest - Latest value to set.
* @param render - Whether to notify render subscribers. Defaults to `true`
*
* @public
*/
set(v, render = true) {
if (!render || !this.passiveEffect) {
this.updateAndNotify(v, render);
}
else {
this.passiveEffect(v, this.updateAndNotify);
}
}
setWithVelocity(prev, current, delta) {
this.set(current);
this.prev = prev;
this.timeDelta = delta;
}
/**
* Returns the latest state of `MotionValue`
*
* @returns - The latest state of `MotionValue`
*
* @public
*/
get() {
return this.current;
}
/**
* @public
*/
getPrevious() {
return this.prev;
}
/**
* Returns the latest velocity of `MotionValue`
*
* @returns - The latest velocity of `MotionValue`. Returns `0` if the state is non-numerical.
*
* @public
*/
getVelocity() {
// This could be isFloat(this.prev) && isFloat(this.current), but that would be wasteful
return this.canTrackVelocity
? // These casts could be avoided if parseFloat would be typed better
velocityPerSecond(parseFloat(this.current) -
parseFloat(this.prev), this.timeDelta)
: 0;
}
/**
* Registers a new animation to control this `MotionValue`. Only one
* animation can drive a `MotionValue` at one time.
*
* ```jsx
* value.start()
* ```
*
* @param animation - A function that starts the provided animation
*
* @internal
*/
start(animation) {
this.stop();
return new Promise((resolve) => {
this.hasAnimated = true;
this.stopAnimation = animation(resolve);
if (this.events.animationStart) {
this.events.animationStart.notify();
}
}).then(() => {
if (this.events.animationComplete) {
this.events.animationComplete.notify();
}
this.clearAnimation();
});
}
/**
* Stop the currently active animation.
*
* @public
*/
stop() {
if (this.stopAnimation) {
this.stopAnimation();
if (this.events.animationCancel) {
this.events.animationCancel.notify();
}
}
this.clearAnimation();
}
/**
* Returns `true` if this value is currently animating.
*
* @public
*/
isAnimating() {
return !!this.stopAnimation;
}
clearAnimation() {
this.stopAnimation = null;
}
/**
* Destroy and clean up subscribers to this `MotionValue`.
*
* The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically
* handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually
* created a `MotionValue` via the `motionValue` function.
*
* @public
*/
destroy() {
this.clearListeners();
this.stop();
}
}
function motionValue(init, options) {
return new MotionValue(init, options);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/types/color/utils.mjs
/**
* Returns true if the provided string is a color, ie rgba(0,0,0,0) or #000,
* but false if a number or multiple colors
*/
const isColorString = (type, testProp) => (v) => {
return Boolean((isString(v) && singleColorRegex.test(v) && v.startsWith(type)) ||
(testProp && Object.prototype.hasOwnProperty.call(v, testProp)));
};
const splitColor = (aName, bName, cName) => (v) => {
if (!isString(v))
return v;
const [a, b, c, alpha] = v.match(floatRegex);
return {
[aName]: parseFloat(a),
[bName]: parseFloat(b),
[cName]: parseFloat(c),
alpha: alpha !== undefined ? parseFloat(alpha) : 1,
};
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/types/color/rgba.mjs
const clampRgbUnit = (v) => clamp_clamp(0, 255, v);
const rgbUnit = {
...number,
transform: (v) => Math.round(clampRgbUnit(v)),
};
const rgba = {
test: isColorString("rgb", "red"),
parse: splitColor("red", "green", "blue"),
transform: ({ red, green, blue, alpha: alpha$1 = 1 }) => "rgba(" +
rgbUnit.transform(red) +
", " +
rgbUnit.transform(green) +
", " +
rgbUnit.transform(blue) +
", " +
sanitize(alpha.transform(alpha$1)) +
")",
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/types/color/hex.mjs
function parseHex(v) {
let r = "";
let g = "";
let b = "";
let a = "";
// If we have 6 characters, ie #FF0000
if (v.length > 5) {
r = v.substring(1, 3);
g = v.substring(3, 5);
b = v.substring(5, 7);
a = v.substring(7, 9);
// Or we have 3 characters, ie #F00
}
else {
r = v.substring(1, 2);
g = v.substring(2, 3);
b = v.substring(3, 4);
a = v.substring(4, 5);
r += r;
g += g;
b += b;
a += a;
}
return {
red: parseInt(r, 16),
green: parseInt(g, 16),
blue: parseInt(b, 16),
alpha: a ? parseInt(a, 16) / 255 : 1,
};
}
const hex = {
test: isColorString("#"),
parse: parseHex,
transform: rgba.transform,
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/types/color/hsla.mjs
const hsla = {
test: isColorString("hsl", "hue"),
parse: splitColor("hue", "saturation", "lightness"),
transform: ({ hue, saturation, lightness, alpha: alpha$1 = 1 }) => {
return ("hsla(" +
Math.round(hue) +
", " +
percent.transform(sanitize(saturation)) +
", " +
percent.transform(sanitize(lightness)) +
", " +
sanitize(alpha.transform(alpha$1)) +
")");
},
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/types/color/index.mjs
const color = {
test: (v) => rgba.test(v) || hex.test(v) || hsla.test(v),
parse: (v) => {
if (rgba.test(v)) {
return rgba.parse(v);
}
else if (hsla.test(v)) {
return hsla.parse(v);
}
else {
return hex.parse(v);
}
},
transform: (v) => {
return isString(v)
? v
: v.hasOwnProperty("red")
? rgba.transform(v)
: hsla.transform(v);
},
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/types/complex/index.mjs
const colorToken = "${c}";
const numberToken = "${n}";
function test(v) {
var _a, _b;
return (isNaN(v) &&
isString(v) &&
(((_a = v.match(floatRegex)) === null || _a === void 0 ? void 0 : _a.length) || 0) +
(((_b = v.match(colorRegex)) === null || _b === void 0 ? void 0 : _b.length) || 0) >
0);
}
function analyseComplexValue(v) {
if (typeof v === "number")
v = `${v}`;
const values = [];
let numColors = 0;
let numNumbers = 0;
const colors = v.match(colorRegex);
if (colors) {
numColors = colors.length;
// Strip colors from input so they're not picked up by number regex.
// There's a better way to combine these regex searches, but its beyond my regex skills
v = v.replace(colorRegex, colorToken);
values.push(...colors.map(color.parse));
}
const numbers = v.match(floatRegex);
if (numbers) {
numNumbers = numbers.length;
v = v.replace(floatRegex, numberToken);
values.push(...numbers.map(number.parse));
}
return { values, numColors, numNumbers, tokenised: v };
}
function parse(v) {
return analyseComplexValue(v).values;
}
function createTransformer(source) {
const { values, numColors, tokenised } = analyseComplexValue(source);
const numValues = values.length;
return (v) => {
let output = tokenised;
for (let i = 0; i < numValues; i++) {
output = output.replace(i < numColors ? colorToken : numberToken, i < numColors
? color.transform(v[i])
: sanitize(v[i]));
}
return output;
};
}
const convertNumbersToZero = (v) => typeof v === "number" ? 0 : v;
function getAnimatableNone(v) {
const parsed = parse(v);
const transformer = createTransformer(v);
return transformer(parsed.map(convertNumbersToZero));
}
const complex = { test, parse, createTransformer, getAnimatableNone };
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/types/complex/filter.mjs
/**
* Properties that should default to 1 or 100%
*/
const maxDefaults = new Set(["brightness", "contrast", "saturate", "opacity"]);
function applyDefaultFilter(v) {
const [name, value] = v.slice(0, -1).split("(");
if (name === "drop-shadow")
return v;
const [number] = value.match(floatRegex) || [];
if (!number)
return v;
const unit = value.replace(number, "");
let defaultValue = maxDefaults.has(name) ? 1 : 0;
if (number !== value)
defaultValue *= 100;
return name + "(" + defaultValue + unit + ")";
}
const functionRegex = /([a-z-]*)\(.*?\)/g;
const filter = {
...complex,
getAnimatableNone: (v) => {
const functions = v.match(functionRegex);
return functions ? functions.map(applyDefaultFilter).join(" ") : v;
},
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/value-types/defaults.mjs
/**
* A map of default value types for common values
*/
const defaultValueTypes = {
...numberValueTypes,
// Color props
color: color,
backgroundColor: color,
outlineColor: color,
fill: color,
stroke: color,
// Border props
borderColor: color,
borderTopColor: color,
borderRightColor: color,
borderBottomColor: color,
borderLeftColor: color,
filter: filter,
WebkitFilter: filter,
};
/**
* Gets the default ValueType for the provided value key
*/
const getDefaultValueType = (key) => defaultValueTypes[key];
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/value-types/animatable-none.mjs
function animatable_none_getAnimatableNone(key, value) {
var _a;
let defaultValueType = getDefaultValueType(key);
if (defaultValueType !== filter)
defaultValueType = complex;
// If value is not recognised as animatable, ie "none", create an animatable version origin based on the target
return (_a = defaultValueType.getAnimatableNone) === null || _a === void 0 ? void 0 : _a.call(defaultValueType, value);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/value-types/test.mjs
/**
* Tests a provided value against a ValueType
*/
const testValueType = (v) => (type) => type.test(v);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/value-types/type-auto.mjs
/**
* ValueType for "auto"
*/
const auto = {
test: (v) => v === "auto",
parse: (v) => v,
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/value-types/dimensions.mjs
/**
* A list of value types commonly used for dimensions
*/
const dimensionValueTypes = [number, px, percent, degrees, vw, vh, auto];
/**
* Tests a dimensional value against the list of dimension ValueTypes
*/
const findDimensionValueType = (v) => dimensionValueTypes.find(testValueType(v));
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/value-types/find.mjs
/**
* A list of all ValueTypes
*/
const valueTypes = [...dimensionValueTypes, color, complex];
/**
* Tests a value against the list of ValueTypes
*/
const findValueType = (v) => valueTypes.find(testValueType(v));
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/utils/resolve-dynamic-variants.mjs
/**
* Creates an object containing the latest state of every MotionValue on a VisualElement
*/
function getCurrent(visualElement) {
const current = {};
visualElement.values.forEach((value, key) => (current[key] = value.get()));
return current;
}
/**
* Creates an object containing the latest velocity of every MotionValue on a VisualElement
*/
function getVelocity(visualElement) {
const velocity = {};
visualElement.values.forEach((value, key) => (velocity[key] = value.getVelocity()));
return velocity;
}
function resolveVariant(visualElement, definition, custom) {
const props = visualElement.getProps();
return resolveVariantFromProps(props, definition, custom !== undefined ? custom : props.custom, getCurrent(visualElement), getVelocity(visualElement));
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/utils/setters.mjs
/**
* Set VisualElement's MotionValue, creating a new MotionValue for it if
* it doesn't exist.
*/
function setMotionValue(visualElement, key, value) {
if (visualElement.hasValue(key)) {
visualElement.getValue(key).set(value);
}
else {
visualElement.addValue(key, motionValue(value));
}
}
function setTarget(visualElement, definition) {
const resolved = resolveVariant(visualElement, definition);
let { transitionEnd = {}, transition = {}, ...target } = resolved ? visualElement.makeTargetAnimatable(resolved, false) : {};
target = { ...target, ...transitionEnd };
for (const key in target) {
const value = resolveFinalValueInKeyframes(target[key]);
setMotionValue(visualElement, key, value);
}
}
function setVariants(visualElement, variantLabels) {
const reversedLabels = [...variantLabels].reverse();
reversedLabels.forEach((key) => {
var _a;
const variant = visualElement.getVariant(key);
variant && setTarget(visualElement, variant);
(_a = visualElement.variantChildren) === null || _a === void 0 ? void 0 : _a.forEach((child) => {
setVariants(child, variantLabels);
});
});
}
function setValues(visualElement, definition) {
if (Array.isArray(definition)) {
return setVariants(visualElement, definition);
}
else if (typeof definition === "string") {
return setVariants(visualElement, [definition]);
}
else {
setTarget(visualElement, definition);
}
}
function checkTargetForNewValues(visualElement, target, origin) {
var _a, _b;
const newValueKeys = Object.keys(target).filter((key) => !visualElement.hasValue(key));
const numNewValues = newValueKeys.length;
if (!numNewValues)
return;
for (let i = 0; i < numNewValues; i++) {
const key = newValueKeys[i];
const targetValue = target[key];
let value = null;
/**
* If the target is a series of keyframes, we can use the first value
* in the array. If this first value is null, we'll still need to read from the DOM.
*/
if (Array.isArray(targetValue)) {
value = targetValue[0];
}
/**
* If the target isn't keyframes, or the first keyframe was null, we need to
* first check if an origin value was explicitly defined in the transition as "from",
* if not read the value from the DOM. As an absolute fallback, take the defined target value.
*/
if (value === null) {
value = (_b = (_a = origin[key]) !== null && _a !== void 0 ? _a : visualElement.readValue(key)) !== null && _b !== void 0 ? _b : target[key];
}
/**
* If value is still undefined or null, ignore it. Preferably this would throw,
* but this was causing issues in Framer.
*/
if (value === undefined || value === null)
continue;
if (typeof value === "string" &&
(isNumericalString(value) || isZeroValueString(value))) {
// If this is a number read as a string, ie "0" or "200", convert it to a number
value = parseFloat(value);
}
else if (!findValueType(value) && complex.test(targetValue)) {
value = animatable_none_getAnimatableNone(key, targetValue);
}
visualElement.addValue(key, motionValue(value, { owner: visualElement }));
if (origin[key] === undefined) {
origin[key] = value;
}
if (value !== null)
visualElement.setBaseTarget(key, value);
}
}
function getOriginFromTransition(key, transition) {
if (!transition)
return;
const valueTransition = transition[key] || transition["default"] || transition;
return valueTransition.from;
}
function getOrigin(target, transition, visualElement) {
var _a;
const origin = {};
for (const key in target) {
const transitionOrigin = getOriginFromTransition(key, transition);
origin[key] =
transitionOrigin !== undefined
? transitionOrigin
: (_a = visualElement.getValue(key)) === null || _a === void 0 ? void 0 : _a.get();
}
return origin;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/value/use-will-change/is.mjs
function isWillChangeMotionValue(value) {
return Boolean(isMotionValue(value) && value.add);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/optimized-appear/store-id.mjs
const appearStoreId = (id, value) => `${id}: ${value}`;
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/optimized-appear/handoff.mjs
function handoffOptimizedAppearAnimation(id, name) {
const { MotionAppearAnimations } = window;
const animationId = appearStoreId(id, transformProps.has(name) ? "transform" : name);
const animation = MotionAppearAnimations && MotionAppearAnimations.get(animationId);
if (animation) {
/**
* We allow the animation to persist until the next frame:
* 1. So it continues to play until Framer Motion is ready to render
* (avoiding a potential flash of the element's original state)
* 2. As all independent transforms share a single transform animation, stopping
* it synchronously would prevent subsequent transforms from handing off.
*/
sync.render(() => {
/**
* Animation.cancel() throws so it needs to be wrapped in a try/catch
*/
try {
animation.cancel();
MotionAppearAnimations.delete(animationId);
}
catch (e) { }
});
return animation.currentTime || 0;
}
else {
return 0;
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/optimized-appear/data-id.mjs
const optimizedAppearDataId = "framerAppearId";
const optimizedAppearDataAttribute = "data-" + camelToDash(optimizedAppearDataId);
;// CONCATENATED MODULE: ./node_modules/hey-listen/dist/hey-listen.es.js
var warning = function () { };
var invariant = function () { };
if (false) {}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/time-conversion.mjs
/**
* Converts seconds to milliseconds
*
* @param seconds - Time in seconds.
* @return milliseconds - Converted time in milliseconds.
*/
const secondsToMilliseconds = (seconds) => seconds * 1000;
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/use-instant-transition-state.mjs
const instantAnimationState = {
current: false,
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/easing/modifiers/mirror.mjs
// Accepts an easing function and returns a new one that outputs mirrored values for
// the second half of the animation. Turns easeIn into easeInOut.
const mirrorEasing = (easing) => (p) => p <= 0.5 ? easing(2 * p) / 2 : (2 - easing(2 * (1 - p))) / 2;
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/easing/modifiers/reverse.mjs
// Accepts an easing function and returns a new one that outputs reversed values.
// Turns easeIn into easeOut.
const reverseEasing = (easing) => (p) => 1 - easing(1 - p);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/easing/ease.mjs
const easeIn = (p) => p * p;
const easeOut = reverseEasing(easeIn);
const easeInOut = mirrorEasing(easeIn);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/mix.mjs
/*
Value in range from progress
Given a lower limit and an upper limit, we return the value within
that range as expressed by progress (usually a number from 0 to 1)
So progress = 0.5 would change
from -------- to
to
from ---- to
E.g. from = 10, to = 20, progress = 0.5 => 15
@param [number]: Lower limit of range
@param [number]: Upper limit of range
@param [number]: The progress between lower and upper limits expressed 0-1
@return [number]: Value as calculated from progress within range (not limited within range)
*/
const mix = (from, to, progress) => -progress * from + progress * to + from;
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/hsla-to-rgba.mjs
// Adapted from https://gist.github.com/mjackson/5311256
function hueToRgb(p, q, t) {
if (t < 0)
t += 1;
if (t > 1)
t -= 1;
if (t < 1 / 6)
return p + (q - p) * 6 * t;
if (t < 1 / 2)
return q;
if (t < 2 / 3)
return p + (q - p) * (2 / 3 - t) * 6;
return p;
}
function hslaToRgba({ hue, saturation, lightness, alpha }) {
hue /= 360;
saturation /= 100;
lightness /= 100;
let red = 0;
let green = 0;
let blue = 0;
if (!saturation) {
red = green = blue = lightness;
}
else {
const q = lightness < 0.5
? lightness * (1 + saturation)
: lightness + saturation - lightness * saturation;
const p = 2 * lightness - q;
red = hueToRgb(p, q, hue + 1 / 3);
green = hueToRgb(p, q, hue);
blue = hueToRgb(p, q, hue - 1 / 3);
}
return {
red: Math.round(red * 255),
green: Math.round(green * 255),
blue: Math.round(blue * 255),
alpha,
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/mix-color.mjs
// Linear color space blending
// Explained https://www.youtube.com/watch?v=LKnqECcg6Gw
// Demonstrated http://codepen.io/osublake/pen/xGVVaN
const mixLinearColor = (from, to, v) => {
const fromExpo = from * from;
return Math.sqrt(Math.max(0, v * (to * to - fromExpo) + fromExpo));
};
const colorTypes = [hex, rgba, hsla];
const getColorType = (v) => colorTypes.find((type) => type.test(v));
function asRGBA(color) {
const type = getColorType(color);
invariant(Boolean(type), `'${color}' is not an animatable color. Use the equivalent color code instead.`);
let model = type.parse(color);
if (type === hsla) {
// TODO Remove this cast - needed since Framer Motion's stricter typing
model = hslaToRgba(model);
}
return model;
}
const mixColor = (from, to) => {
const fromRGBA = asRGBA(from);
const toRGBA = asRGBA(to);
const blended = { ...fromRGBA };
return (v) => {
blended.red = mixLinearColor(fromRGBA.red, toRGBA.red, v);
blended.green = mixLinearColor(fromRGBA.green, toRGBA.green, v);
blended.blue = mixLinearColor(fromRGBA.blue, toRGBA.blue, v);
blended.alpha = mix(fromRGBA.alpha, toRGBA.alpha, v);
return rgba.transform(blended);
};
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/mix-complex.mjs
function getMixer(origin, target) {
if (typeof origin === "number") {
return (v) => mix(origin, target, v);
}
else if (color.test(origin)) {
return mixColor(origin, target);
}
else {
return mixComplex(origin, target);
}
}
const mixArray = (from, to) => {
const output = [...from];
const numValues = output.length;
const blendValue = from.map((fromThis, i) => getMixer(fromThis, to[i]));
return (v) => {
for (let i = 0; i < numValues; i++) {
output[i] = blendValue[i](v);
}
return output;
};
};
const mixObject = (origin, target) => {
const output = { ...origin, ...target };
const blendValue = {};
for (const key in output) {
if (origin[key] !== undefined && target[key] !== undefined) {
blendValue[key] = getMixer(origin[key], target[key]);
}
}
return (v) => {
for (const key in blendValue) {
output[key] = blendValue[key](v);
}
return output;
};
};
const mixComplex = (origin, target) => {
const template = complex.createTransformer(target);
const originStats = analyseComplexValue(origin);
const targetStats = analyseComplexValue(target);
const canInterpolate = originStats.numColors === targetStats.numColors &&
originStats.numNumbers >= targetStats.numNumbers;
if (canInterpolate) {
return pipe(mixArray(originStats.values, targetStats.values), template);
}
else {
warning(true, `Complex values '${origin}' and '${target}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`);
return (p) => `${p > 0 ? target : origin}`;
}
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/progress.mjs
/*
Progress within given range
Given a lower limit and an upper limit, we return the progress
(expressed as a number 0-1) represented by the given value, and
limit that progress to within 0-1.
@param [number]: Lower limit
@param [number]: Upper limit
@param [number]: Value to find progress within given range
@return [number]: Progress of value within range as expressed 0-1
*/
const progress = (from, to, value) => {
const toFromDifference = to - from;
return toFromDifference === 0 ? 1 : (value - from) / toFromDifference;
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/interpolate.mjs
const mixNumber = (from, to) => (p) => mix(from, to, p);
function detectMixerFactory(v) {
if (typeof v === "number") {
return mixNumber;
}
else if (typeof v === "string") {
if (color.test(v)) {
return mixColor;
}
else {
return mixComplex;
}
}
else if (Array.isArray(v)) {
return mixArray;
}
else if (typeof v === "object") {
return mixObject;
}
return mixNumber;
}
function createMixers(output, ease, customMixer) {
const mixers = [];
const mixerFactory = customMixer || detectMixerFactory(output[0]);
const numMixers = output.length - 1;
for (let i = 0; i < numMixers; i++) {
let mixer = mixerFactory(output[i], output[i + 1]);
if (ease) {
const easingFunction = Array.isArray(ease) ? ease[i] : ease;
mixer = pipe(easingFunction, mixer);
}
mixers.push(mixer);
}
return mixers;
}
/**
* Create a function that maps from a numerical input array to a generic output array.
*
* Accepts:
* - Numbers
* - Colors (hex, hsl, hsla, rgb, rgba)
* - Complex (combinations of one or more numbers or strings)
*
* ```jsx
* const mixColor = interpolate([0, 1], ['#fff', '#000'])
*
* mixColor(0.5) // 'rgba(128, 128, 128, 1)'
* ```
*
* TODO Revist this approach once we've moved to data models for values,
* probably not needed to pregenerate mixer functions.
*
* @public
*/
function interpolate(input, output, { clamp: isClamp = true, ease, mixer } = {}) {
const inputLength = input.length;
invariant(inputLength === output.length, "Both input and output ranges must be the same length");
invariant(!ease || !Array.isArray(ease) || ease.length === inputLength - 1, "Array of easing functions must be of length `input.length - 1`, as it applies to the transitions **between** the defined values.");
// If input runs highest -> lowest, reverse both arrays
if (input[0] > input[inputLength - 1]) {
input = [...input].reverse();
output = [...output].reverse();
}
const mixers = createMixers(output, ease, mixer);
const numMixers = mixers.length;
const interpolator = (v) => {
let i = 0;
if (numMixers > 1) {
for (; i < input.length - 2; i++) {
if (v < input[i + 1])
break;
}
}
const progressInRange = progress(input[i], input[i + 1], v);
return mixers[i](progressInRange);
};
return isClamp
? (v) => interpolator(clamp_clamp(input[0], input[inputLength - 1], v))
: interpolator;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/noop.mjs
const noop = (any) => any;
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/easing/cubic-bezier.mjs
/*
Bezier function generator
This has been modified from Gaëtan Renaudeau's BezierEasing
https://github.com/gre/bezier-easing/blob/master/src/index.js
https://github.com/gre/bezier-easing/blob/master/LICENSE
I've removed the newtonRaphsonIterate algo because in benchmarking it
wasn't noticiably faster than binarySubdivision, indeed removing it
usually improved times, depending on the curve.
I also removed the lookup table, as for the added bundle size and loop we're
only cutting ~4 or so subdivision iterations. I bumped the max iterations up
to 12 to compensate and this still tended to be faster for no perceivable
loss in accuracy.
Usage
const easeOut = cubicBezier(.17,.67,.83,.67);
const x = easeOut(0.5); // returns 0.627...
*/
// Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2.
const calcBezier = (t, a1, a2) => (((1.0 - 3.0 * a2 + 3.0 * a1) * t + (3.0 * a2 - 6.0 * a1)) * t + 3.0 * a1) *
t;
const subdivisionPrecision = 0.0000001;
const subdivisionMaxIterations = 12;
function binarySubdivide(x, lowerBound, upperBound, mX1, mX2) {
let currentX;
let currentT;
let i = 0;
do {
currentT = lowerBound + (upperBound - lowerBound) / 2.0;
currentX = calcBezier(currentT, mX1, mX2) - x;
if (currentX > 0.0) {
upperBound = currentT;
}
else {
lowerBound = currentT;
}
} while (Math.abs(currentX) > subdivisionPrecision &&
++i < subdivisionMaxIterations);
return currentT;
}
function cubicBezier(mX1, mY1, mX2, mY2) {
// If this is a linear gradient, return linear easing
if (mX1 === mY1 && mX2 === mY2)
return noop;
const getTForX = (aX) => binarySubdivide(aX, 0, 1, mX1, mX2);
// If animation is at start/end, return t without easing
return (t) => t === 0 || t === 1 ? t : calcBezier(getTForX(t), mY1, mY2);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/easing/circ.mjs
const circIn = (p) => 1 - Math.sin(Math.acos(p));
const circOut = reverseEasing(circIn);
const circInOut = mirrorEasing(circOut);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/easing/back.mjs
const backOut = cubicBezier(0.33, 1.53, 0.69, 0.99);
const backIn = reverseEasing(backOut);
const backInOut = mirrorEasing(backIn);
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/easing/anticipate.mjs
const anticipate = (p) => (p *= 2) < 1 ? 0.5 * backIn(p) : 0.5 * (2 - Math.pow(2, -10 * (p - 1)));
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/utils/easing.mjs
const easingLookup = {
linear: noop,
easeIn: easeIn,
easeInOut: easeInOut,
easeOut: easeOut,
circIn: circIn,
circInOut: circInOut,
circOut: circOut,
backIn: backIn,
backInOut: backInOut,
backOut: backOut,
anticipate: anticipate,
};
const easingDefinitionToFunction = (definition) => {
if (Array.isArray(definition)) {
// If cubic bezier definition, create bezier curve
invariant(definition.length === 4, `Cubic bezier arrays must contain four numerical values.`);
const [x1, y1, x2, y2] = definition;
return cubicBezier(x1, y1, x2, y2);
}
else if (typeof definition === "string") {
// Else lookup from table
invariant(easingLookup[definition] !== undefined, `Invalid easing type '${definition}'`);
return easingLookup[definition];
}
return definition;
};
const isEasingArray = (ease) => {
return Array.isArray(ease) && typeof ease[0] !== "number";
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/legacy-popmotion/keyframes.mjs
function defaultEasing(values, easing) {
return values.map(() => easing || easeInOut).splice(0, values.length - 1);
}
function defaultOffset(values) {
const numValues = values.length;
return values.map((_value, i) => i !== 0 ? i / (numValues - 1) : 0);
}
function convertOffsetToTimes(offset, duration) {
return offset.map((o) => o * duration);
}
function keyframes({ keyframes: keyframeValues, ease = easeInOut, times, duration = 300, }) {
keyframeValues = [...keyframeValues];
const origin = keyframes[0];
/**
* Easing functions can be externally defined as strings. Here we convert them
* into actual functions.
*/
const easingFunctions = isEasingArray(ease)
? ease.map(easingDefinitionToFunction)
: easingDefinitionToFunction(ease);
/**
* This is the Iterator-spec return value. We ensure it's mutable rather than using a generator
* to reduce GC during animation.
*/
const state = { done: false, value: origin };
/**
* Create a times array based on the provided 0-1 offsets
*/
const absoluteTimes = convertOffsetToTimes(
// Only use the provided offsets if they're the correct length
// TODO Maybe we should warn here if there's a length mismatch
times && times.length === keyframes.length
? times
: defaultOffset(keyframeValues), duration);
function createInterpolator() {
return interpolate(absoluteTimes, keyframeValues, {
ease: Array.isArray(easingFunctions)
? easingFunctions
: defaultEasing(keyframeValues, easingFunctions),
});
}
let interpolator = createInterpolator();
return {
next: (t) => {
state.value = interpolator(t);
state.done = t >= duration;
return state;
},
flipTarget: () => {
keyframeValues.reverse();
interpolator = createInterpolator();
},
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/legacy-popmotion/find-spring.mjs
const safeMin = 0.001;
const minDuration = 0.01;
const maxDuration = 10.0;
const minDamping = 0.05;
const maxDamping = 1;
function findSpring({ duration = 800, bounce = 0.25, velocity = 0, mass = 1, }) {
let envelope;
let derivative;
warning(duration <= maxDuration * 1000, "Spring duration must be 10 seconds or less");
let dampingRatio = 1 - bounce;
/**
* Restrict dampingRatio and duration to within acceptable ranges.
*/
dampingRatio = clamp_clamp(minDamping, maxDamping, dampingRatio);
duration = clamp_clamp(minDuration, maxDuration, duration / 1000);
if (dampingRatio < 1) {
/**
* Underdamped spring
*/
envelope = (undampedFreq) => {
const exponentialDecay = undampedFreq * dampingRatio;
const delta = exponentialDecay * duration;
const a = exponentialDecay - velocity;
const b = calcAngularFreq(undampedFreq, dampingRatio);
const c = Math.exp(-delta);
return safeMin - (a / b) * c;
};
derivative = (undampedFreq) => {
const exponentialDecay = undampedFreq * dampingRatio;
const delta = exponentialDecay * duration;
const d = delta * velocity + velocity;
const e = Math.pow(dampingRatio, 2) * Math.pow(undampedFreq, 2) * duration;
const f = Math.exp(-delta);
const g = calcAngularFreq(Math.pow(undampedFreq, 2), dampingRatio);
const factor = -envelope(undampedFreq) + safeMin > 0 ? -1 : 1;
return (factor * ((d - e) * f)) / g;
};
}
else {
/**
* Critically-damped spring
*/
envelope = (undampedFreq) => {
const a = Math.exp(-undampedFreq * duration);
const b = (undampedFreq - velocity) * duration + 1;
return -safeMin + a * b;
};
derivative = (undampedFreq) => {
const a = Math.exp(-undampedFreq * duration);
const b = (velocity - undampedFreq) * (duration * duration);
return a * b;
};
}
const initialGuess = 5 / duration;
const undampedFreq = approximateRoot(envelope, derivative, initialGuess);
duration = duration * 1000;
if (isNaN(undampedFreq)) {
return {
stiffness: 100,
damping: 10,
duration,
};
}
else {
const stiffness = Math.pow(undampedFreq, 2) * mass;
return {
stiffness,
damping: dampingRatio * 2 * Math.sqrt(mass * stiffness),
duration,
};
}
}
const rootIterations = 12;
function approximateRoot(envelope, derivative, initialGuess) {
let result = initialGuess;
for (let i = 1; i < rootIterations; i++) {
result = result - envelope(result) / derivative(result);
}
return result;
}
function calcAngularFreq(undampedFreq, dampingRatio) {
return undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/legacy-popmotion/spring.mjs
const durationKeys = ["duration", "bounce"];
const physicsKeys = ["stiffness", "damping", "mass"];
function isSpringType(options, keys) {
return keys.some((key) => options[key] !== undefined);
}
function getSpringOptions(options) {
let springOptions = {
velocity: 0.0,
stiffness: 100,
damping: 10,
mass: 1.0,
isResolvedFromDuration: false,
...options,
};
// stiffness/damping/mass overrides duration/bounce
if (!isSpringType(options, physicsKeys) &&
isSpringType(options, durationKeys)) {
const derived = findSpring(options);
springOptions = {
...springOptions,
...derived,
velocity: 0.0,
mass: 1.0,
};
springOptions.isResolvedFromDuration = true;
}
return springOptions;
}
const velocitySampleDuration = 5;
/**
* This is based on the spring implementation of Wobble https://github.com/skevy/wobble
*/
function spring({ keyframes, restSpeed = 2, restDelta = 0.01, ...options }) {
let origin = keyframes[0];
let target = keyframes[keyframes.length - 1];
/**
* This is the Iterator-spec return value. We ensure it's mutable rather than using a generator
* to reduce GC during animation.
*/
const state = { done: false, value: origin };
const { stiffness, damping, mass, velocity, duration, isResolvedFromDuration, } = getSpringOptions(options);
let resolveSpring = zero;
let initialVelocity = velocity ? -(velocity / 1000) : 0.0;
const dampingRatio = damping / (2 * Math.sqrt(stiffness * mass));
function createSpring() {
const initialDelta = target - origin;
const undampedAngularFreq = Math.sqrt(stiffness / mass) / 1000;
/**
* If we're working within what looks like a 0-1 range, change the default restDelta
* to 0.01
*/
if (restDelta === undefined) {
restDelta = Math.min(Math.abs(target - origin) / 100, 0.4);
}
if (dampingRatio < 1) {
const angularFreq = calcAngularFreq(undampedAngularFreq, dampingRatio);
// Underdamped spring
resolveSpring = (t) => {
const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);
return (target -
envelope *
(((initialVelocity +
dampingRatio * undampedAngularFreq * initialDelta) /
angularFreq) *
Math.sin(angularFreq * t) +
initialDelta * Math.cos(angularFreq * t)));
};
}
else if (dampingRatio === 1) {
// Critically damped spring
resolveSpring = (t) => target -
Math.exp(-undampedAngularFreq * t) *
(initialDelta +
(initialVelocity + undampedAngularFreq * initialDelta) *
t);
}
else {
// Overdamped spring
const dampedAngularFreq = undampedAngularFreq * Math.sqrt(dampingRatio * dampingRatio - 1);
resolveSpring = (t) => {
const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);
// When performing sinh or cosh values can hit Infinity so we cap them here
const freqForT = Math.min(dampedAngularFreq * t, 300);
return (target -
(envelope *
((initialVelocity +
dampingRatio * undampedAngularFreq * initialDelta) *
Math.sinh(freqForT) +
dampedAngularFreq *
initialDelta *
Math.cosh(freqForT))) /
dampedAngularFreq);
};
}
}
createSpring();
return {
next: (t) => {
const current = resolveSpring(t);
if (!isResolvedFromDuration) {
let currentVelocity = initialVelocity;
if (t !== 0) {
/**
* We only need to calculate velocity for under-damped springs
* as over- and critically-damped springs can't overshoot, so
* checking only for displacement is enough.
*/
if (dampingRatio < 1) {
const prevT = Math.max(0, t - velocitySampleDuration);
currentVelocity = velocityPerSecond(current - resolveSpring(prevT), t - prevT);
}
else {
currentVelocity = 0;
}
}
const isBelowVelocityThreshold = Math.abs(currentVelocity) <= restSpeed;
const isBelowDisplacementThreshold = Math.abs(target - current) <= restDelta;
state.done =
isBelowVelocityThreshold && isBelowDisplacementThreshold;
}
else {
state.done = t >= duration;
}
state.value = state.done ? target : current;
return state;
},
flipTarget: () => {
initialVelocity = -initialVelocity;
[origin, target] = [target, origin];
createSpring();
},
};
}
spring.needsInterpolation = (a, b) => typeof a === "string" || typeof b === "string";
const zero = (_t) => 0;
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/legacy-popmotion/decay.mjs
function decay({
/**
* The decay animation dynamically calculates an end of the animation
* based on the initial keyframe, so we only need to define a single keyframe
* as default.
*/
keyframes = [0], velocity = 0, power = 0.8, timeConstant = 350, restDelta = 0.5, modifyTarget, }) {
const origin = keyframes[0];
/**
* This is the Iterator-spec return value. We ensure it's mutable rather than using a generator
* to reduce GC during animation.
*/
const state = { done: false, value: origin };
let amplitude = power * velocity;
const ideal = origin + amplitude;
const target = modifyTarget === undefined ? ideal : modifyTarget(ideal);
/**
* If the target has changed we need to re-calculate the amplitude, otherwise
* the animation will start from the wrong position.
*/
if (target !== ideal)
amplitude = target - origin;
return {
next: (t) => {
const delta = -amplitude * Math.exp(-t / timeConstant);
state.done = !(delta > restDelta || delta < -restDelta);
state.value = state.done ? target : target + delta;
return state;
},
flipTarget: () => { },
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/legacy-popmotion/index.mjs
const types = {
decay: decay,
keyframes: keyframes,
tween: keyframes,
spring: spring,
};
function loopElapsed(elapsed, duration, delay = 0) {
return elapsed - duration - delay;
}
function reverseElapsed(elapsed, duration = 0, delay = 0, isForwardPlayback = true) {
return isForwardPlayback
? loopElapsed(duration + -elapsed, duration, delay)
: duration - (elapsed - duration) + delay;
}
function hasRepeatDelayElapsed(elapsed, duration, delay, isForwardPlayback) {
return isForwardPlayback ? elapsed >= duration + delay : elapsed <= -delay;
}
const framesync = (update) => {
const passTimestamp = ({ delta }) => update(delta);
return {
start: () => sync.update(passTimestamp, true),
stop: () => cancelSync.update(passTimestamp),
};
};
function animate({ duration, driver = framesync, elapsed = 0, repeat: repeatMax = 0, repeatType = "loop", repeatDelay = 0, keyframes, autoplay = true, onPlay, onStop, onComplete, onRepeat, onUpdate, type = "keyframes", ...options }) {
var _a, _b;
let driverControls;
let repeatCount = 0;
let computedDuration = duration;
let latest;
let isComplete = false;
let isForwardPlayback = true;
let interpolateFromNumber;
const animator = types[keyframes.length > 2 ? "keyframes" : type];
const origin = keyframes[0];
const target = keyframes[keyframes.length - 1];
if ((_b = (_a = animator).needsInterpolation) === null || _b === void 0 ? void 0 : _b.call(_a, origin, target)) {
interpolateFromNumber = interpolate([0, 100], [origin, target], {
clamp: false,
});
keyframes = [0, 100];
}
const animation = animator({
...options,
duration,
keyframes,
});
function repeat() {
repeatCount++;
if (repeatType === "reverse") {
isForwardPlayback = repeatCount % 2 === 0;
elapsed = reverseElapsed(elapsed, computedDuration, repeatDelay, isForwardPlayback);
}
else {
elapsed = loopElapsed(elapsed, computedDuration, repeatDelay);
if (repeatType === "mirror")
animation.flipTarget();
}
isComplete = false;
onRepeat && onRepeat();
}
function complete() {
driverControls.stop();
onComplete && onComplete();
}
function update(delta) {
if (!isForwardPlayback)
delta = -delta;
elapsed += delta;
if (!isComplete) {
const state = animation.next(Math.max(0, elapsed));
latest = state.value;
if (interpolateFromNumber)
latest = interpolateFromNumber(latest);
isComplete = isForwardPlayback ? state.done : elapsed <= 0;
}
onUpdate && onUpdate(latest);
if (isComplete) {
if (repeatCount === 0) {
computedDuration =
computedDuration !== undefined ? computedDuration : elapsed;
}
if (repeatCount < repeatMax) {
hasRepeatDelayElapsed(elapsed, computedDuration, repeatDelay, isForwardPlayback) && repeat();
}
else {
complete();
}
}
}
function play() {
onPlay && onPlay();
driverControls = driver(update);
driverControls.start();
}
autoplay && play();
return {
stop: () => {
onStop && onStop();
driverControls.stop();
},
sample: (t) => {
return animation.next(Math.max(0, t));
},
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/waapi/easing.mjs
function isWaapiSupportedEasing(easing) {
return (!easing || // Default easing
Array.isArray(easing) || // Bezier curve
(typeof easing === "string" && supportedWaapiEasing[easing]));
}
const cubicBezierAsString = ([a, b, c, d]) => `cubic-bezier(${a}, ${b}, ${c}, ${d})`;
const supportedWaapiEasing = {
linear: "linear",
ease: "ease",
easeIn: "ease-in",
easeOut: "ease-out",
easeInOut: "ease-in-out",
circIn: cubicBezierAsString([0, 0.65, 0.55, 1]),
circOut: cubicBezierAsString([0.55, 0, 1, 0.45]),
backIn: cubicBezierAsString([0.31, 0.01, 0.66, -0.59]),
backOut: cubicBezierAsString([0.33, 1.53, 0.69, 0.99]),
};
function mapEasingToNativeEasing(easing) {
if (!easing)
return undefined;
return Array.isArray(easing)
? cubicBezierAsString(easing)
: supportedWaapiEasing[easing];
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/waapi/index.mjs
function animateStyle(element, valueName, keyframes, { delay = 0, duration, repeat = 0, repeatType = "loop", ease, times, } = {}) {
return element.animate({ [valueName]: keyframes, offset: times }, {
delay,
duration,
easing: mapEasingToNativeEasing(ease),
fill: "both",
iterations: repeat + 1,
direction: repeatType === "reverse" ? "alternate" : "normal",
});
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/waapi/create-accelerated-animation.mjs
/**
* 10ms is chosen here as it strikes a balance between smooth
* results (more than one keyframe per frame at 60fps) and
* keyframe quantity.
*/
const sampleDelta = 10; //ms
function createAcceleratedAnimation(value, valueName, { onUpdate, onComplete, ...options }) {
let { keyframes, duration = 0.3, elapsed = 0, ease } = options;
/**
* If this animation needs pre-generated keyframes then generate.
*/
if (options.type === "spring" || !isWaapiSupportedEasing(options.ease)) {
const sampleAnimation = animate(options);
let state = { done: false, value: keyframes[0] };
const pregeneratedKeyframes = [];
let t = 0;
while (!state.done) {
state = sampleAnimation.sample(t);
pregeneratedKeyframes.push(state.value);
t += sampleDelta;
}
keyframes = pregeneratedKeyframes;
duration = t - sampleDelta;
ease = "linear";
}
const animation = animateStyle(value.owner.current, valueName, keyframes, {
...options,
delay: -elapsed,
duration,
/**
* This function is currently not called if ease is provided
* as a function so the cast is safe.
*
* However it would be possible for a future refinement to port
* in easing pregeneration from Motion One for browsers that
* support the upcoming `linear()` easing function.
*/
ease: ease,
});
/**
* Prefer the `onfinish` prop as it's more widely supported than
* the `finished` promise.
*
* Here, we synchronously set the provided MotionValue to the end
* keyframe. If we didn't, when the WAAPI animation is finished it would
* be removed from the element which would then revert to its old styles.
*/
animation.onfinish = () => {
value.set(keyframes[keyframes.length - 1]);
onComplete && onComplete();
};
/**
* Animation interrupt callback.
*/
return () => {
/**
* WAAPI doesn't natively have any interruption capabilities.
*
* Rather than read commited styles back out of the DOM, we can
* create a renderless JS animation and sample it twice to calculate
* its current value, "previous" value, and therefore allow
* Motion to calculate velocity for any subsequent animation.
*/
const { currentTime } = animation;
if (currentTime) {
const sampleAnimation = animate(options);
value.setWithVelocity(sampleAnimation.sample(currentTime - sampleDelta).value, sampleAnimation.sample(currentTime).value, sampleDelta);
}
sync.update(() => animation.cancel());
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/delay.mjs
/**
* Timeout defined in ms
*/
function delay(callback, timeout) {
const start = performance.now();
const checkElapsed = ({ timestamp }) => {
const elapsed = timestamp - start;
if (elapsed >= timeout) {
cancelSync.read(checkElapsed);
callback(elapsed - timeout);
}
};
sync.read(checkElapsed, true);
return () => cancelSync.read(checkElapsed);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/create-instant-animation.mjs
function createInstantAnimation({ keyframes, elapsed, onUpdate, onComplete, }) {
const setValue = () => {
onUpdate && onUpdate(keyframes[keyframes.length - 1]);
onComplete && onComplete();
return () => { };
};
return elapsed ? delay(setValue, -elapsed) : setValue();
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/legacy-popmotion/inertia.mjs
function inertia({ keyframes, velocity = 0, min, max, power = 0.8, timeConstant = 750, bounceStiffness = 500, bounceDamping = 10, restDelta = 1, modifyTarget, driver, onUpdate, onComplete, onStop, }) {
const origin = keyframes[0];
let currentAnimation;
function isOutOfBounds(v) {
return (min !== undefined && v < min) || (max !== undefined && v > max);
}
function findNearestBoundary(v) {
if (min === undefined)
return max;
if (max === undefined)
return min;
return Math.abs(min - v) < Math.abs(max - v) ? min : max;
}
function startAnimation(options) {
currentAnimation === null || currentAnimation === void 0 ? void 0 : currentAnimation.stop();
currentAnimation = animate({
keyframes: [0, 1],
velocity: 0,
...options,
driver,
onUpdate: (v) => {
var _a;
onUpdate === null || onUpdate === void 0 ? void 0 : onUpdate(v);
(_a = options.onUpdate) === null || _a === void 0 ? void 0 : _a.call(options, v);
},
onComplete,
onStop,
});
}
function startSpring(options) {
startAnimation({
type: "spring",
stiffness: bounceStiffness,
damping: bounceDamping,
restDelta,
...options,
});
}
if (isOutOfBounds(origin)) {
// Start the animation with spring if outside the defined boundaries
startSpring({
velocity,
keyframes: [origin, findNearestBoundary(origin)],
});
}
else {
/**
* Or if the value is out of bounds, simulate the inertia movement
* with the decay animation.
*
* Pre-calculate the target so we can detect if it's out-of-bounds.
* If it is, we want to check per frame when to switch to a spring
* animation
*/
let target = power * velocity + origin;
if (typeof modifyTarget !== "undefined")
target = modifyTarget(target);
const boundary = findNearestBoundary(target);
const heading = boundary === min ? -1 : 1;
let prev;
let current;
const checkBoundary = (v) => {
prev = current;
current = v;
velocity = velocityPerSecond(v - prev, frameData.delta);
if ((heading === 1 && v > boundary) ||
(heading === -1 && v < boundary)) {
startSpring({ keyframes: [v, boundary], velocity });
}
};
startAnimation({
type: "decay",
keyframes: [origin, 0],
velocity,
timeConstant,
power,
restDelta,
modifyTarget,
onUpdate: isOutOfBounds(target) ? checkBoundary : undefined,
});
}
return {
stop: () => currentAnimation === null || currentAnimation === void 0 ? void 0 : currentAnimation.stop(),
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/utils/default-transitions.mjs
const underDampedSpring = () => ({
type: "spring",
stiffness: 500,
damping: 25,
restSpeed: 10,
});
const criticallyDampedSpring = (target) => ({
type: "spring",
stiffness: 550,
damping: target === 0 ? 2 * Math.sqrt(550) : 30,
restSpeed: 10,
});
const linearTween = () => ({
type: "keyframes",
ease: "linear",
duration: 0.3,
});
const keyframesTransition = {
type: "keyframes",
duration: 0.8,
};
const defaultTransitions = {
x: underDampedSpring,
y: underDampedSpring,
z: underDampedSpring,
rotate: underDampedSpring,
rotateX: underDampedSpring,
rotateY: underDampedSpring,
rotateZ: underDampedSpring,
scaleX: criticallyDampedSpring,
scaleY: criticallyDampedSpring,
scale: criticallyDampedSpring,
opacity: linearTween,
backgroundColor: linearTween,
color: linearTween,
default: criticallyDampedSpring,
};
const getDefaultTransition = (valueKey, { keyframes }) => {
if (keyframes.length > 2) {
return keyframesTransition;
}
else {
const factory = defaultTransitions[valueKey] || defaultTransitions.default;
return factory(keyframes[1]);
}
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/utils/is-animatable.mjs
/**
* Check if a value is animatable. Examples:
*
* ✅: 100, "100px", "#fff"
* ❌: "block", "url(2.jpg)"
* @param value
*
* @internal
*/
const isAnimatable = (key, value) => {
// If the list of keys tat might be non-animatable grows, replace with Set
if (key === "zIndex")
return false;
// If it's a number or a keyframes array, we can animate it. We might at some point
// need to do a deep isAnimatable check of keyframes, or let Popmotion handle this,
// but for now lets leave it like this for performance reasons
if (typeof value === "number" || Array.isArray(value))
return true;
if (typeof value === "string" && // It's animatable if we have a string
complex.test(value) && // And it contains numbers and/or colors
!value.startsWith("url(") // Unless it starts with "url("
) {
return true;
}
return false;
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/utils/transitions.mjs
/**
* Decide whether a transition is defined on a given Transition.
* This filters out orchestration options and returns true
* if any options are left.
*/
function isTransitionDefined({ when, delay: _delay, delayChildren, staggerChildren, staggerDirection, repeat, repeatType, repeatDelay, from, ...transition }) {
return !!Object.keys(transition).length;
}
function isZero(value) {
return (value === 0 ||
(typeof value === "string" &&
parseFloat(value) === 0 &&
value.indexOf(" ") === -1));
}
function getZeroUnit(potentialUnitType) {
return typeof potentialUnitType === "number"
? 0
: animatable_none_getAnimatableNone("", potentialUnitType);
}
function getValueTransition(transition, key) {
return transition[key] || transition["default"] || transition;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/utils/keyframes.mjs
function getKeyframes(value, valueName, target, transition) {
const isTargetAnimatable = isAnimatable(valueName, target);
let origin = transition.from !== undefined ? transition.from : value.get();
if (origin === "none" && isTargetAnimatable && typeof target === "string") {
/**
* If we're trying to animate from "none", try and get an animatable version
* of the target. This could be improved to work both ways.
*/
origin = animatable_none_getAnimatableNone(valueName, target);
}
else if (isZero(origin) && typeof target === "string") {
origin = getZeroUnit(target);
}
else if (!Array.isArray(target) &&
isZero(target) &&
typeof origin === "string") {
target = getZeroUnit(origin);
}
/**
* If the target has been defined as a series of keyframes
*/
if (Array.isArray(target)) {
/**
* Ensure an initial wildcard keyframe is hydrated by the origin.
* TODO: Support extra wildcard keyframes i.e [1, null, 0]
*/
if (target[0] === null) {
target[0] = origin;
}
return target;
}
else {
return [origin, target];
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/waapi/supports.mjs
const featureTests = {
waapi: () => Object.hasOwnProperty.call(Element.prototype, "animate"),
};
const results = {};
const supports = {};
/**
* Generate features tests that cache their results.
*/
for (const key in featureTests) {
supports[key] = () => {
if (results[key] === undefined)
results[key] = featureTests[key]();
return results[key];
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/index.mjs
/**
* A list of values that can be hardware-accelerated.
*/
const acceleratedValues = new Set(["opacity"]);
const createMotionValueAnimation = (valueName, value, target, transition = {}) => {
return (onComplete) => {
const valueTransition = getValueTransition(transition, valueName) || {};
/**
* Most transition values are currently completely overwritten by value-specific
* transitions. In the future it'd be nicer to blend these transitions. But for now
* delay actually does inherit from the root transition if not value-specific.
*/
const delay = valueTransition.delay || transition.delay || 0;
/**
* Elapsed isn't a public transition option but can be passed through from
* optimized appear effects in milliseconds.
*/
let { elapsed = 0 } = transition;
elapsed = elapsed - secondsToMilliseconds(delay);
const keyframes = getKeyframes(value, valueName, target, valueTransition);
/**
* Check if we're able to animate between the start and end keyframes,
* and throw a warning if we're attempting to animate between one that's
* animatable and another that isn't.
*/
const originKeyframe = keyframes[0];
const targetKeyframe = keyframes[keyframes.length - 1];
const isOriginAnimatable = isAnimatable(valueName, originKeyframe);
const isTargetAnimatable = isAnimatable(valueName, targetKeyframe);
warning(isOriginAnimatable === isTargetAnimatable, `You are trying to animate ${valueName} from "${originKeyframe}" to "${targetKeyframe}". ${originKeyframe} is not an animatable value - to enable this animation set ${originKeyframe} to a value animatable to ${targetKeyframe} via the \`style\` property.`);
let options = {
keyframes,
velocity: value.getVelocity(),
...valueTransition,
elapsed,
onUpdate: (v) => {
value.set(v);
valueTransition.onUpdate && valueTransition.onUpdate(v);
},
onComplete: () => {
onComplete();
valueTransition.onComplete && valueTransition.onComplete();
},
};
if (!isOriginAnimatable ||
!isTargetAnimatable ||
instantAnimationState.current ||
valueTransition.type === false) {
/**
* If we can't animate this value, or the global instant animation flag is set,
* or this is simply defined as an instant transition, return an instant transition.
*/
return createInstantAnimation(options);
}
else if (valueTransition.type === "inertia") {
/**
* If this is an inertia animation, we currently don't support pre-generating
* keyframes for this as such it must always run on the main thread.
*/
const animation = inertia(options);
return () => animation.stop();
}
/**
* If there's no transition defined for this value, we can generate
* unqiue transition settings for this value.
*/
if (!isTransitionDefined(valueTransition)) {
options = {
...options,
...getDefaultTransition(valueName, options),
};
}
/**
* Both WAAPI and our internal animation functions use durations
* as defined by milliseconds, while our external API defines them
* as seconds.
*/
if (options.duration) {
options.duration = secondsToMilliseconds(options.duration);
}
if (options.repeatDelay) {
options.repeatDelay = secondsToMilliseconds(options.repeatDelay);
}
const visualElement = value.owner;
const element = visualElement && visualElement.current;
const canAccelerateAnimation = supports.waapi() &&
acceleratedValues.has(valueName) &&
!options.repeatDelay &&
options.repeatType !== "mirror" &&
options.damping !== 0 &&
visualElement &&
element instanceof HTMLElement &&
!visualElement.getProps().onUpdate;
if (canAccelerateAnimation) {
/**
* If this animation is capable of being run via WAAPI, then do so.
*/
return createAcceleratedAnimation(value, valueName, options);
}
else {
/**
* Otherwise, fall back to the main thread.
*/
const animation = animate(options);
return () => animation.stop();
}
};
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/utils/animation.mjs
function animateVisualElement(visualElement, definition, options = {}) {
visualElement.notify("AnimationStart", definition);
let animation;
if (Array.isArray(definition)) {
const animations = definition.map((variant) => animateVariant(visualElement, variant, options));
animation = Promise.all(animations);
}
else if (typeof definition === "string") {
animation = animateVariant(visualElement, definition, options);
}
else {
const resolvedDefinition = typeof definition === "function"
? resolveVariant(visualElement, definition, options.custom)
: definition;
animation = animateTarget(visualElement, resolvedDefinition, options);
}
return animation.then(() => visualElement.notify("AnimationComplete", definition));
}
function animateVariant(visualElement, variant, options = {}) {
var _a;
const resolved = resolveVariant(visualElement, variant, options.custom);
let { transition = visualElement.getDefaultTransition() || {} } = resolved || {};
if (options.transitionOverride) {
transition = options.transitionOverride;
}
/**
* If we have a variant, create a callback that runs it as an animation.
* Otherwise, we resolve a Promise immediately for a composable no-op.
*/
const getAnimation = resolved
? () => animateTarget(visualElement, resolved, options)
: () => Promise.resolve();
/**
* If we have children, create a callback that runs all their animations.
* Otherwise, we resolve a Promise immediately for a composable no-op.
*/
const getChildAnimations = ((_a = visualElement.variantChildren) === null || _a === void 0 ? void 0 : _a.size)
? (forwardDelay = 0) => {
const { delayChildren = 0, staggerChildren, staggerDirection, } = transition;
return animateChildren(visualElement, variant, delayChildren + forwardDelay, staggerChildren, staggerDirection, options);
}
: () => Promise.resolve();
/**
* If the transition explicitly defines a "when" option, we need to resolve either
* this animation or all children animations before playing the other.
*/
const { when } = transition;
if (when) {
const [first, last] = when === "beforeChildren"
? [getAnimation, getChildAnimations]
: [getChildAnimations, getAnimation];
return first().then(last);
}
else {
return Promise.all([getAnimation(), getChildAnimations(options.delay)]);
}
}
/**
* @internal
*/
function animateTarget(visualElement, definition, { delay = 0, transitionOverride, type } = {}) {
var _a;
let { transition = visualElement.getDefaultTransition(), transitionEnd, ...target } = visualElement.makeTargetAnimatable(definition);
const willChange = visualElement.getValue("willChange");
if (transitionOverride)
transition = transitionOverride;
const animations = [];
const animationTypeState = type && ((_a = visualElement.animationState) === null || _a === void 0 ? void 0 : _a.getState()[type]);
for (const key in target) {
const value = visualElement.getValue(key);
const valueTarget = target[key];
if (!value ||
valueTarget === undefined ||
(animationTypeState &&
shouldBlockAnimation(animationTypeState, key))) {
continue;
}
let valueTransition = { delay, elapsed: 0, ...transition };
/**
* Make animation instant if this is a transform prop and we should reduce motion.
*/
if (visualElement.shouldReduceMotion && transformProps.has(key)) {
valueTransition = {
...valueTransition,
type: false,
delay: 0,
};
}
/**
* If this is the first time a value is being animated, check
* to see if we're handling off from an existing animation.
*/
if (!value.hasAnimated) {
const appearId = visualElement.getProps()[optimizedAppearDataAttribute];
if (appearId) {
valueTransition.elapsed = handoffOptimizedAppearAnimation(appearId, key);
}
}
let animation = value.start(createMotionValueAnimation(key, value, valueTarget, valueTransition));
if (isWillChangeMotionValue(willChange)) {
willChange.add(key);
animation = animation.then(() => willChange.remove(key));
}
animations.push(animation);
}
return Promise.all(animations).then(() => {
transitionEnd && setTarget(visualElement, transitionEnd);
});
}
function animateChildren(visualElement, variant, delayChildren = 0, staggerChildren = 0, staggerDirection = 1, options) {
const animations = [];
const maxStaggerDuration = (visualElement.variantChildren.size - 1) * staggerChildren;
const generateStaggerDuration = staggerDirection === 1
? (i = 0) => i * staggerChildren
: (i = 0) => maxStaggerDuration - i * staggerChildren;
Array.from(visualElement.variantChildren)
.sort(sortByTreeOrder)
.forEach((child, i) => {
animations.push(animateVariant(child, variant, {
...options,
delay: delayChildren + generateStaggerDuration(i),
}).then(() => child.notify("AnimationComplete", variant)));
});
return Promise.all(animations);
}
function stopAnimation(visualElement) {
visualElement.values.forEach((value) => value.stop());
}
function sortByTreeOrder(a, b) {
return a.sortNodePosition(b);
}
/**
* Decide whether we should block this animation. Previously, we achieved this
* just by checking whether the key was listed in protectedKeys, but this
* posed problems if an animation was triggered by afterChildren and protectedKeys
* had been set to true in the meantime.
*/
function shouldBlockAnimation({ protectedKeys, needsAnimating }, key) {
const shouldBlock = protectedKeys.hasOwnProperty(key) && needsAnimating[key] !== true;
needsAnimating[key] = false;
return shouldBlock;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/utils/animation-state.mjs
const variantPriorityOrder = [
AnimationType.Animate,
AnimationType.InView,
AnimationType.Focus,
AnimationType.Hover,
AnimationType.Tap,
AnimationType.Drag,
AnimationType.Exit,
];
const reversePriorityOrder = [...variantPriorityOrder].reverse();
const numAnimationTypes = variantPriorityOrder.length;
function animateList(visualElement) {
return (animations) => Promise.all(animations.map(({ animation, options }) => animateVisualElement(visualElement, animation, options)));
}
function createAnimationState(visualElement) {
let animate = animateList(visualElement);
const state = createState();
let isInitialRender = true;
/**
* This function will be used to reduce the animation definitions for
* each active animation type into an object of resolved values for it.
*/
const buildResolvedTypeValues = (acc, definition) => {
const resolved = resolveVariant(visualElement, definition);
if (resolved) {
const { transition, transitionEnd, ...target } = resolved;
acc = { ...acc, ...target, ...transitionEnd };
}
return acc;
};
/**
* This just allows us to inject mocked animation functions
* @internal
*/
function setAnimateFunction(makeAnimator) {
animate = makeAnimator(visualElement);
}
/**
* When we receive new props, we need to:
* 1. Create a list of protected keys for each type. This is a directory of
* value keys that are currently being "handled" by types of a higher priority
* so that whenever an animation is played of a given type, these values are
* protected from being animated.
* 2. Determine if an animation type needs animating.
* 3. Determine if any values have been removed from a type and figure out
* what to animate those to.
*/
function animateChanges(options, changedActiveType) {
const props = visualElement.getProps();
const context = visualElement.getVariantContext(true) || {};
/**
* A list of animations that we'll build into as we iterate through the animation
* types. This will get executed at the end of the function.
*/
const animations = [];
/**
* Keep track of which values have been removed. Then, as we hit lower priority
* animation types, we can check if they contain removed values and animate to that.
*/
const removedKeys = new Set();
/**
* A dictionary of all encountered keys. This is an object to let us build into and
* copy it without iteration. Each time we hit an animation type we set its protected
* keys - the keys its not allowed to animate - to the latest version of this object.
*/
let encounteredKeys = {};
/**
* If a variant has been removed at a given index, and this component is controlling
* variant animations, we want to ensure lower-priority variants are forced to animate.
*/
let removedVariantIndex = Infinity;
/**
* Iterate through all animation types in reverse priority order. For each, we want to
* detect which values it's handling and whether or not they've changed (and therefore
* need to be animated). If any values have been removed, we want to detect those in
* lower priority props and flag for animation.
*/
for (let i = 0; i < numAnimationTypes; i++) {
const type = reversePriorityOrder[i];
const typeState = state[type];
const prop = props[type] !== undefined ? props[type] : context[type];
const propIsVariant = isVariantLabel(prop);
/**
* If this type has *just* changed isActive status, set activeDelta
* to that status. Otherwise set to null.
*/
const activeDelta = type === changedActiveType ? typeState.isActive : null;
if (activeDelta === false)
removedVariantIndex = i;
/**
* If this prop is an inherited variant, rather than been set directly on the
* component itself, we want to make sure we allow the parent to trigger animations.
*
* TODO: Can probably change this to a !isControllingVariants check
*/
let isInherited = prop === context[type] && prop !== props[type] && propIsVariant;
/**
*
*/
if (isInherited &&
isInitialRender &&
visualElement.manuallyAnimateOnMount) {
isInherited = false;
}
/**
* Set all encountered keys so far as the protected keys for this type. This will
* be any key that has been animated or otherwise handled by active, higher-priortiy types.
*/
typeState.protectedKeys = { ...encounteredKeys };
// Check if we can skip analysing this prop early
if (
// If it isn't active and hasn't *just* been set as inactive
(!typeState.isActive && activeDelta === null) ||
// If we didn't and don't have any defined prop for this animation type
(!prop && !typeState.prevProp) ||
// Or if the prop doesn't define an animation
isAnimationControls(prop) ||
typeof prop === "boolean") {
continue;
}
/**
* As we go look through the values defined on this type, if we detect
* a changed value or a value that was removed in a higher priority, we set
* this to true and add this prop to the animation list.
*/
const variantDidChange = checkVariantsDidChange(typeState.prevProp, prop);
let shouldAnimateType = variantDidChange ||
// If we're making this variant active, we want to always make it active
(type === changedActiveType &&
typeState.isActive &&
!isInherited &&
propIsVariant) ||
// If we removed a higher-priority variant (i is in reverse order)
(i > removedVariantIndex && propIsVariant);
/**
* As animations can be set as variant lists, variants or target objects, we
* coerce everything to an array if it isn't one already
*/
const definitionList = Array.isArray(prop) ? prop : [prop];
/**
* Build an object of all the resolved values. We'll use this in the subsequent
* animateChanges calls to determine whether a value has changed.
*/
let resolvedValues = definitionList.reduce(buildResolvedTypeValues, {});
if (activeDelta === false)
resolvedValues = {};
/**
* Now we need to loop through all the keys in the prev prop and this prop,
* and decide:
* 1. If the value has changed, and needs animating
* 2. If it has been removed, and needs adding to the removedKeys set
* 3. If it has been removed in a higher priority type and needs animating
* 4. If it hasn't been removed in a higher priority but hasn't changed, and
* needs adding to the type's protectedKeys list.
*/
const { prevResolvedValues = {} } = typeState;
const allKeys = {
...prevResolvedValues,
...resolvedValues,
};
const markToAnimate = (key) => {
shouldAnimateType = true;
removedKeys.delete(key);
typeState.needsAnimating[key] = true;
};
for (const key in allKeys) {
const next = resolvedValues[key];
const prev = prevResolvedValues[key];
// If we've already handled this we can just skip ahead
if (encounteredKeys.hasOwnProperty(key))
continue;
/**
* If the value has changed, we probably want to animate it.
*/
if (next !== prev) {
/**
* If both values are keyframes, we need to shallow compare them to
* detect whether any value has changed. If it has, we animate it.
*/
if (isKeyframesTarget(next) && isKeyframesTarget(prev)) {
if (!shallowCompare(next, prev) || variantDidChange) {
markToAnimate(key);
}
else {
/**
* If it hasn't changed, we want to ensure it doesn't animate by
* adding it to the list of protected keys.
*/
typeState.protectedKeys[key] = true;
}
}
else if (next !== undefined) {
// If next is defined and doesn't equal prev, it needs animating
markToAnimate(key);
}
else {
// If it's undefined, it's been removed.
removedKeys.add(key);
}
}
else if (next !== undefined && removedKeys.has(key)) {
/**
* If next hasn't changed and it isn't undefined, we want to check if it's
* been removed by a higher priority
*/
markToAnimate(key);
}
else {
/**
* If it hasn't changed, we add it to the list of protected values
* to ensure it doesn't get animated.
*/
typeState.protectedKeys[key] = true;
}
}
/**
* Update the typeState so next time animateChanges is called we can compare the
* latest prop and resolvedValues to these.
*/
typeState.prevProp = prop;
typeState.prevResolvedValues = resolvedValues;
/**
*
*/
if (typeState.isActive) {
encounteredKeys = { ...encounteredKeys, ...resolvedValues };
}
if (isInitialRender && visualElement.blockInitialAnimation) {
shouldAnimateType = false;
}
/**
* If this is an inherited prop we want to hard-block animations
* TODO: Test as this should probably still handle animations triggered
* by removed values?
*/
if (shouldAnimateType && !isInherited) {
animations.push(...definitionList.map((animation) => ({
animation: animation,
options: { type, ...options },
})));
}
}
/**
* If there are some removed value that haven't been dealt with,
* we need to create a new animation that falls back either to the value
* defined in the style prop, or the last read value.
*/
if (removedKeys.size) {
const fallbackAnimation = {};
removedKeys.forEach((key) => {
const fallbackTarget = visualElement.getBaseTarget(key);
if (fallbackTarget !== undefined) {
fallbackAnimation[key] = fallbackTarget;
}
});
animations.push({ animation: fallbackAnimation });
}
let shouldAnimate = Boolean(animations.length);
if (isInitialRender &&
props.initial === false &&
!visualElement.manuallyAnimateOnMount) {
shouldAnimate = false;
}
isInitialRender = false;
return shouldAnimate ? animate(animations) : Promise.resolve();
}
/**
* Change whether a certain animation type is active.
*/
function setActive(type, isActive, options) {
var _a;
// If the active state hasn't changed, we can safely do nothing here
if (state[type].isActive === isActive)
return Promise.resolve();
// Propagate active change to children
(_a = visualElement.variantChildren) === null || _a === void 0 ? void 0 : _a.forEach((child) => { var _a; return (_a = child.animationState) === null || _a === void 0 ? void 0 : _a.setActive(type, isActive); });
state[type].isActive = isActive;
const animations = animateChanges(options, type);
for (const key in state) {
state[key].protectedKeys = {};
}
return animations;
}
return {
animateChanges,
setActive,
setAnimateFunction,
getState: () => state,
};
}
function checkVariantsDidChange(prev, next) {
if (typeof next === "string") {
return next !== prev;
}
else if (Array.isArray(next)) {
return !shallowCompare(next, prev);
}
return false;
}
function createTypeState(isActive = false) {
return {
isActive,
protectedKeys: {},
needsAnimating: {},
prevResolvedValues: {},
};
}
function createState() {
return {
[AnimationType.Animate]: createTypeState(true),
[AnimationType.InView]: createTypeState(),
[AnimationType.Hover]: createTypeState(),
[AnimationType.Tap]: createTypeState(),
[AnimationType.Drag]: createTypeState(),
[AnimationType.Focus]: createTypeState(),
[AnimationType.Exit]: createTypeState(),
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/features/animations.mjs
const animations = {
animation: makeRenderlessComponent(({ visualElement, animate }) => {
/**
* We dynamically generate the AnimationState manager as it contains a reference
* to the underlying animation library. We only want to load that if we load this,
* so people can optionally code split it out using the `m` component.
*/
visualElement.animationState || (visualElement.animationState = createAnimationState(visualElement));
/**
* Subscribe any provided AnimationControls to the component's VisualElement
*/
if (isAnimationControls(animate)) {
(0,external_React_.useEffect)(() => animate.subscribe(visualElement), [animate]);
}
}),
exit: makeRenderlessComponent((props) => {
const { custom, visualElement } = props;
const [isPresent, safeToRemove] = usePresence();
const presenceContext = (0,external_React_.useContext)(PresenceContext_PresenceContext);
(0,external_React_.useEffect)(() => {
visualElement.isPresent = isPresent;
const animation = visualElement.animationState &&
visualElement.animationState.setActive(AnimationType.Exit, !isPresent, {
custom: (presenceContext && presenceContext.custom) ||
custom,
});
if (animation && !isPresent) {
animation.then(safeToRemove);
}
}, [isPresent]);
}),
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/distance.mjs
const distance = (a, b) => Math.abs(a - b);
function distance2D(a, b) {
// Multi-dimensional
const xDelta = distance(a.x, b.x);
const yDelta = distance(a.y, b.y);
return Math.sqrt(xDelta ** 2 + yDelta ** 2);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/gestures/PanSession.mjs
/**
* @internal
*/
class PanSession {
constructor(event, handlers, { transformPagePoint } = {}) {
/**
* @internal
*/
this.startEvent = null;
/**
* @internal
*/
this.lastMoveEvent = null;
/**
* @internal
*/
this.lastMoveEventInfo = null;
/**
* @internal
*/
this.handlers = {};
this.updatePoint = () => {
if (!(this.lastMoveEvent && this.lastMoveEventInfo))
return;
const info = getPanInfo(this.lastMoveEventInfo, this.history);
const isPanStarted = this.startEvent !== null;
// Only start panning if the offset is larger than 3 pixels. If we make it
// any larger than this we'll want to reset the pointer history
// on the first update to avoid visual snapping to the cursoe.
const isDistancePastThreshold = distance2D(info.offset, { x: 0, y: 0 }) >= 3;
if (!isPanStarted && !isDistancePastThreshold)
return;
const { point } = info;
const { timestamp } = frameData;
this.history.push({ ...point, timestamp });
const { onStart, onMove } = this.handlers;
if (!isPanStarted) {
onStart && onStart(this.lastMoveEvent, info);
this.startEvent = this.lastMoveEvent;
}
onMove && onMove(this.lastMoveEvent, info);
};
this.handlePointerMove = (event, info) => {
this.lastMoveEvent = event;
this.lastMoveEventInfo = transformPoint(info, this.transformPagePoint);
// Because Safari doesn't trigger mouseup events when it's above a `<select>`
if (isMouseEvent(event) && event.buttons === 0) {
this.handlePointerUp(event, info);
return;
}
// Throttle mouse move event to once per frame
sync.update(this.updatePoint, true);
};
this.handlePointerUp = (event, info) => {
this.end();
const { onEnd, onSessionEnd } = this.handlers;
const panInfo = getPanInfo(transformPoint(info, this.transformPagePoint), this.history);
if (this.startEvent && onEnd) {
onEnd(event, panInfo);
}
onSessionEnd && onSessionEnd(event, panInfo);
};
// If we have more than one touch, don't start detecting this gesture
if (isTouchEvent(event) && event.touches.length > 1)
return;
this.handlers = handlers;
this.transformPagePoint = transformPagePoint;
const info = extractEventInfo(event);
const initialInfo = transformPoint(info, this.transformPagePoint);
const { point } = initialInfo;
const { timestamp } = frameData;
this.history = [{ ...point, timestamp }];
const { onSessionStart } = handlers;
onSessionStart &&
onSessionStart(event, getPanInfo(initialInfo, this.history));
this.removeListeners = pipe(addPointerEvent(window, "pointermove", this.handlePointerMove), addPointerEvent(window, "pointerup", this.handlePointerUp), addPointerEvent(window, "pointercancel", this.handlePointerUp));
}
updateHandlers(handlers) {
this.handlers = handlers;
}
end() {
this.removeListeners && this.removeListeners();
cancelSync.update(this.updatePoint);
}
}
function transformPoint(info, transformPagePoint) {
return transformPagePoint ? { point: transformPagePoint(info.point) } : info;
}
function subtractPoint(a, b) {
return { x: a.x - b.x, y: a.y - b.y };
}
function getPanInfo({ point }, history) {
return {
point,
delta: subtractPoint(point, lastDevicePoint(history)),
offset: subtractPoint(point, startDevicePoint(history)),
velocity: PanSession_getVelocity(history, 0.1),
};
}
function startDevicePoint(history) {
return history[0];
}
function lastDevicePoint(history) {
return history[history.length - 1];
}
function PanSession_getVelocity(history, timeDelta) {
if (history.length < 2) {
return { x: 0, y: 0 };
}
let i = history.length - 1;
let timestampedPoint = null;
const lastPoint = lastDevicePoint(history);
while (i >= 0) {
timestampedPoint = history[i];
if (lastPoint.timestamp - timestampedPoint.timestamp >
secondsToMilliseconds(timeDelta)) {
break;
}
i--;
}
if (!timestampedPoint) {
return { x: 0, y: 0 };
}
const time = (lastPoint.timestamp - timestampedPoint.timestamp) / 1000;
if (time === 0) {
return { x: 0, y: 0 };
}
const currentVelocity = {
x: (lastPoint.x - timestampedPoint.x) / time,
y: (lastPoint.y - timestampedPoint.y) / time,
};
if (currentVelocity.x === Infinity) {
currentVelocity.x = 0;
}
if (currentVelocity.y === Infinity) {
currentVelocity.y = 0;
}
return currentVelocity;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/geometry/delta-calc.mjs
function calcLength(axis) {
return axis.max - axis.min;
}
function isNear(value, target = 0, maxDistance = 0.01) {
return Math.abs(value - target) <= maxDistance;
}
function calcAxisDelta(delta, source, target, origin = 0.5) {
delta.origin = origin;
delta.originPoint = mix(source.min, source.max, delta.origin);
delta.scale = calcLength(target) / calcLength(source);
if (isNear(delta.scale, 1, 0.0001) || isNaN(delta.scale))
delta.scale = 1;
delta.translate =
mix(target.min, target.max, delta.origin) - delta.originPoint;
if (isNear(delta.translate) || isNaN(delta.translate))
delta.translate = 0;
}
function calcBoxDelta(delta, source, target, origin) {
calcAxisDelta(delta.x, source.x, target.x, origin === null || origin === void 0 ? void 0 : origin.originX);
calcAxisDelta(delta.y, source.y, target.y, origin === null || origin === void 0 ? void 0 : origin.originY);
}
function calcRelativeAxis(target, relative, parent) {
target.min = parent.min + relative.min;
target.max = target.min + calcLength(relative);
}
function calcRelativeBox(target, relative, parent) {
calcRelativeAxis(target.x, relative.x, parent.x);
calcRelativeAxis(target.y, relative.y, parent.y);
}
function calcRelativeAxisPosition(target, layout, parent) {
target.min = layout.min - parent.min;
target.max = target.min + calcLength(layout);
}
function calcRelativePosition(target, layout, parent) {
calcRelativeAxisPosition(target.x, layout.x, parent.x);
calcRelativeAxisPosition(target.y, layout.y, parent.y);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/gestures/drag/utils/constraints.mjs
/**
* Apply constraints to a point. These constraints are both physical along an
* axis, and an elastic factor that determines how much to constrain the point
* by if it does lie outside the defined parameters.
*/
function applyConstraints(point, { min, max }, elastic) {
if (min !== undefined && point < min) {
// If we have a min point defined, and this is outside of that, constrain
point = elastic ? mix(min, point, elastic.min) : Math.max(point, min);
}
else if (max !== undefined && point > max) {
// If we have a max point defined, and this is outside of that, constrain
point = elastic ? mix(max, point, elastic.max) : Math.min(point, max);
}
return point;
}
/**
* Calculate constraints in terms of the viewport when defined relatively to the
* measured axis. This is measured from the nearest edge, so a max constraint of 200
* on an axis with a max value of 300 would return a constraint of 500 - axis length
*/
function calcRelativeAxisConstraints(axis, min, max) {
return {
min: min !== undefined ? axis.min + min : undefined,
max: max !== undefined
? axis.max + max - (axis.max - axis.min)
: undefined,
};
}
/**
* Calculate constraints in terms of the viewport when
* defined relatively to the measured bounding box.
*/
function calcRelativeConstraints(layoutBox, { top, left, bottom, right }) {
return {
x: calcRelativeAxisConstraints(layoutBox.x, left, right),
y: calcRelativeAxisConstraints(layoutBox.y, top, bottom),
};
}
/**
* Calculate viewport constraints when defined as another viewport-relative axis
*/
function calcViewportAxisConstraints(layoutAxis, constraintsAxis) {
let min = constraintsAxis.min - layoutAxis.min;
let max = constraintsAxis.max - layoutAxis.max;
// If the constraints axis is actually smaller than the layout axis then we can
// flip the constraints
if (constraintsAxis.max - constraintsAxis.min <
layoutAxis.max - layoutAxis.min) {
[min, max] = [max, min];
}
return { min, max };
}
/**
* Calculate viewport constraints when defined as another viewport-relative box
*/
function calcViewportConstraints(layoutBox, constraintsBox) {
return {
x: calcViewportAxisConstraints(layoutBox.x, constraintsBox.x),
y: calcViewportAxisConstraints(layoutBox.y, constraintsBox.y),
};
}
/**
* Calculate a transform origin relative to the source axis, between 0-1, that results
* in an asthetically pleasing scale/transform needed to project from source to target.
*/
function constraints_calcOrigin(source, target) {
let origin = 0.5;
const sourceLength = calcLength(source);
const targetLength = calcLength(target);
if (targetLength > sourceLength) {
origin = progress(target.min, target.max - sourceLength, source.min);
}
else if (sourceLength > targetLength) {
origin = progress(source.min, source.max - targetLength, target.min);
}
return clamp_clamp(0, 1, origin);
}
/**
* Rebase the calculated viewport constraints relative to the layout.min point.
*/
function rebaseAxisConstraints(layout, constraints) {
const relativeConstraints = {};
if (constraints.min !== undefined) {
relativeConstraints.min = constraints.min - layout.min;
}
if (constraints.max !== undefined) {
relativeConstraints.max = constraints.max - layout.min;
}
return relativeConstraints;
}
const defaultElastic = 0.35;
/**
* Accepts a dragElastic prop and returns resolved elastic values for each axis.
*/
function resolveDragElastic(dragElastic = defaultElastic) {
if (dragElastic === false) {
dragElastic = 0;
}
else if (dragElastic === true) {
dragElastic = defaultElastic;
}
return {
x: resolveAxisElastic(dragElastic, "left", "right"),
y: resolveAxisElastic(dragElastic, "top", "bottom"),
};
}
function resolveAxisElastic(dragElastic, minLabel, maxLabel) {
return {
min: resolvePointElastic(dragElastic, minLabel),
max: resolvePointElastic(dragElastic, maxLabel),
};
}
function resolvePointElastic(dragElastic, label) {
return typeof dragElastic === "number"
? dragElastic
: dragElastic[label] || 0;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/geometry/models.mjs
const createAxisDelta = () => ({
translate: 0,
scale: 1,
origin: 0,
originPoint: 0,
});
const createDelta = () => ({
x: createAxisDelta(),
y: createAxisDelta(),
});
const createAxis = () => ({ min: 0, max: 0 });
const createBox = () => ({
x: createAxis(),
y: createAxis(),
});
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/utils/each-axis.mjs
function eachAxis(callback) {
return [callback("x"), callback("y")];
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/geometry/conversion.mjs
/**
* Bounding boxes tend to be defined as top, left, right, bottom. For various operations
* it's easier to consider each axis individually. This function returns a bounding box
* as a map of single-axis min/max values.
*/
function convertBoundingBoxToBox({ top, left, right, bottom, }) {
return {
x: { min: left, max: right },
y: { min: top, max: bottom },
};
}
function convertBoxToBoundingBox({ x, y }) {
return { top: y.min, right: x.max, bottom: y.max, left: x.min };
}
/**
* Applies a TransformPoint function to a bounding box. TransformPoint is usually a function
* provided by Framer to allow measured points to be corrected for device scaling. This is used
* when measuring DOM elements and DOM event points.
*/
function transformBoxPoints(point, transformPoint) {
if (!transformPoint)
return point;
const topLeft = transformPoint({ x: point.left, y: point.top });
const bottomRight = transformPoint({ x: point.right, y: point.bottom });
return {
top: topLeft.y,
left: topLeft.x,
bottom: bottomRight.y,
right: bottomRight.x,
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/utils/has-transform.mjs
function isIdentityScale(scale) {
return scale === undefined || scale === 1;
}
function hasScale({ scale, scaleX, scaleY }) {
return (!isIdentityScale(scale) ||
!isIdentityScale(scaleX) ||
!isIdentityScale(scaleY));
}
function hasTransform(values) {
return (hasScale(values) ||
has2DTranslate(values) ||
values.z ||
values.rotate ||
values.rotateX ||
values.rotateY);
}
function has2DTranslate(values) {
return is2DTranslate(values.x) || is2DTranslate(values.y);
}
function is2DTranslate(value) {
return value && value !== "0%";
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/geometry/delta-apply.mjs
/**
* Scales a point based on a factor and an originPoint
*/
function scalePoint(point, scale, originPoint) {
const distanceFromOrigin = point - originPoint;
const scaled = scale * distanceFromOrigin;
return originPoint + scaled;
}
/**
* Applies a translate/scale delta to a point
*/
function applyPointDelta(point, translate, scale, originPoint, boxScale) {
if (boxScale !== undefined) {
point = scalePoint(point, boxScale, originPoint);
}
return scalePoint(point, scale, originPoint) + translate;
}
/**
* Applies a translate/scale delta to an axis
*/
function applyAxisDelta(axis, translate = 0, scale = 1, originPoint, boxScale) {
axis.min = applyPointDelta(axis.min, translate, scale, originPoint, boxScale);
axis.max = applyPointDelta(axis.max, translate, scale, originPoint, boxScale);
}
/**
* Applies a translate/scale delta to a box
*/
function applyBoxDelta(box, { x, y }) {
applyAxisDelta(box.x, x.translate, x.scale, x.originPoint);
applyAxisDelta(box.y, y.translate, y.scale, y.originPoint);
}
/**
* Apply a tree of deltas to a box. We do this to calculate the effect of all the transforms
* in a tree upon our box before then calculating how to project it into our desired viewport-relative box
*
* This is the final nested loop within updateLayoutDelta for future refactoring
*/
function applyTreeDeltas(box, treeScale, treePath, isSharedTransition = false) {
var _a, _b;
const treeLength = treePath.length;
if (!treeLength)
return;
// Reset the treeScale
treeScale.x = treeScale.y = 1;
let node;
let delta;
for (let i = 0; i < treeLength; i++) {
node = treePath[i];
delta = node.projectionDelta;
if (((_b = (_a = node.instance) === null || _a === void 0 ? void 0 : _a.style) === null || _b === void 0 ? void 0 : _b.display) === "contents")
continue;
if (isSharedTransition &&
node.options.layoutScroll &&
node.scroll &&
node !== node.root) {
transformBox(box, {
x: -node.scroll.offset.x,
y: -node.scroll.offset.y,
});
}
if (delta) {
// Incoporate each ancestor's scale into a culmulative treeScale for this component
treeScale.x *= delta.x.scale;
treeScale.y *= delta.y.scale;
// Apply each ancestor's calculated delta into this component's recorded layout box
applyBoxDelta(box, delta);
}
if (isSharedTransition && hasTransform(node.latestValues)) {
transformBox(box, node.latestValues);
}
}
/**
* Snap tree scale back to 1 if it's within a non-perceivable threshold.
* This will help reduce useless scales getting rendered.
*/
treeScale.x = snapToDefault(treeScale.x);
treeScale.y = snapToDefault(treeScale.y);
}
function snapToDefault(scale) {
if (Number.isInteger(scale))
return scale;
return scale > 1.0000000000001 || scale < 0.999999999999 ? scale : 1;
}
function translateAxis(axis, distance) {
axis.min = axis.min + distance;
axis.max = axis.max + distance;
}
/**
* Apply a transform to an axis from the latest resolved motion values.
* This function basically acts as a bridge between a flat motion value map
* and applyAxisDelta
*/
function transformAxis(axis, transforms, [key, scaleKey, originKey]) {
const axisOrigin = transforms[originKey] !== undefined ? transforms[originKey] : 0.5;
const originPoint = mix(axis.min, axis.max, axisOrigin);
// Apply the axis delta to the final axis
applyAxisDelta(axis, transforms[key], transforms[scaleKey], originPoint, transforms.scale);
}
/**
* The names of the motion values we want to apply as translation, scale and origin.
*/
const xKeys = ["x", "scaleX", "originX"];
const yKeys = ["y", "scaleY", "originY"];
/**
* Apply a transform to a box from the latest resolved motion values.
*/
function transformBox(box, transform) {
transformAxis(box.x, transform, xKeys);
transformAxis(box.y, transform, yKeys);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/utils/measure.mjs
function measureViewportBox(instance, transformPoint) {
return convertBoundingBoxToBox(transformBoxPoints(instance.getBoundingClientRect(), transformPoint));
}
function measurePageBox(element, rootProjectionNode, transformPagePoint) {
const viewportBox = measureViewportBox(element, transformPagePoint);
const { scroll } = rootProjectionNode;
if (scroll) {
translateAxis(viewportBox.x, scroll.offset.x);
translateAxis(viewportBox.y, scroll.offset.y);
}
return viewportBox;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/gestures/drag/VisualElementDragControls.mjs
const elementDragControls = new WeakMap();
/**
*
*/
// let latestPointerEvent: AnyPointerEvent
class VisualElementDragControls {
constructor(visualElement) {
// This is a reference to the global drag gesture lock, ensuring only one component
// can "capture" the drag of one or both axes.
// TODO: Look into moving this into pansession?
this.openGlobalLock = null;
this.isDragging = false;
this.currentDirection = null;
this.originPoint = { x: 0, y: 0 };
/**
* The permitted boundaries of travel, in pixels.
*/
this.constraints = false;
this.hasMutatedConstraints = false;
/**
* The per-axis resolved elastic values.
*/
this.elastic = createBox();
this.visualElement = visualElement;
}
start(originEvent, { snapToCursor = false } = {}) {
/**
* Don't start dragging if this component is exiting
*/
if (this.visualElement.isPresent === false)
return;
const onSessionStart = (event) => {
// Stop any animations on both axis values immediately. This allows the user to throw and catch
// the component.
this.stopAnimation();
if (snapToCursor) {
this.snapToCursor(extractEventInfo(event, "page").point);
}
};
const onStart = (event, info) => {
var _a;
// Attempt to grab the global drag gesture lock - maybe make this part of PanSession
const { drag, dragPropagation, onDragStart } = this.getProps();
if (drag && !dragPropagation) {
if (this.openGlobalLock)
this.openGlobalLock();
this.openGlobalLock = getGlobalLock(drag);
// If we don 't have the lock, don't start dragging
if (!this.openGlobalLock)
return;
}
this.isDragging = true;
this.currentDirection = null;
this.resolveConstraints();
if (this.visualElement.projection) {
this.visualElement.projection.isAnimationBlocked = true;
this.visualElement.projection.target = undefined;
}
/**
* Record gesture origin
*/
eachAxis((axis) => {
var _a, _b;
let current = this.getAxisMotionValue(axis).get() || 0;
/**
* If the MotionValue is a percentage value convert to px
*/
if (percent.test(current)) {
const measuredAxis = (_b = (_a = this.visualElement.projection) === null || _a === void 0 ? void 0 : _a.layout) === null || _b === void 0 ? void 0 : _b.layoutBox[axis];
if (measuredAxis) {
const length = calcLength(measuredAxis);
current = length * (parseFloat(current) / 100);
}
}
this.originPoint[axis] = current;
});
// Fire onDragStart event
onDragStart === null || onDragStart === void 0 ? void 0 : onDragStart(event, info);
(_a = this.visualElement.animationState) === null || _a === void 0 ? void 0 : _a.setActive(AnimationType.Drag, true);
};
const onMove = (event, info) => {
// latestPointerEvent = event
const { dragPropagation, dragDirectionLock, onDirectionLock, onDrag, } = this.getProps();
// If we didn't successfully receive the gesture lock, early return.
if (!dragPropagation && !this.openGlobalLock)
return;
const { offset } = info;
// Attempt to detect drag direction if directionLock is true
if (dragDirectionLock && this.currentDirection === null) {
this.currentDirection = getCurrentDirection(offset);
// If we've successfully set a direction, notify listener
if (this.currentDirection !== null) {
onDirectionLock === null || onDirectionLock === void 0 ? void 0 : onDirectionLock(this.currentDirection);
}
return;
}
// Update each point with the latest position
this.updateAxis("x", info.point, offset);
this.updateAxis("y", info.point, offset);
/**
* Ideally we would leave the renderer to fire naturally at the end of
* this frame but if the element is about to change layout as the result
* of a re-render we want to ensure the browser can read the latest
* bounding box to ensure the pointer and element don't fall out of sync.
*/
this.visualElement.render();
/**
* This must fire after the render call as it might trigger a state
* change which itself might trigger a layout update.
*/
onDrag === null || onDrag === void 0 ? void 0 : onDrag(event, info);
};
const onSessionEnd = (event, info) => this.stop(event, info);
this.panSession = new PanSession(originEvent, {
onSessionStart,
onStart,
onMove,
onSessionEnd,
}, { transformPagePoint: this.visualElement.getTransformPagePoint() });
}
stop(event, info) {
const isDragging = this.isDragging;
this.cancel();
if (!isDragging)
return;
const { velocity } = info;
this.startAnimation(velocity);
const { onDragEnd } = this.getProps();
onDragEnd === null || onDragEnd === void 0 ? void 0 : onDragEnd(event, info);
}
cancel() {
var _a, _b;
this.isDragging = false;
if (this.visualElement.projection) {
this.visualElement.projection.isAnimationBlocked = false;
}
(_a = this.panSession) === null || _a === void 0 ? void 0 : _a.end();
this.panSession = undefined;
const { dragPropagation } = this.getProps();
if (!dragPropagation && this.openGlobalLock) {
this.openGlobalLock();
this.openGlobalLock = null;
}
(_b = this.visualElement.animationState) === null || _b === void 0 ? void 0 : _b.setActive(AnimationType.Drag, false);
}
updateAxis(axis, _point, offset) {
const { drag } = this.getProps();
// If we're not dragging this axis, do an early return.
if (!offset || !shouldDrag(axis, drag, this.currentDirection))
return;
const axisValue = this.getAxisMotionValue(axis);
let next = this.originPoint[axis] + offset[axis];
// Apply constraints
if (this.constraints && this.constraints[axis]) {
next = applyConstraints(next, this.constraints[axis], this.elastic[axis]);
}
axisValue.set(next);
}
resolveConstraints() {
const { dragConstraints, dragElastic } = this.getProps();
const { layout } = this.visualElement.projection || {};
const prevConstraints = this.constraints;
if (dragConstraints && is_ref_object_isRefObject(dragConstraints)) {
if (!this.constraints) {
this.constraints = this.resolveRefConstraints();
}
}
else {
if (dragConstraints && layout) {
this.constraints = calcRelativeConstraints(layout.layoutBox, dragConstraints);
}
else {
this.constraints = false;
}
}
this.elastic = resolveDragElastic(dragElastic);
/**
* If we're outputting to external MotionValues, we want to rebase the measured constraints
* from viewport-relative to component-relative.
*/
if (prevConstraints !== this.constraints &&
layout &&
this.constraints &&
!this.hasMutatedConstraints) {
eachAxis((axis) => {
if (this.getAxisMotionValue(axis)) {
this.constraints[axis] = rebaseAxisConstraints(layout.layoutBox[axis], this.constraints[axis]);
}
});
}
}
resolveRefConstraints() {
const { dragConstraints: constraints, onMeasureDragConstraints } = this.getProps();
if (!constraints || !is_ref_object_isRefObject(constraints))
return false;
const constraintsElement = constraints.current;
invariant(constraintsElement !== null, "If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.");
const { projection } = this.visualElement;
// TODO
if (!projection || !projection.layout)
return false;
const constraintsBox = measurePageBox(constraintsElement, projection.root, this.visualElement.getTransformPagePoint());
let measuredConstraints = calcViewportConstraints(projection.layout.layoutBox, constraintsBox);
/**
* If there's an onMeasureDragConstraints listener we call it and
* if different constraints are returned, set constraints to that
*/
if (onMeasureDragConstraints) {
const userConstraints = onMeasureDragConstraints(convertBoxToBoundingBox(measuredConstraints));
this.hasMutatedConstraints = !!userConstraints;
if (userConstraints) {
measuredConstraints = convertBoundingBoxToBox(userConstraints);
}
}
return measuredConstraints;
}
startAnimation(velocity) {
const { drag, dragMomentum, dragElastic, dragTransition, dragSnapToOrigin, onDragTransitionEnd, } = this.getProps();
const constraints = this.constraints || {};
const momentumAnimations = eachAxis((axis) => {
if (!shouldDrag(axis, drag, this.currentDirection)) {
return;
}
let transition = (constraints === null || constraints === void 0 ? void 0 : constraints[axis]) || {};
if (dragSnapToOrigin)
transition = { min: 0, max: 0 };
/**
* Overdamp the boundary spring if `dragElastic` is disabled. There's still a frame
* of spring animations so we should look into adding a disable spring option to `inertia`.
* We could do something here where we affect the `bounceStiffness` and `bounceDamping`
* using the value of `dragElastic`.
*/
const bounceStiffness = dragElastic ? 200 : 1000000;
const bounceDamping = dragElastic ? 40 : 10000000;
const inertia = {
type: "inertia",
velocity: dragMomentum ? velocity[axis] : 0,
bounceStiffness,
bounceDamping,
timeConstant: 750,
restDelta: 1,
restSpeed: 10,
...dragTransition,
...transition,
};
// If we're not animating on an externally-provided `MotionValue` we can use the
// component's animation controls which will handle interactions with whileHover (etc),
// otherwise we just have to animate the `MotionValue` itself.
return this.startAxisValueAnimation(axis, inertia);
});
// Run all animations and then resolve the new drag constraints.
return Promise.all(momentumAnimations).then(onDragTransitionEnd);
}
startAxisValueAnimation(axis, transition) {
const axisValue = this.getAxisMotionValue(axis);
return axisValue.start(createMotionValueAnimation(axis, axisValue, 0, transition));
}
stopAnimation() {
eachAxis((axis) => this.getAxisMotionValue(axis).stop());
}
/**
* Drag works differently depending on which props are provided.
*
* - If _dragX and _dragY are provided, we output the gesture delta directly to those motion values.
* - Otherwise, we apply the delta to the x/y motion values.
*/
getAxisMotionValue(axis) {
var _a;
const dragKey = "_drag" + axis.toUpperCase();
const externalMotionValue = this.visualElement.getProps()[dragKey];
return externalMotionValue
? externalMotionValue
: this.visualElement.getValue(axis, ((_a = this.visualElement.getProps().initial) === null || _a === void 0 ? void 0 : _a[axis]) || 0);
}
snapToCursor(point) {
eachAxis((axis) => {
const { drag } = this.getProps();
// If we're not dragging this axis, do an early return.
if (!shouldDrag(axis, drag, this.currentDirection))
return;
const { projection } = this.visualElement;
const axisValue = this.getAxisMotionValue(axis);
if (projection && projection.layout) {
const { min, max } = projection.layout.layoutBox[axis];
axisValue.set(point[axis] - mix(min, max, 0.5));
}
});
}
/**
* When the viewport resizes we want to check if the measured constraints
* have changed and, if so, reposition the element within those new constraints
* relative to where it was before the resize.
*/
scalePositionWithinConstraints() {
var _a;
if (!this.visualElement.current)
return;
const { drag, dragConstraints } = this.getProps();
const { projection } = this.visualElement;
if (!is_ref_object_isRefObject(dragConstraints) || !projection || !this.constraints)
return;
/**
* Stop current animations as there can be visual glitching if we try to do
* this mid-animation
*/
this.stopAnimation();
/**
* Record the relative position of the dragged element relative to the
* constraints box and save as a progress value.
*/
const boxProgress = { x: 0, y: 0 };
eachAxis((axis) => {
const axisValue = this.getAxisMotionValue(axis);
if (axisValue) {
const latest = axisValue.get();
boxProgress[axis] = constraints_calcOrigin({ min: latest, max: latest }, this.constraints[axis]);
}
});
/**
* Update the layout of this element and resolve the latest drag constraints
*/
const { transformTemplate } = this.visualElement.getProps();
this.visualElement.current.style.transform = transformTemplate
? transformTemplate({}, "")
: "none";
(_a = projection.root) === null || _a === void 0 ? void 0 : _a.updateScroll();
projection.updateLayout();
this.resolveConstraints();
/**
* For each axis, calculate the current progress of the layout axis
* within the new constraints.
*/
eachAxis((axis) => {
if (!shouldDrag(axis, drag, null))
return;
/**
* Calculate a new transform based on the previous box progress
*/
const axisValue = this.getAxisMotionValue(axis);
const { min, max } = this.constraints[axis];
axisValue.set(mix(min, max, boxProgress[axis]));
});
}
addListeners() {
var _a;
if (!this.visualElement.current)
return;
elementDragControls.set(this.visualElement, this);
const element = this.visualElement.current;
/**
* Attach a pointerdown event listener on this DOM element to initiate drag tracking.
*/
const stopPointerListener = addPointerEvent(element, "pointerdown", (event) => {
const { drag, dragListener = true } = this.getProps();
drag && dragListener && this.start(event);
});
const measureDragConstraints = () => {
const { dragConstraints } = this.getProps();
if (is_ref_object_isRefObject(dragConstraints)) {
this.constraints = this.resolveRefConstraints();
}
};
const { projection } = this.visualElement;
const stopMeasureLayoutListener = projection.addEventListener("measure", measureDragConstraints);
if (projection && !projection.layout) {
(_a = projection.root) === null || _a === void 0 ? void 0 : _a.updateScroll();
projection.updateLayout();
}
measureDragConstraints();
/**
* Attach a window resize listener to scale the draggable target within its defined
* constraints as the window resizes.
*/
const stopResizeListener = addDomEvent(window, "resize", () => this.scalePositionWithinConstraints());
/**
* If the element's layout changes, calculate the delta and apply that to
* the drag gesture's origin point.
*/
const stopLayoutUpdateListener = projection.addEventListener("didUpdate", (({ delta, hasLayoutChanged }) => {
if (this.isDragging && hasLayoutChanged) {
eachAxis((axis) => {
const motionValue = this.getAxisMotionValue(axis);
if (!motionValue)
return;
this.originPoint[axis] += delta[axis].translate;
motionValue.set(motionValue.get() + delta[axis].translate);
});
this.visualElement.render();
}
}));
return () => {
stopResizeListener();
stopPointerListener();
stopMeasureLayoutListener();
stopLayoutUpdateListener === null || stopLayoutUpdateListener === void 0 ? void 0 : stopLayoutUpdateListener();
};
}
getProps() {
const props = this.visualElement.getProps();
const { drag = false, dragDirectionLock = false, dragPropagation = false, dragConstraints = false, dragElastic = defaultElastic, dragMomentum = true, } = props;
return {
...props,
drag,
dragDirectionLock,
dragPropagation,
dragConstraints,
dragElastic,
dragMomentum,
};
}
}
function shouldDrag(direction, drag, currentDirection) {
return ((drag === true || drag === direction) &&
(currentDirection === null || currentDirection === direction));
}
/**
* Based on an x/y offset determine the current drag direction. If both axis' offsets are lower
* than the provided threshold, return `null`.
*
* @param offset - The x/y offset from origin.
* @param lockThreshold - (Optional) - the minimum absolute offset before we can determine a drag direction.
*/
function getCurrentDirection(offset, lockThreshold = 10) {
let direction = null;
if (Math.abs(offset.y) > lockThreshold) {
direction = "y";
}
else if (Math.abs(offset.x) > lockThreshold) {
direction = "x";
}
return direction;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/gestures/drag/use-drag.mjs
/**
* A hook that allows an element to be dragged.
*
* @internal
*/
function useDrag(props) {
const { dragControls: groupDragControls, visualElement } = props;
const dragControls = useConstant(() => new VisualElementDragControls(visualElement));
// If we've been provided a DragControls for manual control over the drag gesture,
// subscribe this component to it on mount.
(0,external_React_.useEffect)(() => groupDragControls && groupDragControls.subscribe(dragControls), [dragControls, groupDragControls]);
// Apply the event listeners to the element
(0,external_React_.useEffect)(() => dragControls.addListeners(), [dragControls]);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/gestures/use-pan-gesture.mjs
/**
*
* @param handlers -
* @param ref -
*
* @privateRemarks
* Currently this sets new pan gesture functions every render. The memo route has been explored
* in the past but ultimately we're still creating new functions every render. An optimisation
* to explore is creating the pan gestures and loading them into a `ref`.
*
* @internal
*/
function usePanGesture({ onPan, onPanStart, onPanEnd, onPanSessionStart, visualElement, }) {
const hasPanEvents = onPan || onPanStart || onPanEnd || onPanSessionStart;
const panSession = (0,external_React_.useRef)(null);
const { transformPagePoint } = (0,external_React_.useContext)(MotionConfigContext);
const handlers = {
onSessionStart: onPanSessionStart,
onStart: onPanStart,
onMove: onPan,
onEnd: (event, info) => {
panSession.current = null;
onPanEnd && onPanEnd(event, info);
},
};
(0,external_React_.useEffect)(() => {
if (panSession.current !== null) {
panSession.current.updateHandlers(handlers);
}
});
function onPointerDown(event) {
panSession.current = new PanSession(event, handlers, {
transformPagePoint,
});
}
usePointerEvent(visualElement, "pointerdown", hasPanEvents && onPointerDown);
useUnmountEffect(() => panSession.current && panSession.current.end());
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/features/drag.mjs
const drag = {
pan: makeRenderlessComponent(usePanGesture),
drag: makeRenderlessComponent(useDrag),
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/utils/css-variables-conversion.mjs
function css_variables_conversion_isCSSVariable(value) {
return typeof value === "string" && value.startsWith("var(--");
}
/**
* Parse Framer's special CSS variable format into a CSS token and a fallback.
*
* ```
* `var(--foo, #fff)` => [`--foo`, '#fff']
* ```
*
* @param current
*/
const cssVariableRegex = /var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/;
function parseCSSVariable(current) {
const match = cssVariableRegex.exec(current);
if (!match)
return [,];
const [, token, fallback] = match;
return [token, fallback];
}
const maxDepth = 4;
function getVariableValue(current, element, depth = 1) {
invariant(depth <= maxDepth, `Max CSS variable fallback depth detected in property "${current}". This may indicate a circular fallback dependency.`);
const [token, fallback] = parseCSSVariable(current);
// No CSS variable detected
if (!token)
return;
// Attempt to read this CSS variable off the element
const resolved = window.getComputedStyle(element).getPropertyValue(token);
if (resolved) {
return resolved.trim();
}
else if (css_variables_conversion_isCSSVariable(fallback)) {
// The fallback might itself be a CSS variable, in which case we attempt to resolve it too.
return getVariableValue(fallback, element, depth + 1);
}
else {
return fallback;
}
}
/**
* Resolve CSS variables from
*
* @internal
*/
function resolveCSSVariables(visualElement, { ...target }, transitionEnd) {
const element = visualElement.current;
if (!(element instanceof Element))
return { target, transitionEnd };
// If `transitionEnd` isn't `undefined`, clone it. We could clone `target` and `transitionEnd`
// only if they change but I think this reads clearer and this isn't a performance-critical path.
if (transitionEnd) {
transitionEnd = { ...transitionEnd };
}
// Go through existing `MotionValue`s and ensure any existing CSS variables are resolved
visualElement.values.forEach((value) => {
const current = value.get();
if (!css_variables_conversion_isCSSVariable(current))
return;
const resolved = getVariableValue(current, element);
if (resolved)
value.set(resolved);
});
// Cycle through every target property and resolve CSS variables. Currently
// we only read single-var properties like `var(--foo)`, not `calc(var(--foo) + 20px)`
for (const key in target) {
const current = target[key];
if (!css_variables_conversion_isCSSVariable(current))
continue;
const resolved = getVariableValue(current, element);
if (!resolved)
continue;
// Clone target if it hasn't already been
target[key] = resolved;
// If the user hasn't already set this key on `transitionEnd`, set it to the unresolved
// CSS variable. This will ensure that after the animation the component will reflect
// changes in the value of the CSS variable.
if (transitionEnd && transitionEnd[key] === undefined) {
transitionEnd[key] = current;
}
}
return { target, transitionEnd };
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/utils/unit-conversion.mjs
const positionalKeys = new Set([
"width",
"height",
"top",
"left",
"right",
"bottom",
"x",
"y",
]);
const isPositionalKey = (key) => positionalKeys.has(key);
const hasPositionalKey = (target) => {
return Object.keys(target).some(isPositionalKey);
};
const setAndResetVelocity = (value, to) => {
// Looks odd but setting it twice doesn't render, it'll just
// set both prev and current to the latest value
value.set(to, false);
value.set(to);
};
const isNumOrPxType = (v) => v === number || v === px;
var BoundingBoxDimension;
(function (BoundingBoxDimension) {
BoundingBoxDimension["width"] = "width";
BoundingBoxDimension["height"] = "height";
BoundingBoxDimension["left"] = "left";
BoundingBoxDimension["right"] = "right";
BoundingBoxDimension["top"] = "top";
BoundingBoxDimension["bottom"] = "bottom";
})(BoundingBoxDimension || (BoundingBoxDimension = {}));
const getPosFromMatrix = (matrix, pos) => parseFloat(matrix.split(", ")[pos]);
const getTranslateFromMatrix = (pos2, pos3) => (_bbox, { transform }) => {
if (transform === "none" || !transform)
return 0;
const matrix3d = transform.match(/^matrix3d\((.+)\)$/);
if (matrix3d) {
return getPosFromMatrix(matrix3d[1], pos3);
}
else {
const matrix = transform.match(/^matrix\((.+)\)$/);
if (matrix) {
return getPosFromMatrix(matrix[1], pos2);
}
else {
return 0;
}
}
};
const transformKeys = new Set(["x", "y", "z"]);
const nonTranslationalTransformKeys = transformPropOrder.filter((key) => !transformKeys.has(key));
function removeNonTranslationalTransform(visualElement) {
const removedTransforms = [];
nonTranslationalTransformKeys.forEach((key) => {
const value = visualElement.getValue(key);
if (value !== undefined) {
removedTransforms.push([key, value.get()]);
value.set(key.startsWith("scale") ? 1 : 0);
}
});
// Apply changes to element before measurement
if (removedTransforms.length)
visualElement.render();
return removedTransforms;
}
const positionalValues = {
// Dimensions
width: ({ x }, { paddingLeft = "0", paddingRight = "0" }) => x.max - x.min - parseFloat(paddingLeft) - parseFloat(paddingRight),
height: ({ y }, { paddingTop = "0", paddingBottom = "0" }) => y.max - y.min - parseFloat(paddingTop) - parseFloat(paddingBottom),
top: (_bbox, { top }) => parseFloat(top),
left: (_bbox, { left }) => parseFloat(left),
bottom: ({ y }, { top }) => parseFloat(top) + (y.max - y.min),
right: ({ x }, { left }) => parseFloat(left) + (x.max - x.min),
// Transform
x: getTranslateFromMatrix(4, 13),
y: getTranslateFromMatrix(5, 14),
};
const convertChangedValueTypes = (target, visualElement, changedKeys) => {
const originBbox = visualElement.measureViewportBox();
const element = visualElement.current;
const elementComputedStyle = getComputedStyle(element);
const { display } = elementComputedStyle;
const origin = {};
// If the element is currently set to display: "none", make it visible before
// measuring the target bounding box
if (display === "none") {
visualElement.setStaticValue("display", target.display || "block");
}
/**
* Record origins before we render and update styles
*/
changedKeys.forEach((key) => {
origin[key] = positionalValues[key](originBbox, elementComputedStyle);
});
// Apply the latest values (as set in checkAndConvertChangedValueTypes)
visualElement.render();
const targetBbox = visualElement.measureViewportBox();
changedKeys.forEach((key) => {
// Restore styles to their **calculated computed style**, not their actual
// originally set style. This allows us to animate between equivalent pixel units.
const value = visualElement.getValue(key);
setAndResetVelocity(value, origin[key]);
target[key] = positionalValues[key](targetBbox, elementComputedStyle);
});
return target;
};
const checkAndConvertChangedValueTypes = (visualElement, target, origin = {}, transitionEnd = {}) => {
target = { ...target };
transitionEnd = { ...transitionEnd };
const targetPositionalKeys = Object.keys(target).filter(isPositionalKey);
// We want to remove any transform values that could affect the element's bounding box before
// it's measured. We'll reapply these later.
let removedTransformValues = [];
let hasAttemptedToRemoveTransformValues = false;
const changedValueTypeKeys = [];
targetPositionalKeys.forEach((key) => {
const value = visualElement.getValue(key);
if (!visualElement.hasValue(key))
return;
let from = origin[key];
let fromType = findDimensionValueType(from);
const to = target[key];
let toType;
// TODO: The current implementation of this basically throws an error
// if you try and do value conversion via keyframes. There's probably
// a way of doing this but the performance implications would need greater scrutiny,
// as it'd be doing multiple resize-remeasure operations.
if (isKeyframesTarget(to)) {
const numKeyframes = to.length;
const fromIndex = to[0] === null ? 1 : 0;
from = to[fromIndex];
fromType = findDimensionValueType(from);
for (let i = fromIndex; i < numKeyframes; i++) {
if (!toType) {
toType = findDimensionValueType(to[i]);
invariant(toType === fromType ||
(isNumOrPxType(fromType) && isNumOrPxType(toType)), "Keyframes must be of the same dimension as the current value");
}
else {
invariant(findDimensionValueType(to[i]) === toType, "All keyframes must be of the same type");
}
}
}
else {
toType = findDimensionValueType(to);
}
if (fromType !== toType) {
// If they're both just number or px, convert them both to numbers rather than
// relying on resize/remeasure to convert (which is wasteful in this situation)
if (isNumOrPxType(fromType) && isNumOrPxType(toType)) {
const current = value.get();
if (typeof current === "string") {
value.set(parseFloat(current));
}
if (typeof to === "string") {
target[key] = parseFloat(to);
}
else if (Array.isArray(to) && toType === px) {
target[key] = to.map(parseFloat);
}
}
else if ((fromType === null || fromType === void 0 ? void 0 : fromType.transform) &&
(toType === null || toType === void 0 ? void 0 : toType.transform) &&
(from === 0 || to === 0)) {
// If one or the other value is 0, it's safe to coerce it to the
// type of the other without measurement
if (from === 0) {
value.set(toType.transform(from));
}
else {
target[key] = fromType.transform(to);
}
}
else {
// If we're going to do value conversion via DOM measurements, we first
// need to remove non-positional transform values that could affect the bbox measurements.
if (!hasAttemptedToRemoveTransformValues) {
removedTransformValues =
removeNonTranslationalTransform(visualElement);
hasAttemptedToRemoveTransformValues = true;
}
changedValueTypeKeys.push(key);
transitionEnd[key] =
transitionEnd[key] !== undefined
? transitionEnd[key]
: target[key];
setAndResetVelocity(value, to);
}
}
});
if (changedValueTypeKeys.length) {
const scrollY = changedValueTypeKeys.indexOf("height") >= 0
? window.pageYOffset
: null;
const convertedTarget = convertChangedValueTypes(target, visualElement, changedValueTypeKeys);
// If we removed transform values, reapply them before the next render
if (removedTransformValues.length) {
removedTransformValues.forEach(([key, value]) => {
visualElement.getValue(key).set(value);
});
}
// Reapply original values
visualElement.render();
// Restore scroll position
if (isBrowser && scrollY !== null) {
window.scrollTo({ top: scrollY });
}
return { target: convertedTarget, transitionEnd };
}
else {
return { target, transitionEnd };
}
};
/**
* Convert value types for x/y/width/height/top/left/bottom/right
*
* Allows animation between `'auto'` -> `'100%'` or `0` -> `'calc(50% - 10vw)'`
*
* @internal
*/
function unitConversion(visualElement, target, origin, transitionEnd) {
return hasPositionalKey(target)
? checkAndConvertChangedValueTypes(visualElement, target, origin, transitionEnd)
: { target, transitionEnd };
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/utils/parse-dom-variant.mjs
/**
* Parse a DOM variant to make it animatable. This involves resolving CSS variables
* and ensuring animations like "20%" => "calc(50vw)" are performed in pixels.
*/
const parseDomVariant = (visualElement, target, origin, transitionEnd) => {
const resolved = resolveCSSVariables(visualElement, target, transitionEnd);
target = resolved.target;
transitionEnd = resolved.transitionEnd;
return unitConversion(visualElement, target, origin, transitionEnd);
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/utils/motion-values.mjs
function updateMotionValuesFromProps(element, next, prev) {
const { willChange } = next;
for (const key in next) {
const nextValue = next[key];
const prevValue = prev[key];
if (isMotionValue(nextValue)) {
/**
* If this is a motion value found in props or style, we want to add it
* to our visual element's motion value map.
*/
element.addValue(key, nextValue);
if (isWillChangeMotionValue(willChange)) {
willChange.add(key);
}
/**
* Check the version of the incoming motion value with this version
* and warn against mismatches.
*/
if (false) {}
}
else if (isMotionValue(prevValue)) {
/**
* If we're swapping from a motion value to a static value,
* create a new motion value from that
*/
element.addValue(key, motionValue(nextValue, { owner: element }));
if (isWillChangeMotionValue(willChange)) {
willChange.remove(key);
}
}
else if (prevValue !== nextValue) {
/**
* If this is a flat value that has changed, update the motion value
* or create one if it doesn't exist. We only want to do this if we're
* not handling the value with our animation state.
*/
if (element.hasValue(key)) {
const existingValue = element.getValue(key);
// TODO: Only update values that aren't being animated or even looked at
!existingValue.hasAnimated && existingValue.set(nextValue);
}
else {
const latestValue = element.getStaticValue(key);
element.addValue(key, motionValue(latestValue !== undefined ? latestValue : nextValue));
}
}
}
// Handle removed values
for (const key in prev) {
if (next[key] === undefined)
element.removeValue(key);
}
return next;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/VisualElement.mjs
const featureNames = Object.keys(featureDefinitions);
const numFeatures = featureNames.length;
const propEventHandlers = [
"AnimationStart",
"AnimationComplete",
"Update",
"Unmount",
"BeforeLayoutMeasure",
"LayoutMeasure",
"LayoutAnimationStart",
"LayoutAnimationComplete",
];
/**
* A VisualElement is an imperative abstraction around UI elements such as
* HTMLElement, SVGElement, Three.Object3D etc.
*/
class VisualElement {
constructor({ parent, props, reducedMotionConfig, visualState, }, options = {}) {
/**
* A reference to the current underlying Instance, e.g. a HTMLElement
* or Three.Mesh etc.
*/
this.current = null;
/**
* A set containing references to this VisualElement's children.
*/
this.children = new Set();
/**
* Determine what role this visual element should take in the variant tree.
*/
this.isVariantNode = false;
this.isControllingVariants = false;
/**
* Decides whether this VisualElement should animate in reduced motion
* mode.
*
* TODO: This is currently set on every individual VisualElement but feels
* like it could be set globally.
*/
this.shouldReduceMotion = null;
/**
* A map of all motion values attached to this visual element. Motion
* values are source of truth for any given animated value. A motion
* value might be provided externally by the component via props.
*/
this.values = new Map();
/**
* Tracks whether this VisualElement's React component is currently present
* within the defined React tree.
*/
this.isPresent = true;
/**
* A map of every subscription that binds the provided or generated
* motion values onChange listeners to this visual element.
*/
this.valueSubscriptions = new Map();
/**
* A reference to the previously-provided motion values as returned
* from scrapeMotionValuesFromProps. We use the keys in here to determine
* if any motion values need to be removed after props are updated.
*/
this.prevMotionValues = {};
/**
* An object containing a SubscriptionManager for each active event.
*/
this.events = {};
/**
* An object containing an unsubscribe function for each prop event subscription.
* For example, every "Update" event can have multiple subscribers via
* VisualElement.on(), but only one of those can be defined via the onUpdate prop.
*/
this.propEventSubscriptions = {};
this.notifyUpdate = () => this.notify("Update", this.latestValues);
this.render = () => {
if (!this.current)
return;
this.triggerBuild();
this.renderInstance(this.current, this.renderState, this.props.style, this.projection);
};
this.scheduleRender = () => sync.render(this.render, false, true);
const { latestValues, renderState } = visualState;
this.latestValues = latestValues;
this.baseTarget = { ...latestValues };
this.initialValues = props.initial ? { ...latestValues } : {};
this.renderState = renderState;
this.parent = parent;
this.props = props;
this.depth = parent ? parent.depth + 1 : 0;
this.reducedMotionConfig = reducedMotionConfig;
this.options = options;
this.isControllingVariants = isControllingVariants(props);
this.isVariantNode = isVariantNode(props);
if (this.isVariantNode) {
this.variantChildren = new Set();
}
this.manuallyAnimateOnMount = Boolean(parent && parent.current);
/**
* Any motion values that are provided to the element when created
* aren't yet bound to the element, as this would technically be impure.
* However, we iterate through the motion values and set them to the
* initial values for this component.
*
* TODO: This is impure and we should look at changing this to run on mount.
* Doing so will break some tests but this isn't neccessarily a breaking change,
* more a reflection of the test.
*/
const { willChange, ...initialMotionValues } = this.scrapeMotionValuesFromProps(props);
for (const key in initialMotionValues) {
const value = initialMotionValues[key];
if (latestValues[key] !== undefined && isMotionValue(value)) {
value.set(latestValues[key], false);
if (isWillChangeMotionValue(willChange)) {
willChange.add(key);
}
}
}
}
/**
* This method takes React props and returns found MotionValues. For example, HTML
* MotionValues will be found within the style prop, whereas for Three.js within attribute arrays.
*
* This isn't an abstract method as it needs calling in the constructor, but it is
* intended to be one.
*/
scrapeMotionValuesFromProps(_props) {
return {};
}
mount(instance) {
var _a;
this.current = instance;
if (this.projection) {
this.projection.mount(instance);
}
if (this.parent && this.isVariantNode && !this.isControllingVariants) {
this.removeFromVariantTree = (_a = this.parent) === null || _a === void 0 ? void 0 : _a.addVariantChild(this);
}
this.values.forEach((value, key) => this.bindToMotionValue(key, value));
if (!hasReducedMotionListener.current) {
initPrefersReducedMotion();
}
this.shouldReduceMotion =
this.reducedMotionConfig === "never"
? false
: this.reducedMotionConfig === "always"
? true
: prefersReducedMotion.current;
if (this.parent)
this.parent.children.add(this);
this.setProps(this.props);
}
unmount() {
var _a, _b, _c;
(_a = this.projection) === null || _a === void 0 ? void 0 : _a.unmount();
cancelSync.update(this.notifyUpdate);
cancelSync.render(this.render);
this.valueSubscriptions.forEach((remove) => remove());
(_b = this.removeFromVariantTree) === null || _b === void 0 ? void 0 : _b.call(this);
(_c = this.parent) === null || _c === void 0 ? void 0 : _c.children.delete(this);
for (const key in this.events) {
this.events[key].clear();
}
this.current = null;
}
bindToMotionValue(key, value) {
const valueIsTransform = transformProps.has(key);
const removeOnChange = value.on("change", (latestValue) => {
this.latestValues[key] = latestValue;
this.props.onUpdate &&
sync.update(this.notifyUpdate, false, true);
if (valueIsTransform && this.projection) {
this.projection.isTransformDirty = true;
}
});
const removeOnRenderRequest = value.on("renderRequest", this.scheduleRender);
this.valueSubscriptions.set(key, () => {
removeOnChange();
removeOnRenderRequest();
});
}
sortNodePosition(other) {
/**
* If these nodes aren't even of the same type we can't compare their depth.
*/
if (!this.current ||
!this.sortInstanceNodePosition ||
this.type !== other.type)
return 0;
return this.sortInstanceNodePosition(this.current, other.current);
}
loadFeatures(renderedProps, isStrict, preloadedFeatures, projectionId, ProjectionNodeConstructor, initialLayoutGroupConfig) {
const features = [];
/**
* If we're in development mode, check to make sure we're not rendering a motion component
* as a child of LazyMotion, as this will break the file-size benefits of using it.
*/
if (env !== "production" && preloadedFeatures && isStrict) {
invariant(false, "You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.");
}
for (let i = 0; i < numFeatures; i++) {
const name = featureNames[i];
const { isEnabled, Component } = featureDefinitions[name];
/**
* It might be possible in the future to use this moment to
* dynamically request functionality. In initial tests this
* was producing a lot of duplication amongst bundles.
*/
if (isEnabled(renderedProps) && Component) {
features.push((0,external_React_.createElement)(Component, {
key: name,
...renderedProps,
visualElement: this,
}));
}
}
if (!this.projection && ProjectionNodeConstructor) {
this.projection = new ProjectionNodeConstructor(projectionId, this.latestValues, this.parent && this.parent.projection);
const { layoutId, layout, drag, dragConstraints, layoutScroll } = renderedProps;
this.projection.setOptions({
layoutId,
layout,
alwaysMeasureLayout: Boolean(drag) ||
(dragConstraints && is_ref_object_isRefObject(dragConstraints)),
visualElement: this,
scheduleRender: () => this.scheduleRender(),
/**
* TODO: Update options in an effect. This could be tricky as it'll be too late
* to update by the time layout animations run.
* We also need to fix this safeToRemove by linking it up to the one returned by usePresence,
* ensuring it gets called if there's no potential layout animations.
*
*/
animationType: typeof layout === "string" ? layout : "both",
initialPromotionConfig: initialLayoutGroupConfig,
layoutScroll,
});
}
return features;
}
triggerBuild() {
this.build(this.renderState, this.latestValues, this.options, this.props);
}
/**
* Measure the current viewport box with or without transforms.
* Only measures axis-aligned boxes, rotate and skew must be manually
* removed with a re-render to work.
*/
measureViewportBox() {
return this.current
? this.measureInstanceViewportBox(this.current, this.props)
: createBox();
}
getStaticValue(key) {
return this.latestValues[key];
}
setStaticValue(key, value) {
this.latestValues[key] = value;
}
/**
* Make a target animatable by Popmotion. For instance, if we're
* trying to animate width from 100px to 100vw we need to measure 100vw
* in pixels to determine what we really need to animate to. This is also
* pluggable to support Framer's custom value types like Color,
* and CSS variables.
*/
makeTargetAnimatable(target, canMutate = true) {
return this.makeTargetAnimatableFromInstance(target, this.props, canMutate);
}
/**
* Update the provided props. Ensure any newly-added motion values are
* added to our map, old ones removed, and listeners updated.
*/
setProps(props) {
if (props.transformTemplate || this.props.transformTemplate) {
this.scheduleRender();
}
this.props = props;
/**
* Update prop event handlers ie onAnimationStart, onAnimationComplete
*/
for (let i = 0; i < propEventHandlers.length; i++) {
const key = propEventHandlers[i];
if (this.propEventSubscriptions[key]) {
this.propEventSubscriptions[key]();
delete this.propEventSubscriptions[key];
}
const listener = props["on" + key];
if (listener) {
this.propEventSubscriptions[key] = this.on(key, listener);
}
}
this.prevMotionValues = updateMotionValuesFromProps(this, this.scrapeMotionValuesFromProps(props), this.prevMotionValues);
}
getProps() {
return this.props;
}
/**
* Returns the variant definition with a given name.
*/
getVariant(name) {
var _a;
return (_a = this.props.variants) === null || _a === void 0 ? void 0 : _a[name];
}
/**
* Returns the defined default transition on this component.
*/
getDefaultTransition() {
return this.props.transition;
}
getTransformPagePoint() {
return this.props.transformPagePoint;
}
getClosestVariantNode() {
var _a;
return this.isVariantNode ? this : (_a = this.parent) === null || _a === void 0 ? void 0 : _a.getClosestVariantNode();
}
getVariantContext(startAtParent = false) {
var _a, _b;
if (startAtParent)
return (_a = this.parent) === null || _a === void 0 ? void 0 : _a.getVariantContext();
if (!this.isControllingVariants) {
const context = ((_b = this.parent) === null || _b === void 0 ? void 0 : _b.getVariantContext()) || {};
if (this.props.initial !== undefined) {
context.initial = this.props.initial;
}
return context;
}
const context = {};
for (let i = 0; i < numVariantProps; i++) {
const name = VisualElement_variantProps[i];
const prop = this.props[name];
if (isVariantLabel(prop) || prop === false) {
context[name] = prop;
}
}
return context;
}
/**
* Add a child visual element to our set of children.
*/
addVariantChild(child) {
var _a;
const closestVariantNode = this.getClosestVariantNode();
if (closestVariantNode) {
(_a = closestVariantNode.variantChildren) === null || _a === void 0 ? void 0 : _a.add(child);
return () => closestVariantNode.variantChildren.delete(child);
}
}
/**
* Add a motion value and bind it to this visual element.
*/
addValue(key, value) {
// Remove existing value if it exists
if (this.hasValue(key))
this.removeValue(key);
this.values.set(key, value);
this.latestValues[key] = value.get();
this.bindToMotionValue(key, value);
}
/**
* Remove a motion value and unbind any active subscriptions.
*/
removeValue(key) {
var _a;
this.values.delete(key);
(_a = this.valueSubscriptions.get(key)) === null || _a === void 0 ? void 0 : _a();
this.valueSubscriptions.delete(key);
delete this.latestValues[key];
this.removeValueFromRenderState(key, this.renderState);
}
/**
* Check whether we have a motion value for this key
*/
hasValue(key) {
return this.values.has(key);
}
/**
* Get a motion value for this key. If called with a default
* value, we'll create one if none exists.
*/
getValue(key, defaultValue) {
if (this.props.values && this.props.values[key]) {
return this.props.values[key];
}
let value = this.values.get(key);
if (value === undefined && defaultValue !== undefined) {
value = motionValue(defaultValue, { owner: this });
this.addValue(key, value);
}
return value;
}
/**
* If we're trying to animate to a previously unencountered value,
* we need to check for it in our state and as a last resort read it
* directly from the instance (which might have performance implications).
*/
readValue(key) {
return this.latestValues[key] !== undefined || !this.current
? this.latestValues[key]
: this.readValueFromInstance(this.current, key, this.options);
}
/**
* Set the base target to later animate back to. This is currently
* only hydrated on creation and when we first read a value.
*/
setBaseTarget(key, value) {
this.baseTarget[key] = value;
}
/**
* Find the base target for a value thats been removed from all animation
* props.
*/
getBaseTarget(key) {
var _a;
const { initial } = this.props;
const valueFromInitial = typeof initial === "string" || typeof initial === "object"
? (_a = resolveVariantFromProps(this.props, initial)) === null || _a === void 0 ? void 0 : _a[key]
: undefined;
/**
* If this value still exists in the current initial variant, read that.
*/
if (initial && valueFromInitial !== undefined) {
return valueFromInitial;
}
/**
* Alternatively, if this VisualElement config has defined a getBaseTarget
* so we can read the value from an alternative source, try that.
*/
const target = this.getBaseTargetFromProps(this.props, key);
if (target !== undefined && !isMotionValue(target))
return target;
/**
* If the value was initially defined on initial, but it doesn't any more,
* return undefined. Otherwise return the value as initially read from the DOM.
*/
return this.initialValues[key] !== undefined &&
valueFromInitial === undefined
? undefined
: this.baseTarget[key];
}
on(eventName, callback) {
if (!this.events[eventName]) {
this.events[eventName] = new SubscriptionManager();
}
return this.events[eventName].add(callback);
}
notify(eventName, ...args) {
var _a;
(_a = this.events[eventName]) === null || _a === void 0 ? void 0 : _a.notify(...args);
}
}
const VisualElement_variantProps = ["initial", ...variantPriorityOrder];
const numVariantProps = VisualElement_variantProps.length;
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/DOMVisualElement.mjs
class DOMVisualElement extends VisualElement {
sortInstanceNodePosition(a, b) {
/**
* compareDocumentPosition returns a bitmask, by using the bitwise &
* we're returning true if 2 in that bitmask is set to true. 2 is set
* to true if b preceeds a.
*/
return a.compareDocumentPosition(b) & 2 ? 1 : -1;
}
getBaseTargetFromProps(props, key) {
var _a;
return (_a = props.style) === null || _a === void 0 ? void 0 : _a[key];
}
removeValueFromRenderState(key, { vars, style }) {
delete vars[key];
delete style[key];
}
makeTargetAnimatableFromInstance({ transition, transitionEnd, ...target }, { transformValues }, isMounted) {
let origin = getOrigin(target, transition || {}, this);
/**
* If Framer has provided a function to convert `Color` etc value types, convert them
*/
if (transformValues) {
if (transitionEnd)
transitionEnd = transformValues(transitionEnd);
if (target)
target = transformValues(target);
if (origin)
origin = transformValues(origin);
}
if (isMounted) {
checkTargetForNewValues(this, target, origin);
const parsed = parseDomVariant(this, target, origin, transitionEnd);
transitionEnd = parsed.transitionEnd;
target = parsed.target;
}
return {
transition,
transitionEnd,
...target,
};
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/html/HTMLVisualElement.mjs
function HTMLVisualElement_getComputedStyle(element) {
return window.getComputedStyle(element);
}
class HTMLVisualElement extends DOMVisualElement {
readValueFromInstance(instance, key) {
if (transformProps.has(key)) {
const defaultType = getDefaultValueType(key);
return defaultType ? defaultType.default || 0 : 0;
}
else {
const computedStyle = HTMLVisualElement_getComputedStyle(instance);
const value = (isCSSVariable(key)
? computedStyle.getPropertyValue(key)
: computedStyle[key]) || 0;
return typeof value === "string" ? value.trim() : value;
}
}
measureInstanceViewportBox(instance, { transformPagePoint }) {
return measureViewportBox(instance, transformPagePoint);
}
build(renderState, latestValues, options, props) {
buildHTMLStyles(renderState, latestValues, options, props.transformTemplate);
}
scrapeMotionValuesFromProps(props) {
return scrapeMotionValuesFromProps(props);
}
renderInstance(instance, renderState, styleProp, projection) {
renderHTML(instance, renderState, styleProp, projection);
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/svg/SVGVisualElement.mjs
class SVGVisualElement extends DOMVisualElement {
constructor() {
super(...arguments);
this.isSVGTag = false;
}
getBaseTargetFromProps(props, key) {
return props[key];
}
readValueFromInstance(instance, key) {
var _a;
if (transformProps.has(key)) {
return ((_a = getDefaultValueType(key)) === null || _a === void 0 ? void 0 : _a.default) || 0;
}
key = !camelCaseAttributes.has(key) ? camelToDash(key) : key;
return instance.getAttribute(key);
}
measureInstanceViewportBox() {
return createBox();
}
scrapeMotionValuesFromProps(props) {
return scrape_motion_values_scrapeMotionValuesFromProps(props);
}
build(renderState, latestValues, options, props) {
buildSVGAttrs(renderState, latestValues, options, this.isSVGTag, props.transformTemplate);
}
renderInstance(instance, renderState, styleProp, projection) {
renderSVG(instance, renderState, styleProp, projection);
}
mount(instance) {
this.isSVGTag = isSVGTag(instance.tagName);
super.mount(instance);
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/create-visual-element.mjs
const create_visual_element_createDomVisualElement = (Component, options) => {
return isSVGComponent(Component)
? new SVGVisualElement(options, { enableHardwareAcceleration: false })
: new HTMLVisualElement(options, { enableHardwareAcceleration: true });
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/styles/scale-border-radius.mjs
function pixelsToPercent(pixels, axis) {
if (axis.max === axis.min)
return 0;
return (pixels / (axis.max - axis.min)) * 100;
}
/**
* We always correct borderRadius as a percentage rather than pixels to reduce paints.
* For example, if you are projecting a box that is 100px wide with a 10px borderRadius
* into a box that is 200px wide with a 20px borderRadius, that is actually a 10%
* borderRadius in both states. If we animate between the two in pixels that will trigger
* a paint each time. If we animate between the two in percentage we'll avoid a paint.
*/
const correctBorderRadius = {
correct: (latest, node) => {
if (!node.target)
return latest;
/**
* If latest is a string, if it's a percentage we can return immediately as it's
* going to be stretched appropriately. Otherwise, if it's a pixel, convert it to a number.
*/
if (typeof latest === "string") {
if (px.test(latest)) {
latest = parseFloat(latest);
}
else {
return latest;
}
}
/**
* If latest is a number, it's a pixel value. We use the current viewportBox to calculate that
* pixel value as a percentage of each axis
*/
const x = pixelsToPercent(latest, node.target.x);
const y = pixelsToPercent(latest, node.target.y);
return `${x}% ${y}%`;
},
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/styles/scale-box-shadow.mjs
const varToken = "_$css";
const correctBoxShadow = {
correct: (latest, { treeScale, projectionDelta }) => {
const original = latest;
/**
* We need to first strip and store CSS variables from the string.
*/
const containsCSSVariables = latest.includes("var(");
const cssVariables = [];
if (containsCSSVariables) {
latest = latest.replace(cssVariableRegex, (match) => {
cssVariables.push(match);
return varToken;
});
}
const shadow = complex.parse(latest);
// TODO: Doesn't support multiple shadows
if (shadow.length > 5)
return original;
const template = complex.createTransformer(latest);
const offset = typeof shadow[0] !== "number" ? 1 : 0;
// Calculate the overall context scale
const xScale = projectionDelta.x.scale * treeScale.x;
const yScale = projectionDelta.y.scale * treeScale.y;
shadow[0 + offset] /= xScale;
shadow[1 + offset] /= yScale;
/**
* Ideally we'd correct x and y scales individually, but because blur and
* spread apply to both we have to take a scale average and apply that instead.
* We could potentially improve the outcome of this by incorporating the ratio between
* the two scales.
*/
const averageScale = mix(xScale, yScale, 0.5);
// Blur
if (typeof shadow[2 + offset] === "number")
shadow[2 + offset] /= averageScale;
// Spread
if (typeof shadow[3 + offset] === "number")
shadow[3 + offset] /= averageScale;
let output = template(shadow);
if (containsCSSVariables) {
let i = 0;
output = output.replace(varToken, () => {
const cssVariable = cssVariables[i];
i++;
return cssVariable;
});
}
return output;
},
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/features/layout/MeasureLayout.mjs
class MeasureLayoutWithContext extends external_React_.Component {
/**
* This only mounts projection nodes for components that
* need measuring, we might want to do it for all components
* in order to incorporate transforms
*/
componentDidMount() {
const { visualElement, layoutGroup, switchLayoutGroup, layoutId } = this.props;
const { projection } = visualElement;
addScaleCorrector(defaultScaleCorrectors);
if (projection) {
if (layoutGroup.group)
layoutGroup.group.add(projection);
if (switchLayoutGroup && switchLayoutGroup.register && layoutId) {
switchLayoutGroup.register(projection);
}
projection.root.didUpdate();
projection.addEventListener("animationComplete", () => {
this.safeToRemove();
});
projection.setOptions({
...projection.options,
onExitComplete: () => this.safeToRemove(),
});
}
globalProjectionState.hasEverUpdated = true;
}
getSnapshotBeforeUpdate(prevProps) {
const { layoutDependency, visualElement, drag, isPresent } = this.props;
const projection = visualElement.projection;
if (!projection)
return null;
/**
* TODO: We use this data in relegate to determine whether to
* promote a previous element. There's no guarantee its presence data
* will have updated by this point - if a bug like this arises it will
* have to be that we markForRelegation and then find a new lead some other way,
* perhaps in didUpdate
*/
projection.isPresent = isPresent;
if (drag ||
prevProps.layoutDependency !== layoutDependency ||
layoutDependency === undefined) {
projection.willUpdate();
}
else {
this.safeToRemove();
}
if (prevProps.isPresent !== isPresent) {
if (isPresent) {
projection.promote();
}
else if (!projection.relegate()) {
/**
* If there's another stack member taking over from this one,
* it's in charge of the exit animation and therefore should
* be in charge of the safe to remove. Otherwise we call it here.
*/
sync.postRender(() => {
var _a;
if (!((_a = projection.getStack()) === null || _a === void 0 ? void 0 : _a.members.length)) {
this.safeToRemove();
}
});
}
}
return null;
}
componentDidUpdate() {
const { projection } = this.props.visualElement;
if (projection) {
projection.root.didUpdate();
if (!projection.currentAnimation && projection.isLead()) {
this.safeToRemove();
}
}
}
componentWillUnmount() {
const { visualElement, layoutGroup, switchLayoutGroup: promoteContext, } = this.props;
const { projection } = visualElement;
if (projection) {
projection.scheduleCheckAfterUnmount();
if (layoutGroup === null || layoutGroup === void 0 ? void 0 : layoutGroup.group)
layoutGroup.group.remove(projection);
if (promoteContext === null || promoteContext === void 0 ? void 0 : promoteContext.deregister)
promoteContext.deregister(projection);
}
}
safeToRemove() {
const { safeToRemove } = this.props;
safeToRemove === null || safeToRemove === void 0 ? void 0 : safeToRemove();
}
render() {
return null;
}
}
function MeasureLayout(props) {
const [isPresent, safeToRemove] = usePresence();
const layoutGroup = (0,external_React_.useContext)(LayoutGroupContext);
return (external_React_.createElement(MeasureLayoutWithContext, { ...props, layoutGroup: layoutGroup, switchLayoutGroup: (0,external_React_.useContext)(SwitchLayoutGroupContext), isPresent: isPresent, safeToRemove: safeToRemove }));
}
const defaultScaleCorrectors = {
borderRadius: {
...correctBorderRadius,
applyTo: [
"borderTopLeftRadius",
"borderTopRightRadius",
"borderBottomLeftRadius",
"borderBottomRightRadius",
],
},
borderTopLeftRadius: correctBorderRadius,
borderTopRightRadius: correctBorderRadius,
borderBottomLeftRadius: correctBorderRadius,
borderBottomRightRadius: correctBorderRadius,
boxShadow: correctBoxShadow,
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/motion/features/layout/index.mjs
const layoutFeatures = {
measureLayout: MeasureLayout,
};
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/animation/animate.mjs
/**
* Animate a single value or a `MotionValue`.
*
* The first argument is either a `MotionValue` to animate, or an initial animation value.
*
* The second is either a value to animate to, or an array of keyframes to animate through.
*
* The third argument can be either tween or spring options, and optional lifecycle methods: `onUpdate`, `onPlay`, `onComplete`, `onRepeat` and `onStop`.
*
* Returns `AnimationPlaybackControls`, currently just a `stop` method.
*
* ```javascript
* const x = useMotionValue(0)
*
* useEffect(() => {
* const controls = animate(x, 100, {
* type: "spring",
* stiffness: 2000,
* onComplete: v => {}
* })
*
* return controls.stop
* })
* ```
*
* @public
*/
function animate_animate(from, to, transition = {}) {
const value = isMotionValue(from) ? from : motionValue(from);
value.start(createMotionValueAnimation("", value, to, transition));
return {
stop: () => value.stop(),
isAnimating: () => value.isAnimating(),
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/animation/mix-values.mjs
const borders = ["TopLeft", "TopRight", "BottomLeft", "BottomRight"];
const numBorders = borders.length;
const asNumber = (value) => typeof value === "string" ? parseFloat(value) : value;
const isPx = (value) => typeof value === "number" || px.test(value);
function mixValues(target, follow, lead, progress, shouldCrossfadeOpacity, isOnlyMember) {
if (shouldCrossfadeOpacity) {
target.opacity = mix(0,
// TODO Reinstate this if only child
lead.opacity !== undefined ? lead.opacity : 1, easeCrossfadeIn(progress));
target.opacityExit = mix(follow.opacity !== undefined ? follow.opacity : 1, 0, easeCrossfadeOut(progress));
}
else if (isOnlyMember) {
target.opacity = mix(follow.opacity !== undefined ? follow.opacity : 1, lead.opacity !== undefined ? lead.opacity : 1, progress);
}
/**
* Mix border radius
*/
for (let i = 0; i < numBorders; i++) {
const borderLabel = `border${borders[i]}Radius`;
let followRadius = getRadius(follow, borderLabel);
let leadRadius = getRadius(lead, borderLabel);
if (followRadius === undefined && leadRadius === undefined)
continue;
followRadius || (followRadius = 0);
leadRadius || (leadRadius = 0);
const canMix = followRadius === 0 ||
leadRadius === 0 ||
isPx(followRadius) === isPx(leadRadius);
if (canMix) {
target[borderLabel] = Math.max(mix(asNumber(followRadius), asNumber(leadRadius), progress), 0);
if (percent.test(leadRadius) || percent.test(followRadius)) {
target[borderLabel] += "%";
}
}
else {
target[borderLabel] = leadRadius;
}
}
/**
* Mix rotation
*/
if (follow.rotate || lead.rotate) {
target.rotate = mix(follow.rotate || 0, lead.rotate || 0, progress);
}
}
function getRadius(values, radiusName) {
return values[radiusName] !== undefined
? values[radiusName]
: values.borderRadius;
}
// /**
// * We only want to mix the background color if there's a follow element
// * that we're not crossfading opacity between. For instance with switch
// * AnimateSharedLayout animations, this helps the illusion of a continuous
// * element being animated but also cuts down on the number of paints triggered
// * for elements where opacity is doing that work for us.
// */
// if (
// !hasFollowElement &&
// latestLeadValues.backgroundColor &&
// latestFollowValues.backgroundColor
// ) {
// /**
// * This isn't ideal performance-wise as mixColor is creating a new function every frame.
// * We could probably create a mixer that runs at the start of the animation but
// * the idea behind the crossfader is that it runs dynamically between two potentially
// * changing targets (ie opacity or borderRadius may be animating independently via variants)
// */
// leadState.backgroundColor = followState.backgroundColor = mixColor(
// latestFollowValues.backgroundColor as string,
// latestLeadValues.backgroundColor as string
// )(p)
// }
const easeCrossfadeIn = compress(0, 0.5, circOut);
const easeCrossfadeOut = compress(0.5, 0.95, noop);
function compress(min, max, easing) {
return (p) => {
// Could replace ifs with clamp
if (p < min)
return 0;
if (p > max)
return 1;
return easing(progress(min, max, p));
};
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/geometry/copy.mjs
/**
* Reset an axis to the provided origin box.
*
* This is a mutative operation.
*/
function copyAxisInto(axis, originAxis) {
axis.min = originAxis.min;
axis.max = originAxis.max;
}
/**
* Reset a box to the provided origin box.
*
* This is a mutative operation.
*/
function copyBoxInto(box, originBox) {
copyAxisInto(box.x, originBox.x);
copyAxisInto(box.y, originBox.y);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/geometry/delta-remove.mjs
/**
* Remove a delta from a point. This is essentially the steps of applyPointDelta in reverse
*/
function removePointDelta(point, translate, scale, originPoint, boxScale) {
point -= translate;
point = scalePoint(point, 1 / scale, originPoint);
if (boxScale !== undefined) {
point = scalePoint(point, 1 / boxScale, originPoint);
}
return point;
}
/**
* Remove a delta from an axis. This is essentially the steps of applyAxisDelta in reverse
*/
function removeAxisDelta(axis, translate = 0, scale = 1, origin = 0.5, boxScale, originAxis = axis, sourceAxis = axis) {
if (percent.test(translate)) {
translate = parseFloat(translate);
const relativeProgress = mix(sourceAxis.min, sourceAxis.max, translate / 100);
translate = relativeProgress - sourceAxis.min;
}
if (typeof translate !== "number")
return;
let originPoint = mix(originAxis.min, originAxis.max, origin);
if (axis === originAxis)
originPoint -= translate;
axis.min = removePointDelta(axis.min, translate, scale, originPoint, boxScale);
axis.max = removePointDelta(axis.max, translate, scale, originPoint, boxScale);
}
/**
* Remove a transforms from an axis. This is essentially the steps of applyAxisTransforms in reverse
* and acts as a bridge between motion values and removeAxisDelta
*/
function removeAxisTransforms(axis, transforms, [key, scaleKey, originKey], origin, sourceAxis) {
removeAxisDelta(axis, transforms[key], transforms[scaleKey], transforms[originKey], transforms.scale, origin, sourceAxis);
}
/**
* The names of the motion values we want to apply as translation, scale and origin.
*/
const delta_remove_xKeys = ["x", "scaleX", "originX"];
const delta_remove_yKeys = ["y", "scaleY", "originY"];
/**
* Remove a transforms from an box. This is essentially the steps of applyAxisBox in reverse
* and acts as a bridge between motion values and removeAxisDelta
*/
function removeBoxTransforms(box, transforms, originBox, sourceBox) {
removeAxisTransforms(box.x, transforms, delta_remove_xKeys, originBox === null || originBox === void 0 ? void 0 : originBox.x, sourceBox === null || sourceBox === void 0 ? void 0 : sourceBox.x);
removeAxisTransforms(box.y, transforms, delta_remove_yKeys, originBox === null || originBox === void 0 ? void 0 : originBox.y, sourceBox === null || sourceBox === void 0 ? void 0 : sourceBox.y);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/geometry/utils.mjs
function isAxisDeltaZero(delta) {
return delta.translate === 0 && delta.scale === 1;
}
function isDeltaZero(delta) {
return isAxisDeltaZero(delta.x) && isAxisDeltaZero(delta.y);
}
function boxEquals(a, b) {
return (a.x.min === b.x.min &&
a.x.max === b.x.max &&
a.y.min === b.y.min &&
a.y.max === b.y.max);
}
function aspectRatio(box) {
return calcLength(box.x) / calcLength(box.y);
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/shared/stack.mjs
class NodeStack {
constructor() {
this.members = [];
}
add(node) {
addUniqueItem(this.members, node);
node.scheduleRender();
}
remove(node) {
removeItem(this.members, node);
if (node === this.prevLead) {
this.prevLead = undefined;
}
if (node === this.lead) {
const prevLead = this.members[this.members.length - 1];
if (prevLead) {
this.promote(prevLead);
}
}
}
relegate(node) {
const indexOfNode = this.members.findIndex((member) => node === member);
if (indexOfNode === 0)
return false;
/**
* Find the next projection node that is present
*/
let prevLead;
for (let i = indexOfNode; i >= 0; i--) {
const member = this.members[i];
if (member.isPresent !== false) {
prevLead = member;
break;
}
}
if (prevLead) {
this.promote(prevLead);
return true;
}
else {
return false;
}
}
promote(node, preserveFollowOpacity) {
var _a;
const prevLead = this.lead;
if (node === prevLead)
return;
this.prevLead = prevLead;
this.lead = node;
node.show();
if (prevLead) {
prevLead.instance && prevLead.scheduleRender();
node.scheduleRender();
node.resumeFrom = prevLead;
if (preserveFollowOpacity) {
node.resumeFrom.preserveOpacity = true;
}
if (prevLead.snapshot) {
node.snapshot = prevLead.snapshot;
node.snapshot.latestValues =
prevLead.animationValues || prevLead.latestValues;
}
if ((_a = node.root) === null || _a === void 0 ? void 0 : _a.isUpdating) {
node.isLayoutDirty = true;
}
const { crossfade } = node.options;
if (crossfade === false) {
prevLead.hide();
}
/**
* TODO:
* - Test border radius when previous node was deleted
* - boxShadow mixing
* - Shared between element A in scrolled container and element B (scroll stays the same or changes)
* - Shared between element A in transformed container and element B (transform stays the same or changes)
* - Shared between element A in scrolled page and element B (scroll stays the same or changes)
* ---
* - Crossfade opacity of root nodes
* - layoutId changes after animation
* - layoutId changes mid animation
*/
}
}
exitAnimationComplete() {
this.members.forEach((node) => {
var _a, _b, _c, _d, _e;
(_b = (_a = node.options).onExitComplete) === null || _b === void 0 ? void 0 : _b.call(_a);
(_e = (_c = node.resumingFrom) === null || _c === void 0 ? void 0 : (_d = _c.options).onExitComplete) === null || _e === void 0 ? void 0 : _e.call(_d);
});
}
scheduleRender() {
this.members.forEach((node) => {
node.instance && node.scheduleRender(false);
});
}
/**
* Clear any leads that have been removed this render to prevent them from being
* used in future animations and to prevent memory leaks
*/
removeLeadSnapshot() {
if (this.lead && this.lead.snapshot) {
this.lead.snapshot = undefined;
}
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/styles/transform.mjs
function buildProjectionTransform(delta, treeScale, latestTransform) {
let transform = "";
/**
* The translations we use to calculate are always relative to the viewport coordinate space.
* But when we apply scales, we also scale the coordinate space of an element and its children.
* For instance if we have a treeScale (the culmination of all parent scales) of 0.5 and we need
* to move an element 100 pixels, we actually need to move it 200 in within that scaled space.
*/
const xTranslate = delta.x.translate / treeScale.x;
const yTranslate = delta.y.translate / treeScale.y;
if (xTranslate || yTranslate) {
transform = `translate3d(${xTranslate}px, ${yTranslate}px, 0) `;
}
/**
* Apply scale correction for the tree transform.
* This will apply scale to the screen-orientated axes.
*/
if (treeScale.x !== 1 || treeScale.y !== 1) {
transform += `scale(${1 / treeScale.x}, ${1 / treeScale.y}) `;
}
if (latestTransform) {
const { rotate, rotateX, rotateY } = latestTransform;
if (rotate)
transform += `rotate(${rotate}deg) `;
if (rotateX)
transform += `rotateX(${rotateX}deg) `;
if (rotateY)
transform += `rotateY(${rotateY}deg) `;
}
/**
* Apply scale to match the size of the element to the size we want it.
* This will apply scale to the element-orientated axes.
*/
const elementScaleX = delta.x.scale * treeScale.x;
const elementScaleY = delta.y.scale * treeScale.y;
if (elementScaleX !== 1 || elementScaleY !== 1) {
transform += `scale(${elementScaleX}, ${elementScaleY})`;
}
return transform || "none";
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/utils/compare-by-depth.mjs
const compareByDepth = (a, b) => a.depth - b.depth;
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/utils/flat-tree.mjs
class FlatTree {
constructor() {
this.children = [];
this.isDirty = false;
}
add(child) {
addUniqueItem(this.children, child);
this.isDirty = true;
}
remove(child) {
removeItem(this.children, child);
this.isDirty = true;
}
forEach(callback) {
this.isDirty && this.children.sort(compareByDepth);
this.isDirty = false;
this.children.forEach(callback);
}
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/node/create-projection-node.mjs
const transformAxes = ["", "X", "Y", "Z"];
/**
* We use 1000 as the animation target as 0-1000 maps better to pixels than 0-1
* which has a noticeable difference in spring animations
*/
const animationTarget = 1000;
let create_projection_node_id = 0;
function createProjectionNode({ attachResizeListener, defaultParent, measureScroll, checkIsScrollRoot, resetTransform, }) {
return class ProjectionNode {
constructor(elementId, latestValues = {}, parent = defaultParent === null || defaultParent === void 0 ? void 0 : defaultParent()) {
/**
* A unique ID generated for every projection node.
*/
this.id = create_projection_node_id++;
/**
* An id that represents a unique session instigated by startUpdate.
*/
this.animationId = 0;
/**
* A Set containing all this component's children. This is used to iterate
* through the children.
*
* TODO: This could be faster to iterate as a flat array stored on the root node.
*/
this.children = new Set();
/**
* Options for the node. We use this to configure what kind of layout animations
* we should perform (if any).
*/
this.options = {};
/**
* We use this to detect when its safe to shut down part of a projection tree.
* We have to keep projecting children for scale correction and relative projection
* until all their parents stop performing layout animations.
*/
this.isTreeAnimating = false;
this.isAnimationBlocked = false;
/**
* Flag to true if we think this layout has been changed. We can't always know this,
* currently we set it to true every time a component renders, or if it has a layoutDependency
* if that has changed between renders. Additionally, components can be grouped by LayoutGroup
* and if one node is dirtied, they all are.
*/
this.isLayoutDirty = false;
this.isTransformDirty = false;
/**
* Flag to true if we think the projection calculations for this or any
* child might need recalculating as a result of an updated transform or layout animation.
*/
this.isProjectionDirty = false;
/**
* Block layout updates for instant layout transitions throughout the tree.
*/
this.updateManuallyBlocked = false;
this.updateBlockedByResize = false;
/**
* Set to true between the start of the first `willUpdate` call and the end of the `didUpdate`
* call.
*/
this.isUpdating = false;
/**
* If this is an SVG element we currently disable projection transforms
*/
this.isSVG = false;
/**
* Flag to true (during promotion) if a node doing an instant layout transition needs to reset
* its projection styles.
*/
this.needsReset = false;
/**
* Flags whether this node should have its transform reset prior to measuring.
*/
this.shouldResetTransform = false;
/**
* An object representing the calculated contextual/accumulated/tree scale.
* This will be used to scale calculcated projection transforms, as these are
* calculated in screen-space but need to be scaled for elements to layoutly
* make it to their calculated destinations.
*
* TODO: Lazy-init
*/
this.treeScale = { x: 1, y: 1 };
/**
*
*/
this.eventHandlers = new Map();
// Note: Currently only running on root node
this.potentialNodes = new Map();
this.checkUpdateFailed = () => {
if (this.isUpdating) {
this.isUpdating = false;
this.clearAllSnapshots();
}
};
/**
* This is a multi-step process as shared nodes might be of different depths. Nodes
* are sorted by depth order, so we need to resolve the entire tree before moving to
* the next step.
*/
this.updateProjection = () => {
this.nodes.forEach(propagateDirtyNodes);
this.nodes.forEach(resolveTargetDelta);
this.nodes.forEach(calcProjection);
};
this.hasProjected = false;
this.isVisible = true;
this.animationProgress = 0;
/**
* Shared layout
*/
// TODO Only running on root node
this.sharedNodes = new Map();
this.elementId = elementId;
this.latestValues = latestValues;
this.root = parent ? parent.root || parent : this;
this.path = parent ? [...parent.path, parent] : [];
this.parent = parent;
this.depth = parent ? parent.depth + 1 : 0;
elementId && this.root.registerPotentialNode(elementId, this);
for (let i = 0; i < this.path.length; i++) {
this.path[i].shouldResetTransform = true;
}
if (this.root === this)
this.nodes = new FlatTree();
}
addEventListener(name, handler) {
if (!this.eventHandlers.has(name)) {
this.eventHandlers.set(name, new SubscriptionManager());
}
return this.eventHandlers.get(name).add(handler);
}
notifyListeners(name, ...args) {
const subscriptionManager = this.eventHandlers.get(name);
subscriptionManager === null || subscriptionManager === void 0 ? void 0 : subscriptionManager.notify(...args);
}
hasListeners(name) {
return this.eventHandlers.has(name);
}
registerPotentialNode(elementId, node) {
this.potentialNodes.set(elementId, node);
}
/**
* Lifecycles
*/
mount(instance, isLayoutDirty = false) {
var _a;
if (this.instance)
return;
this.isSVG =
instance instanceof SVGElement && instance.tagName !== "svg";
this.instance = instance;
const { layoutId, layout, visualElement } = this.options;
if (visualElement && !visualElement.current) {
visualElement.mount(instance);
}
this.root.nodes.add(this);
(_a = this.parent) === null || _a === void 0 ? void 0 : _a.children.add(this);
this.elementId && this.root.potentialNodes.delete(this.elementId);
if (isLayoutDirty && (layout || layoutId)) {
this.isLayoutDirty = true;
}
if (attachResizeListener) {
let cancelDelay;
const resizeUnblockUpdate = () => (this.root.updateBlockedByResize = false);
attachResizeListener(instance, () => {
this.root.updateBlockedByResize = true;
cancelDelay && cancelDelay();
cancelDelay = delay(resizeUnblockUpdate, 250);
if (globalProjectionState.hasAnimatedSinceResize) {
globalProjectionState.hasAnimatedSinceResize = false;
this.nodes.forEach(finishAnimation);
}
});
}
if (layoutId) {
this.root.registerSharedNode(layoutId, this);
}
// Only register the handler if it requires layout animation
if (this.options.animate !== false &&
visualElement &&
(layoutId || layout)) {
this.addEventListener("didUpdate", ({ delta, hasLayoutChanged, hasRelativeTargetChanged, layout: newLayout, }) => {
var _a, _b, _c, _d, _e;
if (this.isTreeAnimationBlocked()) {
this.target = undefined;
this.relativeTarget = undefined;
return;
}
// TODO: Check here if an animation exists
const layoutTransition = (_b = (_a = this.options.transition) !== null && _a !== void 0 ? _a : visualElement.getDefaultTransition()) !== null && _b !== void 0 ? _b : defaultLayoutTransition;
const { onLayoutAnimationStart, onLayoutAnimationComplete, } = visualElement.getProps();
/**
* The target layout of the element might stay the same,
* but its position relative to its parent has changed.
*/
const targetChanged = !this.targetLayout ||
!boxEquals(this.targetLayout, newLayout) ||
hasRelativeTargetChanged;
/**
* If the layout hasn't seemed to have changed, it might be that the
* element is visually in the same place in the document but its position
* relative to its parent has indeed changed. So here we check for that.
*/
const hasOnlyRelativeTargetChanged = !hasLayoutChanged && hasRelativeTargetChanged;
if (((_c = this.resumeFrom) === null || _c === void 0 ? void 0 : _c.instance) ||
hasOnlyRelativeTargetChanged ||
(hasLayoutChanged &&
(targetChanged || !this.currentAnimation))) {
if (this.resumeFrom) {
this.resumingFrom = this.resumeFrom;
this.resumingFrom.resumingFrom = undefined;
}
this.setAnimationOrigin(delta, hasOnlyRelativeTargetChanged);
const animationOptions = {
...getValueTransition(layoutTransition, "layout"),
onPlay: onLayoutAnimationStart,
onComplete: onLayoutAnimationComplete,
};
if (visualElement.shouldReduceMotion) {
animationOptions.delay = 0;
animationOptions.type = false;
}
this.startAnimation(animationOptions);
}
else {
/**
* If the layout hasn't changed and we have an animation that hasn't started yet,
* finish it immediately. Otherwise it will be animating from a location
* that was probably never commited to screen and look like a jumpy box.
*/
if (!hasLayoutChanged &&
this.animationProgress === 0) {
finishAnimation(this);
}
this.isLead() && ((_e = (_d = this.options).onExitComplete) === null || _e === void 0 ? void 0 : _e.call(_d));
}
this.targetLayout = newLayout;
});
}
}
unmount() {
var _a, _b;
this.options.layoutId && this.willUpdate();
this.root.nodes.remove(this);
(_a = this.getStack()) === null || _a === void 0 ? void 0 : _a.remove(this);
(_b = this.parent) === null || _b === void 0 ? void 0 : _b.children.delete(this);
this.instance = undefined;
cancelSync.preRender(this.updateProjection);
}
// only on the root
blockUpdate() {
this.updateManuallyBlocked = true;
}
unblockUpdate() {
this.updateManuallyBlocked = false;
}
isUpdateBlocked() {
return this.updateManuallyBlocked || this.updateBlockedByResize;
}
isTreeAnimationBlocked() {
var _a;
return (this.isAnimationBlocked ||
((_a = this.parent) === null || _a === void 0 ? void 0 : _a.isTreeAnimationBlocked()) ||
false);
}
// Note: currently only running on root node
startUpdate() {
var _a;
if (this.isUpdateBlocked())
return;
this.isUpdating = true;
(_a = this.nodes) === null || _a === void 0 ? void 0 : _a.forEach(resetRotation);
this.animationId++;
}
willUpdate(shouldNotifyListeners = true) {
var _a, _b, _c;
if (this.root.isUpdateBlocked()) {
(_b = (_a = this.options).onExitComplete) === null || _b === void 0 ? void 0 : _b.call(_a);
return;
}
!this.root.isUpdating && this.root.startUpdate();
if (this.isLayoutDirty)
return;
this.isLayoutDirty = true;
for (let i = 0; i < this.path.length; i++) {
const node = this.path[i];
node.shouldResetTransform = true;
node.updateScroll("snapshot");
}
const { layoutId, layout } = this.options;
if (layoutId === undefined && !layout)
return;
const transformTemplate = (_c = this.options.visualElement) === null || _c === void 0 ? void 0 : _c.getProps().transformTemplate;
this.prevTransformTemplateValue = transformTemplate === null || transformTemplate === void 0 ? void 0 : transformTemplate(this.latestValues, "");
this.updateSnapshot();
shouldNotifyListeners && this.notifyListeners("willUpdate");
}
// Note: Currently only running on root node
didUpdate() {
const updateWasBlocked = this.isUpdateBlocked();
// When doing an instant transition, we skip the layout update,
// but should still clean up the measurements so that the next
// snapshot could be taken correctly.
if (updateWasBlocked) {
this.unblockUpdate();
this.clearAllSnapshots();
this.nodes.forEach(clearMeasurements);
return;
}
if (!this.isUpdating)
return;
this.isUpdating = false;
/**
* Search for and mount newly-added projection elements.
*
* TODO: Every time a new component is rendered we could search up the tree for
* the closest mounted node and query from there rather than document.
*/
if (this.potentialNodes.size) {
this.potentialNodes.forEach(mountNodeEarly);
this.potentialNodes.clear();
}
/**
* Write
*/
this.nodes.forEach(resetTransformStyle);
/**
* Read ==================
*/
// Update layout measurements of updated children
this.nodes.forEach(updateLayout);
/**
* Write
*/
// Notify listeners that the layout is updated
this.nodes.forEach(notifyLayoutUpdate);
this.clearAllSnapshots();
// Flush any scheduled updates
flushSync.update();
flushSync.preRender();
flushSync.render();
}
clearAllSnapshots() {
this.nodes.forEach(clearSnapshot);
this.sharedNodes.forEach(removeLeadSnapshots);
}
scheduleUpdateProjection() {
sync.preRender(this.updateProjection, false, true);
}
scheduleCheckAfterUnmount() {
/**
* If the unmounting node is in a layoutGroup and did trigger a willUpdate,
* we manually call didUpdate to give a chance to the siblings to animate.
* Otherwise, cleanup all snapshots to prevents future nodes from reusing them.
*/
sync.postRender(() => {
if (this.isLayoutDirty) {
this.root.didUpdate();
}
else {
this.root.checkUpdateFailed();
}
});
}
/**
* Update measurements
*/
updateSnapshot() {
if (this.snapshot || !this.instance)
return;
this.snapshot = this.measure();
}
updateLayout() {
var _a;
if (!this.instance)
return;
// TODO: Incorporate into a forwarded scroll offset
this.updateScroll();
if (!(this.options.alwaysMeasureLayout && this.isLead()) &&
!this.isLayoutDirty) {
return;
}
/**
* When a node is mounted, it simply resumes from the prevLead's
* snapshot instead of taking a new one, but the ancestors scroll
* might have updated while the prevLead is unmounted. We need to
* update the scroll again to make sure the layout we measure is
* up to date.
*/
if (this.resumeFrom && !this.resumeFrom.instance) {
for (let i = 0; i < this.path.length; i++) {
const node = this.path[i];
node.updateScroll();
}
}
const prevLayout = this.layout;
this.layout = this.measure(false);
this.layoutCorrected = createBox();
this.isLayoutDirty = false;
this.projectionDelta = undefined;
this.notifyListeners("measure", this.layout.layoutBox);
(_a = this.options.visualElement) === null || _a === void 0 ? void 0 : _a.notify("LayoutMeasure", this.layout.layoutBox, prevLayout === null || prevLayout === void 0 ? void 0 : prevLayout.layoutBox);
}
updateScroll(phase = "measure") {
let needsMeasurement = Boolean(this.options.layoutScroll && this.instance);
if (this.scroll &&
this.scroll.animationId === this.root.animationId &&
this.scroll.phase === phase) {
needsMeasurement = false;
}
if (needsMeasurement) {
this.scroll = {
animationId: this.root.animationId,
phase,
isRoot: checkIsScrollRoot(this.instance),
offset: measureScroll(this.instance),
};
}
}
resetTransform() {
var _a;
if (!resetTransform)
return;
const isResetRequested = this.isLayoutDirty || this.shouldResetTransform;
const hasProjection = this.projectionDelta && !isDeltaZero(this.projectionDelta);
const transformTemplate = (_a = this.options.visualElement) === null || _a === void 0 ? void 0 : _a.getProps().transformTemplate;
const transformTemplateValue = transformTemplate === null || transformTemplate === void 0 ? void 0 : transformTemplate(this.latestValues, "");
const transformTemplateHasChanged = transformTemplateValue !== this.prevTransformTemplateValue;
if (isResetRequested &&
(hasProjection ||
hasTransform(this.latestValues) ||
transformTemplateHasChanged)) {
resetTransform(this.instance, transformTemplateValue);
this.shouldResetTransform = false;
this.scheduleRender();
}
}
measure(removeTransform = true) {
const pageBox = this.measurePageBox();
let layoutBox = this.removeElementScroll(pageBox);
/**
* Measurements taken during the pre-render stage
* still have transforms applied so we remove them
* via calculation.
*/
if (removeTransform) {
layoutBox = this.removeTransform(layoutBox);
}
roundBox(layoutBox);
return {
animationId: this.root.animationId,
measuredBox: pageBox,
layoutBox,
latestValues: {},
source: this.id,
};
}
measurePageBox() {
const { visualElement } = this.options;
if (!visualElement)
return createBox();
const box = visualElement.measureViewportBox();
// Remove viewport scroll to give page-relative coordinates
const { scroll } = this.root;
if (scroll) {
translateAxis(box.x, scroll.offset.x);
translateAxis(box.y, scroll.offset.y);
}
return box;
}
removeElementScroll(box) {
const boxWithoutScroll = createBox();
copyBoxInto(boxWithoutScroll, box);
/**
* Performance TODO: Keep a cumulative scroll offset down the tree
* rather than loop back up the path.
*/
for (let i = 0; i < this.path.length; i++) {
const node = this.path[i];
const { scroll, options } = node;
if (node !== this.root && scroll && options.layoutScroll) {
/**
* If this is a new scroll root, we want to remove all previous scrolls
* from the viewport box.
*/
if (scroll.isRoot) {
copyBoxInto(boxWithoutScroll, box);
const { scroll: rootScroll } = this.root;
/**
* Undo the application of page scroll that was originally added
* to the measured bounding box.
*/
if (rootScroll) {
translateAxis(boxWithoutScroll.x, -rootScroll.offset.x);
translateAxis(boxWithoutScroll.y, -rootScroll.offset.y);
}
}
translateAxis(boxWithoutScroll.x, scroll.offset.x);
translateAxis(boxWithoutScroll.y, scroll.offset.y);
}
}
return boxWithoutScroll;
}
applyTransform(box, transformOnly = false) {
const withTransforms = createBox();
copyBoxInto(withTransforms, box);
for (let i = 0; i < this.path.length; i++) {
const node = this.path[i];
if (!transformOnly &&
node.options.layoutScroll &&
node.scroll &&
node !== node.root) {
transformBox(withTransforms, {
x: -node.scroll.offset.x,
y: -node.scroll.offset.y,
});
}
if (!hasTransform(node.latestValues))
continue;
transformBox(withTransforms, node.latestValues);
}
if (hasTransform(this.latestValues)) {
transformBox(withTransforms, this.latestValues);
}
return withTransforms;
}
removeTransform(box) {
var _a;
const boxWithoutTransform = createBox();
copyBoxInto(boxWithoutTransform, box);
for (let i = 0; i < this.path.length; i++) {
const node = this.path[i];
if (!node.instance)
continue;
if (!hasTransform(node.latestValues))
continue;
hasScale(node.latestValues) && node.updateSnapshot();
const sourceBox = createBox();
const nodeBox = node.measurePageBox();
copyBoxInto(sourceBox, nodeBox);
removeBoxTransforms(boxWithoutTransform, node.latestValues, (_a = node.snapshot) === null || _a === void 0 ? void 0 : _a.layoutBox, sourceBox);
}
if (hasTransform(this.latestValues)) {
removeBoxTransforms(boxWithoutTransform, this.latestValues);
}
return boxWithoutTransform;
}
/**
*
*/
setTargetDelta(delta) {
this.targetDelta = delta;
this.isProjectionDirty = true;
this.root.scheduleUpdateProjection();
}
setOptions(options) {
this.options = {
...this.options,
...options,
crossfade: options.crossfade !== undefined ? options.crossfade : true,
};
}
clearMeasurements() {
this.scroll = undefined;
this.layout = undefined;
this.snapshot = undefined;
this.prevTransformTemplateValue = undefined;
this.targetDelta = undefined;
this.target = undefined;
this.isLayoutDirty = false;
}
/**
* Frame calculations
*/
resolveTargetDelta() {
var _a;
/**
* Once the dirty status of nodes has been spread through the tree, we also
* need to check if we have a shared node of a different depth that has itself
* been dirtied.
*/
const lead = this.getLead();
this.isProjectionDirty || (this.isProjectionDirty = lead.isProjectionDirty);
this.isTransformDirty || (this.isTransformDirty = lead.isTransformDirty);
/**
* We don't use transform for this step of processing so we don't
* need to check whether any nodes have changed transform.
*/
if (!this.isProjectionDirty && !this.attemptToResolveRelativeTarget)
return;
const { layout, layoutId } = this.options;
/**
* If we have no layout, we can't perform projection, so early return
*/
if (!this.layout || !(layout || layoutId))
return;
/**
* If we don't have a targetDelta but do have a layout, we can attempt to resolve
* a relativeParent. This will allow a component to perform scale correction
* even if no animation has started.
*/
// TODO If this is unsuccessful this currently happens every frame
if (!this.targetDelta && !this.relativeTarget) {
// TODO: This is a semi-repetition of further down this function, make DRY
const relativeParent = this.getClosestProjectingParent();
if (relativeParent && relativeParent.layout) {
this.relativeParent = relativeParent;
this.relativeTarget = createBox();
this.relativeTargetOrigin = createBox();
calcRelativePosition(this.relativeTargetOrigin, this.layout.layoutBox, relativeParent.layout.layoutBox);
copyBoxInto(this.relativeTarget, this.relativeTargetOrigin);
}
else {
this.relativeParent = this.relativeTarget = undefined;
}
}
/**
* If we have no relative target or no target delta our target isn't valid
* for this frame.
*/
if (!this.relativeTarget && !this.targetDelta)
return;
/**
* Lazy-init target data structure
*/
if (!this.target) {
this.target = createBox();
this.targetWithTransforms = createBox();
}
/**
* If we've got a relative box for this component, resolve it into a target relative to the parent.
*/
if (this.relativeTarget &&
this.relativeTargetOrigin &&
((_a = this.relativeParent) === null || _a === void 0 ? void 0 : _a.target)) {
calcRelativeBox(this.target, this.relativeTarget, this.relativeParent.target);
/**
* If we've only got a targetDelta, resolve it into a target
*/
}
else if (this.targetDelta) {
if (Boolean(this.resumingFrom)) {
// TODO: This is creating a new object every frame
this.target = this.applyTransform(this.layout.layoutBox);
}
else {
copyBoxInto(this.target, this.layout.layoutBox);
}
applyBoxDelta(this.target, this.targetDelta);
}
else {
/**
* If no target, use own layout as target
*/
copyBoxInto(this.target, this.layout.layoutBox);
}
/**
* If we've been told to attempt to resolve a relative target, do so.
*/
if (this.attemptToResolveRelativeTarget) {
this.attemptToResolveRelativeTarget = false;
const relativeParent = this.getClosestProjectingParent();
if (relativeParent &&
Boolean(relativeParent.resumingFrom) ===
Boolean(this.resumingFrom) &&
!relativeParent.options.layoutScroll &&
relativeParent.target) {
this.relativeParent = relativeParent;
this.relativeTarget = createBox();
this.relativeTargetOrigin = createBox();
calcRelativePosition(this.relativeTargetOrigin, this.target, relativeParent.target);
copyBoxInto(this.relativeTarget, this.relativeTargetOrigin);
}
else {
this.relativeParent = this.relativeTarget = undefined;
}
}
}
getClosestProjectingParent() {
if (!this.parent ||
hasScale(this.parent.latestValues) ||
has2DTranslate(this.parent.latestValues))
return undefined;
if ((this.parent.relativeTarget || this.parent.targetDelta) &&
this.parent.layout) {
return this.parent;
}
else {
return this.parent.getClosestProjectingParent();
}
}
calcProjection() {
var _a;
const { isProjectionDirty, isTransformDirty } = this;
this.isProjectionDirty = this.isTransformDirty = false;
const lead = this.getLead();
const isShared = Boolean(this.resumingFrom) || this !== lead;
let canSkip = true;
if (isProjectionDirty)
canSkip = false;
if (isShared && isTransformDirty)
canSkip = false;
if (canSkip)
return;
const { layout, layoutId } = this.options;
/**
* If this section of the tree isn't animating we can
* delete our target sources for the following frame.
*/
this.isTreeAnimating = Boolean(((_a = this.parent) === null || _a === void 0 ? void 0 : _a.isTreeAnimating) ||
this.currentAnimation ||
this.pendingAnimation);
if (!this.isTreeAnimating) {
this.targetDelta = this.relativeTarget = undefined;
}
if (!this.layout || !(layout || layoutId))
return;
/**
* Reset the corrected box with the latest values from box, as we're then going
* to perform mutative operations on it.
*/
copyBoxInto(this.layoutCorrected, this.layout.layoutBox);
/**
* Apply all the parent deltas to this box to produce the corrected box. This
* is the layout box, as it will appear on screen as a result of the transforms of its parents.
*/
applyTreeDeltas(this.layoutCorrected, this.treeScale, this.path, isShared);
const { target } = lead;
if (!target)
return;
if (!this.projectionDelta) {
this.projectionDelta = createDelta();
this.projectionDeltaWithTransform = createDelta();
}
const prevTreeScaleX = this.treeScale.x;
const prevTreeScaleY = this.treeScale.y;
const prevProjectionTransform = this.projectionTransform;
/**
* Update the delta between the corrected box and the target box before user-set transforms were applied.
* This will allow us to calculate the corrected borderRadius and boxShadow to compensate
* for our layout reprojection, but still allow them to be scaled correctly by the user.
* It might be that to simplify this we may want to accept that user-set scale is also corrected
* and we wouldn't have to keep and calc both deltas, OR we could support a user setting
* to allow people to choose whether these styles are corrected based on just the
* layout reprojection or the final bounding box.
*/
calcBoxDelta(this.projectionDelta, this.layoutCorrected, target, this.latestValues);
this.projectionTransform = buildProjectionTransform(this.projectionDelta, this.treeScale);
if (this.projectionTransform !== prevProjectionTransform ||
this.treeScale.x !== prevTreeScaleX ||
this.treeScale.y !== prevTreeScaleY) {
this.hasProjected = true;
this.scheduleRender();
this.notifyListeners("projectionUpdate", target);
}
}
hide() {
this.isVisible = false;
// TODO: Schedule render
}
show() {
this.isVisible = true;
// TODO: Schedule render
}
scheduleRender(notifyAll = true) {
var _a, _b, _c;
(_b = (_a = this.options).scheduleRender) === null || _b === void 0 ? void 0 : _b.call(_a);
notifyAll && ((_c = this.getStack()) === null || _c === void 0 ? void 0 : _c.scheduleRender());
if (this.resumingFrom && !this.resumingFrom.instance) {
this.resumingFrom = undefined;
}
}
setAnimationOrigin(delta, hasOnlyRelativeTargetChanged = false) {
var _a, _b;
const snapshot = this.snapshot;
const snapshotLatestValues = (snapshot === null || snapshot === void 0 ? void 0 : snapshot.latestValues) || {};
const mixedValues = { ...this.latestValues };
const targetDelta = createDelta();
this.relativeTarget = this.relativeTargetOrigin = undefined;
this.attemptToResolveRelativeTarget = !hasOnlyRelativeTargetChanged;
const relativeLayout = createBox();
const isSharedLayoutAnimation = (snapshot === null || snapshot === void 0 ? void 0 : snapshot.source) !== ((_a = this.layout) === null || _a === void 0 ? void 0 : _a.source);
const isOnlyMember = (((_b = this.getStack()) === null || _b === void 0 ? void 0 : _b.members.length) || 0) <= 1;
const shouldCrossfadeOpacity = Boolean(isSharedLayoutAnimation &&
!isOnlyMember &&
this.options.crossfade === true &&
!this.path.some(hasOpacityCrossfade));
this.animationProgress = 0;
this.mixTargetDelta = (latest) => {
var _a;
const progress = latest / 1000;
mixAxisDelta(targetDelta.x, delta.x, progress);
mixAxisDelta(targetDelta.y, delta.y, progress);
this.setTargetDelta(targetDelta);
if (this.relativeTarget &&
this.relativeTargetOrigin &&
this.layout &&
((_a = this.relativeParent) === null || _a === void 0 ? void 0 : _a.layout)) {
calcRelativePosition(relativeLayout, this.layout.layoutBox, this.relativeParent.layout.layoutBox);
mixBox(this.relativeTarget, this.relativeTargetOrigin, relativeLayout, progress);
}
if (isSharedLayoutAnimation) {
this.animationValues = mixedValues;
mixValues(mixedValues, snapshotLatestValues, this.latestValues, progress, shouldCrossfadeOpacity, isOnlyMember);
}
this.root.scheduleUpdateProjection();
this.scheduleRender();
this.animationProgress = progress;
};
this.mixTargetDelta(0);
}
startAnimation(options) {
var _a, _b;
this.notifyListeners("animationStart");
(_a = this.currentAnimation) === null || _a === void 0 ? void 0 : _a.stop();
if (this.resumingFrom) {
(_b = this.resumingFrom.currentAnimation) === null || _b === void 0 ? void 0 : _b.stop();
}
if (this.pendingAnimation) {
cancelSync.update(this.pendingAnimation);
this.pendingAnimation = undefined;
}
/**
* Start the animation in the next frame to have a frame with progress 0,
* where the target is the same as when the animation started, so we can
* calculate the relative positions correctly for instant transitions.
*/
this.pendingAnimation = sync.update(() => {
globalProjectionState.hasAnimatedSinceResize = true;
this.currentAnimation = animate_animate(0, animationTarget, {
...options,
onUpdate: (latest) => {
var _a;
this.mixTargetDelta(latest);
(_a = options.onUpdate) === null || _a === void 0 ? void 0 : _a.call(options, latest);
},
onComplete: () => {
var _a;
(_a = options.onComplete) === null || _a === void 0 ? void 0 : _a.call(options);
this.completeAnimation();
},
});
if (this.resumingFrom) {
this.resumingFrom.currentAnimation = this.currentAnimation;
}
this.pendingAnimation = undefined;
});
}
completeAnimation() {
var _a;
if (this.resumingFrom) {
this.resumingFrom.currentAnimation = undefined;
this.resumingFrom.preserveOpacity = undefined;
}
(_a = this.getStack()) === null || _a === void 0 ? void 0 : _a.exitAnimationComplete();
this.resumingFrom =
this.currentAnimation =
this.animationValues =
undefined;
this.notifyListeners("animationComplete");
}
finishAnimation() {
var _a;
if (this.currentAnimation) {
(_a = this.mixTargetDelta) === null || _a === void 0 ? void 0 : _a.call(this, animationTarget);
this.currentAnimation.stop();
}
this.completeAnimation();
}
applyTransformsToTarget() {
const lead = this.getLead();
let { targetWithTransforms, target, layout, latestValues } = lead;
if (!targetWithTransforms || !target || !layout)
return;
/**
* If we're only animating position, and this element isn't the lead element,
* then instead of projecting into the lead box we instead want to calculate
* a new target that aligns the two boxes but maintains the layout shape.
*/
if (this !== lead &&
this.layout &&
layout &&
shouldAnimatePositionOnly(this.options.animationType, this.layout.layoutBox, layout.layoutBox)) {
target = this.target || createBox();
const xLength = calcLength(this.layout.layoutBox.x);
target.x.min = lead.target.x.min;
target.x.max = target.x.min + xLength;
const yLength = calcLength(this.layout.layoutBox.y);
target.y.min = lead.target.y.min;
target.y.max = target.y.min + yLength;
}
copyBoxInto(targetWithTransforms, target);
/**
* Apply the latest user-set transforms to the targetBox to produce the targetBoxFinal.
* This is the final box that we will then project into by calculating a transform delta and
* applying it to the corrected box.
*/
transformBox(targetWithTransforms, latestValues);
/**
* Update the delta between the corrected box and the final target box, after
* user-set transforms are applied to it. This will be used by the renderer to
* create a transform style that will reproject the element from its layout layout
* into the desired bounding box.
*/
calcBoxDelta(this.projectionDeltaWithTransform, this.layoutCorrected, targetWithTransforms, latestValues);
}
registerSharedNode(layoutId, node) {
var _a, _b, _c;
if (!this.sharedNodes.has(layoutId)) {
this.sharedNodes.set(layoutId, new NodeStack());
}
const stack = this.sharedNodes.get(layoutId);
stack.add(node);
node.promote({
transition: (_a = node.options.initialPromotionConfig) === null || _a === void 0 ? void 0 : _a.transition,
preserveFollowOpacity: (_c = (_b = node.options.initialPromotionConfig) === null || _b === void 0 ? void 0 : _b.shouldPreserveFollowOpacity) === null || _c === void 0 ? void 0 : _c.call(_b, node),
});
}
isLead() {
const stack = this.getStack();
return stack ? stack.lead === this : true;
}
getLead() {
var _a;
const { layoutId } = this.options;
return layoutId ? ((_a = this.getStack()) === null || _a === void 0 ? void 0 : _a.lead) || this : this;
}
getPrevLead() {
var _a;
const { layoutId } = this.options;
return layoutId ? (_a = this.getStack()) === null || _a === void 0 ? void 0 : _a.prevLead : undefined;
}
getStack() {
const { layoutId } = this.options;
if (layoutId)
return this.root.sharedNodes.get(layoutId);
}
promote({ needsReset, transition, preserveFollowOpacity, } = {}) {
const stack = this.getStack();
if (stack)
stack.promote(this, preserveFollowOpacity);
if (needsReset) {
this.projectionDelta = undefined;
this.needsReset = true;
}
if (transition)
this.setOptions({ transition });
}
relegate() {
const stack = this.getStack();
if (stack) {
return stack.relegate(this);
}
else {
return false;
}
}
resetRotation() {
const { visualElement } = this.options;
if (!visualElement)
return;
// If there's no detected rotation values, we can early return without a forced render.
let hasRotate = false;
/**
* An unrolled check for rotation values. Most elements don't have any rotation and
* skipping the nested loop and new object creation is 50% faster.
*/
const { latestValues } = visualElement;
if (latestValues.rotate ||
latestValues.rotateX ||
latestValues.rotateY ||
latestValues.rotateZ) {
hasRotate = true;
}
// If there's no rotation values, we don't need to do any more.
if (!hasRotate)
return;
const resetValues = {};
// Check the rotate value of all axes and reset to 0
for (let i = 0; i < transformAxes.length; i++) {
const key = "rotate" + transformAxes[i];
// Record the rotation and then temporarily set it to 0
if (latestValues[key]) {
resetValues[key] = latestValues[key];
visualElement.setStaticValue(key, 0);
}
}
// Force a render of this element to apply the transform with all rotations
// set to 0.
visualElement === null || visualElement === void 0 ? void 0 : visualElement.render();
// Put back all the values we reset
for (const key in resetValues) {
visualElement.setStaticValue(key, resetValues[key]);
}
// Schedule a render for the next frame. This ensures we won't visually
// see the element with the reset rotate value applied.
visualElement.scheduleRender();
}
getProjectionStyles(styleProp = {}) {
var _a, _b, _c;
// TODO: Return lifecycle-persistent object
const styles = {};
if (!this.instance || this.isSVG)
return styles;
if (!this.isVisible) {
return { visibility: "hidden" };
}
else {
styles.visibility = "";
}
const transformTemplate = (_a = this.options.visualElement) === null || _a === void 0 ? void 0 : _a.getProps().transformTemplate;
if (this.needsReset) {
this.needsReset = false;
styles.opacity = "";
styles.pointerEvents =
resolveMotionValue(styleProp.pointerEvents) || "";
styles.transform = transformTemplate
? transformTemplate(this.latestValues, "")
: "none";
return styles;
}
const lead = this.getLead();
if (!this.projectionDelta || !this.layout || !lead.target) {
const emptyStyles = {};
if (this.options.layoutId) {
emptyStyles.opacity =
this.latestValues.opacity !== undefined
? this.latestValues.opacity
: 1;
emptyStyles.pointerEvents =
resolveMotionValue(styleProp.pointerEvents) || "";
}
if (this.hasProjected && !hasTransform(this.latestValues)) {
emptyStyles.transform = transformTemplate
? transformTemplate({}, "")
: "none";
this.hasProjected = false;
}
return emptyStyles;
}
const valuesToRender = lead.animationValues || lead.latestValues;
this.applyTransformsToTarget();
styles.transform = buildProjectionTransform(this.projectionDeltaWithTransform, this.treeScale, valuesToRender);
if (transformTemplate) {
styles.transform = transformTemplate(valuesToRender, styles.transform);
}
const { x, y } = this.projectionDelta;
styles.transformOrigin = `${x.origin * 100}% ${y.origin * 100}% 0`;
if (lead.animationValues) {
/**
* If the lead component is animating, assign this either the entering/leaving
* opacity
*/
styles.opacity =
lead === this
? (_c = (_b = valuesToRender.opacity) !== null && _b !== void 0 ? _b : this.latestValues.opacity) !== null && _c !== void 0 ? _c : 1
: this.preserveOpacity
? this.latestValues.opacity
: valuesToRender.opacityExit;
}
else {
/**
* Or we're not animating at all, set the lead component to its layout
* opacity and other components to hidden.
*/
styles.opacity =
lead === this
? valuesToRender.opacity !== undefined
? valuesToRender.opacity
: ""
: valuesToRender.opacityExit !== undefined
? valuesToRender.opacityExit
: 0;
}
/**
* Apply scale correction
*/
for (const key in scaleCorrectors) {
if (valuesToRender[key] === undefined)
continue;
const { correct, applyTo } = scaleCorrectors[key];
const corrected = correct(valuesToRender[key], lead);
if (applyTo) {
const num = applyTo.length;
for (let i = 0; i < num; i++) {
styles[applyTo[i]] = corrected;
}
}
else {
styles[key] = corrected;
}
}
/**
* Disable pointer events on follow components. This is to ensure
* that if a follow component covers a lead component it doesn't block
* pointer events on the lead.
*/
if (this.options.layoutId) {
styles.pointerEvents =
lead === this
? resolveMotionValue(styleProp.pointerEvents) || ""
: "none";
}
return styles;
}
clearSnapshot() {
this.resumeFrom = this.snapshot = undefined;
}
// Only run on root
resetTree() {
this.root.nodes.forEach((node) => { var _a; return (_a = node.currentAnimation) === null || _a === void 0 ? void 0 : _a.stop(); });
this.root.nodes.forEach(clearMeasurements);
this.root.sharedNodes.clear();
}
};
}
function updateLayout(node) {
node.updateLayout();
}
function notifyLayoutUpdate(node) {
var _a, _b, _c;
const snapshot = ((_a = node.resumeFrom) === null || _a === void 0 ? void 0 : _a.snapshot) || node.snapshot;
if (node.isLead() &&
node.layout &&
snapshot &&
node.hasListeners("didUpdate")) {
const { layoutBox: layout, measuredBox: measuredLayout } = node.layout;
const { animationType } = node.options;
const isShared = snapshot.source !== node.layout.source;
// TODO Maybe we want to also resize the layout snapshot so we don't trigger
// animations for instance if layout="size" and an element has only changed position
if (animationType === "size") {
eachAxis((axis) => {
const axisSnapshot = isShared
? snapshot.measuredBox[axis]
: snapshot.layoutBox[axis];
const length = calcLength(axisSnapshot);
axisSnapshot.min = layout[axis].min;
axisSnapshot.max = axisSnapshot.min + length;
});
}
else if (shouldAnimatePositionOnly(animationType, snapshot.layoutBox, layout)) {
eachAxis((axis) => {
const axisSnapshot = isShared
? snapshot.measuredBox[axis]
: snapshot.layoutBox[axis];
const length = calcLength(layout[axis]);
axisSnapshot.max = axisSnapshot.min + length;
});
}
const layoutDelta = createDelta();
calcBoxDelta(layoutDelta, layout, snapshot.layoutBox);
const visualDelta = createDelta();
if (isShared) {
calcBoxDelta(visualDelta, node.applyTransform(measuredLayout, true), snapshot.measuredBox);
}
else {
calcBoxDelta(visualDelta, layout, snapshot.layoutBox);
}
const hasLayoutChanged = !isDeltaZero(layoutDelta);
let hasRelativeTargetChanged = false;
if (!node.resumeFrom) {
const relativeParent = node.getClosestProjectingParent();
/**
* If the relativeParent is itself resuming from a different element then
* the relative snapshot is not relavent
*/
if (relativeParent && !relativeParent.resumeFrom) {
const { snapshot: parentSnapshot, layout: parentLayout } = relativeParent;
if (parentSnapshot && parentLayout) {
const relativeSnapshot = createBox();
calcRelativePosition(relativeSnapshot, snapshot.layoutBox, parentSnapshot.layoutBox);
const relativeLayout = createBox();
calcRelativePosition(relativeLayout, layout, parentLayout.layoutBox);
if (!boxEquals(relativeSnapshot, relativeLayout)) {
hasRelativeTargetChanged = true;
}
}
}
}
node.notifyListeners("didUpdate", {
layout,
snapshot,
delta: visualDelta,
layoutDelta,
hasLayoutChanged,
hasRelativeTargetChanged,
});
}
else if (node.isLead()) {
(_c = (_b = node.options).onExitComplete) === null || _c === void 0 ? void 0 : _c.call(_b);
}
/**
* Clearing transition
* TODO: Investigate why this transition is being passed in as {type: false } from Framer
* and why we need it at all
*/
node.options.transition = undefined;
}
function propagateDirtyNodes(node) {
/**
* Propagate isProjectionDirty. Nodes are ordered by depth, so if the parent here
* is dirty we can simply pass this forward.
*/
node.isProjectionDirty || (node.isProjectionDirty = Boolean(node.parent && node.parent.isProjectionDirty));
/**
* Propagate isTransformDirty.
*/
node.isTransformDirty || (node.isTransformDirty = Boolean(node.parent && node.parent.isTransformDirty));
}
function clearSnapshot(node) {
node.clearSnapshot();
}
function clearMeasurements(node) {
node.clearMeasurements();
}
function resetTransformStyle(node) {
const { visualElement } = node.options;
if (visualElement === null || visualElement === void 0 ? void 0 : visualElement.getProps().onBeforeLayoutMeasure) {
visualElement.notify("BeforeLayoutMeasure");
}
node.resetTransform();
}
function finishAnimation(node) {
node.finishAnimation();
node.targetDelta = node.relativeTarget = node.target = undefined;
}
function resolveTargetDelta(node) {
node.resolveTargetDelta();
}
function calcProjection(node) {
node.calcProjection();
}
function resetRotation(node) {
node.resetRotation();
}
function removeLeadSnapshots(stack) {
stack.removeLeadSnapshot();
}
function mixAxisDelta(output, delta, p) {
output.translate = mix(delta.translate, 0, p);
output.scale = mix(delta.scale, 1, p);
output.origin = delta.origin;
output.originPoint = delta.originPoint;
}
function mixAxis(output, from, to, p) {
output.min = mix(from.min, to.min, p);
output.max = mix(from.max, to.max, p);
}
function mixBox(output, from, to, p) {
mixAxis(output.x, from.x, to.x, p);
mixAxis(output.y, from.y, to.y, p);
}
function hasOpacityCrossfade(node) {
return (node.animationValues && node.animationValues.opacityExit !== undefined);
}
const defaultLayoutTransition = {
duration: 0.45,
ease: [0.4, 0, 0.1, 1],
};
function mountNodeEarly(node, elementId) {
/**
* Rather than searching the DOM from document we can search the
* path for the deepest mounted ancestor and search from there
*/
let searchNode = node.root;
for (let i = node.path.length - 1; i >= 0; i--) {
if (Boolean(node.path[i].instance)) {
searchNode = node.path[i];
break;
}
}
const searchElement = searchNode && searchNode !== node.root ? searchNode.instance : document;
const element = searchElement.querySelector(`[data-projection-id="${elementId}"]`);
if (element)
node.mount(element, true);
}
function roundAxis(axis) {
axis.min = Math.round(axis.min);
axis.max = Math.round(axis.max);
}
function roundBox(box) {
roundAxis(box.x);
roundAxis(box.y);
}
function shouldAnimatePositionOnly(animationType, snapshot, layout) {
return (animationType === "position" ||
(animationType === "preserve-aspect" &&
!isNear(aspectRatio(snapshot), aspectRatio(layout), 0.2)));
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/node/DocumentProjectionNode.mjs
const DocumentProjectionNode = createProjectionNode({
attachResizeListener: (ref, notify) => addDomEvent(ref, "resize", notify),
measureScroll: () => ({
x: document.documentElement.scrollLeft || document.body.scrollLeft,
y: document.documentElement.scrollTop || document.body.scrollTop,
}),
checkIsScrollRoot: () => true,
});
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/projection/node/HTMLProjectionNode.mjs
const rootProjectionNode = {
current: undefined,
};
const HTMLProjectionNode_HTMLProjectionNode = createProjectionNode({
measureScroll: (instance) => ({
x: instance.scrollLeft,
y: instance.scrollTop,
}),
defaultParent: () => {
if (!rootProjectionNode.current) {
const documentNode = new DocumentProjectionNode(0, {});
documentNode.mount(window);
documentNode.setOptions({ layoutScroll: true });
rootProjectionNode.current = documentNode;
}
return rootProjectionNode.current;
},
resetTransform: (instance, value) => {
instance.style.transform = value !== undefined ? value : "none";
},
checkIsScrollRoot: (instance) => Boolean(window.getComputedStyle(instance).position === "fixed"),
});
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/render/dom/motion.mjs
const featureBundle = {
...animations,
...gestureAnimations,
...drag,
...layoutFeatures,
};
/**
* HTML & SVG components, optimised for use with gestures and animation. These can be used as
* drop-in replacements for any HTML & SVG component, all CSS & SVG properties are supported.
*
* @public
*/
const motion = /*@__PURE__*/ createMotionProxy((Component, config) => create_config_createDomMotionConfig(Component, config, featureBundle, create_visual_element_createDomVisualElement, HTMLProjectionNode_HTMLProjectionNode));
/**
* Create a DOM `motion` component with the provided string. This is primarily intended
* as a full alternative to `motion` for consumers who have to support environments that don't
* support `Proxy`.
*
* ```javascript
* import { createDomMotionComponent } from "framer-motion"
*
* const motion = {
* div: createDomMotionComponent('div')
* }
* ```
*
* @public
*/
function createDomMotionComponent(key) {
return createMotionComponent(createDomMotionConfig(key, { forwardMotionProps: false }, featureBundle, createDomVisualElement, HTMLProjectionNode));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/close.js
/**
* WordPress dependencies
*/
const close_close = (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: "M13 11.8l6.1-6.3-1-1-6.1 6.2-6.1-6.2-1 1 6.1 6.3-6.5 6.7 1 1 6.5-6.6 6.5 6.6 1-1z"
}));
/* harmony default export */ var library_close = (close_close);
;// CONCATENATED MODULE: external ["wp","deprecated"]
var external_wp_deprecated_namespaceObject = window["wp"]["deprecated"];
var external_wp_deprecated_default = /*#__PURE__*/__webpack_require__.n(external_wp_deprecated_namespaceObject);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/dashicon/index.js
/**
* @typedef OwnProps
*
* @property {import('./types').IconKey} icon Icon name
* @property {string} [className] Class name
* @property {number} [size] Size of the icon
*/
/**
* Internal dependencies
*/
function Dashicon(_ref) {
let {
icon,
className,
size = 20,
style = {},
...extraProps
} = _ref;
const iconClass = ['dashicon', 'dashicons', 'dashicons-' + icon, className].filter(Boolean).join(' '); // For retro-compatibility reasons (for example if people are overriding icon size with CSS), we add inline styles just if the size is different to the default
const sizeStyles = // using `!=` to catch both 20 and "20"
// eslint-disable-next-line eqeqeq
20 != size ? {
fontSize: `${size}px`,
width: `${size}px`,
height: `${size}px`
} : {};
const styles = { ...sizeStyles,
...style
};
return (0,external_wp_element_namespaceObject.createElement)("span", extends_extends({
className: iconClass,
style: styles
}, extraProps));
}
/* harmony default export */ var dashicon = (Dashicon);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/icon/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function Icon(_ref) {
let {
icon = null,
size = 'string' === typeof icon ? 20 : 24,
...additionalProps
} = _ref;
if ('string' === typeof icon) {
return (0,external_wp_element_namespaceObject.createElement)(dashicon, extends_extends({
icon: icon,
size: size
}, additionalProps));
}
if ((0,external_wp_element_namespaceObject.isValidElement)(icon) && dashicon === icon.type) {
return (0,external_wp_element_namespaceObject.cloneElement)(icon, { ...additionalProps
});
}
if ('function' === typeof icon) {
if (icon.prototype instanceof external_wp_element_namespaceObject.Component) {
return (0,external_wp_element_namespaceObject.createElement)(icon, {
size,
...additionalProps
});
}
return icon({
size,
...additionalProps
});
}
if (icon && (icon.type === 'svg' || icon.type === external_wp_primitives_namespaceObject.SVG)) {
const appliedProps = { ...icon.props,
width: size,
height: size,
...additionalProps
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, appliedProps);
}
if ((0,external_wp_element_namespaceObject.isValidElement)(icon)) {
return (0,external_wp_element_namespaceObject.cloneElement)(icon, {
// @ts-ignore Just forwarding the size prop along
size,
...additionalProps
});
}
return icon;
}
/* harmony default export */ var build_module_icon = (Icon);
;// CONCATENATED MODULE: external ["wp","warning"]
var external_wp_warning_namespaceObject = window["wp"]["warning"];
// EXTERNAL MODULE: ./node_modules/fast-deep-equal/es6/index.js
var es6 = __webpack_require__(5619);
var es6_default = /*#__PURE__*/__webpack_require__.n(es6);
;// CONCATENATED MODULE: external "lodash"
var external_lodash_namespaceObject = window["lodash"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/hooks/use-update-effect.js
/**
* WordPress dependencies
*/
/**
* A `React.useEffect` that will not run on the first render.
* Source:
* https://github.com/reakit/reakit/blob/HEAD/packages/reakit-utils/src/useUpdateEffect.ts
*
* @param {import('react').EffectCallback} effect
* @param {import('react').DependencyList} deps
*/
function useUpdateEffect(effect, deps) {
const mounted = (0,external_wp_element_namespaceObject.useRef)(false);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (mounted.current) {
return effect();
}
mounted.current = true;
return undefined; // Disable reasons:
// 1. This hook needs to pass a dep list that isn't an array literal
// 2. `effect` is missing from the array, and will need to be added carefully to avoid additional warnings
// see https://github.com/WordPress/gutenberg/pull/41166
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
}
/* harmony default export */ var use_update_effect = (useUpdateEffect);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/context/context-system-provider.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const ComponentsContext = (0,external_wp_element_namespaceObject.createContext)(
/** @type {Record<string, any>} */
{});
const useComponentsContext = () => (0,external_wp_element_namespaceObject.useContext)(ComponentsContext);
/**
* Consolidates incoming ContextSystem values with a (potential) parent ContextSystem value.
*
* Note: This function will warn if it detects an un-memoized `value`
*
* @param {Object} props
* @param {Record<string, any>} props.value
* @return {Record<string, any>} The consolidated value.
*/
function useContextSystemBridge(_ref) {
let {
value
} = _ref;
const parentContext = useComponentsContext();
const valueRef = (0,external_wp_element_namespaceObject.useRef)(value);
use_update_effect(() => {
if ( // Objects are equivalent.
es6_default()(valueRef.current, value) && // But not the same reference.
valueRef.current !== value) {
typeof process !== "undefined" && process.env && "production" !== "production" ? 0 : void 0;
}
}, [value]); // `parentContext` will always be memoized (i.e., the result of this hook itself)
// or the default value from when the `ComponentsContext` was originally
// initialized (which will never change, it's a static variable)
// so this memoization will prevent `merge` and `JSON.parse/stringify` from rerunning unless
// the references to `value` change OR the `parentContext` has an actual material change
// (because again, it's guaranteed to be memoized or a static reference to the empty object
// so we know that the only changes for `parentContext` are material ones... i.e., why we
// don't have to warn in the `useUpdateEffect` hook above for `parentContext` and we only
// need to bother with the `value`). The `useUpdateEffect` above will ensure that we are
// correctly warning when the `value` isn't being properly memoized. All of that to say
// that this should be super safe to assume that `useMemo` will only run on actual
// changes to the two dependencies, therefore saving us calls to `merge` and `JSON.parse/stringify`!
const config = (0,external_wp_element_namespaceObject.useMemo)(() => {
// Deep clone `parentContext` to avoid mutating it later.
return (0,external_lodash_namespaceObject.merge)(JSON.parse(JSON.stringify(parentContext)), value);
}, [parentContext, value]);
return config;
}
/**
* A Provider component that can modify props for connected components within
* the Context system.
*
* @example
* ```jsx
* <ContextSystemProvider value={{ Button: { size: 'small' }}}>
* <Button>...</Button>
* </ContextSystemProvider>
* ```
*
* @template {Record<string, any>} T
* @param {Object} options
* @param {import('react').ReactNode} options.children Children to render.
* @param {T} options.value Props to render into connected components.
* @return {JSX.Element} A Provider wrapped component.
*/
const BaseContextSystemProvider = _ref2 => {
let {
children,
value
} = _ref2;
const contextValue = useContextSystemBridge({
value
});
return (0,external_wp_element_namespaceObject.createElement)(ComponentsContext.Provider, {
value: contextValue
}, children);
};
const ContextSystemProvider = (0,external_wp_element_namespaceObject.memo)(BaseContextSystemProvider);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/context/constants.js
const REACT_TYPEOF_KEY = '$$typeof';
const COMPONENT_NAMESPACE = 'data-wp-component';
const CONNECTED_NAMESPACE = 'data-wp-c16t';
const CONTEXT_COMPONENT_NAMESPACE = 'data-wp-c5tc8t';
/**
* Special key where the connected namespaces are stored.
* This is attached to Context connected components as a static property.
*/
const CONNECT_STATIC_NAMESPACE = '__contextSystemKey__';
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/context/utils.js
/**
* Internal dependencies
*/
/**
* Creates a dedicated context namespace HTML attribute for components.
* ns is short for "namespace"
*
* @example
* ```jsx
* <div {...ns('Container')} />
* ```
*
* @param {string} componentName The name for the component.
* @return {Record<string, any>} A props object with the namespaced HTML attribute.
*/
function getNamespace(componentName) {
return {
[COMPONENT_NAMESPACE]: componentName
};
}
/**
* Creates a dedicated connected context namespace HTML attribute for components.
* ns is short for "namespace"
*
* @example
* ```jsx
* <div {...cns()} />
* ```
*
* @return {Record<string, any>} A props object with the namespaced HTML attribute.
*/
function getConnectedNamespace() {
return {
[CONNECTED_NAMESPACE]: true
};
}
// EXTERNAL MODULE: ./node_modules/memize/index.js
var memize = __webpack_require__(9756);
var memize_default = /*#__PURE__*/__webpack_require__.n(memize);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/context/get-styled-class-name-from-key.js
/**
* External dependencies
*/
/**
* Generates the connected component CSS className based on the namespace.
*
* @param namespace The name of the connected component.
* @return The generated CSS className.
*/
function getStyledClassName(namespace) {
const kebab = (0,external_lodash_namespaceObject.kebabCase)(namespace);
return `components-${kebab}`;
}
const getStyledClassNameFromKey = memize_default()(getStyledClassName);
;// CONCATENATED MODULE: ./node_modules/@emotion/sheet/dist/emotion-sheet.browser.esm.js
/*
Based off glamor's StyleSheet, thanks Sunil ❤️
high performance StyleSheet for css-in-js systems
- uses multiple style tags behind the scenes for millions of rules
- uses `insertRule` for appending in production for *much* faster performance
// usage
import { StyleSheet } from '@emotion/sheet'
let styleSheet = new StyleSheet({ key: '', container: document.head })
styleSheet.insert('#box { border: 1px solid red; }')
- appends a css rule into the stylesheet
styleSheet.flush()
- empties the stylesheet of all its contents
*/
// $FlowFixMe
function sheetForTag(tag) {
if (tag.sheet) {
// $FlowFixMe
return tag.sheet;
} // this weirdness brought to you by firefox
/* istanbul ignore next */
for (var i = 0; i < document.styleSheets.length; i++) {
if (document.styleSheets[i].ownerNode === tag) {
// $FlowFixMe
return document.styleSheets[i];
}
}
}
function createStyleElement(options) {
var tag = document.createElement('style');
tag.setAttribute('data-emotion', options.key);
if (options.nonce !== undefined) {
tag.setAttribute('nonce', options.nonce);
}
tag.appendChild(document.createTextNode(''));
tag.setAttribute('data-s', '');
return tag;
}
var StyleSheet = /*#__PURE__*/function () {
// Using Node instead of HTMLElement since container may be a ShadowRoot
function StyleSheet(options) {
var _this = this;
this._insertTag = function (tag) {
var before;
if (_this.tags.length === 0) {
if (_this.insertionPoint) {
before = _this.insertionPoint.nextSibling;
} else if (_this.prepend) {
before = _this.container.firstChild;
} else {
before = _this.before;
}
} else {
before = _this.tags[_this.tags.length - 1].nextSibling;
}
_this.container.insertBefore(tag, before);
_this.tags.push(tag);
};
this.isSpeedy = options.speedy === undefined ? "production" === 'production' : options.speedy;
this.tags = [];
this.ctr = 0;
this.nonce = options.nonce; // key is the value of the data-emotion attribute, it's used to identify different sheets
this.key = options.key;
this.container = options.container;
this.prepend = options.prepend;
this.insertionPoint = options.insertionPoint;
this.before = null;
}
var _proto = StyleSheet.prototype;
_proto.hydrate = function hydrate(nodes) {
nodes.forEach(this._insertTag);
};
_proto.insert = function insert(rule) {
// the max length is how many rules we have per style tag, it's 65000 in speedy mode
// it's 1 in dev because we insert source maps that map a single rule to a location
// and you can only have one source map per style tag
if (this.ctr % (this.isSpeedy ? 65000 : 1) === 0) {
this._insertTag(createStyleElement(this));
}
var tag = this.tags[this.tags.length - 1];
if (false) { var isImportRule; }
if (this.isSpeedy) {
var sheet = sheetForTag(tag);
try {
// this is the ultrafast version, works across browsers
// the big drawback is that the css won't be editable in devtools
sheet.insertRule(rule, sheet.cssRules.length);
} catch (e) {
if (false) {}
}
} else {
tag.appendChild(document.createTextNode(rule));
}
this.ctr++;
};
_proto.flush = function flush() {
// $FlowFixMe
this.tags.forEach(function (tag) {
return tag.parentNode && tag.parentNode.removeChild(tag);
});
this.tags = [];
this.ctr = 0;
if (false) {}
};
return StyleSheet;
}();
;// CONCATENATED MODULE: ./node_modules/stylis/src/Utility.js
/**
* @param {number}
* @return {number}
*/
var abs = Math.abs
/**
* @param {number}
* @return {string}
*/
var Utility_from = String.fromCharCode
/**
* @param {object}
* @return {object}
*/
var Utility_assign = Object.assign
/**
* @param {string} value
* @param {number} length
* @return {number}
*/
function hash (value, length) {
return Utility_charat(value, 0) ^ 45 ? (((((((length << 2) ^ Utility_charat(value, 0)) << 2) ^ Utility_charat(value, 1)) << 2) ^ Utility_charat(value, 2)) << 2) ^ Utility_charat(value, 3) : 0
}
/**
* @param {string} value
* @return {string}
*/
function trim (value) {
return value.trim()
}
/**
* @param {string} value
* @param {RegExp} pattern
* @return {string?}
*/
function Utility_match (value, pattern) {
return (value = pattern.exec(value)) ? value[0] : value
}
/**
* @param {string} value
* @param {(string|RegExp)} pattern
* @param {string} replacement
* @return {string}
*/
function Utility_replace (value, pattern, replacement) {
return value.replace(pattern, replacement)
}
/**
* @param {string} value
* @param {string} search
* @return {number}
*/
function indexof (value, search) {
return value.indexOf(search)
}
/**
* @param {string} value
* @param {number} index
* @return {number}
*/
function Utility_charat (value, index) {
return value.charCodeAt(index) | 0
}
/**
* @param {string} value
* @param {number} begin
* @param {number} end
* @return {string}
*/
function Utility_substr (value, begin, end) {
return value.slice(begin, end)
}
/**
* @param {string} value
* @return {number}
*/
function Utility_strlen (value) {
return value.length
}
/**
* @param {any[]} value
* @return {number}
*/
function Utility_sizeof (value) {
return value.length
}
/**
* @param {any} value
* @param {any[]} array
* @return {any}
*/
function Utility_append (value, array) {
return array.push(value), value
}
/**
* @param {string[]} array
* @param {function} callback
* @return {string}
*/
function Utility_combine (array, callback) {
return array.map(callback).join('')
}
;// CONCATENATED MODULE: ./node_modules/stylis/src/Tokenizer.js
var line = 1
var column = 1
var Tokenizer_length = 0
var position = 0
var character = 0
var characters = ''
/**
* @param {string} value
* @param {object | null} root
* @param {object | null} parent
* @param {string} type
* @param {string[] | string} props
* @param {object[] | string} children
* @param {number} length
*/
function node (value, root, parent, type, props, children, length) {
return {value: value, root: root, parent: parent, type: type, props: props, children: children, line: line, column: column, length: length, return: ''}
}
/**
* @param {object} root
* @param {object} props
* @return {object}
*/
function Tokenizer_copy (root, props) {
return Utility_assign(node('', null, null, '', null, null, 0), root, {length: -root.length}, props)
}
/**
* @return {number}
*/
function Tokenizer_char () {
return character
}
/**
* @return {number}
*/
function prev () {
character = position > 0 ? Utility_charat(characters, --position) : 0
if (column--, character === 10)
column = 1, line--
return character
}
/**
* @return {number}
*/
function next () {
character = position < Tokenizer_length ? Utility_charat(characters, position++) : 0
if (column++, character === 10)
column = 1, line++
return character
}
/**
* @return {number}
*/
function peek () {
return Utility_charat(characters, position)
}
/**
* @return {number}
*/
function caret () {
return position
}
/**
* @param {number} begin
* @param {number} end
* @return {string}
*/
function slice (begin, end) {
return Utility_substr(characters, begin, end)
}
/**
* @param {number} type
* @return {number}
*/
function token (type) {
switch (type) {
// \0 \t \n \r \s whitespace token
case 0: case 9: case 10: case 13: case 32:
return 5
// ! + , / > @ ~ isolate token
case 33: case 43: case 44: case 47: case 62: case 64: case 126:
// ; { } breakpoint token
case 59: case 123: case 125:
return 4
// : accompanied token
case 58:
return 3
// " ' ( [ opening delimit token
case 34: case 39: case 40: case 91:
return 2
// ) ] closing delimit token
case 41: case 93:
return 1
}
return 0
}
/**
* @param {string} value
* @return {any[]}
*/
function alloc (value) {
return line = column = 1, Tokenizer_length = Utility_strlen(characters = value), position = 0, []
}
/**
* @param {any} value
* @return {any}
*/
function dealloc (value) {
return characters = '', value
}
/**
* @param {number} type
* @return {string}
*/
function delimit (type) {
return trim(slice(position - 1, delimiter(type === 91 ? type + 2 : type === 40 ? type + 1 : type)))
}
/**
* @param {string} value
* @return {string[]}
*/
function Tokenizer_tokenize (value) {
return dealloc(tokenizer(alloc(value)))
}
/**
* @param {number} type
* @return {string}
*/
function whitespace (type) {
while (character = peek())
if (character < 33)
next()
else
break
return token(type) > 2 || token(character) > 3 ? '' : ' '
}
/**
* @param {string[]} children
* @return {string[]}
*/
function tokenizer (children) {
while (next())
switch (token(character)) {
case 0: append(identifier(position - 1), children)
break
case 2: append(delimit(character), children)
break
default: append(from(character), children)
}
return children
}
/**
* @param {number} index
* @param {number} count
* @return {string}
*/
function escaping (index, count) {
while (--count && next())
// not 0-9 A-F a-f
if (character < 48 || character > 102 || (character > 57 && character < 65) || (character > 70 && character < 97))
break
return slice(index, caret() + (count < 6 && peek() == 32 && next() == 32))
}
/**
* @param {number} type
* @return {number}
*/
function delimiter (type) {
while (next())
switch (character) {
// ] ) " '
case type:
return position
// " '
case 34: case 39:
if (type !== 34 && type !== 39)
delimiter(character)
break
// (
case 40:
if (type === 41)
delimiter(type)
break
// \
case 92:
next()
break
}
return position
}
/**
* @param {number} type
* @param {number} index
* @return {number}
*/
function commenter (type, index) {
while (next())
// //
if (type + character === 47 + 10)
break
// /*
else if (type + character === 42 + 42 && peek() === 47)
break
return '/*' + slice(index, position - 1) + '*' + Utility_from(type === 47 ? type : next())
}
/**
* @param {number} index
* @return {string}
*/
function identifier (index) {
while (!token(peek()))
next()
return slice(index, position)
}
;// CONCATENATED MODULE: ./node_modules/stylis/src/Enum.js
var Enum_MS = '-ms-'
var Enum_MOZ = '-moz-'
var Enum_WEBKIT = '-webkit-'
var COMMENT = 'comm'
var Enum_RULESET = 'rule'
var Enum_DECLARATION = 'decl'
var PAGE = '@page'
var MEDIA = '@media'
var IMPORT = '@import'
var CHARSET = '@charset'
var VIEWPORT = '@viewport'
var SUPPORTS = '@supports'
var DOCUMENT = '@document'
var NAMESPACE = '@namespace'
var Enum_KEYFRAMES = '@keyframes'
var FONT_FACE = '@font-face'
var COUNTER_STYLE = '@counter-style'
var FONT_FEATURE_VALUES = '@font-feature-values'
var LAYER = '@layer'
;// CONCATENATED MODULE: ./node_modules/stylis/src/Serializer.js
/**
* @param {object[]} children
* @param {function} callback
* @return {string}
*/
function Serializer_serialize (children, callback) {
var output = ''
var length = Utility_sizeof(children)
for (var i = 0; i < length; i++)
output += callback(children[i], i, children, callback) || ''
return output
}
/**
* @param {object} element
* @param {number} index
* @param {object[]} children
* @param {function} callback
* @return {string}
*/
function stringify (element, index, children, callback) {
switch (element.type) {
case LAYER: if (element.children.length) break
case IMPORT: case Enum_DECLARATION: return element.return = element.return || element.value
case COMMENT: return ''
case Enum_KEYFRAMES: return element.return = element.value + '{' + Serializer_serialize(element.children, callback) + '}'
case Enum_RULESET: element.value = element.props.join(',')
}
return Utility_strlen(children = Serializer_serialize(element.children, callback)) ? element.return = element.value + '{' + children + '}' : ''
}
;// CONCATENATED MODULE: ./node_modules/stylis/src/Middleware.js
/**
* @param {function[]} collection
* @return {function}
*/
function middleware (collection) {
var length = Utility_sizeof(collection)
return function (element, index, children, callback) {
var output = ''
for (var i = 0; i < length; i++)
output += collection[i](element, index, children, callback) || ''
return output
}
}
/**
* @param {function} callback
* @return {function}
*/
function rulesheet (callback) {
return function (element) {
if (!element.root)
if (element = element.return)
callback(element)
}
}
/**
* @param {object} element
* @param {number} index
* @param {object[]} children
* @param {function} callback
*/
function prefixer (element, index, children, callback) {
if (element.length > -1)
if (!element.return)
switch (element.type) {
case DECLARATION: element.return = prefix(element.value, element.length, children)
return
case KEYFRAMES:
return serialize([copy(element, {value: replace(element.value, '@', '@' + WEBKIT)})], callback)
case RULESET:
if (element.length)
return combine(element.props, function (value) {
switch (match(value, /(::plac\w+|:read-\w+)/)) {
// :read-(only|write)
case ':read-only': case ':read-write':
return serialize([copy(element, {props: [replace(value, /:(read-\w+)/, ':' + MOZ + '$1')]})], callback)
// :placeholder
case '::placeholder':
return serialize([
copy(element, {props: [replace(value, /:(plac\w+)/, ':' + WEBKIT + 'input-$1')]}),
copy(element, {props: [replace(value, /:(plac\w+)/, ':' + MOZ + '$1')]}),
copy(element, {props: [replace(value, /:(plac\w+)/, MS + 'input-$1')]})
], callback)
}
return ''
})
}
}
/**
* @param {object} element
* @param {number} index
* @param {object[]} children
*/
function namespace (element) {
switch (element.type) {
case RULESET:
element.props = element.props.map(function (value) {
return combine(tokenize(value), function (value, index, children) {
switch (charat(value, 0)) {
// \f
case 12:
return substr(value, 1, strlen(value))
// \0 ( + > ~
case 0: case 40: case 43: case 62: case 126:
return value
// :
case 58:
if (children[++index] === 'global')
children[index] = '', children[++index] = '\f' + substr(children[index], index = 1, -1)
// \s
case 32:
return index === 1 ? '' : value
default:
switch (index) {
case 0: element = value
return sizeof(children) > 1 ? '' : value
case index = sizeof(children) - 1: case 2:
return index === 2 ? value + element + element : value + element
default:
return value
}
}
})
})
}
}
;// CONCATENATED MODULE: ./node_modules/stylis/src/Parser.js
/**
* @param {string} value
* @return {object[]}
*/
function compile (value) {
return dealloc(Parser_parse('', null, null, null, [''], value = alloc(value), 0, [0], value))
}
/**
* @param {string} value
* @param {object} root
* @param {object?} parent
* @param {string[]} rule
* @param {string[]} rules
* @param {string[]} rulesets
* @param {number[]} pseudo
* @param {number[]} points
* @param {string[]} declarations
* @return {object}
*/
function Parser_parse (value, root, parent, rule, rules, rulesets, pseudo, points, declarations) {
var index = 0
var offset = 0
var length = pseudo
var atrule = 0
var property = 0
var previous = 0
var variable = 1
var scanning = 1
var ampersand = 1
var character = 0
var type = ''
var props = rules
var children = rulesets
var reference = rule
var characters = type
while (scanning)
switch (previous = character, character = next()) {
// (
case 40:
if (previous != 108 && Utility_charat(characters, length - 1) == 58) {
if (indexof(characters += Utility_replace(delimit(character), '&', '&\f'), '&\f') != -1)
ampersand = -1
break
}
// " ' [
case 34: case 39: case 91:
characters += delimit(character)
break
// \t \n \r \s
case 9: case 10: case 13: case 32:
characters += whitespace(previous)
break
// \
case 92:
characters += escaping(caret() - 1, 7)
continue
// /
case 47:
switch (peek()) {
case 42: case 47:
Utility_append(comment(commenter(next(), caret()), root, parent), declarations)
break
default:
characters += '/'
}
break
// {
case 123 * variable:
points[index++] = Utility_strlen(characters) * ampersand
// } ; \0
case 125 * variable: case 59: case 0:
switch (character) {
// \0 }
case 0: case 125: scanning = 0
// ;
case 59 + offset: if (ampersand == -1) characters = Utility_replace(characters, /\f/g, '')
if (property > 0 && (Utility_strlen(characters) - length))
Utility_append(property > 32 ? declaration(characters + ';', rule, parent, length - 1) : declaration(Utility_replace(characters, ' ', '') + ';', rule, parent, length - 2), declarations)
break
// @ ;
case 59: characters += ';'
// { rule/at-rule
default:
Utility_append(reference = ruleset(characters, root, parent, index, offset, rules, points, type, props = [], children = [], length), rulesets)
if (character === 123)
if (offset === 0)
Parser_parse(characters, root, reference, reference, props, rulesets, length, points, children)
else
switch (atrule === 99 && Utility_charat(characters, 3) === 110 ? 100 : atrule) {
// d l m s
case 100: case 108: case 109: case 115:
Parser_parse(value, reference, reference, rule && Utility_append(ruleset(value, reference, reference, 0, 0, rules, points, type, rules, props = [], length), children), rules, children, length, points, rule ? props : children)
break
default:
Parser_parse(characters, reference, reference, reference, [''], children, 0, points, children)
}
}
index = offset = property = 0, variable = ampersand = 1, type = characters = '', length = pseudo
break
// :
case 58:
length = 1 + Utility_strlen(characters), property = previous
default:
if (variable < 1)
if (character == 123)
--variable
else if (character == 125 && variable++ == 0 && prev() == 125)
continue
switch (characters += Utility_from(character), character * variable) {
// &
case 38:
ampersand = offset > 0 ? 1 : (characters += '\f', -1)
break
// ,
case 44:
points[index++] = (Utility_strlen(characters) - 1) * ampersand, ampersand = 1
break
// @
case 64:
// -
if (peek() === 45)
characters += delimit(next())
atrule = peek(), offset = length = Utility_strlen(type = characters += identifier(caret())), character++
break
// -
case 45:
if (previous === 45 && Utility_strlen(characters) == 2)
variable = 0
}
}
return rulesets
}
/**
* @param {string} value
* @param {object} root
* @param {object?} parent
* @param {number} index
* @param {number} offset
* @param {string[]} rules
* @param {number[]} points
* @param {string} type
* @param {string[]} props
* @param {string[]} children
* @param {number} length
* @return {object}
*/
function ruleset (value, root, parent, index, offset, rules, points, type, props, children, length) {
var post = offset - 1
var rule = offset === 0 ? rules : ['']
var size = Utility_sizeof(rule)
for (var i = 0, j = 0, k = 0; i < index; ++i)
for (var x = 0, y = Utility_substr(value, post + 1, post = abs(j = points[i])), z = value; x < size; ++x)
if (z = trim(j > 0 ? rule[x] + ' ' + y : Utility_replace(y, /&\f/g, rule[x])))
props[k++] = z
return node(value, root, parent, offset === 0 ? Enum_RULESET : type, props, children, length)
}
/**
* @param {number} value
* @param {object} root
* @param {object?} parent
* @return {object}
*/
function comment (value, root, parent) {
return node(value, root, parent, COMMENT, Utility_from(Tokenizer_char()), Utility_substr(value, 2, -2), 0)
}
/**
* @param {string} value
* @param {object} root
* @param {object?} parent
* @param {number} length
* @return {object}
*/
function declaration (value, root, parent, length) {
return node(value, root, parent, Enum_DECLARATION, Utility_substr(value, 0, length), Utility_substr(value, length + 1, -1), length)
}
;// CONCATENATED MODULE: ./node_modules/@emotion/cache/dist/emotion-cache.browser.esm.js
var identifierWithPointTracking = function identifierWithPointTracking(begin, points, index) {
var previous = 0;
var character = 0;
while (true) {
previous = character;
character = peek(); // &\f
if (previous === 38 && character === 12) {
points[index] = 1;
}
if (token(character)) {
break;
}
next();
}
return slice(begin, position);
};
var toRules = function toRules(parsed, points) {
// pretend we've started with a comma
var index = -1;
var character = 44;
do {
switch (token(character)) {
case 0:
// &\f
if (character === 38 && peek() === 12) {
// this is not 100% correct, we don't account for literal sequences here - like for example quoted strings
// stylis inserts \f after & to know when & where it should replace this sequence with the context selector
// and when it should just concatenate the outer and inner selectors
// it's very unlikely for this sequence to actually appear in a different context, so we just leverage this fact here
points[index] = 1;
}
parsed[index] += identifierWithPointTracking(position - 1, points, index);
break;
case 2:
parsed[index] += delimit(character);
break;
case 4:
// comma
if (character === 44) {
// colon
parsed[++index] = peek() === 58 ? '&\f' : '';
points[index] = parsed[index].length;
break;
}
// fallthrough
default:
parsed[index] += Utility_from(character);
}
} while (character = next());
return parsed;
};
var getRules = function getRules(value, points) {
return dealloc(toRules(alloc(value), points));
}; // WeakSet would be more appropriate, but only WeakMap is supported in IE11
var fixedElements = /* #__PURE__ */new WeakMap();
var compat = function compat(element) {
if (element.type !== 'rule' || !element.parent || // positive .length indicates that this rule contains pseudo
// negative .length indicates that this rule has been already prefixed
element.length < 1) {
return;
}
var value = element.value,
parent = element.parent;
var isImplicitRule = element.column === parent.column && element.line === parent.line;
while (parent.type !== 'rule') {
parent = parent.parent;
if (!parent) return;
} // short-circuit for the simplest case
if (element.props.length === 1 && value.charCodeAt(0) !== 58
/* colon */
&& !fixedElements.get(parent)) {
return;
} // if this is an implicitly inserted rule (the one eagerly inserted at the each new nested level)
// then the props has already been manipulated beforehand as they that array is shared between it and its "rule parent"
if (isImplicitRule) {
return;
}
fixedElements.set(element, true);
var points = [];
var rules = getRules(value, points);
var parentRules = parent.props;
for (var i = 0, k = 0; i < rules.length; i++) {
for (var j = 0; j < parentRules.length; j++, k++) {
element.props[k] = points[i] ? rules[i].replace(/&\f/g, parentRules[j]) : parentRules[j] + " " + rules[i];
}
}
};
var removeLabel = function removeLabel(element) {
if (element.type === 'decl') {
var value = element.value;
if ( // charcode for l
value.charCodeAt(0) === 108 && // charcode for b
value.charCodeAt(2) === 98) {
// this ignores label
element["return"] = '';
element.value = '';
}
}
};
var ignoreFlag = 'emotion-disable-server-rendering-unsafe-selector-warning-please-do-not-use-this-the-warning-exists-for-a-reason';
var isIgnoringComment = function isIgnoringComment(element) {
return element.type === 'comm' && element.children.indexOf(ignoreFlag) > -1;
};
var createUnsafeSelectorsAlarm = function createUnsafeSelectorsAlarm(cache) {
return function (element, index, children) {
if (element.type !== 'rule' || cache.compat) return;
var unsafePseudoClasses = element.value.match(/(:first|:nth|:nth-last)-child/g);
if (unsafePseudoClasses) {
var isNested = !!element.parent; // in nested rules comments become children of the "auto-inserted" rule and that's always the `element.parent`
//
// considering this input:
// .a {
// .b /* comm */ {}
// color: hotpink;
// }
// we get output corresponding to this:
// .a {
// & {
// /* comm */
// color: hotpink;
// }
// .b {}
// }
var commentContainer = isNested ? element.parent.children : // global rule at the root level
children;
for (var i = commentContainer.length - 1; i >= 0; i--) {
var node = commentContainer[i];
if (node.line < element.line) {
break;
} // it is quite weird but comments are *usually* put at `column: element.column - 1`
// so we seek *from the end* for the node that is earlier than the rule's `element` and check that
// this will also match inputs like this:
// .a {
// /* comm */
// .b {}
// }
//
// but that is fine
//
// it would be the easiest to change the placement of the comment to be the first child of the rule:
// .a {
// .b { /* comm */ }
// }
// with such inputs we wouldn't have to search for the comment at all
// TODO: consider changing this comment placement in the next major version
if (node.column < element.column) {
if (isIgnoringComment(node)) {
return;
}
break;
}
}
unsafePseudoClasses.forEach(function (unsafePseudoClass) {
console.error("The pseudo class \"" + unsafePseudoClass + "\" is potentially unsafe when doing server-side rendering. Try changing it to \"" + unsafePseudoClass.split('-child')[0] + "-of-type\".");
});
}
};
};
var isImportRule = function isImportRule(element) {
return element.type.charCodeAt(1) === 105 && element.type.charCodeAt(0) === 64;
};
var isPrependedWithRegularRules = function isPrependedWithRegularRules(index, children) {
for (var i = index - 1; i >= 0; i--) {
if (!isImportRule(children[i])) {
return true;
}
}
return false;
}; // use this to remove incorrect elements from further processing
// so they don't get handed to the `sheet` (or anything else)
// as that could potentially lead to additional logs which in turn could be overhelming to the user
var nullifyElement = function nullifyElement(element) {
element.type = '';
element.value = '';
element["return"] = '';
element.children = '';
element.props = '';
};
var incorrectImportAlarm = function incorrectImportAlarm(element, index, children) {
if (!isImportRule(element)) {
return;
}
if (element.parent) {
console.error("`@import` rules can't be nested inside other rules. Please move it to the top level and put it before regular rules. Keep in mind that they can only be used within global styles.");
nullifyElement(element);
} else if (isPrependedWithRegularRules(index, children)) {
console.error("`@import` rules can't be after other rules. Please put your `@import` rules before your other rules.");
nullifyElement(element);
}
};
/* eslint-disable no-fallthrough */
function emotion_cache_browser_esm_prefix(value, length) {
switch (hash(value, length)) {
// color-adjust
case 5103:
return Enum_WEBKIT + 'print-' + value + value;
// animation, animation-(delay|direction|duration|fill-mode|iteration-count|name|play-state|timing-function)
case 5737:
case 4201:
case 3177:
case 3433:
case 1641:
case 4457:
case 2921: // text-decoration, filter, clip-path, backface-visibility, column, box-decoration-break
case 5572:
case 6356:
case 5844:
case 3191:
case 6645:
case 3005: // mask, mask-image, mask-(mode|clip|size), mask-(repeat|origin), mask-position, mask-composite,
case 6391:
case 5879:
case 5623:
case 6135:
case 4599:
case 4855: // background-clip, columns, column-(count|fill|gap|rule|rule-color|rule-style|rule-width|span|width)
case 4215:
case 6389:
case 5109:
case 5365:
case 5621:
case 3829:
return Enum_WEBKIT + value + value;
// appearance, user-select, transform, hyphens, text-size-adjust
case 5349:
case 4246:
case 4810:
case 6968:
case 2756:
return Enum_WEBKIT + value + Enum_MOZ + value + Enum_MS + value + value;
// flex, flex-direction
case 6828:
case 4268:
return Enum_WEBKIT + value + Enum_MS + value + value;
// order
case 6165:
return Enum_WEBKIT + value + Enum_MS + 'flex-' + value + value;
// align-items
case 5187:
return Enum_WEBKIT + value + Utility_replace(value, /(\w+).+(:[^]+)/, Enum_WEBKIT + 'box-$1$2' + Enum_MS + 'flex-$1$2') + value;
// align-self
case 5443:
return Enum_WEBKIT + value + Enum_MS + 'flex-item-' + Utility_replace(value, /flex-|-self/, '') + value;
// align-content
case 4675:
return Enum_WEBKIT + value + Enum_MS + 'flex-line-pack' + Utility_replace(value, /align-content|flex-|-self/, '') + value;
// flex-shrink
case 5548:
return Enum_WEBKIT + value + Enum_MS + Utility_replace(value, 'shrink', 'negative') + value;
// flex-basis
case 5292:
return Enum_WEBKIT + value + Enum_MS + Utility_replace(value, 'basis', 'preferred-size') + value;
// flex-grow
case 6060:
return Enum_WEBKIT + 'box-' + Utility_replace(value, '-grow', '') + Enum_WEBKIT + value + Enum_MS + Utility_replace(value, 'grow', 'positive') + value;
// transition
case 4554:
return Enum_WEBKIT + Utility_replace(value, /([^-])(transform)/g, '$1' + Enum_WEBKIT + '$2') + value;
// cursor
case 6187:
return Utility_replace(Utility_replace(Utility_replace(value, /(zoom-|grab)/, Enum_WEBKIT + '$1'), /(image-set)/, Enum_WEBKIT + '$1'), value, '') + value;
// background, background-image
case 5495:
case 3959:
return Utility_replace(value, /(image-set\([^]*)/, Enum_WEBKIT + '$1' + '$`$1');
// justify-content
case 4968:
return Utility_replace(Utility_replace(value, /(.+:)(flex-)?(.*)/, Enum_WEBKIT + 'box-pack:$3' + Enum_MS + 'flex-pack:$3'), /s.+-b[^;]+/, 'justify') + Enum_WEBKIT + value + value;
// (margin|padding)-inline-(start|end)
case 4095:
case 3583:
case 4068:
case 2532:
return Utility_replace(value, /(.+)-inline(.+)/, Enum_WEBKIT + '$1$2') + value;
// (min|max)?(width|height|inline-size|block-size)
case 8116:
case 7059:
case 5753:
case 5535:
case 5445:
case 5701:
case 4933:
case 4677:
case 5533:
case 5789:
case 5021:
case 4765:
// stretch, max-content, min-content, fill-available
if (Utility_strlen(value) - 1 - length > 6) switch (Utility_charat(value, length + 1)) {
// (m)ax-content, (m)in-content
case 109:
// -
if (Utility_charat(value, length + 4) !== 45) break;
// (f)ill-available, (f)it-content
case 102:
return Utility_replace(value, /(.+:)(.+)-([^]+)/, '$1' + Enum_WEBKIT + '$2-$3' + '$1' + Enum_MOZ + (Utility_charat(value, length + 3) == 108 ? '$3' : '$2-$3')) + value;
// (s)tretch
case 115:
return ~indexof(value, 'stretch') ? emotion_cache_browser_esm_prefix(Utility_replace(value, 'stretch', 'fill-available'), length) + value : value;
}
break;
// position: sticky
case 4949:
// (s)ticky?
if (Utility_charat(value, length + 1) !== 115) break;
// display: (flex|inline-flex)
case 6444:
switch (Utility_charat(value, Utility_strlen(value) - 3 - (~indexof(value, '!important') && 10))) {
// stic(k)y
case 107:
return Utility_replace(value, ':', ':' + Enum_WEBKIT) + value;
// (inline-)?fl(e)x
case 101:
return Utility_replace(value, /(.+:)([^;!]+)(;|!.+)?/, '$1' + Enum_WEBKIT + (Utility_charat(value, 14) === 45 ? 'inline-' : '') + 'box$3' + '$1' + Enum_WEBKIT + '$2$3' + '$1' + Enum_MS + '$2box$3') + value;
}
break;
// writing-mode
case 5936:
switch (Utility_charat(value, length + 11)) {
// vertical-l(r)
case 114:
return Enum_WEBKIT + value + Enum_MS + Utility_replace(value, /[svh]\w+-[tblr]{2}/, 'tb') + value;
// vertical-r(l)
case 108:
return Enum_WEBKIT + value + Enum_MS + Utility_replace(value, /[svh]\w+-[tblr]{2}/, 'tb-rl') + value;
// horizontal(-)tb
case 45:
return Enum_WEBKIT + value + Enum_MS + Utility_replace(value, /[svh]\w+-[tblr]{2}/, 'lr') + value;
}
return Enum_WEBKIT + value + Enum_MS + value + value;
}
return value;
}
var emotion_cache_browser_esm_prefixer = function prefixer(element, index, children, callback) {
if (element.length > -1) if (!element["return"]) switch (element.type) {
case Enum_DECLARATION:
element["return"] = emotion_cache_browser_esm_prefix(element.value, element.length);
break;
case Enum_KEYFRAMES:
return Serializer_serialize([Tokenizer_copy(element, {
value: Utility_replace(element.value, '@', '@' + Enum_WEBKIT)
})], callback);
case Enum_RULESET:
if (element.length) return Utility_combine(element.props, function (value) {
switch (Utility_match(value, /(::plac\w+|:read-\w+)/)) {
// :read-(only|write)
case ':read-only':
case ':read-write':
return Serializer_serialize([Tokenizer_copy(element, {
props: [Utility_replace(value, /:(read-\w+)/, ':' + Enum_MOZ + '$1')]
})], callback);
// :placeholder
case '::placeholder':
return Serializer_serialize([Tokenizer_copy(element, {
props: [Utility_replace(value, /:(plac\w+)/, ':' + Enum_WEBKIT + 'input-$1')]
}), Tokenizer_copy(element, {
props: [Utility_replace(value, /:(plac\w+)/, ':' + Enum_MOZ + '$1')]
}), Tokenizer_copy(element, {
props: [Utility_replace(value, /:(plac\w+)/, Enum_MS + 'input-$1')]
})], callback);
}
return '';
});
}
};
var defaultStylisPlugins = [emotion_cache_browser_esm_prefixer];
var createCache = function createCache(options) {
var key = options.key;
if (false) {}
if (key === 'css') {
var ssrStyles = document.querySelectorAll("style[data-emotion]:not([data-s])"); // get SSRed styles out of the way of React's hydration
// document.head is a safe place to move them to(though note document.head is not necessarily the last place they will be)
// note this very very intentionally targets all style elements regardless of the key to ensure
// that creating a cache works inside of render of a React component
Array.prototype.forEach.call(ssrStyles, function (node) {
// we want to only move elements which have a space in the data-emotion attribute value
// because that indicates that it is an Emotion 11 server-side rendered style elements
// while we will already ignore Emotion 11 client-side inserted styles because of the :not([data-s]) part in the selector
// Emotion 10 client-side inserted styles did not have data-s (but importantly did not have a space in their data-emotion attributes)
// so checking for the space ensures that loading Emotion 11 after Emotion 10 has inserted some styles
// will not result in the Emotion 10 styles being destroyed
var dataEmotionAttribute = node.getAttribute('data-emotion');
if (dataEmotionAttribute.indexOf(' ') === -1) {
return;
}
document.head.appendChild(node);
node.setAttribute('data-s', '');
});
}
var stylisPlugins = options.stylisPlugins || defaultStylisPlugins;
if (false) {}
var inserted = {};
var container;
var nodesToHydrate = [];
{
container = options.container || document.head;
Array.prototype.forEach.call( // this means we will ignore elements which don't have a space in them which
// means that the style elements we're looking at are only Emotion 11 server-rendered style elements
document.querySelectorAll("style[data-emotion^=\"" + key + " \"]"), function (node) {
var attrib = node.getAttribute("data-emotion").split(' '); // $FlowFixMe
for (var i = 1; i < attrib.length; i++) {
inserted[attrib[i]] = true;
}
nodesToHydrate.push(node);
});
}
var _insert;
var omnipresentPlugins = [compat, removeLabel];
if (false) {}
{
var currentSheet;
var finalizingPlugins = [stringify, false ? 0 : rulesheet(function (rule) {
currentSheet.insert(rule);
})];
var serializer = middleware(omnipresentPlugins.concat(stylisPlugins, finalizingPlugins));
var stylis = function stylis(styles) {
return Serializer_serialize(compile(styles), serializer);
};
_insert = function insert(selector, serialized, sheet, shouldCache) {
currentSheet = sheet;
if (false) {}
stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles);
if (shouldCache) {
cache.inserted[serialized.name] = true;
}
};
}
var cache = {
key: key,
sheet: new StyleSheet({
key: key,
container: container,
nonce: options.nonce,
speedy: options.speedy,
prepend: options.prepend,
insertionPoint: options.insertionPoint
}),
nonce: options.nonce,
inserted: inserted,
registered: {},
insert: _insert
};
cache.sheet.hydrate(nodesToHydrate);
return cache;
};
;// CONCATENATED MODULE: ./node_modules/@emotion/hash/dist/emotion-hash.esm.js
/* eslint-disable */
// Inspired by https://github.com/garycourt/murmurhash-js
// Ported from https://github.com/aappleby/smhasher/blob/61a0530f28277f2e850bfc39600ce61d02b518de/src/MurmurHash2.cpp#L37-L86
function murmur2(str) {
// 'm' and 'r' are mixing constants generated offline.
// They're not really 'magic', they just happen to work well.
// const m = 0x5bd1e995;
// const r = 24;
// Initialize the hash
var h = 0; // Mix 4 bytes at a time into the hash
var k,
i = 0,
len = str.length;
for (; len >= 4; ++i, len -= 4) {
k = str.charCodeAt(i) & 0xff | (str.charCodeAt(++i) & 0xff) << 8 | (str.charCodeAt(++i) & 0xff) << 16 | (str.charCodeAt(++i) & 0xff) << 24;
k =
/* Math.imul(k, m): */
(k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16);
k ^=
/* k >>> r: */
k >>> 24;
h =
/* Math.imul(k, m): */
(k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16) ^
/* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
} // Handle the last few bytes of the input array
switch (len) {
case 3:
h ^= (str.charCodeAt(i + 2) & 0xff) << 16;
case 2:
h ^= (str.charCodeAt(i + 1) & 0xff) << 8;
case 1:
h ^= str.charCodeAt(i) & 0xff;
h =
/* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
} // Do a few final mixes of the hash to ensure the last few
// bytes are well-incorporated.
h ^= h >>> 13;
h =
/* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
return ((h ^ h >>> 15) >>> 0).toString(36);
}
;// CONCATENATED MODULE: ./node_modules/@emotion/unitless/dist/emotion-unitless.esm.js
var unitlessKeys = {
animationIterationCount: 1,
aspectRatio: 1,
borderImageOutset: 1,
borderImageSlice: 1,
borderImageWidth: 1,
boxFlex: 1,
boxFlexGroup: 1,
boxOrdinalGroup: 1,
columnCount: 1,
columns: 1,
flex: 1,
flexGrow: 1,
flexPositive: 1,
flexShrink: 1,
flexNegative: 1,
flexOrder: 1,
gridRow: 1,
gridRowEnd: 1,
gridRowSpan: 1,
gridRowStart: 1,
gridColumn: 1,
gridColumnEnd: 1,
gridColumnSpan: 1,
gridColumnStart: 1,
msGridRow: 1,
msGridRowSpan: 1,
msGridColumn: 1,
msGridColumnSpan: 1,
fontWeight: 1,
lineHeight: 1,
opacity: 1,
order: 1,
orphans: 1,
tabSize: 1,
widows: 1,
zIndex: 1,
zoom: 1,
WebkitLineClamp: 1,
// SVG-related properties
fillOpacity: 1,
floodOpacity: 1,
stopOpacity: 1,
strokeDasharray: 1,
strokeDashoffset: 1,
strokeMiterlimit: 1,
strokeOpacity: 1,
strokeWidth: 1
};
;// CONCATENATED MODULE: ./node_modules/@emotion/memoize/dist/emotion-memoize.esm.js
function memoize(fn) {
var cache = Object.create(null);
return function (arg) {
if (cache[arg] === undefined) cache[arg] = fn(arg);
return cache[arg];
};
}
;// CONCATENATED MODULE: ./node_modules/@emotion/serialize/dist/emotion-serialize.browser.esm.js
var ILLEGAL_ESCAPE_SEQUENCE_ERROR = "You have illegal escape sequence in your template literal, most likely inside content's property value.\nBecause you write your CSS inside a JavaScript string you actually have to do double escaping, so for example \"content: '\\00d7';\" should become \"content: '\\\\00d7';\".\nYou can read more about this here:\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#ES2018_revision_of_illegal_escape_sequences";
var UNDEFINED_AS_OBJECT_KEY_ERROR = "You have passed in falsy value as style object's key (can happen when in example you pass unexported component as computed key).";
var hyphenateRegex = /[A-Z]|^ms/g;
var animationRegex = /_EMO_([^_]+?)_([^]*?)_EMO_/g;
var isCustomProperty = function isCustomProperty(property) {
return property.charCodeAt(1) === 45;
};
var isProcessableValue = function isProcessableValue(value) {
return value != null && typeof value !== 'boolean';
};
var processStyleName = /* #__PURE__ */memoize(function (styleName) {
return isCustomProperty(styleName) ? styleName : styleName.replace(hyphenateRegex, '-$&').toLowerCase();
});
var processStyleValue = function processStyleValue(key, value) {
switch (key) {
case 'animation':
case 'animationName':
{
if (typeof value === 'string') {
return value.replace(animationRegex, function (match, p1, p2) {
cursor = {
name: p1,
styles: p2,
next: cursor
};
return p1;
});
}
}
}
if (unitlessKeys[key] !== 1 && !isCustomProperty(key) && typeof value === 'number' && value !== 0) {
return value + 'px';
}
return value;
};
if (false) { var hyphenatedCache, hyphenPattern, msPattern, oldProcessStyleValue, contentValues, contentValuePattern; }
var noComponentSelectorMessage = (/* unused pure expression or super */ null && ('Component selectors can only be used in conjunction with ' + '@emotion/babel-plugin, the swc Emotion plugin, or another Emotion-aware ' + 'compiler transform.'));
function handleInterpolation(mergedProps, registered, interpolation) {
if (interpolation == null) {
return '';
}
if (interpolation.__emotion_styles !== undefined) {
if (false) {}
return interpolation;
}
switch (typeof interpolation) {
case 'boolean':
{
return '';
}
case 'object':
{
if (interpolation.anim === 1) {
cursor = {
name: interpolation.name,
styles: interpolation.styles,
next: cursor
};
return interpolation.name;
}
if (interpolation.styles !== undefined) {
var next = interpolation.next;
if (next !== undefined) {
// not the most efficient thing ever but this is a pretty rare case
// and there will be very few iterations of this generally
while (next !== undefined) {
cursor = {
name: next.name,
styles: next.styles,
next: cursor
};
next = next.next;
}
}
var styles = interpolation.styles + ";";
if (false) {}
return styles;
}
return createStringFromObject(mergedProps, registered, interpolation);
}
case 'function':
{
if (mergedProps !== undefined) {
var previousCursor = cursor;
var result = interpolation(mergedProps);
cursor = previousCursor;
return handleInterpolation(mergedProps, registered, result);
} else if (false) {}
break;
}
case 'string':
if (false) { var replaced, matched; }
break;
} // finalize string values (regular strings and functions interpolated into css calls)
if (registered == null) {
return interpolation;
}
var cached = registered[interpolation];
return cached !== undefined ? cached : interpolation;
}
function createStringFromObject(mergedProps, registered, obj) {
var string = '';
if (Array.isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
string += handleInterpolation(mergedProps, registered, obj[i]) + ";";
}
} else {
for (var _key in obj) {
var value = obj[_key];
if (typeof value !== 'object') {
if (registered != null && registered[value] !== undefined) {
string += _key + "{" + registered[value] + "}";
} else if (isProcessableValue(value)) {
string += processStyleName(_key) + ":" + processStyleValue(_key, value) + ";";
}
} else {
if (_key === 'NO_COMPONENT_SELECTOR' && "production" !== 'production') {}
if (Array.isArray(value) && typeof value[0] === 'string' && (registered == null || registered[value[0]] === undefined)) {
for (var _i = 0; _i < value.length; _i++) {
if (isProcessableValue(value[_i])) {
string += processStyleName(_key) + ":" + processStyleValue(_key, value[_i]) + ";";
}
}
} else {
var interpolated = handleInterpolation(mergedProps, registered, value);
switch (_key) {
case 'animation':
case 'animationName':
{
string += processStyleName(_key) + ":" + interpolated + ";";
break;
}
default:
{
if (false) {}
string += _key + "{" + interpolated + "}";
}
}
}
}
}
}
return string;
}
var labelPattern = /label:\s*([^\s;\n{]+)\s*(;|$)/g;
var sourceMapPattern;
if (false) {} // this is the cursor for keyframes
// keyframes are stored on the SerializedStyles object as a linked list
var cursor;
var emotion_serialize_browser_esm_serializeStyles = function serializeStyles(args, registered, mergedProps) {
if (args.length === 1 && typeof args[0] === 'object' && args[0] !== null && args[0].styles !== undefined) {
return args[0];
}
var stringMode = true;
var styles = '';
cursor = undefined;
var strings = args[0];
if (strings == null || strings.raw === undefined) {
stringMode = false;
styles += handleInterpolation(mergedProps, registered, strings);
} else {
if (false) {}
styles += strings[0];
} // we start at 1 since we've already handled the first arg
for (var i = 1; i < args.length; i++) {
styles += handleInterpolation(mergedProps, registered, args[i]);
if (stringMode) {
if (false) {}
styles += strings[i];
}
}
var sourceMap;
if (false) {} // using a global regex with .exec is stateful so lastIndex has to be reset each time
labelPattern.lastIndex = 0;
var identifierName = '';
var match; // https://esbench.com/bench/5b809c2cf2949800a0f61fb5
while ((match = labelPattern.exec(styles)) !== null) {
identifierName += '-' + // $FlowFixMe we know it's not null
match[1];
}
var name = murmur2(styles) + identifierName;
if (false) {}
return {
name: name,
styles: styles,
next: cursor
};
};
;// CONCATENATED MODULE: ./node_modules/@emotion/use-insertion-effect-with-fallbacks/dist/emotion-use-insertion-effect-with-fallbacks.browser.esm.js
var syncFallback = function syncFallback(create) {
return create();
};
var useInsertionEffect = external_React_['useInsertion' + 'Effect'] ? external_React_['useInsertion' + 'Effect'] : false;
var emotion_use_insertion_effect_with_fallbacks_browser_esm_useInsertionEffectAlwaysWithSyncFallback = useInsertionEffect || syncFallback;
var emotion_use_insertion_effect_with_fallbacks_browser_esm_useInsertionEffectWithLayoutFallback = useInsertionEffect || external_React_.useLayoutEffect;
;// CONCATENATED MODULE: ./node_modules/@emotion/react/dist/emotion-element-43c6fea0.browser.esm.js
var emotion_element_43c6fea0_browser_esm_isBrowser = "object" !== 'undefined';
var emotion_element_43c6fea0_browser_esm_hasOwn = {}.hasOwnProperty;
var EmotionCacheContext = /* #__PURE__ */external_React_.createContext( // we're doing this to avoid preconstruct's dead code elimination in this one case
// because this module is primarily intended for the browser and node
// but it's also required in react native and similar environments sometimes
// and we could have a special build just for that
// but this is much easier and the native packages
// might use a different theme context in the future anyway
typeof HTMLElement !== 'undefined' ? /* #__PURE__ */createCache({
key: 'css'
}) : null);
if (false) {}
var CacheProvider = EmotionCacheContext.Provider;
var __unsafe_useEmotionCache = function useEmotionCache() {
return (0,external_React_.useContext)(EmotionCacheContext);
};
var emotion_element_43c6fea0_browser_esm_withEmotionCache = function withEmotionCache(func) {
// $FlowFixMe
return /*#__PURE__*/(0,external_React_.forwardRef)(function (props, ref) {
// the cache will never be null in the browser
var cache = (0,external_React_.useContext)(EmotionCacheContext);
return func(props, cache, ref);
});
};
if (!emotion_element_43c6fea0_browser_esm_isBrowser) {
emotion_element_43c6fea0_browser_esm_withEmotionCache = function withEmotionCache(func) {
return function (props) {
var cache = (0,external_React_.useContext)(EmotionCacheContext);
if (cache === null) {
// yes, we're potentially creating this on every render
// it doesn't actually matter though since it's only on the server
// so there will only every be a single render
// that could change in the future because of suspense and etc. but for now,
// this works and i don't want to optimise for a future thing that we aren't sure about
cache = createCache({
key: 'css'
});
return /*#__PURE__*/external_React_.createElement(EmotionCacheContext.Provider, {
value: cache
}, func(props, cache));
} else {
return func(props, cache);
}
};
};
}
var emotion_element_43c6fea0_browser_esm_ThemeContext = /* #__PURE__ */external_React_.createContext({});
if (false) {}
var useTheme = function useTheme() {
return React.useContext(emotion_element_43c6fea0_browser_esm_ThemeContext);
};
var getTheme = function getTheme(outerTheme, theme) {
if (typeof theme === 'function') {
var mergedTheme = theme(outerTheme);
if (false) {}
return mergedTheme;
}
if (false) {}
return _extends({}, outerTheme, theme);
};
var createCacheWithTheme = /* #__PURE__ */(/* unused pure expression or super */ null && (weakMemoize(function (outerTheme) {
return weakMemoize(function (theme) {
return getTheme(outerTheme, theme);
});
})));
var ThemeProvider = function ThemeProvider(props) {
var theme = React.useContext(emotion_element_43c6fea0_browser_esm_ThemeContext);
if (props.theme !== theme) {
theme = createCacheWithTheme(theme)(props.theme);
}
return /*#__PURE__*/React.createElement(emotion_element_43c6fea0_browser_esm_ThemeContext.Provider, {
value: theme
}, props.children);
};
function withTheme(Component) {
var componentName = Component.displayName || Component.name || 'Component';
var render = function render(props, ref) {
var theme = React.useContext(emotion_element_43c6fea0_browser_esm_ThemeContext);
return /*#__PURE__*/React.createElement(Component, _extends({
theme: theme,
ref: ref
}, props));
}; // $FlowFixMe
var WithTheme = /*#__PURE__*/React.forwardRef(render);
WithTheme.displayName = "WithTheme(" + componentName + ")";
return hoistNonReactStatics(WithTheme, Component);
}
var getLastPart = function getLastPart(functionName) {
// The match may be something like 'Object.createEmotionProps' or
// 'Loader.prototype.render'
var parts = functionName.split('.');
return parts[parts.length - 1];
};
var getFunctionNameFromStackTraceLine = function getFunctionNameFromStackTraceLine(line) {
// V8
var match = /^\s+at\s+([A-Za-z0-9$.]+)\s/.exec(line);
if (match) return getLastPart(match[1]); // Safari / Firefox
match = /^([A-Za-z0-9$.]+)@/.exec(line);
if (match) return getLastPart(match[1]);
return undefined;
};
var internalReactFunctionNames = /* #__PURE__ */new Set(['renderWithHooks', 'processChild', 'finishClassComponent', 'renderToString']); // These identifiers come from error stacks, so they have to be valid JS
// identifiers, thus we only need to replace what is a valid character for JS,
// but not for CSS.
var sanitizeIdentifier = function sanitizeIdentifier(identifier) {
return identifier.replace(/\$/g, '-');
};
var getLabelFromStackTrace = function getLabelFromStackTrace(stackTrace) {
if (!stackTrace) return undefined;
var lines = stackTrace.split('\n');
for (var i = 0; i < lines.length; i++) {
var functionName = getFunctionNameFromStackTraceLine(lines[i]); // The first line of V8 stack traces is just "Error"
if (!functionName) continue; // If we reach one of these, we have gone too far and should quit
if (internalReactFunctionNames.has(functionName)) break; // The component name is the first function in the stack that starts with an
// uppercase letter
if (/^[A-Z]/.test(functionName)) return sanitizeIdentifier(functionName);
}
return undefined;
};
var typePropName = '__EMOTION_TYPE_PLEASE_DO_NOT_USE__';
var labelPropName = '__EMOTION_LABEL_PLEASE_DO_NOT_USE__';
var emotion_element_43c6fea0_browser_esm_createEmotionProps = function createEmotionProps(type, props) {
if (false) {}
var newProps = {};
for (var key in props) {
if (emotion_element_43c6fea0_browser_esm_hasOwn.call(props, key)) {
newProps[key] = props[key];
}
}
newProps[typePropName] = type; // For performance, only call getLabelFromStackTrace in development and when
// the label hasn't already been computed
if (false) { var label; }
return newProps;
};
var Insertion = function Insertion(_ref) {
var cache = _ref.cache,
serialized = _ref.serialized,
isStringTag = _ref.isStringTag;
registerStyles(cache, serialized, isStringTag);
useInsertionEffectAlwaysWithSyncFallback(function () {
return insertStyles(cache, serialized, isStringTag);
});
return null;
};
var emotion_element_43c6fea0_browser_esm_Emotion = /* #__PURE__ */(/* unused pure expression or super */ null && (emotion_element_43c6fea0_browser_esm_withEmotionCache(function (props, cache, ref) {
var cssProp = props.css; // so that using `css` from `emotion` and passing the result to the css prop works
// not passing the registered cache to serializeStyles because it would
// make certain babel optimisations not possible
if (typeof cssProp === 'string' && cache.registered[cssProp] !== undefined) {
cssProp = cache.registered[cssProp];
}
var WrappedComponent = props[typePropName];
var registeredStyles = [cssProp];
var className = '';
if (typeof props.className === 'string') {
className = getRegisteredStyles(cache.registered, registeredStyles, props.className);
} else if (props.className != null) {
className = props.className + " ";
}
var serialized = serializeStyles(registeredStyles, undefined, React.useContext(emotion_element_43c6fea0_browser_esm_ThemeContext));
if (false) { var labelFromStack; }
className += cache.key + "-" + serialized.name;
var newProps = {};
for (var key in props) {
if (emotion_element_43c6fea0_browser_esm_hasOwn.call(props, key) && key !== 'css' && key !== typePropName && ( true || 0)) {
newProps[key] = props[key];
}
}
newProps.ref = ref;
newProps.className = className;
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Insertion, {
cache: cache,
serialized: serialized,
isStringTag: typeof WrappedComponent === 'string'
}), /*#__PURE__*/React.createElement(WrappedComponent, newProps));
})));
if (false) {}
var Emotion$1 = (/* unused pure expression or super */ null && (emotion_element_43c6fea0_browser_esm_Emotion));
;// CONCATENATED MODULE: ./node_modules/@emotion/utils/dist/emotion-utils.browser.esm.js
var emotion_utils_browser_esm_isBrowser = "object" !== 'undefined';
function emotion_utils_browser_esm_getRegisteredStyles(registered, registeredStyles, classNames) {
var rawClassName = '';
classNames.split(' ').forEach(function (className) {
if (registered[className] !== undefined) {
registeredStyles.push(registered[className] + ";");
} else {
rawClassName += className + " ";
}
});
return rawClassName;
}
var emotion_utils_browser_esm_registerStyles = function registerStyles(cache, serialized, isStringTag) {
var className = cache.key + "-" + serialized.name;
if ( // we only need to add the styles to the registered cache if the
// class name could be used further down
// the tree but if it's a string tag, we know it won't
// so we don't have to add it to registered cache.
// this improves memory usage since we can avoid storing the whole style string
(isStringTag === false || // we need to always store it if we're in compat mode and
// in node since emotion-server relies on whether a style is in
// the registered cache to know whether a style is global or not
// also, note that this check will be dead code eliminated in the browser
emotion_utils_browser_esm_isBrowser === false ) && cache.registered[className] === undefined) {
cache.registered[className] = serialized.styles;
}
};
var emotion_utils_browser_esm_insertStyles = function insertStyles(cache, serialized, isStringTag) {
emotion_utils_browser_esm_registerStyles(cache, serialized, isStringTag);
var className = cache.key + "-" + serialized.name;
if (cache.inserted[serialized.name] === undefined) {
var current = serialized;
do {
cache.insert(serialized === current ? "." + className : '', current, cache.sheet, true);
current = current.next;
} while (current !== undefined);
}
};
;// CONCATENATED MODULE: ./node_modules/@emotion/css/create-instance/dist/emotion-css-create-instance.esm.js
function insertWithoutScoping(cache, serialized) {
if (cache.inserted[serialized.name] === undefined) {
return cache.insert('', serialized, cache.sheet, true);
}
}
function merge(registered, css, className) {
var registeredStyles = [];
var rawClassName = emotion_utils_browser_esm_getRegisteredStyles(registered, registeredStyles, className);
if (registeredStyles.length < 2) {
return className;
}
return rawClassName + css(registeredStyles);
}
var createEmotion = function createEmotion(options) {
var cache = createCache(options); // $FlowFixMe
cache.sheet.speedy = function (value) {
if (false) {}
this.isSpeedy = value;
};
cache.compat = true;
var css = function css() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var serialized = emotion_serialize_browser_esm_serializeStyles(args, cache.registered, undefined);
emotion_utils_browser_esm_insertStyles(cache, serialized, false);
return cache.key + "-" + serialized.name;
};
var keyframes = function keyframes() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var serialized = emotion_serialize_browser_esm_serializeStyles(args, cache.registered);
var animation = "animation-" + serialized.name;
insertWithoutScoping(cache, {
name: serialized.name,
styles: "@keyframes " + animation + "{" + serialized.styles + "}"
});
return animation;
};
var injectGlobal = function injectGlobal() {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
var serialized = emotion_serialize_browser_esm_serializeStyles(args, cache.registered);
insertWithoutScoping(cache, serialized);
};
var cx = function cx() {
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
return merge(cache.registered, css, emotion_css_create_instance_esm_classnames(args));
};
return {
css: css,
cx: cx,
injectGlobal: injectGlobal,
keyframes: keyframes,
hydrate: function hydrate(ids) {
ids.forEach(function (key) {
cache.inserted[key] = true;
});
},
flush: function flush() {
cache.registered = {};
cache.inserted = {};
cache.sheet.flush();
},
// $FlowFixMe
sheet: cache.sheet,
cache: cache,
getRegisteredStyles: emotion_utils_browser_esm_getRegisteredStyles.bind(null, cache.registered),
merge: merge.bind(null, cache.registered, css)
};
};
var emotion_css_create_instance_esm_classnames = function classnames(args) {
var cls = '';
for (var i = 0; i < args.length; i++) {
var arg = args[i];
if (arg == null) continue;
var toAdd = void 0;
switch (typeof arg) {
case 'boolean':
break;
case 'object':
{
if (Array.isArray(arg)) {
toAdd = classnames(arg);
} else {
toAdd = '';
for (var k in arg) {
if (arg[k] && k) {
toAdd && (toAdd += ' ');
toAdd += k;
}
}
}
break;
}
default:
{
toAdd = arg;
}
}
if (toAdd) {
cls && (cls += ' ');
cls += toAdd;
}
}
return cls;
};
;// CONCATENATED MODULE: ./node_modules/@emotion/css/dist/emotion-css.esm.js
var _createEmotion = createEmotion({
key: 'css'
}),
flush = _createEmotion.flush,
hydrate = _createEmotion.hydrate,
emotion_css_esm_cx = _createEmotion.cx,
emotion_css_esm_merge = _createEmotion.merge,
emotion_css_esm_getRegisteredStyles = _createEmotion.getRegisteredStyles,
injectGlobal = _createEmotion.injectGlobal,
emotion_css_esm_keyframes = _createEmotion.keyframes,
css = _createEmotion.css,
sheet = _createEmotion.sheet,
cache = _createEmotion.cache;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/hooks/use-cx.js
/**
* External dependencies
*/
// eslint-disable-next-line no-restricted-imports
/**
* WordPress dependencies
*/
const isSerializedStyles = o => typeof o !== 'undefined' && o !== null && ['name', 'styles'].every(p => typeof o[p] !== 'undefined');
/**
* Retrieve a `cx` function that knows how to handle `SerializedStyles`
* returned by the `@emotion/react` `css` function in addition to what
* `cx` normally knows how to handle. It also hooks into the Emotion
* Cache, allowing `css` calls to work inside iframes.
*
* @example
* import { css } from '@emotion/react';
*
* const styles = css`
* color: red
* `;
*
* function RedText( { className, ...props } ) {
* const cx = useCx();
*
* const classes = cx(styles, className);
*
* return <span className={classes} {...props} />;
* }
*/
const useCx = () => {
const cache = __unsafe_useEmotionCache();
const cx = (0,external_wp_element_namespaceObject.useCallback)(function () {
if (cache === null) {
throw new Error('The `useCx` hook should be only used within a valid Emotion Cache Context');
}
for (var _len = arguments.length, classNames = new Array(_len), _key = 0; _key < _len; _key++) {
classNames[_key] = arguments[_key];
}
return emotion_css_esm_cx(...classNames.map(arg => {
if (isSerializedStyles(arg)) {
emotion_utils_browser_esm_insertStyles(cache, arg, false);
return `${cache.key}-${arg.name}`;
}
return arg;
}));
}, [cache]);
return cx;
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/context/use-context-system.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* @template TProps
* @typedef {TProps & { className: string }} ConnectedProps
*/
/**
* Custom hook that derives registered props from the Context system.
* These derived props are then consolidated with incoming component props.
*
* @template {{ className?: string }} P
* @param {P} props Incoming props from the component.
* @param {string} namespace The namespace to register and to derive context props from.
* @return {ConnectedProps<P>} The connected props.
*/
function useContextSystem(props, namespace) {
const contextSystemProps = useComponentsContext();
if (typeof namespace === 'undefined') {
typeof process !== "undefined" && process.env && "production" !== "production" ? 0 : void 0;
}
const contextProps = (contextSystemProps === null || contextSystemProps === void 0 ? void 0 : contextSystemProps[namespace]) || {};
/* eslint-disable jsdoc/no-undefined-types */
/** @type {ConnectedProps<P>} */
// @ts-ignore We fill in the missing properties below
const finalComponentProps = { ...getConnectedNamespace(),
...getNamespace(namespace)
};
/* eslint-enable jsdoc/no-undefined-types */
const {
_overrides: overrideProps,
...otherContextProps
} = contextProps;
const initialMergedProps = Object.entries(otherContextProps).length ? Object.assign({}, otherContextProps, props) : props;
const cx = useCx();
const classes = cx(getStyledClassNameFromKey(namespace), props.className); // Provides the ability to customize the render of the component.
const rendered = typeof initialMergedProps.renderChildren === 'function' ? initialMergedProps.renderChildren(initialMergedProps) : initialMergedProps.children;
for (const key in initialMergedProps) {
// @ts-ignore filling in missing props
finalComponentProps[key] = initialMergedProps[key];
}
for (const key in overrideProps) {
// @ts-ignore filling in missing props
finalComponentProps[key] = overrideProps[key];
} // Setting an `undefined` explicitly can cause unintended overwrites
// when a `cloneElement()` is involved.
if (rendered !== undefined) {
// @ts-ignore
finalComponentProps.children = rendered;
}
finalComponentProps.className = classes;
return finalComponentProps;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/context/context-connect.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Forwards ref (React.ForwardRef) and "Connects" (or registers) a component
* within the Context system under a specified namespace.
*
* @param Component The component to register into the Context system.
* @param namespace The namespace to register the component under.
* @return The connected WordPressComponent
*/
function contextConnect(Component, namespace) {
return _contextConnect(Component, namespace, {
forwardsRef: true
});
}
/**
* "Connects" (or registers) a component within the Context system under a specified namespace.
* Does not forward a ref.
*
* @param Component The component to register into the Context system.
* @param namespace The namespace to register the component under.
* @return The connected WordPressComponent
*/
function contextConnectWithoutRef(Component, namespace) {
return _contextConnect(Component, namespace);
} // This is an (experimental) evolution of the initial connect() HOC.
// The hope is that we can improve render performance by removing functional
// component wrappers.
function _contextConnect(Component, namespace, options) {
const WrappedComponent = options !== null && options !== void 0 && options.forwardsRef ? (0,external_wp_element_namespaceObject.forwardRef)(Component) : Component;
if (typeof namespace === 'undefined') {
typeof process !== "undefined" && process.env && "production" !== "production" ? 0 : void 0;
} // @ts-expect-error internal property
let mergedNamespace = WrappedComponent[CONNECT_STATIC_NAMESPACE] || [namespace];
/**
* Consolidate (merge) namespaces before attaching it to the WrappedComponent.
*/
if (Array.isArray(namespace)) {
mergedNamespace = [...mergedNamespace, ...namespace];
}
if (typeof namespace === 'string') {
mergedNamespace = [...mergedNamespace, namespace];
} // @ts-expect-error We can't rely on inferred types here because of the
// `as` prop polymorphism we're handling in https://github.com/WordPress/gutenberg/blob/9620bae6fef4fde7cc2b7833f416e240207cda29/packages/components/src/ui/context/wordpress-component.ts#L32-L33
return Object.assign(WrappedComponent, {
[CONNECT_STATIC_NAMESPACE]: [...new Set(mergedNamespace)],
displayName: namespace,
selector: `.${getStyledClassNameFromKey(namespace)}`
});
}
/**
* Attempts to retrieve the connected namespace from a component.
*
* @param Component The component to retrieve a namespace from.
* @return The connected namespaces.
*/
function getConnectNamespace(Component) {
if (!Component) return [];
let namespaces = []; // @ts-ignore internal property
if (Component[CONNECT_STATIC_NAMESPACE]) {
// @ts-ignore internal property
namespaces = Component[CONNECT_STATIC_NAMESPACE];
} // @ts-ignore
if (Component.type && Component.type[CONNECT_STATIC_NAMESPACE]) {
// @ts-ignore
namespaces = Component.type[CONNECT_STATIC_NAMESPACE];
}
return namespaces;
}
/**
* Checks to see if a component is connected within the Context system.
*
* @param Component The component to retrieve a namespace from.
* @param match The namespace to check.
*/
function hasConnectNamespace(Component, match) {
if (!Component) return false;
if (typeof match === 'string') {
return getConnectNamespace(Component).includes(match);
}
if (Array.isArray(match)) {
return match.some(result => getConnectNamespace(Component).includes(result));
}
return false;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/visually-hidden/styles.js
/**
* External dependencies
*/
const visuallyHidden = {
border: 0,
clip: 'rect(1px, 1px, 1px, 1px)',
WebkitClipPath: 'inset( 50% )',
clipPath: 'inset( 50% )',
height: '1px',
margin: '-1px',
overflow: 'hidden',
padding: 0,
position: 'absolute',
width: '1px',
wordWrap: 'normal'
};
;// CONCATENATED MODULE: ./node_modules/@emotion/is-prop-valid/dist/emotion-is-prop-valid.esm.js
var reactPropsRegex = /^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|abbr|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|disableRemotePlayback|download|draggable|encType|enterKeyHint|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|translate|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|incremental|fallback|inert|itemProp|itemScope|itemType|itemID|itemRef|on|option|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/; // https://esbench.com/bench/5bfee68a4cd7e6009ef61d23
var isPropValid = /* #__PURE__ */memoize(function (prop) {
return reactPropsRegex.test(prop) || prop.charCodeAt(0) === 111
/* o */
&& prop.charCodeAt(1) === 110
/* n */
&& prop.charCodeAt(2) < 91;
}
/* Z+1 */
);
;// CONCATENATED MODULE: ./node_modules/@emotion/styled/base/dist/emotion-styled-base.browser.esm.js
var testOmitPropsOnStringTag = isPropValid;
var testOmitPropsOnComponent = function testOmitPropsOnComponent(key) {
return key !== 'theme';
};
var getDefaultShouldForwardProp = function getDefaultShouldForwardProp(tag) {
return typeof tag === 'string' && // 96 is one less than the char code
// for "a" so this is checking that
// it's a lowercase character
tag.charCodeAt(0) > 96 ? testOmitPropsOnStringTag : testOmitPropsOnComponent;
};
var composeShouldForwardProps = function composeShouldForwardProps(tag, options, isReal) {
var shouldForwardProp;
if (options) {
var optionsShouldForwardProp = options.shouldForwardProp;
shouldForwardProp = tag.__emotion_forwardProp && optionsShouldForwardProp ? function (propName) {
return tag.__emotion_forwardProp(propName) && optionsShouldForwardProp(propName);
} : optionsShouldForwardProp;
}
if (typeof shouldForwardProp !== 'function' && isReal) {
shouldForwardProp = tag.__emotion_forwardProp;
}
return shouldForwardProp;
};
var emotion_styled_base_browser_esm_ILLEGAL_ESCAPE_SEQUENCE_ERROR = "You have illegal escape sequence in your template literal, most likely inside content's property value.\nBecause you write your CSS inside a JavaScript string you actually have to do double escaping, so for example \"content: '\\00d7';\" should become \"content: '\\\\00d7';\".\nYou can read more about this here:\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#ES2018_revision_of_illegal_escape_sequences";
var emotion_styled_base_browser_esm_Insertion = function Insertion(_ref) {
var cache = _ref.cache,
serialized = _ref.serialized,
isStringTag = _ref.isStringTag;
emotion_utils_browser_esm_registerStyles(cache, serialized, isStringTag);
emotion_use_insertion_effect_with_fallbacks_browser_esm_useInsertionEffectAlwaysWithSyncFallback(function () {
return emotion_utils_browser_esm_insertStyles(cache, serialized, isStringTag);
});
return null;
};
var createStyled = function createStyled(tag, options) {
if (false) {}
var isReal = tag.__emotion_real === tag;
var baseTag = isReal && tag.__emotion_base || tag;
var identifierName;
var targetClassName;
if (options !== undefined) {
identifierName = options.label;
targetClassName = options.target;
}
var shouldForwardProp = composeShouldForwardProps(tag, options, isReal);
var defaultShouldForwardProp = shouldForwardProp || getDefaultShouldForwardProp(baseTag);
var shouldUseAs = !defaultShouldForwardProp('as');
return function () {
var args = arguments;
var styles = isReal && tag.__emotion_styles !== undefined ? tag.__emotion_styles.slice(0) : [];
if (identifierName !== undefined) {
styles.push("label:" + identifierName + ";");
}
if (args[0] == null || args[0].raw === undefined) {
styles.push.apply(styles, args);
} else {
if (false) {}
styles.push(args[0][0]);
var len = args.length;
var i = 1;
for (; i < len; i++) {
if (false) {}
styles.push(args[i], args[0][i]);
}
} // $FlowFixMe: we need to cast StatelessFunctionalComponent to our PrivateStyledComponent class
var Styled = emotion_element_43c6fea0_browser_esm_withEmotionCache(function (props, cache, ref) {
var FinalTag = shouldUseAs && props.as || baseTag;
var className = '';
var classInterpolations = [];
var mergedProps = props;
if (props.theme == null) {
mergedProps = {};
for (var key in props) {
mergedProps[key] = props[key];
}
mergedProps.theme = external_React_.useContext(emotion_element_43c6fea0_browser_esm_ThemeContext);
}
if (typeof props.className === 'string') {
className = emotion_utils_browser_esm_getRegisteredStyles(cache.registered, classInterpolations, props.className);
} else if (props.className != null) {
className = props.className + " ";
}
var serialized = emotion_serialize_browser_esm_serializeStyles(styles.concat(classInterpolations), cache.registered, mergedProps);
className += cache.key + "-" + serialized.name;
if (targetClassName !== undefined) {
className += " " + targetClassName;
}
var finalShouldForwardProp = shouldUseAs && shouldForwardProp === undefined ? getDefaultShouldForwardProp(FinalTag) : defaultShouldForwardProp;
var newProps = {};
for (var _key in props) {
if (shouldUseAs && _key === 'as') continue;
if ( // $FlowFixMe
finalShouldForwardProp(_key)) {
newProps[_key] = props[_key];
}
}
newProps.className = className;
newProps.ref = ref;
return /*#__PURE__*/external_React_.createElement(external_React_.Fragment, null, /*#__PURE__*/external_React_.createElement(emotion_styled_base_browser_esm_Insertion, {
cache: cache,
serialized: serialized,
isStringTag: typeof FinalTag === 'string'
}), /*#__PURE__*/external_React_.createElement(FinalTag, newProps));
});
Styled.displayName = identifierName !== undefined ? identifierName : "Styled(" + (typeof baseTag === 'string' ? baseTag : baseTag.displayName || baseTag.name || 'Component') + ")";
Styled.defaultProps = tag.defaultProps;
Styled.__emotion_real = Styled;
Styled.__emotion_base = baseTag;
Styled.__emotion_styles = styles;
Styled.__emotion_forwardProp = shouldForwardProp;
Object.defineProperty(Styled, 'toString', {
value: function value() {
if (targetClassName === undefined && "production" !== 'production') {} // $FlowFixMe: coerce undefined to string
return "." + targetClassName;
}
});
Styled.withComponent = function (nextTag, nextOptions) {
return createStyled(nextTag, extends_extends({}, options, nextOptions, {
shouldForwardProp: composeShouldForwardProps(Styled, nextOptions, true)
})).apply(void 0, styles);
};
return Styled;
};
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/view/component.js
/**
* External dependencies
*/
/**
* `View` is a core component that renders everything in the library.
* It is the principle component in the entire library.
*
* @example
* ```jsx
* import { View } from `@wordpress/components`;
*
* function Example() {
* return (
* <View>
* Code is Poetry
* </View>
* );
* }
* ```
*/
// @ts-expect-error
const View = createStyled("div", true ? {
target: "e19lxcc00"
} : 0)( true ? "" : 0);
View.selector = '.components-view';
View.displayName = 'View';
/* harmony default export */ var component = (View);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/visually-hidden/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedVisuallyHidden(props, forwardedRef) {
const {
style: styleProp,
...contextProps
} = useContextSystem(props, 'VisuallyHidden');
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({
ref: forwardedRef
}, contextProps, {
style: { ...visuallyHidden,
...(styleProp || {})
}
}));
}
/**
* `VisuallyHidden` is a component used to render text intended to be visually
* hidden, but will show for alternate devices, for example a screen reader.
*
* ```jsx
* import { VisuallyHidden } from `@wordpress/components`;
*
* function Example() {
* return (
* <VisuallyHidden>
* <label>Code is Poetry</label>
* </VisuallyHidden>
* );
* }
* ```
*/
const VisuallyHidden = contextConnect(UnconnectedVisuallyHidden, 'VisuallyHidden');
/* harmony default export */ var visually_hidden_component = (VisuallyHidden);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/button/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const disabledEventsOnDisabledButton = ['onMouseDown', 'onClick'];
function useDeprecatedProps(_ref) {
let {
isDefault,
isPrimary,
isSecondary,
isTertiary,
isLink,
variant,
...otherProps
} = _ref;
let computedVariant = variant;
if (isPrimary) {
var _computedVariant;
(_computedVariant = computedVariant) !== null && _computedVariant !== void 0 ? _computedVariant : computedVariant = 'primary';
}
if (isTertiary) {
var _computedVariant2;
(_computedVariant2 = computedVariant) !== null && _computedVariant2 !== void 0 ? _computedVariant2 : computedVariant = 'tertiary';
}
if (isSecondary) {
var _computedVariant3;
(_computedVariant3 = computedVariant) !== null && _computedVariant3 !== void 0 ? _computedVariant3 : computedVariant = 'secondary';
}
if (isDefault) {
var _computedVariant4;
external_wp_deprecated_default()('Button isDefault prop', {
since: '5.4',
alternative: 'variant="secondary"',
version: '6.2'
});
(_computedVariant4 = computedVariant) !== null && _computedVariant4 !== void 0 ? _computedVariant4 : computedVariant = 'secondary';
}
if (isLink) {
var _computedVariant5;
(_computedVariant5 = computedVariant) !== null && _computedVariant5 !== void 0 ? _computedVariant5 : computedVariant = 'link';
}
return { ...otherProps,
variant: computedVariant
};
}
function UnforwardedButton(props, ref) {
var _children$, _children$$props;
const {
isSmall,
isPressed,
isBusy,
isDestructive,
className,
disabled,
icon,
iconPosition = 'left',
iconSize,
showTooltip,
tooltipPosition,
shortcut,
label,
children,
text,
variant,
__experimentalIsFocusable: isFocusable,
describedBy,
...buttonOrAnchorProps
} = useDeprecatedProps(props);
const {
href,
target,
...additionalProps
} = 'href' in buttonOrAnchorProps ? buttonOrAnchorProps : {
href: undefined,
target: undefined,
...buttonOrAnchorProps
};
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(Button, 'components-button__description');
const hasChildren = 'string' === typeof children && !!children || Array.isArray(children) && (children === null || children === void 0 ? void 0 : children[0]) && children[0] !== null && // Tooltip should not considered as a child
(children === null || children === void 0 ? void 0 : (_children$ = children[0]) === null || _children$ === void 0 ? void 0 : (_children$$props = _children$.props) === null || _children$$props === void 0 ? void 0 : _children$$props.className) !== 'components-tooltip';
const classes = classnames_default()('components-button', className, {
'is-secondary': variant === 'secondary',
'is-primary': variant === 'primary',
'is-small': isSmall,
'is-tertiary': variant === 'tertiary',
'is-pressed': isPressed,
'is-busy': isBusy,
'is-link': variant === 'link',
'is-destructive': isDestructive,
'has-text': !!icon && hasChildren,
'has-icon': !!icon
});
const trulyDisabled = disabled && !isFocusable;
const Tag = href !== undefined && !trulyDisabled ? 'a' : 'button';
const buttonProps = Tag === 'button' ? {
type: 'button',
disabled: trulyDisabled,
'aria-pressed': isPressed
} : {};
const anchorProps = Tag === 'a' ? {
href,
target
} : {};
if (disabled && isFocusable) {
// In this case, the button will be disabled, but still focusable and
// perceivable by screen reader users.
buttonProps['aria-disabled'] = true;
anchorProps['aria-disabled'] = true;
for (const disabledEvent of disabledEventsOnDisabledButton) {
additionalProps[disabledEvent] = event => {
if (event) {
event.stopPropagation();
event.preventDefault();
}
};
}
} // Should show the tooltip if...
const shouldShowTooltip = !trulyDisabled && ( // An explicit tooltip is passed or...
showTooltip && label || // There's a shortcut or...
shortcut || // There's a label and...
!!label && // The children are empty and...
!(children !== null && children !== void 0 && children.length) && // The tooltip is not explicitly disabled.
false !== showTooltip);
const descriptionId = describedBy ? instanceId : undefined;
const describedById = additionalProps['aria-describedby'] || descriptionId;
const commonProps = {
className: classes,
'aria-label': additionalProps['aria-label'] || label,
'aria-describedby': describedById,
ref
};
const elementChildren = (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, icon && iconPosition === 'left' && (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: icon,
size: iconSize
}), text && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, text), icon && iconPosition === 'right' && (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: icon,
size: iconSize
}), children);
const element = Tag === 'a' ? (0,external_wp_element_namespaceObject.createElement)("a", extends_extends({}, anchorProps, additionalProps, commonProps), elementChildren) : (0,external_wp_element_namespaceObject.createElement)("button", extends_extends({}, buttonProps, additionalProps, commonProps), elementChildren);
if (!shouldShowTooltip) {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, element, describedBy && (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, null, (0,external_wp_element_namespaceObject.createElement)("span", {
id: descriptionId
}, describedBy)));
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(tooltip, {
text: children !== null && children !== void 0 && children.length && describedBy ? describedBy : label,
shortcut: shortcut,
position: tooltipPosition
}, element), describedBy && (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, null, (0,external_wp_element_namespaceObject.createElement)("span", {
id: descriptionId
}, describedBy)));
}
/**
* Lets users take actions and make choices with a single click or tap.
*
* ```jsx
* import { Button } from '@wordpress/components';
* const Mybutton = () => (
* <Button
* variant="primary"
* onClick={ handleClick }
* >
* Click here
* </Button>
* );
* ```
*/
const Button = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedButton);
/* harmony default export */ var build_module_button = (Button);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/scroll-lock/index.js
/**
* WordPress dependencies
*/
/*
* Setting `overflow: hidden` on html and body elements resets body scroll in iOS.
* Save scroll top so we can restore it after locking scroll.
*
* NOTE: It would be cleaner and possibly safer to find a localized solution such
* as preventing default on certain touchmove events.
*/
let previousScrollTop = 0;
function setLocked(locked) {
const scrollingElement = document.scrollingElement || document.body;
if (locked) {
previousScrollTop = scrollingElement.scrollTop;
}
const methodName = locked ? 'add' : 'remove';
scrollingElement.classList[methodName]('lockscroll'); // Adding the class to the document element seems to be necessary in iOS.
document.documentElement.classList[methodName]('lockscroll');
if (!locked) {
scrollingElement.scrollTop = previousScrollTop;
}
}
let lockCounter = 0;
/**
* ScrollLock is a content-free React component for declaratively preventing
* scroll bleed from modal UI to the page body. This component applies a
* `lockscroll` class to the `document.documentElement` and
* `document.scrollingElement` elements to stop the body from scrolling. When it
* is present, the lock is applied.
*
* ```jsx
* import { ScrollLock, Button } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyScrollLock = () => {
* const [ isScrollLocked, setIsScrollLocked ] = useState( false );
*
* const toggleLock = () => {
* setIsScrollLocked( ( locked ) => ! locked ) );
* };
*
* return (
* <div>
* <Button variant="secondary" onClick={ toggleLock }>
* Toggle scroll lock
* </Button>
* { isScrollLocked && <ScrollLock /> }
* <p>
* Scroll locked:
* <strong>{ isScrollLocked ? 'Yes' : 'No' }</strong>
* </p>
* </div>
* );
* };
* ```
*/
function ScrollLock() {
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (lockCounter === 0) {
setLocked(true);
}
++lockCounter;
return () => {
if (lockCounter === 1) {
setLocked(false);
}
--lockCounter;
};
}, []);
return null;
}
/* harmony default export */ var scroll_lock = (ScrollLock);
;// CONCATENATED MODULE: ./node_modules/proxy-compare/dist/index.modern.js
const index_modern_e=Symbol(),t=Symbol(),r=Symbol();let index_modern_n=(e,t)=>new Proxy(e,t);const index_modern_o=Object.getPrototypeOf,s=new WeakMap,c=e=>e&&(s.has(e)?s.get(e):index_modern_o(e)===Object.prototype||index_modern_o(e)===Array.prototype),l=e=>"object"==typeof e&&null!==e,index_modern_a=new WeakMap,f=e=>e[r]||e,i=(s,l,p)=>{if(!c(s))return s;const y=f(s),u=(e=>Object.isFrozen(e)||Object.values(Object.getOwnPropertyDescriptors(e)).some(e=>!e.writable))(y);let g=p&&p.get(y);return g&&g[1].f===u||(g=((n,o)=>{const s={f:o};let c=!1;const l=(t,r)=>{if(!c){let o=s.a.get(n);o||(o=new Set,s.a.set(n,o)),r&&o.has(index_modern_e)||o.add(t)}},a={get:(e,t)=>t===r?n:(l(t),i(e[t],s.a,s.c)),has:(e,r)=>r===t?(c=!0,s.a.delete(n),!0):(l(r),r in e),getOwnPropertyDescriptor:(e,t)=>(l(t,!0),Object.getOwnPropertyDescriptor(e,t)),ownKeys:t=>(l(index_modern_e),Reflect.ownKeys(t))};return o&&(a.set=a.deleteProperty=()=>!1),[a,s]})(y,u),g[1].p=index_modern_n(u?(e=>{let t=index_modern_a.get(e);if(!t){if(Array.isArray(e))t=Array.from(e);else{const r=Object.getOwnPropertyDescriptors(e);Object.values(r).forEach(e=>{e.configurable=!0}),t=Object.create(index_modern_o(e),r)}index_modern_a.set(e,t)}return t})(y):y,g[0]),p&&p.set(y,g)),g[1].a=l,g[1].c=p,g[1].p},p=(e,t)=>{const r=Reflect.ownKeys(e),n=Reflect.ownKeys(t);return r.length!==n.length||r.some((e,t)=>e!==n[t])},y=(t,r,n,o)=>{if(Object.is(t,r))return!1;if(!l(t)||!l(r))return!0;const s=n.get(f(t));if(!s)return!0;if(o){const e=o.get(t);if(e&&e.n===r)return e.g;o.set(t,{n:r,g:!1})}let c=null;for(const l of s){const s=l===index_modern_e?p(t,r):y(t[l],r[l],n,o);if(!0!==s&&!1!==s||(c=s),c)break}return null===c&&(c=!0),o&&o.set(t,{n:r,g:c}),c},u=e=>!!c(e)&&t in e,g=e=>c(e)&&e[r]||null,b=(e,t=!0)=>{s.set(e,t)},O=(e,t)=>{const r=[],n=new WeakSet,o=(e,s)=>{if(n.has(e))return;l(e)&&n.add(e);const c=l(e)&&t.get(f(e));c?c.forEach(t=>{o(e[t],s?[...s,t]:[t])}):s&&r.push(s)};return o(e),r},w=e=>{index_modern_n=e};
// EXTERNAL MODULE: ./node_modules/use-sync-external-store/shim/index.js
var shim = __webpack_require__(635);
;// CONCATENATED MODULE: ./node_modules/valtio/esm/vanilla.js
const vanilla_isObject = (x) => typeof x === "object" && x !== null;
const refSet = /* @__PURE__ */ new WeakSet();
const VERSION = true ? Symbol("VERSION") : 0;
const LISTENERS = true ? Symbol("LISTENERS") : 0;
const SNAPSHOT = true ? Symbol("SNAPSHOT") : 0;
const buildProxyFunction = (objectIs = Object.is, newProxy = (target, handler) => new Proxy(target, handler), canProxy = (x) => vanilla_isObject(x) && !refSet.has(x) && (Array.isArray(x) || !(Symbol.iterator in x)) && !(x instanceof WeakMap) && !(x instanceof WeakSet) && !(x instanceof Error) && !(x instanceof Number) && !(x instanceof Date) && !(x instanceof String) && !(x instanceof RegExp) && !(x instanceof ArrayBuffer), PROMISE_RESULT = true ? Symbol("PROMISE_RESULT") : 0, PROMISE_ERROR = true ? Symbol("PROMISE_ERROR") : 0, snapshotCache = /* @__PURE__ */ new WeakMap(), createSnapshot = (version, target, receiver) => {
const cache = snapshotCache.get(receiver);
if ((cache == null ? void 0 : cache[0]) === version) {
return cache[1];
}
const snapshot2 = Array.isArray(target) ? [] : Object.create(Object.getPrototypeOf(target));
b(snapshot2, true);
snapshotCache.set(receiver, [version, snapshot2]);
Reflect.ownKeys(target).forEach((key) => {
const value = Reflect.get(target, key, receiver);
if (refSet.has(value)) {
b(value, false);
snapshot2[key] = value;
} else if (value instanceof Promise) {
if (PROMISE_RESULT in value) {
snapshot2[key] = value[PROMISE_RESULT];
} else {
const errorOrPromise = value[PROMISE_ERROR] || value;
Object.defineProperty(snapshot2, key, {
get() {
if (PROMISE_RESULT in value) {
return value[PROMISE_RESULT];
}
throw errorOrPromise;
}
});
}
} else if (value == null ? void 0 : value[LISTENERS]) {
snapshot2[key] = value[SNAPSHOT];
} else {
snapshot2[key] = value;
}
});
return Object.freeze(snapshot2);
}, proxyCache = /* @__PURE__ */ new WeakMap(), versionHolder = [1], proxyFunction2 = (initialObject) => {
if (!vanilla_isObject(initialObject)) {
throw new Error("object required");
}
const found = proxyCache.get(initialObject);
if (found) {
return found;
}
let version = versionHolder[0];
const listeners = /* @__PURE__ */ new Set();
const notifyUpdate = (op, nextVersion = ++versionHolder[0]) => {
if (version !== nextVersion) {
version = nextVersion;
listeners.forEach((listener) => listener(op, nextVersion));
}
};
const propListeners = /* @__PURE__ */ new Map();
const getPropListener = (prop) => {
let propListener = propListeners.get(prop);
if (!propListener) {
propListener = (op, nextVersion) => {
const newOp = [...op];
newOp[1] = [prop, ...newOp[1]];
notifyUpdate(newOp, nextVersion);
};
propListeners.set(prop, propListener);
}
return propListener;
};
const popPropListener = (prop) => {
const propListener = propListeners.get(prop);
propListeners.delete(prop);
return propListener;
};
const baseObject = Array.isArray(initialObject) ? [] : Object.create(Object.getPrototypeOf(initialObject));
const handler = {
get(target, prop, receiver) {
if (prop === VERSION) {
return version;
}
if (prop === LISTENERS) {
return listeners;
}
if (prop === SNAPSHOT) {
return createSnapshot(version, target, receiver);
}
return Reflect.get(target, prop, receiver);
},
deleteProperty(target, prop) {
const prevValue = Reflect.get(target, prop);
const childListeners = prevValue == null ? void 0 : prevValue[LISTENERS];
if (childListeners) {
childListeners.delete(popPropListener(prop));
}
const deleted = Reflect.deleteProperty(target, prop);
if (deleted) {
notifyUpdate(["delete", [prop], prevValue]);
}
return deleted;
},
set(target, prop, value, receiver) {
var _a;
const hasPrevValue = Reflect.has(target, prop);
const prevValue = Reflect.get(target, prop, receiver);
if (hasPrevValue && objectIs(prevValue, value)) {
return true;
}
const childListeners = prevValue == null ? void 0 : prevValue[LISTENERS];
if (childListeners) {
childListeners.delete(popPropListener(prop));
}
if (vanilla_isObject(value)) {
value = g(value) || value;
}
let nextValue;
if ((_a = Object.getOwnPropertyDescriptor(target, prop)) == null ? void 0 : _a.set) {
nextValue = value;
} else if (value instanceof Promise) {
nextValue = value.then((v) => {
nextValue[PROMISE_RESULT] = v;
notifyUpdate(["resolve", [prop], v]);
return v;
}).catch((e) => {
nextValue[PROMISE_ERROR] = e;
notifyUpdate(["reject", [prop], e]);
});
} else if (value == null ? void 0 : value[LISTENERS]) {
nextValue = value;
nextValue[LISTENERS].add(getPropListener(prop));
} else if (canProxy(value)) {
nextValue = vanilla_proxy(value);
nextValue[LISTENERS].add(getPropListener(prop));
} else {
nextValue = value;
}
Reflect.set(target, prop, nextValue, receiver);
notifyUpdate(["set", [prop], value, prevValue]);
return true;
}
};
const proxyObject = newProxy(baseObject, handler);
proxyCache.set(initialObject, proxyObject);
Reflect.ownKeys(initialObject).forEach((key) => {
const desc = Object.getOwnPropertyDescriptor(
initialObject,
key
);
if (desc.get || desc.set) {
Object.defineProperty(baseObject, key, desc);
} else {
proxyObject[key] = initialObject[key];
}
});
return proxyObject;
}) => [
proxyFunction2,
refSet,
VERSION,
LISTENERS,
SNAPSHOT,
objectIs,
newProxy,
canProxy,
PROMISE_RESULT,
PROMISE_ERROR,
snapshotCache,
createSnapshot,
proxyCache,
versionHolder
];
const [proxyFunction] = buildProxyFunction();
function vanilla_proxy(initialObject = {}) {
return proxyFunction(initialObject);
}
function vanilla_getVersion(proxyObject) {
return vanilla_isObject(proxyObject) ? proxyObject[VERSION] : void 0;
}
function vanilla_subscribe(proxyObject, callback, notifyInSync) {
if ( true && !(proxyObject == null ? void 0 : proxyObject[LISTENERS])) {
console.warn("Please use proxy object");
}
let promise;
const ops = [];
const listener = (op) => {
ops.push(op);
if (notifyInSync) {
callback(ops.splice(0));
return;
}
if (!promise) {
promise = Promise.resolve().then(() => {
promise = void 0;
callback(ops.splice(0));
});
}
};
proxyObject[LISTENERS].add(listener);
return () => {
proxyObject[LISTENERS].delete(listener);
};
}
function vanilla_snapshot(proxyObject) {
if ( true && !(proxyObject == null ? void 0 : proxyObject[SNAPSHOT])) {
console.warn("Please use proxy object");
}
return proxyObject[SNAPSHOT];
}
function vanilla_ref(obj) {
refSet.add(obj);
return obj;
}
const unstable_buildProxyFunction = (/* unused pure expression or super */ null && (buildProxyFunction));
;// CONCATENATED MODULE: ./node_modules/valtio/esm/index.js
const { useSyncExternalStore } = shim;
const useAffectedDebugValue = (state, affected) => {
const pathList = (0,external_React_.useRef)();
(0,external_React_.useEffect)(() => {
pathList.current = O(state, affected);
});
(0,external_React_.useDebugValue)(pathList.current);
};
function useSnapshot(proxyObject, options) {
const notifyInSync = options == null ? void 0 : options.sync;
const lastSnapshot = (0,external_React_.useRef)();
const lastAffected = (0,external_React_.useRef)();
let inRender = true;
const currSnapshot = useSyncExternalStore(
(0,external_React_.useCallback)(
(callback) => {
const unsub = vanilla_subscribe(proxyObject, callback, notifyInSync);
callback();
return unsub;
},
[proxyObject, notifyInSync]
),
() => {
const nextSnapshot = vanilla_snapshot(proxyObject);
try {
if (!inRender && lastSnapshot.current && lastAffected.current && !y(
lastSnapshot.current,
nextSnapshot,
lastAffected.current,
/* @__PURE__ */ new WeakMap()
)) {
return lastSnapshot.current;
}
} catch (e) {
}
return nextSnapshot;
},
() => vanilla_snapshot(proxyObject)
);
inRender = false;
const currAffected = /* @__PURE__ */ new WeakMap();
(0,external_React_.useEffect)(() => {
lastSnapshot.current = currSnapshot;
lastAffected.current = currAffected;
});
if (true) {
useAffectedDebugValue(currSnapshot, currAffected);
}
const proxyCache = (0,external_React_.useMemo)(() => /* @__PURE__ */ new WeakMap(), []);
return i(currSnapshot, currAffected, proxyCache);
}
;// CONCATENATED MODULE: ./node_modules/valtio/esm/utils.js
function subscribeKey(proxyObject, key, callback, notifyInSync) {
return subscribe(
proxyObject,
(ops) => {
if (ops.some((op) => op[1][0] === key)) {
callback(proxyObject[key]);
}
},
notifyInSync
);
}
let currentCleanups;
function watch(callback, options) {
let alive = true;
const cleanups = /* @__PURE__ */ new Set();
const subscriptions = /* @__PURE__ */ new Map();
const cleanup = () => {
if (alive) {
alive = false;
cleanups.forEach((clean) => clean());
cleanups.clear();
subscriptions.forEach((unsubscribe) => unsubscribe());
subscriptions.clear();
}
};
const revalidate = () => {
if (!alive) {
return;
}
cleanups.forEach((clean) => clean());
cleanups.clear();
const proxiesToSubscribe = /* @__PURE__ */ new Set();
const parent = currentCleanups;
currentCleanups = cleanups;
try {
const cleanupReturn = callback((proxyObject) => {
proxiesToSubscribe.add(proxyObject);
return proxyObject;
});
if (cleanupReturn) {
cleanups.add(cleanupReturn);
}
} finally {
currentCleanups = parent;
}
subscriptions.forEach((unsubscribe, proxyObject) => {
if (proxiesToSubscribe.has(proxyObject)) {
proxiesToSubscribe.delete(proxyObject);
} else {
subscriptions.delete(proxyObject);
unsubscribe();
}
});
proxiesToSubscribe.forEach((proxyObject) => {
const unsubscribe = subscribe(proxyObject, revalidate, options == null ? void 0 : options.sync);
subscriptions.set(proxyObject, unsubscribe);
});
};
if (currentCleanups) {
currentCleanups.add(cleanup);
}
revalidate();
return cleanup;
}
const DEVTOOLS = Symbol();
function devtools(proxyObject, options) {
if (typeof options === "string") {
console.warn(
"string name option is deprecated, use { name }. https://github.com/pmndrs/valtio/pull/400"
);
options = { name: options };
}
const { enabled, name = "" } = options || {};
let extension;
try {
extension = (enabled != null ? enabled : (/* unsupported import.meta.env */ undefined && 0) !== "production") && window.__REDUX_DEVTOOLS_EXTENSION__;
} catch {
}
if (!extension) {
if ( true && enabled) {
console.warn("[Warning] Please install/enable Redux devtools extension");
}
return;
}
let isTimeTraveling = false;
const devtools2 = extension.connect({ name });
const unsub1 = subscribe(proxyObject, (ops) => {
const action = ops.filter(([_, path]) => path[0] !== DEVTOOLS).map(([op, path]) => `${op}:${path.map(String).join(".")}`).join(", ");
if (!action) {
return;
}
if (isTimeTraveling) {
isTimeTraveling = false;
} else {
const snapWithoutDevtools = Object.assign({}, snapshot(proxyObject));
delete snapWithoutDevtools[DEVTOOLS];
devtools2.send(
{
type: action,
updatedAt: new Date().toLocaleString()
},
snapWithoutDevtools
);
}
});
const unsub2 = devtools2.subscribe((message) => {
var _a, _b, _c, _d, _e, _f;
if (message.type === "ACTION" && message.payload) {
try {
Object.assign(proxyObject, JSON.parse(message.payload));
} catch (e) {
console.error(
"please dispatch a serializable value that JSON.parse() and proxy() support\n",
e
);
}
}
if (message.type === "DISPATCH" && message.state) {
if (((_a = message.payload) == null ? void 0 : _a.type) === "JUMP_TO_ACTION" || ((_b = message.payload) == null ? void 0 : _b.type) === "JUMP_TO_STATE") {
isTimeTraveling = true;
const state = JSON.parse(message.state);
Object.assign(proxyObject, state);
}
proxyObject[DEVTOOLS] = message;
} else if (message.type === "DISPATCH" && ((_c = message.payload) == null ? void 0 : _c.type) === "COMMIT") {
devtools2.init(snapshot(proxyObject));
} else if (message.type === "DISPATCH" && ((_d = message.payload) == null ? void 0 : _d.type) === "IMPORT_STATE") {
const actions = (_e = message.payload.nextLiftedState) == null ? void 0 : _e.actionsById;
const computedStates = ((_f = message.payload.nextLiftedState) == null ? void 0 : _f.computedStates) || [];
isTimeTraveling = true;
computedStates.forEach(({ state }, index) => {
const action = actions[index] || "No action found";
Object.assign(proxyObject, state);
if (index === 0) {
devtools2.init(snapshot(proxyObject));
} else {
devtools2.send(action, snapshot(proxyObject));
}
});
}
});
devtools2.init(snapshot(proxyObject));
return () => {
unsub1();
unsub2 == null ? void 0 : unsub2();
};
}
const sourceObjectMap = /* @__PURE__ */ new WeakMap();
const derivedObjectMap = /* @__PURE__ */ new WeakMap();
const markPending = (sourceObject, callback) => {
const sourceObjectEntry = sourceObjectMap.get(sourceObject);
if (sourceObjectEntry) {
sourceObjectEntry[0].forEach((subscription) => {
const { d: derivedObject } = subscription;
if (sourceObject !== derivedObject) {
markPending(derivedObject);
}
});
++sourceObjectEntry[2];
if (callback) {
sourceObjectEntry[3].add(callback);
}
}
};
const checkPending = (sourceObject, callback) => {
const sourceObjectEntry = sourceObjectMap.get(sourceObject);
if (sourceObjectEntry == null ? void 0 : sourceObjectEntry[2]) {
sourceObjectEntry[3].add(callback);
return true;
}
return false;
};
const unmarkPending = (sourceObject) => {
const sourceObjectEntry = sourceObjectMap.get(sourceObject);
if (sourceObjectEntry) {
--sourceObjectEntry[2];
if (!sourceObjectEntry[2]) {
sourceObjectEntry[3].forEach((callback) => callback());
sourceObjectEntry[3].clear();
}
sourceObjectEntry[0].forEach((subscription) => {
const { d: derivedObject } = subscription;
if (sourceObject !== derivedObject) {
unmarkPending(derivedObject);
}
});
}
};
const addSubscription = (subscription) => {
const { s: sourceObject, d: derivedObject } = subscription;
let derivedObjectEntry = derivedObjectMap.get(derivedObject);
if (!derivedObjectEntry) {
derivedObjectEntry = [/* @__PURE__ */ new Set()];
derivedObjectMap.set(subscription.d, derivedObjectEntry);
}
derivedObjectEntry[0].add(subscription);
let sourceObjectEntry = sourceObjectMap.get(sourceObject);
if (!sourceObjectEntry) {
const subscriptions = /* @__PURE__ */ new Set();
const unsubscribe = vanilla_subscribe(
sourceObject,
(ops) => {
subscriptions.forEach((subscription2) => {
const {
d: derivedObject2,
c: callback,
n: notifyInSync,
i: ignoreKeys
} = subscription2;
if (sourceObject === derivedObject2 && ops.every(
(op) => op[1].length === 1 && ignoreKeys.includes(op[1][0])
)) {
return;
}
if (subscription2.p) {
return;
}
markPending(sourceObject, callback);
if (notifyInSync) {
unmarkPending(sourceObject);
} else {
subscription2.p = Promise.resolve().then(() => {
delete subscription2.p;
unmarkPending(sourceObject);
});
}
});
},
true
);
sourceObjectEntry = [subscriptions, unsubscribe, 0, /* @__PURE__ */ new Set()];
sourceObjectMap.set(sourceObject, sourceObjectEntry);
}
sourceObjectEntry[0].add(subscription);
};
const removeSubscription = (subscription) => {
const { s: sourceObject, d: derivedObject } = subscription;
const derivedObjectEntry = derivedObjectMap.get(derivedObject);
derivedObjectEntry == null ? void 0 : derivedObjectEntry[0].delete(subscription);
if ((derivedObjectEntry == null ? void 0 : derivedObjectEntry[0].size) === 0) {
derivedObjectMap.delete(derivedObject);
}
const sourceObjectEntry = sourceObjectMap.get(sourceObject);
if (sourceObjectEntry) {
const [subscriptions, unsubscribe] = sourceObjectEntry;
subscriptions.delete(subscription);
if (!subscriptions.size) {
unsubscribe();
sourceObjectMap.delete(sourceObject);
}
}
};
const listSubscriptions = (derivedObject) => {
const derivedObjectEntry = derivedObjectMap.get(derivedObject);
if (derivedObjectEntry) {
return Array.from(derivedObjectEntry[0]);
}
return [];
};
const unstable_deriveSubscriptions = {
add: addSubscription,
remove: removeSubscription,
list: listSubscriptions
};
function derive(derivedFns, options) {
const proxyObject = (options == null ? void 0 : options.proxy) || proxy({});
const notifyInSync = !!(options == null ? void 0 : options.sync);
const derivedKeys = Object.keys(derivedFns);
derivedKeys.forEach((key) => {
if (Object.getOwnPropertyDescriptor(proxyObject, key)) {
throw new Error("object property already defined");
}
const fn = derivedFns[key];
let lastDependencies = null;
const evaluate = () => {
if (lastDependencies) {
if (Array.from(lastDependencies).map(([p]) => checkPending(p, evaluate)).some((isPending) => isPending)) {
return;
}
if (Array.from(lastDependencies).every(
([p, entry]) => getVersion(p) === entry.v
)) {
return;
}
}
const dependencies = /* @__PURE__ */ new Map();
const get = (p) => {
dependencies.set(p, { v: getVersion(p) });
return p;
};
const value = fn(get);
const subscribeToDependencies = () => {
dependencies.forEach((entry, p) => {
var _a;
const lastSubscription = (_a = lastDependencies == null ? void 0 : lastDependencies.get(p)) == null ? void 0 : _a.s;
if (lastSubscription) {
entry.s = lastSubscription;
} else {
const subscription = {
s: p,
d: proxyObject,
k: key,
c: evaluate,
n: notifyInSync,
i: derivedKeys
};
addSubscription(subscription);
entry.s = subscription;
}
});
lastDependencies == null ? void 0 : lastDependencies.forEach((entry, p) => {
if (!dependencies.has(p) && entry.s) {
removeSubscription(entry.s);
}
});
lastDependencies = dependencies;
};
if (value instanceof Promise) {
value.finally(subscribeToDependencies);
} else {
subscribeToDependencies();
}
proxyObject[key] = value;
};
evaluate();
});
return proxyObject;
}
function underive(proxyObject, options) {
const keysToDelete = (options == null ? void 0 : options.delete) ? /* @__PURE__ */ new Set() : null;
listSubscriptions(proxyObject).forEach((subscription) => {
const { k: key } = subscription;
if (!(options == null ? void 0 : options.keys) || options.keys.includes(key)) {
removeSubscription(subscription);
if (keysToDelete) {
keysToDelete.add(key);
}
}
});
if (keysToDelete) {
keysToDelete.forEach((key) => {
delete proxyObject[key];
});
}
}
function addComputed_DEPRECATED(proxyObject, computedFns_FAKE, targetObject = proxyObject) {
console.warn(
"addComputed is deprecated. Please consider using `derive` or `proxyWithComputed` instead. Falling back to emulation with derive. https://github.com/pmndrs/valtio/pull/201"
);
const derivedFns = {};
Object.keys(computedFns_FAKE).forEach((key) => {
derivedFns[key] = (get) => computedFns_FAKE[key](get(proxyObject));
});
return derive(derivedFns, { proxy: targetObject });
}
function proxyWithComputed(initialObject, computedFns) {
Object.keys(computedFns).forEach((key) => {
if (Object.getOwnPropertyDescriptor(initialObject, key)) {
throw new Error("object property already defined");
}
const computedFn = computedFns[key];
const { get, set } = typeof computedFn === "function" ? { get: computedFn } : computedFn;
const desc = {};
desc.get = () => get(snapshot(proxyObject));
if (set) {
desc.set = (newValue) => set(proxyObject, newValue);
}
Object.defineProperty(initialObject, key, desc);
});
const proxyObject = proxy(initialObject);
return proxyObject;
}
const utils_isObject = (x) => typeof x === "object" && x !== null;
const deepClone = (obj) => {
if (!utils_isObject(obj)) {
return obj;
}
const baseObject = Array.isArray(obj) ? [] : Object.create(Object.getPrototypeOf(obj));
Reflect.ownKeys(obj).forEach((key) => {
baseObject[key] = deepClone(obj[key]);
});
return baseObject;
};
function proxyWithHistory(initialValue, skipSubscribe = false) {
const proxyObject = proxy({
value: initialValue,
history: ref({
wip: void 0,
snapshots: [],
index: -1
}),
canUndo: () => proxyObject.history.index > 0,
undo: () => {
if (proxyObject.canUndo()) {
proxyObject.value = proxyObject.history.wip = deepClone(
proxyObject.history.snapshots[--proxyObject.history.index]
);
}
},
canRedo: () => proxyObject.history.index < proxyObject.history.snapshots.length - 1,
redo: () => {
if (proxyObject.canRedo()) {
proxyObject.value = proxyObject.history.wip = deepClone(
proxyObject.history.snapshots[++proxyObject.history.index]
);
}
},
saveHistory: () => {
proxyObject.history.snapshots.splice(proxyObject.history.index + 1);
proxyObject.history.snapshots.push(snapshot(proxyObject).value);
++proxyObject.history.index;
},
subscribe: () => subscribe(proxyObject, (ops) => {
if (ops.every(
(op) => op[1][0] === "value" && (op[0] !== "set" || op[2] !== proxyObject.history.wip)
)) {
proxyObject.saveHistory();
}
})
});
proxyObject.saveHistory();
if (!skipSubscribe) {
proxyObject.subscribe();
}
return proxyObject;
}
function proxySet(initialValues) {
const set = proxy({
data: Array.from(new Set(initialValues)),
has(value) {
return this.data.indexOf(value) !== -1;
},
add(value) {
let hasProxy = false;
if (typeof value === "object" && value !== null) {
hasProxy = this.data.indexOf(proxy(value)) !== -1;
}
if (this.data.indexOf(value) === -1 && !hasProxy) {
this.data.push(value);
}
return this;
},
delete(value) {
const index = this.data.indexOf(value);
if (index === -1) {
return false;
}
this.data.splice(index, 1);
return true;
},
clear() {
this.data.splice(0);
},
get size() {
return this.data.length;
},
forEach(cb) {
this.data.forEach((value) => {
cb(value, value, this);
});
},
get [Symbol.toStringTag]() {
return "Set";
},
toJSON() {
return {};
},
[Symbol.iterator]() {
return this.data[Symbol.iterator]();
},
values() {
return this.data.values();
},
keys() {
return this.data.values();
},
entries() {
return new Set(this.data).entries();
}
});
Object.defineProperties(set, {
data: {
enumerable: false
},
size: {
enumerable: false
},
toJSON: {
enumerable: false
}
});
Object.seal(set);
return set;
}
function proxyMap(entries) {
const map = vanilla_proxy({
data: Array.from(entries || []),
has(key) {
return this.data.some((p) => p[0] === key);
},
set(key, value) {
const record = this.data.find((p) => p[0] === key);
if (record) {
record[1] = value;
} else {
this.data.push([key, value]);
}
return this;
},
get(key) {
var _a;
return (_a = this.data.find((p) => p[0] === key)) == null ? void 0 : _a[1];
},
delete(key) {
const index = this.data.findIndex((p) => p[0] === key);
if (index === -1) {
return false;
}
this.data.splice(index, 1);
return true;
},
clear() {
this.data.splice(0);
},
get size() {
return this.data.length;
},
toJSON() {
return {};
},
forEach(cb) {
this.data.forEach((p) => {
cb(p[1], p[0], this);
});
},
keys() {
return this.data.map((p) => p[0]).values();
},
values() {
return this.data.map((p) => p[1]).values();
},
entries() {
return new Map(this.data).entries();
},
get [Symbol.toStringTag]() {
return "Map";
},
[Symbol.iterator]() {
return this.entries();
}
});
Object.defineProperties(map, {
data: {
enumerable: false
},
size: {
enumerable: false
},
toJSON: {
enumerable: false
}
});
Object.seal(map);
return map;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/bubbles-virtually/slot-fill-context.js
// @ts-nocheck
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
const SlotFillContext = (0,external_wp_element_namespaceObject.createContext)({
slots: proxyMap(),
fills: proxyMap(),
registerSlot: () => {
typeof process !== "undefined" && process.env && "production" !== "production" ? 0 : void 0;
},
updateSlot: () => {},
unregisterSlot: () => {},
registerFill: () => {},
unregisterFill: () => {}
});
/* harmony default export */ var slot_fill_context = (SlotFillContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/bubbles-virtually/use-slot.js
// @ts-nocheck
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useSlot(name) {
const {
updateSlot: registryUpdateSlot,
unregisterSlot: registryUnregisterSlot,
registerFill: registryRegisterFill,
unregisterFill: registryUnregisterFill,
...registry
} = (0,external_wp_element_namespaceObject.useContext)(slot_fill_context);
const slots = useSnapshot(registry.slots, {
sync: true
}); // The important bit here is that this call ensures
// the hook only causes a re-render if the slot
// with the given name change, not any other slot.
const slot = slots.get(name);
const updateSlot = (0,external_wp_element_namespaceObject.useCallback)(fillProps => {
registryUpdateSlot(name, fillProps);
}, [name, registryUpdateSlot]);
const unregisterSlot = (0,external_wp_element_namespaceObject.useCallback)(slotRef => {
registryUnregisterSlot(name, slotRef);
}, [name, registryUnregisterSlot]);
const registerFill = (0,external_wp_element_namespaceObject.useCallback)(fillRef => {
registryRegisterFill(name, fillRef);
}, [name, registryRegisterFill]);
const unregisterFill = (0,external_wp_element_namespaceObject.useCallback)(fillRef => {
registryUnregisterFill(name, fillRef);
}, [name, registryUnregisterFill]);
return { ...slot,
updateSlot,
unregisterSlot,
registerFill,
unregisterFill
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/context.js
// @ts-nocheck
/**
* WordPress dependencies
*/
const context_SlotFillContext = (0,external_wp_element_namespaceObject.createContext)({
registerSlot: () => {},
unregisterSlot: () => {},
registerFill: () => {},
unregisterFill: () => {},
getSlot: () => {},
getFills: () => {},
subscribe: () => {}
});
/* harmony default export */ var context = (context_SlotFillContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/use-slot.js
// @ts-nocheck
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* React hook returning the active slot given a name.
*
* @param {string} name Slot name.
* @return {Object} Slot object.
*/
const use_slot_useSlot = name => {
const {
getSlot,
subscribe
} = (0,external_wp_element_namespaceObject.useContext)(context);
return (0,external_wp_element_namespaceObject.useSyncExternalStore)(subscribe, () => getSlot(name), () => getSlot(name));
};
/* harmony default export */ var use_slot = (use_slot_useSlot);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/fill.js
// @ts-nocheck
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function FillComponent(_ref) {
let {
name,
children,
registerFill,
unregisterFill
} = _ref;
const slot = use_slot(name);
const ref = (0,external_wp_element_namespaceObject.useRef)({
name,
children
});
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
const refValue = ref.current;
registerFill(name, refValue);
return () => unregisterFill(name, refValue); // Ignore reason: the useLayoutEffects here are written to fire at specific times, and introducing new dependencies could cause unexpected changes in behavior.
// We'll leave them as-is until a more detailed investigation/refactor can be performed.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
ref.current.children = children;
if (slot) {
slot.forceUpdate();
} // Ignore reason: the useLayoutEffects here are written to fire at specific times, and introducing new dependencies could cause unexpected changes in behavior.
// We'll leave them as-is until a more detailed investigation/refactor can be performed.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [children]);
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
if (name === ref.current.name) {
// Ignore initial effect.
return;
}
unregisterFill(ref.current.name, ref.current);
ref.current.name = name;
registerFill(name, ref.current); // Ignore reason: the useLayoutEffects here are written to fire at specific times, and introducing new dependencies could cause unexpected changes in behavior.
// We'll leave them as-is until a more detailed investigation/refactor can be performed.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [name]);
if (!slot || !slot.node) {
return null;
} // If a function is passed as a child, provide it with the fillProps.
if (typeof children === 'function') {
children = children(slot.props.fillProps);
}
return (0,external_wp_element_namespaceObject.createPortal)(children, slot.node);
}
const Fill = props => (0,external_wp_element_namespaceObject.createElement)(context.Consumer, null, _ref2 => {
let {
registerFill,
unregisterFill
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(FillComponent, extends_extends({}, props, {
registerFill: registerFill,
unregisterFill: unregisterFill
}));
});
/* harmony default export */ var fill = (Fill);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/slot.js
// @ts-nocheck
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Whether the argument is a function.
*
* @param {*} maybeFunc The argument to check.
* @return {boolean} True if the argument is a function, false otherwise.
*/
function isFunction(maybeFunc) {
return typeof maybeFunc === 'function';
}
class SlotComponent extends external_wp_element_namespaceObject.Component {
constructor() {
super(...arguments);
this.isUnmounted = false;
this.bindNode = this.bindNode.bind(this);
}
componentDidMount() {
const {
registerSlot
} = this.props;
this.isUnmounted = false;
registerSlot(this.props.name, this);
}
componentWillUnmount() {
const {
unregisterSlot
} = this.props;
this.isUnmounted = true;
unregisterSlot(this.props.name, this);
}
componentDidUpdate(prevProps) {
const {
name,
unregisterSlot,
registerSlot
} = this.props;
if (prevProps.name !== name) {
unregisterSlot(prevProps.name);
registerSlot(name, this);
}
}
bindNode(node) {
this.node = node;
}
forceUpdate() {
if (this.isUnmounted) {
return;
}
super.forceUpdate();
}
render() {
var _getFills;
const {
children,
name,
fillProps = {},
getFills
} = this.props;
const fills = ((_getFills = getFills(name, this)) !== null && _getFills !== void 0 ? _getFills : []).map(fill => {
const fillChildren = isFunction(fill.children) ? fill.children(fillProps) : fill.children;
return external_wp_element_namespaceObject.Children.map(fillChildren, (child, childIndex) => {
if (!child || typeof child === 'string') {
return child;
}
const childKey = child.key || childIndex;
return (0,external_wp_element_namespaceObject.cloneElement)(child, {
key: childKey
});
});
}).filter( // In some cases fills are rendered only when some conditions apply.
// This ensures that we only use non-empty fills when rendering, i.e.,
// it allows us to render wrappers only when the fills are actually present.
element => !(0,external_wp_element_namespaceObject.isEmptyElement)(element));
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, isFunction(children) ? children(fills) : fills);
}
}
const Slot = props => (0,external_wp_element_namespaceObject.createElement)(context.Consumer, null, _ref => {
let {
registerSlot,
unregisterSlot,
getFills
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(SlotComponent, extends_extends({}, props, {
registerSlot: registerSlot,
unregisterSlot: unregisterSlot,
getFills: getFills
}));
});
/* harmony default export */ var slot = (Slot);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/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);
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);
if (!getRandomValues) {
throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
}
}
return getRandomValues(rnds8);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/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/components/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/components/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 = [];
for (var stringify_i = 0; stringify_i < 256; ++stringify_i) {
byteToHex.push((stringify_i + 0x100).toString(16).substr(1));
}
function stringify_stringify(arr) {
var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 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
// 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)) {
throw TypeError('Stringified UUID is invalid');
}
return uuid;
}
/* harmony default export */ var esm_browser_stringify = (stringify_stringify);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/node_modules/uuid/dist/esm-browser/v4.js
function v4(options, buf, offset) {
options = options || {};
var 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
if (buf) {
offset = offset || 0;
for (var i = 0; i < 16; ++i) {
buf[offset + i] = rnds[i];
}
return buf;
}
return esm_browser_stringify(rnds);
}
/* harmony default export */ var esm_browser_v4 = (v4);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/style-provider/index.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const uuidCache = new Set();
const memoizedCreateCacheWithContainer = memize_default()(container => {
// Emotion only accepts alphabetical and hyphenated keys so we just
// strip the numbers from the UUID. It _should_ be fine.
let key = esm_browser_v4().replace(/[0-9]/g, '');
while (uuidCache.has(key)) {
key = esm_browser_v4().replace(/[0-9]/g, '');
}
uuidCache.add(key);
return createCache({
container,
key
});
});
function StyleProvider(props) {
const {
children,
document
} = props;
if (!document) {
return null;
}
const cache = memoizedCreateCacheWithContainer(document.head);
return (0,external_wp_element_namespaceObject.createElement)(CacheProvider, {
value: cache
}, children);
}
/* harmony default export */ var style_provider = (StyleProvider);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/bubbles-virtually/fill.js
// @ts-nocheck
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useForceUpdate() {
const [, setState] = (0,external_wp_element_namespaceObject.useState)({});
const mounted = (0,external_wp_element_namespaceObject.useRef)(true);
(0,external_wp_element_namespaceObject.useEffect)(() => {
mounted.current = true;
return () => {
mounted.current = false;
};
}, []);
return () => {
if (mounted.current) {
setState({});
}
};
}
function fill_Fill(_ref) {
let {
name,
children
} = _ref;
const {
registerFill,
unregisterFill,
...slot
} = useSlot(name);
const ref = (0,external_wp_element_namespaceObject.useRef)({
rerender: useForceUpdate()
});
(0,external_wp_element_namespaceObject.useEffect)(() => {
// We register fills so we can keep track of their existence.
// Some Slot implementations need to know if there're already fills
// registered so they can choose to render themselves or not.
registerFill(ref);
return () => {
unregisterFill(ref);
};
}, [registerFill, unregisterFill]);
if (!slot.ref || !slot.ref.current) {
return null;
}
if (typeof children === 'function') {
children = children(slot.fillProps);
} // When using a `Fill`, the `children` will be rendered in the document of the
// `Slot`. This means that we need to wrap the `children` in a `StyleProvider`
// to make sure we're referencing the right document/iframe (instead of the
// context of the `Fill`'s parent).
const wrappedChildren = (0,external_wp_element_namespaceObject.createElement)(style_provider, {
document: slot.ref.current.ownerDocument
}, children);
return (0,external_wp_element_namespaceObject.createPortal)(wrappedChildren, slot.ref.current);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/bubbles-virtually/slot.js
// @ts-nocheck
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function slot_Slot(_ref, forwardedRef) {
let {
name,
fillProps = {},
as: Component = 'div',
...props
} = _ref;
const {
registerSlot,
unregisterSlot,
...registry
} = (0,external_wp_element_namespaceObject.useContext)(slot_fill_context);
const ref = (0,external_wp_element_namespaceObject.useRef)();
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
registerSlot(name, ref, fillProps);
return () => {
unregisterSlot(name, ref);
}; // Ignore reason: We don't want to unregister and register the slot whenever
// `fillProps` change, which would cause the fill to be re-mounted. Instead,
// we can just update the slot (see hook below).
// For more context, see https://github.com/WordPress/gutenberg/pull/44403#discussion_r994415973
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [registerSlot, unregisterSlot, name]); // fillProps may be an update that interacts with the layout, so we
// useLayoutEffect.
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
registry.updateSlot(name, fillProps);
});
return (0,external_wp_element_namespaceObject.createElement)(Component, extends_extends({
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([forwardedRef, ref])
}, props));
}
/* harmony default export */ var bubbles_virtually_slot = ((0,external_wp_element_namespaceObject.forwardRef)(slot_Slot));
;// CONCATENATED MODULE: external ["wp","isShallowEqual"]
var external_wp_isShallowEqual_namespaceObject = window["wp"]["isShallowEqual"];
var external_wp_isShallowEqual_default = /*#__PURE__*/__webpack_require__.n(external_wp_isShallowEqual_namespaceObject);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/bubbles-virtually/slot-fill-provider.js
// @ts-nocheck
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useSlotRegistry() {
const slots = (0,external_wp_element_namespaceObject.useRef)(proxyMap());
const fills = (0,external_wp_element_namespaceObject.useRef)(proxyMap());
const registerSlot = (0,external_wp_element_namespaceObject.useCallback)((name, ref, fillProps) => {
const slot = slots.current.get(name) || {};
slots.current.set(name, vanilla_ref({ ...slot,
ref: ref || slot.ref,
fillProps: fillProps || slot.fillProps || {}
}));
}, []);
const unregisterSlot = (0,external_wp_element_namespaceObject.useCallback)((name, ref) => {
var _slots$current$get;
// Make sure we're not unregistering a slot registered by another element
// See https://github.com/WordPress/gutenberg/pull/19242#issuecomment-590295412
if (((_slots$current$get = slots.current.get(name)) === null || _slots$current$get === void 0 ? void 0 : _slots$current$get.ref) === ref) {
slots.current.delete(name);
}
}, []);
const updateSlot = (0,external_wp_element_namespaceObject.useCallback)((name, fillProps) => {
const slot = slots.current.get(name);
if (!slot) {
return;
}
if (!external_wp_isShallowEqual_default()(slot.fillProps, fillProps)) {
slot.fillProps = fillProps;
const slotFills = fills.current.get(name);
if (slotFills) {
// Force update fills.
slotFills.map(fill => fill.current.rerender());
}
}
}, []);
const registerFill = (0,external_wp_element_namespaceObject.useCallback)((name, ref) => {
fills.current.set(name, vanilla_ref([...(fills.current.get(name) || []), ref]));
}, []);
const unregisterFill = (0,external_wp_element_namespaceObject.useCallback)((name, ref) => {
if (fills.current.get(name)) {
fills.current.set(name, vanilla_ref(fills.current.get(name).filter(fillRef => fillRef !== ref)));
}
}, []); // Memoizing the return value so it can be directly passed to Provider value
const registry = (0,external_wp_element_namespaceObject.useMemo)(() => ({
slots: slots.current,
fills: fills.current,
registerSlot,
updateSlot,
unregisterSlot,
registerFill,
unregisterFill
}), [registerSlot, updateSlot, unregisterSlot, registerFill, unregisterFill]);
return registry;
}
function SlotFillProvider(_ref) {
let {
children
} = _ref;
const registry = useSlotRegistry();
return (0,external_wp_element_namespaceObject.createElement)(slot_fill_context.Provider, {
value: registry
}, children);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/provider.js
// @ts-nocheck
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
class provider_SlotFillProvider extends external_wp_element_namespaceObject.Component {
constructor() {
super(...arguments);
this.registerSlot = this.registerSlot.bind(this);
this.registerFill = this.registerFill.bind(this);
this.unregisterSlot = this.unregisterSlot.bind(this);
this.unregisterFill = this.unregisterFill.bind(this);
this.getSlot = this.getSlot.bind(this);
this.getFills = this.getFills.bind(this);
this.hasFills = this.hasFills.bind(this);
this.subscribe = this.subscribe.bind(this);
this.slots = {};
this.fills = {};
this.listeners = [];
this.contextValue = {
registerSlot: this.registerSlot,
unregisterSlot: this.unregisterSlot,
registerFill: this.registerFill,
unregisterFill: this.unregisterFill,
getSlot: this.getSlot,
getFills: this.getFills,
hasFills: this.hasFills,
subscribe: this.subscribe
};
}
registerSlot(name, slot) {
const previousSlot = this.slots[name];
this.slots[name] = slot;
this.triggerListeners(); // Sometimes the fills are registered after the initial render of slot
// But before the registerSlot call, we need to rerender the slot.
this.forceUpdateSlot(name); // If a new instance of a slot is being mounted while another with the
// same name exists, force its update _after_ the new slot has been
// assigned into the instance, such that its own rendering of children
// will be empty (the new Slot will subsume all fills for this name).
if (previousSlot) {
previousSlot.forceUpdate();
}
}
registerFill(name, instance) {
this.fills[name] = [...(this.fills[name] || []), instance];
this.forceUpdateSlot(name);
}
unregisterSlot(name, instance) {
// If a previous instance of a Slot by this name unmounts, do nothing,
// as the slot and its fills should only be removed for the current
// known instance.
if (this.slots[name] !== instance) {
return;
}
delete this.slots[name];
this.triggerListeners();
}
unregisterFill(name, instance) {
var _this$fills$name$filt, _this$fills$name;
this.fills[name] = (_this$fills$name$filt = (_this$fills$name = this.fills[name]) === null || _this$fills$name === void 0 ? void 0 : _this$fills$name.filter(fill => fill !== instance)) !== null && _this$fills$name$filt !== void 0 ? _this$fills$name$filt : [];
this.forceUpdateSlot(name);
}
getSlot(name) {
return this.slots[name];
}
getFills(name, slotInstance) {
// Fills should only be returned for the current instance of the slot
// in which they occupy.
if (this.slots[name] !== slotInstance) {
return [];
}
return this.fills[name];
}
hasFills(name) {
return this.fills[name] && !!this.fills[name].length;
}
forceUpdateSlot(name) {
const slot = this.getSlot(name);
if (slot) {
slot.forceUpdate();
}
}
triggerListeners() {
this.listeners.forEach(listener => listener());
}
subscribe(listener) {
this.listeners.push(listener);
return () => {
this.listeners = this.listeners.filter(l => l !== listener);
};
}
render() {
return (0,external_wp_element_namespaceObject.createElement)(context.Provider, {
value: this.contextValue
}, this.props.children);
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/index.js
// @ts-nocheck
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function slot_fill_Fill(props) {
// We're adding both Fills here so they can register themselves before
// their respective slot has been registered. Only the Fill that has a slot
// will render. The other one will return null.
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(fill, props), (0,external_wp_element_namespaceObject.createElement)(fill_Fill, props));
}
const slot_fill_Slot = (0,external_wp_element_namespaceObject.forwardRef)((_ref, ref) => {
let {
bubblesVirtually,
...props
} = _ref;
if (bubblesVirtually) {
return (0,external_wp_element_namespaceObject.createElement)(bubbles_virtually_slot, extends_extends({}, props, {
ref: ref
}));
}
return (0,external_wp_element_namespaceObject.createElement)(slot, props);
});
function Provider(_ref2) {
let {
children,
...props
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(provider_SlotFillProvider, props, (0,external_wp_element_namespaceObject.createElement)(SlotFillProvider, null, children));
}
function createSlotFill(name) {
const FillComponent = props => (0,external_wp_element_namespaceObject.createElement)(slot_fill_Fill, extends_extends({
name: name
}, props));
FillComponent.displayName = name + 'Fill';
const SlotComponent = props => (0,external_wp_element_namespaceObject.createElement)(slot_fill_Slot, extends_extends({
name: name
}, props));
SlotComponent.displayName = name + 'Slot';
SlotComponent.__unstableName = name;
return {
Fill: FillComponent,
Slot: SlotComponent
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/popover/utils.js
/**
* External dependencies
*/
// eslint-disable-next-line no-restricted-imports
/**
* Internal dependencies
*/
const POSITION_TO_PLACEMENT = {
bottom: 'bottom',
top: 'top',
'middle left': 'left',
'middle right': 'right',
'bottom left': 'bottom-end',
'bottom center': 'bottom',
'bottom right': 'bottom-start',
'top left': 'top-end',
'top center': 'top',
'top right': 'top-start',
'middle left left': 'left',
'middle left right': 'left',
'middle left bottom': 'left-end',
'middle left top': 'left-start',
'middle right left': 'right',
'middle right right': 'right',
'middle right bottom': 'right-end',
'middle right top': 'right-start',
'bottom left left': 'bottom-end',
'bottom left right': 'bottom-end',
'bottom left bottom': 'bottom-end',
'bottom left top': 'bottom-end',
'bottom center left': 'bottom',
'bottom center right': 'bottom',
'bottom center bottom': 'bottom',
'bottom center top': 'bottom',
'bottom right left': 'bottom-start',
'bottom right right': 'bottom-start',
'bottom right bottom': 'bottom-start',
'bottom right top': 'bottom-start',
'top left left': 'top-end',
'top left right': 'top-end',
'top left bottom': 'top-end',
'top left top': 'top-end',
'top center left': 'top',
'top center right': 'top',
'top center bottom': 'top',
'top center top': 'top',
'top right left': 'top-start',
'top right right': 'top-start',
'top right bottom': 'top-start',
'top right top': 'top-start',
// `middle`/`middle center [corner?]` positions are associated to a fallback
// `bottom` placement because there aren't any corresponding placement values.
middle: 'bottom',
'middle center': 'bottom',
'middle center bottom': 'bottom',
'middle center left': 'bottom',
'middle center right': 'bottom',
'middle center top': 'bottom'
};
/**
* Converts the `Popover`'s legacy "position" prop to the new "placement" prop
* (used by `floating-ui`).
*
* @param position The legacy position
* @return The corresponding placement
*/
const positionToPlacement = position => {
var _POSITION_TO_PLACEMEN;
return (_POSITION_TO_PLACEMEN = POSITION_TO_PLACEMENT[position]) !== null && _POSITION_TO_PLACEMEN !== void 0 ? _POSITION_TO_PLACEMEN : 'bottom';
};
/**
* @typedef AnimationOrigin
* @type {Object}
* @property {number} originX A number between 0 and 1 (in CSS logical properties jargon, 0 is "start", 0.5 is "center", and 1 is "end")
* @property {number} originY A number between 0 and 1 (0 is top, 0.5 is center, and 1 is bottom)
*/
const PLACEMENT_TO_ANIMATION_ORIGIN = {
top: {
originX: 0.5,
originY: 1
},
// open from bottom, center
'top-start': {
originX: 0,
originY: 1
},
// open from bottom, left
'top-end': {
originX: 1,
originY: 1
},
// open from bottom, right
right: {
originX: 0,
originY: 0.5
},
// open from middle, left
'right-start': {
originX: 0,
originY: 0
},
// open from top, left
'right-end': {
originX: 0,
originY: 1
},
// open from bottom, left
bottom: {
originX: 0.5,
originY: 0
},
// open from top, center
'bottom-start': {
originX: 0,
originY: 0
},
// open from top, left
'bottom-end': {
originX: 1,
originY: 0
},
// open from top, right
left: {
originX: 1,
originY: 0.5
},
// open from middle, right
'left-start': {
originX: 1,
originY: 0
},
// open from top, right
'left-end': {
originX: 1,
originY: 1
} // open from bottom, right
};
/**
* Given the floating-ui `placement`, compute the framer-motion props for the
* popover's entry animation.
*
* @param placement A placement string from floating ui
* @return The object containing the motion props
*/
const placementToMotionAnimationProps = placement => {
const translateProp = placement.startsWith('top') || placement.startsWith('bottom') ? 'translateY' : 'translateX';
const translateDirection = placement.startsWith('top') || placement.startsWith('left') ? 1 : -1;
return {
style: PLACEMENT_TO_ANIMATION_ORIGIN[placement],
initial: {
opacity: 0,
scale: 0,
[translateProp]: `${2 * translateDirection}em`
},
animate: {
opacity: 1,
scale: 1,
[translateProp]: 0
},
transition: {
duration: 0.1,
ease: [0, 0, 0.2, 1]
}
};
};
/**
* Returns the offset of a document's frame element.
*
* @param document The iframe's owner document.
*
* @return The offset of the document's frame element, or undefined if the
* document has no frame element.
*/
const getFrameOffset = document => {
var _document$defaultView;
const frameElement = document === null || document === void 0 ? void 0 : (_document$defaultView = document.defaultView) === null || _document$defaultView === void 0 ? void 0 : _document$defaultView.frameElement;
if (!frameElement) {
return;
}
const iframeRect = frameElement.getBoundingClientRect();
return {
x: iframeRect.left,
y: iframeRect.top
};
};
const getReferenceOwnerDocument = _ref => {
var _resultingReferenceOw;
let {
anchor,
anchorRef,
anchorRect,
getAnchorRect,
fallbackReferenceElement,
fallbackDocument
} = _ref;
// In floating-ui's terms:
// - "reference" refers to the popover's anchor element.
// - "floating" refers the floating popover's element.
// A floating element can also be positioned relative to a virtual element,
// instead of a real one. A virtual element is represented by an object
// with the `getBoundingClientRect()` function (like real elements).
// See https://floating-ui.com/docs/virtual-elements for more info.
let resultingReferenceOwnerDoc;
if (anchor) {
resultingReferenceOwnerDoc = anchor.ownerDocument;
} else if (anchorRef !== null && anchorRef !== void 0 && anchorRef.top) {
resultingReferenceOwnerDoc = anchorRef === null || anchorRef === void 0 ? void 0 : anchorRef.top.ownerDocument;
} else if (anchorRef !== null && anchorRef !== void 0 && anchorRef.startContainer) {
resultingReferenceOwnerDoc = anchorRef.startContainer.ownerDocument;
} else if (anchorRef !== null && anchorRef !== void 0 && anchorRef.current) {
resultingReferenceOwnerDoc = anchorRef.current.ownerDocument;
} else if (anchorRef) {
// This one should be deprecated.
resultingReferenceOwnerDoc = anchorRef.ownerDocument;
} else if (anchorRect && anchorRect !== null && anchorRect !== void 0 && anchorRect.ownerDocument) {
resultingReferenceOwnerDoc = anchorRect.ownerDocument;
} else if (getAnchorRect) {
var _getAnchorRect;
resultingReferenceOwnerDoc = (_getAnchorRect = getAnchorRect(fallbackReferenceElement)) === null || _getAnchorRect === void 0 ? void 0 : _getAnchorRect.ownerDocument;
}
return (_resultingReferenceOw = resultingReferenceOwnerDoc) !== null && _resultingReferenceOw !== void 0 ? _resultingReferenceOw : fallbackDocument;
};
const getReferenceElement = _ref2 => {
var _referenceElement;
let {
anchor,
anchorRef,
anchorRect,
getAnchorRect,
fallbackReferenceElement
} = _ref2;
let referenceElement = null;
if (anchor) {
referenceElement = anchor;
} else if (anchorRef !== null && anchorRef !== void 0 && anchorRef.top) {
// Create a virtual element for the ref. The expectation is that
// if anchorRef.top is defined, then anchorRef.bottom is defined too.
// Seems to be used by the block toolbar, when multiple blocks are selected
// (top and bottom blocks are used to calculate the resulting rect).
referenceElement = {
getBoundingClientRect() {
const topRect = anchorRef.top.getBoundingClientRect();
const bottomRect = anchorRef.bottom.getBoundingClientRect();
return new window.DOMRect(topRect.x, topRect.y, topRect.width, bottomRect.bottom - topRect.top);
}
};
} else if (anchorRef !== null && anchorRef !== void 0 && anchorRef.current) {
// Standard React ref.
referenceElement = anchorRef.current;
} else if (anchorRef) {
// If `anchorRef` holds directly the element's value (no `current` key)
// This is a weird scenario and should be deprecated.
referenceElement = anchorRef;
} else if (anchorRect) {
// Create a virtual element for the ref.
referenceElement = {
getBoundingClientRect() {
return anchorRect;
}
};
} else if (getAnchorRect) {
// Create a virtual element for the ref.
referenceElement = {
getBoundingClientRect() {
var _rect$x, _rect$y, _rect$width, _rect$height;
const rect = getAnchorRect(fallbackReferenceElement);
return new window.DOMRect((_rect$x = rect.x) !== null && _rect$x !== void 0 ? _rect$x : rect.left, (_rect$y = rect.y) !== null && _rect$y !== void 0 ? _rect$y : rect.top, (_rect$width = rect.width) !== null && _rect$width !== void 0 ? _rect$width : rect.right - rect.left, (_rect$height = rect.height) !== null && _rect$height !== void 0 ? _rect$height : rect.bottom - rect.top);
}
};
} else if (fallbackReferenceElement) {
// If no explicit ref is passed via props, fall back to
// anchoring to the popover's parent node.
referenceElement = fallbackReferenceElement.parentElement;
} // Convert any `undefined` value to `null`.
return (_referenceElement = referenceElement) !== null && _referenceElement !== void 0 ? _referenceElement : null;
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/popover/limit-shift.js
/**
* External dependencies
*/
/**
* Parts of this source were derived and modified from `floating-ui`,
* released under the MIT license.
*
* https://github.com/floating-ui/floating-ui
*
* Copyright (c) 2021 Floating UI contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* Custom limiter function for the `shift` middleware.
* This function is mostly identical default `limitShift` from ``@floating-ui`;
* the only difference is that, when computing the min/max shift limits, it
* also takes into account the iframe offset that is added by the
* custom "frameOffset" middleware.
*
* All unexported types and functions are also from the `@floating-ui` library,
* and have been copied to this file for convenience.
*/
function limit_shift_getSide(placement) {
return placement.split('-')[0];
}
function getMainAxisFromPlacement(placement) {
return ['top', 'bottom'].includes(limit_shift_getSide(placement)) ? 'x' : 'y';
}
function getCrossAxis(axis) {
return axis === 'x' ? 'y' : 'x';
}
const limit_shift_limitShift = function () {
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return {
options,
fn(middlewareArguments) {
var _middlewareData$frame;
const {
x,
y,
placement,
rects,
middlewareData
} = middlewareArguments;
const {
offset = 0,
mainAxis: checkMainAxis = true,
crossAxis: checkCrossAxis = true
} = options;
const coords = {
x,
y
};
const mainAxis = getMainAxisFromPlacement(placement);
const crossAxis = getCrossAxis(mainAxis);
let mainAxisCoord = coords[mainAxis];
let crossAxisCoord = coords[crossAxis];
const rawOffset = typeof offset === 'function' ? offset(middlewareArguments) : offset;
const computedOffset = typeof rawOffset === 'number' ? {
mainAxis: rawOffset,
crossAxis: 0
} : {
mainAxis: 0,
crossAxis: 0,
...rawOffset
}; // At the moment of writing, this is the only difference
// with the `limitShift` function from `@floating-ui`.
// This offset needs to be added to all min/max limits
// in order to make the shift-limiting work as expected.
const additionalFrameOffset = {
x: 0,
y: 0,
...((_middlewareData$frame = middlewareData.frameOffset) === null || _middlewareData$frame === void 0 ? void 0 : _middlewareData$frame.amount)
};
if (checkMainAxis) {
const len = mainAxis === 'y' ? 'height' : 'width';
const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis + additionalFrameOffset[mainAxis];
const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis + additionalFrameOffset[mainAxis];
if (mainAxisCoord < limitMin) {
mainAxisCoord = limitMin;
} else if (mainAxisCoord > limitMax) {
mainAxisCoord = limitMax;
}
}
if (checkCrossAxis) {
var _middlewareData$offse, _middlewareData$offse2, _middlewareData$offse3, _middlewareData$offse4;
const len = mainAxis === 'y' ? 'width' : 'height';
const isOriginSide = ['top', 'left'].includes(limit_shift_getSide(placement));
const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? (_middlewareData$offse = (_middlewareData$offse2 = middlewareData.offset) === null || _middlewareData$offse2 === void 0 ? void 0 : _middlewareData$offse2[crossAxis]) !== null && _middlewareData$offse !== void 0 ? _middlewareData$offse : 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis) + additionalFrameOffset[crossAxis];
const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : (_middlewareData$offse3 = (_middlewareData$offse4 = middlewareData.offset) === null || _middlewareData$offse4 === void 0 ? void 0 : _middlewareData$offse4[crossAxis]) !== null && _middlewareData$offse3 !== void 0 ? _middlewareData$offse3 : 0) - (isOriginSide ? computedOffset.crossAxis : 0) + additionalFrameOffset[crossAxis];
if (crossAxisCoord < limitMin) {
crossAxisCoord = limitMin;
} else if (crossAxisCoord > limitMax) {
crossAxisCoord = limitMax;
}
}
return {
[mainAxis]: mainAxisCoord,
[crossAxis]: crossAxisCoord
};
}
};
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/popover/index.js
/**
* External dependencies
*/
// eslint-disable-next-line no-restricted-imports
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Name of slot in which popover should fill.
*
* @type {string}
*/
const SLOT_NAME = 'Popover'; // An SVG displaying a triangle facing down, filled with a solid
// color and bordered in such a way to create an arrow-like effect.
// Keeping the SVG's viewbox squared simplify the arrow positioning
// calculations.
const ArrowTriangle = () => (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: `0 0 100 100`,
className: "components-popover__triangle",
role: "presentation"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
className: "components-popover__triangle-bg",
d: "M 0 0 L 50 50 L 100 0"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
className: "components-popover__triangle-border",
d: "M 0 0 L 50 50 L 100 0",
vectorEffect: "non-scaling-stroke"
}));
const AnimatedWrapper = (0,external_wp_element_namespaceObject.forwardRef)((_ref, forwardedRef) => {
let {
style: receivedInlineStyles,
placement,
shouldAnimate = false,
...props
} = _ref;
// When animating, animate only once (i.e. when the popover is opened), and
// do not animate on subsequent prop changes (as it conflicts with
// floating-ui's positioning updates).
const [hasAnimatedOnce, setHasAnimatedOnce] = (0,external_wp_element_namespaceObject.useState)(false);
const shouldReduceMotion = useReducedMotion();
const {
style: motionInlineStyles,
...otherMotionProps
} = (0,external_wp_element_namespaceObject.useMemo)(() => placementToMotionAnimationProps(placement), [placement]);
const onAnimationComplete = (0,external_wp_element_namespaceObject.useCallback)(() => setHasAnimatedOnce(true), []);
const computedAnimationProps = shouldAnimate && !shouldReduceMotion ? {
style: { ...motionInlineStyles,
...receivedInlineStyles
},
...otherMotionProps,
onAnimationComplete,
animate: hasAnimatedOnce ? false : otherMotionProps.animate
} : {
animate: false,
style: receivedInlineStyles
};
return (0,external_wp_element_namespaceObject.createElement)(motion.div, extends_extends({}, computedAnimationProps, props, {
ref: forwardedRef
}));
});
const slotNameContext = (0,external_wp_element_namespaceObject.createContext)(undefined);
const UnforwardedPopover = (props, forwardedRef) => {
var _frameOffsetRef$curre, _frameOffsetRef$curre2, _frameOffsetRef$curre3, _frameOffsetRef$curre4;
const {
animate = true,
headerTitle,
onClose,
children,
className,
noArrow = true,
position,
placement: placementProp = 'bottom-start',
offset: offsetProp = 0,
focusOnMount = 'firstElement',
anchor,
expandOnMobile,
onFocusOutside,
__unstableSlotName = SLOT_NAME,
flip = true,
resize = true,
shift = false,
variant,
// Deprecated props
__unstableForcePosition,
anchorRef,
anchorRect,
getAnchorRect,
isAlternate,
// Rest
...contentProps
} = props;
let computedFlipProp = flip;
let computedResizeProp = resize;
if (__unstableForcePosition !== undefined) {
external_wp_deprecated_default()('`__unstableForcePosition` prop in wp.components.Popover', {
since: '6.1',
version: '6.3',
alternative: '`flip={ false }` and `resize={ false }`'
}); // Back-compat, set the `flip` and `resize` props
// to `false` to replicate `__unstableForcePosition`.
computedFlipProp = !__unstableForcePosition;
computedResizeProp = !__unstableForcePosition;
}
if (anchorRef !== undefined) {
external_wp_deprecated_default()('`anchorRef` prop in wp.components.Popover', {
since: '6.1',
alternative: '`anchor` prop'
});
}
if (anchorRect !== undefined) {
external_wp_deprecated_default()('`anchorRect` prop in wp.components.Popover', {
since: '6.1',
alternative: '`anchor` prop'
});
}
if (getAnchorRect !== undefined) {
external_wp_deprecated_default()('`getAnchorRect` prop in wp.components.Popover', {
since: '6.1',
alternative: '`anchor` prop'
});
}
const computedVariant = isAlternate ? 'toolbar' : variant;
if (isAlternate !== undefined) {
external_wp_deprecated_default()('`isAlternate` prop in wp.components.Popover', {
since: '6.2',
alternative: "`variant` prop with the `'toolbar'` value"
});
}
const arrowRef = (0,external_wp_element_namespaceObject.useRef)(null);
const [fallbackReferenceElement, setFallbackReferenceElement] = (0,external_wp_element_namespaceObject.useState)(null);
const [referenceOwnerDocument, setReferenceOwnerDocument] = (0,external_wp_element_namespaceObject.useState)();
const anchorRefFallback = (0,external_wp_element_namespaceObject.useCallback)(node => {
setFallbackReferenceElement(node);
}, []);
const isMobileViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('medium', '<');
const isExpanded = expandOnMobile && isMobileViewport;
const hasArrow = !isExpanded && !noArrow;
const normalizedPlacementFromProps = position ? positionToPlacement(position) : placementProp;
/**
* Offsets the position of the popover when the anchor is inside an iframe.
*
* Store the offset in a ref, due to constraints with floating-ui:
* https://floating-ui.com/docs/react-dom#variables-inside-middleware-functions.
*/
const frameOffsetRef = (0,external_wp_element_namespaceObject.useRef)(getFrameOffset(referenceOwnerDocument));
const middleware = [// Custom middleware which adjusts the popover's position by taking into
// account the offset of the anchor's iframe (if any) compared to the page.
{
name: 'frameOffset',
fn(_ref2) {
let {
x,
y
} = _ref2;
if (!frameOffsetRef.current) {
return {
x,
y
};
}
return {
x: x + frameOffsetRef.current.x,
y: y + frameOffsetRef.current.y,
data: {
// This will be used in the customLimitShift() function.
amount: frameOffsetRef.current
}
};
}
}, floating_ui_dom_offset(offsetProp), computedFlipProp ? floating_ui_dom_flip() : undefined, computedResizeProp ? floating_ui_dom_size({
apply(sizeProps) {
var _refs$floating$curren;
const {
firstElementChild
} = (_refs$floating$curren = refs.floating.current) !== null && _refs$floating$curren !== void 0 ? _refs$floating$curren : {}; // Only HTMLElement instances have the `style` property.
if (!(firstElementChild instanceof HTMLElement)) return; // Reduce the height of the popover to the available space.
Object.assign(firstElementChild.style, {
maxHeight: `${sizeProps.availableHeight}px`,
overflow: 'auto'
});
}
}) : undefined, shift ? floating_ui_dom_shift({
crossAxis: true,
limiter: limit_shift_limitShift(),
padding: 1 // Necessary to avoid flickering at the edge of the viewport.
}) : undefined, floating_ui_react_dom_esm_arrow({
element: arrowRef
})].filter(m => m !== undefined);
const slotName = (0,external_wp_element_namespaceObject.useContext)(slotNameContext) || __unstableSlotName;
const slot = useSlot(slotName);
let onDialogClose;
if (onClose || onFocusOutside) {
onDialogClose = (type, event) => {
// Ideally the popover should have just a single onClose prop and
// not three props that potentially do the same thing.
if (type === 'focus-outside' && onFocusOutside) {
onFocusOutside(event);
} else if (onClose) {
onClose();
}
};
}
const [dialogRef, dialogProps] = (0,external_wp_compose_namespaceObject.__experimentalUseDialog)({
focusOnMount,
__unstableOnClose: onDialogClose,
// @ts-expect-error The __unstableOnClose property needs to be deprecated first (see https://github.com/WordPress/gutenberg/pull/27675)
onClose: onDialogClose
});
const {
// Positioning coordinates
x,
y,
// Callback refs (not regular refs). This allows the position to be updated.
// when either elements change.
reference: referenceCallbackRef,
floating,
// Object with "regular" refs to both "reference" and "floating"
refs,
// Type of CSS position property to use (absolute or fixed)
strategy,
update,
placement: computedPlacement,
middlewareData: {
arrow: arrowData
}
} = useFloating({
placement: normalizedPlacementFromProps,
middleware,
whileElementsMounted: (referenceParam, floatingParam, updateParam) => autoUpdate(referenceParam, floatingParam, updateParam, {
animationFrame: true
})
});
const arrowCallbackRef = (0,external_wp_element_namespaceObject.useCallback)(node => {
arrowRef.current = node;
update();
}, [update]); // When any of the possible anchor "sources" change,
// recompute the reference element (real or virtual) and its owner document.
const anchorRefTop = anchorRef === null || anchorRef === void 0 ? void 0 : anchorRef.top;
const anchorRefBottom = anchorRef === null || anchorRef === void 0 ? void 0 : anchorRef.bottom;
const anchorRefStartContainer = anchorRef === null || anchorRef === void 0 ? void 0 : anchorRef.startContainer;
const anchorRefCurrent = anchorRef === null || anchorRef === void 0 ? void 0 : anchorRef.current;
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
const resultingReferenceOwnerDoc = getReferenceOwnerDocument({
anchor,
anchorRef,
anchorRect,
getAnchorRect,
fallbackReferenceElement,
fallbackDocument: document
});
const resultingReferenceElement = getReferenceElement({
anchor,
anchorRef,
anchorRect,
getAnchorRect,
fallbackReferenceElement
});
referenceCallbackRef(resultingReferenceElement);
setReferenceOwnerDocument(resultingReferenceOwnerDoc);
}, [anchor, anchorRef, anchorRefTop, anchorRefBottom, anchorRefStartContainer, anchorRefCurrent, anchorRect, getAnchorRect, fallbackReferenceElement, referenceCallbackRef]); // If the reference element is in a different ownerDocument (e.g. iFrame),
// we need to manually update the floating's position as the reference's owner
// document scrolls. Also update the frame offset if the view resizes.
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
var _refs$floating$curren2, _referenceOwnerDocume;
if ( // Reference and root documents are the same.
referenceOwnerDocument === document || // Reference and floating are in the same document.
referenceOwnerDocument === ((_refs$floating$curren2 = refs.floating.current) === null || _refs$floating$curren2 === void 0 ? void 0 : _refs$floating$curren2.ownerDocument) || // The reference's document has no view (i.e. window)
// or frame element (ie. it's not an iframe).
!(referenceOwnerDocument !== null && referenceOwnerDocument !== void 0 && (_referenceOwnerDocume = referenceOwnerDocument.defaultView) !== null && _referenceOwnerDocume !== void 0 && _referenceOwnerDocume.frameElement)) {
frameOffsetRef.current = undefined;
return;
}
const {
defaultView
} = referenceOwnerDocument;
const updateFrameOffset = () => {
frameOffsetRef.current = getFrameOffset(referenceOwnerDocument);
update();
};
defaultView.addEventListener('resize', updateFrameOffset);
updateFrameOffset();
return () => {
defaultView.removeEventListener('resize', updateFrameOffset);
};
}, [referenceOwnerDocument, update, refs.floating]);
const mergedFloatingRef = (0,external_wp_compose_namespaceObject.useMergeRefs)([floating, dialogRef, forwardedRef]); // Disable reason: We care to capture the _bubbled_ events from inputs
// within popover as inferring close intent.
let content = // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions
// eslint-disable-next-line jsx-a11y/no-static-element-interactions
(0,external_wp_element_namespaceObject.createElement)(AnimatedWrapper, extends_extends({
shouldAnimate: animate && !isExpanded,
placement: computedPlacement,
className: classnames_default()('components-popover', className, {
'is-expanded': isExpanded,
'is-positioned': x !== null && y !== null,
// Use the 'alternate' classname for 'toolbar' variant for back compat.
[`is-${computedVariant === 'toolbar' ? 'alternate' : computedVariant}`]: computedVariant
})
}, contentProps, {
ref: mergedFloatingRef
}, dialogProps, {
tabIndex: -1,
style: isExpanded ? undefined : {
position: strategy,
top: 0,
left: 0,
// `x` and `y` are framer-motion specific props and are shorthands
// for `translateX` and `translateY`. Currently it is not possible
// to use `translateX` and `translateY` because those values would
// be overridden by the return value of the
// `placementToMotionAnimationProps` function in `AnimatedWrapper`
x: Math.round(x !== null && x !== void 0 ? x : 0) || undefined,
y: Math.round(y !== null && y !== void 0 ? y : 0) || undefined
}
}), isExpanded && (0,external_wp_element_namespaceObject.createElement)(scroll_lock, null), isExpanded && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-popover__header"
}, (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-popover__header-title"
}, headerTitle), (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-popover__close",
icon: library_close,
onClick: onClose
})), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-popover__content"
}, children), hasArrow && (0,external_wp_element_namespaceObject.createElement)("div", {
ref: arrowCallbackRef,
className: ['components-popover__arrow', `is-${computedPlacement.split('-')[0]}`].join(' '),
style: {
left: typeof (arrowData === null || arrowData === void 0 ? void 0 : arrowData.x) !== 'undefined' && Number.isFinite(arrowData.x) ? `${arrowData.x + ((_frameOffsetRef$curre = (_frameOffsetRef$curre2 = frameOffsetRef.current) === null || _frameOffsetRef$curre2 === void 0 ? void 0 : _frameOffsetRef$curre2.x) !== null && _frameOffsetRef$curre !== void 0 ? _frameOffsetRef$curre : 0)}px` : '',
top: typeof (arrowData === null || arrowData === void 0 ? void 0 : arrowData.y) !== 'undefined' && Number.isFinite(arrowData.y) ? `${arrowData.y + ((_frameOffsetRef$curre3 = (_frameOffsetRef$curre4 = frameOffsetRef.current) === null || _frameOffsetRef$curre4 === void 0 ? void 0 : _frameOffsetRef$curre4.y) !== null && _frameOffsetRef$curre3 !== void 0 ? _frameOffsetRef$curre3 : 0)}px` : ''
}
}, (0,external_wp_element_namespaceObject.createElement)(ArrowTriangle, null)));
if (slot.ref) {
content = (0,external_wp_element_namespaceObject.createElement)(slot_fill_Fill, {
name: slotName
}, content);
}
if (anchorRef || anchorRect || anchor) {
return content;
}
return (0,external_wp_element_namespaceObject.createElement)("span", {
ref: anchorRefFallback
}, content);
};
/**
* `Popover` renders its content in a floating modal. If no explicit anchor is passed via props, it anchors to its parent element by default.
*
* ```jsx
* import { Button, Popover } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyPopover = () => {
* const [ isVisible, setIsVisible ] = useState( false );
* const toggleVisible = () => {
* setIsVisible( ( state ) => ! state );
* };
*
* return (
* <Button variant="secondary" onClick={ toggleVisible }>
* Toggle Popover!
* { isVisible && <Popover>Popover is toggled!</Popover> }
* </Button>
* );
* };
* ```
*
*/
const Popover = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedPopover);
function PopoverSlot(_ref3, ref) {
let {
name = SLOT_NAME
} = _ref3;
return (0,external_wp_element_namespaceObject.createElement)(slot_fill_Slot // @ts-expect-error Need to type `SlotFill`
, {
bubblesVirtually: true,
name: name,
className: "popover-slot",
ref: ref
});
} // @ts-expect-error For Legacy Reasons
Popover.Slot = (0,external_wp_element_namespaceObject.forwardRef)(PopoverSlot); // @ts-expect-error For Legacy Reasons
Popover.__unstableSlotNameProvider = slotNameContext.Provider;
/* harmony default export */ var popover = (Popover);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/shortcut/index.js
/**
* Internal dependencies
*/
function Shortcut(props) {
const {
shortcut,
className
} = props;
if (!shortcut) {
return null;
}
let displayText;
let ariaLabel;
if (typeof shortcut === 'string') {
displayText = shortcut;
}
if (shortcut !== null && typeof shortcut === 'object') {
displayText = shortcut.display;
ariaLabel = shortcut.ariaLabel;
}
return (0,external_wp_element_namespaceObject.createElement)("span", {
className: className,
"aria-label": ariaLabel
}, displayText);
}
/* harmony default export */ var build_module_shortcut = (Shortcut);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tooltip/index.js
// @ts-nocheck
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Time over children to wait before showing tooltip
*
* @type {number}
*/
const TOOLTIP_DELAY = 700;
const eventCatcher = (0,external_wp_element_namespaceObject.createElement)("div", {
className: "event-catcher"
});
const getDisabledElement = _ref => {
let {
eventHandlers,
child,
childrenWithPopover,
mergedRefs
} = _ref;
return (0,external_wp_element_namespaceObject.cloneElement)((0,external_wp_element_namespaceObject.createElement)("span", {
className: "disabled-element-wrapper"
}, (0,external_wp_element_namespaceObject.cloneElement)(eventCatcher, eventHandlers), (0,external_wp_element_namespaceObject.cloneElement)(child, {
children: childrenWithPopover,
ref: mergedRefs
})), { ...eventHandlers
});
};
const getRegularElement = _ref2 => {
let {
child,
eventHandlers,
childrenWithPopover,
mergedRefs
} = _ref2;
return (0,external_wp_element_namespaceObject.cloneElement)(child, { ...eventHandlers,
children: childrenWithPopover,
ref: mergedRefs
});
};
const addPopoverToGrandchildren = _ref3 => {
let {
anchor,
grandchildren,
isOver,
offset,
position,
shortcut,
text,
className,
...props
} = _ref3;
return (0,external_wp_element_namespaceObject.concatChildren)(grandchildren, isOver && (0,external_wp_element_namespaceObject.createElement)(popover, extends_extends({
focusOnMount: false,
position: position,
className: classnames_default()('components-tooltip', className),
"aria-hidden": "true",
animate: false,
offset: offset,
anchor: anchor,
shift: true
}, props), text, (0,external_wp_element_namespaceObject.createElement)(build_module_shortcut, {
className: "components-tooltip__shortcut",
shortcut: shortcut
})));
};
const emitToChild = (children, eventName, event) => {
if (external_wp_element_namespaceObject.Children.count(children) !== 1) {
return;
}
const child = external_wp_element_namespaceObject.Children.only(children); // If the underlying element is disabled, do not emit the event.
if (child.props.disabled) {
return;
}
if (typeof child.props[eventName] === 'function') {
child.props[eventName](event);
}
};
function Tooltip(props) {
var _Children$toArray$;
const {
children,
position = 'bottom middle',
text,
shortcut,
delay = TOOLTIP_DELAY,
...popoverProps
} = props;
/**
* Whether a mouse is currently pressed, used in determining whether
* to handle a focus event as displaying the tooltip immediately.
*
* @type {boolean}
*/
const [isMouseDown, setIsMouseDown] = (0,external_wp_element_namespaceObject.useState)(false);
const [isOver, setIsOver] = (0,external_wp_element_namespaceObject.useState)(false);
const delayedSetIsOver = (0,external_wp_compose_namespaceObject.useDebounce)(setIsOver, delay); // Using internal state (instead of a ref) for the popover anchor to make sure
// that the component re-renders when the anchor updates.
const [popoverAnchor, setPopoverAnchor] = (0,external_wp_element_namespaceObject.useState)(null); // Create a reference to the Tooltip's child, to be passed to the Popover
// so that the Tooltip can be correctly positioned. Also, merge with the
// existing ref for the first child, so that its ref is preserved.
const existingChildRef = (_Children$toArray$ = external_wp_element_namespaceObject.Children.toArray(children)[0]) === null || _Children$toArray$ === void 0 ? void 0 : _Children$toArray$.ref;
const mergedChildRefs = (0,external_wp_compose_namespaceObject.useMergeRefs)([setPopoverAnchor, existingChildRef]);
const createMouseDown = event => {
// In firefox, the mouse down event is also fired when the select
// list is chosen.
// Cancel further processing because re-rendering of child components
// causes onChange to be triggered with the old value.
// See https://github.com/WordPress/gutenberg/pull/42483
if (event.target.tagName === 'OPTION') {
return;
} // Preserve original child callback behavior.
emitToChild(children, 'onMouseDown', event); // On mouse down, the next `mouseup` should revert the value of the
// instance property and remove its own event handler. The bind is
// made on the document since the `mouseup` might not occur within
// the bounds of the element.
document.addEventListener('mouseup', cancelIsMouseDown);
setIsMouseDown(true);
};
const createMouseUp = event => {
// In firefox, the mouse up event is also fired when the select
// list is chosen.
// Cancel further processing because re-rendering of child components
// causes onChange to be triggered with the old value.
// See https://github.com/WordPress/gutenberg/pull/42483
if (event.target.tagName === 'OPTION') {
return;
}
emitToChild(children, 'onMouseUp', event);
document.removeEventListener('mouseup', cancelIsMouseDown);
setIsMouseDown(false);
};
const createMouseEvent = type => {
if (type === 'mouseUp') return createMouseUp;
if (type === 'mouseDown') return createMouseDown;
};
/**
* Prebound `isInMouseDown` handler, created as a constant reference to
* assure ability to remove in component unmount.
*
* @type {Function}
*/
const cancelIsMouseDown = createMouseEvent('mouseUp');
const createToggleIsOver = (eventName, isDelayed) => {
return event => {
// Preserve original child callback behavior.
emitToChild(children, eventName, event); // Mouse events behave unreliably in React for disabled elements,
// firing on mouseenter but not mouseleave. Further, the default
// behavior for disabled elements in some browsers is to ignore
// mouse events. Don't bother trying to handle them.
//
// See: https://github.com/facebook/react/issues/4251
if (event.currentTarget.disabled) {
return;
} // A focus event will occur as a result of a mouse click, but it
// should be disambiguated between interacting with the button and
// using an explicit focus shift as a cue to display the tooltip.
if ('focus' === event.type && isMouseDown) {
return;
} // Needed in case unsetting is over while delayed set pending, i.e.
// quickly blur/mouseleave before delayedSetIsOver is called.
delayedSetIsOver.cancel();
const _isOver = ['focus', 'mouseenter'].includes(event.type);
if (_isOver === isOver) {
return;
}
if (isDelayed) {
delayedSetIsOver(_isOver);
} else {
setIsOver(_isOver);
}
};
};
const clearOnUnmount = () => {
delayedSetIsOver.cancel();
document.removeEventListener('mouseup', cancelIsMouseDown);
}; // Ignore reason: updating the deps array here could cause unexpected changes in behavior.
// Deferring until a more detailed investigation/refactor can be performed.
// eslint-disable-next-line react-hooks/exhaustive-deps
(0,external_wp_element_namespaceObject.useEffect)(() => clearOnUnmount, []);
if (external_wp_element_namespaceObject.Children.count(children) !== 1) {
if (false) {}
return children;
}
const eventHandlers = {
onMouseEnter: createToggleIsOver('onMouseEnter', true),
onMouseLeave: createToggleIsOver('onMouseLeave'),
onClick: createToggleIsOver('onClick'),
onFocus: createToggleIsOver('onFocus'),
onBlur: createToggleIsOver('onBlur'),
onMouseDown: createMouseEvent('mouseDown')
};
const child = external_wp_element_namespaceObject.Children.only(children);
const {
children: grandchildren,
disabled
} = child.props;
const getElementWithPopover = disabled ? getDisabledElement : getRegularElement;
const popoverData = {
anchor: popoverAnchor,
isOver,
offset: 4,
position,
shortcut,
text
};
const childrenWithPopover = addPopoverToGrandchildren({
grandchildren,
...popoverData,
...popoverProps
});
return getElementWithPopover({
child,
eventHandlers,
childrenWithPopover,
mergedRefs: mergedChildRefs
});
}
/* harmony default export */ var tooltip = (Tooltip);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/alignment-matrix-control/utils.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const GRID = [['top left', 'top center', 'top right'], ['center left', 'center center', 'center right'], ['bottom left', 'bottom center', 'bottom right']]; // Stored as map as i18n __() only accepts strings (not variables)
const ALIGNMENT_LABEL = {
'top left': (0,external_wp_i18n_namespaceObject.__)('Top Left'),
'top center': (0,external_wp_i18n_namespaceObject.__)('Top Center'),
'top right': (0,external_wp_i18n_namespaceObject.__)('Top Right'),
'center left': (0,external_wp_i18n_namespaceObject.__)('Center Left'),
'center center': (0,external_wp_i18n_namespaceObject.__)('Center'),
center: (0,external_wp_i18n_namespaceObject.__)('Center'),
'center right': (0,external_wp_i18n_namespaceObject.__)('Center Right'),
'bottom left': (0,external_wp_i18n_namespaceObject.__)('Bottom Left'),
'bottom center': (0,external_wp_i18n_namespaceObject.__)('Bottom Center'),
'bottom right': (0,external_wp_i18n_namespaceObject.__)('Bottom Right')
}; // Transforms GRID into a flat Array of values.
const ALIGNMENTS = GRID.flat();
/**
* Parses and transforms an incoming value to better match the alignment values
*
* @param value An alignment value to parse.
*
* @return The parsed value.
*/
function transformValue(value) {
const nextValue = value === 'center' ? 'center center' : value;
return nextValue.replace('-', ' ');
}
/**
* Creates an item ID based on a prefix ID and an alignment value.
*
* @param prefixId An ID to prefix.
* @param value An alignment value.
*
* @return The item id.
*/
function getItemId(prefixId, value) {
const valueId = transformValue(value).replace(' ', '-');
return `${prefixId}-${valueId}`;
}
/**
* Retrieves the alignment index from a value.
*
* @param alignment Value to check.
*
* @return The index of a matching alignment.
*/
function getAlignmentIndex() {
let alignment = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'center';
const item = transformValue(alignment);
const index = ALIGNMENTS.indexOf(item);
return index > -1 ? index : undefined;
}
// EXTERNAL MODULE: ./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js
var hoist_non_react_statics_cjs = __webpack_require__(1281);
;// CONCATENATED MODULE: ./node_modules/@emotion/react/dist/emotion-react.browser.esm.js
var pkg = {
name: "@emotion/react",
version: "11.11.4",
main: "dist/emotion-react.cjs.js",
module: "dist/emotion-react.esm.js",
browser: {
"./dist/emotion-react.esm.js": "./dist/emotion-react.browser.esm.js"
},
exports: {
".": {
module: {
worker: "./dist/emotion-react.worker.esm.js",
browser: "./dist/emotion-react.browser.esm.js",
"default": "./dist/emotion-react.esm.js"
},
"import": "./dist/emotion-react.cjs.mjs",
"default": "./dist/emotion-react.cjs.js"
},
"./jsx-runtime": {
module: {
worker: "./jsx-runtime/dist/emotion-react-jsx-runtime.worker.esm.js",
browser: "./jsx-runtime/dist/emotion-react-jsx-runtime.browser.esm.js",
"default": "./jsx-runtime/dist/emotion-react-jsx-runtime.esm.js"
},
"import": "./jsx-runtime/dist/emotion-react-jsx-runtime.cjs.mjs",
"default": "./jsx-runtime/dist/emotion-react-jsx-runtime.cjs.js"
},
"./_isolated-hnrs": {
module: {
worker: "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.worker.esm.js",
browser: "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.browser.esm.js",
"default": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.esm.js"
},
"import": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.cjs.mjs",
"default": "./_isolated-hnrs/dist/emotion-react-_isolated-hnrs.cjs.js"
},
"./jsx-dev-runtime": {
module: {
worker: "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.worker.esm.js",
browser: "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.browser.esm.js",
"default": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.esm.js"
},
"import": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.cjs.mjs",
"default": "./jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.cjs.js"
},
"./package.json": "./package.json",
"./types/css-prop": "./types/css-prop.d.ts",
"./macro": {
types: {
"import": "./macro.d.mts",
"default": "./macro.d.ts"
},
"default": "./macro.js"
}
},
types: "types/index.d.ts",
files: [
"src",
"dist",
"jsx-runtime",
"jsx-dev-runtime",
"_isolated-hnrs",
"types/*.d.ts",
"macro.*"
],
sideEffects: false,
author: "Emotion Contributors",
license: "MIT",
scripts: {
"test:typescript": "dtslint types"
},
dependencies: {
"@babel/runtime": "^7.18.3",
"@emotion/babel-plugin": "^11.11.0",
"@emotion/cache": "^11.11.0",
"@emotion/serialize": "^1.1.3",
"@emotion/use-insertion-effect-with-fallbacks": "^1.0.1",
"@emotion/utils": "^1.2.1",
"@emotion/weak-memoize": "^0.3.1",
"hoist-non-react-statics": "^3.3.1"
},
peerDependencies: {
react: ">=16.8.0"
},
peerDependenciesMeta: {
"@types/react": {
optional: true
}
},
devDependencies: {
"@definitelytyped/dtslint": "0.0.112",
"@emotion/css": "11.11.2",
"@emotion/css-prettifier": "1.1.3",
"@emotion/server": "11.11.0",
"@emotion/styled": "11.11.0",
"html-tag-names": "^1.1.2",
react: "16.14.0",
"svg-tag-names": "^1.1.1",
typescript: "^4.5.5"
},
repository: "https://github.com/emotion-js/emotion/tree/main/packages/react",
publishConfig: {
access: "public"
},
"umd:main": "dist/emotion-react.umd.min.js",
preconstruct: {
entrypoints: [
"./index.js",
"./jsx-runtime.js",
"./jsx-dev-runtime.js",
"./_isolated-hnrs.js"
],
umdName: "emotionReact",
exports: {
envConditions: [
"browser",
"worker"
],
extra: {
"./types/css-prop": "./types/css-prop.d.ts",
"./macro": {
types: {
"import": "./macro.d.mts",
"default": "./macro.d.ts"
},
"default": "./macro.js"
}
}
}
}
};
var jsx = function jsx(type, props) {
var args = arguments;
if (props == null || !hasOwn.call(props, 'css')) {
// $FlowFixMe
return React.createElement.apply(undefined, args);
}
var argsLength = args.length;
var createElementArgArray = new Array(argsLength);
createElementArgArray[0] = Emotion;
createElementArgArray[1] = createEmotionProps(type, props);
for (var i = 2; i < argsLength; i++) {
createElementArgArray[i] = args[i];
} // $FlowFixMe
return React.createElement.apply(null, createElementArgArray);
};
var warnedAboutCssPropForGlobal = false; // maintain place over rerenders.
// initial render from browser, insertBefore context.sheet.tags[0] or if a style hasn't been inserted there yet, appendChild
// initial client-side render from SSR, use place of hydrating tag
var Global = /* #__PURE__ */(/* unused pure expression or super */ null && (withEmotionCache(function (props, cache) {
if (false) {}
var styles = props.styles;
var serialized = serializeStyles([styles], undefined, React.useContext(ThemeContext));
if (!isBrowser$1) {
var _ref;
var serializedNames = serialized.name;
var serializedStyles = serialized.styles;
var next = serialized.next;
while (next !== undefined) {
serializedNames += ' ' + next.name;
serializedStyles += next.styles;
next = next.next;
}
var shouldCache = cache.compat === true;
var rules = cache.insert("", {
name: serializedNames,
styles: serializedStyles
}, cache.sheet, shouldCache);
if (shouldCache) {
return null;
}
return /*#__PURE__*/React.createElement("style", (_ref = {}, _ref["data-emotion"] = cache.key + "-global " + serializedNames, _ref.dangerouslySetInnerHTML = {
__html: rules
}, _ref.nonce = cache.sheet.nonce, _ref));
} // yes, i know these hooks are used conditionally
// but it is based on a constant that will never change at runtime
// it's effectively like having two implementations and switching them out
// so it's not actually breaking anything
var sheetRef = React.useRef();
useInsertionEffectWithLayoutFallback(function () {
var key = cache.key + "-global"; // use case of https://github.com/emotion-js/emotion/issues/2675
var sheet = new cache.sheet.constructor({
key: key,
nonce: cache.sheet.nonce,
container: cache.sheet.container,
speedy: cache.sheet.isSpeedy
});
var rehydrating = false; // $FlowFixMe
var node = document.querySelector("style[data-emotion=\"" + key + " " + serialized.name + "\"]");
if (cache.sheet.tags.length) {
sheet.before = cache.sheet.tags[0];
}
if (node !== null) {
rehydrating = true; // clear the hash so this node won't be recognizable as rehydratable by other <Global/>s
node.setAttribute('data-emotion', key);
sheet.hydrate([node]);
}
sheetRef.current = [sheet, rehydrating];
return function () {
sheet.flush();
};
}, [cache]);
useInsertionEffectWithLayoutFallback(function () {
var sheetRefCurrent = sheetRef.current;
var sheet = sheetRefCurrent[0],
rehydrating = sheetRefCurrent[1];
if (rehydrating) {
sheetRefCurrent[1] = false;
return;
}
if (serialized.next !== undefined) {
// insert keyframes
insertStyles(cache, serialized.next, true);
}
if (sheet.tags.length) {
// if this doesn't exist then it will be null so the style element will be appended
var element = sheet.tags[sheet.tags.length - 1].nextElementSibling;
sheet.before = element;
sheet.flush();
}
cache.insert("", serialized, sheet, false);
}, [cache, serialized.name]);
return null;
})));
if (false) {}
function emotion_react_browser_esm_css() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return emotion_serialize_browser_esm_serializeStyles(args);
}
var emotion_react_browser_esm_keyframes = function keyframes() {
var insertable = emotion_react_browser_esm_css.apply(void 0, arguments);
var name = "animation-" + insertable.name; // $FlowFixMe
return {
name: name,
styles: "@keyframes " + name + "{" + insertable.styles + "}",
anim: 1,
toString: function toString() {
return "_EMO_" + this.name + "_" + this.styles + "_EMO_";
}
};
};
var emotion_react_browser_esm_classnames = function classnames(args) {
var len = args.length;
var i = 0;
var cls = '';
for (; i < len; i++) {
var arg = args[i];
if (arg == null) continue;
var toAdd = void 0;
switch (typeof arg) {
case 'boolean':
break;
case 'object':
{
if (Array.isArray(arg)) {
toAdd = classnames(arg);
} else {
if (false) {}
toAdd = '';
for (var k in arg) {
if (arg[k] && k) {
toAdd && (toAdd += ' ');
toAdd += k;
}
}
}
break;
}
default:
{
toAdd = arg;
}
}
if (toAdd) {
cls && (cls += ' ');
cls += toAdd;
}
}
return cls;
};
function emotion_react_browser_esm_merge(registered, css, className) {
var registeredStyles = [];
var rawClassName = getRegisteredStyles(registered, registeredStyles, className);
if (registeredStyles.length < 2) {
return className;
}
return rawClassName + css(registeredStyles);
}
var emotion_react_browser_esm_Insertion = function Insertion(_ref) {
var cache = _ref.cache,
serializedArr = _ref.serializedArr;
useInsertionEffectAlwaysWithSyncFallback(function () {
for (var i = 0; i < serializedArr.length; i++) {
insertStyles(cache, serializedArr[i], false);
}
});
return null;
};
var ClassNames = /* #__PURE__ */(/* unused pure expression or super */ null && (withEmotionCache(function (props, cache) {
var hasRendered = false;
var serializedArr = [];
var css = function css() {
if (hasRendered && "production" !== 'production') {}
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var serialized = serializeStyles(args, cache.registered);
serializedArr.push(serialized); // registration has to happen here as the result of this might get consumed by `cx`
registerStyles(cache, serialized, false);
return cache.key + "-" + serialized.name;
};
var cx = function cx() {
if (hasRendered && "production" !== 'production') {}
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return emotion_react_browser_esm_merge(cache.registered, css, emotion_react_browser_esm_classnames(args));
};
var content = {
css: css,
cx: cx,
theme: React.useContext(ThemeContext)
};
var ele = props.children(content);
hasRendered = true;
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(emotion_react_browser_esm_Insertion, {
cache: cache,
serializedArr: serializedArr
}), ele);
})));
if (false) {}
if (false) { var globalKey, globalContext, isTestEnv, emotion_react_browser_esm_isBrowser; }
;// CONCATENATED MODULE: ./node_modules/colord/index.mjs
var colord_r={grad:.9,turn:360,rad:360/(2*Math.PI)},colord_t=function(r){return"string"==typeof r?r.length>0:"number"==typeof r},colord_n=function(r,t,n){return void 0===t&&(t=0),void 0===n&&(n=Math.pow(10,t)),Math.round(n*r)/n+0},colord_e=function(r,t,n){return void 0===t&&(t=0),void 0===n&&(n=1),r>n?n:r>t?r:t},colord_u=function(r){return(r=isFinite(r)?r%360:0)>0?r:r+360},colord_a=function(r){return{r:colord_e(r.r,0,255),g:colord_e(r.g,0,255),b:colord_e(r.b,0,255),a:colord_e(r.a)}},colord_o=function(r){return{r:colord_n(r.r),g:colord_n(r.g),b:colord_n(r.b),a:colord_n(r.a,3)}},colord_i=/^#([0-9a-f]{3,8})$/i,colord_s=function(r){var t=r.toString(16);return t.length<2?"0"+t:t},h=function(r){var t=r.r,n=r.g,e=r.b,u=r.a,a=Math.max(t,n,e),o=a-Math.min(t,n,e),i=o?a===t?(n-e)/o:a===n?2+(e-t)/o:4+(t-n)/o:0;return{h:60*(i<0?i+6:i),s:a?o/a*100:0,v:a/255*100,a:u}},colord_b=function(r){var t=r.h,n=r.s,e=r.v,u=r.a;t=t/360*6,n/=100,e/=100;var a=Math.floor(t),o=e*(1-n),i=e*(1-(t-a)*n),s=e*(1-(1-t+a)*n),h=a%6;return{r:255*[e,i,o,o,s,e][h],g:255*[s,e,e,i,o,o][h],b:255*[o,o,s,e,e,i][h],a:u}},colord_g=function(r){return{h:colord_u(r.h),s:colord_e(r.s,0,100),l:colord_e(r.l,0,100),a:colord_e(r.a)}},d=function(r){return{h:colord_n(r.h),s:colord_n(r.s),l:colord_n(r.l),a:colord_n(r.a,3)}},colord_f=function(r){return colord_b((n=(t=r).s,{h:t.h,s:(n*=((e=t.l)<50?e:100-e)/100)>0?2*n/(e+n)*100:0,v:e+n,a:t.a}));var t,n,e},colord_c=function(r){return{h:(t=h(r)).h,s:(u=(200-(n=t.s))*(e=t.v)/100)>0&&u<200?n*e/100/(u<=100?u:200-u)*100:0,l:u/2,a:t.a};var t,n,e,u},colord_l=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,colord_p=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,v=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,m=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,colord_y={string:[[function(r){var t=colord_i.exec(r);return t?(r=t[1]).length<=4?{r:parseInt(r[0]+r[0],16),g:parseInt(r[1]+r[1],16),b:parseInt(r[2]+r[2],16),a:4===r.length?colord_n(parseInt(r[3]+r[3],16)/255,2):1}:6===r.length||8===r.length?{r:parseInt(r.substr(0,2),16),g:parseInt(r.substr(2,2),16),b:parseInt(r.substr(4,2),16),a:8===r.length?colord_n(parseInt(r.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(r){var t=v.exec(r)||m.exec(r);return t?t[2]!==t[4]||t[4]!==t[6]?null:colord_a({r:Number(t[1])/(t[2]?100/255:1),g:Number(t[3])/(t[4]?100/255:1),b:Number(t[5])/(t[6]?100/255:1),a:void 0===t[7]?1:Number(t[7])/(t[8]?100:1)}):null},"rgb"],[function(t){var n=colord_l.exec(t)||colord_p.exec(t);if(!n)return null;var e,u,a=colord_g({h:(e=n[1],u=n[2],void 0===u&&(u="deg"),Number(e)*(colord_r[u]||1)),s:Number(n[3]),l:Number(n[4]),a:void 0===n[5]?1:Number(n[5])/(n[6]?100:1)});return colord_f(a)},"hsl"]],object:[[function(r){var n=r.r,e=r.g,u=r.b,o=r.a,i=void 0===o?1:o;return colord_t(n)&&colord_t(e)&&colord_t(u)?colord_a({r:Number(n),g:Number(e),b:Number(u),a:Number(i)}):null},"rgb"],[function(r){var n=r.h,e=r.s,u=r.l,a=r.a,o=void 0===a?1:a;if(!colord_t(n)||!colord_t(e)||!colord_t(u))return null;var i=colord_g({h:Number(n),s:Number(e),l:Number(u),a:Number(o)});return colord_f(i)},"hsl"],[function(r){var n=r.h,a=r.s,o=r.v,i=r.a,s=void 0===i?1:i;if(!colord_t(n)||!colord_t(a)||!colord_t(o))return null;var h=function(r){return{h:colord_u(r.h),s:colord_e(r.s,0,100),v:colord_e(r.v,0,100),a:colord_e(r.a)}}({h:Number(n),s:Number(a),v:Number(o),a:Number(s)});return colord_b(h)},"hsv"]]},N=function(r,t){for(var n=0;n<t.length;n++){var e=t[n][0](r);if(e)return[e,t[n][1]]}return[null,void 0]},x=function(r){return"string"==typeof r?N(r.trim(),colord_y.string):"object"==typeof r&&null!==r?N(r,colord_y.object):[null,void 0]},I=function(r){return x(r)[1]},M=function(r,t){var n=colord_c(r);return{h:n.h,s:colord_e(n.s+100*t,0,100),l:n.l,a:n.a}},H=function(r){return(299*r.r+587*r.g+114*r.b)/1e3/255},$=function(r,t){var n=colord_c(r);return{h:n.h,s:n.s,l:colord_e(n.l+100*t,0,100),a:n.a}},j=function(){function r(r){this.parsed=x(r)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return r.prototype.isValid=function(){return null!==this.parsed},r.prototype.brightness=function(){return colord_n(H(this.rgba),2)},r.prototype.isDark=function(){return H(this.rgba)<.5},r.prototype.isLight=function(){return H(this.rgba)>=.5},r.prototype.toHex=function(){return r=colord_o(this.rgba),t=r.r,e=r.g,u=r.b,i=(a=r.a)<1?colord_s(colord_n(255*a)):"","#"+colord_s(t)+colord_s(e)+colord_s(u)+i;var r,t,e,u,a,i},r.prototype.toRgb=function(){return colord_o(this.rgba)},r.prototype.toRgbString=function(){return r=colord_o(this.rgba),t=r.r,n=r.g,e=r.b,(u=r.a)<1?"rgba("+t+", "+n+", "+e+", "+u+")":"rgb("+t+", "+n+", "+e+")";var r,t,n,e,u},r.prototype.toHsl=function(){return d(colord_c(this.rgba))},r.prototype.toHslString=function(){return r=d(colord_c(this.rgba)),t=r.h,n=r.s,e=r.l,(u=r.a)<1?"hsla("+t+", "+n+"%, "+e+"%, "+u+")":"hsl("+t+", "+n+"%, "+e+"%)";var r,t,n,e,u},r.prototype.toHsv=function(){return r=h(this.rgba),{h:colord_n(r.h),s:colord_n(r.s),v:colord_n(r.v),a:colord_n(r.a,3)};var r},r.prototype.invert=function(){return colord_w({r:255-(r=this.rgba).r,g:255-r.g,b:255-r.b,a:r.a});var r},r.prototype.saturate=function(r){return void 0===r&&(r=.1),colord_w(M(this.rgba,r))},r.prototype.desaturate=function(r){return void 0===r&&(r=.1),colord_w(M(this.rgba,-r))},r.prototype.grayscale=function(){return colord_w(M(this.rgba,-1))},r.prototype.lighten=function(r){return void 0===r&&(r=.1),colord_w($(this.rgba,r))},r.prototype.darken=function(r){return void 0===r&&(r=.1),colord_w($(this.rgba,-r))},r.prototype.rotate=function(r){return void 0===r&&(r=15),this.hue(this.hue()+r)},r.prototype.alpha=function(r){return"number"==typeof r?colord_w({r:(t=this.rgba).r,g:t.g,b:t.b,a:r}):colord_n(this.rgba.a,3);var t},r.prototype.hue=function(r){var t=colord_c(this.rgba);return"number"==typeof r?colord_w({h:r,s:t.s,l:t.l,a:t.a}):colord_n(t.h)},r.prototype.isEqual=function(r){return this.toHex()===colord_w(r).toHex()},r}(),colord_w=function(r){return r instanceof j?r:new j(r)},S=[],k=function(r){r.forEach(function(r){S.indexOf(r)<0&&(r(j,colord_y),S.push(r))})},E=function(){return new j({r:255*Math.random(),g:255*Math.random(),b:255*Math.random()})};
;// CONCATENATED MODULE: ./node_modules/colord/plugins/names.mjs
/* harmony default export */ function names(e,f){var a={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},r={};for(var d in a)r[a[d]]=d;var l={};e.prototype.toName=function(f){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var d,i,n=r[this.toHex()];if(n)return n;if(null==f?void 0:f.closest){var o=this.toRgb(),t=1/0,b="black";if(!l.length)for(var c in a)l[c]=new e(a[c]).toRgb();for(var g in a){var u=(d=o,i=l[g],Math.pow(d.r-i.r,2)+Math.pow(d.g-i.g,2)+Math.pow(d.b-i.b,2));u<t&&(t=u,b=g)}return b}};f.string.push([function(f){var r=f.toLowerCase(),d="transparent"===r?"#0000":a[r];return d?new e(d).toRgb():null},"name"])}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/colors.js
/**
* External dependencies
*/
k([names]);
/**
* Generating a CSS compliant rgba() color value.
*
* @param {string} hexValue The hex value to convert to rgba().
* @param {number} alpha The alpha value for opacity.
* @return {string} The converted rgba() color value.
*
* @example
* rgba( '#000000', 0.5 )
* // rgba(0, 0, 0, 0.5)
*/
function colors_rgba() {
let hexValue = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
let alpha = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
return colord_w(hexValue).alpha(alpha).toRgbString();
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/colors-values.js
/**
* Internal dependencies
*/
const white = '#fff'; // Matches the grays in @wordpress/base-styles
const GRAY = {
900: '#1e1e1e',
800: '#2f2f2f',
/** Meets 4.6:1 text contrast against white. */
700: '#757575',
/** Meets 3:1 UI or large text contrast against white. */
600: '#949494',
400: '#ccc',
/** Used for most borders. */
300: '#ddd',
/** Used sparingly for light borders. */
200: '#e0e0e0',
/** Used for light gray backgrounds. */
100: '#f0f0f0'
}; // Matches @wordpress/base-styles
const ALERT = {
yellow: '#f0b849',
red: '#d94f4f',
green: '#4ab866'
}; // Matches @wordpress/base-styles
const ADMIN = {
theme: 'var(--wp-components-color-accent, var(--wp-admin-theme-color, #007cba))',
themeDark10: 'var(--wp-components-color-accent-darker-10, var(--wp-admin-theme-color-darker-10, #006ba1))'
};
const UI = {
theme: ADMIN.theme,
themeDark10: ADMIN.themeDark10,
background: white,
backgroundDisabled: GRAY[100],
border: GRAY[600],
borderHover: GRAY[700],
borderFocus: ADMIN.themeDark10,
borderDisabled: GRAY[400],
textDisabled: GRAY[600],
textDark: white,
// Matches @wordpress/base-styles
darkGrayPlaceholder: colors_rgba(GRAY[900], 0.62),
lightGrayPlaceholder: colors_rgba(white, 0.65)
};
const COLORS = Object.freeze({
/**
* The main gray color object.
*/
gray: GRAY,
white,
alert: ALERT,
ui: UI
});
/* harmony default export */ var colors_values = ((/* unused pure expression or super */ null && (COLORS)));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/reduce-motion.js
/**
* Allows users to opt-out of animations via OS-level preferences.
*
* @param {'transition' | 'animation' | string} [prop='transition'] CSS Property name
* @return {string} Generated CSS code for the reduced style
*/
function reduceMotion() {
let prop = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'transition';
let style;
switch (prop) {
case 'transition':
style = 'transition-duration: 0ms;';
break;
case 'animation':
style = 'animation-duration: 1ms;';
break;
default:
style = `
animation-duration: 1ms;
transition-duration: 0ms;
`;
}
return `
@media ( prefers-reduced-motion: reduce ) {
${style};
}
`;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/alignment-matrix-control/styles/alignment-matrix-control-styles.js
function _EMOTION_STRINGIFIED_CSS_ERROR__() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
var _ref = true ? {
name: "93uojk",
styles: "border-radius:2px;box-sizing:border-box;direction:ltr;display:grid;grid-template-columns:repeat( 3, 1fr );outline:none"
} : 0;
const rootBase = () => {
return _ref;
};
const rootSize = _ref2 => {
let {
size = 92
} = _ref2;
return /*#__PURE__*/emotion_react_browser_esm_css("grid-template-rows:repeat( 3, calc( ", size, "px / 3 ) );width:", size, "px;" + ( true ? "" : 0), true ? "" : 0);
};
const Root = createStyled("div", true ? {
target: "ecapk1j3"
} : 0)(rootBase, ";border:1px solid transparent;cursor:pointer;grid-template-columns:auto;", rootSize, ";" + ( true ? "" : 0));
const Row = createStyled("div", true ? {
target: "ecapk1j2"
} : 0)( true ? {
name: "1x5gbbj",
styles: "box-sizing:border-box;display:grid;grid-template-columns:repeat( 3, 1fr )"
} : 0);
const pointActive = _ref3 => {
let {
isActive
} = _ref3;
const boxShadow = isActive ? `0 0 0 2px ${COLORS.gray[900]}` : null;
const pointColor = isActive ? COLORS.gray[900] : COLORS.gray[400];
const pointColorHover = isActive ? COLORS.gray[900] : COLORS.ui.theme;
return /*#__PURE__*/emotion_react_browser_esm_css("box-shadow:", boxShadow, ";color:", pointColor, ";*:hover>&{color:", pointColorHover, ";}" + ( true ? "" : 0), true ? "" : 0);
};
const pointBase = props => {
return /*#__PURE__*/emotion_react_browser_esm_css("background:currentColor;box-sizing:border-box;display:grid;margin:auto;transition:all 120ms linear;", reduceMotion('transition'), " ", pointActive(props), ";" + ( true ? "" : 0), true ? "" : 0);
};
const Point = createStyled("span", true ? {
target: "ecapk1j1"
} : 0)("height:6px;width:6px;", pointBase, ";" + ( true ? "" : 0));
const Cell = createStyled("span", true ? {
target: "ecapk1j0"
} : 0)( true ? {
name: "rjf3ub",
styles: "appearance:none;border:none;box-sizing:border-box;margin:0;display:flex;position:relative;outline:none;align-items:center;justify-content:center;padding:0"
} : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/alignment-matrix-control/cell.js
/**
* Internal dependencies
*/
/**
* Internal dependencies
*/
function cell_Cell(_ref) {
let {
isActive = false,
value,
...props
} = _ref;
const tooltipText = ALIGNMENT_LABEL[value];
return (0,external_wp_element_namespaceObject.createElement)(tooltip, {
text: tooltipText
}, (0,external_wp_element_namespaceObject.createElement)(CompositeItem, extends_extends({
as: Cell,
role: "gridcell"
}, props), (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, null, value), (0,external_wp_element_namespaceObject.createElement)(Point, {
isActive: isActive,
role: "presentation"
})));
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/useSealedState.js
/**
* React custom hook that returns the very first value passed to `initialState`,
* even if it changes between re-renders.
*/
function useSealedState(initialState) {
var _React$useState = (0,external_React_.useState)(initialState),
sealed = _React$useState[0];
return sealed;
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/reverse-30eaa122.js
function groupItems(items) {
var groups = [[]];
var _loop = function _loop() {
var item = _step.value;
var group = groups.find(function (g) {
return !g[0] || g[0].groupId === item.groupId;
});
if (group) {
group.push(item);
} else {
groups.push([item]);
}
};
for (var _iterator = _createForOfIteratorHelperLoose(items), _step; !(_step = _iterator()).done;) {
_loop();
}
return groups;
}
function flatten(grid) {
var flattened = [];
for (var _iterator = _createForOfIteratorHelperLoose(grid), _step; !(_step = _iterator()).done;) {
var row = _step.value;
flattened.push.apply(flattened, row);
}
return flattened;
}
function reverse(array) {
return array.slice().reverse();
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/findEnabledItemById-8ddca752.js
function findEnabledItemById(items, id) {
if (!id) return undefined;
return items === null || items === void 0 ? void 0 : items.find(function (item) {
return item.id === id && !item.disabled;
});
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/applyState.js
function isUpdater(argument) {
return typeof argument === "function";
}
/**
* Receives a `setState` argument and calls it with `currentValue` if it's a
* function. Otherwise return the argument as the new value.
*
* @example
* import { applyState } from "reakit-utils";
*
* applyState((value) => value + 1, 1); // 2
* applyState(2, 1); // 2
*/
function applyState(argument, currentValue) {
if (isUpdater(argument)) {
return argument(currentValue);
}
return argument;
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/Id/IdState.js
function unstable_useIdState(initialState) {
if (initialState === void 0) {
initialState = {};
}
var _useSealedState = useSealedState(initialState),
initialBaseId = _useSealedState.baseId;
var generateId = (0,external_React_.useContext)(unstable_IdContext);
var idCountRef = (0,external_React_.useRef)(0);
var _React$useState = (0,external_React_.useState)(function () {
return initialBaseId || generateId();
}),
baseId = _React$useState[0],
setBaseId = _React$useState[1];
return {
baseId: baseId,
setBaseId: setBaseId,
unstable_idCountRef: idCountRef
};
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/Composite/CompositeState.js
function isElementPreceding(element1, element2) {
return Boolean(element2.compareDocumentPosition(element1) & Node.DOCUMENT_POSITION_PRECEDING);
}
function findDOMIndex(items, item) {
return items.findIndex(function (currentItem) {
if (!currentItem.ref.current || !item.ref.current) {
return false;
}
return isElementPreceding(item.ref.current, currentItem.ref.current);
});
}
function getMaxLength(rows) {
var maxLength = 0;
for (var _iterator = _createForOfIteratorHelperLoose(rows), _step; !(_step = _iterator()).done;) {
var length = _step.value.length;
if (length > maxLength) {
maxLength = length;
}
}
return maxLength;
}
/**
* Turns [row1, row1, row2, row2] into [row1, row2, row1, row2]
*/
function verticalizeItems(items) {
var groups = groupItems(items);
var maxLength = getMaxLength(groups);
var verticalized = [];
for (var i = 0; i < maxLength; i += 1) {
for (var _iterator = _createForOfIteratorHelperLoose(groups), _step; !(_step = _iterator()).done;) {
var group = _step.value;
if (group[i]) {
verticalized.push(_objectSpread2(_objectSpread2({}, group[i]), {}, {
// If there's no groupId, it means that it's not a grid composite,
// but a single row instead. So, instead of verticalizing it, that
// is, assigning a different groupId based on the column index, we
// keep it undefined so they will be part of the same group.
// It's useful when using up/down on one-dimensional composites.
groupId: group[i].groupId ? "" + i : undefined
}));
}
}
}
return verticalized;
}
function createEmptyItem(groupId) {
return {
id: "__EMPTY_ITEM__",
disabled: true,
ref: {
current: null
},
groupId: groupId
};
}
/**
* Turns [[row1, row1], [row2]] into [[row1, row1], [row2, row2]]
*/
function fillGroups(groups, currentId, shift) {
var maxLength = getMaxLength(groups);
for (var _iterator = _createForOfIteratorHelperLoose(groups), _step; !(_step = _iterator()).done;) {
var group = _step.value;
for (var i = 0; i < maxLength; i += 1) {
var item = group[i];
if (!item || shift && item.disabled) {
var isFrist = i === 0;
var previousItem = isFrist && shift ? findFirstEnabledItem(group) : group[i - 1];
group[i] = previousItem && currentId !== (previousItem === null || previousItem === void 0 ? void 0 : previousItem.id) && shift ? previousItem : createEmptyItem(previousItem === null || previousItem === void 0 ? void 0 : previousItem.groupId);
}
}
}
return groups;
}
var nullItem = {
id: null,
ref: {
current: null
}
};
function placeItemsAfter(items, id, shouldInsertNullItem) {
var index = items.findIndex(function (item) {
return item.id === id;
});
return [].concat(items.slice(index + 1), shouldInsertNullItem ? [nullItem] : [], items.slice(0, index));
}
function getItemsInGroup(items, groupId) {
return items.filter(function (item) {
return item.groupId === groupId;
});
}
var map = {
horizontal: "vertical",
vertical: "horizontal"
};
function getOppositeOrientation(orientation) {
return orientation && map[orientation];
}
function addItemAtIndex(array, item, index) {
if (!(index in array)) {
return [].concat(array, [item]);
}
return [].concat(array.slice(0, index), [item], array.slice(index));
}
function sortBasedOnDOMPosition(items) {
var pairs = items.map(function (item, index) {
return [index, item];
});
var isOrderDifferent = false;
pairs.sort(function (_ref, _ref2) {
var indexA = _ref[0],
a = _ref[1];
var indexB = _ref2[0],
b = _ref2[1];
var elementA = a.ref.current;
var elementB = b.ref.current;
if (!elementA || !elementB) return 0; // a before b
if (isElementPreceding(elementA, elementB)) {
if (indexA > indexB) {
isOrderDifferent = true;
}
return -1;
} // a after b
if (indexA < indexB) {
isOrderDifferent = true;
}
return 1;
});
if (isOrderDifferent) {
return pairs.map(function (_ref3) {
var _ = _ref3[0],
item = _ref3[1];
return item;
});
}
return items;
}
function setItemsBasedOnDOMPosition(items, setItems) {
var sortedItems = sortBasedOnDOMPosition(items);
if (items !== sortedItems) {
setItems(sortedItems);
}
}
function getCommonParent(items) {
var _firstItem$ref$curren;
var firstItem = items[0],
nextItems = items.slice(1);
var parentElement = firstItem === null || firstItem === void 0 ? void 0 : (_firstItem$ref$curren = firstItem.ref.current) === null || _firstItem$ref$curren === void 0 ? void 0 : _firstItem$ref$curren.parentElement;
var _loop = function _loop() {
var parent = parentElement;
if (nextItems.every(function (item) {
return parent.contains(item.ref.current);
})) {
return {
v: parentElement
};
}
parentElement = parentElement.parentElement;
};
while (parentElement) {
var _ret = _loop();
if (typeof _ret === "object") return _ret.v;
}
return getDocument(parentElement).body;
} // istanbul ignore next: JSDOM doesn't support IntersectionObverser
// See https://github.com/jsdom/jsdom/issues/2032
function CompositeState_useIntersectionObserver(items, setItems) {
var previousItems = (0,external_React_.useRef)([]);
(0,external_React_.useEffect)(function () {
var callback = function callback() {
var hasPreviousItems = !!previousItems.current.length; // We don't want to sort items if items have been just registered.
if (hasPreviousItems) {
setItemsBasedOnDOMPosition(items, setItems);
}
previousItems.current = items;
};
var root = getCommonParent(items);
var observer = new IntersectionObserver(callback, {
root: root
});
for (var _iterator = _createForOfIteratorHelperLoose(items), _step; !(_step = _iterator()).done;) {
var item = _step.value;
if (item.ref.current) {
observer.observe(item.ref.current);
}
}
return function () {
observer.disconnect();
};
}, [items]);
}
function useTimeoutObserver(items, setItems) {
(0,external_React_.useEffect)(function () {
var callback = function callback() {
return setItemsBasedOnDOMPosition(items, setItems);
};
var timeout = setTimeout(callback, 250);
return function () {
return clearTimeout(timeout);
};
});
}
function useSortBasedOnDOMPosition(items, setItems) {
if (typeof IntersectionObserver === "function") {
CompositeState_useIntersectionObserver(items, setItems);
} else {
useTimeoutObserver(items, setItems);
}
}
function reducer(state, action) {
var virtual = state.unstable_virtual,
rtl = state.rtl,
orientation = state.orientation,
items = state.items,
groups = state.groups,
currentId = state.currentId,
loop = state.loop,
wrap = state.wrap,
pastIds = state.pastIds,
shift = state.shift,
moves = state.unstable_moves,
includesBaseElement = state.unstable_includesBaseElement,
initialVirtual = state.initialVirtual,
initialRTL = state.initialRTL,
initialOrientation = state.initialOrientation,
initialCurrentId = state.initialCurrentId,
initialLoop = state.initialLoop,
initialWrap = state.initialWrap,
initialShift = state.initialShift,
hasSetCurrentId = state.hasSetCurrentId;
switch (action.type) {
case "registerGroup":
{
var _group = action.group; // If there are no groups yet, just add it as the first one
if (groups.length === 0) {
return _objectSpread2(_objectSpread2({}, state), {}, {
groups: [_group]
});
} // Finds the group index based on DOM position
var index = findDOMIndex(groups, _group);
return _objectSpread2(_objectSpread2({}, state), {}, {
groups: addItemAtIndex(groups, _group, index)
});
}
case "unregisterGroup":
{
var _id = action.id;
var nextGroups = groups.filter(function (group) {
return group.id !== _id;
}); // The group isn't registered, so do nothing
if (nextGroups.length === groups.length) {
return state;
}
return _objectSpread2(_objectSpread2({}, state), {}, {
groups: nextGroups
});
}
case "registerItem":
{
var _item = action.item; // Finds the item group based on the DOM hierarchy
var _group2 = groups.find(function (r) {
var _r$ref$current;
return (_r$ref$current = r.ref.current) === null || _r$ref$current === void 0 ? void 0 : _r$ref$current.contains(_item.ref.current);
}); // Group will be null if it's a one-dimensional composite
var nextItem = _objectSpread2({
groupId: _group2 === null || _group2 === void 0 ? void 0 : _group2.id
}, _item);
var _index = findDOMIndex(items, nextItem);
var nextState = _objectSpread2(_objectSpread2({}, state), {}, {
items: addItemAtIndex(items, nextItem, _index)
});
if (!hasSetCurrentId && !moves && initialCurrentId === undefined) {
var _findFirstEnabledItem;
// Sets currentId to the first enabled item. This runs whenever an item
// is registered because the first enabled item may be registered
// asynchronously.
return _objectSpread2(_objectSpread2({}, nextState), {}, {
currentId: (_findFirstEnabledItem = findFirstEnabledItem(nextState.items)) === null || _findFirstEnabledItem === void 0 ? void 0 : _findFirstEnabledItem.id
});
}
return nextState;
}
case "unregisterItem":
{
var _id2 = action.id;
var nextItems = items.filter(function (item) {
return item.id !== _id2;
}); // The item isn't registered, so do nothing
if (nextItems.length === items.length) {
return state;
} // Filters out the item that is being removed from the pastIds list
var nextPastIds = pastIds.filter(function (pastId) {
return pastId !== _id2;
});
var _nextState = _objectSpread2(_objectSpread2({}, state), {}, {
pastIds: nextPastIds,
items: nextItems
}); // If the current item is the item that is being removed, focus pastId
if (currentId && currentId === _id2) {
var nextId = includesBaseElement ? null : getCurrentId(_objectSpread2(_objectSpread2({}, _nextState), {}, {
currentId: nextPastIds[0]
}));
return _objectSpread2(_objectSpread2({}, _nextState), {}, {
currentId: nextId
});
}
return _nextState;
}
case "move":
{
var _id3 = action.id; // move() does nothing
if (_id3 === undefined) {
return state;
} // Removes the current item and the item that is receiving focus from the
// pastIds list
var filteredPastIds = pastIds.filter(function (pastId) {
return pastId !== currentId && pastId !== _id3;
}); // If there's a currentId, add it to the pastIds list so it can be focused
// if the new item gets removed or disabled
var _nextPastIds = currentId ? [currentId].concat(filteredPastIds) : filteredPastIds;
var _nextState2 = _objectSpread2(_objectSpread2({}, state), {}, {
pastIds: _nextPastIds
}); // move(null) will focus the composite element itself, not an item
if (_id3 === null) {
return _objectSpread2(_objectSpread2({}, _nextState2), {}, {
unstable_moves: moves + 1,
currentId: getCurrentId(_nextState2, _id3)
});
}
var _item2 = findEnabledItemById(items, _id3);
return _objectSpread2(_objectSpread2({}, _nextState2), {}, {
unstable_moves: _item2 ? moves + 1 : moves,
currentId: getCurrentId(_nextState2, _item2 === null || _item2 === void 0 ? void 0 : _item2.id)
});
}
case "next":
{
// If there's no item focused, we just move the first one
if (currentId == null) {
return reducer(state, _objectSpread2(_objectSpread2({}, action), {}, {
type: "first"
}));
} // RTL doesn't make sense on vertical navigation
var isHorizontal = orientation !== "vertical";
var isRTL = rtl && isHorizontal;
var allItems = isRTL ? reverse(items) : items;
var currentItem = allItems.find(function (item) {
return item.id === currentId;
}); // If there's no item focused, we just move the first one
if (!currentItem) {
return reducer(state, _objectSpread2(_objectSpread2({}, action), {}, {
type: "first"
}));
}
var isGrid = !!currentItem.groupId;
var currentIndex = allItems.indexOf(currentItem);
var _nextItems = allItems.slice(currentIndex + 1);
var nextItemsInGroup = getItemsInGroup(_nextItems, currentItem.groupId); // Home, End
if (action.allTheWay) {
// We reverse so we can get the last enabled item in the group. If it's
// RTL, nextItems and nextItemsInGroup are already reversed and don't
// have the items before the current one anymore. So we have to get
// items in group again with allItems.
var _nextItem2 = findFirstEnabledItem(isRTL ? getItemsInGroup(allItems, currentItem.groupId) : reverse(nextItemsInGroup));
return reducer(state, _objectSpread2(_objectSpread2({}, action), {}, {
type: "move",
id: _nextItem2 === null || _nextItem2 === void 0 ? void 0 : _nextItem2.id
}));
}
var oppositeOrientation = getOppositeOrientation( // If it's a grid and orientation is not set, it's a next/previous
// call, which is inherently horizontal. up/down will call next with
// orientation set to vertical by default (see below on up/down cases).
isGrid ? orientation || "horizontal" : orientation);
var canLoop = loop && loop !== oppositeOrientation;
var canWrap = isGrid && wrap && wrap !== oppositeOrientation;
var hasNullItem = // `previous` and `up` will set action.hasNullItem, but when calling
// next directly, hasNullItem will only be true if it's not a grid and
// loop is set to true, which means that pressing right or down keys on
// grids will never focus the composite element. On one-dimensional
// composites that don't loop, pressing right or down keys also doesn't
// focus the composite element.
action.hasNullItem || !isGrid && canLoop && includesBaseElement;
if (canLoop) {
var loopItems = canWrap && !hasNullItem ? allItems : getItemsInGroup(allItems, currentItem.groupId); // Turns [0, 1, current, 3, 4] into [3, 4, 0, 1]
var sortedItems = placeItemsAfter(loopItems, currentId, hasNullItem);
var _nextItem3 = findFirstEnabledItem(sortedItems, currentId);
return reducer(state, _objectSpread2(_objectSpread2({}, action), {}, {
type: "move",
id: _nextItem3 === null || _nextItem3 === void 0 ? void 0 : _nextItem3.id
}));
}
if (canWrap) {
var _nextItem4 = findFirstEnabledItem( // We can use nextItems, which contains all the next items, including
// items from other groups, to wrap between groups. However, if there
// is a null item (the composite element), we'll only use the next
// items in the group. So moving next from the last item will focus
// the composite element (null). On grid composites, horizontal
// navigation never focuses the composite element, only vertical.
hasNullItem ? nextItemsInGroup : _nextItems, currentId);
var _nextId = hasNullItem ? (_nextItem4 === null || _nextItem4 === void 0 ? void 0 : _nextItem4.id) || null : _nextItem4 === null || _nextItem4 === void 0 ? void 0 : _nextItem4.id;
return reducer(state, _objectSpread2(_objectSpread2({}, action), {}, {
type: "move",
id: _nextId
}));
}
var _nextItem = findFirstEnabledItem(nextItemsInGroup, currentId);
if (!_nextItem && hasNullItem) {
return reducer(state, _objectSpread2(_objectSpread2({}, action), {}, {
type: "move",
id: null
}));
}
return reducer(state, _objectSpread2(_objectSpread2({}, action), {}, {
type: "move",
id: _nextItem === null || _nextItem === void 0 ? void 0 : _nextItem.id
}));
}
case "previous":
{
// If currentId is initially set to null, the composite element will be
// focusable while navigating with arrow keys. But, if it's a grid, we
// don't want to focus the composite element with horizontal navigation.
var _isGrid = !!groups.length;
var _hasNullItem = !_isGrid && includesBaseElement;
var _nextState3 = reducer(_objectSpread2(_objectSpread2({}, state), {}, {
items: reverse(items)
}), _objectSpread2(_objectSpread2({}, action), {}, {
type: "next",
hasNullItem: _hasNullItem
}));
return _objectSpread2(_objectSpread2({}, _nextState3), {}, {
items: items
});
}
case "down":
{
var shouldShift = shift && !action.allTheWay; // First, we make sure groups have the same number of items by filling it
// with disabled fake items. Then, we reorganize the items list so
// [1-1, 1-2, 2-1, 2-2] becomes [1-1, 2-1, 1-2, 2-2].
var verticalItems = verticalizeItems(flatten(fillGroups(groupItems(items), currentId, shouldShift)));
var _canLoop = loop && loop !== "horizontal"; // Pressing down arrow key will only focus the composite element if loop
// is true or vertical.
var _hasNullItem2 = _canLoop && includesBaseElement;
var _nextState4 = reducer(_objectSpread2(_objectSpread2({}, state), {}, {
orientation: "vertical",
items: verticalItems
}), _objectSpread2(_objectSpread2({}, action), {}, {
type: "next",
hasNullItem: _hasNullItem2
}));
return _objectSpread2(_objectSpread2({}, _nextState4), {}, {
orientation: orientation,
items: items
});
}
case "up":
{
var _shouldShift = shift && !action.allTheWay;
var _verticalItems = verticalizeItems(reverse(flatten(fillGroups(groupItems(items), currentId, _shouldShift)))); // If currentId is initially set to null, we'll always focus the
// composite element when the up arrow key is pressed in the first row.
var _hasNullItem3 = includesBaseElement;
var _nextState5 = reducer(_objectSpread2(_objectSpread2({}, state), {}, {
orientation: "vertical",
items: _verticalItems
}), _objectSpread2(_objectSpread2({}, action), {}, {
type: "next",
hasNullItem: _hasNullItem3
}));
return _objectSpread2(_objectSpread2({}, _nextState5), {}, {
orientation: orientation,
items: items
});
}
case "first":
{
var firstItem = findFirstEnabledItem(items);
return reducer(state, _objectSpread2(_objectSpread2({}, action), {}, {
type: "move",
id: firstItem === null || firstItem === void 0 ? void 0 : firstItem.id
}));
}
case "last":
{
var _nextState6 = reducer(_objectSpread2(_objectSpread2({}, state), {}, {
items: reverse(items)
}), _objectSpread2(_objectSpread2({}, action), {}, {
type: "first"
}));
return _objectSpread2(_objectSpread2({}, _nextState6), {}, {
items: items
});
}
case "sort":
{
return _objectSpread2(_objectSpread2({}, state), {}, {
items: sortBasedOnDOMPosition(items),
groups: sortBasedOnDOMPosition(groups)
});
}
case "setVirtual":
return _objectSpread2(_objectSpread2({}, state), {}, {
unstable_virtual: applyState(action.virtual, virtual)
});
case "setRTL":
return _objectSpread2(_objectSpread2({}, state), {}, {
rtl: applyState(action.rtl, rtl)
});
case "setOrientation":
return _objectSpread2(_objectSpread2({}, state), {}, {
orientation: applyState(action.orientation, orientation)
});
case "setCurrentId":
{
var nextCurrentId = getCurrentId(_objectSpread2(_objectSpread2({}, state), {}, {
currentId: applyState(action.currentId, currentId)
}));
return _objectSpread2(_objectSpread2({}, state), {}, {
currentId: nextCurrentId,
hasSetCurrentId: true
});
}
case "setLoop":
return _objectSpread2(_objectSpread2({}, state), {}, {
loop: applyState(action.loop, loop)
});
case "setWrap":
return _objectSpread2(_objectSpread2({}, state), {}, {
wrap: applyState(action.wrap, wrap)
});
case "setShift":
return _objectSpread2(_objectSpread2({}, state), {}, {
shift: applyState(action.shift, shift)
});
case "setIncludesBaseElement":
{
return _objectSpread2(_objectSpread2({}, state), {}, {
unstable_includesBaseElement: applyState(action.includesBaseElement, includesBaseElement)
});
}
case "reset":
return _objectSpread2(_objectSpread2({}, state), {}, {
unstable_virtual: initialVirtual,
rtl: initialRTL,
orientation: initialOrientation,
currentId: getCurrentId(_objectSpread2(_objectSpread2({}, state), {}, {
currentId: initialCurrentId
})),
loop: initialLoop,
wrap: initialWrap,
shift: initialShift,
unstable_moves: 0,
pastIds: []
});
case "setItems":
{
return _objectSpread2(_objectSpread2({}, state), {}, {
items: action.items
});
}
default:
throw new Error();
}
}
function useAction(fn) {
return (0,external_React_.useCallback)(fn, []);
}
function useIsUnmountedRef() {
var isUnmountedRef = (0,external_React_.useRef)(false);
useIsomorphicEffect(function () {
return function () {
isUnmountedRef.current = true;
};
}, []);
return isUnmountedRef;
}
function useCompositeState(initialState) {
if (initialState === void 0) {
initialState = {};
}
var _useSealedState = useSealedState(initialState),
_useSealedState$unsta = _useSealedState.unstable_virtual,
virtual = _useSealedState$unsta === void 0 ? false : _useSealedState$unsta,
_useSealedState$rtl = _useSealedState.rtl,
rtl = _useSealedState$rtl === void 0 ? false : _useSealedState$rtl,
orientation = _useSealedState.orientation,
currentId = _useSealedState.currentId,
_useSealedState$loop = _useSealedState.loop,
loop = _useSealedState$loop === void 0 ? false : _useSealedState$loop,
_useSealedState$wrap = _useSealedState.wrap,
wrap = _useSealedState$wrap === void 0 ? false : _useSealedState$wrap,
_useSealedState$shift = _useSealedState.shift,
shift = _useSealedState$shift === void 0 ? false : _useSealedState$shift,
unstable_includesBaseElement = _useSealedState.unstable_includesBaseElement,
sealed = _objectWithoutPropertiesLoose(_useSealedState, ["unstable_virtual", "rtl", "orientation", "currentId", "loop", "wrap", "shift", "unstable_includesBaseElement"]);
var idState = unstable_useIdState(sealed);
var _React$useReducer = (0,external_React_.useReducer)(reducer, {
unstable_virtual: virtual,
rtl: rtl,
orientation: orientation,
items: [],
groups: [],
currentId: currentId,
loop: loop,
wrap: wrap,
shift: shift,
unstable_moves: 0,
pastIds: [],
unstable_includesBaseElement: unstable_includesBaseElement != null ? unstable_includesBaseElement : currentId === null,
initialVirtual: virtual,
initialRTL: rtl,
initialOrientation: orientation,
initialCurrentId: currentId,
initialLoop: loop,
initialWrap: wrap,
initialShift: shift
}),
_React$useReducer$ = _React$useReducer[0],
pastIds = _React$useReducer$.pastIds,
initialVirtual = _React$useReducer$.initialVirtual,
initialRTL = _React$useReducer$.initialRTL,
initialOrientation = _React$useReducer$.initialOrientation,
initialCurrentId = _React$useReducer$.initialCurrentId,
initialLoop = _React$useReducer$.initialLoop,
initialWrap = _React$useReducer$.initialWrap,
initialShift = _React$useReducer$.initialShift,
hasSetCurrentId = _React$useReducer$.hasSetCurrentId,
state = _objectWithoutPropertiesLoose(_React$useReducer$, ["pastIds", "initialVirtual", "initialRTL", "initialOrientation", "initialCurrentId", "initialLoop", "initialWrap", "initialShift", "hasSetCurrentId"]),
dispatch = _React$useReducer[1];
var _React$useState = (0,external_React_.useState)(false),
hasActiveWidget = _React$useState[0],
setHasActiveWidget = _React$useState[1]; // register/unregister may be called when this component is unmounted. We
// store the unmounted state here so we don't update the state if it's true.
// This only happens in a very specific situation.
// See https://github.com/reakit/reakit/issues/650
var isUnmountedRef = useIsUnmountedRef();
var setItems = (0,external_React_.useCallback)(function (items) {
return dispatch({
type: "setItems",
items: items
});
}, []);
useSortBasedOnDOMPosition(state.items, setItems);
return _objectSpread2(_objectSpread2(_objectSpread2({}, idState), state), {}, {
unstable_hasActiveWidget: hasActiveWidget,
unstable_setHasActiveWidget: setHasActiveWidget,
registerItem: useAction(function (item) {
if (isUnmountedRef.current) return;
dispatch({
type: "registerItem",
item: item
});
}),
unregisterItem: useAction(function (id) {
if (isUnmountedRef.current) return;
dispatch({
type: "unregisterItem",
id: id
});
}),
registerGroup: useAction(function (group) {
if (isUnmountedRef.current) return;
dispatch({
type: "registerGroup",
group: group
});
}),
unregisterGroup: useAction(function (id) {
if (isUnmountedRef.current) return;
dispatch({
type: "unregisterGroup",
id: id
});
}),
move: useAction(function (id) {
return dispatch({
type: "move",
id: id
});
}),
next: useAction(function (allTheWay) {
return dispatch({
type: "next",
allTheWay: allTheWay
});
}),
previous: useAction(function (allTheWay) {
return dispatch({
type: "previous",
allTheWay: allTheWay
});
}),
up: useAction(function (allTheWay) {
return dispatch({
type: "up",
allTheWay: allTheWay
});
}),
down: useAction(function (allTheWay) {
return dispatch({
type: "down",
allTheWay: allTheWay
});
}),
first: useAction(function () {
return dispatch({
type: "first"
});
}),
last: useAction(function () {
return dispatch({
type: "last"
});
}),
sort: useAction(function () {
return dispatch({
type: "sort"
});
}),
unstable_setVirtual: useAction(function (value) {
return dispatch({
type: "setVirtual",
virtual: value
});
}),
setRTL: useAction(function (value) {
return dispatch({
type: "setRTL",
rtl: value
});
}),
setOrientation: useAction(function (value) {
return dispatch({
type: "setOrientation",
orientation: value
});
}),
setCurrentId: useAction(function (value) {
return dispatch({
type: "setCurrentId",
currentId: value
});
}),
setLoop: useAction(function (value) {
return dispatch({
type: "setLoop",
loop: value
});
}),
setWrap: useAction(function (value) {
return dispatch({
type: "setWrap",
wrap: value
});
}),
setShift: useAction(function (value) {
return dispatch({
type: "setShift",
shift: value
});
}),
unstable_setIncludesBaseElement: useAction(function (value) {
return dispatch({
type: "setIncludesBaseElement",
includesBaseElement: value
});
}),
reset: useAction(function () {
return dispatch({
type: "reset"
});
})
});
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/fireBlurEvent.js
function createFocusEvent(element, type, eventInit) {
if (eventInit === void 0) {
eventInit = {};
}
if (typeof FocusEvent === "function") {
return new FocusEvent(type, eventInit);
}
return createEvent(element, type, eventInit);
}
/**
* Creates and dispatches a blur event in a way that also works on IE 11.
*
* @example
* import { fireBlurEvent } from "reakit-utils";
*
* fireBlurEvent(document.getElementById("id"));
*/
function fireBlurEvent(element, eventInit) {
var event = createFocusEvent(element, "blur", eventInit);
var defaultAllowed = element.dispatchEvent(event);
var bubbleInit = _rollupPluginBabelHelpers_1f0bf8c2_objectSpread2(_rollupPluginBabelHelpers_1f0bf8c2_objectSpread2({}, eventInit), {}, {
bubbles: true
});
element.dispatchEvent(createFocusEvent(element, "focusout", bubbleInit));
return defaultAllowed;
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/fireKeyboardEvent.js
function createKeyboardEvent(element, type, eventInit) {
if (eventInit === void 0) {
eventInit = {};
}
if (typeof KeyboardEvent === "function") {
return new KeyboardEvent(type, eventInit);
} // IE 11 doesn't support Event constructors
var event = getDocument(element).createEvent("KeyboardEvent");
event.initKeyboardEvent(type, eventInit.bubbles, eventInit.cancelable, getWindow(element), eventInit.key, eventInit.location, eventInit.ctrlKey, eventInit.altKey, eventInit.shiftKey, eventInit.metaKey);
return event;
}
/**
* Creates and dispatches `KeyboardEvent` in a way that also works on IE 11.
*
* @example
* import { fireKeyboardEvent } from "reakit-utils";
*
* fireKeyboardEvent(document.getElementById("id"), "keydown", {
* key: "ArrowDown",
* shiftKey: true,
* });
*/
function fireKeyboardEvent(element, type, eventInit) {
return element.dispatchEvent(createKeyboardEvent(element, type, eventInit));
}
;// CONCATENATED MODULE: ./node_modules/reakit-utils/es/getNextActiveElementOnBlur.js
var isIE11 = canUseDOM && "msCrypto" in window;
/**
* Cross-browser method that returns the next active element (the element that
* is receiving focus) after a blur event is dispatched. It receives the blur
* event object as the argument.
*
* @example
* import { getNextActiveElementOnBlur } from "reakit-utils";
*
* const element = document.getElementById("id");
* element.addEventListener("blur", (event) => {
* const nextActiveElement = getNextActiveElementOnBlur(event);
* });
*/
function getNextActiveElementOnBlur(event) {
// IE 11 doesn't support event.relatedTarget on blur.
// document.activeElement points the the next active element.
// On modern browsers, document.activeElement points to the current target.
if (isIE11) {
var activeElement = getActiveElement_getActiveElement(event.currentTarget);
return activeElement;
}
return event.relatedTarget;
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/Composite/Composite.js
var Composite_isIE11 = canUseDOM && "msCrypto" in window;
function canProxyKeyboardEvent(event) {
if (!isSelfTarget(event)) return false;
if (event.metaKey) return false;
if (event.key === "Tab") return false;
return true;
}
function useKeyboardEventProxy(virtual, currentItem, htmlEventHandler) {
var eventHandlerRef = useLiveRef(htmlEventHandler);
return (0,external_React_.useCallback)(function (event) {
var _eventHandlerRef$curr;
(_eventHandlerRef$curr = eventHandlerRef.current) === null || _eventHandlerRef$curr === void 0 ? void 0 : _eventHandlerRef$curr.call(eventHandlerRef, event);
if (event.defaultPrevented) return;
if (virtual && canProxyKeyboardEvent(event)) {
var currentElement = currentItem === null || currentItem === void 0 ? void 0 : currentItem.ref.current;
if (currentElement) {
if (!fireKeyboardEvent(currentElement, event.type, event)) {
event.preventDefault();
} // The event will be triggered on the composite item and then
// propagated up to this composite element again, so we can pretend
// that it wasn't called on this component in the first place.
if (event.currentTarget.contains(currentElement)) {
event.stopPropagation();
}
}
}
}, [virtual, currentItem]);
} // istanbul ignore next
function useActiveElementRef(elementRef) {
var activeElementRef = (0,external_React_.useRef)(null);
(0,external_React_.useEffect)(function () {
var document = getDocument(elementRef.current);
var onFocus = function onFocus(event) {
var target = event.target;
activeElementRef.current = target;
};
document.addEventListener("focus", onFocus, true);
return function () {
document.removeEventListener("focus", onFocus, true);
};
}, []);
return activeElementRef;
}
function findFirstEnabledItemInTheLastRow(items) {
return findFirstEnabledItem(flatten(reverse(groupItems(items))));
}
function isItem(items, element) {
return items === null || items === void 0 ? void 0 : items.some(function (item) {
return !!element && item.ref.current === element;
});
}
function useScheduleUserFocus(currentItem) {
var currentItemRef = useLiveRef(currentItem);
var _React$useReducer = (0,external_React_.useReducer)(function (n) {
return n + 1;
}, 0),
scheduled = _React$useReducer[0],
schedule = _React$useReducer[1];
(0,external_React_.useEffect)(function () {
var _currentItemRef$curre;
var currentElement = (_currentItemRef$curre = currentItemRef.current) === null || _currentItemRef$curre === void 0 ? void 0 : _currentItemRef$curre.ref.current;
if (scheduled && currentElement) {
userFocus(currentElement);
}
}, [scheduled]);
return schedule;
}
var useComposite = createHook({
name: "Composite",
compose: [useTabbable],
keys: COMPOSITE_KEYS,
useOptions: function useOptions(options) {
return _objectSpread2(_objectSpread2({}, options), {}, {
currentId: getCurrentId(options)
});
},
useProps: function useProps(options, _ref) {
var htmlRef = _ref.ref,
htmlOnFocusCapture = _ref.onFocusCapture,
htmlOnFocus = _ref.onFocus,
htmlOnBlurCapture = _ref.onBlurCapture,
htmlOnKeyDown = _ref.onKeyDown,
htmlOnKeyDownCapture = _ref.onKeyDownCapture,
htmlOnKeyUpCapture = _ref.onKeyUpCapture,
htmlProps = _objectWithoutPropertiesLoose(_ref, ["ref", "onFocusCapture", "onFocus", "onBlurCapture", "onKeyDown", "onKeyDownCapture", "onKeyUpCapture"]);
var ref = (0,external_React_.useRef)(null);
var currentItem = findEnabledItemById(options.items, options.currentId);
var previousElementRef = (0,external_React_.useRef)(null);
var onFocusCaptureRef = useLiveRef(htmlOnFocusCapture);
var onFocusRef = useLiveRef(htmlOnFocus);
var onBlurCaptureRef = useLiveRef(htmlOnBlurCapture);
var onKeyDownRef = useLiveRef(htmlOnKeyDown);
var scheduleUserFocus = useScheduleUserFocus(currentItem); // IE 11 doesn't support event.relatedTarget, so we use the active element
// ref instead.
var activeElementRef = Composite_isIE11 ? useActiveElementRef(ref) : undefined;
(0,external_React_.useEffect)(function () {
var element = ref.current;
if (options.unstable_moves && !currentItem) {
false ? 0 : void 0; // If composite.move(null) has been called, the composite container
// will receive focus.
element === null || element === void 0 ? void 0 : element.focus();
}
}, [options.unstable_moves, currentItem]);
var onKeyDownCapture = useKeyboardEventProxy(options.unstable_virtual, currentItem, htmlOnKeyDownCapture);
var onKeyUpCapture = useKeyboardEventProxy(options.unstable_virtual, currentItem, htmlOnKeyUpCapture);
var onFocusCapture = (0,external_React_.useCallback)(function (event) {
var _onFocusCaptureRef$cu;
(_onFocusCaptureRef$cu = onFocusCaptureRef.current) === null || _onFocusCaptureRef$cu === void 0 ? void 0 : _onFocusCaptureRef$cu.call(onFocusCaptureRef, event);
if (event.defaultPrevented) return;
if (!options.unstable_virtual) return; // IE11 doesn't support event.relatedTarget, so we use the active
// element ref instead.
var previousActiveElement = (activeElementRef === null || activeElementRef === void 0 ? void 0 : activeElementRef.current) || event.relatedTarget;
var previousActiveElementWasItem = isItem(options.items, previousActiveElement);
if (isSelfTarget(event) && previousActiveElementWasItem) {
// Composite has been focused as a result of an item receiving focus.
// The composite item will move focus back to the composite
// container. In this case, we don't want to propagate this
// additional event nor call the onFocus handler passed to
// <Composite onFocus={...} />.
event.stopPropagation(); // We keep track of the previous active item element so we can
// manually fire a blur event on it later when the focus is moved to
// another item on the onBlurCapture event below.
previousElementRef.current = previousActiveElement;
}
}, [options.unstable_virtual, options.items]);
var onFocus = (0,external_React_.useCallback)(function (event) {
var _onFocusRef$current;
(_onFocusRef$current = onFocusRef.current) === null || _onFocusRef$current === void 0 ? void 0 : _onFocusRef$current.call(onFocusRef, event);
if (event.defaultPrevented) return;
if (options.unstable_virtual) {
if (isSelfTarget(event)) {
// This means that the composite element has been focused while the
// composite item has not. For example, by clicking on the
// composite element without touching any item, or by tabbing into
// the composite element. In this case, we want to trigger focus on
// the item, just like it would happen with roving tabindex.
// When it receives focus, the composite item will put focus back
// on the composite element, in which case hasItemWithFocus will be
// true.
scheduleUserFocus();
}
} else if (isSelfTarget(event)) {
var _options$setCurrentId;
// When the roving tabindex composite gets intentionally focused (for
// example, by clicking directly on it, and not on an item), we make
// sure to set the current id to null (which means the composite
// itself is focused).
(_options$setCurrentId = options.setCurrentId) === null || _options$setCurrentId === void 0 ? void 0 : _options$setCurrentId.call(options, null);
}
}, [options.unstable_virtual, options.setCurrentId]);
var onBlurCapture = (0,external_React_.useCallback)(function (event) {
var _onBlurCaptureRef$cur;
(_onBlurCaptureRef$cur = onBlurCaptureRef.current) === null || _onBlurCaptureRef$cur === void 0 ? void 0 : _onBlurCaptureRef$cur.call(onBlurCaptureRef, event);
if (event.defaultPrevented) return;
if (!options.unstable_virtual) return; // When virtual is set to true, we move focus from the composite
// container (this component) to the composite item that is being
// selected. Then we move focus back to the composite container. This
// is so we can provide the same API as the roving tabindex method,
// which means people can attach onFocus/onBlur handlers on the
// CompositeItem component regardless of whether it's virtual or not.
// This sequence of blurring and focusing items and composite may be
// confusing, so we ignore intermediate focus and blurs by stopping its
// propagation and not calling the passed onBlur handler (htmlOnBlur).
var currentElement = (currentItem === null || currentItem === void 0 ? void 0 : currentItem.ref.current) || null;
var nextActiveElement = getNextActiveElementOnBlur(event);
var nextActiveElementIsItem = isItem(options.items, nextActiveElement);
if (isSelfTarget(event) && nextActiveElementIsItem) {
// This is an intermediate blur event: blurring the composite
// container to focus an item (nextActiveElement).
if (nextActiveElement === currentElement) {
// The next active element will be the same as the current item in
// the state in two scenarios:
// - Moving focus with keyboard: the state is updated before the
// blur event is triggered, so here the current item is already
// pointing to the next active element.
// - Clicking on the current active item with a pointer: this
// will trigger blur on the composite element and then the next
// active element will be the same as the current item. Clicking on
// an item other than the current one doesn't end up here as the
// currentItem state will be updated only after it.
if (previousElementRef.current && previousElementRef.current !== nextActiveElement) {
// If there's a previous active item and it's not a click action,
// then we fire a blur event on it so it will work just like if
// it had DOM focus before (like when using roving tabindex).
fireBlurEvent(previousElementRef.current, event);
}
} else if (currentElement) {
// This will be true when the next active element is not the
// current element, but there's a current item. This will only
// happen when clicking with a pointer on a different item, when
// there's already an item selected, in which case currentElement
// is the item that is getting blurred, and nextActiveElement is
// the item that is being clicked.
fireBlurEvent(currentElement, event);
} // We want to ignore intermediate blur events, so we stop its
// propagation and return early so onFocus will not be called.
event.stopPropagation();
} else {
var targetIsItem = isItem(options.items, event.target);
if (!targetIsItem && currentElement) {
// If target is not a composite item, it may be the composite
// element itself (isSelfTarget) or a tabbable element inside the
// composite widget. This may be triggered by clicking outside the
// composite widget or by tabbing out of it. In either cases we
// want to fire a blur event on the current item.
fireBlurEvent(currentElement, event);
}
}
}, [options.unstable_virtual, options.items, currentItem]);
var onKeyDown = (0,external_React_.useCallback)(function (event) {
var _onKeyDownRef$current, _options$groups;
(_onKeyDownRef$current = onKeyDownRef.current) === null || _onKeyDownRef$current === void 0 ? void 0 : _onKeyDownRef$current.call(onKeyDownRef, event);
if (event.defaultPrevented) return;
if (options.currentId !== null) return;
if (!isSelfTarget(event)) return;
var isVertical = options.orientation !== "horizontal";
var isHorizontal = options.orientation !== "vertical";
var isGrid = !!((_options$groups = options.groups) !== null && _options$groups !== void 0 && _options$groups.length);
var up = function up() {
if (isGrid) {
var item = findFirstEnabledItemInTheLastRow(options.items);
if (item !== null && item !== void 0 && item.id) {
var _options$move;
(_options$move = options.move) === null || _options$move === void 0 ? void 0 : _options$move.call(options, item.id);
}
} else {
var _options$last;
(_options$last = options.last) === null || _options$last === void 0 ? void 0 : _options$last.call(options);
}
};
var keyMap = {
ArrowUp: (isGrid || isVertical) && up,
ArrowRight: (isGrid || isHorizontal) && options.first,
ArrowDown: (isGrid || isVertical) && options.first,
ArrowLeft: (isGrid || isHorizontal) && options.last,
Home: options.first,
End: options.last,
PageUp: options.first,
PageDown: options.last
};
var action = keyMap[event.key];
if (action) {
event.preventDefault();
action();
}
}, [options.currentId, options.orientation, options.groups, options.items, options.move, options.last, options.first]);
return _objectSpread2({
ref: useForkRef(ref, htmlRef),
id: options.baseId,
onFocus: onFocus,
onFocusCapture: onFocusCapture,
onBlurCapture: onBlurCapture,
onKeyDownCapture: onKeyDownCapture,
onKeyDown: onKeyDown,
onKeyUpCapture: onKeyUpCapture,
"aria-activedescendant": options.unstable_virtual ? (currentItem === null || currentItem === void 0 ? void 0 : currentItem.id) || undefined : undefined
}, htmlProps);
},
useComposeProps: function useComposeProps(options, htmlProps) {
htmlProps = useRole(options, htmlProps, true);
var tabbableHTMLProps = useTabbable(options, htmlProps, true);
if (options.unstable_virtual || options.currentId === null) {
// Composite will only be tabbable by default if the focus is managed
// using aria-activedescendant, which requires DOM focus on the container
// element (the composite)
return _objectSpread2({
tabIndex: 0
}, tabbableHTMLProps);
}
return _objectSpread2(_objectSpread2({}, htmlProps), {}, {
ref: tabbableHTMLProps.ref
});
}
});
var Composite = createComponent({
as: "div",
useHook: useComposite,
useCreateElement: function useCreateElement$1(type, props, children) {
false ? 0 : void 0;
return useCreateElement(type, props, children);
}
});
;// CONCATENATED MODULE: ./node_modules/reakit/es/Group/Group.js
// Automatically generated
var GROUP_KEYS = [];
var useGroup = createHook({
name: "Group",
compose: useRole,
keys: GROUP_KEYS,
useProps: function useProps(_, htmlProps) {
return _objectSpread2({
role: "group"
}, htmlProps);
}
});
var Group = createComponent({
as: "div",
useHook: useGroup
});
;// CONCATENATED MODULE: ./node_modules/reakit/es/Composite/CompositeGroup.js
var useCompositeGroup = createHook({
name: "CompositeGroup",
compose: [useGroup, unstable_useId],
keys: COMPOSITE_GROUP_KEYS,
propsAreEqual: function propsAreEqual(prev, next) {
if (!next.id || prev.id !== next.id) {
return useGroup.unstable_propsAreEqual(prev, next);
}
var prevCurrentId = prev.currentId,
prevMoves = prev.unstable_moves,
prevProps = _objectWithoutPropertiesLoose(prev, ["currentId", "unstable_moves"]);
var nextCurrentId = next.currentId,
nextMoves = next.unstable_moves,
nextProps = _objectWithoutPropertiesLoose(next, ["currentId", "unstable_moves"]);
if (prev.items && next.items) {
var prevCurrentItem = findEnabledItemById(prev.items, prevCurrentId);
var nextCurrentItem = findEnabledItemById(next.items, nextCurrentId);
var prevGroupId = prevCurrentItem === null || prevCurrentItem === void 0 ? void 0 : prevCurrentItem.groupId;
var nextGroupId = nextCurrentItem === null || nextCurrentItem === void 0 ? void 0 : nextCurrentItem.groupId;
if (next.id === nextGroupId || next.id === prevGroupId) {
return false;
}
}
return useGroup.unstable_propsAreEqual(prevProps, nextProps);
},
useProps: function useProps(options, _ref) {
var htmlRef = _ref.ref,
htmlProps = _objectWithoutPropertiesLoose(_ref, ["ref"]);
var ref = (0,external_React_.useRef)(null);
var id = options.id; // We need this to be called before CompositeItems' register
useIsomorphicEffect(function () {
var _options$registerGrou;
if (!id) return undefined;
(_options$registerGrou = options.registerGroup) === null || _options$registerGrou === void 0 ? void 0 : _options$registerGrou.call(options, {
id: id,
ref: ref
});
return function () {
var _options$unregisterGr;
(_options$unregisterGr = options.unregisterGroup) === null || _options$unregisterGr === void 0 ? void 0 : _options$unregisterGr.call(options, id);
};
}, [id, options.registerGroup, options.unregisterGroup]);
return _objectSpread2({
ref: useForkRef(ref, htmlRef)
}, htmlProps);
}
});
var CompositeGroup = createComponent({
as: "div",
useHook: useCompositeGroup
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/alignment-matrix-control/styles/alignment-matrix-control-icon-styles.js
function alignment_matrix_control_icon_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const alignment_matrix_control_icon_styles_rootSize = () => {
const padding = 1.5;
const size = 24;
return /*#__PURE__*/emotion_react_browser_esm_css({
gridTemplateRows: `repeat( 3, calc( ${size - padding * 2}px / 3))`,
padding,
maxHeight: size,
maxWidth: size
}, true ? "" : 0, true ? "" : 0);
};
const rootPointerEvents = _ref => {
let {
disablePointerEvents
} = _ref;
return /*#__PURE__*/emotion_react_browser_esm_css({
pointerEvents: disablePointerEvents ? 'none' : undefined
}, true ? "" : 0, true ? "" : 0);
};
const Wrapper = createStyled("div", true ? {
target: "erowt52"
} : 0)( true ? {
name: "ogl07i",
styles: "box-sizing:border-box;padding:2px"
} : 0);
const alignment_matrix_control_icon_styles_Root = createStyled("div", true ? {
target: "erowt51"
} : 0)("transform-origin:top left;height:100%;width:100%;", rootBase, ";", alignment_matrix_control_icon_styles_rootSize, ";", rootPointerEvents, ";" + ( true ? "" : 0));
const alignment_matrix_control_icon_styles_pointActive = _ref2 => {
let {
isActive
} = _ref2;
const boxShadow = isActive ? `0 0 0 1px currentColor` : null;
return /*#__PURE__*/emotion_react_browser_esm_css("box-shadow:", boxShadow, ";color:currentColor;*:hover>&{color:currentColor;}" + ( true ? "" : 0), true ? "" : 0);
};
const alignment_matrix_control_icon_styles_Point = createStyled("span", true ? {
target: "erowt50"
} : 0)("height:2px;width:2px;", pointBase, ";", alignment_matrix_control_icon_styles_pointActive, ";" + ( true ? "" : 0));
const alignment_matrix_control_icon_styles_Cell = Cell;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/alignment-matrix-control/icon.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const BASE_SIZE = 24;
function AlignmentMatrixControlIcon(_ref) {
let {
className,
disablePointerEvents = true,
size = BASE_SIZE,
style = {},
value = 'center',
...props
} = _ref;
const alignIndex = getAlignmentIndex(value);
const scale = (size / BASE_SIZE).toFixed(2);
const classes = classnames_default()('component-alignment-matrix-control-icon', className);
const styles = { ...style,
transform: `scale(${scale})`
};
return (0,external_wp_element_namespaceObject.createElement)(alignment_matrix_control_icon_styles_Root, extends_extends({}, props, {
className: classes,
disablePointerEvents: disablePointerEvents,
role: "presentation",
style: styles
}), ALIGNMENTS.map((align, index) => {
const isActive = alignIndex === index;
return (0,external_wp_element_namespaceObject.createElement)(alignment_matrix_control_icon_styles_Cell, {
key: align
}, (0,external_wp_element_namespaceObject.createElement)(alignment_matrix_control_icon_styles_Point, {
isActive: isActive
}));
}));
}
/* harmony default export */ var icon = (AlignmentMatrixControlIcon);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/alignment-matrix-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const alignment_matrix_control_noop = () => {};
function useBaseId(id) {
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(AlignmentMatrixControl, 'alignment-matrix-control');
return id || instanceId;
}
/**
*
* AlignmentMatrixControl components enable adjustments to horizontal and vertical alignments for UI.
*
* ```jsx
* import { __experimentalAlignmentMatrixControl as AlignmentMatrixControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const Example = () => {
* const [ alignment, setAlignment ] = useState( 'center center' );
*
* return (
* <AlignmentMatrixControl
* value={ alignment }
* onChange={ setAlignment }
* />
* );
* };
* ```
*/
function AlignmentMatrixControl(_ref) {
let {
className,
id,
label = (0,external_wp_i18n_namespaceObject.__)('Alignment Matrix Control'),
defaultValue = 'center center',
value,
onChange = alignment_matrix_control_noop,
width = 92,
...props
} = _ref;
const [immutableDefaultValue] = (0,external_wp_element_namespaceObject.useState)(value !== null && value !== void 0 ? value : defaultValue);
const baseId = useBaseId(id);
const initialCurrentId = getItemId(baseId, immutableDefaultValue);
const composite = useCompositeState({
baseId,
currentId: initialCurrentId,
rtl: (0,external_wp_i18n_namespaceObject.isRTL)()
});
const handleOnChange = nextValue => {
onChange(nextValue);
};
const {
setCurrentId
} = composite;
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (typeof value !== 'undefined') {
setCurrentId(getItemId(baseId, value));
}
}, [value, setCurrentId, baseId]);
const classes = classnames_default()('component-alignment-matrix-control', className);
return (0,external_wp_element_namespaceObject.createElement)(Composite, extends_extends({}, props, composite, {
"aria-label": label,
as: Root,
className: classes,
role: "grid",
size: width
}), GRID.map((cells, index) => (0,external_wp_element_namespaceObject.createElement)(CompositeGroup, extends_extends({}, composite, {
as: Row,
role: "row",
key: index
}), cells.map(cell => {
const cellId = getItemId(baseId, cell);
const isActive = composite.currentId === cellId;
return (0,external_wp_element_namespaceObject.createElement)(cell_Cell, extends_extends({}, composite, {
id: cellId,
isActive: isActive,
key: cell,
value: cell,
onFocus: () => handleOnChange(cell),
tabIndex: isActive ? 0 : -1
}));
}))));
}
AlignmentMatrixControl.Icon = icon;
/* harmony default export */ var alignment_matrix_control = (AlignmentMatrixControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/animate/index.js
/**
* External dependencies
*/
/**
* @typedef {'top' | 'top left' | 'top right' | 'middle' | 'middle left' | 'middle right' | 'bottom' | 'bottom left' | 'bottom right'} AppearOrigin
* @typedef {'left' | 'right'} SlideInOrigin
* @typedef {{ type: 'appear'; origin?: AppearOrigin }} AppearOptions
* @typedef {{ type: 'slide-in'; origin?: SlideInOrigin }} SlideInOptions
* @typedef {{ type: 'loading' }} LoadingOptions
* @typedef {AppearOptions | SlideInOptions | LoadingOptions} GetAnimateOptions
*/
/* eslint-disable jsdoc/valid-types */
/**
* @param {GetAnimateOptions['type']} type The animation type
* @return {'top' | 'left'} Default origin
*/
function getDefaultOrigin(type) {
return type === 'appear' ? 'top' : 'left';
}
/* eslint-enable jsdoc/valid-types */
/**
* @param {GetAnimateOptions} options
*
* @return {string | void} ClassName that applies the animations
*/
function getAnimateClassName(options) {
if (options.type === 'loading') {
return classnames_default()('components-animate__loading');
}
const {
type,
origin = getDefaultOrigin(type)
} = options;
if (type === 'appear') {
const [yAxis, xAxis = 'center'] = origin.split(' ');
return classnames_default()('components-animate__appear', {
['is-from-' + xAxis]: xAxis !== 'center',
['is-from-' + yAxis]: yAxis !== 'middle'
});
}
if (type === 'slide-in') {
return classnames_default()('components-animate__slide-in', 'is-from-' + origin);
}
} // @ts-ignore Reason: Planned for deprecation
function Animate(_ref) {
let {
type,
options = {},
children
} = _ref;
return children({
className: getAnimateClassName({
type,
...options
})
});
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/use-is-mounted.mjs
function useIsMounted() {
const isMounted = (0,external_React_.useRef)(false);
useIsomorphicLayoutEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);
return isMounted;
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/utils/use-force-update.mjs
function use_force_update_useForceUpdate() {
const isMounted = useIsMounted();
const [forcedRenderCount, setForcedRenderCount] = (0,external_React_.useState)(0);
const forceRender = (0,external_React_.useCallback)(() => {
isMounted.current && setForcedRenderCount(forcedRenderCount + 1);
}, [forcedRenderCount]);
/**
* Defer this to the end of the next animation frame in case there are multiple
* synchronous calls.
*/
const deferredForceRender = (0,external_React_.useCallback)(() => sync.postRender(forceRender), [forceRender]);
return [deferredForceRender, forcedRenderCount];
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/components/AnimatePresence/PopChild.mjs
/**
* Measurement functionality has to be within a separate component
* to leverage snapshot lifecycle.
*/
class PopChildMeasure extends external_React_.Component {
getSnapshotBeforeUpdate(prevProps) {
const element = this.props.childRef.current;
if (element && prevProps.isPresent && !this.props.isPresent) {
const size = this.props.sizeRef.current;
size.height = element.offsetHeight || 0;
size.width = element.offsetWidth || 0;
size.top = element.offsetTop;
size.left = element.offsetLeft;
}
return null;
}
/**
* Required with getSnapshotBeforeUpdate to stop React complaining.
*/
componentDidUpdate() { }
render() {
return this.props.children;
}
}
function PopChild({ children, isPresent }) {
const id = (0,external_React_.useId)();
const ref = (0,external_React_.useRef)(null);
const size = (0,external_React_.useRef)({
width: 0,
height: 0,
top: 0,
left: 0,
});
/**
* We create and inject a style block so we can apply this explicit
* sizing in a non-destructive manner by just deleting the style block.
*
* We can't apply size via render as the measurement happens
* in getSnapshotBeforeUpdate (post-render), likewise if we apply the
* styles directly on the DOM node, we might be overwriting
* styles set via the style prop.
*/
(0,external_React_.useInsertionEffect)(() => {
const { width, height, top, left } = size.current;
if (isPresent || !ref.current || !width || !height)
return;
ref.current.dataset.motionPopId = id;
const style = document.createElement("style");
document.head.appendChild(style);
if (style.sheet) {
style.sheet.insertRule(`
[data-motion-pop-id="${id}"] {
position: absolute !important;
width: ${width}px !important;
height: ${height}px !important;
top: ${top}px !important;
left: ${left}px !important;
}
`);
}
return () => {
document.head.removeChild(style);
};
}, [isPresent]);
return (external_React_.createElement(PopChildMeasure, { isPresent: isPresent, childRef: ref, sizeRef: size }, external_React_.cloneElement(children, { ref })));
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/components/AnimatePresence/PresenceChild.mjs
const PresenceChild = ({ children, initial, isPresent, onExitComplete, custom, presenceAffectsLayout, mode, }) => {
const presenceChildren = useConstant(newChildrenMap);
const id = (0,external_React_.useId)();
const context = (0,external_React_.useMemo)(() => ({
id,
initial,
isPresent,
custom,
onExitComplete: (childId) => {
presenceChildren.set(childId, true);
for (const isComplete of presenceChildren.values()) {
if (!isComplete)
return; // can stop searching when any is incomplete
}
onExitComplete && onExitComplete();
},
register: (childId) => {
presenceChildren.set(childId, false);
return () => presenceChildren.delete(childId);
},
}),
/**
* If the presence of a child affects the layout of the components around it,
* we want to make a new context value to ensure they get re-rendered
* so they can detect that layout change.
*/
presenceAffectsLayout ? undefined : [isPresent]);
(0,external_React_.useMemo)(() => {
presenceChildren.forEach((_, key) => presenceChildren.set(key, false));
}, [isPresent]);
/**
* If there's no `motion` components to fire exit animations, we want to remove this
* component immediately.
*/
external_React_.useEffect(() => {
!isPresent &&
!presenceChildren.size &&
onExitComplete &&
onExitComplete();
}, [isPresent]);
if (mode === "popLayout") {
children = external_React_.createElement(PopChild, { isPresent: isPresent }, children);
}
return (external_React_.createElement(PresenceContext_PresenceContext.Provider, { value: context }, children));
};
function newChildrenMap() {
return new Map();
}
;// CONCATENATED MODULE: ./node_modules/framer-motion/dist/es/components/AnimatePresence/index.mjs
const getChildKey = (child) => child.key || "";
function updateChildLookup(children, allChildren) {
children.forEach((child) => {
const key = getChildKey(child);
allChildren.set(key, child);
});
}
function onlyElements(children) {
const filtered = [];
// We use forEach here instead of map as map mutates the component key by preprending `.$`
external_React_.Children.forEach(children, (child) => {
if ((0,external_React_.isValidElement)(child))
filtered.push(child);
});
return filtered;
}
/**
* `AnimatePresence` enables the animation of components that have been removed from the tree.
*
* When adding/removing more than a single child, every child **must** be given a unique `key` prop.
*
* Any `motion` components that have an `exit` property defined will animate out when removed from
* the tree.
*
* ```jsx
* import { motion, AnimatePresence } from 'framer-motion'
*
* export const Items = ({ items }) => (
* <AnimatePresence>
* {items.map(item => (
* <motion.div
* key={item.id}
* initial={{ opacity: 0 }}
* animate={{ opacity: 1 }}
* exit={{ opacity: 0 }}
* />
* ))}
* </AnimatePresence>
* )
* ```
*
* You can sequence exit animations throughout a tree using variants.
*
* If a child contains multiple `motion` components with `exit` props, it will only unmount the child
* once all `motion` components have finished animating out. Likewise, any components using
* `usePresence` all need to call `safeToRemove`.
*
* @public
*/
const AnimatePresence = ({ children, custom, initial = true, onExitComplete, exitBeforeEnter, presenceAffectsLayout = true, mode = "sync", }) => {
// Support deprecated exitBeforeEnter prop
if (exitBeforeEnter) {
mode = "wait";
warnOnce(false, "Replace exitBeforeEnter with mode='wait'");
}
// We want to force a re-render once all exiting animations have finished. We
// either use a local forceRender function, or one from a parent context if it exists.
let [forceRender] = use_force_update_useForceUpdate();
const forceRenderLayoutGroup = (0,external_React_.useContext)(LayoutGroupContext).forceRender;
if (forceRenderLayoutGroup)
forceRender = forceRenderLayoutGroup;
const isMounted = useIsMounted();
// Filter out any children that aren't ReactElements. We can only track ReactElements with a props.key
const filteredChildren = onlyElements(children);
let childrenToRender = filteredChildren;
const exiting = new Set();
// Keep a living record of the children we're actually rendering so we
// can diff to figure out which are entering and exiting
const presentChildren = (0,external_React_.useRef)(childrenToRender);
// A lookup table to quickly reference components by key
const allChildren = (0,external_React_.useRef)(new Map()).current;
// If this is the initial component render, just deal with logic surrounding whether
// we play onMount animations or not.
const isInitialRender = (0,external_React_.useRef)(true);
useIsomorphicLayoutEffect(() => {
isInitialRender.current = false;
updateChildLookup(filteredChildren, allChildren);
presentChildren.current = childrenToRender;
});
useUnmountEffect(() => {
isInitialRender.current = true;
allChildren.clear();
exiting.clear();
});
if (isInitialRender.current) {
return (external_React_.createElement(external_React_.Fragment, null, childrenToRender.map((child) => (external_React_.createElement(PresenceChild, { key: getChildKey(child), isPresent: true, initial: initial ? undefined : false, presenceAffectsLayout: presenceAffectsLayout, mode: mode }, child)))));
}
// If this is a subsequent render, deal with entering and exiting children
childrenToRender = [...childrenToRender];
// Diff the keys of the currently-present and target children to update our
// exiting list.
const presentKeys = presentChildren.current.map(getChildKey);
const targetKeys = filteredChildren.map(getChildKey);
// Diff the present children with our target children and mark those that are exiting
const numPresent = presentKeys.length;
for (let i = 0; i < numPresent; i++) {
const key = presentKeys[i];
if (targetKeys.indexOf(key) === -1) {
exiting.add(key);
}
}
// If we currently have exiting children, and we're deferring rendering incoming children
// until after all current children have exiting, empty the childrenToRender array
if (mode === "wait" && exiting.size) {
childrenToRender = [];
}
// Loop through all currently exiting components and clone them to overwrite `animate`
// with any `exit` prop they might have defined.
exiting.forEach((key) => {
// If this component is actually entering again, early return
if (targetKeys.indexOf(key) !== -1)
return;
const child = allChildren.get(key);
if (!child)
return;
const insertionIndex = presentKeys.indexOf(key);
const onExit = () => {
allChildren.delete(key);
exiting.delete(key);
// Remove this child from the present children
const removeIndex = presentChildren.current.findIndex((presentChild) => presentChild.key === key);
presentChildren.current.splice(removeIndex, 1);
// Defer re-rendering until all exiting children have indeed left
if (!exiting.size) {
presentChildren.current = filteredChildren;
if (isMounted.current === false)
return;
forceRender();
onExitComplete && onExitComplete();
}
};
childrenToRender.splice(insertionIndex, 0, external_React_.createElement(PresenceChild, { key: getChildKey(child), isPresent: false, onExitComplete: onExit, custom: custom, presenceAffectsLayout: presenceAffectsLayout, mode: mode }, child));
});
// Add `MotionContext` even to children that don't need it to ensure we're rendering
// the same tree between renders
childrenToRender = childrenToRender.map((child) => {
const key = child.key;
return exiting.has(key) ? (child) : (external_React_.createElement(PresenceChild, { key: getChildKey(child), isPresent: true, presenceAffectsLayout: presenceAffectsLayout, mode: mode }, child));
});
if (env !== "production" &&
mode === "wait" &&
childrenToRender.length > 1) {
console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`);
}
return (external_React_.createElement(external_React_.Fragment, null, exiting.size
? childrenToRender
: childrenToRender.map((child) => (0,external_React_.cloneElement)(child))));
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/flex/context.js
/**
* WordPress dependencies
*/
const FlexContext = (0,external_wp_element_namespaceObject.createContext)({
flexItemDisplay: undefined
});
const useFlexContext = () => (0,external_wp_element_namespaceObject.useContext)(FlexContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/flex/styles.js
function styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
const Flex = true ? {
name: "zjik7",
styles: "display:flex"
} : 0;
const Item = true ? {
name: "qgaee5",
styles: "display:block;max-height:100%;max-width:100%;min-height:0;min-width:0"
} : 0;
const block = true ? {
name: "82a6rk",
styles: "flex:1"
} : 0;
/**
* Workaround to optimize DOM rendering.
* We'll enhance alignment with naive parent flex assumptions.
*
* Trade-off:
* Far less DOM less. However, UI rendering is not as reliable.
*/
/**
* Improves stability of width/height rendering.
* https://github.com/ItsJonQ/g2/pull/149
*/
const ItemsColumn = true ? {
name: "13nosa1",
styles: ">*{min-height:0;}"
} : 0;
const ItemsRow = true ? {
name: "1pwxzk4",
styles: ">*{min-width:0;}"
} : 0;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/flex/flex-item/hook.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function useFlexItem(props) {
const {
className,
display: displayProp,
isBlock = false,
...otherProps
} = useContextSystem(props, 'FlexItem');
const sx = {};
const contextDisplay = useFlexContext().flexItemDisplay;
sx.Base = /*#__PURE__*/emotion_react_browser_esm_css({
display: displayProp || contextDisplay
}, true ? "" : 0, true ? "" : 0);
const cx = useCx();
const classes = cx(Item, sx.Base, isBlock && block, className);
return { ...otherProps,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/flex/flex-block/hook.js
/**
* Internal dependencies
*/
function useFlexBlock(props) {
const otherProps = useContextSystem(props, 'FlexBlock');
const flexItemProps = useFlexItem({
isBlock: true,
...otherProps
});
return flexItemProps;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/flex/flex-block/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedFlexBlock(props, forwardedRef) {
const flexBlockProps = useFlexBlock(props);
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({}, flexBlockProps, {
ref: forwardedRef
}));
}
/**
* `FlexBlock` is a primitive layout component that adaptively resizes content
* within layout containers like `Flex`.
*
* ```jsx
* import { Flex, FlexBlock } from '@wordpress/components';
*
* function Example() {
* return (
* <Flex>
* <FlexBlock>...</FlexBlock>
* </Flex>
* );
* }
* ```
*/
const FlexBlock = contextConnect(UnconnectedFlexBlock, 'FlexBlock');
/* harmony default export */ var flex_block_component = (FlexBlock);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/flex/flex-item/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedFlexItem(props, forwardedRef) {
const flexItemProps = useFlexItem(props);
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({}, flexItemProps, {
ref: forwardedRef
}));
}
/**
* `FlexItem` is a primitive layout component that aligns content within layout
* containers like `Flex`.
*
* ```jsx
* import { Flex, FlexItem } from '@wordpress/components';
*
* function Example() {
* return (
* <Flex>
* <FlexItem>...</FlexItem>
* </Flex>
* );
* }
* ```
*/
const FlexItem = contextConnect(UnconnectedFlexItem, 'FlexItem');
/* harmony default export */ var flex_item_component = (FlexItem);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/plus.js
/**
* WordPress dependencies
*/
const plus = (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: "M18 11.2h-5.2V6h-1.6v5.2H6v1.6h5.2V18h1.6v-5.2H18z"
}));
/* harmony default export */ var library_plus = (plus);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/reset.js
/**
* WordPress dependencies
*/
const reset_reset = (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: "M7 11.5h10V13H7z"
}));
/* harmony default export */ var library_reset = (reset_reset);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/utils/use-responsive-value.js
/**
* WordPress dependencies
*/
const breakpoints = ['40em', '52em', '64em'];
const useBreakpointIndex = function () {
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const {
defaultIndex = 0
} = options;
if (typeof defaultIndex !== 'number') {
throw new TypeError(`Default breakpoint index should be a number. Got: ${defaultIndex}, ${typeof defaultIndex}`);
} else if (defaultIndex < 0 || defaultIndex > breakpoints.length - 1) {
throw new RangeError(`Default breakpoint index out of range. Theme has ${breakpoints.length} breakpoints, got index ${defaultIndex}`);
}
const [value, setValue] = (0,external_wp_element_namespaceObject.useState)(defaultIndex);
(0,external_wp_element_namespaceObject.useEffect)(() => {
const getIndex = () => breakpoints.filter(bp => {
return typeof window !== 'undefined' ? window.matchMedia(`screen and (min-width: ${bp})`).matches : false;
}).length;
const onResize = () => {
const newValue = getIndex();
if (value !== newValue) {
setValue(newValue);
}
};
onResize();
if (typeof window !== 'undefined') {
window.addEventListener('resize', onResize);
}
return () => {
if (typeof window !== 'undefined') {
window.removeEventListener('resize', onResize);
}
};
}, [value]);
return value;
};
function useResponsiveValue(values) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const index = useBreakpointIndex(options); // Allow calling the function with a "normal" value without having to check on the outside.
if (!Array.isArray(values) && typeof values !== 'function') return values;
const array = values || [];
/* eslint-disable jsdoc/no-undefined-types */
return (
/** @type {T[]} */
array[
/* eslint-enable jsdoc/no-undefined-types */
index >= array.length ? array.length - 1 : index]
);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/utils/space.js
/**
* The argument value for the `space()` utility function.
*
* When this is a number or a numeric string, it will be interpreted as a
* multiplier for the grid base value (4px). For example, `space( 2 )` will be 8px.
*
* Otherwise, it will be interpreted as a literal CSS length value. For example,
* `space( 'auto' )` will be 'auto', and `space( '2px' )` will be 2px.
*/
const GRID_BASE = '4px';
/**
* A function that handles numbers, numeric strings, and unit values.
*
* When given a number or a numeric string, it will return the grid-based
* value as a factor of GRID_BASE, defined above.
*
* When given a unit value or one of the named CSS values like `auto`,
* it will simply return the value back.
*
* @param value A number, numeric string, or a unit value.
*/
function space(value) {
var _window$CSS, _window$CSS$supports;
if (typeof value === 'undefined') {
return undefined;
} // Handle empty strings, if it's the number 0 this still works.
if (!value) {
return '0';
}
const asInt = typeof value === 'number' ? value : Number(value); // Test if the input has a unit, was NaN, or was one of the named CSS values (like `auto`), in which case just use that value.
if (typeof window !== 'undefined' && (_window$CSS = window.CSS) !== null && _window$CSS !== void 0 && (_window$CSS$supports = _window$CSS.supports) !== null && _window$CSS$supports !== void 0 && _window$CSS$supports.call(_window$CSS, 'margin', value.toString()) || Number.isNaN(asInt)) {
return value.toString();
}
return `calc(${GRID_BASE} * ${value})`;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/flex/flex/hook.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function hook_useDeprecatedProps(props) {
const {
isReversed,
...otherProps
} = props;
if (typeof isReversed !== 'undefined') {
external_wp_deprecated_default()('Flex isReversed', {
alternative: 'Flex direction="row-reverse" or "column-reverse"',
since: '5.9'
});
return { ...otherProps,
direction: isReversed ? 'row-reverse' : 'row'
};
}
return otherProps;
}
function useFlex(props) {
const {
align = 'center',
className,
direction: directionProp = 'row',
expanded = true,
gap = 2,
justify = 'space-between',
wrap = false,
...otherProps
} = useContextSystem(hook_useDeprecatedProps(props), 'Flex');
const directionAsArray = Array.isArray(directionProp) ? directionProp : [directionProp];
const direction = useResponsiveValue(directionAsArray);
const isColumn = typeof direction === 'string' && !!direction.includes('column');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
const base = /*#__PURE__*/emotion_react_browser_esm_css({
alignItems: isColumn ? 'normal' : align,
flexDirection: direction,
flexWrap: wrap ? 'wrap' : undefined,
gap: space(gap),
justifyContent: justify,
height: isColumn && expanded ? '100%' : undefined,
width: !isColumn && expanded ? '100%' : undefined
}, true ? "" : 0, true ? "" : 0);
return cx(Flex, base, isColumn ? ItemsColumn : ItemsRow, className);
}, [align, className, cx, direction, expanded, gap, isColumn, justify, wrap]);
return { ...otherProps,
className: classes,
isColumn
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/flex/flex/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedFlex(props, forwardedRef) {
const {
children,
isColumn,
...otherProps
} = useFlex(props);
return (0,external_wp_element_namespaceObject.createElement)(FlexContext.Provider, {
value: {
flexItemDisplay: isColumn ? 'block' : undefined
}
}, (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({}, otherProps, {
ref: forwardedRef
}), children));
}
/**
* `Flex` is a primitive layout component that adaptively aligns child content
* horizontally or vertically. `Flex` powers components like `HStack` and
* `VStack`.
*
* `Flex` is used with any of its two sub-components, `FlexItem` and
* `FlexBlock`.
*
* ```jsx
* import { Flex, FlexBlock, FlexItem } from '@wordpress/components';
*
* function Example() {
* return (
* <Flex>
* <FlexItem>
* <p>Code</p>
* </FlexItem>
* <FlexBlock>
* <p>Poetry</p>
* </FlexBlock>
* </Flex>
* );
* }
* ```
*/
const component_Flex = contextConnect(UnconnectedFlex, 'Flex');
/* harmony default export */ var flex_component = (component_Flex);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/truncate/styles.js
function truncate_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
const Truncate = true ? {
name: "hdknak",
styles: "display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"
} : 0;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/values.js
/* eslint-disable jsdoc/valid-types */
/**
* Determines if a value is null or undefined.
*
* @template T
*
* @param {T} value The value to check.
* @return {value is Exclude<T, null | undefined>} Whether value is not null or undefined.
*/
function isValueDefined(value) {
return value !== undefined && value !== null;
}
/* eslint-enable jsdoc/valid-types */
/* eslint-disable jsdoc/valid-types */
/**
* Determines if a value is empty, null, or undefined.
*
* @param {string | number | null | undefined} value The value to check.
* @return {value is ("" | null | undefined)} Whether value is empty.
*/
function isValueEmpty(value) {
const isEmptyString = value === '';
return !isValueDefined(value) || isEmptyString;
}
/* eslint-enable jsdoc/valid-types */
/**
* Get the first defined/non-null value from an array.
*
* @template T
*
* @param {Array<T | null | undefined>} values Values to derive from.
* @param {T} fallbackValue Fallback value if there are no defined values.
* @return {T} A defined value or the fallback value.
*/
function getDefinedValue() {
var _values$find;
let values = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
let fallbackValue = arguments.length > 1 ? arguments[1] : undefined;
return (_values$find = values.find(isValueDefined)) !== null && _values$find !== void 0 ? _values$find : fallbackValue;
}
/**
* @param {string} [locale]
* @return {[RegExp, RegExp]} The delimiter and decimal regexp
*/
const getDelimiterAndDecimalRegex = locale => {
const formatted = Intl.NumberFormat(locale).format(1000.1);
const delimiter = formatted[1];
const decimal = formatted[formatted.length - 2];
return [new RegExp(`\\${delimiter}`, 'g'), new RegExp(`\\${decimal}`, 'g')];
}; // https://en.wikipedia.org/wiki/Decimal_separator#Current_standards
const INTERNATIONAL_THOUSANDS_DELIMITER = / /g;
const ARABIC_NUMERAL_LOCALES = (/* unused pure expression or super */ null && (['ar', 'fa', 'ur', 'ckb', 'ps']));
const EASTERN_ARABIC_NUMBERS = /([۰-۹]|[٠-٩])/g;
/**
* Checks to see if a value is a numeric value (`number` or `string`).
*
* Intentionally ignores whether the thousands delimiters are only
* in the thousands marks.
*
* @param {any} value
* @param {string} [locale]
* @return {boolean} Whether value is numeric.
*/
function isValueNumeric(value) {
let locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window.navigator.language;
if (ARABIC_NUMERAL_LOCALES.some(l => locale.startsWith(l))) {
locale = 'en-GB';
if (EASTERN_ARABIC_NUMBERS.test(value)) {
value = value.replace(/[٠-٩]/g, (
/** @type {string} */
d) => '٠١٢٣٤٥٦٧٨٩'.indexOf(d)).replace(/[۰-۹]/g, (
/** @type {string} */
d) => '۰۱۲۳۴۵۶۷۸۹'.indexOf(d)).replace(/٬/g, ',').replace(/٫/g, '.');
}
}
const [delimiterRegexp, decimalRegexp] = getDelimiterAndDecimalRegex(locale);
const valueToCheck = typeof value === 'string' ? value.replace(delimiterRegexp, '').replace(decimalRegexp, '.').replace(INTERNATIONAL_THOUSANDS_DELIMITER, '') : value;
return !isNaN(parseFloat(valueToCheck)) && isFinite(valueToCheck);
}
/**
* Converts a string to a number.
*
* @param {string} value
* @return {number} String as a number.
*/
const stringToNumber = value => {
return parseFloat(value);
};
/**
* Converts a number to a string.
*
* @param {number} value
* @return {string} Number as a string.
*/
const numberToString = value => {
return `${value}`;
};
/**
* Regardless of the input being a string or a number, returns a number.
*
* Returns `undefined` in case the string is `undefined` or not a valid numeric value.
*
* @param {string | number} value
* @return {number} The parsed number.
*/
const ensureNumber = value => {
return typeof value === 'string' ? stringToNumber(value) : value;
};
/**
* Regardless of the input being a string or a number, returns a number.
*
* Returns `undefined` in case the string is `undefined` or not a valid numeric value.
*
* @param {string | number} value
* @return {string} The converted string, or `undefined` in case the input is `undefined` or `NaN`.
*/
const ensureString = value => {
return typeof value === 'string' ? value : numberToString(value);
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/truncate/utils.js
/**
* Internal dependencies
*/
const TRUNCATE_ELLIPSIS = '…';
const TRUNCATE_TYPE = {
auto: 'auto',
head: 'head',
middle: 'middle',
tail: 'tail',
none: 'none'
};
const TRUNCATE_DEFAULT_PROPS = {
ellipsis: TRUNCATE_ELLIPSIS,
ellipsizeMode: TRUNCATE_TYPE.auto,
limit: 0,
numberOfLines: 0
}; // Source
// https://github.com/kahwee/truncate-middle
function truncateMiddle(word, headLength, tailLength, ellipsis) {
if (typeof word !== 'string') {
return '';
}
const wordLength = word.length; // Setting default values
// eslint-disable-next-line no-bitwise
const frontLength = ~~headLength; // Will cast to integer
// eslint-disable-next-line no-bitwise
const backLength = ~~tailLength;
/* istanbul ignore next */
const truncateStr = isValueDefined(ellipsis) ? ellipsis : TRUNCATE_ELLIPSIS;
if (frontLength === 0 && backLength === 0 || frontLength >= wordLength || backLength >= wordLength || frontLength + backLength >= wordLength) {
return word;
} else if (backLength === 0) {
return word.slice(0, frontLength) + truncateStr;
}
return word.slice(0, frontLength) + truncateStr + word.slice(wordLength - backLength);
}
function truncateContent() {
let words = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
let props = arguments.length > 1 ? arguments[1] : undefined;
const mergedProps = { ...TRUNCATE_DEFAULT_PROPS,
...props
};
const {
ellipsis,
ellipsizeMode,
limit
} = mergedProps;
if (ellipsizeMode === TRUNCATE_TYPE.none) {
return words;
}
let truncateHead;
let truncateTail;
switch (ellipsizeMode) {
case TRUNCATE_TYPE.head:
truncateHead = 0;
truncateTail = limit;
break;
case TRUNCATE_TYPE.middle:
truncateHead = Math.floor(limit / 2);
truncateTail = Math.floor(limit / 2);
break;
default:
truncateHead = limit;
truncateTail = 0;
}
const truncatedContent = ellipsizeMode !== TRUNCATE_TYPE.auto ? truncateMiddle(words, truncateHead, truncateTail, ellipsis) : words;
return truncatedContent;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/truncate/hook.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useTruncate(props) {
const {
className,
children,
ellipsis = TRUNCATE_ELLIPSIS,
ellipsizeMode = TRUNCATE_TYPE.auto,
limit = 0,
numberOfLines = 0,
...otherProps
} = useContextSystem(props, 'Truncate');
const cx = useCx();
const truncatedContent = truncateContent(typeof children === 'string' ? children : '', {
ellipsis,
ellipsizeMode,
limit,
numberOfLines
});
const shouldTruncate = ellipsizeMode === TRUNCATE_TYPE.auto;
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
const truncateLines = /*#__PURE__*/emotion_react_browser_esm_css("-webkit-box-orient:vertical;-webkit-line-clamp:", numberOfLines, ";display:-webkit-box;overflow:hidden;" + ( true ? "" : 0), true ? "" : 0);
return cx(shouldTruncate && !numberOfLines && Truncate, shouldTruncate && !!numberOfLines && truncateLines, className);
}, [className, cx, numberOfLines, shouldTruncate]);
return { ...otherProps,
className: classes,
children: truncatedContent
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/utils/colors.js
/**
* External dependencies
*/
/** @type {HTMLDivElement} */
let colorComputationNode;
k([names]);
/**
* @return {HTMLDivElement | undefined} The HTML element for color computation.
*/
function getColorComputationNode() {
if (typeof document === 'undefined') return;
if (!colorComputationNode) {
// Create a temporary element for style computation.
const el = document.createElement('div');
el.setAttribute('data-g2-color-computation-node', ''); // Inject for window computed style.
document.body.appendChild(el);
colorComputationNode = el;
}
return colorComputationNode;
}
/**
* @param {string | unknown} value
*
* @return {boolean} Whether the value is a valid color.
*/
function isColor(value) {
if (typeof value !== 'string') return false;
const test = colord_w(value);
return test.isValid();
}
/**
* Retrieves the computed background color. This is useful for getting the
* value of a CSS variable color.
*
* @param {string | unknown} backgroundColor The background color to compute.
*
* @return {string} The computed background color.
*/
function _getComputedBackgroundColor(backgroundColor) {
var _window;
if (typeof backgroundColor !== 'string') return '';
if (isColor(backgroundColor)) return backgroundColor;
if (!backgroundColor.includes('var(')) return '';
if (typeof document === 'undefined') return ''; // Attempts to gracefully handle CSS variables color values.
const el = getColorComputationNode();
if (!el) return '';
el.style.background = backgroundColor; // Grab the style.
const computedColor = (_window = window) === null || _window === void 0 ? void 0 : _window.getComputedStyle(el).background; // Reset.
el.style.background = '';
return computedColor || '';
}
const getComputedBackgroundColor = memize_default()(_getComputedBackgroundColor);
/**
* Get the text shade optimized for readability, based on a background color.
*
* @param {string | unknown} backgroundColor The background color.
*
* @return {string} The optimized text color (black or white).
*/
function getOptimalTextColor(backgroundColor) {
const background = getComputedBackgroundColor(backgroundColor);
return colord_w(background).isLight() ? '#000000' : '#ffffff';
}
/**
* Get the text shade optimized for readability, based on a background color.
*
* @param {string | unknown} backgroundColor The background color.
*
* @return {string} The optimized text shade (dark or light).
*/
function getOptimalTextShade(backgroundColor) {
const result = getOptimalTextColor(backgroundColor);
return result === '#000000' ? 'dark' : 'light';
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/config-values.js
/**
* Internal dependencies
*/
const CONTROL_HEIGHT = '36px';
const CONTROL_PADDING_X = '12px';
const CONTROL_PROPS = {
controlSurfaceColor: COLORS.white,
controlTextActiveColor: COLORS.ui.theme,
controlPaddingX: CONTROL_PADDING_X,
controlPaddingXLarge: `calc(${CONTROL_PADDING_X} * 1.3334)`,
controlPaddingXSmall: `calc(${CONTROL_PADDING_X} / 1.3334)`,
controlBackgroundColor: COLORS.white,
controlBorderRadius: '2px',
controlBoxShadow: 'transparent',
controlBoxShadowFocus: `0 0 0 0.5px ${COLORS.ui.theme}`,
controlDestructiveBorderColor: COLORS.alert.red,
controlHeight: CONTROL_HEIGHT,
controlHeightXSmall: `calc( ${CONTROL_HEIGHT} * 0.6 )`,
controlHeightSmall: `calc( ${CONTROL_HEIGHT} * 0.8 )`,
controlHeightLarge: `calc( ${CONTROL_HEIGHT} * 1.2 )`,
controlHeightXLarge: `calc( ${CONTROL_HEIGHT} * 1.4 )`
};
const TOGGLE_GROUP_CONTROL_PROPS = {
toggleGroupControlBackgroundColor: CONTROL_PROPS.controlBackgroundColor,
toggleGroupControlBorderColor: COLORS.ui.border,
toggleGroupControlBackdropBackgroundColor: CONTROL_PROPS.controlSurfaceColor,
toggleGroupControlBackdropBorderColor: COLORS.ui.border,
toggleGroupControlButtonColorActive: CONTROL_PROPS.controlBackgroundColor
}; // Using Object.assign to avoid creating circular references when emitting
// TypeScript type declarations.
/* harmony default export */ var config_values = (Object.assign({}, CONTROL_PROPS, TOGGLE_GROUP_CONTROL_PROPS, {
colorDivider: 'rgba(0, 0, 0, 0.1)',
colorScrollbarThumb: 'rgba(0, 0, 0, 0.2)',
colorScrollbarThumbHover: 'rgba(0, 0, 0, 0.5)',
colorScrollbarTrack: 'rgba(0, 0, 0, 0.04)',
elevationIntensity: 1,
radiusBlockUi: '2px',
borderWidth: '1px',
borderWidthFocus: '1.5px',
borderWidthTab: '4px',
spinnerSize: 16,
fontSize: '13px',
fontSizeH1: 'calc(2.44 * 13px)',
fontSizeH2: 'calc(1.95 * 13px)',
fontSizeH3: 'calc(1.56 * 13px)',
fontSizeH4: 'calc(1.25 * 13px)',
fontSizeH5: '13px',
fontSizeH6: 'calc(0.8 * 13px)',
fontSizeInputMobile: '16px',
fontSizeMobile: '15px',
fontSizeSmall: 'calc(0.92 * 13px)',
fontSizeXSmall: 'calc(0.75 * 13px)',
fontLineHeightBase: '1.2',
fontWeight: 'normal',
fontWeightHeading: '600',
gridBase: '4px',
cardBorderRadius: '2px',
cardPaddingXSmall: `${space(2)}`,
cardPaddingSmall: `${space(4)}`,
cardPaddingMedium: `${space(4)} ${space(6)}`,
cardPaddingLarge: `${space(6)} ${space(8)}`,
surfaceBackgroundColor: COLORS.white,
surfaceBackgroundSubtleColor: '#F3F3F3',
surfaceBackgroundTintColor: '#F5F5F5',
surfaceBorderColor: 'rgba(0, 0, 0, 0.1)',
surfaceBorderBoldColor: 'rgba(0, 0, 0, 0.15)',
surfaceBorderSubtleColor: 'rgba(0, 0, 0, 0.05)',
surfaceBackgroundTertiaryColor: COLORS.white,
surfaceColor: COLORS.white,
transitionDuration: '200ms',
transitionDurationFast: '160ms',
transitionDurationFaster: '120ms',
transitionDurationFastest: '100ms',
transitionTimingFunction: 'cubic-bezier(0.08, 0.52, 0.52, 1)',
transitionTimingFunctionControl: 'cubic-bezier(0.12, 0.8, 0.32, 1)'
}));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/text/styles.js
function text_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const Text = /*#__PURE__*/emotion_react_browser_esm_css("color:", COLORS.gray[900], ";line-height:", config_values.fontLineHeightBase, ";margin:0;" + ( true ? "" : 0), true ? "" : 0);
const styles_block = true ? {
name: "4zleql",
styles: "display:block"
} : 0;
const positive = /*#__PURE__*/emotion_react_browser_esm_css("color:", COLORS.alert.green, ";" + ( true ? "" : 0), true ? "" : 0);
const destructive = /*#__PURE__*/emotion_react_browser_esm_css("color:", COLORS.alert.red, ";" + ( true ? "" : 0), true ? "" : 0);
const muted = /*#__PURE__*/emotion_react_browser_esm_css("color:", COLORS.gray[700], ";" + ( true ? "" : 0), true ? "" : 0);
const highlighterText = /*#__PURE__*/emotion_react_browser_esm_css("mark{background:", COLORS.alert.yellow, ";border-radius:2px;box-shadow:0 0 0 1px rgba( 0, 0, 0, 0.05 ) inset,0 -1px 0 rgba( 0, 0, 0, 0.1 ) inset;}" + ( true ? "" : 0), true ? "" : 0);
const upperCase = true ? {
name: "50zrmy",
styles: "text-transform:uppercase"
} : 0;
// EXTERNAL MODULE: ./node_modules/highlight-words-core/dist/index.js
var dist = __webpack_require__(3138);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/text/utils.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Source:
* https://github.com/bvaughn/react-highlight-words/blob/HEAD/src/Highlighter.js
*/
/* eslint-disable jsdoc/valid-types */
/**
* @typedef Options
* @property {string} [activeClassName=''] Classname for active highlighted areas.
* @property {number} [activeIndex=-1] The index of the active highlighted area.
* @property {import('react').AllHTMLAttributes<HTMLDivElement>['style']} [activeStyle] Styles to apply to the active highlighted area.
* @property {boolean} [autoEscape] Whether to automatically escape text.
* @property {boolean} [caseSensitive=false] Whether to highlight in a case-sensitive manner.
* @property {string} children Children to highlight.
* @property {import('highlight-words-core').FindAllArgs['findChunks']} [findChunks] Custom `findChunks` function to pass to `highlight-words-core`.
* @property {string | Record<string, unknown>} [highlightClassName=''] Classname to apply to highlighted text or a Record of classnames to apply to given text (which should be the key).
* @property {import('react').AllHTMLAttributes<HTMLDivElement>['style']} [highlightStyle={}] Styles to apply to highlighted text.
* @property {keyof JSX.IntrinsicElements} [highlightTag='mark'] Tag to use for the highlighted text.
* @property {import('highlight-words-core').FindAllArgs['sanitize']} [sanitize] Custom `santize` function to pass to `highlight-words-core`.
* @property {string[]} [searchWords=[]] Words to search for and highlight.
* @property {string} [unhighlightClassName=''] Classname to apply to unhighlighted text.
* @property {import('react').AllHTMLAttributes<HTMLDivElement>['style']} [unhighlightStyle] Style to apply to unhighlighted text.
*/
/**
* Maps props to lowercase names.
*
* @template {Record<string, unknown>} T
* @param {T} object Props to map.
* @return {{[K in keyof T as Lowercase<string & K>]: T[K]}} The mapped props.
*/
/* eslint-enable jsdoc/valid-types */
const lowercaseProps = object => {
/** @type {any} */
const mapped = {};
for (const key in object) {
mapped[key.toLowerCase()] = object[key];
}
return mapped;
};
const memoizedLowercaseProps = memize_default()(lowercaseProps);
/**
*
* @param {Options} options
*/
function createHighlighterText(_ref) {
let {
activeClassName = '',
activeIndex = -1,
activeStyle,
autoEscape,
caseSensitive = false,
children,
findChunks,
highlightClassName = '',
highlightStyle = {},
highlightTag = 'mark',
sanitize,
searchWords = [],
unhighlightClassName = '',
unhighlightStyle
} = _ref;
if (!children) return null;
if (typeof children !== 'string') return children;
const textToHighlight = children;
const chunks = (0,dist.findAll)({
autoEscape,
caseSensitive,
findChunks,
sanitize,
searchWords,
textToHighlight
});
const HighlightTag = highlightTag;
let highlightIndex = -1;
let highlightClassNames = '';
let highlightStyles;
const textContent = chunks.map((chunk, index) => {
const text = textToHighlight.substr(chunk.start, chunk.end - chunk.start);
if (chunk.highlight) {
highlightIndex++;
let highlightClass;
if (typeof highlightClassName === 'object') {
if (!caseSensitive) {
highlightClassName = memoizedLowercaseProps(highlightClassName);
highlightClass = highlightClassName[text.toLowerCase()];
} else {
highlightClass = highlightClassName[text];
}
} else {
highlightClass = highlightClassName;
}
const isActive = highlightIndex === +activeIndex;
highlightClassNames = `${highlightClass} ${isActive ? activeClassName : ''}`;
highlightStyles = isActive === true && activeStyle !== null ? Object.assign({}, highlightStyle, activeStyle) : highlightStyle;
/** @type {Record<string, any>} */
const props = {
children: text,
className: highlightClassNames,
key: index,
style: highlightStyles
}; // Don't attach arbitrary props to DOM elements; this triggers React DEV warnings (https://fb.me/react-unknown-prop)
// Only pass through the highlightIndex attribute for custom components.
if (typeof HighlightTag !== 'string') {
props.highlightIndex = highlightIndex;
}
return (0,external_wp_element_namespaceObject.createElement)(HighlightTag, props);
}
return (0,external_wp_element_namespaceObject.createElement)('span', {
children: text,
className: unhighlightClassName,
key: index,
style: unhighlightStyle
});
});
return textContent;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/utils/font-size.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const BASE_FONT_SIZE = 13;
const PRESET_FONT_SIZES = {
body: BASE_FONT_SIZE,
caption: 10,
footnote: 11,
largeTitle: 28,
subheadline: 12,
title: 20
};
const HEADING_FONT_SIZES = [1, 2, 3, 4, 5, 6].flatMap(n => [n, n.toString()]);
function getFontSize() {
let size = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : BASE_FONT_SIZE;
if (size in PRESET_FONT_SIZES) {
return getFontSize(PRESET_FONT_SIZES[size]);
}
if (typeof size !== 'number') {
const parsed = parseFloat(size);
if (Number.isNaN(parsed)) return size;
size = parsed;
}
const ratio = `(${size} / ${BASE_FONT_SIZE})`;
return `calc(${ratio} * ${config_values.fontSize})`;
}
function getHeadingFontSize() {
let size = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 3;
if (!HEADING_FONT_SIZES.includes(size)) {
return getFontSize(size);
}
const headingSize = `fontSizeH${size}`;
return config_values[headingSize];
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/text/get-line-height.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function getLineHeight(adjustLineHeightForInnerControls, lineHeight) {
if (lineHeight) return lineHeight;
if (!adjustLineHeightForInnerControls) return;
let value = `calc(${config_values.controlHeight} + ${space(2)})`;
switch (adjustLineHeightForInnerControls) {
case 'large':
value = `calc(${config_values.controlHeightLarge} + ${space(2)})`;
break;
case 'small':
value = `calc(${config_values.controlHeightSmall} + ${space(2)})`;
break;
case 'xSmall':
value = `calc(${config_values.controlHeightXSmall} + ${space(2)})`;
break;
default:
break;
}
return value;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/text/hook.js
function hook_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* @param {import('../ui/context').WordPressComponentProps<import('./types').Props, 'span'>} props
*/
var hook_ref = true ? {
name: "50zrmy",
styles: "text-transform:uppercase"
} : 0;
function useText(props) {
const {
adjustLineHeightForInnerControls,
align,
children,
className,
color,
ellipsizeMode,
isDestructive = false,
display,
highlightEscape = false,
highlightCaseSensitive = false,
highlightWords,
highlightSanitize,
isBlock = false,
letterSpacing,
lineHeight: lineHeightProp,
optimizeReadabilityFor,
size,
truncate = false,
upperCase = false,
variant,
weight = config_values.fontWeight,
...otherProps
} = useContextSystem(props, 'Text');
/** @type {import('react').ReactNode} */
let content = children;
const isHighlighter = Array.isArray(highlightWords);
const isCaption = size === 'caption';
if (isHighlighter) {
if (typeof children !== 'string') {
throw new TypeError('`children` of `Text` must only be `string` types when `highlightWords` is defined');
}
content = createHighlighterText({
autoEscape: highlightEscape,
// Disable reason: We need to disable this otherwise it erases the cast
// eslint-disable-next-line object-shorthand
children:
/** @type {string} */
children,
caseSensitive: highlightCaseSensitive,
searchWords: highlightWords,
sanitize: highlightSanitize
});
}
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
const sx = {};
const lineHeight = getLineHeight(adjustLineHeightForInnerControls, lineHeightProp);
sx.Base = /*#__PURE__*/emotion_react_browser_esm_css({
color,
display,
fontSize: getFontSize(size),
/* eslint-disable jsdoc/valid-types */
fontWeight:
/** @type {import('react').CSSProperties['fontWeight']} */
weight,
/* eslint-enable jsdoc/valid-types */
lineHeight,
letterSpacing,
textAlign: align
}, true ? "" : 0, true ? "" : 0);
sx.upperCase = hook_ref;
sx.optimalTextColor = null;
if (optimizeReadabilityFor) {
const isOptimalTextColorDark = getOptimalTextShade(optimizeReadabilityFor) === 'dark';
sx.optimalTextColor = isOptimalTextColorDark ? /*#__PURE__*/emotion_react_browser_esm_css({
color: COLORS.gray[900]
}, true ? "" : 0, true ? "" : 0) : /*#__PURE__*/emotion_react_browser_esm_css({
color: COLORS.white
}, true ? "" : 0, true ? "" : 0);
}
return cx(Text, sx.Base, sx.optimalTextColor, isDestructive && destructive, !!isHighlighter && highlighterText, isBlock && styles_block, isCaption && muted, variant && text_styles_namespaceObject[variant], upperCase && sx.upperCase, className);
}, [adjustLineHeightForInnerControls, align, className, color, cx, display, isBlock, isCaption, isDestructive, isHighlighter, letterSpacing, lineHeightProp, optimizeReadabilityFor, size, upperCase, variant, weight]);
/** @type {undefined | 'auto' | 'none'} */
let finalEllipsizeMode;
if (truncate === true) {
finalEllipsizeMode = 'auto';
}
if (truncate === false) {
finalEllipsizeMode = 'none';
}
const finalComponentProps = { ...otherProps,
className: classes,
children,
ellipsizeMode: ellipsizeMode || finalEllipsizeMode
};
const truncateProps = useTruncate(finalComponentProps);
/**
* Enhance child `<Link />` components to inherit font size.
*/
if (!truncate && Array.isArray(children)) {
content = external_wp_element_namespaceObject.Children.map(children, child => {
if (typeof child !== 'object' || child === null || !('props' in child)) {
return child;
}
const isLink = hasConnectNamespace(child, ['Link']);
if (isLink) {
return (0,external_wp_element_namespaceObject.cloneElement)(child, {
size: child.props.size || 'inherit'
});
}
return child;
});
}
return { ...truncateProps,
children: truncate ? truncateProps.children : content
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/text/component.js
/**
* Internal dependencies
*/
/**
* @param {import('../ui/context').WordPressComponentProps<import('./types').Props, 'span'>} props
* @param {import('react').ForwardedRef<any>} forwardedRef
*/
function component_Text(props, forwardedRef) {
const textProps = useText(props);
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({
as: "span"
}, textProps, {
ref: forwardedRef
}));
}
/**
* `Text` is a core component that renders text in the library, using the
* library's typography system.
*
* `Text` can be used to render any text-content, like an HTML `p` or `span`.
*
* @example
*
* ```jsx
* import { __experimentalText as Text } from `@wordpress/components`;
*
* function Example() {
* return <Text>Code is Poetry</Text>;
* }
* ```
*/
const ConnectedText = contextConnect(component_Text, 'Text');
/* harmony default export */ var text_component = (ConnectedText);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/base-label.js
function base_label_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
// This is a very low-level mixin which you shouldn't have to use directly.
// Try to use BaseControl's StyledLabel or BaseControl.VisualLabel if you can.
const baseLabelTypography = true ? {
name: "9amh4a",
styles: "font-size:11px;font-weight:500;line-height:1.4;text-transform:uppercase"
} : 0;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/rtl.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
const LOWER_LEFT_REGEXP = new RegExp(/-left/g);
const LOWER_RIGHT_REGEXP = new RegExp(/-right/g);
const UPPER_LEFT_REGEXP = new RegExp(/Left/g);
const UPPER_RIGHT_REGEXP = new RegExp(/Right/g);
/**
* Flips a CSS property from left <-> right.
*
* @param {string} key The CSS property name.
*
* @return {string} The flipped CSS property name, if applicable.
*/
function getConvertedKey(key) {
if (key === 'left') {
return 'right';
}
if (key === 'right') {
return 'left';
}
if (LOWER_LEFT_REGEXP.test(key)) {
return key.replace(LOWER_LEFT_REGEXP, '-right');
}
if (LOWER_RIGHT_REGEXP.test(key)) {
return key.replace(LOWER_RIGHT_REGEXP, '-left');
}
if (UPPER_LEFT_REGEXP.test(key)) {
return key.replace(UPPER_LEFT_REGEXP, 'Right');
}
if (UPPER_RIGHT_REGEXP.test(key)) {
return key.replace(UPPER_RIGHT_REGEXP, 'Left');
}
return key;
}
/**
* An incredibly basic ltr -> rtl converter for style properties
*
* @param {import('react').CSSProperties} ltrStyles
*
* @return {import('react').CSSProperties} Converted ltr -> rtl styles
*/
const convertLTRToRTL = function () {
let ltrStyles = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return Object.fromEntries(Object.entries(ltrStyles).map(_ref => {
let [key, value] = _ref;
return [getConvertedKey(key), value];
}));
};
/**
* A higher-order function that create an incredibly basic ltr -> rtl style converter for CSS objects.
*
* @param {import('react').CSSProperties} ltrStyles Ltr styles. Converts and renders from ltr -> rtl styles, if applicable.
* @param {import('react').CSSProperties} [rtlStyles] Rtl styles. Renders if provided.
*
* @return {() => import('@emotion/react').SerializedStyles} A function to output CSS styles for Emotion's renderer
*/
function rtl() {
let ltrStyles = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let rtlStyles = arguments.length > 1 ? arguments[1] : undefined;
return () => {
if (rtlStyles) {
// @ts-ignore: `css` types are wrong, it can accept an object: https://emotion.sh/docs/object-styles#with-css
return (0,external_wp_i18n_namespaceObject.isRTL)() ? /*#__PURE__*/emotion_react_browser_esm_css(rtlStyles, true ? "" : 0) : /*#__PURE__*/emotion_react_browser_esm_css(ltrStyles, true ? "" : 0);
} // @ts-ignore: `css` types are wrong, it can accept an object: https://emotion.sh/docs/object-styles#with-css
return (0,external_wp_i18n_namespaceObject.isRTL)() ? /*#__PURE__*/emotion_react_browser_esm_css(convertLTRToRTL(ltrStyles), true ? "" : 0) : /*#__PURE__*/emotion_react_browser_esm_css(ltrStyles, true ? "" : 0);
};
}
/**
* Call this in the `useMemo` dependency array to ensure that subsequent renders will
* cause rtl styles to update based on the `isRTL` return value even if all other dependencies
* remain the same.
*
* @example
* const styles = useMemo( () => {
* return css`
* ${ rtl( { marginRight: '10px' } ) }
* `;
* }, [ rtl.watch() ] );
*/
rtl.watch = () => (0,external_wp_i18n_namespaceObject.isRTL)();
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/styles/input-control-styles.js
function input_control_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
var _ref2 = true ? {
name: "1739oy8",
styles: "z-index:1"
} : 0;
const rootFocusedStyles = _ref3 => {
let {
isFocused
} = _ref3;
if (!isFocused) return '';
return _ref2;
};
const input_control_styles_Root = /*#__PURE__*/createStyled(flex_component, true ? {
target: "em5sgkm7"
} : 0)("box-sizing:border-box;position:relative;border-radius:2px;padding-top:0;", rootFocusedStyles, ";" + ( true ? "" : 0));
const containerDisabledStyles = _ref4 => {
let {
disabled
} = _ref4;
const backgroundColor = disabled ? COLORS.ui.backgroundDisabled : COLORS.ui.background;
return /*#__PURE__*/emotion_react_browser_esm_css({
backgroundColor
}, true ? "" : 0, true ? "" : 0);
};
var input_control_styles_ref = true ? {
name: "1d3w5wq",
styles: "width:100%"
} : 0;
const containerWidthStyles = _ref5 => {
let {
__unstableInputWidth,
labelPosition
} = _ref5;
if (!__unstableInputWidth) return input_control_styles_ref;
if (labelPosition === 'side') return '';
if (labelPosition === 'edge') {
return /*#__PURE__*/emotion_react_browser_esm_css({
flex: `0 0 ${__unstableInputWidth}`
}, true ? "" : 0, true ? "" : 0);
}
return /*#__PURE__*/emotion_react_browser_esm_css({
width: __unstableInputWidth
}, true ? "" : 0, true ? "" : 0);
};
const Container = createStyled("div", true ? {
target: "em5sgkm6"
} : 0)("align-items:center;box-sizing:border-box;border-radius:inherit;display:flex;flex:1;position:relative;", containerDisabledStyles, " ", containerWidthStyles, ";" + ( true ? "" : 0));
const disabledStyles = _ref6 => {
let {
disabled
} = _ref6;
if (!disabled) return '';
return /*#__PURE__*/emotion_react_browser_esm_css({
color: COLORS.ui.textDisabled
}, true ? "" : 0, true ? "" : 0);
};
const fontSizeStyles = _ref7 => {
let {
inputSize: size
} = _ref7;
const sizes = {
default: '13px',
small: '11px',
'__unstable-large': '13px'
};
const fontSize = sizes[size] || sizes.default;
const fontSizeMobile = '16px';
if (!fontSize) return '';
return /*#__PURE__*/emotion_react_browser_esm_css("font-size:", fontSizeMobile, ";@media ( min-width: 600px ){font-size:", fontSize, ";}" + ( true ? "" : 0), true ? "" : 0);
};
const getSizeConfig = _ref8 => {
let {
inputSize: size,
__next36pxDefaultSize
} = _ref8;
// Paddings may be overridden by the custom paddings props.
const sizes = {
default: {
height: 36,
lineHeight: 1,
minHeight: 36,
paddingLeft: space(4),
paddingRight: space(4)
},
small: {
height: 24,
lineHeight: 1,
minHeight: 24,
paddingLeft: space(2),
paddingRight: space(2)
},
'__unstable-large': {
height: 40,
lineHeight: 1,
minHeight: 40,
paddingLeft: space(4),
paddingRight: space(4)
}
};
if (!__next36pxDefaultSize) {
sizes.default = {
height: 30,
lineHeight: 1,
minHeight: 30,
paddingLeft: space(2),
paddingRight: space(2)
};
}
return sizes[size] || sizes.default;
};
const sizeStyles = props => {
return /*#__PURE__*/emotion_react_browser_esm_css(getSizeConfig(props), true ? "" : 0, true ? "" : 0);
};
const customPaddings = _ref9 => {
let {
paddingInlineStart,
paddingInlineEnd
} = _ref9;
return /*#__PURE__*/emotion_react_browser_esm_css({
paddingInlineStart,
paddingInlineEnd
}, true ? "" : 0, true ? "" : 0);
};
const dragStyles = _ref10 => {
let {
isDragging,
dragCursor
} = _ref10;
let defaultArrowStyles;
let activeDragCursorStyles;
if (isDragging) {
defaultArrowStyles = /*#__PURE__*/emotion_react_browser_esm_css("cursor:", dragCursor, ";user-select:none;&::-webkit-outer-spin-button,&::-webkit-inner-spin-button{-webkit-appearance:none!important;margin:0!important;}" + ( true ? "" : 0), true ? "" : 0);
}
if (isDragging && dragCursor) {
activeDragCursorStyles = /*#__PURE__*/emotion_react_browser_esm_css("&:active{cursor:", dragCursor, ";}" + ( true ? "" : 0), true ? "" : 0);
}
return /*#__PURE__*/emotion_react_browser_esm_css(defaultArrowStyles, " ", activeDragCursorStyles, ";" + ( true ? "" : 0), true ? "" : 0);
}; // TODO: Resolve need to use &&& to increase specificity
// https://github.com/WordPress/gutenberg/issues/18483
const Input = createStyled("input", true ? {
target: "em5sgkm5"
} : 0)("&&&{background-color:transparent;box-sizing:border-box;border:none;box-shadow:none!important;color:", COLORS.gray[900], ";display:block;font-family:inherit;margin:0;outline:none;width:100%;", dragStyles, " ", disabledStyles, " ", fontSizeStyles, " ", sizeStyles, " ", customPaddings, " &::-webkit-input-placeholder{line-height:normal;}}" + ( true ? "" : 0));
const BaseLabel = /*#__PURE__*/createStyled(text_component, true ? {
target: "em5sgkm4"
} : 0)("&&&{", baseLabelTypography, ";box-sizing:border-box;display:block;padding-top:0;padding-bottom:0;max-width:100%;z-index:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}" + ( true ? "" : 0));
const Label = props => (0,external_wp_element_namespaceObject.createElement)(BaseLabel, extends_extends({}, props, {
as: "label"
}));
const LabelWrapper = /*#__PURE__*/createStyled(flex_item_component, true ? {
target: "em5sgkm3"
} : 0)( true ? {
name: "1b6uupn",
styles: "max-width:calc( 100% - 10px )"
} : 0);
const backdropFocusedStyles = _ref11 => {
let {
disabled,
isFocused
} = _ref11;
let borderColor = isFocused ? COLORS.ui.borderFocus : COLORS.ui.border;
let boxShadow;
if (isFocused) {
boxShadow = `0 0 0 1px ${COLORS.ui.borderFocus} inset`;
}
if (disabled) {
borderColor = COLORS.ui.borderDisabled;
}
return /*#__PURE__*/emotion_react_browser_esm_css({
boxShadow,
borderColor,
borderStyle: 'solid',
borderWidth: 1
}, true ? "" : 0, true ? "" : 0);
};
const BackdropUI = createStyled("div", true ? {
target: "em5sgkm2"
} : 0)("&&&{box-sizing:border-box;border-radius:inherit;bottom:0;left:0;margin:0;padding:0;pointer-events:none;position:absolute;right:0;top:0;", backdropFocusedStyles, " ", rtl({
paddingLeft: 2
}), ";}" + ( true ? "" : 0));
const Prefix = createStyled("span", true ? {
target: "em5sgkm1"
} : 0)( true ? {
name: "pvvbxf",
styles: "box-sizing:border-box;display:block"
} : 0);
const Suffix = createStyled("span", true ? {
target: "em5sgkm0"
} : 0)( true ? {
name: "jgf79h",
styles: "align-items:center;align-self:stretch;box-sizing:border-box;display:flex"
} : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/backdrop.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function Backdrop(_ref) {
let {
disabled = false,
isFocused = false
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(BackdropUI, {
"aria-hidden": "true",
className: "components-input-control__backdrop",
disabled: disabled,
isFocused: isFocused
});
}
const MemoizedBackdrop = (0,external_wp_element_namespaceObject.memo)(Backdrop);
/* harmony default export */ var backdrop = (MemoizedBackdrop);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/label.js
/**
* Internal dependencies
*/
function label_Label(_ref) {
let {
children,
hideLabelFromVision,
htmlFor,
...props
} = _ref;
if (!children) return null;
if (hideLabelFromVision) {
return (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, {
as: "label",
htmlFor: htmlFor
}, children);
}
return (0,external_wp_element_namespaceObject.createElement)(LabelWrapper, null, (0,external_wp_element_namespaceObject.createElement)(Label, extends_extends({
htmlFor: htmlFor
}, props), children));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/input-base.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useUniqueId(idProp) {
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(InputBase);
const id = `input-base-control-${instanceId}`;
return idProp || id;
} // Adapter to map props for the new ui/flex component.
function getUIFlexProps(labelPosition) {
const props = {};
switch (labelPosition) {
case 'top':
props.direction = 'column';
props.expanded = false;
props.gap = 0;
break;
case 'bottom':
props.direction = 'column-reverse';
props.expanded = false;
props.gap = 0;
break;
case 'edge':
props.justify = 'space-between';
break;
}
return props;
}
function InputBase(_ref, ref) {
let {
__next36pxDefaultSize,
__unstableInputWidth,
children,
className,
disabled = false,
hideLabelFromVision = false,
labelPosition,
id: idProp,
isFocused = false,
label,
prefix,
size = 'default',
suffix,
...props
} = _ref;
const id = useUniqueId(idProp);
const hideLabel = hideLabelFromVision || !label;
const {
paddingLeft,
paddingRight
} = getSizeConfig({
inputSize: size,
__next36pxDefaultSize
});
const prefixSuffixContextValue = (0,external_wp_element_namespaceObject.useMemo)(() => {
return {
InputControlPrefixWrapper: {
paddingLeft
},
InputControlSuffixWrapper: {
paddingRight
}
};
}, [paddingLeft, paddingRight]);
return (// @ts-expect-error The `direction` prop from Flex (FlexDirection) conflicts with legacy SVGAttributes `direction` (string) that come from React intrinsic prop definitions.
(0,external_wp_element_namespaceObject.createElement)(input_control_styles_Root, extends_extends({}, props, getUIFlexProps(labelPosition), {
className: className,
gap: 2,
isFocused: isFocused,
labelPosition: labelPosition,
ref: ref
}), (0,external_wp_element_namespaceObject.createElement)(label_Label, {
className: "components-input-control__label",
hideLabelFromVision: hideLabelFromVision,
labelPosition: labelPosition,
htmlFor: id
}, label), (0,external_wp_element_namespaceObject.createElement)(Container, {
__unstableInputWidth: __unstableInputWidth,
className: "components-input-control__container",
disabled: disabled,
hideLabel: hideLabel,
labelPosition: labelPosition
}, (0,external_wp_element_namespaceObject.createElement)(ContextSystemProvider, {
value: prefixSuffixContextValue
}, prefix && (0,external_wp_element_namespaceObject.createElement)(Prefix, {
className: "components-input-control__prefix"
}, prefix), children, suffix && (0,external_wp_element_namespaceObject.createElement)(Suffix, {
className: "components-input-control__suffix"
}, suffix)), (0,external_wp_element_namespaceObject.createElement)(backdrop, {
disabled: disabled,
isFocused: isFocused
})))
);
}
/* harmony default export */ var input_base = ((0,external_wp_element_namespaceObject.forwardRef)(InputBase));
;// CONCATENATED MODULE: ./node_modules/@use-gesture/core/dist/maths-0ab39ae9.esm.js
function maths_0ab39ae9_esm_clamp(v, min, max) {
return Math.max(min, Math.min(v, max));
}
const V = {
toVector(v, fallback) {
if (v === undefined) v = fallback;
return Array.isArray(v) ? v : [v, v];
},
add(v1, v2) {
return [v1[0] + v2[0], v1[1] + v2[1]];
},
sub(v1, v2) {
return [v1[0] - v2[0], v1[1] - v2[1]];
},
addTo(v1, v2) {
v1[0] += v2[0];
v1[1] += v2[1];
},
subTo(v1, v2) {
v1[0] -= v2[0];
v1[1] -= v2[1];
}
};
function rubberband(distance, dimension, constant) {
if (dimension === 0 || Math.abs(dimension) === Infinity) return Math.pow(distance, constant * 5);
return distance * dimension * constant / (dimension + constant * distance);
}
function rubberbandIfOutOfBounds(position, min, max, constant = 0.15) {
if (constant === 0) return maths_0ab39ae9_esm_clamp(position, min, max);
if (position < min) return -rubberband(min - position, max - min, constant) + min;
if (position > max) return +rubberband(position - max, max - min, constant) + max;
return position;
}
function computeRubberband(bounds, [Vx, Vy], [Rx, Ry]) {
const [[X0, X1], [Y0, Y1]] = bounds;
return [rubberbandIfOutOfBounds(Vx, X0, X1, Rx), rubberbandIfOutOfBounds(Vy, Y0, Y1, Ry)];
}
;// CONCATENATED MODULE: ./node_modules/@use-gesture/core/dist/actions-fe213e88.esm.js
function _toPrimitive(input, hint) {
if (typeof input !== "object" || input === null) return input;
var prim = input[Symbol.toPrimitive];
if (prim !== undefined) {
var res = prim.call(input, hint || "default");
if (typeof res !== "object") return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
function _toPropertyKey(arg) {
var key = _toPrimitive(arg, "string");
return typeof key === "symbol" ? key : String(key);
}
function actions_fe213e88_esm_defineProperty(obj, key, value) {
key = _toPropertyKey(key);
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function actions_fe213e88_esm_ownKeys(e, r) {
var t = Object.keys(e);
if (Object.getOwnPropertySymbols) {
var o = Object.getOwnPropertySymbols(e);
r && (o = o.filter(function (r) {
return Object.getOwnPropertyDescriptor(e, r).enumerable;
})), t.push.apply(t, o);
}
return t;
}
function actions_fe213e88_esm_objectSpread2(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? actions_fe213e88_esm_ownKeys(Object(t), !0).forEach(function (r) {
actions_fe213e88_esm_defineProperty(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : actions_fe213e88_esm_ownKeys(Object(t)).forEach(function (r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
const EVENT_TYPE_MAP = {
pointer: {
start: 'down',
change: 'move',
end: 'up'
},
mouse: {
start: 'down',
change: 'move',
end: 'up'
},
touch: {
start: 'start',
change: 'move',
end: 'end'
},
gesture: {
start: 'start',
change: 'change',
end: 'end'
}
};
function capitalize(string) {
if (!string) return '';
return string[0].toUpperCase() + string.slice(1);
}
const actionsWithoutCaptureSupported = ['enter', 'leave'];
function hasCapture(capture = false, actionKey) {
return capture && !actionsWithoutCaptureSupported.includes(actionKey);
}
function toHandlerProp(device, action = '', capture = false) {
const deviceProps = EVENT_TYPE_MAP[device];
const actionKey = deviceProps ? deviceProps[action] || action : action;
return 'on' + capitalize(device) + capitalize(actionKey) + (hasCapture(capture, actionKey) ? 'Capture' : '');
}
const pointerCaptureEvents = ['gotpointercapture', 'lostpointercapture'];
function parseProp(prop) {
let eventKey = prop.substring(2).toLowerCase();
const passive = !!~eventKey.indexOf('passive');
if (passive) eventKey = eventKey.replace('passive', '');
const captureKey = pointerCaptureEvents.includes(eventKey) ? 'capturecapture' : 'capture';
const capture = !!~eventKey.indexOf(captureKey);
if (capture) eventKey = eventKey.replace('capture', '');
return {
device: eventKey,
capture,
passive
};
}
function toDomEventType(device, action = '') {
const deviceProps = EVENT_TYPE_MAP[device];
const actionKey = deviceProps ? deviceProps[action] || action : action;
return device + actionKey;
}
function isTouch(event) {
return 'touches' in event;
}
function getPointerType(event) {
if (isTouch(event)) return 'touch';
if ('pointerType' in event) return event.pointerType;
return 'mouse';
}
function getCurrentTargetTouchList(event) {
return Array.from(event.touches).filter(e => {
var _event$currentTarget, _event$currentTarget$;
return e.target === event.currentTarget || ((_event$currentTarget = event.currentTarget) === null || _event$currentTarget === void 0 || (_event$currentTarget$ = _event$currentTarget.contains) === null || _event$currentTarget$ === void 0 ? void 0 : _event$currentTarget$.call(_event$currentTarget, e.target));
});
}
function getTouchList(event) {
return event.type === 'touchend' || event.type === 'touchcancel' ? event.changedTouches : event.targetTouches;
}
function getValueEvent(event) {
return isTouch(event) ? getTouchList(event)[0] : event;
}
function distanceAngle(P1, P2) {
try {
const dx = P2.clientX - P1.clientX;
const dy = P2.clientY - P1.clientY;
const cx = (P2.clientX + P1.clientX) / 2;
const cy = (P2.clientY + P1.clientY) / 2;
const distance = Math.hypot(dx, dy);
const angle = -(Math.atan2(dx, dy) * 180) / Math.PI;
const origin = [cx, cy];
return {
angle,
distance,
origin
};
} catch (_unused) {}
return null;
}
function touchIds(event) {
return getCurrentTargetTouchList(event).map(touch => touch.identifier);
}
function touchDistanceAngle(event, ids) {
const [P1, P2] = Array.from(event.touches).filter(touch => ids.includes(touch.identifier));
return distanceAngle(P1, P2);
}
function pointerId(event) {
const valueEvent = getValueEvent(event);
return isTouch(event) ? valueEvent.identifier : valueEvent.pointerId;
}
function pointerValues(event) {
const valueEvent = getValueEvent(event);
return [valueEvent.clientX, valueEvent.clientY];
}
const LINE_HEIGHT = 40;
const PAGE_HEIGHT = 800;
function wheelValues(event) {
let {
deltaX,
deltaY,
deltaMode
} = event;
if (deltaMode === 1) {
deltaX *= LINE_HEIGHT;
deltaY *= LINE_HEIGHT;
} else if (deltaMode === 2) {
deltaX *= PAGE_HEIGHT;
deltaY *= PAGE_HEIGHT;
}
return [deltaX, deltaY];
}
function scrollValues(event) {
var _ref, _ref2;
const {
scrollX,
scrollY,
scrollLeft,
scrollTop
} = event.currentTarget;
return [(_ref = scrollX !== null && scrollX !== void 0 ? scrollX : scrollLeft) !== null && _ref !== void 0 ? _ref : 0, (_ref2 = scrollY !== null && scrollY !== void 0 ? scrollY : scrollTop) !== null && _ref2 !== void 0 ? _ref2 : 0];
}
function getEventDetails(event) {
const payload = {};
if ('buttons' in event) payload.buttons = event.buttons;
if ('shiftKey' in event) {
const {
shiftKey,
altKey,
metaKey,
ctrlKey
} = event;
Object.assign(payload, {
shiftKey,
altKey,
metaKey,
ctrlKey
});
}
return payload;
}
function call(v, ...args) {
if (typeof v === 'function') {
return v(...args);
} else {
return v;
}
}
function actions_fe213e88_esm_noop() {}
function chain(...fns) {
if (fns.length === 0) return actions_fe213e88_esm_noop;
if (fns.length === 1) return fns[0];
return function () {
let result;
for (const fn of fns) {
result = fn.apply(this, arguments) || result;
}
return result;
};
}
function assignDefault(value, fallback) {
return Object.assign({}, fallback, value || {});
}
const BEFORE_LAST_KINEMATICS_DELAY = 32;
class Engine {
constructor(ctrl, args, key) {
this.ctrl = ctrl;
this.args = args;
this.key = key;
if (!this.state) {
this.state = {};
this.computeValues([0, 0]);
this.computeInitial();
if (this.init) this.init();
this.reset();
}
}
get state() {
return this.ctrl.state[this.key];
}
set state(state) {
this.ctrl.state[this.key] = state;
}
get shared() {
return this.ctrl.state.shared;
}
get eventStore() {
return this.ctrl.gestureEventStores[this.key];
}
get timeoutStore() {
return this.ctrl.gestureTimeoutStores[this.key];
}
get config() {
return this.ctrl.config[this.key];
}
get sharedConfig() {
return this.ctrl.config.shared;
}
get handler() {
return this.ctrl.handlers[this.key];
}
reset() {
const {
state,
shared,
ingKey,
args
} = this;
shared[ingKey] = state._active = state.active = state._blocked = state._force = false;
state._step = [false, false];
state.intentional = false;
state._movement = [0, 0];
state._distance = [0, 0];
state._direction = [0, 0];
state._delta = [0, 0];
state._bounds = [[-Infinity, Infinity], [-Infinity, Infinity]];
state.args = args;
state.axis = undefined;
state.memo = undefined;
state.elapsedTime = state.timeDelta = 0;
state.direction = [0, 0];
state.distance = [0, 0];
state.overflow = [0, 0];
state._movementBound = [false, false];
state.velocity = [0, 0];
state.movement = [0, 0];
state.delta = [0, 0];
state.timeStamp = 0;
}
start(event) {
const state = this.state;
const config = this.config;
if (!state._active) {
this.reset();
this.computeInitial();
state._active = true;
state.target = event.target;
state.currentTarget = event.currentTarget;
state.lastOffset = config.from ? call(config.from, state) : state.offset;
state.offset = state.lastOffset;
state.startTime = state.timeStamp = event.timeStamp;
}
}
computeValues(values) {
const state = this.state;
state._values = values;
state.values = this.config.transform(values);
}
computeInitial() {
const state = this.state;
state._initial = state._values;
state.initial = state.values;
}
compute(event) {
const {
state,
config,
shared
} = this;
state.args = this.args;
let dt = 0;
if (event) {
state.event = event;
if (config.preventDefault && event.cancelable) state.event.preventDefault();
state.type = event.type;
shared.touches = this.ctrl.pointerIds.size || this.ctrl.touchIds.size;
shared.locked = !!document.pointerLockElement;
Object.assign(shared, getEventDetails(event));
shared.down = shared.pressed = shared.buttons % 2 === 1 || shared.touches > 0;
dt = event.timeStamp - state.timeStamp;
state.timeStamp = event.timeStamp;
state.elapsedTime = state.timeStamp - state.startTime;
}
if (state._active) {
const _absoluteDelta = state._delta.map(Math.abs);
V.addTo(state._distance, _absoluteDelta);
}
if (this.axisIntent) this.axisIntent(event);
const [_m0, _m1] = state._movement;
const [t0, t1] = config.threshold;
const {
_step,
values
} = state;
if (config.hasCustomTransform) {
if (_step[0] === false) _step[0] = Math.abs(_m0) >= t0 && values[0];
if (_step[1] === false) _step[1] = Math.abs(_m1) >= t1 && values[1];
} else {
if (_step[0] === false) _step[0] = Math.abs(_m0) >= t0 && Math.sign(_m0) * t0;
if (_step[1] === false) _step[1] = Math.abs(_m1) >= t1 && Math.sign(_m1) * t1;
}
state.intentional = _step[0] !== false || _step[1] !== false;
if (!state.intentional) return;
const movement = [0, 0];
if (config.hasCustomTransform) {
const [v0, v1] = values;
movement[0] = _step[0] !== false ? v0 - _step[0] : 0;
movement[1] = _step[1] !== false ? v1 - _step[1] : 0;
} else {
movement[0] = _step[0] !== false ? _m0 - _step[0] : 0;
movement[1] = _step[1] !== false ? _m1 - _step[1] : 0;
}
if (this.restrictToAxis && !state._blocked) this.restrictToAxis(movement);
const previousOffset = state.offset;
const gestureIsActive = state._active && !state._blocked || state.active;
if (gestureIsActive) {
state.first = state._active && !state.active;
state.last = !state._active && state.active;
state.active = shared[this.ingKey] = state._active;
if (event) {
if (state.first) {
if ('bounds' in config) state._bounds = call(config.bounds, state);
if (this.setup) this.setup();
}
state.movement = movement;
this.computeOffset();
}
}
const [ox, oy] = state.offset;
const [[x0, x1], [y0, y1]] = state._bounds;
state.overflow = [ox < x0 ? -1 : ox > x1 ? 1 : 0, oy < y0 ? -1 : oy > y1 ? 1 : 0];
state._movementBound[0] = state.overflow[0] ? state._movementBound[0] === false ? state._movement[0] : state._movementBound[0] : false;
state._movementBound[1] = state.overflow[1] ? state._movementBound[1] === false ? state._movement[1] : state._movementBound[1] : false;
const rubberband = state._active ? config.rubberband || [0, 0] : [0, 0];
state.offset = computeRubberband(state._bounds, state.offset, rubberband);
state.delta = V.sub(state.offset, previousOffset);
this.computeMovement();
if (gestureIsActive && (!state.last || dt > BEFORE_LAST_KINEMATICS_DELAY)) {
state.delta = V.sub(state.offset, previousOffset);
const absoluteDelta = state.delta.map(Math.abs);
V.addTo(state.distance, absoluteDelta);
state.direction = state.delta.map(Math.sign);
state._direction = state._delta.map(Math.sign);
if (!state.first && dt > 0) {
state.velocity = [absoluteDelta[0] / dt, absoluteDelta[1] / dt];
state.timeDelta = dt;
}
}
}
emit() {
const state = this.state;
const shared = this.shared;
const config = this.config;
if (!state._active) this.clean();
if ((state._blocked || !state.intentional) && !state._force && !config.triggerAllEvents) return;
const memo = this.handler(actions_fe213e88_esm_objectSpread2(actions_fe213e88_esm_objectSpread2(actions_fe213e88_esm_objectSpread2({}, shared), state), {}, {
[this.aliasKey]: state.values
}));
if (memo !== undefined) state.memo = memo;
}
clean() {
this.eventStore.clean();
this.timeoutStore.clean();
}
}
function selectAxis([dx, dy], threshold) {
const absDx = Math.abs(dx);
const absDy = Math.abs(dy);
if (absDx > absDy && absDx > threshold) {
return 'x';
}
if (absDy > absDx && absDy > threshold) {
return 'y';
}
return undefined;
}
class CoordinatesEngine extends Engine {
constructor(...args) {
super(...args);
actions_fe213e88_esm_defineProperty(this, "aliasKey", 'xy');
}
reset() {
super.reset();
this.state.axis = undefined;
}
init() {
this.state.offset = [0, 0];
this.state.lastOffset = [0, 0];
}
computeOffset() {
this.state.offset = V.add(this.state.lastOffset, this.state.movement);
}
computeMovement() {
this.state.movement = V.sub(this.state.offset, this.state.lastOffset);
}
axisIntent(event) {
const state = this.state;
const config = this.config;
if (!state.axis && event) {
const threshold = typeof config.axisThreshold === 'object' ? config.axisThreshold[getPointerType(event)] : config.axisThreshold;
state.axis = selectAxis(state._movement, threshold);
}
state._blocked = (config.lockDirection || !!config.axis) && !state.axis || !!config.axis && config.axis !== state.axis;
}
restrictToAxis(v) {
if (this.config.axis || this.config.lockDirection) {
switch (this.state.axis) {
case 'x':
v[1] = 0;
break;
case 'y':
v[0] = 0;
break;
}
}
}
}
const identity = v => v;
const DEFAULT_RUBBERBAND = 0.15;
const commonConfigResolver = {
enabled(value = true) {
return value;
},
eventOptions(value, _k, config) {
return actions_fe213e88_esm_objectSpread2(actions_fe213e88_esm_objectSpread2({}, config.shared.eventOptions), value);
},
preventDefault(value = false) {
return value;
},
triggerAllEvents(value = false) {
return value;
},
rubberband(value = 0) {
switch (value) {
case true:
return [DEFAULT_RUBBERBAND, DEFAULT_RUBBERBAND];
case false:
return [0, 0];
default:
return V.toVector(value);
}
},
from(value) {
if (typeof value === 'function') return value;
if (value != null) return V.toVector(value);
},
transform(value, _k, config) {
const transform = value || config.shared.transform;
this.hasCustomTransform = !!transform;
if (false) {}
return transform || identity;
},
threshold(value) {
return V.toVector(value, 0);
}
};
if (false) {}
const DEFAULT_AXIS_THRESHOLD = 0;
const coordinatesConfigResolver = actions_fe213e88_esm_objectSpread2(actions_fe213e88_esm_objectSpread2({}, commonConfigResolver), {}, {
axis(_v, _k, {
axis
}) {
this.lockDirection = axis === 'lock';
if (!this.lockDirection) return axis;
},
axisThreshold(value = DEFAULT_AXIS_THRESHOLD) {
return value;
},
bounds(value = {}) {
if (typeof value === 'function') {
return state => coordinatesConfigResolver.bounds(value(state));
}
if ('current' in value) {
return () => value.current;
}
if (typeof HTMLElement === 'function' && value instanceof HTMLElement) {
return value;
}
const {
left = -Infinity,
right = Infinity,
top = -Infinity,
bottom = Infinity
} = value;
return [[left, right], [top, bottom]];
}
});
const KEYS_DELTA_MAP = {
ArrowRight: (displacement, factor = 1) => [displacement * factor, 0],
ArrowLeft: (displacement, factor = 1) => [-1 * displacement * factor, 0],
ArrowUp: (displacement, factor = 1) => [0, -1 * displacement * factor],
ArrowDown: (displacement, factor = 1) => [0, displacement * factor]
};
class DragEngine extends CoordinatesEngine {
constructor(...args) {
super(...args);
actions_fe213e88_esm_defineProperty(this, "ingKey", 'dragging');
}
reset() {
super.reset();
const state = this.state;
state._pointerId = undefined;
state._pointerActive = false;
state._keyboardActive = false;
state._preventScroll = false;
state._delayed = false;
state.swipe = [0, 0];
state.tap = false;
state.canceled = false;
state.cancel = this.cancel.bind(this);
}
setup() {
const state = this.state;
if (state._bounds instanceof HTMLElement) {
const boundRect = state._bounds.getBoundingClientRect();
const targetRect = state.currentTarget.getBoundingClientRect();
const _bounds = {
left: boundRect.left - targetRect.left + state.offset[0],
right: boundRect.right - targetRect.right + state.offset[0],
top: boundRect.top - targetRect.top + state.offset[1],
bottom: boundRect.bottom - targetRect.bottom + state.offset[1]
};
state._bounds = coordinatesConfigResolver.bounds(_bounds);
}
}
cancel() {
const state = this.state;
if (state.canceled) return;
state.canceled = true;
state._active = false;
setTimeout(() => {
this.compute();
this.emit();
}, 0);
}
setActive() {
this.state._active = this.state._pointerActive || this.state._keyboardActive;
}
clean() {
this.pointerClean();
this.state._pointerActive = false;
this.state._keyboardActive = false;
super.clean();
}
pointerDown(event) {
const config = this.config;
const state = this.state;
if (event.buttons != null && (Array.isArray(config.pointerButtons) ? !config.pointerButtons.includes(event.buttons) : config.pointerButtons !== -1 && config.pointerButtons !== event.buttons)) return;
const ctrlIds = this.ctrl.setEventIds(event);
if (config.pointerCapture) {
event.target.setPointerCapture(event.pointerId);
}
if (ctrlIds && ctrlIds.size > 1 && state._pointerActive) return;
this.start(event);
this.setupPointer(event);
state._pointerId = pointerId(event);
state._pointerActive = true;
this.computeValues(pointerValues(event));
this.computeInitial();
if (config.preventScrollAxis && getPointerType(event) !== 'mouse') {
state._active = false;
this.setupScrollPrevention(event);
} else if (config.delay > 0) {
this.setupDelayTrigger(event);
if (config.triggerAllEvents) {
this.compute(event);
this.emit();
}
} else {
this.startPointerDrag(event);
}
}
startPointerDrag(event) {
const state = this.state;
state._active = true;
state._preventScroll = true;
state._delayed = false;
this.compute(event);
this.emit();
}
pointerMove(event) {
const state = this.state;
const config = this.config;
if (!state._pointerActive) return;
const id = pointerId(event);
if (state._pointerId !== undefined && id !== state._pointerId) return;
const _values = pointerValues(event);
if (document.pointerLockElement === event.target) {
state._delta = [event.movementX, event.movementY];
} else {
state._delta = V.sub(_values, state._values);
this.computeValues(_values);
}
V.addTo(state._movement, state._delta);
this.compute(event);
if (state._delayed && state.intentional) {
this.timeoutStore.remove('dragDelay');
state.active = false;
this.startPointerDrag(event);
return;
}
if (config.preventScrollAxis && !state._preventScroll) {
if (state.axis) {
if (state.axis === config.preventScrollAxis || config.preventScrollAxis === 'xy') {
state._active = false;
this.clean();
return;
} else {
this.timeoutStore.remove('startPointerDrag');
this.startPointerDrag(event);
return;
}
} else {
return;
}
}
this.emit();
}
pointerUp(event) {
this.ctrl.setEventIds(event);
try {
if (this.config.pointerCapture && event.target.hasPointerCapture(event.pointerId)) {
;
event.target.releasePointerCapture(event.pointerId);
}
} catch (_unused) {
if (false) {}
}
const state = this.state;
const config = this.config;
if (!state._active || !state._pointerActive) return;
const id = pointerId(event);
if (state._pointerId !== undefined && id !== state._pointerId) return;
this.state._pointerActive = false;
this.setActive();
this.compute(event);
const [dx, dy] = state._distance;
state.tap = dx <= config.tapsThreshold && dy <= config.tapsThreshold;
if (state.tap && config.filterTaps) {
state._force = true;
} else {
const [_dx, _dy] = state._delta;
const [_mx, _my] = state._movement;
const [svx, svy] = config.swipe.velocity;
const [sx, sy] = config.swipe.distance;
const sdt = config.swipe.duration;
if (state.elapsedTime < sdt) {
const _vx = Math.abs(_dx / state.timeDelta);
const _vy = Math.abs(_dy / state.timeDelta);
if (_vx > svx && Math.abs(_mx) > sx) state.swipe[0] = Math.sign(_dx);
if (_vy > svy && Math.abs(_my) > sy) state.swipe[1] = Math.sign(_dy);
}
}
this.emit();
}
pointerClick(event) {
if (!this.state.tap && event.detail > 0) {
event.preventDefault();
event.stopPropagation();
}
}
setupPointer(event) {
const config = this.config;
const device = config.device;
if (false) {}
if (config.pointerLock) {
event.currentTarget.requestPointerLock();
}
if (!config.pointerCapture) {
this.eventStore.add(this.sharedConfig.window, device, 'change', this.pointerMove.bind(this));
this.eventStore.add(this.sharedConfig.window, device, 'end', this.pointerUp.bind(this));
this.eventStore.add(this.sharedConfig.window, device, 'cancel', this.pointerUp.bind(this));
}
}
pointerClean() {
if (this.config.pointerLock && document.pointerLockElement === this.state.currentTarget) {
document.exitPointerLock();
}
}
preventScroll(event) {
if (this.state._preventScroll && event.cancelable) {
event.preventDefault();
}
}
setupScrollPrevention(event) {
this.state._preventScroll = false;
persistEvent(event);
const remove = this.eventStore.add(this.sharedConfig.window, 'touch', 'change', this.preventScroll.bind(this), {
passive: false
});
this.eventStore.add(this.sharedConfig.window, 'touch', 'end', remove);
this.eventStore.add(this.sharedConfig.window, 'touch', 'cancel', remove);
this.timeoutStore.add('startPointerDrag', this.startPointerDrag.bind(this), this.config.preventScrollDelay, event);
}
setupDelayTrigger(event) {
this.state._delayed = true;
this.timeoutStore.add('dragDelay', () => {
this.state._step = [0, 0];
this.startPointerDrag(event);
}, this.config.delay);
}
keyDown(event) {
const deltaFn = KEYS_DELTA_MAP[event.key];
if (deltaFn) {
const state = this.state;
const factor = event.shiftKey ? 10 : event.altKey ? 0.1 : 1;
this.start(event);
state._delta = deltaFn(this.config.keyboardDisplacement, factor);
state._keyboardActive = true;
V.addTo(state._movement, state._delta);
this.compute(event);
this.emit();
}
}
keyUp(event) {
if (!(event.key in KEYS_DELTA_MAP)) return;
this.state._keyboardActive = false;
this.setActive();
this.compute(event);
this.emit();
}
bind(bindFunction) {
const device = this.config.device;
bindFunction(device, 'start', this.pointerDown.bind(this));
if (this.config.pointerCapture) {
bindFunction(device, 'change', this.pointerMove.bind(this));
bindFunction(device, 'end', this.pointerUp.bind(this));
bindFunction(device, 'cancel', this.pointerUp.bind(this));
bindFunction('lostPointerCapture', '', this.pointerUp.bind(this));
}
if (this.config.keys) {
bindFunction('key', 'down', this.keyDown.bind(this));
bindFunction('key', 'up', this.keyUp.bind(this));
}
if (this.config.filterTaps) {
bindFunction('click', '', this.pointerClick.bind(this), {
capture: true,
passive: false
});
}
}
}
function persistEvent(event) {
'persist' in event && typeof event.persist === 'function' && event.persist();
}
const actions_fe213e88_esm_isBrowser = typeof window !== 'undefined' && window.document && window.document.createElement;
function actions_fe213e88_esm_supportsTouchEvents() {
return actions_fe213e88_esm_isBrowser && 'ontouchstart' in window;
}
function isTouchScreen() {
return actions_fe213e88_esm_supportsTouchEvents() || actions_fe213e88_esm_isBrowser && window.navigator.maxTouchPoints > 1;
}
function actions_fe213e88_esm_supportsPointerEvents() {
return actions_fe213e88_esm_isBrowser && 'onpointerdown' in window;
}
function supportsPointerLock() {
return actions_fe213e88_esm_isBrowser && 'exitPointerLock' in window.document;
}
function supportsGestureEvents() {
try {
return 'constructor' in GestureEvent;
} catch (e) {
return false;
}
}
const SUPPORT = {
isBrowser: actions_fe213e88_esm_isBrowser,
gesture: supportsGestureEvents(),
touch: actions_fe213e88_esm_supportsTouchEvents(),
touchscreen: isTouchScreen(),
pointer: actions_fe213e88_esm_supportsPointerEvents(),
pointerLock: supportsPointerLock()
};
const DEFAULT_PREVENT_SCROLL_DELAY = 250;
const DEFAULT_DRAG_DELAY = 180;
const DEFAULT_SWIPE_VELOCITY = 0.5;
const DEFAULT_SWIPE_DISTANCE = 50;
const DEFAULT_SWIPE_DURATION = 250;
const DEFAULT_KEYBOARD_DISPLACEMENT = 10;
const DEFAULT_DRAG_AXIS_THRESHOLD = {
mouse: 0,
touch: 0,
pen: 8
};
const dragConfigResolver = actions_fe213e88_esm_objectSpread2(actions_fe213e88_esm_objectSpread2({}, coordinatesConfigResolver), {}, {
device(_v, _k, {
pointer: {
touch = false,
lock = false,
mouse = false
} = {}
}) {
this.pointerLock = lock && SUPPORT.pointerLock;
if (SUPPORT.touch && touch) return 'touch';
if (this.pointerLock) return 'mouse';
if (SUPPORT.pointer && !mouse) return 'pointer';
if (SUPPORT.touch) return 'touch';
return 'mouse';
},
preventScrollAxis(value, _k, {
preventScroll
}) {
this.preventScrollDelay = typeof preventScroll === 'number' ? preventScroll : preventScroll || preventScroll === undefined && value ? DEFAULT_PREVENT_SCROLL_DELAY : undefined;
if (!SUPPORT.touchscreen || preventScroll === false) return undefined;
return value ? value : preventScroll !== undefined ? 'y' : undefined;
},
pointerCapture(_v, _k, {
pointer: {
capture = true,
buttons = 1,
keys = true
} = {}
}) {
this.pointerButtons = buttons;
this.keys = keys;
return !this.pointerLock && this.device === 'pointer' && capture;
},
threshold(value, _k, {
filterTaps = false,
tapsThreshold = 3,
axis = undefined
}) {
const threshold = V.toVector(value, filterTaps ? tapsThreshold : axis ? 1 : 0);
this.filterTaps = filterTaps;
this.tapsThreshold = tapsThreshold;
return threshold;
},
swipe({
velocity = DEFAULT_SWIPE_VELOCITY,
distance = DEFAULT_SWIPE_DISTANCE,
duration = DEFAULT_SWIPE_DURATION
} = {}) {
return {
velocity: this.transform(V.toVector(velocity)),
distance: this.transform(V.toVector(distance)),
duration
};
},
delay(value = 0) {
switch (value) {
case true:
return DEFAULT_DRAG_DELAY;
case false:
return 0;
default:
return value;
}
},
axisThreshold(value) {
if (!value) return DEFAULT_DRAG_AXIS_THRESHOLD;
return actions_fe213e88_esm_objectSpread2(actions_fe213e88_esm_objectSpread2({}, DEFAULT_DRAG_AXIS_THRESHOLD), value);
},
keyboardDisplacement(value = DEFAULT_KEYBOARD_DISPLACEMENT) {
return value;
}
});
if (false) {}
function clampStateInternalMovementToBounds(state) {
const [ox, oy] = state.overflow;
const [dx, dy] = state._delta;
const [dirx, diry] = state._direction;
if (ox < 0 && dx > 0 && dirx < 0 || ox > 0 && dx < 0 && dirx > 0) {
state._movement[0] = state._movementBound[0];
}
if (oy < 0 && dy > 0 && diry < 0 || oy > 0 && dy < 0 && diry > 0) {
state._movement[1] = state._movementBound[1];
}
}
const SCALE_ANGLE_RATIO_INTENT_DEG = 30;
const PINCH_WHEEL_RATIO = 100;
class PinchEngine extends Engine {
constructor(...args) {
super(...args);
actions_fe213e88_esm_defineProperty(this, "ingKey", 'pinching');
actions_fe213e88_esm_defineProperty(this, "aliasKey", 'da');
}
init() {
this.state.offset = [1, 0];
this.state.lastOffset = [1, 0];
this.state._pointerEvents = new Map();
}
reset() {
super.reset();
const state = this.state;
state._touchIds = [];
state.canceled = false;
state.cancel = this.cancel.bind(this);
state.turns = 0;
}
computeOffset() {
const {
type,
movement,
lastOffset
} = this.state;
if (type === 'wheel') {
this.state.offset = V.add(movement, lastOffset);
} else {
this.state.offset = [(1 + movement[0]) * lastOffset[0], movement[1] + lastOffset[1]];
}
}
computeMovement() {
const {
offset,
lastOffset
} = this.state;
this.state.movement = [offset[0] / lastOffset[0], offset[1] - lastOffset[1]];
}
axisIntent() {
const state = this.state;
const [_m0, _m1] = state._movement;
if (!state.axis) {
const axisMovementDifference = Math.abs(_m0) * SCALE_ANGLE_RATIO_INTENT_DEG - Math.abs(_m1);
if (axisMovementDifference < 0) state.axis = 'angle';else if (axisMovementDifference > 0) state.axis = 'scale';
}
}
restrictToAxis(v) {
if (this.config.lockDirection) {
if (this.state.axis === 'scale') v[1] = 0;else if (this.state.axis === 'angle') v[0] = 0;
}
}
cancel() {
const state = this.state;
if (state.canceled) return;
setTimeout(() => {
state.canceled = true;
state._active = false;
this.compute();
this.emit();
}, 0);
}
touchStart(event) {
this.ctrl.setEventIds(event);
const state = this.state;
const ctrlTouchIds = this.ctrl.touchIds;
if (state._active) {
if (state._touchIds.every(id => ctrlTouchIds.has(id))) return;
}
if (ctrlTouchIds.size < 2) return;
this.start(event);
state._touchIds = Array.from(ctrlTouchIds).slice(0, 2);
const payload = touchDistanceAngle(event, state._touchIds);
if (!payload) return;
this.pinchStart(event, payload);
}
pointerStart(event) {
if (event.buttons != null && event.buttons % 2 !== 1) return;
this.ctrl.setEventIds(event);
event.target.setPointerCapture(event.pointerId);
const state = this.state;
const _pointerEvents = state._pointerEvents;
const ctrlPointerIds = this.ctrl.pointerIds;
if (state._active) {
if (Array.from(_pointerEvents.keys()).every(id => ctrlPointerIds.has(id))) return;
}
if (_pointerEvents.size < 2) {
_pointerEvents.set(event.pointerId, event);
}
if (state._pointerEvents.size < 2) return;
this.start(event);
const payload = distanceAngle(...Array.from(_pointerEvents.values()));
if (!payload) return;
this.pinchStart(event, payload);
}
pinchStart(event, payload) {
const state = this.state;
state.origin = payload.origin;
this.computeValues([payload.distance, payload.angle]);
this.computeInitial();
this.compute(event);
this.emit();
}
touchMove(event) {
if (!this.state._active) return;
const payload = touchDistanceAngle(event, this.state._touchIds);
if (!payload) return;
this.pinchMove(event, payload);
}
pointerMove(event) {
const _pointerEvents = this.state._pointerEvents;
if (_pointerEvents.has(event.pointerId)) {
_pointerEvents.set(event.pointerId, event);
}
if (!this.state._active) return;
const payload = distanceAngle(...Array.from(_pointerEvents.values()));
if (!payload) return;
this.pinchMove(event, payload);
}
pinchMove(event, payload) {
const state = this.state;
const prev_a = state._values[1];
const delta_a = payload.angle - prev_a;
let delta_turns = 0;
if (Math.abs(delta_a) > 270) delta_turns += Math.sign(delta_a);
this.computeValues([payload.distance, payload.angle - 360 * delta_turns]);
state.origin = payload.origin;
state.turns = delta_turns;
state._movement = [state._values[0] / state._initial[0] - 1, state._values[1] - state._initial[1]];
this.compute(event);
this.emit();
}
touchEnd(event) {
this.ctrl.setEventIds(event);
if (!this.state._active) return;
if (this.state._touchIds.some(id => !this.ctrl.touchIds.has(id))) {
this.state._active = false;
this.compute(event);
this.emit();
}
}
pointerEnd(event) {
const state = this.state;
this.ctrl.setEventIds(event);
try {
event.target.releasePointerCapture(event.pointerId);
} catch (_unused) {}
if (state._pointerEvents.has(event.pointerId)) {
state._pointerEvents.delete(event.pointerId);
}
if (!state._active) return;
if (state._pointerEvents.size < 2) {
state._active = false;
this.compute(event);
this.emit();
}
}
gestureStart(event) {
if (event.cancelable) event.preventDefault();
const state = this.state;
if (state._active) return;
this.start(event);
this.computeValues([event.scale, event.rotation]);
state.origin = [event.clientX, event.clientY];
this.compute(event);
this.emit();
}
gestureMove(event) {
if (event.cancelable) event.preventDefault();
if (!this.state._active) return;
const state = this.state;
this.computeValues([event.scale, event.rotation]);
state.origin = [event.clientX, event.clientY];
const _previousMovement = state._movement;
state._movement = [event.scale - 1, event.rotation];
state._delta = V.sub(state._movement, _previousMovement);
this.compute(event);
this.emit();
}
gestureEnd(event) {
if (!this.state._active) return;
this.state._active = false;
this.compute(event);
this.emit();
}
wheel(event) {
const modifierKey = this.config.modifierKey;
if (modifierKey && (Array.isArray(modifierKey) ? !modifierKey.find(k => event[k]) : !event[modifierKey])) return;
if (!this.state._active) this.wheelStart(event);else this.wheelChange(event);
this.timeoutStore.add('wheelEnd', this.wheelEnd.bind(this));
}
wheelStart(event) {
this.start(event);
this.wheelChange(event);
}
wheelChange(event) {
const isR3f = ('uv' in event);
if (!isR3f) {
if (event.cancelable) {
event.preventDefault();
}
if (false) {}
}
const state = this.state;
state._delta = [-wheelValues(event)[1] / PINCH_WHEEL_RATIO * state.offset[0], 0];
V.addTo(state._movement, state._delta);
clampStateInternalMovementToBounds(state);
this.state.origin = [event.clientX, event.clientY];
this.compute(event);
this.emit();
}
wheelEnd() {
if (!this.state._active) return;
this.state._active = false;
this.compute();
this.emit();
}
bind(bindFunction) {
const device = this.config.device;
if (!!device) {
bindFunction(device, 'start', this[device + 'Start'].bind(this));
bindFunction(device, 'change', this[device + 'Move'].bind(this));
bindFunction(device, 'end', this[device + 'End'].bind(this));
bindFunction(device, 'cancel', this[device + 'End'].bind(this));
bindFunction('lostPointerCapture', '', this[device + 'End'].bind(this));
}
if (this.config.pinchOnWheel) {
bindFunction('wheel', '', this.wheel.bind(this), {
passive: false
});
}
}
}
const pinchConfigResolver = actions_fe213e88_esm_objectSpread2(actions_fe213e88_esm_objectSpread2({}, commonConfigResolver), {}, {
device(_v, _k, {
shared,
pointer: {
touch = false
} = {}
}) {
const sharedConfig = shared;
if (sharedConfig.target && !SUPPORT.touch && SUPPORT.gesture) return 'gesture';
if (SUPPORT.touch && touch) return 'touch';
if (SUPPORT.touchscreen) {
if (SUPPORT.pointer) return 'pointer';
if (SUPPORT.touch) return 'touch';
}
},
bounds(_v, _k, {
scaleBounds = {},
angleBounds = {}
}) {
const _scaleBounds = state => {
const D = assignDefault(call(scaleBounds, state), {
min: -Infinity,
max: Infinity
});
return [D.min, D.max];
};
const _angleBounds = state => {
const A = assignDefault(call(angleBounds, state), {
min: -Infinity,
max: Infinity
});
return [A.min, A.max];
};
if (typeof scaleBounds !== 'function' && typeof angleBounds !== 'function') return [_scaleBounds(), _angleBounds()];
return state => [_scaleBounds(state), _angleBounds(state)];
},
threshold(value, _k, config) {
this.lockDirection = config.axis === 'lock';
const threshold = V.toVector(value, this.lockDirection ? [0.1, 3] : 0);
return threshold;
},
modifierKey(value) {
if (value === undefined) return 'ctrlKey';
return value;
},
pinchOnWheel(value = true) {
return value;
}
});
class MoveEngine extends CoordinatesEngine {
constructor(...args) {
super(...args);
actions_fe213e88_esm_defineProperty(this, "ingKey", 'moving');
}
move(event) {
if (this.config.mouseOnly && event.pointerType !== 'mouse') return;
if (!this.state._active) this.moveStart(event);else this.moveChange(event);
this.timeoutStore.add('moveEnd', this.moveEnd.bind(this));
}
moveStart(event) {
this.start(event);
this.computeValues(pointerValues(event));
this.compute(event);
this.computeInitial();
this.emit();
}
moveChange(event) {
if (!this.state._active) return;
const values = pointerValues(event);
const state = this.state;
state._delta = V.sub(values, state._values);
V.addTo(state._movement, state._delta);
this.computeValues(values);
this.compute(event);
this.emit();
}
moveEnd(event) {
if (!this.state._active) return;
this.state._active = false;
this.compute(event);
this.emit();
}
bind(bindFunction) {
bindFunction('pointer', 'change', this.move.bind(this));
bindFunction('pointer', 'leave', this.moveEnd.bind(this));
}
}
const moveConfigResolver = actions_fe213e88_esm_objectSpread2(actions_fe213e88_esm_objectSpread2({}, coordinatesConfigResolver), {}, {
mouseOnly: (value = true) => value
});
class ScrollEngine extends CoordinatesEngine {
constructor(...args) {
super(...args);
actions_fe213e88_esm_defineProperty(this, "ingKey", 'scrolling');
}
scroll(event) {
if (!this.state._active) this.start(event);
this.scrollChange(event);
this.timeoutStore.add('scrollEnd', this.scrollEnd.bind(this));
}
scrollChange(event) {
if (event.cancelable) event.preventDefault();
const state = this.state;
const values = scrollValues(event);
state._delta = V.sub(values, state._values);
V.addTo(state._movement, state._delta);
this.computeValues(values);
this.compute(event);
this.emit();
}
scrollEnd() {
if (!this.state._active) return;
this.state._active = false;
this.compute();
this.emit();
}
bind(bindFunction) {
bindFunction('scroll', '', this.scroll.bind(this));
}
}
const scrollConfigResolver = coordinatesConfigResolver;
class WheelEngine extends CoordinatesEngine {
constructor(...args) {
super(...args);
actions_fe213e88_esm_defineProperty(this, "ingKey", 'wheeling');
}
wheel(event) {
if (!this.state._active) this.start(event);
this.wheelChange(event);
this.timeoutStore.add('wheelEnd', this.wheelEnd.bind(this));
}
wheelChange(event) {
const state = this.state;
state._delta = wheelValues(event);
V.addTo(state._movement, state._delta);
clampStateInternalMovementToBounds(state);
this.compute(event);
this.emit();
}
wheelEnd() {
if (!this.state._active) return;
this.state._active = false;
this.compute();
this.emit();
}
bind(bindFunction) {
bindFunction('wheel', '', this.wheel.bind(this));
}
}
const wheelConfigResolver = coordinatesConfigResolver;
class HoverEngine extends CoordinatesEngine {
constructor(...args) {
super(...args);
actions_fe213e88_esm_defineProperty(this, "ingKey", 'hovering');
}
enter(event) {
if (this.config.mouseOnly && event.pointerType !== 'mouse') return;
this.start(event);
this.computeValues(pointerValues(event));
this.compute(event);
this.emit();
}
leave(event) {
if (this.config.mouseOnly && event.pointerType !== 'mouse') return;
const state = this.state;
if (!state._active) return;
state._active = false;
const values = pointerValues(event);
state._movement = state._delta = V.sub(values, state._values);
this.computeValues(values);
this.compute(event);
state.delta = state.movement;
this.emit();
}
bind(bindFunction) {
bindFunction('pointer', 'enter', this.enter.bind(this));
bindFunction('pointer', 'leave', this.leave.bind(this));
}
}
const hoverConfigResolver = actions_fe213e88_esm_objectSpread2(actions_fe213e88_esm_objectSpread2({}, coordinatesConfigResolver), {}, {
mouseOnly: (value = true) => value
});
const actions_fe213e88_esm_EngineMap = new Map();
const ConfigResolverMap = new Map();
function actions_fe213e88_esm_registerAction(action) {
actions_fe213e88_esm_EngineMap.set(action.key, action.engine);
ConfigResolverMap.set(action.key, action.resolver);
}
const actions_fe213e88_esm_dragAction = {
key: 'drag',
engine: DragEngine,
resolver: dragConfigResolver
};
const actions_fe213e88_esm_hoverAction = {
key: 'hover',
engine: HoverEngine,
resolver: hoverConfigResolver
};
const actions_fe213e88_esm_moveAction = {
key: 'move',
engine: MoveEngine,
resolver: moveConfigResolver
};
const actions_fe213e88_esm_pinchAction = {
key: 'pinch',
engine: PinchEngine,
resolver: pinchConfigResolver
};
const actions_fe213e88_esm_scrollAction = {
key: 'scroll',
engine: ScrollEngine,
resolver: scrollConfigResolver
};
const actions_fe213e88_esm_wheelAction = {
key: 'wheel',
engine: WheelEngine,
resolver: wheelConfigResolver
};
;// CONCATENATED MODULE: ./node_modules/@use-gesture/core/dist/use-gesture-core.esm.js
function use_gesture_core_esm_objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = use_gesture_core_esm_objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
const sharedConfigResolver = {
target(value) {
if (value) {
return () => 'current' in value ? value.current : value;
}
return undefined;
},
enabled(value = true) {
return value;
},
window(value = SUPPORT.isBrowser ? window : undefined) {
return value;
},
eventOptions({
passive = true,
capture = false
} = {}) {
return {
passive,
capture
};
},
transform(value) {
return value;
}
};
const _excluded = ["target", "eventOptions", "window", "enabled", "transform"];
function resolveWith(config = {}, resolvers) {
const result = {};
for (const [key, resolver] of Object.entries(resolvers)) {
switch (typeof resolver) {
case 'function':
if (false) {} else {
result[key] = resolver.call(result, config[key], key, config);
}
break;
case 'object':
result[key] = resolveWith(config[key], resolver);
break;
case 'boolean':
if (resolver) result[key] = config[key];
break;
}
}
return result;
}
function use_gesture_core_esm_parse(newConfig, gestureKey, _config = {}) {
const _ref = newConfig,
{
target,
eventOptions,
window,
enabled,
transform
} = _ref,
rest = _objectWithoutProperties(_ref, _excluded);
_config.shared = resolveWith({
target,
eventOptions,
window,
enabled,
transform
}, sharedConfigResolver);
if (gestureKey) {
const resolver = ConfigResolverMap.get(gestureKey);
_config[gestureKey] = resolveWith(actions_fe213e88_esm_objectSpread2({
shared: _config.shared
}, rest), resolver);
} else {
for (const key in rest) {
const resolver = ConfigResolverMap.get(key);
if (resolver) {
_config[key] = resolveWith(actions_fe213e88_esm_objectSpread2({
shared: _config.shared
}, rest[key]), resolver);
} else if (false) {}
}
}
return _config;
}
class EventStore {
constructor(ctrl, gestureKey) {
actions_fe213e88_esm_defineProperty(this, "_listeners", new Set());
this._ctrl = ctrl;
this._gestureKey = gestureKey;
}
add(element, device, action, handler, options) {
const listeners = this._listeners;
const type = toDomEventType(device, action);
const _options = this._gestureKey ? this._ctrl.config[this._gestureKey].eventOptions : {};
const eventOptions = actions_fe213e88_esm_objectSpread2(actions_fe213e88_esm_objectSpread2({}, _options), options);
element.addEventListener(type, handler, eventOptions);
const remove = () => {
element.removeEventListener(type, handler, eventOptions);
listeners.delete(remove);
};
listeners.add(remove);
return remove;
}
clean() {
this._listeners.forEach(remove => remove());
this._listeners.clear();
}
}
class TimeoutStore {
constructor() {
actions_fe213e88_esm_defineProperty(this, "_timeouts", new Map());
}
add(key, callback, ms = 140, ...args) {
this.remove(key);
this._timeouts.set(key, window.setTimeout(callback, ms, ...args));
}
remove(key) {
const timeout = this._timeouts.get(key);
if (timeout) window.clearTimeout(timeout);
}
clean() {
this._timeouts.forEach(timeout => void window.clearTimeout(timeout));
this._timeouts.clear();
}
}
class Controller {
constructor(handlers) {
actions_fe213e88_esm_defineProperty(this, "gestures", new Set());
actions_fe213e88_esm_defineProperty(this, "_targetEventStore", new EventStore(this));
actions_fe213e88_esm_defineProperty(this, "gestureEventStores", {});
actions_fe213e88_esm_defineProperty(this, "gestureTimeoutStores", {});
actions_fe213e88_esm_defineProperty(this, "handlers", {});
actions_fe213e88_esm_defineProperty(this, "config", {});
actions_fe213e88_esm_defineProperty(this, "pointerIds", new Set());
actions_fe213e88_esm_defineProperty(this, "touchIds", new Set());
actions_fe213e88_esm_defineProperty(this, "state", {
shared: {
shiftKey: false,
metaKey: false,
ctrlKey: false,
altKey: false
}
});
resolveGestures(this, handlers);
}
setEventIds(event) {
if (isTouch(event)) {
this.touchIds = new Set(touchIds(event));
return this.touchIds;
} else if ('pointerId' in event) {
if (event.type === 'pointerup' || event.type === 'pointercancel') this.pointerIds.delete(event.pointerId);else if (event.type === 'pointerdown') this.pointerIds.add(event.pointerId);
return this.pointerIds;
}
}
applyHandlers(handlers, nativeHandlers) {
this.handlers = handlers;
this.nativeHandlers = nativeHandlers;
}
applyConfig(config, gestureKey) {
this.config = use_gesture_core_esm_parse(config, gestureKey, this.config);
}
clean() {
this._targetEventStore.clean();
for (const key of this.gestures) {
this.gestureEventStores[key].clean();
this.gestureTimeoutStores[key].clean();
}
}
effect() {
if (this.config.shared.target) this.bind();
return () => this._targetEventStore.clean();
}
bind(...args) {
const sharedConfig = this.config.shared;
const props = {};
let target;
if (sharedConfig.target) {
target = sharedConfig.target();
if (!target) return;
}
if (sharedConfig.enabled) {
for (const gestureKey of this.gestures) {
const gestureConfig = this.config[gestureKey];
const bindFunction = bindToProps(props, gestureConfig.eventOptions, !!target);
if (gestureConfig.enabled) {
const Engine = actions_fe213e88_esm_EngineMap.get(gestureKey);
new Engine(this, args, gestureKey).bind(bindFunction);
}
}
const nativeBindFunction = bindToProps(props, sharedConfig.eventOptions, !!target);
for (const eventKey in this.nativeHandlers) {
nativeBindFunction(eventKey, '', event => this.nativeHandlers[eventKey](actions_fe213e88_esm_objectSpread2(actions_fe213e88_esm_objectSpread2({}, this.state.shared), {}, {
event,
args
})), undefined, true);
}
}
for (const handlerProp in props) {
props[handlerProp] = chain(...props[handlerProp]);
}
if (!target) return props;
for (const handlerProp in props) {
const {
device,
capture,
passive
} = parseProp(handlerProp);
this._targetEventStore.add(target, device, '', props[handlerProp], {
capture,
passive
});
}
}
}
function setupGesture(ctrl, gestureKey) {
ctrl.gestures.add(gestureKey);
ctrl.gestureEventStores[gestureKey] = new EventStore(ctrl, gestureKey);
ctrl.gestureTimeoutStores[gestureKey] = new TimeoutStore();
}
function resolveGestures(ctrl, internalHandlers) {
if (internalHandlers.drag) setupGesture(ctrl, 'drag');
if (internalHandlers.wheel) setupGesture(ctrl, 'wheel');
if (internalHandlers.scroll) setupGesture(ctrl, 'scroll');
if (internalHandlers.move) setupGesture(ctrl, 'move');
if (internalHandlers.pinch) setupGesture(ctrl, 'pinch');
if (internalHandlers.hover) setupGesture(ctrl, 'hover');
}
const bindToProps = (props, eventOptions, withPassiveOption) => (device, action, handler, options = {}, isNative = false) => {
var _options$capture, _options$passive;
const capture = (_options$capture = options.capture) !== null && _options$capture !== void 0 ? _options$capture : eventOptions.capture;
const passive = (_options$passive = options.passive) !== null && _options$passive !== void 0 ? _options$passive : eventOptions.passive;
let handlerProp = isNative ? device : toHandlerProp(device, action, capture);
if (withPassiveOption && passive) handlerProp += 'Passive';
props[handlerProp] = props[handlerProp] || [];
props[handlerProp].push(handler);
};
const RE_NOT_NATIVE = /^on(Drag|Wheel|Scroll|Move|Pinch|Hover)/;
function sortHandlers(_handlers) {
const native = {};
const handlers = {};
const actions = new Set();
for (let key in _handlers) {
if (RE_NOT_NATIVE.test(key)) {
actions.add(RegExp.lastMatch);
handlers[key] = _handlers[key];
} else {
native[key] = _handlers[key];
}
}
return [handlers, native, actions];
}
function registerGesture(actions, handlers, handlerKey, key, internalHandlers, config) {
if (!actions.has(handlerKey)) return;
if (!EngineMap.has(key)) {
if (false) {}
return;
}
const startKey = handlerKey + 'Start';
const endKey = handlerKey + 'End';
const fn = state => {
let memo = undefined;
if (state.first && startKey in handlers) handlers[startKey](state);
if (handlerKey in handlers) memo = handlers[handlerKey](state);
if (state.last && endKey in handlers) handlers[endKey](state);
return memo;
};
internalHandlers[key] = fn;
config[key] = config[key] || {};
}
function use_gesture_core_esm_parseMergedHandlers(mergedHandlers, mergedConfig) {
const [handlers, nativeHandlers, actions] = sortHandlers(mergedHandlers);
const internalHandlers = {};
registerGesture(actions, handlers, 'onDrag', 'drag', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onWheel', 'wheel', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onScroll', 'scroll', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onPinch', 'pinch', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onMove', 'move', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onHover', 'hover', internalHandlers, mergedConfig);
return {
handlers: internalHandlers,
config: mergedConfig,
nativeHandlers
};
}
;// CONCATENATED MODULE: ./node_modules/@use-gesture/react/dist/use-gesture-react.esm.js
function useRecognizers(handlers, config = {}, gestureKey, nativeHandlers) {
const ctrl = external_React_default().useMemo(() => new Controller(handlers), []);
ctrl.applyHandlers(handlers, nativeHandlers);
ctrl.applyConfig(config, gestureKey);
external_React_default().useEffect(ctrl.effect.bind(ctrl));
external_React_default().useEffect(() => {
return ctrl.clean.bind(ctrl);
}, []);
if (config.target === undefined) {
return ctrl.bind.bind(ctrl);
}
return undefined;
}
function use_gesture_react_esm_useDrag(handler, config) {
actions_fe213e88_esm_registerAction(actions_fe213e88_esm_dragAction);
return useRecognizers({
drag: handler
}, config || {}, 'drag');
}
function usePinch(handler, config) {
registerAction(pinchAction);
return useRecognizers({
pinch: handler
}, config || {}, 'pinch');
}
function useWheel(handler, config) {
registerAction(wheelAction);
return useRecognizers({
wheel: handler
}, config || {}, 'wheel');
}
function useScroll(handler, config) {
registerAction(scrollAction);
return useRecognizers({
scroll: handler
}, config || {}, 'scroll');
}
function useMove(handler, config) {
registerAction(moveAction);
return useRecognizers({
move: handler
}, config || {}, 'move');
}
function useHover(handler, config) {
actions_fe213e88_esm_registerAction(actions_fe213e88_esm_hoverAction);
return useRecognizers({
hover: handler
}, config || {}, 'hover');
}
function createUseGesture(actions) {
actions.forEach(registerAction);
return function useGesture(_handlers, _config) {
const {
handlers,
nativeHandlers,
config
} = parseMergedHandlers(_handlers, _config || {});
return useRecognizers(handlers, config, undefined, nativeHandlers);
};
}
function useGesture(handlers, config) {
const hook = createUseGesture([dragAction, pinchAction, scrollAction, wheelAction, moveAction, hoverAction]);
return hook(handlers, config || {});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/utils.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Gets a CSS cursor value based on a drag direction.
*
* @param dragDirection The drag direction.
* @return The CSS cursor value.
*/
function getDragCursor(dragDirection) {
let dragCursor = 'ns-resize';
switch (dragDirection) {
case 'n':
case 's':
dragCursor = 'ns-resize';
break;
case 'e':
case 'w':
dragCursor = 'ew-resize';
break;
}
return dragCursor;
}
/**
* Custom hook that renders a drag cursor when dragging.
*
* @param {boolean} isDragging The dragging state.
* @param {string} dragDirection The drag direction.
*
* @return {string} The CSS cursor value.
*/
function useDragCursor(isDragging, dragDirection) {
const dragCursor = getDragCursor(dragDirection);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (isDragging) {
document.documentElement.style.cursor = dragCursor;
} else {
// @ts-expect-error
document.documentElement.style.cursor = null;
}
}, [isDragging, dragCursor]);
return dragCursor;
}
function useDraft(props) {
const refPreviousValue = (0,external_wp_element_namespaceObject.useRef)(props.value);
const [draft, setDraft] = (0,external_wp_element_namespaceObject.useState)({});
const value = draft.value !== undefined ? draft.value : props.value; // Determines when to discard the draft value to restore controlled status.
// To do so, it tracks the previous value and marks the draft value as stale
// after each render.
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
const {
current: previousValue
} = refPreviousValue;
refPreviousValue.current = props.value;
if (draft.value !== undefined && !draft.isStale) setDraft({ ...draft,
isStale: true
});else if (draft.isStale && props.value !== previousValue) setDraft({});
}, [props.value, draft]);
const onChange = (nextValue, extra) => {
// Mutates the draft value to avoid an extra effect run.
setDraft(current => Object.assign(current, {
value: nextValue,
isStale: false
}));
props.onChange(nextValue, extra);
};
const onBlur = event => {
var _props$onBlur;
setDraft({});
(_props$onBlur = props.onBlur) === null || _props$onBlur === void 0 ? void 0 : _props$onBlur.call(props, event);
};
return {
value,
onBlur,
onChange
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/reducer/state.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const initialStateReducer = state => state;
const initialInputControlState = {
error: null,
initialValue: '',
isDirty: false,
isDragEnabled: false,
isDragging: false,
isPressEnterToChange: false,
value: ''
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/reducer/actions.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const CHANGE = 'CHANGE';
const COMMIT = 'COMMIT';
const CONTROL = 'CONTROL';
const DRAG_END = 'DRAG_END';
const DRAG_START = 'DRAG_START';
const DRAG = 'DRAG';
const INVALIDATE = 'INVALIDATE';
const PRESS_DOWN = 'PRESS_DOWN';
const PRESS_ENTER = 'PRESS_ENTER';
const PRESS_UP = 'PRESS_UP';
const RESET = 'RESET';
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/reducer/reducer.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Prepares initialState for the reducer.
*
* @param initialState The initial state.
* @return Prepared initialState for the reducer
*/
function mergeInitialState() {
let initialState = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialInputControlState;
const {
value
} = initialState;
return { ...initialInputControlState,
...initialState,
initialValue: value
};
}
/**
* Creates the base reducer which may be coupled to a specializing reducer.
* As its final step, for all actions other than CONTROL, the base reducer
* passes the state and action on through the specializing reducer. The
* exception for CONTROL actions is because they represent controlled updates
* from props and no case has yet presented for their specialization.
*
* @param composedStateReducers A reducer to specialize state changes.
* @return The reducer.
*/
function inputControlStateReducer(composedStateReducers) {
return (state, action) => {
const nextState = { ...state
};
switch (action.type) {
/*
* Controlled updates
*/
case CONTROL:
nextState.value = action.payload.value;
nextState.isDirty = false;
nextState._event = undefined; // Returns immediately to avoid invoking additional reducers.
return nextState;
/**
* Keyboard events
*/
case PRESS_UP:
nextState.isDirty = false;
break;
case PRESS_DOWN:
nextState.isDirty = false;
break;
/**
* Drag events
*/
case DRAG_START:
nextState.isDragging = true;
break;
case DRAG_END:
nextState.isDragging = false;
break;
/**
* Input events
*/
case CHANGE:
nextState.error = null;
nextState.value = action.payload.value;
if (state.isPressEnterToChange) {
nextState.isDirty = true;
}
break;
case COMMIT:
nextState.value = action.payload.value;
nextState.isDirty = false;
break;
case RESET:
nextState.error = null;
nextState.isDirty = false;
nextState.value = action.payload.value || state.initialValue;
break;
/**
* Validation
*/
case INVALIDATE:
nextState.error = action.payload.error;
break;
}
nextState._event = action.payload.event;
/**
* Send the nextState + action to the composedReducers via
* this "bridge" mechanism. This allows external stateReducers
* to hook into actions, and modify state if needed.
*/
return composedStateReducers(nextState, action);
};
}
/**
* A custom hook that connects and external stateReducer with an internal
* reducer. This hook manages the internal state of InputControl.
* However, by connecting an external stateReducer function, other
* components can react to actions as well as modify state before it is
* applied.
*
* This technique uses the "stateReducer" design pattern:
* https://kentcdodds.com/blog/the-state-reducer-pattern/
*
* @param stateReducer An external state reducer.
* @param initialState The initial state for the reducer.
* @param onChangeHandler A handler for the onChange event.
* @return State, dispatch, and a collection of actions.
*/
function useInputControlStateReducer() {
let stateReducer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialStateReducer;
let initialState = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : initialInputControlState;
let onChangeHandler = arguments.length > 2 ? arguments[2] : undefined;
const [state, dispatch] = (0,external_wp_element_namespaceObject.useReducer)(inputControlStateReducer(stateReducer), mergeInitialState(initialState));
const createChangeEvent = type => (nextValue, event) => {
dispatch({
type,
payload: {
value: nextValue,
event
}
});
};
const createKeyEvent = type => event => {
dispatch({
type,
payload: {
event
}
});
};
const createDragEvent = type => payload => {
dispatch({
type,
payload
});
};
/**
* Actions for the reducer
*/
const change = createChangeEvent(CHANGE);
const invalidate = (error, event) => dispatch({
type: INVALIDATE,
payload: {
error,
event
}
});
const reset = createChangeEvent(RESET);
const commit = createChangeEvent(COMMIT);
const dragStart = createDragEvent(DRAG_START);
const drag = createDragEvent(DRAG);
const dragEnd = createDragEvent(DRAG_END);
const pressUp = createKeyEvent(PRESS_UP);
const pressDown = createKeyEvent(PRESS_DOWN);
const pressEnter = createKeyEvent(PRESS_ENTER);
const currentState = (0,external_wp_element_namespaceObject.useRef)(state);
const refProps = (0,external_wp_element_namespaceObject.useRef)({
value: initialState.value,
onChangeHandler
}); // Freshens refs to props and state so that subsequent effects have access
// to their latest values without their changes causing effect runs.
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
currentState.current = state;
refProps.current = {
value: initialState.value,
onChangeHandler
};
}); // Propagates the latest state through onChange.
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
if (currentState.current._event !== undefined && state.value !== refProps.current.value && !state.isDirty) {
var _state$value;
refProps.current.onChangeHandler((_state$value = state.value) !== null && _state$value !== void 0 ? _state$value : '', {
event: currentState.current._event
});
}
}, [state.value, state.isDirty]); // Updates the state from props.
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
if (initialState.value !== currentState.current.value && !currentState.current.isDirty) {
var _initialState$value;
dispatch({
type: CONTROL,
payload: {
value: (_initialState$value = initialState.value) !== null && _initialState$value !== void 0 ? _initialState$value : ''
}
});
}
}, [initialState.value]);
return {
change,
commit,
dispatch,
drag,
dragEnd,
dragStart,
invalidate,
pressDown,
pressEnter,
pressUp,
reset,
state
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/input-field.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const input_field_noop = () => {};
function InputField(_ref, ref) {
let {
disabled = false,
dragDirection = 'n',
dragThreshold = 10,
id,
isDragEnabled = false,
isFocused,
isPressEnterToChange = false,
onBlur = input_field_noop,
onChange = input_field_noop,
onDrag = input_field_noop,
onDragEnd = input_field_noop,
onDragStart = input_field_noop,
onFocus = input_field_noop,
onKeyDown = input_field_noop,
onValidate = input_field_noop,
size = 'default',
setIsFocused,
stateReducer = state => state,
value: valueProp,
type,
...props
} = _ref;
const {
// State.
state,
// Actions.
change,
commit,
drag,
dragEnd,
dragStart,
invalidate,
pressDown,
pressEnter,
pressUp,
reset
} = useInputControlStateReducer(stateReducer, {
isDragEnabled,
value: valueProp,
isPressEnterToChange
}, onChange);
const {
value,
isDragging,
isDirty
} = state;
const wasDirtyOnBlur = (0,external_wp_element_namespaceObject.useRef)(false);
const dragCursor = useDragCursor(isDragging, dragDirection);
const handleOnBlur = event => {
onBlur(event);
setIsFocused === null || setIsFocused === void 0 ? void 0 : setIsFocused(false);
/**
* If isPressEnterToChange is set, this commits the value to
* the onChange callback.
*/
if (isDirty || !event.target.validity.valid) {
wasDirtyOnBlur.current = true;
handleOnCommit(event);
}
};
const handleOnFocus = event => {
onFocus(event);
setIsFocused === null || setIsFocused === void 0 ? void 0 : setIsFocused(true);
};
const handleOnChange = event => {
const nextValue = event.target.value;
change(nextValue, event);
};
const handleOnCommit = event => {
const nextValue = event.currentTarget.value;
try {
onValidate(nextValue);
commit(nextValue, event);
} catch (err) {
invalidate(err, event);
}
};
const handleOnKeyDown = event => {
const {
key
} = event;
onKeyDown(event);
switch (key) {
case 'ArrowUp':
pressUp(event);
break;
case 'ArrowDown':
pressDown(event);
break;
case 'Enter':
pressEnter(event);
if (isPressEnterToChange) {
event.preventDefault();
handleOnCommit(event);
}
break;
case 'Escape':
if (isPressEnterToChange && isDirty) {
event.preventDefault();
reset(valueProp, event);
}
break;
}
};
const dragGestureProps = use_gesture_react_esm_useDrag(dragProps => {
const {
distance,
dragging,
event,
target
} = dragProps; // The `target` prop always references the `input` element while, by
// default, the `dragProps.event.target` property would reference the real
// event target (i.e. any DOM element that the pointer is hovering while
// dragging). Ensuring that the `target` is always the `input` element
// allows consumers of `InputControl` (or any higher-level control) to
// check the input's validity by accessing `event.target.validity.valid`.
dragProps.event = { ...dragProps.event,
target
};
if (!distance) return;
event.stopPropagation();
/**
* Quick return if no longer dragging.
* This prevents unnecessary value calculations.
*/
if (!dragging) {
onDragEnd(dragProps);
dragEnd(dragProps);
return;
}
onDrag(dragProps);
drag(dragProps);
if (!isDragging) {
onDragStart(dragProps);
dragStart(dragProps);
}
}, {
axis: dragDirection === 'e' || dragDirection === 'w' ? 'x' : 'y',
threshold: dragThreshold,
enabled: isDragEnabled,
pointer: {
capture: false
}
});
const dragProps = isDragEnabled ? dragGestureProps() : {};
/*
* Works around the odd UA (e.g. Firefox) that does not focus inputs of
* type=number when their spinner arrows are pressed.
*/
let handleOnMouseDown;
if (type === 'number') {
handleOnMouseDown = event => {
var _props$onMouseDown;
(_props$onMouseDown = props.onMouseDown) === null || _props$onMouseDown === void 0 ? void 0 : _props$onMouseDown.call(props, event);
if (event.currentTarget !== event.currentTarget.ownerDocument.activeElement) {
event.currentTarget.focus();
}
};
}
return (0,external_wp_element_namespaceObject.createElement)(Input, extends_extends({}, props, dragProps, {
className: "components-input-control__input",
disabled: disabled,
dragCursor: dragCursor,
isDragging: isDragging,
id: id,
onBlur: handleOnBlur,
onChange: handleOnChange,
onFocus: handleOnFocus,
onKeyDown: handleOnKeyDown,
onMouseDown: handleOnMouseDown,
ref: ref,
inputSize: size // Fallback to `''` to avoid "uncontrolled to controlled" warning.
// See https://github.com/WordPress/gutenberg/pull/47250 for details.
,
value: value !== null && value !== void 0 ? value : '',
type: type
}));
}
const ForwardedComponent = (0,external_wp_element_namespaceObject.forwardRef)(InputField);
/* harmony default export */ var input_field = (ForwardedComponent);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/font-values.js
/* harmony default export */ var font_values = ({
'default.fontFamily': "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif",
'default.fontSize': '13px',
'helpText.fontSize': '12px',
mobileTextMinFontSize: '16px'
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/font.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
/**
*
* @param {keyof FONT} value Path of value from `FONT`
* @return {string} Font rule value
*/
function font(value) {
return (0,external_lodash_namespaceObject.get)(font_values, value, '');
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/box-sizing.js
function box_sizing_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
const boxSizingReset = true ? {
name: "kv6lnz",
styles: "box-sizing:border-box;*,*::before,*::after{box-sizing:inherit;}"
} : 0;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/base-control/styles/base-control-styles.js
function base_control_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const base_control_styles_Wrapper = createStyled("div", true ? {
target: "ej5x27r4"
} : 0)("font-family:", font('default.fontFamily'), ";font-size:", font('default.fontSize'), ";", boxSizingReset, ";" + ( true ? "" : 0));
const deprecatedMarginField = _ref2 => {
let {
__nextHasNoMarginBottom = false
} = _ref2;
return !__nextHasNoMarginBottom && /*#__PURE__*/emotion_react_browser_esm_css("margin-bottom:", space(2), ";" + ( true ? "" : 0), true ? "" : 0);
};
const StyledField = createStyled("div", true ? {
target: "ej5x27r3"
} : 0)(deprecatedMarginField, " .components-panel__row &{margin-bottom:inherit;}" + ( true ? "" : 0));
const labelStyles = /*#__PURE__*/emotion_react_browser_esm_css(baseLabelTypography, ";display:inline-block;margin-bottom:", space(2), ";padding:0;" + ( true ? "" : 0), true ? "" : 0);
const StyledLabel = createStyled("label", true ? {
target: "ej5x27r2"
} : 0)(labelStyles, ";" + ( true ? "" : 0));
var base_control_styles_ref = true ? {
name: "11yad0w",
styles: "margin-bottom:revert"
} : 0;
const deprecatedMarginHelp = _ref3 => {
let {
__nextHasNoMarginBottom = false
} = _ref3;
return !__nextHasNoMarginBottom && base_control_styles_ref;
};
const StyledHelp = createStyled("p", true ? {
target: "ej5x27r1"
} : 0)("margin-top:", space(2), ";margin-bottom:0;font-size:", font('helpText.fontSize'), ";font-style:normal;color:", COLORS.gray[700], ";", deprecatedMarginHelp, ";" + ( true ? "" : 0));
const StyledVisualLabel = createStyled("span", true ? {
target: "ej5x27r0"
} : 0)(labelStyles, ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/base-control/index.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
/**
* `BaseControl` is a component used to generate labels and help text for components handling user inputs.
*
* ```jsx
* import { BaseControl, useBaseControlProps } from '@wordpress/components';
*
* // Render a `BaseControl` for a textarea input
* const MyCustomTextareaControl = ({ children, ...baseProps }) => (
* // `useBaseControlProps` is a convenience hook to get the props for the `BaseControl`
* // and the inner control itself. Namely, it takes care of generating a unique `id`,
* // properly associating it with the `label` and `help` elements.
* const { baseControlProps, controlProps } = useBaseControlProps( baseProps );
*
* return (
* <BaseControl { ...baseControlProps } __nextHasNoMarginBottom={ true }>
* <textarea { ...controlProps }>
* { children }
* </textarea>
* </BaseControl>
* );
* );
* ```
*/
const BaseControl = _ref => {
let {
__nextHasNoMarginBottom = false,
id,
label,
hideLabelFromVision = false,
help,
className,
children
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(base_control_styles_Wrapper, {
className: classnames_default()('components-base-control', className)
}, (0,external_wp_element_namespaceObject.createElement)(StyledField, {
className: "components-base-control__field" // TODO: Official deprecation for this should start after all internal usages have been migrated
,
__nextHasNoMarginBottom: __nextHasNoMarginBottom
}, label && id && (hideLabelFromVision ? (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, {
as: "label",
htmlFor: id
}, label) : (0,external_wp_element_namespaceObject.createElement)(StyledLabel, {
className: "components-base-control__label",
htmlFor: id
}, label)), label && !id && (hideLabelFromVision ? (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, {
as: "label"
}, label) : (0,external_wp_element_namespaceObject.createElement)(BaseControl.VisualLabel, null, label)), children), !!help && (0,external_wp_element_namespaceObject.createElement)(StyledHelp, {
id: id ? id + '__help' : undefined,
className: "components-base-control__help",
__nextHasNoMarginBottom: __nextHasNoMarginBottom
}, help));
};
/**
* `BaseControl.VisualLabel` is used to render a purely visual label inside a `BaseControl` component.
*
* It should only be used in cases where the children being rendered inside `BaseControl` are already accessibly labeled,
* e.g., a button, but we want an additional visual label for that section equivalent to the labels `BaseControl` would
* otherwise use if the `label` prop was passed.
*
* @example
* import { BaseControl } from '@wordpress/components';
*
* const MyBaseControl = () => (
* <BaseControl help="This button is already accessibly labeled.">
* <BaseControl.VisualLabel>Author</BaseControl.VisualLabel>
* <Button>Select an author</Button>
* </BaseControl>
* );
*/
const VisualLabel = _ref2 => {
let {
className,
children,
...props
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(StyledVisualLabel, extends_extends({}, props, {
className: classnames_default()('components-base-control__label', className)
}), children);
};
BaseControl.VisualLabel = VisualLabel;
/* harmony default export */ var base_control = (BaseControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const input_control_noop = () => {};
function input_control_useUniqueId(idProp) {
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(InputControl);
const id = `inspector-input-control-${instanceId}`;
return idProp || id;
}
function UnforwardedInputControl(_ref, ref) {
let {
__next36pxDefaultSize,
__unstableStateReducer: stateReducer = state => state,
__unstableInputWidth,
className,
disabled = false,
help,
hideLabelFromVision = false,
id: idProp,
isPressEnterToChange = false,
label,
labelPosition = 'top',
onChange = input_control_noop,
onValidate = input_control_noop,
onKeyDown = input_control_noop,
prefix,
size = 'default',
style,
suffix,
value,
...props
} = _ref;
const [isFocused, setIsFocused] = (0,external_wp_element_namespaceObject.useState)(false);
const id = input_control_useUniqueId(idProp);
const classes = classnames_default()('components-input-control', className);
const draftHookProps = useDraft({
value,
onBlur: props.onBlur,
onChange
}); // ARIA descriptions can only contain plain text, so fall back to aria-details if not.
const helpPropName = typeof help === 'string' ? 'aria-describedby' : 'aria-details';
const helpProp = !!help ? {
[helpPropName]: `${id}__help`
} : {};
return (0,external_wp_element_namespaceObject.createElement)(base_control, {
className: classes,
help: help,
id: id,
__nextHasNoMarginBottom: true
}, (0,external_wp_element_namespaceObject.createElement)(input_base, {
__next36pxDefaultSize: __next36pxDefaultSize,
__unstableInputWidth: __unstableInputWidth,
disabled: disabled,
gap: 3,
hideLabelFromVision: hideLabelFromVision,
id: id,
isFocused: isFocused,
justify: "left",
label: label,
labelPosition: labelPosition,
prefix: prefix,
size: size,
style: style,
suffix: suffix
}, (0,external_wp_element_namespaceObject.createElement)(input_field, extends_extends({}, props, helpProp, {
__next36pxDefaultSize: __next36pxDefaultSize,
className: "components-input-control__input",
disabled: disabled,
id: id,
isFocused: isFocused,
isPressEnterToChange: isPressEnterToChange,
onKeyDown: onKeyDown,
onValidate: onValidate,
paddingInlineStart: prefix ? space(2) : undefined,
paddingInlineEnd: suffix ? space(2) : undefined,
ref: ref,
setIsFocused: setIsFocused,
size: size,
stateReducer: stateReducer
}, draftHookProps))));
}
/**
* InputControl components let users enter and edit text. This is an experimental component
* intended to (in time) merge with or replace `TextControl`.
*
* ```jsx
* import { __experimentalInputControl as InputControl } from '@wordpress/components';
* import { useState } from '@wordpress/compose';
*
* const Example = () => {
* const [ value, setValue ] = useState( '' );
*
* return (
* <InputControl
* value={ value }
* onChange={ ( nextValue ) => setValue( nextValue ?? '' ) }
* />
* );
* };
* ```
*/
const InputControl = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedInputControl);
/* harmony default export */ var input_control = (InputControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/number-control/styles/number-control-styles.js
function number_control_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
var number_control_styles_ref = true ? {
name: "euqsgg",
styles: "input[type='number']::-webkit-outer-spin-button,input[type='number']::-webkit-inner-spin-button{-webkit-appearance:none!important;margin:0!important;}input[type='number']{-moz-appearance:textfield;}"
} : 0;
const htmlArrowStyles = _ref2 => {
let {
hideHTMLArrows
} = _ref2;
if (!hideHTMLArrows) {
return ``;
}
return number_control_styles_ref;
};
const number_control_styles_Input = /*#__PURE__*/createStyled(input_control, true ? {
target: "ep09it41"
} : 0)(htmlArrowStyles, ";" + ( true ? "" : 0));
const spinButtonSizeStyles = _ref3 => {
let {
size
} = _ref3;
if (size !== 'small') {
return ``;
}
return /*#__PURE__*/emotion_react_browser_esm_css("width:", space(5), ";min-width:", space(5), ";height:", space(5), ";" + ( true ? "" : 0), true ? "" : 0);
};
const SpinButton = /*#__PURE__*/createStyled(build_module_button, true ? {
target: "ep09it40"
} : 0)("&&&&&{color:", COLORS.ui.theme, ";", spinButtonSizeStyles, ";}" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/math.js
/**
* Parses and retrieves a number value.
*
* @param {unknown} value The incoming value.
*
* @return {number} The parsed number value.
*/
function getNumber(value) {
const number = Number(value);
return isNaN(number) ? 0 : number;
}
/**
* Safely adds 2 values.
*
* @param {Array<number|string>} args Values to add together.
*
* @return {number} The sum of values.
*/
function add() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return args.reduce(
/** @type {(sum:number, arg: number|string) => number} */
(sum, arg) => sum + getNumber(arg), 0);
}
/**
* Safely subtracts 2 values.
*
* @param {Array<number|string>} args Values to subtract together.
*
* @return {number} The difference of the values.
*/
function subtract() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return args.reduce(
/** @type {(diff:number, arg: number|string, index:number) => number} */
(diff, arg, index) => {
const value = getNumber(arg);
return index === 0 ? value : diff - value;
}, 0);
}
/**
* Determines the decimal position of a number value.
*
* @param {number} value The number to evaluate.
*
* @return {number} The number of decimal places.
*/
function getPrecision(value) {
const split = (value + '').split('.');
return split[1] !== undefined ? split[1].length : 0;
}
/**
* Clamps a value based on a min/max range.
*
* @param {number} value The value.
* @param {number} min The minimum range.
* @param {number} max The maximum range.
*
* @return {number} The clamped value.
*/
function math_clamp(value, min, max) {
const baseValue = getNumber(value);
return Math.max(min, Math.min(baseValue, max));
}
/**
* Clamps a value based on a min/max range with rounding
*
* @param {number | string} value The value.
* @param {number} min The minimum range.
* @param {number} max The maximum range.
* @param {number} step A multiplier for the value.
*
* @return {number} The rounded and clamped value.
*/
function roundClamp() {
let value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
let min = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Infinity;
let max = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : Infinity;
let step = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1;
const baseValue = getNumber(value);
const stepValue = getNumber(step);
const precision = getPrecision(step);
const rounded = Math.round(baseValue / stepValue) * stepValue;
const clampedValue = math_clamp(rounded, min, max);
return precision ? getNumber(clampedValue.toFixed(precision)) : clampedValue;
}
/**
* Clamps a value based on a min/max range with rounding.
* Returns a string.
*
* @param {Parameters<typeof roundClamp>} args Arguments for roundClamp().
* @return {string} The rounded and clamped value.
*/
function roundClampString() {
return roundClamp(...arguments).toString();
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/h-stack/utils.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const H_ALIGNMENTS = {
bottom: {
align: 'flex-end',
justify: 'center'
},
bottomLeft: {
align: 'flex-start',
justify: 'flex-end'
},
bottomRight: {
align: 'flex-end',
justify: 'flex-end'
},
center: {
align: 'center',
justify: 'center'
},
edge: {
align: 'center',
justify: 'space-between'
},
left: {
align: 'center',
justify: 'flex-start'
},
right: {
align: 'center',
justify: 'flex-end'
},
stretch: {
align: 'stretch'
},
top: {
align: 'flex-start',
justify: 'center'
},
topLeft: {
align: 'flex-start',
justify: 'flex-start'
},
topRight: {
align: 'flex-start',
justify: 'flex-end'
}
};
const V_ALIGNMENTS = {
bottom: {
justify: 'flex-end',
align: 'center'
},
bottomLeft: {
justify: 'flex-start',
align: 'flex-end'
},
bottomRight: {
justify: 'flex-end',
align: 'flex-end'
},
center: {
justify: 'center',
align: 'center'
},
edge: {
justify: 'space-between',
align: 'center'
},
left: {
justify: 'center',
align: 'flex-start'
},
right: {
justify: 'center',
align: 'flex-end'
},
stretch: {
justify: 'stretch'
},
top: {
justify: 'flex-start',
align: 'center'
},
topLeft: {
justify: 'flex-start',
align: 'flex-start'
},
topRight: {
justify: 'flex-start',
align: 'flex-end'
}
};
function getAlignmentProps(alignment) {
let direction = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'row';
if (!isValueDefined(alignment)) {
return {};
}
const isVertical = direction === 'column';
const props = isVertical ? V_ALIGNMENTS : H_ALIGNMENTS;
const alignmentProps = alignment in props ? props[alignment] : {
align: alignment
};
return alignmentProps;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/utils/get-valid-children.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Gets a collection of available children elements from a React component's children prop.
*
* @param children
*
* @return An array of available children.
*/
function getValidChildren(children) {
if (typeof children === 'string') return [children];
return external_wp_element_namespaceObject.Children.toArray(children).filter(child => (0,external_wp_element_namespaceObject.isValidElement)(child));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/h-stack/hook.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function useHStack(props) {
const {
alignment = 'edge',
children,
direction,
spacing = 2,
...otherProps
} = useContextSystem(props, 'HStack');
const align = getAlignmentProps(alignment, direction);
const validChildren = getValidChildren(children);
const clonedChildren = validChildren.map((child, index) => {
const _isSpacer = hasConnectNamespace(child, ['Spacer']);
if (_isSpacer) {
const childElement = child;
const _key = childElement.key || `hstack-${index}`;
return (0,external_wp_element_namespaceObject.createElement)(flex_item_component, extends_extends({
isBlock: true,
key: _key
}, childElement.props));
}
return child;
});
const propsForFlex = {
children: clonedChildren,
direction,
justify: 'center',
...align,
...otherProps,
gap: spacing
};
const flexProps = useFlex(propsForFlex);
return flexProps;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/h-stack/component.js
/**
* Internal dependencies
*/
function UnconnectedHStack(props, forwardedRef) {
const hStackProps = useHStack(props);
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({}, hStackProps, {
ref: forwardedRef
}));
}
/**
* `HStack` (Horizontal Stack) arranges child elements in a horizontal line.
*
* `HStack` can render anything inside.
*
* ```jsx
* import {
* __experimentalHStack as HStack,
* __experimentalText as Text,
* } from `@wordpress/components`;
*
* function Example() {
* return (
* <HStack>
* <Text>Code</Text>
* <Text>is</Text>
* <Text>Poetry</Text>
* </HStack>
* );
* }
* ```
*/
const HStack = contextConnect(UnconnectedHStack, 'HStack');
/* harmony default export */ var h_stack_component = (HStack);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/spacer/hook.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const isDefined = o => typeof o !== 'undefined' && o !== null;
function useSpacer(props) {
const {
className,
margin,
marginBottom = 2,
marginLeft,
marginRight,
marginTop,
marginX,
marginY,
padding,
paddingBottom,
paddingLeft,
paddingRight,
paddingTop,
paddingX,
paddingY,
...otherProps
} = useContextSystem(props, 'Spacer');
const cx = useCx();
const classes = cx(isDefined(margin) && /*#__PURE__*/emotion_react_browser_esm_css("margin:", space(margin), ";" + ( true ? "" : 0), true ? "" : 0), isDefined(marginY) && /*#__PURE__*/emotion_react_browser_esm_css("margin-bottom:", space(marginY), ";margin-top:", space(marginY), ";" + ( true ? "" : 0), true ? "" : 0), isDefined(marginX) && /*#__PURE__*/emotion_react_browser_esm_css("margin-left:", space(marginX), ";margin-right:", space(marginX), ";" + ( true ? "" : 0), true ? "" : 0), isDefined(marginTop) && /*#__PURE__*/emotion_react_browser_esm_css("margin-top:", space(marginTop), ";" + ( true ? "" : 0), true ? "" : 0), isDefined(marginBottom) && /*#__PURE__*/emotion_react_browser_esm_css("margin-bottom:", space(marginBottom), ";" + ( true ? "" : 0), true ? "" : 0), isDefined(marginLeft) && rtl({
marginLeft: space(marginLeft)
})(), isDefined(marginRight) && rtl({
marginRight: space(marginRight)
})(), isDefined(padding) && /*#__PURE__*/emotion_react_browser_esm_css("padding:", space(padding), ";" + ( true ? "" : 0), true ? "" : 0), isDefined(paddingY) && /*#__PURE__*/emotion_react_browser_esm_css("padding-bottom:", space(paddingY), ";padding-top:", space(paddingY), ";" + ( true ? "" : 0), true ? "" : 0), isDefined(paddingX) && /*#__PURE__*/emotion_react_browser_esm_css("padding-left:", space(paddingX), ";padding-right:", space(paddingX), ";" + ( true ? "" : 0), true ? "" : 0), isDefined(paddingTop) && /*#__PURE__*/emotion_react_browser_esm_css("padding-top:", space(paddingTop), ";" + ( true ? "" : 0), true ? "" : 0), isDefined(paddingBottom) && /*#__PURE__*/emotion_react_browser_esm_css("padding-bottom:", space(paddingBottom), ";" + ( true ? "" : 0), true ? "" : 0), isDefined(paddingLeft) && rtl({
paddingLeft: space(paddingLeft)
})(), isDefined(paddingRight) && rtl({
paddingRight: space(paddingRight)
})(), className);
return { ...otherProps,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/spacer/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedSpacer(props, forwardedRef) {
const spacerProps = useSpacer(props);
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({}, spacerProps, {
ref: forwardedRef
}));
}
/**
* `Spacer` is a primitive layout component that providers inner (`padding`) or outer (`margin`) space in-between components. It can also be used to adaptively provide space within an `HStack` or `VStack`.
*
* `Spacer` comes with a bunch of shorthand props to adjust `margin` and `padding`. The values of these props
* can either be a number (which will act as a multiplier to the library's grid system base of 4px),
* or a literal CSS value string.
*
* ```jsx
* import { Spacer } from `@wordpress/components`
*
* function Example() {
* return (
* <View>
* <Spacer>
* <Heading>WordPress.org</Heading>
* </Spacer>
* <Text>
* Code is Poetry
* </Text>
* </View>
* );
* }
* ```
*/
const Spacer = contextConnect(UnconnectedSpacer, 'Spacer');
/* harmony default export */ var spacer_component = (Spacer);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/number-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const number_control_noop = () => {};
function UnforwardedNumberControl(_ref, forwardedRef) {
let {
__unstableStateReducer: stateReducerProp,
className,
dragDirection = 'n',
hideHTMLArrows = false,
spinControls = 'native',
isDragEnabled = true,
isShiftStepEnabled = true,
label,
max = Infinity,
min = -Infinity,
required = false,
shiftStep = 10,
step = 1,
type: typeProp = 'number',
value: valueProp,
size = 'default',
suffix,
onChange = number_control_noop,
...props
} = _ref;
if (hideHTMLArrows) {
external_wp_deprecated_default()('wp.components.NumberControl hideHTMLArrows prop ', {
alternative: 'spinControls="none"',
since: '6.2',
version: '6.3'
});
spinControls = 'none';
}
const inputRef = (0,external_wp_element_namespaceObject.useRef)();
const mergedRef = (0,external_wp_compose_namespaceObject.useMergeRefs)([inputRef, forwardedRef]);
const isStepAny = step === 'any';
const baseStep = isStepAny ? 1 : ensureNumber(step);
const baseValue = roundClamp(0, min, max, baseStep);
const constrainValue = (value, stepOverride) => {
// When step is "any" clamp the value, otherwise round and clamp it.
return isStepAny ? Math.min(max, Math.max(min, ensureNumber(value))) : roundClamp(value, min, max, stepOverride !== null && stepOverride !== void 0 ? stepOverride : baseStep);
};
const autoComplete = typeProp === 'number' ? 'off' : undefined;
const classes = classnames_default()('components-number-control', className);
const spinValue = (value, direction, event) => {
event === null || event === void 0 ? void 0 : event.preventDefault();
const shift = (event === null || event === void 0 ? void 0 : event.shiftKey) && isShiftStepEnabled;
const delta = shift ? ensureNumber(shiftStep) * baseStep : baseStep;
let nextValue = isValueEmpty(value) ? baseValue : value;
if (direction === 'up') {
nextValue = add(nextValue, delta);
} else if (direction === 'down') {
nextValue = subtract(nextValue, delta);
}
return constrainValue(nextValue, shift ? delta : undefined);
};
/**
* "Middleware" function that intercepts updates from InputControl.
* This allows us to tap into actions to transform the (next) state for
* InputControl.
*
* @return The updated state to apply to InputControl
*/
const numberControlStateReducer = (state, action) => {
const nextState = { ...state
};
const {
type,
payload
} = action;
const event = payload.event;
const currentValue = nextState.value;
/**
* Handles custom UP and DOWN Keyboard events
*/
if (type === PRESS_UP || type === PRESS_DOWN) {
// @ts-expect-error TODO: Resolve discrepancy between `value` types in InputControl based components
nextState.value = spinValue(currentValue, type === PRESS_UP ? 'up' : 'down', event);
}
/**
* Handles drag to update events
*/
if (type === DRAG && isDragEnabled) {
// @ts-expect-error TODO: See if reducer actions can be typed better
const [x, y] = payload.delta; // @ts-expect-error TODO: See if reducer actions can be typed better
const enableShift = payload.shiftKey && isShiftStepEnabled;
const modifier = enableShift ? ensureNumber(shiftStep) * baseStep : baseStep;
let directionModifier;
let delta;
switch (dragDirection) {
case 'n':
delta = y;
directionModifier = -1;
break;
case 'e':
delta = x;
directionModifier = (0,external_wp_i18n_namespaceObject.isRTL)() ? -1 : 1;
break;
case 's':
delta = y;
directionModifier = 1;
break;
case 'w':
delta = x;
directionModifier = (0,external_wp_i18n_namespaceObject.isRTL)() ? 1 : -1;
break;
}
if (delta !== 0) {
delta = Math.ceil(Math.abs(delta)) * Math.sign(delta);
const distance = delta * modifier * directionModifier; // @ts-expect-error TODO: Resolve discrepancy between `value` types in InputControl based components
nextState.value = constrainValue( // @ts-expect-error TODO: Investigate if it's ok for currentValue to be undefined
add(currentValue, distance), enableShift ? modifier : undefined);
}
}
/**
* Handles commit (ENTER key press or blur)
*/
if (type === PRESS_ENTER || type === COMMIT) {
const applyEmptyValue = required === false && currentValue === ''; // @ts-expect-error TODO: Resolve discrepancy between `value` types in InputControl based components
nextState.value = applyEmptyValue ? currentValue : // @ts-expect-error TODO: Investigate if it's ok for currentValue to be undefined
constrainValue(currentValue);
}
return nextState;
};
const buildSpinButtonClickHandler = direction => event => onChange(String(spinValue(valueProp, direction, event)), {
// Set event.target to the <input> so that consumers can use
// e.g. event.target.validity.
event: { ...event,
target: inputRef.current
}
});
return (0,external_wp_element_namespaceObject.createElement)(number_control_styles_Input, extends_extends({
autoComplete: autoComplete,
inputMode: "numeric"
}, props, {
className: classes,
dragDirection: dragDirection,
hideHTMLArrows: spinControls !== 'native',
isDragEnabled: isDragEnabled,
label: label,
max: max,
min: min,
ref: mergedRef,
required: required,
step: step,
type: typeProp // @ts-expect-error TODO: Resolve discrepancy between `value` types in InputControl based components
,
value: valueProp,
__unstableStateReducer: (state, action) => {
var _stateReducerProp;
const baseState = numberControlStateReducer(state, action);
return (_stateReducerProp = stateReducerProp === null || stateReducerProp === void 0 ? void 0 : stateReducerProp(baseState, action)) !== null && _stateReducerProp !== void 0 ? _stateReducerProp : baseState;
},
size: size,
suffix: spinControls === 'custom' ? (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, suffix, (0,external_wp_element_namespaceObject.createElement)(spacer_component, {
marginBottom: 0,
marginRight: 2
}, (0,external_wp_element_namespaceObject.createElement)(h_stack_component, {
spacing: 1
}, (0,external_wp_element_namespaceObject.createElement)(SpinButton, {
icon: library_plus,
isSmall: true,
"aria-hidden": "true",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Increment'),
tabIndex: -1,
onClick: buildSpinButtonClickHandler('up'),
size: size
}), (0,external_wp_element_namespaceObject.createElement)(SpinButton, {
icon: library_reset,
isSmall: true,
"aria-hidden": "true",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Decrement'),
tabIndex: -1,
onClick: buildSpinButtonClickHandler('down'),
size: size
})))) : suffix,
onChange: onChange
}));
}
const NumberControl = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedNumberControl);
/* harmony default export */ var number_control = (NumberControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/angle-picker-control/styles/angle-picker-control-styles.js
function angle_picker_control_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const CIRCLE_SIZE = 32;
const INNER_CIRCLE_SIZE = 3;
const deprecatedBottomMargin = _ref => {
let {
__nextHasNoMarginBottom
} = _ref;
return !__nextHasNoMarginBottom ? /*#__PURE__*/emotion_react_browser_esm_css("margin-bottom:", space(2), ";" + ( true ? "" : 0), true ? "" : 0) : '';
};
const angle_picker_control_styles_Root = /*#__PURE__*/createStyled(flex_component, true ? {
target: "e65ony43"
} : 0)(deprecatedBottomMargin, ";" + ( true ? "" : 0));
const CircleRoot = createStyled("div", true ? {
target: "e65ony42"
} : 0)("border-radius:50%;border:", config_values.borderWidth, " solid ", COLORS.ui.border, ";box-sizing:border-box;cursor:grab;height:", CIRCLE_SIZE, "px;overflow:hidden;width:", CIRCLE_SIZE, "px;" + ( true ? "" : 0));
const CircleIndicatorWrapper = createStyled("div", true ? {
target: "e65ony41"
} : 0)( true ? {
name: "1r307gh",
styles: "box-sizing:border-box;position:relative;width:100%;height:100%;:focus-visible{outline:none;}"
} : 0);
const CircleIndicator = createStyled("div", true ? {
target: "e65ony40"
} : 0)("background:", COLORS.ui.theme, ";border-radius:50%;border:", INNER_CIRCLE_SIZE, "px solid ", COLORS.ui.theme, ";bottom:0;box-sizing:border-box;display:block;height:0px;left:0;margin:auto;position:absolute;right:0;top:-", CIRCLE_SIZE / 2, "px;width:0px;" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/angle-picker-control/angle-circle.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function AngleCircle(_ref) {
let {
value,
onChange,
...props
} = _ref;
const angleCircleRef = (0,external_wp_element_namespaceObject.useRef)();
const angleCircleCenter = (0,external_wp_element_namespaceObject.useRef)();
const previousCursorValue = (0,external_wp_element_namespaceObject.useRef)();
const setAngleCircleCenter = () => {
const rect = angleCircleRef.current.getBoundingClientRect();
angleCircleCenter.current = {
x: rect.x + rect.width / 2,
y: rect.y + rect.height / 2
};
};
const changeAngleToPosition = event => {
const {
x: centerX,
y: centerY
} = angleCircleCenter.current; // Prevent (drag) mouse events from selecting and accidentally
// triggering actions from other elements.
event.preventDefault(); // Input control needs to lose focus and by preventDefault above, it doesn't.
event.target.focus();
onChange(getAngle(centerX, centerY, event.clientX, event.clientY));
};
const {
startDrag,
isDragging
} = (0,external_wp_compose_namespaceObject.__experimentalUseDragging)({
onDragStart: event => {
setAngleCircleCenter();
changeAngleToPosition(event);
},
onDragMove: changeAngleToPosition,
onDragEnd: changeAngleToPosition
});
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (isDragging) {
if (previousCursorValue.current === undefined) {
previousCursorValue.current = document.body.style.cursor;
}
document.body.style.cursor = 'grabbing';
} else {
document.body.style.cursor = previousCursorValue.current || null;
previousCursorValue.current = undefined;
}
}, [isDragging]);
return (
/* eslint-disable jsx-a11y/no-static-element-interactions */
(0,external_wp_element_namespaceObject.createElement)(CircleRoot, extends_extends({
ref: angleCircleRef,
onMouseDown: startDrag,
className: "components-angle-picker-control__angle-circle",
style: isDragging ? {
cursor: 'grabbing'
} : undefined
}, props), (0,external_wp_element_namespaceObject.createElement)(CircleIndicatorWrapper, {
style: value ? {
transform: `rotate(${value}deg)`
} : undefined,
className: "components-angle-picker-control__angle-circle-indicator-wrapper",
tabIndex: -1
}, (0,external_wp_element_namespaceObject.createElement)(CircleIndicator, {
className: "components-angle-picker-control__angle-circle-indicator"
})))
/* eslint-enable jsx-a11y/no-static-element-interactions */
);
}
function getAngle(centerX, centerY, pointX, pointY) {
const y = pointY - centerY;
const x = pointX - centerX;
const angleInRadians = Math.atan2(y, x);
const angleInDeg = Math.round(angleInRadians * (180 / Math.PI)) + 90;
if (angleInDeg < 0) {
return 360 + angleInDeg;
}
return angleInDeg;
}
/* harmony default export */ var angle_circle = (AngleCircle);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/angle-picker-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function AnglePickerControl(_ref) {
let {
/** Start opting into the new margin-free styles that will become the default in a future version. */
__nextHasNoMarginBottom = false,
className,
label = (0,external_wp_i18n_namespaceObject.__)('Angle'),
onChange,
value
} = _ref;
if (!__nextHasNoMarginBottom) {
external_wp_deprecated_default()('Bottom margin styles for wp.components.AnglePickerControl', {
since: '6.1',
version: '6.4',
hint: 'Set the `__nextHasNoMarginBottom` prop to true to start opting into the new styles, which will become the default in a future version.'
});
}
const handleOnNumberChange = unprocessedValue => {
const inputValue = unprocessedValue !== '' ? parseInt(unprocessedValue, 10) : 0;
onChange(inputValue);
};
const classes = classnames_default()('components-angle-picker-control', className);
return (0,external_wp_element_namespaceObject.createElement)(angle_picker_control_styles_Root, {
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
className: classes,
gap: 4
}, (0,external_wp_element_namespaceObject.createElement)(flex_block_component, null, (0,external_wp_element_namespaceObject.createElement)(number_control, {
label: label,
className: "components-angle-picker-control__input-field",
max: 360,
min: 0,
onChange: handleOnNumberChange,
size: "__unstable-large",
step: "1",
value: value,
spinControls: "none",
suffix: (0,external_wp_element_namespaceObject.createElement)(spacer_component, {
as: text_component,
marginBottom: 0,
marginRight: space(3),
style: {
color: COLORS.ui.theme
}
}, "\xB0")
})), (0,external_wp_element_namespaceObject.createElement)(flex_item_component, {
style: {
marginBottom: space(1),
marginTop: 'auto'
}
}, (0,external_wp_element_namespaceObject.createElement)(angle_circle, {
"aria-hidden": "true",
value: value,
onChange: onChange
})));
}
// EXTERNAL MODULE: ./node_modules/remove-accents/index.js
var remove_accents = __webpack_require__(4793);
var remove_accents_default = /*#__PURE__*/__webpack_require__.n(remove_accents);
;// CONCATENATED MODULE: external ["wp","richText"]
var external_wp_richText_namespaceObject = window["wp"]["richText"];
;// CONCATENATED MODULE: external ["wp","a11y"]
var external_wp_a11y_namespaceObject = window["wp"]["a11y"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/strings.js
/**
* External dependencies
*/
const ALL_UNICODE_DASH_CHARACTERS = new RegExp(`[${[// - (hyphen-minus)
'\u002d', // ~ (tilde)
'\u007e', // (soft hyphen)
'\u00ad', // ֊ (armenian hyphen)
'\u058a', // ־ (hebrew punctuation maqaf)
'\u05be', // ᐀ (canadian syllabics hyphen)
'\u1400', // ᠆ (mongolian todo soft hyphen)
'\u1806', // ‐ (hyphen)
'\u2010', // non-breaking hyphen)
'\u2011', // ‒ (figure dash)
'\u2012', // – (en dash)
'\u2013', // — (em dash)
'\u2014', // ― (horizontal bar)
'\u2015', // ⁓ (swung dash)
'\u2053', // superscript minus)
'\u207b', // subscript minus)
'\u208b', // − (minus sign)
'\u2212', // ⸗ (double oblique hyphen)
'\u2e17', // ⸺ (two-em dash)
'\u2e3a', // ⸻ (three-em dash)
'\u2e3b', // 〜 (wave dash)
'\u301c', // 〰 (wavy dash)
'\u3030', // ゠ (katakana-hiragana double hyphen)
'\u30a0', // ︱ (presentation form for vertical em dash)
'\ufe31', // ︲ (presentation form for vertical en dash)
'\ufe32', // ﹘ (small em dash)
'\ufe58', // ﹣ (small hyphen-minus)
'\ufe63', // - (fullwidth hyphen-minus)
'\uff0d'].join('')}]`, 'g');
const normalizeTextString = value => {
return remove_accents_default()(value).toLocaleLowerCase().replace(ALL_UNICODE_DASH_CHARACTERS, '-');
};
/**
* Escapes the RegExp special characters.
*
* @param {string} string Input string.
*
* @return {string} Regex-escaped string.
*/
function escapeRegExp(string) {
return string.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&');
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/autocomplete/get-default-use-items.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function filterOptions(search) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
let maxResults = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 10;
const filtered = [];
for (let i = 0; i < options.length; i++) {
const option = options[i]; // Merge label into keywords.
let {
keywords = []
} = option;
if ('string' === typeof option.label) {
keywords = [...keywords, option.label];
}
const isMatch = keywords.some(keyword => search.test(remove_accents_default()(keyword)));
if (!isMatch) {
continue;
}
filtered.push(option); // Abort early if max reached.
if (filtered.length === maxResults) {
break;
}
}
return filtered;
}
function getDefaultUseItems(autocompleter) {
return filterValue => {
const [items, setItems] = (0,external_wp_element_namespaceObject.useState)([]);
/*
* We support both synchronous and asynchronous retrieval of completer options
* but internally treat all as async so we maintain a single, consistent code path.
*
* Because networks can be slow, and the internet is wonderfully unpredictable,
* we don't want two promises updating the state at once. This ensures that only
* the most recent promise will act on `optionsData`. This doesn't use the state
* because `setState` is batched, and so there's no guarantee that setting
* `activePromise` in the state would result in it actually being in `this.state`
* before the promise resolves and we check to see if this is the active promise or not.
*/
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
const {
options,
isDebounced
} = autocompleter;
const loadOptions = (0,external_wp_compose_namespaceObject.debounce)(() => {
const promise = Promise.resolve(typeof options === 'function' ? options(filterValue) : options).then(optionsData => {
if (promise.canceled) {
return;
}
const keyedOptions = optionsData.map((optionData, optionIndex) => ({
key: `${autocompleter.name}-${optionIndex}`,
value: optionData,
label: autocompleter.getOptionLabel(optionData),
keywords: autocompleter.getOptionKeywords ? autocompleter.getOptionKeywords(optionData) : [],
isDisabled: autocompleter.isOptionDisabled ? autocompleter.isOptionDisabled(optionData) : false
})); // Create a regular expression to filter the options.
const search = new RegExp('(?:\\b|\\s|^)' + escapeRegExp(filterValue), 'i');
setItems(filterOptions(search, keyedOptions));
});
return promise;
}, isDebounced ? 250 : 0);
const promise = loadOptions();
return () => {
loadOptions.cancel();
if (promise) {
promise.canceled = true;
}
};
}, [filterValue]);
return [items];
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/autocomplete/autocompleter-ui.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function getAutoCompleterUI(autocompleter) {
const useItems = autocompleter.useItems ? autocompleter.useItems : getDefaultUseItems(autocompleter);
function AutocompleterUI(_ref) {
let {
filterValue,
instanceId,
listBoxId,
className,
selectedIndex,
onChangeOptions,
onSelect,
onReset,
reset,
value,
contentRef
} = _ref;
const [items] = useItems(filterValue);
const popoverAnchor = (0,external_wp_richText_namespaceObject.useAnchor)({
editableContentElement: contentRef.current,
value
});
const popoverRef = (0,external_wp_element_namespaceObject.useRef)();
useOnClickOutside(popoverRef, reset);
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
onChangeOptions(items); // Temporarily disabling exhaustive-deps to avoid introducing unexpected side effecst.
// See https://github.com/WordPress/gutenberg/pull/41820
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [items]);
if (!items.length > 0) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(popover, {
focusOnMount: false,
onClose: onReset,
placement: "top-start",
className: "components-autocomplete__popover",
anchor: popoverAnchor,
ref: popoverRef
}, (0,external_wp_element_namespaceObject.createElement)("div", {
id: listBoxId,
role: "listbox",
className: "components-autocomplete__results"
}, items.map((option, index) => (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
key: option.key,
id: `components-autocomplete-item-${instanceId}-${option.key}`,
role: "option",
"aria-selected": index === selectedIndex,
disabled: option.isDisabled,
className: classnames_default()('components-autocomplete__result', className, {
'is-selected': index === selectedIndex
}),
onClick: () => onSelect(option)
}, option.label))));
}
return AutocompleterUI;
}
function useOnClickOutside(ref, handler) {
(0,external_wp_element_namespaceObject.useEffect)(() => {
const listener = event => {
// Do nothing if clicking ref's element or descendent elements, or if the ref is not referencing an element
if (!ref.current || ref.current.contains(event.target)) {
return;
}
handler(event);
};
document.addEventListener('mousedown', listener);
document.addEventListener('touchstart', listener);
return () => {
document.removeEventListener('mousedown', listener);
document.removeEventListener('touchstart', listener);
}; // Disable reason: `ref` is a ref object and should not be included in a
// hook's dependency list.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [handler]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/autocomplete/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* A raw completer option.
*
* @typedef {*} CompleterOption
*/
/**
* @callback FnGetOptions
*
* @return {(CompleterOption[]|Promise.<CompleterOption[]>)} The completer options or a promise for them.
*/
/**
* @callback FnGetOptionKeywords
* @param {CompleterOption} option a completer option.
*
* @return {string[]} list of key words to search.
*/
/**
* @callback FnIsOptionDisabled
* @param {CompleterOption} option a completer option.
*
* @return {string[]} whether or not the given option is disabled.
*/
/**
* @callback FnGetOptionLabel
* @param {CompleterOption} option a completer option.
*
* @return {(string|Array.<(string|WPElement)>)} list of react components to render.
*/
/**
* @callback FnAllowContext
* @param {string} before the string before the auto complete trigger and query.
* @param {string} after the string after the autocomplete trigger and query.
*
* @return {boolean} true if the completer can handle.
*/
/**
* @typedef {Object} OptionCompletion
* @property {'insert-at-caret'|'replace'} action the intended placement of the completion.
* @property {OptionCompletionValue} value the completion value.
*/
/**
* A completion value.
*
* @typedef {(string|WPElement|Object)} OptionCompletionValue
*/
/**
* @callback FnGetOptionCompletion
* @param {CompleterOption} value the value of the completer option.
* @param {string} query the text value of the autocomplete query.
*
* @return {(OptionCompletion|OptionCompletionValue)} the completion for the given option. If an
* OptionCompletionValue is returned, the
* completion action defaults to `insert-at-caret`.
*/
/**
* @typedef {Object} WPCompleter
* @property {string} name a way to identify a completer, useful for selective overriding.
* @property {?string} className A class to apply to the popup menu.
* @property {string} triggerPrefix the prefix that will display the menu.
* @property {(CompleterOption[]|FnGetOptions)} options the completer options or a function to get them.
* @property {?FnGetOptionKeywords} getOptionKeywords get the keywords for a given option.
* @property {?FnIsOptionDisabled} isOptionDisabled get whether or not the given option is disabled.
* @property {FnGetOptionLabel} getOptionLabel get the label for a given option.
* @property {?FnAllowContext} allowContext filter the context under which the autocomplete activates.
* @property {FnGetOptionCompletion} getOptionCompletion get the completion associated with a given option.
*/
function useAutocomplete(_ref) {
let {
record,
onChange,
onReplace,
completers,
contentRef
} = _ref;
const debouncedSpeak = (0,external_wp_compose_namespaceObject.useDebounce)(external_wp_a11y_namespaceObject.speak, 500);
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(useAutocomplete);
const [selectedIndex, setSelectedIndex] = (0,external_wp_element_namespaceObject.useState)(0);
const [filteredOptions, setFilteredOptions] = (0,external_wp_element_namespaceObject.useState)([]);
const [filterValue, setFilterValue] = (0,external_wp_element_namespaceObject.useState)('');
const [autocompleter, setAutocompleter] = (0,external_wp_element_namespaceObject.useState)(null);
const [AutocompleterUI, setAutocompleterUI] = (0,external_wp_element_namespaceObject.useState)(null);
const backspacing = (0,external_wp_element_namespaceObject.useRef)(false);
function insertCompletion(replacement) {
const end = record.start;
const start = end - autocompleter.triggerPrefix.length - filterValue.length;
const toInsert = (0,external_wp_richText_namespaceObject.create)({
html: (0,external_wp_element_namespaceObject.renderToString)(replacement)
});
onChange((0,external_wp_richText_namespaceObject.insert)(record, toInsert, start, end));
}
function select(option) {
const {
getOptionCompletion
} = autocompleter || {};
if (option.isDisabled) {
return;
}
if (getOptionCompletion) {
const completion = getOptionCompletion(option.value, filterValue);
const {
action,
value
} = undefined === completion.action || undefined === completion.value ? {
action: 'insert-at-caret',
value: completion
} : completion;
if ('replace' === action) {
onReplace([value]); // When replacing, the component will unmount, so don't reset
// state (below) on an unmounted component.
return;
} else if ('insert-at-caret' === action) {
insertCompletion(value);
}
} // Reset autocomplete state after insertion rather than before
// so insertion events don't cause the completion menu to redisplay.
reset();
}
function reset() {
setSelectedIndex(0);
setFilteredOptions([]);
setFilterValue('');
setAutocompleter(null);
setAutocompleterUI(null);
}
function announce(options) {
if (!debouncedSpeak) {
return;
}
if (!!options.length) {
debouncedSpeak((0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %d: number of results. */
(0,external_wp_i18n_namespaceObject._n)('%d result found, use up and down arrow keys to navigate.', '%d results found, use up and down arrow keys to navigate.', options.length), options.length), 'assertive');
} else {
debouncedSpeak((0,external_wp_i18n_namespaceObject.__)('No results.'), 'assertive');
}
}
/**
* Load options for an autocompleter.
*
* @param {Array} options
*/
function onChangeOptions(options) {
setSelectedIndex(options.length === filteredOptions.length ? selectedIndex : 0);
setFilteredOptions(options);
announce(options);
}
function handleKeyDown(event) {
backspacing.current = event.key === 'Backspace';
if (!autocompleter) {
return;
}
if (filteredOptions.length === 0) {
return;
}
if (event.defaultPrevented || // Ignore keydowns from IMEs
event.isComposing || // Workaround for Mac Safari where the final Enter/Backspace of an IME composition
// is `isComposing=false`, even though it's technically still part of the composition.
// These can only be detected by keyCode.
event.keyCode === 229) {
return;
}
switch (event.key) {
case 'ArrowUp':
setSelectedIndex((selectedIndex === 0 ? filteredOptions.length : selectedIndex) - 1);
break;
case 'ArrowDown':
setSelectedIndex((selectedIndex + 1) % filteredOptions.length);
break;
case 'Escape':
setAutocompleter(null);
setAutocompleterUI(null);
event.preventDefault();
break;
case 'Enter':
select(filteredOptions[selectedIndex]);
break;
case 'ArrowLeft':
case 'ArrowRight':
reset();
return;
default:
return;
} // Any handled key should prevent original behavior. This relies on
// the early return in the default case.
event.preventDefault();
} // textContent is a primitive (string), memoizing is not strictly necessary
// but this is a preemptive performance improvement, since the autocompleter
// is a potential bottleneck for the editor type metric.
const textContent = (0,external_wp_element_namespaceObject.useMemo)(() => {
if ((0,external_wp_richText_namespaceObject.isCollapsed)(record)) {
return (0,external_wp_richText_namespaceObject.getTextContent)((0,external_wp_richText_namespaceObject.slice)(record, 0));
}
}, [record]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (!textContent) {
reset();
return;
}
const text = remove_accents_default()(textContent);
const textAfterSelection = (0,external_wp_richText_namespaceObject.getTextContent)((0,external_wp_richText_namespaceObject.slice)(record, undefined, (0,external_wp_richText_namespaceObject.getTextContent)(record).length));
const completer = completers === null || completers === void 0 ? void 0 : completers.find(_ref2 => {
let {
triggerPrefix,
allowContext
} = _ref2;
const index = text.lastIndexOf(triggerPrefix);
if (index === -1) {
return false;
}
const textWithoutTrigger = text.slice(index + triggerPrefix.length);
const tooDistantFromTrigger = textWithoutTrigger.length > 50; // 50 chars seems to be a good limit.
// This is a final barrier to prevent the effect from completing with
// an extremely long string, which causes the editor to slow-down
// significantly. This could happen, for example, if `matchingWhileBackspacing`
// is true and one of the "words" end up being too long. If that's the case,
// it will be caught by this guard.
if (tooDistantFromTrigger) return false;
const mismatch = filteredOptions.length === 0;
const wordsFromTrigger = textWithoutTrigger.split(/\s/); // We need to allow the effect to run when not backspacing and if there
// was a mismatch. i.e when typing a trigger + the match string or when
// clicking in an existing trigger word on the page. We do that if we
// detect that we have one word from trigger in the current textual context.
//
// Ex.: "Some text @a" <-- "@a" will be detected as the trigger word and
// allow the effect to run. It will run until there's a mismatch.
const hasOneTriggerWord = wordsFromTrigger.length === 1; // This is used to allow the effect to run when backspacing and if
// "touching" a word that "belongs" to a trigger. We consider a "trigger
// word" any word up to the limit of 3 from the trigger character.
// Anything beyond that is ignored if there's a mismatch. This allows
// us to "escape" a mismatch when backspacing, but still imposing some
// sane limits.
//
// Ex: "Some text @marcelo sekkkk" <--- "kkkk" caused a mismatch, but
// if the user presses backspace here, it will show the completion popup again.
const matchingWhileBackspacing = backspacing.current && textWithoutTrigger.split(/\s/).length <= 3;
if (mismatch && !(matchingWhileBackspacing || hasOneTriggerWord)) {
return false;
}
if (allowContext && !allowContext(text.slice(0, index), textAfterSelection)) {
return false;
}
if (/^\s/.test(textWithoutTrigger) || /\s\s+$/.test(textWithoutTrigger)) {
return false;
}
return /[\u0000-\uFFFF]*$/.test(textWithoutTrigger);
});
if (!completer) {
reset();
return;
}
const safeTrigger = escapeRegExp(completer.triggerPrefix);
const match = text.slice(text.lastIndexOf(completer.triggerPrefix)).match(new RegExp(`${safeTrigger}([\u0000-\uFFFF]*)$`));
const query = match && match[1];
setAutocompleter(completer);
setAutocompleterUI(() => completer !== autocompleter ? getAutoCompleterUI(completer) : AutocompleterUI);
setFilterValue(query); // Temporarily disabling exhaustive-deps to avoid introducing unexpected side effecst.
// See https://github.com/WordPress/gutenberg/pull/41820
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [textContent]);
const {
key: selectedKey = ''
} = filteredOptions[selectedIndex] || {};
const {
className
} = autocompleter || {};
const isExpanded = !!autocompleter && filteredOptions.length > 0;
const listBoxId = isExpanded ? `components-autocomplete-listbox-${instanceId}` : null;
const activeId = isExpanded ? `components-autocomplete-item-${instanceId}-${selectedKey}` : null;
const hasSelection = record.start !== undefined;
return {
listBoxId,
activeId,
onKeyDown: handleKeyDown,
popover: hasSelection && AutocompleterUI && (0,external_wp_element_namespaceObject.createElement)(AutocompleterUI, {
className: className,
filterValue: filterValue,
instanceId: instanceId,
listBoxId: listBoxId,
selectedIndex: selectedIndex,
onChangeOptions: onChangeOptions,
onSelect: select,
value: record,
contentRef: contentRef,
reset: reset
})
};
}
function useAutocompleteProps(options) {
const [isVisible, setIsVisible] = (0,external_wp_element_namespaceObject.useState)(false);
const ref = (0,external_wp_element_namespaceObject.useRef)();
const recordAfterInput = (0,external_wp_element_namespaceObject.useRef)();
const onKeyDownRef = (0,external_wp_element_namespaceObject.useRef)();
const {
popover,
listBoxId,
activeId,
onKeyDown
} = useAutocomplete({ ...options,
contentRef: ref
});
onKeyDownRef.current = onKeyDown;
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (isVisible) {
if (!recordAfterInput.current) {
recordAfterInput.current = options.record;
} else if (recordAfterInput.current.start !== options.record.start || recordAfterInput.current.end !== options.record.end) {
setIsVisible(false);
recordAfterInput.current = null;
}
} // eslint-disable-next-line react-hooks/exhaustive-deps
}, [options.record]);
const mergedRefs = (0,external_wp_compose_namespaceObject.useMergeRefs)([ref, (0,external_wp_compose_namespaceObject.useRefEffect)(element => {
function _onKeyDown(event) {
onKeyDownRef.current(event);
}
function _onInput() {
// Only show auto complete UI if the user is inputting text.
setIsVisible(true);
recordAfterInput.current = null;
}
element.addEventListener('keydown', _onKeyDown);
element.addEventListener('input', _onInput);
return () => {
element.removeEventListener('keydown', _onKeyDown);
element.removeEventListener('input', _onInput);
};
}, [])]);
if (!isVisible) {
return {
ref: mergedRefs
};
}
return {
ref: mergedRefs,
children: popover,
'aria-autocomplete': listBoxId ? 'list' : undefined,
'aria-owns': listBoxId,
'aria-activedescendant': activeId
};
}
function Autocomplete(_ref3) {
let {
children,
isSelected,
...options
} = _ref3;
const {
popover,
...props
} = useAutocomplete(options);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, children(props), isSelected && popover);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/base-control/hooks.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Generate props for the `BaseControl` and the inner control itself.
*
* Namely, it takes care of generating a unique `id`, properly associating it with the `label` and `help` elements.
*
* @param props
*/
function useBaseControlProps(props) {
const {
help,
id: preferredId,
...restProps
} = props;
const uniqueId = (0,external_wp_compose_namespaceObject.useInstanceId)(base_control, 'wp-components-base-control', preferredId); // ARIA descriptions can only contain plain text, so fall back to aria-details if not.
const helpPropName = typeof help === 'string' ? 'aria-describedby' : 'aria-details';
return {
baseControlProps: {
id: uniqueId,
help,
...restProps
},
controlProps: {
id: uniqueId,
...(!!help ? {
[helpPropName]: `${uniqueId}__help`
} : {})
}
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/link.js
/**
* WordPress dependencies
*/
const link_link = (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: "M15.6 7.2H14v1.5h1.6c2 0 3.7 1.7 3.7 3.7s-1.7 3.7-3.7 3.7H14v1.5h1.6c2.8 0 5.2-2.3 5.2-5.2 0-2.9-2.3-5.2-5.2-5.2zM4.7 12.4c0-2 1.7-3.7 3.7-3.7H10V7.2H8.4c-2.9 0-5.2 2.3-5.2 5.2 0 2.9 2.3 5.2 5.2 5.2H10v-1.5H8.4c-2 0-3.7-1.7-3.7-3.7zm4.6.9h5.3v-1.5H9.3v1.5z"
}));
/* harmony default export */ var library_link = (link_link);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/link-off.js
/**
* WordPress dependencies
*/
const linkOff = (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: "M15.6 7.3h-.7l1.6-3.5-.9-.4-3.9 8.5H9v1.5h2l-1.3 2.8H8.4c-2 0-3.7-1.7-3.7-3.7s1.7-3.7 3.7-3.7H10V7.3H8.4c-2.9 0-5.2 2.3-5.2 5.2 0 2.9 2.3 5.2 5.2 5.2H9l-1.4 3.2.9.4 5.7-12.5h1.4c2 0 3.7 1.7 3.7 3.7s-1.7 3.7-3.7 3.7H14v1.5h1.6c2.9 0 5.2-2.3 5.2-5.2 0-2.9-2.4-5.2-5.2-5.2z"
}));
/* harmony default export */ var link_off = (linkOff);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-box-control/styles.js
function border_box_control_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const borderBoxControl = /*#__PURE__*/emotion_react_browser_esm_css( true ? "" : 0, true ? "" : 0);
const linkedBorderControl = () => /*#__PURE__*/emotion_react_browser_esm_css("flex:1;", rtl({
marginRight: '24px'
})(), ";" + ( true ? "" : 0), true ? "" : 0);
const wrapper = true ? {
name: "bjn8wh",
styles: "position:relative"
} : 0;
const borderBoxControlLinkedButton = size => {
return /*#__PURE__*/emotion_react_browser_esm_css("position:absolute;top:", size === '__unstable-large' ? '8px' : '3px', ";", rtl({
right: 0
})(), " line-height:0;" + ( true ? "" : 0), true ? "" : 0);
};
const borderBoxStyleWithFallback = border => {
const {
color = COLORS.gray[200],
style = 'solid',
width = config_values.borderWidth
} = border || {};
const clampedWidth = width !== config_values.borderWidth ? `clamp(1px, ${width}, 10px)` : width;
const hasVisibleBorder = !!width && width !== '0' || !!color;
const borderStyle = hasVisibleBorder ? style || 'solid' : style;
return `${color} ${borderStyle} ${clampedWidth}`;
};
const borderBoxControlVisualizer = (borders, size) => {
return /*#__PURE__*/emotion_react_browser_esm_css("position:absolute;top:", size === '__unstable-large' ? '20px' : '15px', ";right:", size === '__unstable-large' ? '39px' : '29px', ";bottom:", size === '__unstable-large' ? '20px' : '15px', ";left:", size === '__unstable-large' ? '39px' : '29px', ";border-top:", borderBoxStyleWithFallback(borders === null || borders === void 0 ? void 0 : borders.top), ";border-bottom:", borderBoxStyleWithFallback(borders === null || borders === void 0 ? void 0 : borders.bottom), ";", rtl({
borderLeft: borderBoxStyleWithFallback(borders === null || borders === void 0 ? void 0 : borders.left)
})(), " ", rtl({
borderRight: borderBoxStyleWithFallback(borders === null || borders === void 0 ? void 0 : borders.right)
})(), ";" + ( true ? "" : 0), true ? "" : 0);
};
const borderBoxControlSplitControls = size => /*#__PURE__*/emotion_react_browser_esm_css("position:relative;flex:1;width:", size === '__unstable-large' ? undefined : '80%', ";" + ( true ? "" : 0), true ? "" : 0);
const centeredBorderControl = true ? {
name: "1nwbfnf",
styles: "grid-column:span 2;margin:0 auto"
} : 0;
const rightBorderControl = () => /*#__PURE__*/emotion_react_browser_esm_css(rtl({
marginLeft: 'auto'
})(), ";" + ( true ? "" : 0), true ? "" : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-box-control/border-box-control-linked-button/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useBorderBoxControlLinkedButton(props) {
const {
className,
size = 'default',
...otherProps
} = useContextSystem(props, 'BorderBoxControlLinkedButton'); // Generate class names.
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderBoxControlLinkedButton(size), className);
}, [className, cx, size]);
return { ...otherProps,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-box-control/border-box-control-linked-button/component.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const BorderBoxControlLinkedButton = (props, forwardedRef) => {
const {
className,
isLinked,
...buttonProps
} = useBorderBoxControlLinkedButton(props);
const label = isLinked ? (0,external_wp_i18n_namespaceObject.__)('Unlink sides') : (0,external_wp_i18n_namespaceObject.__)('Link sides');
return (0,external_wp_element_namespaceObject.createElement)(tooltip, {
text: label
}, (0,external_wp_element_namespaceObject.createElement)(component, {
className: className
}, (0,external_wp_element_namespaceObject.createElement)(build_module_button, extends_extends({}, buttonProps, {
isSmall: true,
icon: isLinked ? library_link : link_off,
iconSize: 24,
"aria-label": label,
ref: forwardedRef
}))));
};
const ConnectedBorderBoxControlLinkedButton = contextConnect(BorderBoxControlLinkedButton, 'BorderBoxControlLinkedButton');
/* harmony default export */ var border_box_control_linked_button_component = (ConnectedBorderBoxControlLinkedButton);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-box-control/border-box-control-visualizer/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useBorderBoxControlVisualizer(props) {
const {
className,
value,
size = 'default',
...otherProps
} = useContextSystem(props, 'BorderBoxControlVisualizer'); // Generate class names.
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderBoxControlVisualizer(value, size), className);
}, [cx, className, value, size]);
return { ...otherProps,
className: classes,
value
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-box-control/border-box-control-visualizer/component.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const BorderBoxControlVisualizer = (props, forwardedRef) => {
const {
value,
...otherProps
} = useBorderBoxControlVisualizer(props);
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({}, otherProps, {
ref: forwardedRef
}));
};
const ConnectedBorderBoxControlVisualizer = contextConnect(BorderBoxControlVisualizer, 'BorderBoxControlVisualizer');
/* harmony default export */ var border_box_control_visualizer_component = (ConnectedBorderBoxControlVisualizer);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/close-small.js
/**
* WordPress dependencies
*/
const closeSmall = (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: "M12 13.06l3.712 3.713 1.061-1.06L13.061 12l3.712-3.712-1.06-1.06L12 10.938 8.288 7.227l-1.061 1.06L10.939 12l-3.712 3.712 1.06 1.061L12 13.061z"
}));
/* harmony default export */ var close_small = (closeSmall);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/line-solid.js
/**
* WordPress dependencies
*/
const lineSolid = (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: "M5 11.25h14v1.5H5z"
}));
/* harmony default export */ var line_solid = (lineSolid);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/line-dashed.js
/**
* WordPress dependencies
*/
const lineDashed = (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, {
fillRule: "evenodd",
d: "M5 11.25h3v1.5H5v-1.5zm5.5 0h3v1.5h-3v-1.5zm8.5 0h-3v1.5h3v-1.5z",
clipRule: "evenodd"
}));
/* harmony default export */ var line_dashed = (lineDashed);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/line-dotted.js
/**
* WordPress dependencies
*/
const lineDotted = (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, {
fillRule: "evenodd",
d: "M5.25 11.25h1.5v1.5h-1.5v-1.5zm3 0h1.5v1.5h-1.5v-1.5zm4.5 0h-1.5v1.5h1.5v-1.5zm1.5 0h1.5v1.5h-1.5v-1.5zm4.5 0h-1.5v1.5h1.5v-1.5z",
clipRule: "evenodd"
}));
/* harmony default export */ var line_dotted = (lineDotted);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/unit-control/styles/unit-control-styles.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
// Using `selectSize` instead of `size` to avoid a type conflict with the
// `size` HTML attribute of the `select` element.
// TODO: Resolve need to use &&& to increase specificity
// https://github.com/WordPress/gutenberg/issues/18483
const ValueInput = /*#__PURE__*/createStyled(number_control, true ? {
target: "e1bagdl32"
} : 0)("&&&{input{display:block;width:100%;}", BackdropUI, "{transition:box-shadow 0.1s linear;}}" + ( true ? "" : 0));
const baseUnitLabelStyles = _ref => {
let {
selectSize
} = _ref;
const sizes = {
default: /*#__PURE__*/emotion_react_browser_esm_css("box-sizing:border-box;padding:2px 1px;width:20px;color:", COLORS.gray[800], ";font-size:8px;line-height:1;letter-spacing:-0.5px;text-transform:uppercase;text-align-last:center;" + ( true ? "" : 0), true ? "" : 0),
large: /*#__PURE__*/emotion_react_browser_esm_css("box-sizing:border-box;min-width:24px;max-width:48px;height:24px;margin-inline-end:", space(2), ";padding:", space(1), ";color:", COLORS.ui.theme, ";font-size:13px;line-height:1;text-align-last:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;" + ( true ? "" : 0), true ? "" : 0)
};
return selectSize === '__unstable-large' ? sizes.large : sizes.default;
};
const UnitLabel = createStyled("div", true ? {
target: "e1bagdl31"
} : 0)("&&&{pointer-events:none;", baseUnitLabelStyles, ";color:", COLORS.gray[900], ";}" + ( true ? "" : 0));
const unitSelectSizes = _ref2 => {
let {
selectSize = 'default'
} = _ref2;
const sizes = {
default: /*#__PURE__*/emotion_react_browser_esm_css("height:100%;border:1px solid transparent;transition:box-shadow 0.1s linear,border 0.1s linear;", rtl({
borderTopLeftRadius: 0,
borderBottomLeftRadius: 0
})(), " &:not(:disabled):hover{background-color:", COLORS.gray[100], ";}&:focus{border:1px solid ", COLORS.ui.borderFocus, ";box-shadow:inset 0 0 0 ", config_values.borderWidth + ' ' + COLORS.ui.borderFocus, ";outline-offset:0;outline:2px solid transparent;z-index:1;}" + ( true ? "" : 0), true ? "" : 0),
large: /*#__PURE__*/emotion_react_browser_esm_css("display:flex;justify-content:center;align-items:center;&:hover{color:", COLORS.ui.borderFocus, ";box-shadow:inset 0 0 0 ", config_values.borderWidth + ' ' + COLORS.ui.borderFocus, ";outline:", config_values.borderWidth, " solid transparent;}&:focus{box-shadow:0 0 0 ", config_values.borderWidthFocus + ' ' + COLORS.ui.borderFocus, ";outline:", config_values.borderWidthFocus, " solid transparent;}" + ( true ? "" : 0), true ? "" : 0)
};
return selectSize === '__unstable-large' ? sizes.large : sizes.default;
};
const UnitSelect = createStyled("select", true ? {
target: "e1bagdl30"
} : 0)("&&&{appearance:none;background:transparent;border-radius:2px;border:none;display:block;outline:none;margin:0;min-height:auto;font-family:inherit;", baseUnitLabelStyles, ";", unitSelectSizes, ";&:not( :disabled ){cursor:pointer;}}" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-control/styles.js
function border_control_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const styles_labelStyles = true ? {
name: "f3vz0n",
styles: "font-weight:500"
} : 0;
const focusBoxShadow = /*#__PURE__*/emotion_react_browser_esm_css("box-shadow:inset 0 0 0 ", config_values.borderWidth, " ", COLORS.ui.borderFocus, ";" + ( true ? "" : 0), true ? "" : 0);
const borderControl = /*#__PURE__*/emotion_react_browser_esm_css("border:0;padding:0;margin:0;", boxSizingReset, ";" + ( true ? "" : 0), true ? "" : 0);
const innerWrapper = () => /*#__PURE__*/emotion_react_browser_esm_css(ValueInput, "{flex:1 1 40%;}&& ", UnitSelect, "{min-height:0;}" + ( true ? "" : 0), true ? "" : 0);
/*
* This style is only applied to the UnitControl wrapper when the border width
* field should be a set width. Omitting this allows the UnitControl &
* RangeControl to share the available width in a 40/60 split respectively.
*/
const styles_wrapperWidth = /*#__PURE__*/emotion_react_browser_esm_css(ValueInput, "{flex:0 0 auto;}" + ( true ? "" : 0), true ? "" : 0);
const wrapperHeight = size => {
return /*#__PURE__*/emotion_react_browser_esm_css("height:", size === '__unstable-large' ? '40px' : '30px', ";" + ( true ? "" : 0), true ? "" : 0);
};
const borderControlDropdown = size => /*#__PURE__*/emotion_react_browser_esm_css("background:#fff;&&>button{height:", size === '__unstable-large' ? '40px' : '30px', ";width:", size === '__unstable-large' ? '40px' : '30px', ";padding:0;display:flex;align-items:center;justify-content:center;", rtl({
borderRadius: `2px 0 0 2px`
}, {
borderRadius: `0 2px 2px 0`
})(), " border:", config_values.borderWidth, " solid ", COLORS.ui.border, ";&:focus,&:hover:not( :disabled ){", focusBoxShadow, " border-color:", COLORS.ui.borderFocus, ";z-index:1;position:relative;}}" + ( true ? "" : 0), true ? "" : 0);
const colorIndicatorBorder = border => {
const {
color,
style
} = border || {};
const fallbackColor = !!style && style !== 'none' ? COLORS.gray[300] : undefined;
return /*#__PURE__*/emotion_react_browser_esm_css("border-style:", style === 'none' ? 'solid' : style, ";border-color:", color || fallbackColor, ";" + ( true ? "" : 0), true ? "" : 0);
};
const colorIndicatorWrapper = (border, size) => {
const {
style
} = border || {};
return /*#__PURE__*/emotion_react_browser_esm_css("border-radius:9999px;border:2px solid transparent;", style ? colorIndicatorBorder(border) : undefined, " width:", size === '__unstable-large' ? '24px' : '22px', ";height:", size === '__unstable-large' ? '24px' : '22px', ";padding:", size === '__unstable-large' ? '2px' : '1px', ";&>span{height:", space(4), ";width:", space(4), ";background:linear-gradient(\n\t\t\t\t-45deg,\n\t\t\t\ttransparent 48%,\n\t\t\t\trgb( 0 0 0 / 20% ) 48%,\n\t\t\t\trgb( 0 0 0 / 20% ) 52%,\n\t\t\t\ttransparent 52%\n\t\t\t);}" + ( true ? "" : 0), true ? "" : 0);
}; // Must equal $color-palette-circle-size from:
// @wordpress/components/src/circular-option-picker/style.scss
const swatchSize = 28;
const swatchGap = 12;
const borderControlPopoverControls = /*#__PURE__*/emotion_react_browser_esm_css("width:", swatchSize * 6 + swatchGap * 5, "px;>div:first-of-type>", StyledLabel, "{margin-bottom:0;", styles_labelStyles, ";}&& ", StyledLabel, "+button:not( .has-text ){min-width:24px;padding:0;}" + ( true ? "" : 0), true ? "" : 0);
const borderControlPopoverContent = /*#__PURE__*/emotion_react_browser_esm_css( true ? "" : 0, true ? "" : 0);
const borderColorIndicator = /*#__PURE__*/emotion_react_browser_esm_css( true ? "" : 0, true ? "" : 0);
const resetButton = /*#__PURE__*/emotion_react_browser_esm_css("justify-content:center;width:100%;&&{border-top:", config_values.borderWidth, " solid ", COLORS.gray[200], ";border-top-left-radius:0;border-top-right-radius:0;height:46px;}" + ( true ? "" : 0), true ? "" : 0);
const borderControlStylePicker = /*#__PURE__*/emotion_react_browser_esm_css(StyledLabel, "{", styles_labelStyles, ";}" + ( true ? "" : 0), true ? "" : 0);
const borderStyleButton = true ? {
name: "1486260",
styles: "&&&&&{min-width:30px;width:30px;height:30px;padding:3px;}"
} : 0;
const borderSlider = () => /*#__PURE__*/emotion_react_browser_esm_css("flex:1 1 60%;", rtl({
marginRight: space(3)
})(), ";" + ( true ? "" : 0), true ? "" : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-control/border-control-style-picker/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useBorderControlStylePicker(props) {
const {
className,
...otherProps
} = useContextSystem(props, 'BorderControlStylePicker'); // Generate class names.
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderControlStylePicker, className);
}, [className, cx]);
const buttonClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderStyleButton);
}, [cx]);
return { ...otherProps,
className: classes,
buttonClassName
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-control/border-control-style-picker/component.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const BORDER_STYLES = [{
label: (0,external_wp_i18n_namespaceObject.__)('Solid'),
icon: line_solid,
value: 'solid'
}, {
label: (0,external_wp_i18n_namespaceObject.__)('Dashed'),
icon: line_dashed,
value: 'dashed'
}, {
label: (0,external_wp_i18n_namespaceObject.__)('Dotted'),
icon: line_dotted,
value: 'dotted'
}];
const component_Label = props => {
const {
label,
hideLabelFromVision
} = props;
if (!label) {
return null;
}
return hideLabelFromVision ? (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, {
as: "label"
}, label) : (0,external_wp_element_namespaceObject.createElement)(StyledLabel, null, label);
};
const BorderControlStylePicker = (props, forwardedRef) => {
const {
buttonClassName,
hideLabelFromVision,
label,
onChange,
value,
...otherProps
} = useBorderControlStylePicker(props);
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({}, otherProps, {
ref: forwardedRef
}), (0,external_wp_element_namespaceObject.createElement)(component_Label, {
label: label,
hideLabelFromVision: hideLabelFromVision
}), (0,external_wp_element_namespaceObject.createElement)(flex_component, {
justify: "flex-start",
gap: 1
}, BORDER_STYLES.map(borderStyle => (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
key: borderStyle.value,
className: buttonClassName,
icon: borderStyle.icon,
isSmall: true,
isPressed: borderStyle.value === value,
onClick: () => onChange(borderStyle.value === value ? undefined : borderStyle.value),
"aria-label": borderStyle.label,
label: borderStyle.label,
showTooltip: true
}))));
};
const ConnectedBorderControlStylePicker = contextConnect(BorderControlStylePicker, 'BorderControlStylePicker');
/* harmony default export */ var border_control_style_picker_component = (ConnectedBorderControlStylePicker);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-indicator/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedColorIndicator(props, forwardedRef) {
const {
className,
colorValue,
...additionalProps
} = props;
return (0,external_wp_element_namespaceObject.createElement)("span", extends_extends({
className: classnames_default()('component-color-indicator', className),
style: {
background: colorValue
},
ref: forwardedRef
}, additionalProps));
}
/**
* ColorIndicator is a React component that renders a specific color in a
* circle. It's often used to summarize a collection of used colors in a child
* component.
*
* ```jsx
* import { ColorIndicator } from '@wordpress/components';
*
* const MyColorIndicator = () => <ColorIndicator colorValue="#0073aa" />;
* ```
*/
const ColorIndicator = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedColorIndicator);
/* harmony default export */ var color_indicator = (ColorIndicator);
;// CONCATENATED MODULE: ./node_modules/colord/plugins/a11y.mjs
var a11y_o=function(o){var t=o/255;return t<.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)},a11y_t=function(t){return.2126*a11y_o(t.r)+.7152*a11y_o(t.g)+.0722*a11y_o(t.b)};/* harmony default export */ function a11y(o){o.prototype.luminance=function(){return o=a11y_t(this.rgba),void 0===(r=2)&&(r=0),void 0===n&&(n=Math.pow(10,r)),Math.round(n*o)/n+0;var o,r,n},o.prototype.contrast=function(r){void 0===r&&(r="#FFF");var n,a,i,e,v,u,d,c=r instanceof o?r:new o(r);return e=this.rgba,v=c.toRgb(),u=a11y_t(e),d=a11y_t(v),n=u>d?(u+.05)/(d+.05):(d+.05)/(u+.05),void 0===(a=2)&&(a=0),void 0===i&&(i=Math.pow(10,a)),Math.floor(i*n)/i+0},o.prototype.isReadable=function(o,t){return void 0===o&&(o="#FFF"),void 0===t&&(t={}),this.contrast(o)>=(e=void 0===(i=(r=t).size)?"normal":i,"AAA"===(a=void 0===(n=r.level)?"AA":n)&&"normal"===e?7:"AA"===a&&"large"===e?3:4.5);var r,n,a,i,e}}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/dropdown/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useObservableState(initialState, onStateChange) {
const [state, setState] = (0,external_wp_element_namespaceObject.useState)(initialState);
return [state, value => {
setState(value);
if (onStateChange) {
onStateChange(value);
}
}];
}
function UnforwardedDropdown(_ref, forwardedRef) {
let {
renderContent,
renderToggle,
className,
contentClassName,
expandOnMobile,
headerTitle,
focusOnMount,
popoverProps,
onClose,
onToggle,
style,
// Deprecated props
position
} = _ref;
if (position !== undefined) {
external_wp_deprecated_default()('`position` prop in wp.components.Dropdown', {
since: '6.2',
alternative: '`popoverProps.placement` prop',
hint: 'Note that the `position` prop will override any values passed through the `popoverProps.placement` prop.'
});
} // Use internal state instead of a ref to make sure that the component
// re-renders when the popover's anchor updates.
const [fallbackPopoverAnchor, setFallbackPopoverAnchor] = (0,external_wp_element_namespaceObject.useState)(null);
const containerRef = (0,external_wp_element_namespaceObject.useRef)();
const [isOpen, setIsOpen] = useObservableState(false, onToggle);
(0,external_wp_element_namespaceObject.useEffect)(() => () => {
if (onToggle && isOpen) {
onToggle(false);
}
}, [onToggle, isOpen]);
function toggle() {
setIsOpen(!isOpen);
}
/**
* Closes the popover when focus leaves it unless the toggle was pressed or
* focus has moved to a separate dialog. The former is to let the toggle
* handle closing the popover and the latter is to preserve presence in
* case a dialog has opened, allowing focus to return when it's dismissed.
*/
function closeIfFocusOutside() {
var _ownerDocument$active;
if (!containerRef.current) {
return;
}
const {
ownerDocument
} = containerRef.current;
const dialog = ownerDocument === null || ownerDocument === void 0 ? void 0 : (_ownerDocument$active = ownerDocument.activeElement) === null || _ownerDocument$active === void 0 ? void 0 : _ownerDocument$active.closest('[role="dialog"]');
if (!containerRef.current.contains(ownerDocument.activeElement) && (!dialog || dialog.contains(containerRef.current))) {
close();
}
}
function close() {
if (onClose) {
onClose();
}
setIsOpen(false);
}
const args = {
isOpen,
onToggle: toggle,
onClose: close
};
const popoverPropsHaveAnchor = !!(popoverProps !== null && popoverProps !== void 0 && popoverProps.anchor) || // Note: `anchorRef`, `getAnchorRect` and `anchorRect` are deprecated and
// be removed from `Popover` from WordPress 6.3
!!(popoverProps !== null && popoverProps !== void 0 && popoverProps.anchorRef) || !!(popoverProps !== null && popoverProps !== void 0 && popoverProps.getAnchorRect) || !!(popoverProps !== null && popoverProps !== void 0 && popoverProps.anchorRect);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('components-dropdown', className),
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([containerRef, forwardedRef, setFallbackPopoverAnchor]) // Some UAs focus the closest focusable parent when the toggle is
// clicked. Making this div focusable ensures such UAs will focus
// it and `closeIfFocusOutside` can tell if the toggle was clicked.
,
tabIndex: -1,
style: style
}, renderToggle(args), isOpen && (0,external_wp_element_namespaceObject.createElement)(popover, extends_extends({
position: position,
onClose: close,
onFocusOutside: closeIfFocusOutside,
expandOnMobile: expandOnMobile,
headerTitle: headerTitle,
focusOnMount: focusOnMount // This value is used to ensure that the dropdowns
// align with the editor header by default.
,
offset: 13,
anchor: !popoverPropsHaveAnchor ? fallbackPopoverAnchor : undefined
}, popoverProps, {
className: classnames_default()('components-dropdown__content', popoverProps === null || popoverProps === void 0 ? void 0 : popoverProps.className, contentClassName)
}), renderContent(args)));
}
/**
* Renders a button that opens a floating content modal when clicked.
*
* ```jsx
* import { Button, Dropdown } from '@wordpress/components';
*
* const MyDropdown = () => (
* <Dropdown
* className="my-container-class-name"
* contentClassName="my-dropdown-content-classname"
* popoverProps={ { placement: 'bottom-start' } }
* renderToggle={ ( { isOpen, onToggle } ) => (
* <Button
* variant="primary"
* onClick={ onToggle }
* aria-expanded={ isOpen }
* >
* Toggle Dropdown!
* </Button>
* ) }
* renderContent={ () => <div>This is the content of the dropdown.</div> }
* />
* );
* ```
*/
const Dropdown = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedDropdown);
/* harmony default export */ var dropdown = (Dropdown);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/input-suffix-wrapper.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedInputControlSuffixWrapper(props, forwardedRef) {
const derivedProps = useContextSystem(props, 'InputControlSuffixWrapper');
return (0,external_wp_element_namespaceObject.createElement)(spacer_component, extends_extends({
marginBottom: 0
}, derivedProps, {
ref: forwardedRef
}));
}
/**
* A convenience wrapper for the `suffix` when you want to apply
* standard padding in accordance with the size variant.
*
* ```jsx
* import {
* __experimentalInputControl as InputControl,
* __experimentalInputControlSuffixWrapper as InputControlSuffixWrapper,
* } from '@wordpress/components';
*
* <InputControl
* suffix={<InputControlSuffixWrapper>%</InputControlSuffixWrapper>}
* />
* ```
*/
const InputControlSuffixWrapper = contextConnect(UnconnectedInputControlSuffixWrapper, 'InputControlSuffixWrapper');
/* harmony default export */ var input_suffix_wrapper = (InputControlSuffixWrapper);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/select-control/styles/select-control-styles.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const select_control_styles_disabledStyles = _ref => {
let {
disabled
} = _ref;
if (!disabled) return '';
return /*#__PURE__*/emotion_react_browser_esm_css({
color: COLORS.ui.textDisabled
}, true ? "" : 0, true ? "" : 0);
};
const select_control_styles_fontSizeStyles = _ref2 => {
let {
selectSize = 'default'
} = _ref2;
const sizes = {
default: '13px',
small: '11px',
'__unstable-large': '13px'
};
const fontSize = sizes[selectSize];
const fontSizeMobile = '16px';
if (!fontSize) return '';
return /*#__PURE__*/emotion_react_browser_esm_css("font-size:", fontSizeMobile, ";@media ( min-width: 600px ){font-size:", fontSize, ";}" + ( true ? "" : 0), true ? "" : 0);
};
const select_control_styles_sizeStyles = _ref3 => {
let {
__next36pxDefaultSize,
multiple,
selectSize = 'default'
} = _ref3;
if (multiple) {
// When `multiple`, just use the native browser styles
// without setting explicit height.
return;
}
const sizes = {
default: {
height: 36,
minHeight: 36,
paddingTop: 0,
paddingBottom: 0
},
small: {
height: 24,
minHeight: 24,
paddingTop: 0,
paddingBottom: 0
},
'__unstable-large': {
height: 40,
minHeight: 40,
paddingTop: 0,
paddingBottom: 0
}
};
if (!__next36pxDefaultSize) {
sizes.default = {
height: 30,
minHeight: 30,
paddingTop: 0,
paddingBottom: 0
};
}
const style = sizes[selectSize] || sizes.default;
return /*#__PURE__*/emotion_react_browser_esm_css(style, true ? "" : 0, true ? "" : 0);
};
const chevronIconSize = 18;
const sizePaddings = _ref4 => {
let {
__next36pxDefaultSize,
multiple,
selectSize = 'default'
} = _ref4;
const padding = {
default: 16,
small: 8,
'__unstable-large': 16
};
if (!__next36pxDefaultSize) {
padding.default = 8;
}
const selectedPadding = padding[selectSize] || padding.default;
return rtl({
paddingLeft: selectedPadding,
paddingRight: selectedPadding + chevronIconSize,
...(multiple ? {
paddingTop: selectedPadding,
paddingBottom: selectedPadding
} : {})
});
};
const overflowStyles = _ref5 => {
let {
multiple
} = _ref5;
return {
overflow: multiple ? 'auto' : 'hidden'
};
}; // TODO: Resolve need to use &&& to increase specificity
// https://github.com/WordPress/gutenberg/issues/18483
const Select = createStyled("select", true ? {
target: "e1mv6sxx2"
} : 0)("&&&{appearance:none;background:transparent;box-sizing:border-box;border:none;box-shadow:none!important;color:", COLORS.gray[900], ";display:block;font-family:inherit;margin:0;width:100%;max-width:none;cursor:pointer;white-space:nowrap;text-overflow:ellipsis;", select_control_styles_disabledStyles, ";", select_control_styles_fontSizeStyles, ";", select_control_styles_sizeStyles, ";", sizePaddings, ";", overflowStyles, ";}" + ( true ? "" : 0));
const DownArrowWrapper = createStyled("div", true ? {
target: "e1mv6sxx1"
} : 0)("margin-inline-end:", space(-1), ";line-height:0;" + ( true ? "" : 0));
const InputControlSuffixWrapperWithClickThrough = /*#__PURE__*/createStyled(input_suffix_wrapper, true ? {
target: "e1mv6sxx0"
} : 0)("position:absolute;pointer-events:none;", rtl({
right: 0
}), ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/icon/index.js
/**
* WordPress dependencies
*/
/** @typedef {{icon: JSX.Element, size?: number} & import('@wordpress/primitives').SVGProps} IconProps */
/**
* Return an SVG icon.
*
* @param {IconProps} props icon is the SVG component to render
* size is a number specifiying the icon size in pixels
* Other props will be passed to wrapped SVG component
*
* @return {JSX.Element} Icon component
*/
function icon_Icon(_ref) {
let {
icon,
size = 24,
...props
} = _ref;
return (0,external_wp_element_namespaceObject.cloneElement)(icon, {
width: size,
height: size,
...props
});
}
/* harmony default export */ var icons_build_module_icon = (icon_Icon);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/chevron-down.js
/**
* WordPress dependencies
*/
const chevronDown = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M17.5 11.6L12 16l-5.5-4.4.9-1.2L12 14l4.5-3.6 1 1.2z"
}));
/* harmony default export */ var chevron_down = (chevronDown);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/select-control/chevron-down.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const SelectControlChevronDown = () => {
return (0,external_wp_element_namespaceObject.createElement)(InputControlSuffixWrapperWithClickThrough, null, (0,external_wp_element_namespaceObject.createElement)(DownArrowWrapper, null, (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, {
icon: chevron_down,
size: chevronIconSize
})));
};
/* harmony default export */ var select_control_chevron_down = (SelectControlChevronDown);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/select-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const select_control_noop = () => {};
function select_control_useUniqueId(idProp) {
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(SelectControl);
const id = `inspector-select-control-${instanceId}`;
return idProp || id;
}
function UnforwardedSelectControl(_ref, ref) {
let {
className,
disabled = false,
help,
hideLabelFromVision,
id: idProp,
label,
multiple = false,
onBlur = select_control_noop,
onChange = select_control_noop,
onFocus = select_control_noop,
options = [],
size = 'default',
value: valueProp,
labelPosition = 'top',
children,
prefix,
suffix,
__next36pxDefaultSize = false,
__nextHasNoMarginBottom = false,
...props
} = _ref;
const [isFocused, setIsFocused] = (0,external_wp_element_namespaceObject.useState)(false);
const id = select_control_useUniqueId(idProp);
const helpId = help ? `${id}__help` : undefined; // Disable reason: A select with an onchange throws a warning.
if (!(options !== null && options !== void 0 && options.length) && !children) return null;
const handleOnBlur = event => {
onBlur(event);
setIsFocused(false);
};
const handleOnFocus = event => {
onFocus(event);
setIsFocused(true);
};
const handleOnChange = event => {
if (multiple) {
const selectedOptions = Array.from(event.target.options).filter(_ref2 => {
let {
selected
} = _ref2;
return selected;
});
const newValues = selectedOptions.map(_ref3 => {
let {
value
} = _ref3;
return value;
});
onChange(newValues);
return;
}
onChange(event.target.value, {
event
});
};
const classes = classnames_default()('components-select-control', className);
/* eslint-disable jsx-a11y/no-onchange */
return (0,external_wp_element_namespaceObject.createElement)(base_control, {
help: help,
id: id,
__nextHasNoMarginBottom: __nextHasNoMarginBottom
}, (0,external_wp_element_namespaceObject.createElement)(input_base, {
className: classes,
disabled: disabled,
hideLabelFromVision: hideLabelFromVision,
id: id,
isFocused: isFocused,
label: label,
size: size,
suffix: suffix || !multiple && (0,external_wp_element_namespaceObject.createElement)(select_control_chevron_down, null),
prefix: prefix,
labelPosition: labelPosition,
__next36pxDefaultSize: __next36pxDefaultSize
}, (0,external_wp_element_namespaceObject.createElement)(Select, extends_extends({}, props, {
__next36pxDefaultSize: __next36pxDefaultSize,
"aria-describedby": helpId,
className: "components-select-control__input",
disabled: disabled,
id: id,
multiple: multiple,
onBlur: handleOnBlur,
onChange: handleOnChange,
onFocus: handleOnFocus,
ref: ref,
selectSize: size,
value: valueProp
}), children || options.map((option, index) => {
const key = option.id || `${option.label}-${option.value}-${index}`;
return (0,external_wp_element_namespaceObject.createElement)("option", {
key: key,
value: option.value,
disabled: option.disabled
}, option.label);
}))));
/* eslint-enable jsx-a11y/no-onchange */
}
/**
* `SelectControl` allows users to select from a single or multiple option menu.
* It functions as a wrapper around the browser's native `<select>` element.
*
* @example
* import { SelectControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MySelectControl = () => {
* const [ size, setSize ] = useState( '50%' );
*
* return (
* <SelectControl
* label="Size"
* value={ size }
* options={ [
* { label: 'Big', value: '100%' },
* { label: 'Medium', value: '50%' },
* { label: 'Small', value: '25%' },
* ] }
* onChange={ setSize }
* />
* );
* };
*/
const SelectControl = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedSelectControl);
/* harmony default export */ var select_control = (SelectControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/hooks/use-controlled-state.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* @template T
* @typedef Options
* @property {T | undefined} initial Initial value
* @property {T | ""} fallback Fallback value
*/
/** @type {Readonly<{ initial: undefined, fallback: '' }>} */
const defaultOptions = {
initial: undefined,
/**
* Defaults to empty string, as that is preferred for usage with
* <input />, <textarea />, and <select /> form elements.
*/
fallback: ''
};
/**
* Custom hooks for "controlled" components to track and consolidate internal
* state and incoming values. This is useful for components that render
* `input`, `textarea`, or `select` HTML elements.
*
* https://reactjs.org/docs/forms.html#controlled-components
*
* At first, a component using useControlledState receives an initial prop
* value, which is used as initial internal state.
*
* This internal state can be maintained and updated without
* relying on new incoming prop values.
*
* Unlike the basic useState hook, useControlledState's state can
* be updated if a new incoming prop value is changed.
*
* @template T
*
* @param {T | undefined} currentState The current value.
* @param {Options<T>} [options=defaultOptions] Additional options for the hook.
*
* @return {[T | "", (nextState: T) => void]} The controlled value and the value setter.
*/
function useControlledState(currentState) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultOptions;
const {
initial,
fallback
} = { ...defaultOptions,
...options
};
const [internalState, setInternalState] = (0,external_wp_element_namespaceObject.useState)(currentState);
const hasCurrentState = isValueDefined(currentState);
/*
* Resets internal state if value every changes from uncontrolled <-> controlled.
*/
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (hasCurrentState && internalState) {
setInternalState(undefined);
}
}, [hasCurrentState, internalState]);
const state = getDefinedValue([currentState, internalState, initial], fallback);
/* eslint-disable jsdoc/no-undefined-types */
/** @type {(nextState: T) => void} */
const setState = (0,external_wp_element_namespaceObject.useCallback)(nextState => {
if (!hasCurrentState) {
setInternalState(nextState);
}
}, [hasCurrentState]);
/* eslint-enable jsdoc/no-undefined-types */
return [state, setState];
}
/* harmony default export */ var use_controlled_state = (useControlledState);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/range-control/utils.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* A float supported clamp function for a specific value.
*
* @param value The value to clamp.
* @param min The minimum value.
* @param max The maximum value.
*
* @return A (float) number
*/
function floatClamp(value, min, max) {
if (typeof value !== 'number') {
return null;
}
return parseFloat(`${math_clamp(value, min, max)}`);
}
/**
* Hook to store a clamped value, derived from props.
*
* @param settings
* @return The controlled value and the value setter.
*/
function useControlledRangeValue(settings) {
const {
min,
max,
value: valueProp,
initial
} = settings;
const [state, setInternalState] = use_controlled_state(floatClamp(valueProp, min, max), {
initial: floatClamp(initial !== null && initial !== void 0 ? initial : null, min, max),
fallback: null
});
const setState = (0,external_wp_element_namespaceObject.useCallback)(nextValue => {
if (nextValue === null) {
setInternalState(null);
} else {
setInternalState(floatClamp(nextValue, min, max));
}
}, [min, max, setInternalState]); // `state` can't be an empty string because we specified a fallback value of
// `null` in `useControlledState`
return [state, setState];
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/range-control/styles/range-control-styles.js
function range_control_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const rangeHeightValue = 30;
const railHeight = 4;
const rangeHeight = () => /*#__PURE__*/emotion_react_browser_esm_css({
height: rangeHeightValue,
minHeight: rangeHeightValue
}, true ? "" : 0, true ? "" : 0);
const thumbSize = 12;
const range_control_styles_Root = createStyled("div", true ? {
target: "e1epgpqk14"
} : 0)( true ? {
name: "1se47kl",
styles: "-webkit-tap-highlight-color:transparent;align-items:flex-start;display:flex;justify-content:flex-start;padding:0;position:relative;touch-action:none;width:100%"
} : 0);
const wrapperColor = _ref3 => {
let {
color = COLORS.ui.borderFocus
} = _ref3;
return /*#__PURE__*/emotion_react_browser_esm_css({
color
}, true ? "" : 0, true ? "" : 0);
};
const wrapperMargin = _ref4 => {
let {
marks,
__nextHasNoMarginBottom
} = _ref4;
if (!__nextHasNoMarginBottom) {
return /*#__PURE__*/emotion_react_browser_esm_css({
marginBottom: marks ? 16 : undefined
}, true ? "" : 0, true ? "" : 0);
}
return '';
};
const range_control_styles_Wrapper = createStyled("div", true ? {
target: "e1epgpqk13"
} : 0)("display:block;flex:1;position:relative;width:100%;", wrapperColor, ";", rangeHeight, ";", wrapperMargin, ";" + ( true ? "" : 0));
const BeforeIconWrapper = createStyled("span", true ? {
target: "e1epgpqk12"
} : 0)("display:flex;margin-top:", railHeight, "px;", rtl({
marginRight: 6
}), ";" + ( true ? "" : 0));
const AfterIconWrapper = createStyled("span", true ? {
target: "e1epgpqk11"
} : 0)("display:flex;margin-top:", railHeight, "px;", rtl({
marginLeft: 6
}), ";" + ( true ? "" : 0));
const railBackgroundColor = _ref5 => {
let {
disabled,
railColor
} = _ref5;
let background = railColor || '';
if (disabled) {
background = COLORS.ui.backgroundDisabled;
}
return /*#__PURE__*/emotion_react_browser_esm_css({
background
}, true ? "" : 0, true ? "" : 0);
};
const Rail = createStyled("span", true ? {
target: "e1epgpqk10"
} : 0)("background-color:", COLORS.gray[300], ";left:0;pointer-events:none;right:0;display:block;height:", railHeight, "px;position:absolute;margin-top:", (rangeHeightValue - railHeight) / 2, "px;top:0;border-radius:", railHeight, "px;", railBackgroundColor, ";" + ( true ? "" : 0));
const trackBackgroundColor = _ref6 => {
let {
disabled,
trackColor
} = _ref6;
let background = trackColor || 'currentColor';
if (disabled) {
background = COLORS.gray[400];
}
return /*#__PURE__*/emotion_react_browser_esm_css({
background
}, true ? "" : 0, true ? "" : 0);
};
const Track = createStyled("span", true ? {
target: "e1epgpqk9"
} : 0)("background-color:currentColor;border-radius:", railHeight, "px;height:", railHeight, "px;pointer-events:none;display:block;position:absolute;margin-top:", (rangeHeightValue - railHeight) / 2, "px;top:0;", trackBackgroundColor, ";" + ( true ? "" : 0));
const MarksWrapper = createStyled("span", true ? {
target: "e1epgpqk8"
} : 0)( true ? {
name: "l7tjj5",
styles: "display:block;pointer-events:none;position:relative;width:100%;user-select:none"
} : 0);
const markFill = _ref7 => {
let {
disabled,
isFilled
} = _ref7;
let backgroundColor = isFilled ? 'currentColor' : COLORS.gray[300];
if (disabled) {
backgroundColor = COLORS.gray[400];
}
return /*#__PURE__*/emotion_react_browser_esm_css({
backgroundColor
}, true ? "" : 0, true ? "" : 0);
};
const Mark = createStyled("span", true ? {
target: "e1epgpqk7"
} : 0)("height:", thumbSize, "px;left:0;position:absolute;top:-4px;width:1px;", markFill, ";" + ( true ? "" : 0));
const markLabelFill = _ref8 => {
let {
isFilled
} = _ref8;
return /*#__PURE__*/emotion_react_browser_esm_css({
color: isFilled ? COLORS.gray[700] : COLORS.gray[300]
}, true ? "" : 0, true ? "" : 0);
};
const MarkLabel = createStyled("span", true ? {
target: "e1epgpqk6"
} : 0)("color:", COLORS.gray[300], ";left:0;font-size:11px;position:absolute;top:12px;transform:translateX( -50% );white-space:nowrap;", markLabelFill, ";" + ( true ? "" : 0));
const thumbColor = _ref9 => {
let {
disabled
} = _ref9;
return disabled ? /*#__PURE__*/emotion_react_browser_esm_css("background-color:", COLORS.gray[400], ";" + ( true ? "" : 0), true ? "" : 0) : /*#__PURE__*/emotion_react_browser_esm_css("background-color:", COLORS.ui.theme, ";" + ( true ? "" : 0), true ? "" : 0);
};
const ThumbWrapper = createStyled("span", true ? {
target: "e1epgpqk5"
} : 0)("align-items:center;display:flex;height:", thumbSize, "px;justify-content:center;margin-top:", (rangeHeightValue - thumbSize) / 2, "px;outline:0;pointer-events:none;position:absolute;top:0;user-select:none;width:", thumbSize, "px;border-radius:50%;", thumbColor, ";", rtl({
marginLeft: -10
}), ";", rtl({
transform: 'translateX( 4.5px )'
}, {
transform: 'translateX( -4.5px )'
}), ";" + ( true ? "" : 0));
const thumbFocus = _ref10 => {
let {
isFocused
} = _ref10;
return isFocused ? /*#__PURE__*/emotion_react_browser_esm_css("&::before{content:' ';position:absolute;background-color:", COLORS.ui.theme, ";opacity:0.4;border-radius:50%;height:", thumbSize + 8, "px;width:", thumbSize + 8, "px;top:-4px;left:-4px;}" + ( true ? "" : 0), true ? "" : 0) : '';
};
const Thumb = createStyled("span", true ? {
target: "e1epgpqk4"
} : 0)("align-items:center;border-radius:50%;height:100%;outline:0;position:absolute;user-select:none;width:100%;", thumbColor, ";", thumbFocus, ";" + ( true ? "" : 0));
const InputRange = createStyled("input", true ? {
target: "e1epgpqk3"
} : 0)("box-sizing:border-box;cursor:pointer;display:block;height:100%;left:0;margin:0 -", thumbSize / 2, "px;opacity:0;outline:none;position:absolute;right:0;top:0;width:calc( 100% + ", thumbSize, "px );" + ( true ? "" : 0));
const tooltipShow = _ref11 => {
let {
show
} = _ref11;
return /*#__PURE__*/emotion_react_browser_esm_css({
opacity: show ? 1 : 0
}, true ? "" : 0, true ? "" : 0);
};
var range_control_styles_ref = true ? {
name: "1cypxip",
styles: "top:-80%"
} : 0;
var range_control_styles_ref2 = true ? {
name: "1lr98c4",
styles: "bottom:-80%"
} : 0;
const tooltipPosition = _ref12 => {
let {
position
} = _ref12;
const isBottom = position === 'bottom';
if (isBottom) {
return range_control_styles_ref2;
}
return range_control_styles_ref;
};
const range_control_styles_Tooltip = createStyled("span", true ? {
target: "e1epgpqk2"
} : 0)("background:rgba( 0, 0, 0, 0.8 );border-radius:2px;color:white;display:inline-block;font-size:12px;min-width:32px;opacity:0;padding:4px 8px;pointer-events:none;position:absolute;text-align:center;transition:opacity 120ms ease;user-select:none;line-height:1.4;", tooltipShow, ";", tooltipPosition, ";", reduceMotion('transition'), ";", rtl({
transform: 'translateX(-50%)'
}, {
transform: 'translateX(50%)'
}), ";" + ( true ? "" : 0)); // @todo: Refactor RangeControl with latest HStack configuration
// @wordpress/components/ui/hstack.
const InputNumber = /*#__PURE__*/createStyled(number_control, true ? {
target: "e1epgpqk1"
} : 0)("display:inline-block;font-size:13px;margin-top:0;width:", space(16), "!important;input[type='number']&{", rangeHeight, ";}", rtl({
marginLeft: `${space(4)} !important`
}), ";" + ( true ? "" : 0));
const ActionRightWrapper = createStyled("span", true ? {
target: "e1epgpqk0"
} : 0)("display:block;margin-top:0;button,button.is-small{margin-left:0;", rangeHeight, ";}", rtl({
marginLeft: 8
}), ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/range-control/input-range.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function input_range_InputRange(props, ref) {
const {
describedBy,
label,
value,
...otherProps
} = props;
return (0,external_wp_element_namespaceObject.createElement)(InputRange, extends_extends({}, otherProps, {
"aria-describedby": describedBy,
"aria-label": label,
"aria-hidden": false,
ref: ref,
tabIndex: 0,
type: "range",
value: value
}));
}
const input_range_ForwardedComponent = (0,external_wp_element_namespaceObject.forwardRef)(input_range_InputRange);
/* harmony default export */ var input_range = (input_range_ForwardedComponent);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/range-control/mark.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function RangeMark(props) {
const {
className,
isFilled = false,
label,
style = {},
...otherProps
} = props;
const classes = classnames_default()('components-range-control__mark', isFilled && 'is-filled', className);
const labelClasses = classnames_default()('components-range-control__mark-label', isFilled && 'is-filled');
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(Mark, extends_extends({}, otherProps, {
"aria-hidden": "true",
className: classes,
isFilled: isFilled,
style: style
})), label && (0,external_wp_element_namespaceObject.createElement)(MarkLabel, {
"aria-hidden": "true",
className: labelClasses,
isFilled: isFilled,
style: style
}, label));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/range-control/rail.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function RangeRail(props) {
const {
disabled = false,
marks = false,
min = 0,
max = 100,
step = 1,
value = 0,
...restProps
} = props;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(Rail, extends_extends({
disabled: disabled
}, restProps)), marks && (0,external_wp_element_namespaceObject.createElement)(Marks, {
disabled: disabled,
marks: marks,
min: min,
max: max,
step: step,
value: value
}));
}
function Marks(props) {
const {
disabled = false,
marks = false,
min = 0,
max = 100,
step: stepProp = 1,
value = 0
} = props;
const step = stepProp === 'any' ? 1 : stepProp;
const marksData = useMarks({
marks,
min,
max,
step,
value
});
return (0,external_wp_element_namespaceObject.createElement)(MarksWrapper, {
"aria-hidden": "true",
className: "components-range-control__marks"
}, marksData.map(mark => (0,external_wp_element_namespaceObject.createElement)(RangeMark, extends_extends({}, mark, {
key: mark.key,
"aria-hidden": "true",
disabled: disabled
}))));
}
function useMarks(_ref) {
let {
marks,
min = 0,
max = 100,
step = 1,
value = 0
} = _ref;
if (!marks) {
return [];
}
const range = max - min;
if (!Array.isArray(marks)) {
marks = [];
const count = 1 + Math.round(range / step);
while (count > marks.push({
value: step * marks.length + min
}));
}
const placedMarks = [];
marks.forEach((mark, index) => {
if (mark.value < min || mark.value > max) {
return;
}
const key = `mark-${index}`;
const isFilled = mark.value <= value;
const offset = `${(mark.value - min) / range * 100}%`;
const offsetStyle = {
[(0,external_wp_i18n_namespaceObject.isRTL)() ? 'right' : 'left']: offset
};
placedMarks.push({ ...mark,
isFilled,
key,
style: offsetStyle
});
});
return placedMarks;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/range-control/tooltip.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function SimpleTooltip(props) {
const {
className,
inputRef,
tooltipPosition,
show = false,
style = {},
value = 0,
renderTooltipContent = v => v,
zIndex = 100,
...restProps
} = props;
const position = useTooltipPosition({
inputRef,
tooltipPosition
});
const classes = classnames_default()('components-simple-tooltip', className);
const styles = { ...style,
zIndex
};
return (0,external_wp_element_namespaceObject.createElement)(range_control_styles_Tooltip, extends_extends({}, restProps, {
"aria-hidden": show,
className: classes,
position: position,
show: show,
role: "tooltip",
style: styles
}), renderTooltipContent(value));
}
function useTooltipPosition(_ref) {
let {
inputRef,
tooltipPosition
} = _ref;
const [position, setPosition] = (0,external_wp_element_namespaceObject.useState)();
const setTooltipPosition = (0,external_wp_element_namespaceObject.useCallback)(() => {
if (inputRef && inputRef.current) {
setPosition(tooltipPosition);
}
}, [tooltipPosition, inputRef]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
setTooltipPosition();
}, [setTooltipPosition]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
window.addEventListener('resize', setTooltipPosition);
return () => {
window.removeEventListener('resize', setTooltipPosition);
};
});
return position;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/range-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const range_control_noop = () => {};
function UnforwardedRangeControl(props, forwardedRef) {
var _inputRef$current;
const {
__nextHasNoMarginBottom = false,
afterIcon,
allowReset = false,
beforeIcon,
className,
color: colorProp = COLORS.ui.theme,
currentInput,
disabled = false,
help,
hideLabelFromVision = false,
initialPosition,
isShiftStepEnabled = true,
label,
marks = false,
max = 100,
min = 0,
onBlur = range_control_noop,
onChange = range_control_noop,
onFocus = range_control_noop,
onMouseLeave = range_control_noop,
onMouseMove = range_control_noop,
railColor,
renderTooltipContent = v => v,
resetFallbackValue,
shiftStep = 10,
showTooltip: showTooltipProp,
step = 1,
trackColor,
value: valueProp,
withInputField = true,
...otherProps
} = props;
const [value, setValue] = useControlledRangeValue({
min,
max,
value: valueProp !== null && valueProp !== void 0 ? valueProp : null,
initial: initialPosition
});
const isResetPendent = (0,external_wp_element_namespaceObject.useRef)(false);
let hasTooltip = showTooltipProp;
let hasInputField = withInputField;
if (step === 'any') {
// The tooltip and number input field are hidden when the step is "any"
// because the decimals get too lengthy to fit well.
hasTooltip = false;
hasInputField = false;
}
const [showTooltip, setShowTooltip] = (0,external_wp_element_namespaceObject.useState)(hasTooltip);
const [isFocused, setIsFocused] = (0,external_wp_element_namespaceObject.useState)(false);
const inputRef = (0,external_wp_element_namespaceObject.useRef)();
const isCurrentlyFocused = (_inputRef$current = inputRef.current) === null || _inputRef$current === void 0 ? void 0 : _inputRef$current.matches(':focus');
const isThumbFocused = !disabled && isFocused;
const isValueReset = value === null;
const currentValue = value !== undefined ? value : currentInput;
const inputSliderValue = isValueReset ? '' : currentValue;
const rangeFillValue = isValueReset ? (max - min) / 2 + min : value;
const fillValue = isValueReset ? 50 : (value - min) / (max - min) * 100;
const fillValueOffset = `${math_clamp(fillValue, 0, 100)}%`;
const classes = classnames_default()('components-range-control', className);
const wrapperClasses = classnames_default()('components-range-control__wrapper', !!marks && 'is-marked');
const id = (0,external_wp_compose_namespaceObject.useInstanceId)(UnforwardedRangeControl, 'inspector-range-control');
const describedBy = !!help ? `${id}__help` : undefined;
const enableTooltip = hasTooltip !== false && Number.isFinite(value);
const handleOnRangeChange = event => {
const nextValue = parseFloat(event.target.value);
setValue(nextValue);
onChange(nextValue);
};
const handleOnChange = next => {
// @ts-expect-error TODO: Investigate if it's problematic for setValue() to
// potentially receive a NaN when next is undefined.
let nextValue = parseFloat(next);
setValue(nextValue);
/*
* Calls onChange only when nextValue is numeric
* otherwise may queue a reset for the blur event.
*/
if (!isNaN(nextValue)) {
if (nextValue < min || nextValue > max) {
nextValue = floatClamp(nextValue, min, max);
}
onChange(nextValue);
isResetPendent.current = false;
} else if (allowReset) {
isResetPendent.current = true;
}
};
const handleOnInputNumberBlur = () => {
if (isResetPendent.current) {
handleOnReset();
isResetPendent.current = false;
}
};
const handleOnReset = () => {
let resetValue = parseFloat(`${resetFallbackValue}`);
let onChangeResetValue = resetValue;
if (isNaN(resetValue)) {
resetValue = null;
onChangeResetValue = undefined;
}
setValue(resetValue);
/**
* Previously, this callback would always receive undefined as
* an argument. This behavior is unexpected, specifically
* when resetFallbackValue is defined.
*
* The value of undefined is not ideal. Passing it through
* to internal <input /> elements would change it from a
* controlled component to an uncontrolled component.
*
* For now, to minimize unexpected regressions, we're going to
* preserve the undefined callback argument, except when a
* resetFallbackValue is defined.
*/
onChange(onChangeResetValue);
};
const handleShowTooltip = () => setShowTooltip(true);
const handleHideTooltip = () => setShowTooltip(false);
const handleOnBlur = event => {
onBlur(event);
setIsFocused(false);
handleHideTooltip();
};
const handleOnFocus = event => {
onFocus(event);
setIsFocused(true);
handleShowTooltip();
};
const offsetStyle = {
[(0,external_wp_i18n_namespaceObject.isRTL)() ? 'right' : 'left']: fillValueOffset
};
return (0,external_wp_element_namespaceObject.createElement)(base_control, {
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
className: classes,
label: label,
hideLabelFromVision: hideLabelFromVision,
id: `${id}`,
help: help
}, (0,external_wp_element_namespaceObject.createElement)(range_control_styles_Root, {
className: "components-range-control__root"
}, beforeIcon && (0,external_wp_element_namespaceObject.createElement)(BeforeIconWrapper, null, (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: beforeIcon
})), (0,external_wp_element_namespaceObject.createElement)(range_control_styles_Wrapper, {
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
className: wrapperClasses,
color: colorProp,
marks: !!marks
}, (0,external_wp_element_namespaceObject.createElement)(input_range, extends_extends({}, otherProps, {
className: "components-range-control__slider",
describedBy: describedBy,
disabled: disabled,
id: `${id}`,
label: label,
max: max,
min: min,
onBlur: handleOnBlur,
onChange: handleOnRangeChange,
onFocus: handleOnFocus,
onMouseMove: onMouseMove,
onMouseLeave: onMouseLeave,
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([inputRef, forwardedRef]),
step: step,
value: inputSliderValue !== null && inputSliderValue !== void 0 ? inputSliderValue : undefined
})), (0,external_wp_element_namespaceObject.createElement)(RangeRail, {
"aria-hidden": true,
disabled: disabled,
marks: marks,
max: max,
min: min,
railColor: railColor,
step: step,
value: rangeFillValue
}), (0,external_wp_element_namespaceObject.createElement)(Track, {
"aria-hidden": true,
className: "components-range-control__track",
disabled: disabled,
style: {
width: fillValueOffset
},
trackColor: trackColor
}), (0,external_wp_element_namespaceObject.createElement)(ThumbWrapper, {
className: "components-range-control__thumb-wrapper",
style: offsetStyle,
disabled: disabled
}, (0,external_wp_element_namespaceObject.createElement)(Thumb, {
"aria-hidden": true,
isFocused: isThumbFocused,
disabled: disabled
})), enableTooltip && (0,external_wp_element_namespaceObject.createElement)(SimpleTooltip, {
className: "components-range-control__tooltip",
inputRef: inputRef,
tooltipPosition: "bottom",
renderTooltipContent: renderTooltipContent,
show: isCurrentlyFocused || showTooltip,
style: offsetStyle,
value: value
})), afterIcon && (0,external_wp_element_namespaceObject.createElement)(AfterIconWrapper, null, (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: afterIcon
})), hasInputField && (0,external_wp_element_namespaceObject.createElement)(InputNumber, {
"aria-label": label,
className: "components-range-control__number",
disabled: disabled,
inputMode: "decimal",
isShiftStepEnabled: isShiftStepEnabled,
max: max,
min: min,
onBlur: handleOnInputNumberBlur,
onChange: handleOnChange,
shiftStep: shiftStep,
step: step // @ts-expect-error TODO: Investigate if the `null` value is necessary
,
value: inputSliderValue
}), allowReset && (0,external_wp_element_namespaceObject.createElement)(ActionRightWrapper, null, (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-range-control__reset",
disabled: disabled || value === undefined,
variant: "secondary",
isSmall: true,
onClick: handleOnReset
}, (0,external_wp_i18n_namespaceObject.__)('Reset')))));
}
/**
* RangeControls are used to make selections from a range of incremental values.
*
* ```jsx
* import { RangeControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyRangeControl = () => {
* const [ isChecked, setChecked ] = useState( true );
* return (
* <RangeControl
* help="Please select how transparent you would like this."
* initialPosition={50}
* label="Opacity"
* max={100}
* min={0}
* onChange={() => {}}
* />
* );
* };
* ```
*/
const RangeControl = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedRangeControl);
/* harmony default export */ var range_control = (RangeControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-picker/styles.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const NumberControlWrapper = /*#__PURE__*/createStyled(number_control, true ? {
target: "ez9hsf47"
} : 0)(Container, "{width:", space(24), ";}" + ( true ? "" : 0));
const styles_SelectControl = /*#__PURE__*/createStyled(select_control, true ? {
target: "ez9hsf46"
} : 0)("margin-left:", space(-2), ";width:5em;", BackdropUI, "{display:none;}" + ( true ? "" : 0));
const styles_RangeControl = /*#__PURE__*/createStyled(range_control, true ? {
target: "ez9hsf45"
} : 0)("flex:1;margin-right:", space(2), ";" + ( true ? "" : 0)); // Make the Hue circle picker not go out of the bar.
const interactiveHueStyles = `
.react-colorful__interactive {
width: calc( 100% - ${space(2)} );
margin-left: ${space(1)};
}`;
const AuxiliaryColorArtefactWrapper = createStyled("div", true ? {
target: "ez9hsf44"
} : 0)("padding-top:", space(2), ";padding-right:0;padding-left:0;padding-bottom:0;" + ( true ? "" : 0));
const AuxiliaryColorArtefactHStackHeader = /*#__PURE__*/createStyled(h_stack_component, true ? {
target: "ez9hsf43"
} : 0)("padding-left:", space(4), ";padding-right:", space(4), ";" + ( true ? "" : 0));
const ColorInputWrapper = /*#__PURE__*/createStyled(flex_component, true ? {
target: "ez9hsf42"
} : 0)("padding-top:", space(4), ";padding-left:", space(4), ";padding-right:", space(3), ";padding-bottom:", space(5), ";" + ( true ? "" : 0));
const ColorfulWrapper = createStyled("div", true ? {
target: "ez9hsf41"
} : 0)(boxSizingReset, ";width:216px;.react-colorful{display:flex;flex-direction:column;align-items:center;width:216px;height:auto;overflow:hidden;}.react-colorful__saturation{width:100%;border-radius:0;height:216px;margin-bottom:", space(4), ";border-bottom:none;}.react-colorful__hue,.react-colorful__alpha{width:184px;height:16px;border-radius:16px;margin-bottom:", space(2), ";}.react-colorful__pointer{height:16px;width:16px;border:none;box-shadow:0 0 2px 0 rgba( 0, 0, 0, 0.25 );outline:2px solid transparent;}.react-colorful__pointer-fill{box-shadow:inset 0 0 0 ", config_values.borderWidthFocus, " #fff;}", interactiveHueStyles, ";" + ( true ? "" : 0));
const CopyButton = /*#__PURE__*/createStyled(build_module_button, true ? {
target: "ez9hsf40"
} : 0)("&&&&&{min-width:", space(6), ";padding:0;>svg{margin-right:0;}}" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/copy.js
/**
* WordPress dependencies
*/
const copy_copy = (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: "M20.2 8v11c0 .7-.6 1.2-1.2 1.2H6v1.5h13c1.5 0 2.7-1.2 2.7-2.8V8zM18 16.4V4.6c0-.9-.7-1.6-1.6-1.6H4.6C3.7 3 3 3.7 3 4.6v11.8c0 .9.7 1.6 1.6 1.6h11.8c.9 0 1.6-.7 1.6-1.6zm-13.5 0V4.6c0-.1.1-.1.1-.1h11.8c.1 0 .1.1.1.1v11.8c0 .1-.1.1-.1.1H4.6l-.1-.1z"
}));
/* harmony default export */ var library_copy = (copy_copy);
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getWindow.js
function getWindow_getWindow(node) {
if (node == null) {
return window;
}
if (node.toString() !== '[object Window]') {
var ownerDocument = node.ownerDocument;
return ownerDocument ? ownerDocument.defaultView || window : window;
}
return node;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/instanceOf.js
function instanceOf_isElement(node) {
var OwnElement = getWindow_getWindow(node).Element;
return node instanceof OwnElement || node instanceof Element;
}
function instanceOf_isHTMLElement(node) {
var OwnElement = getWindow_getWindow(node).HTMLElement;
return node instanceof OwnElement || node instanceof HTMLElement;
}
function instanceOf_isShadowRoot(node) {
// IE 11 has no ShadowRoot
if (typeof ShadowRoot === 'undefined') {
return false;
}
var OwnElement = getWindow_getWindow(node).ShadowRoot;
return node instanceof OwnElement || node instanceof ShadowRoot;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/math.js
var math_max = Math.max;
var math_min = Math.min;
var math_round = Math.round;
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/userAgent.js
function getUAString() {
var uaData = navigator.userAgentData;
if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) {
return uaData.brands.map(function (item) {
return item.brand + "/" + item.version;
}).join(' ');
}
return navigator.userAgent;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/isLayoutViewport.js
function isLayoutViewport() {
return !/^((?!chrome|android).)*safari/i.test(getUAString());
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js
function getBoundingClientRect_getBoundingClientRect(element, includeScale, isFixedStrategy) {
if (includeScale === void 0) {
includeScale = false;
}
if (isFixedStrategy === void 0) {
isFixedStrategy = false;
}
var clientRect = element.getBoundingClientRect();
var scaleX = 1;
var scaleY = 1;
if (includeScale && instanceOf_isHTMLElement(element)) {
scaleX = element.offsetWidth > 0 ? math_round(clientRect.width) / element.offsetWidth || 1 : 1;
scaleY = element.offsetHeight > 0 ? math_round(clientRect.height) / element.offsetHeight || 1 : 1;
}
var _ref = instanceOf_isElement(element) ? getWindow_getWindow(element) : window,
visualViewport = _ref.visualViewport;
var addVisualOffsets = !isLayoutViewport() && isFixedStrategy;
var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX;
var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY;
var width = clientRect.width / scaleX;
var height = clientRect.height / scaleY;
return {
width: width,
height: height,
top: y,
right: x + width,
bottom: y + height,
left: x,
x: x,
y: y
};
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js
function getWindowScroll(node) {
var win = getWindow_getWindow(node);
var scrollLeft = win.pageXOffset;
var scrollTop = win.pageYOffset;
return {
scrollLeft: scrollLeft,
scrollTop: scrollTop
};
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js
function getHTMLElementScroll(element) {
return {
scrollLeft: element.scrollLeft,
scrollTop: element.scrollTop
};
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js
function getNodeScroll_getNodeScroll(node) {
if (node === getWindow_getWindow(node) || !instanceOf_isHTMLElement(node)) {
return getWindowScroll(node);
} else {
return getHTMLElementScroll(node);
}
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getNodeName.js
function getNodeName_getNodeName(element) {
return element ? (element.nodeName || '').toLowerCase() : null;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js
function getDocumentElement_getDocumentElement(element) {
// $FlowFixMe[incompatible-return]: assume body is always available
return ((instanceOf_isElement(element) ? element.ownerDocument : // $FlowFixMe[prop-missing]
element.document) || window.document).documentElement;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js
function getWindowScrollBarX_getWindowScrollBarX(element) {
// If <html> has a CSS width greater than the viewport, then this will be
// incorrect for RTL.
// Popper 1 is broken in this case and never had a bug report so let's assume
// it's not an issue. I don't think anyone ever specifies width on <html>
// anyway.
// Browsers where the left scrollbar doesn't cause an issue report `0` for
// this (e.g. Edge 2019, IE11, Safari)
return getBoundingClientRect_getBoundingClientRect(getDocumentElement_getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js
function getComputedStyle_getComputedStyle(element) {
return getWindow_getWindow(element).getComputedStyle(element);
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js
function isScrollParent(element) {
// Firefox wants us to check `-x` and `-y` variations as well
var _getComputedStyle = getComputedStyle_getComputedStyle(element),
overflow = _getComputedStyle.overflow,
overflowX = _getComputedStyle.overflowX,
overflowY = _getComputedStyle.overflowY;
return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js
function isElementScaled(element) {
var rect = element.getBoundingClientRect();
var scaleX = math_round(rect.width) / element.offsetWidth || 1;
var scaleY = math_round(rect.height) / element.offsetHeight || 1;
return scaleX !== 1 || scaleY !== 1;
} // Returns the composite rect of an element relative to its offsetParent.
// Composite means it takes into account transforms as well as layout.
function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {
if (isFixed === void 0) {
isFixed = false;
}
var isOffsetParentAnElement = instanceOf_isHTMLElement(offsetParent);
var offsetParentIsScaled = instanceOf_isHTMLElement(offsetParent) && isElementScaled(offsetParent);
var documentElement = getDocumentElement_getDocumentElement(offsetParent);
var rect = getBoundingClientRect_getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed);
var scroll = {
scrollLeft: 0,
scrollTop: 0
};
var offsets = {
x: 0,
y: 0
};
if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
if (getNodeName_getNodeName(offsetParent) !== 'body' || // https://github.com/popperjs/popper-core/issues/1078
isScrollParent(documentElement)) {
scroll = getNodeScroll_getNodeScroll(offsetParent);
}
if (instanceOf_isHTMLElement(offsetParent)) {
offsets = getBoundingClientRect_getBoundingClientRect(offsetParent, true);
offsets.x += offsetParent.clientLeft;
offsets.y += offsetParent.clientTop;
} else if (documentElement) {
offsets.x = getWindowScrollBarX_getWindowScrollBarX(documentElement);
}
}
return {
x: rect.left + scroll.scrollLeft - offsets.x,
y: rect.top + scroll.scrollTop - offsets.y,
width: rect.width,
height: rect.height
};
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js
// Returns the layout rect of an element relative to its offsetParent. Layout
// means it doesn't take into account transforms.
function getLayoutRect(element) {
var clientRect = getBoundingClientRect_getBoundingClientRect(element); // Use the clientRect sizes if it's not been transformed.
// Fixes https://github.com/popperjs/popper-core/issues/1223
var width = element.offsetWidth;
var height = element.offsetHeight;
if (Math.abs(clientRect.width - width) <= 1) {
width = clientRect.width;
}
if (Math.abs(clientRect.height - height) <= 1) {
height = clientRect.height;
}
return {
x: element.offsetLeft,
y: element.offsetTop,
width: width,
height: height
};
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getParentNode.js
function getParentNode_getParentNode(element) {
if (getNodeName_getNodeName(element) === 'html') {
return element;
}
return (// this is a quicker (but less type safe) way to save quite some bytes from the bundle
// $FlowFixMe[incompatible-return]
// $FlowFixMe[prop-missing]
element.assignedSlot || // step into the shadow DOM of the parent of a slotted node
element.parentNode || ( // DOM Element detected
instanceOf_isShadowRoot(element) ? element.host : null) || // ShadowRoot detected
// $FlowFixMe[incompatible-call]: HTMLElement is a Node
getDocumentElement_getDocumentElement(element) // fallback
);
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js
function getScrollParent(node) {
if (['html', 'body', '#document'].indexOf(getNodeName_getNodeName(node)) >= 0) {
// $FlowFixMe[incompatible-return]: assume body is always available
return node.ownerDocument.body;
}
if (instanceOf_isHTMLElement(node) && isScrollParent(node)) {
return node;
}
return getScrollParent(getParentNode_getParentNode(node));
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js
/*
given a DOM element, return the list of all scroll parents, up the list of ancesors
until we get to the top window object. This list is what we attach scroll listeners
to, because if any of these parent elements scroll, we'll need to re-calculate the
reference element's position.
*/
function listScrollParents(element, list) {
var _element$ownerDocumen;
if (list === void 0) {
list = [];
}
var scrollParent = getScrollParent(element);
var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body);
var win = getWindow_getWindow(scrollParent);
var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;
var updatedList = list.concat(target);
return isBody ? updatedList : // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here
updatedList.concat(listScrollParents(getParentNode_getParentNode(target)));
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/isTableElement.js
function isTableElement_isTableElement(element) {
return ['table', 'td', 'th'].indexOf(getNodeName_getNodeName(element)) >= 0;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js
function getOffsetParent_getTrueOffsetParent(element) {
if (!instanceOf_isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837
getComputedStyle_getComputedStyle(element).position === 'fixed') {
return null;
}
return element.offsetParent;
} // `.offsetParent` reports `null` for fixed elements, while absolute elements
// return the containing block
function getOffsetParent_getContainingBlock(element) {
var isFirefox = /firefox/i.test(getUAString());
var isIE = /Trident/i.test(getUAString());
if (isIE && instanceOf_isHTMLElement(element)) {
// In IE 9, 10 and 11 fixed elements containing block is always established by the viewport
var elementCss = getComputedStyle_getComputedStyle(element);
if (elementCss.position === 'fixed') {
return null;
}
}
var currentNode = getParentNode_getParentNode(element);
if (instanceOf_isShadowRoot(currentNode)) {
currentNode = currentNode.host;
}
while (instanceOf_isHTMLElement(currentNode) && ['html', 'body'].indexOf(getNodeName_getNodeName(currentNode)) < 0) {
var css = getComputedStyle_getComputedStyle(currentNode); // This is non-exhaustive but covers the most common CSS properties that
// create a containing block.
// https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block
if (css.transform !== 'none' || css.perspective !== 'none' || css.contain === 'paint' || ['transform', 'perspective'].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === 'filter' || isFirefox && css.filter && css.filter !== 'none') {
return currentNode;
} else {
currentNode = currentNode.parentNode;
}
}
return null;
} // Gets the closest ancestor positioned element. Handles some edge cases,
// such as table ancestors and cross browser bugs.
function getOffsetParent_getOffsetParent(element) {
var window = getWindow_getWindow(element);
var offsetParent = getOffsetParent_getTrueOffsetParent(element);
while (offsetParent && isTableElement_isTableElement(offsetParent) && getComputedStyle_getComputedStyle(offsetParent).position === 'static') {
offsetParent = getOffsetParent_getTrueOffsetParent(offsetParent);
}
if (offsetParent && (getNodeName_getNodeName(offsetParent) === 'html' || getNodeName_getNodeName(offsetParent) === 'body' && getComputedStyle_getComputedStyle(offsetParent).position === 'static')) {
return window;
}
return offsetParent || getOffsetParent_getContainingBlock(element) || window;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/enums.js
var enums_top = 'top';
var bottom = 'bottom';
var right = 'right';
var left = 'left';
var enums_auto = 'auto';
var basePlacements = [enums_top, bottom, right, left];
var start = 'start';
var end = 'end';
var clippingParents = 'clippingParents';
var viewport = 'viewport';
var popper = 'popper';
var reference = 'reference';
var variationPlacements = /*#__PURE__*/basePlacements.reduce(function (acc, placement) {
return acc.concat([placement + "-" + start, placement + "-" + end]);
}, []);
var enums_placements = /*#__PURE__*/[].concat(basePlacements, [enums_auto]).reduce(function (acc, placement) {
return acc.concat([placement, placement + "-" + start, placement + "-" + end]);
}, []); // modifiers that need to read the DOM
var beforeRead = 'beforeRead';
var read = 'read';
var afterRead = 'afterRead'; // pure-logic modifiers
var beforeMain = 'beforeMain';
var main = 'main';
var afterMain = 'afterMain'; // modifier with the purpose to write to the DOM (or write into a framework state)
var beforeWrite = 'beforeWrite';
var write = 'write';
var afterWrite = 'afterWrite';
var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite];
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/orderModifiers.js
// source: https://stackoverflow.com/questions/49875255
function order(modifiers) {
var map = new Map();
var visited = new Set();
var result = [];
modifiers.forEach(function (modifier) {
map.set(modifier.name, modifier);
}); // On visiting object, check for its dependencies and visit them recursively
function sort(modifier) {
visited.add(modifier.name);
var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);
requires.forEach(function (dep) {
if (!visited.has(dep)) {
var depModifier = map.get(dep);
if (depModifier) {
sort(depModifier);
}
}
});
result.push(modifier);
}
modifiers.forEach(function (modifier) {
if (!visited.has(modifier.name)) {
// check for visited object
sort(modifier);
}
});
return result;
}
function orderModifiers(modifiers) {
// order based on dependencies
var orderedModifiers = order(modifiers); // order based on phase
return modifierPhases.reduce(function (acc, phase) {
return acc.concat(orderedModifiers.filter(function (modifier) {
return modifier.phase === phase;
}));
}, []);
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/debounce.js
function debounce(fn) {
var pending;
return function () {
if (!pending) {
pending = new Promise(function (resolve) {
Promise.resolve().then(function () {
pending = undefined;
resolve(fn());
});
});
}
return pending;
};
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/mergeByName.js
function mergeByName(modifiers) {
var merged = modifiers.reduce(function (merged, current) {
var existing = merged[current.name];
merged[current.name] = existing ? Object.assign({}, existing, current, {
options: Object.assign({}, existing.options, current.options),
data: Object.assign({}, existing.data, current.data)
}) : current;
return merged;
}, {}); // IE11 does not support Object.values
return Object.keys(merged).map(function (key) {
return merged[key];
});
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/createPopper.js
var DEFAULT_OPTIONS = {
placement: 'bottom',
modifiers: [],
strategy: 'absolute'
};
function areValidElements() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return !args.some(function (element) {
return !(element && typeof element.getBoundingClientRect === 'function');
});
}
function popperGenerator(generatorOptions) {
if (generatorOptions === void 0) {
generatorOptions = {};
}
var _generatorOptions = generatorOptions,
_generatorOptions$def = _generatorOptions.defaultModifiers,
defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def,
_generatorOptions$def2 = _generatorOptions.defaultOptions,
defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;
return function createPopper(reference, popper, options) {
if (options === void 0) {
options = defaultOptions;
}
var state = {
placement: 'bottom',
orderedModifiers: [],
options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions),
modifiersData: {},
elements: {
reference: reference,
popper: popper
},
attributes: {},
styles: {}
};
var effectCleanupFns = [];
var isDestroyed = false;
var instance = {
state: state,
setOptions: function setOptions(setOptionsAction) {
var options = typeof setOptionsAction === 'function' ? setOptionsAction(state.options) : setOptionsAction;
cleanupModifierEffects();
state.options = Object.assign({}, defaultOptions, state.options, options);
state.scrollParents = {
reference: instanceOf_isElement(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [],
popper: listScrollParents(popper)
}; // Orders the modifiers based on their dependencies and `phase`
// properties
var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); // Strip out disabled modifiers
state.orderedModifiers = orderedModifiers.filter(function (m) {
return m.enabled;
});
runModifierEffects();
return instance.update();
},
// Sync update – it will always be executed, even if not necessary. This
// is useful for low frequency updates where sync behavior simplifies the
// logic.
// For high frequency updates (e.g. `resize` and `scroll` events), always
// prefer the async Popper#update method
forceUpdate: function forceUpdate() {
if (isDestroyed) {
return;
}
var _state$elements = state.elements,
reference = _state$elements.reference,
popper = _state$elements.popper; // Don't proceed if `reference` or `popper` are not valid elements
// anymore
if (!areValidElements(reference, popper)) {
return;
} // Store the reference and popper rects to be read by modifiers
state.rects = {
reference: getCompositeRect(reference, getOffsetParent_getOffsetParent(popper), state.options.strategy === 'fixed'),
popper: getLayoutRect(popper)
}; // Modifiers have the ability to reset the current update cycle. The
// most common use case for this is the `flip` modifier changing the
// placement, which then needs to re-run all the modifiers, because the
// logic was previously ran for the previous placement and is therefore
// stale/incorrect
state.reset = false;
state.placement = state.options.placement; // On each update cycle, the `modifiersData` property for each modifier
// is filled with the initial data specified by the modifier. This means
// it doesn't persist and is fresh on each update.
// To ensure persistent data, use `${name}#persistent`
state.orderedModifiers.forEach(function (modifier) {
return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);
});
for (var index = 0; index < state.orderedModifiers.length; index++) {
if (state.reset === true) {
state.reset = false;
index = -1;
continue;
}
var _state$orderedModifie = state.orderedModifiers[index],
fn = _state$orderedModifie.fn,
_state$orderedModifie2 = _state$orderedModifie.options,
_options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2,
name = _state$orderedModifie.name;
if (typeof fn === 'function') {
state = fn({
state: state,
options: _options,
name: name,
instance: instance
}) || state;
}
}
},
// Async and optimistically optimized update – it will not be executed if
// not necessary (debounced to run at most once-per-tick)
update: debounce(function () {
return new Promise(function (resolve) {
instance.forceUpdate();
resolve(state);
});
}),
destroy: function destroy() {
cleanupModifierEffects();
isDestroyed = true;
}
};
if (!areValidElements(reference, popper)) {
return instance;
}
instance.setOptions(options).then(function (state) {
if (!isDestroyed && options.onFirstUpdate) {
options.onFirstUpdate(state);
}
}); // Modifiers have the ability to execute arbitrary code before the first
// update cycle runs. They will be executed in the same order as the update
// cycle. This is useful when a modifier adds some persistent data that
// other modifiers need to use, but the modifier is run after the dependent
// one.
function runModifierEffects() {
state.orderedModifiers.forEach(function (_ref) {
var name = _ref.name,
_ref$options = _ref.options,
options = _ref$options === void 0 ? {} : _ref$options,
effect = _ref.effect;
if (typeof effect === 'function') {
var cleanupFn = effect({
state: state,
name: name,
instance: instance,
options: options
});
var noopFn = function noopFn() {};
effectCleanupFns.push(cleanupFn || noopFn);
}
});
}
function cleanupModifierEffects() {
effectCleanupFns.forEach(function (fn) {
return fn();
});
effectCleanupFns = [];
}
return instance;
};
}
var createPopper = /*#__PURE__*/(/* unused pure expression or super */ null && (popperGenerator())); // eslint-disable-next-line import/no-unused-modules
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/eventListeners.js
// eslint-disable-next-line import/no-unused-modules
var passive = {
passive: true
};
function effect(_ref) {
var state = _ref.state,
instance = _ref.instance,
options = _ref.options;
var _options$scroll = options.scroll,
scroll = _options$scroll === void 0 ? true : _options$scroll,
_options$resize = options.resize,
resize = _options$resize === void 0 ? true : _options$resize;
var window = getWindow_getWindow(state.elements.popper);
var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);
if (scroll) {
scrollParents.forEach(function (scrollParent) {
scrollParent.addEventListener('scroll', instance.update, passive);
});
}
if (resize) {
window.addEventListener('resize', instance.update, passive);
}
return function () {
if (scroll) {
scrollParents.forEach(function (scrollParent) {
scrollParent.removeEventListener('scroll', instance.update, passive);
});
}
if (resize) {
window.removeEventListener('resize', instance.update, passive);
}
};
} // eslint-disable-next-line import/no-unused-modules
/* harmony default export */ var eventListeners = ({
name: 'eventListeners',
enabled: true,
phase: 'write',
fn: function fn() {},
effect: effect,
data: {}
});
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/getBasePlacement.js
function getBasePlacement(placement) {
return placement.split('-')[0];
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/getVariation.js
function getVariation(placement) {
return placement.split('-')[1];
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js
function getMainAxisFromPlacement_getMainAxisFromPlacement(placement) {
return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y';
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/computeOffsets.js
function computeOffsets(_ref) {
var reference = _ref.reference,
element = _ref.element,
placement = _ref.placement;
var basePlacement = placement ? getBasePlacement(placement) : null;
var variation = placement ? getVariation(placement) : null;
var commonX = reference.x + reference.width / 2 - element.width / 2;
var commonY = reference.y + reference.height / 2 - element.height / 2;
var offsets;
switch (basePlacement) {
case enums_top:
offsets = {
x: commonX,
y: reference.y - element.height
};
break;
case bottom:
offsets = {
x: commonX,
y: reference.y + reference.height
};
break;
case right:
offsets = {
x: reference.x + reference.width,
y: commonY
};
break;
case left:
offsets = {
x: reference.x - element.width,
y: commonY
};
break;
default:
offsets = {
x: reference.x,
y: reference.y
};
}
var mainAxis = basePlacement ? getMainAxisFromPlacement_getMainAxisFromPlacement(basePlacement) : null;
if (mainAxis != null) {
var len = mainAxis === 'y' ? 'height' : 'width';
switch (variation) {
case start:
offsets[mainAxis] = offsets[mainAxis] - (reference[len] / 2 - element[len] / 2);
break;
case end:
offsets[mainAxis] = offsets[mainAxis] + (reference[len] / 2 - element[len] / 2);
break;
default:
}
}
return offsets;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/popperOffsets.js
function popperOffsets(_ref) {
var state = _ref.state,
name = _ref.name;
// Offsets are the actual position the popper needs to have to be
// properly positioned near its reference element
// This is the most basic placement, and will be adjusted by
// the modifiers in the next step
state.modifiersData[name] = computeOffsets({
reference: state.rects.reference,
element: state.rects.popper,
strategy: 'absolute',
placement: state.placement
});
} // eslint-disable-next-line import/no-unused-modules
/* harmony default export */ var modifiers_popperOffsets = ({
name: 'popperOffsets',
enabled: true,
phase: 'read',
fn: popperOffsets,
data: {}
});
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/computeStyles.js
// eslint-disable-next-line import/no-unused-modules
var unsetSides = {
top: 'auto',
right: 'auto',
bottom: 'auto',
left: 'auto'
}; // Round the offsets to the nearest suitable subpixel based on the DPR.
// Zooming can change the DPR, but it seems to report a value that will
// cleanly divide the values into the appropriate subpixels.
function roundOffsetsByDPR(_ref, win) {
var x = _ref.x,
y = _ref.y;
var dpr = win.devicePixelRatio || 1;
return {
x: math_round(x * dpr) / dpr || 0,
y: math_round(y * dpr) / dpr || 0
};
}
function mapToStyles(_ref2) {
var _Object$assign2;
var popper = _ref2.popper,
popperRect = _ref2.popperRect,
placement = _ref2.placement,
variation = _ref2.variation,
offsets = _ref2.offsets,
position = _ref2.position,
gpuAcceleration = _ref2.gpuAcceleration,
adaptive = _ref2.adaptive,
roundOffsets = _ref2.roundOffsets,
isFixed = _ref2.isFixed;
var _offsets$x = offsets.x,
x = _offsets$x === void 0 ? 0 : _offsets$x,
_offsets$y = offsets.y,
y = _offsets$y === void 0 ? 0 : _offsets$y;
var _ref3 = typeof roundOffsets === 'function' ? roundOffsets({
x: x,
y: y
}) : {
x: x,
y: y
};
x = _ref3.x;
y = _ref3.y;
var hasX = offsets.hasOwnProperty('x');
var hasY = offsets.hasOwnProperty('y');
var sideX = left;
var sideY = enums_top;
var win = window;
if (adaptive) {
var offsetParent = getOffsetParent_getOffsetParent(popper);
var heightProp = 'clientHeight';
var widthProp = 'clientWidth';
if (offsetParent === getWindow_getWindow(popper)) {
offsetParent = getDocumentElement_getDocumentElement(popper);
if (getComputedStyle_getComputedStyle(offsetParent).position !== 'static' && position === 'absolute') {
heightProp = 'scrollHeight';
widthProp = 'scrollWidth';
}
} // $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it
offsetParent = offsetParent;
if (placement === enums_top || (placement === left || placement === right) && variation === end) {
sideY = bottom;
var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : // $FlowFixMe[prop-missing]
offsetParent[heightProp];
y -= offsetY - popperRect.height;
y *= gpuAcceleration ? 1 : -1;
}
if (placement === left || (placement === enums_top || placement === bottom) && variation === end) {
sideX = right;
var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : // $FlowFixMe[prop-missing]
offsetParent[widthProp];
x -= offsetX - popperRect.width;
x *= gpuAcceleration ? 1 : -1;
}
}
var commonStyles = Object.assign({
position: position
}, adaptive && unsetSides);
var _ref4 = roundOffsets === true ? roundOffsetsByDPR({
x: x,
y: y
}, getWindow_getWindow(popper)) : {
x: x,
y: y
};
x = _ref4.x;
y = _ref4.y;
if (gpuAcceleration) {
var _Object$assign;
return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign));
}
return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : '', _Object$assign2[sideX] = hasX ? x + "px" : '', _Object$assign2.transform = '', _Object$assign2));
}
function computeStyles(_ref5) {
var state = _ref5.state,
options = _ref5.options;
var _options$gpuAccelerat = options.gpuAcceleration,
gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat,
_options$adaptive = options.adaptive,
adaptive = _options$adaptive === void 0 ? true : _options$adaptive,
_options$roundOffsets = options.roundOffsets,
roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;
var commonStyles = {
placement: getBasePlacement(state.placement),
variation: getVariation(state.placement),
popper: state.elements.popper,
popperRect: state.rects.popper,
gpuAcceleration: gpuAcceleration,
isFixed: state.options.strategy === 'fixed'
};
if (state.modifiersData.popperOffsets != null) {
state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, {
offsets: state.modifiersData.popperOffsets,
position: state.options.strategy,
adaptive: adaptive,
roundOffsets: roundOffsets
})));
}
if (state.modifiersData.arrow != null) {
state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, {
offsets: state.modifiersData.arrow,
position: 'absolute',
adaptive: false,
roundOffsets: roundOffsets
})));
}
state.attributes.popper = Object.assign({}, state.attributes.popper, {
'data-popper-placement': state.placement
});
} // eslint-disable-next-line import/no-unused-modules
/* harmony default export */ var modifiers_computeStyles = ({
name: 'computeStyles',
enabled: true,
phase: 'beforeWrite',
fn: computeStyles,
data: {}
});
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/applyStyles.js
// This modifier takes the styles prepared by the `computeStyles` modifier
// and applies them to the HTMLElements such as popper and arrow
function applyStyles(_ref) {
var state = _ref.state;
Object.keys(state.elements).forEach(function (name) {
var style = state.styles[name] || {};
var attributes = state.attributes[name] || {};
var element = state.elements[name]; // arrow is optional + virtual elements
if (!instanceOf_isHTMLElement(element) || !getNodeName_getNodeName(element)) {
return;
} // Flow doesn't support to extend this property, but it's the most
// effective way to apply styles to an HTMLElement
// $FlowFixMe[cannot-write]
Object.assign(element.style, style);
Object.keys(attributes).forEach(function (name) {
var value = attributes[name];
if (value === false) {
element.removeAttribute(name);
} else {
element.setAttribute(name, value === true ? '' : value);
}
});
});
}
function applyStyles_effect(_ref2) {
var state = _ref2.state;
var initialStyles = {
popper: {
position: state.options.strategy,
left: '0',
top: '0',
margin: '0'
},
arrow: {
position: 'absolute'
},
reference: {}
};
Object.assign(state.elements.popper.style, initialStyles.popper);
state.styles = initialStyles;
if (state.elements.arrow) {
Object.assign(state.elements.arrow.style, initialStyles.arrow);
}
return function () {
Object.keys(state.elements).forEach(function (name) {
var element = state.elements[name];
var attributes = state.attributes[name] || {};
var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); // Set all values to an empty string to unset them
var style = styleProperties.reduce(function (style, property) {
style[property] = '';
return style;
}, {}); // arrow is optional + virtual elements
if (!instanceOf_isHTMLElement(element) || !getNodeName_getNodeName(element)) {
return;
}
Object.assign(element.style, style);
Object.keys(attributes).forEach(function (attribute) {
element.removeAttribute(attribute);
});
});
};
} // eslint-disable-next-line import/no-unused-modules
/* harmony default export */ var modifiers_applyStyles = ({
name: 'applyStyles',
enabled: true,
phase: 'write',
fn: applyStyles,
effect: applyStyles_effect,
requires: ['computeStyles']
});
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/offset.js
// eslint-disable-next-line import/no-unused-modules
function distanceAndSkiddingToXY(placement, rects, offset) {
var basePlacement = getBasePlacement(placement);
var invertDistance = [left, enums_top].indexOf(basePlacement) >= 0 ? -1 : 1;
var _ref = typeof offset === 'function' ? offset(Object.assign({}, rects, {
placement: placement
})) : offset,
skidding = _ref[0],
distance = _ref[1];
skidding = skidding || 0;
distance = (distance || 0) * invertDistance;
return [left, right].indexOf(basePlacement) >= 0 ? {
x: distance,
y: skidding
} : {
x: skidding,
y: distance
};
}
function offset_offset(_ref2) {
var state = _ref2.state,
options = _ref2.options,
name = _ref2.name;
var _options$offset = options.offset,
offset = _options$offset === void 0 ? [0, 0] : _options$offset;
var data = enums_placements.reduce(function (acc, placement) {
acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset);
return acc;
}, {});
var _data$state$placement = data[state.placement],
x = _data$state$placement.x,
y = _data$state$placement.y;
if (state.modifiersData.popperOffsets != null) {
state.modifiersData.popperOffsets.x += x;
state.modifiersData.popperOffsets.y += y;
}
state.modifiersData[name] = data;
} // eslint-disable-next-line import/no-unused-modules
/* harmony default export */ var modifiers_offset = ({
name: 'offset',
enabled: true,
phase: 'main',
requires: ['popperOffsets'],
fn: offset_offset
});
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/getOppositePlacement.js
var getOppositePlacement_hash = {
left: 'right',
right: 'left',
bottom: 'top',
top: 'bottom'
};
function getOppositePlacement_getOppositePlacement(placement) {
return placement.replace(/left|right|bottom|top/g, function (matched) {
return getOppositePlacement_hash[matched];
});
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js
var getOppositeVariationPlacement_hash = {
start: 'end',
end: 'start'
};
function getOppositeVariationPlacement(placement) {
return placement.replace(/start|end/g, function (matched) {
return getOppositeVariationPlacement_hash[matched];
});
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js
function getViewportRect_getViewportRect(element, strategy) {
var win = getWindow_getWindow(element);
var html = getDocumentElement_getDocumentElement(element);
var visualViewport = win.visualViewport;
var width = html.clientWidth;
var height = html.clientHeight;
var x = 0;
var y = 0;
if (visualViewport) {
width = visualViewport.width;
height = visualViewport.height;
var layoutViewport = isLayoutViewport();
if (layoutViewport || !layoutViewport && strategy === 'fixed') {
x = visualViewport.offsetLeft;
y = visualViewport.offsetTop;
}
}
return {
width: width,
height: height,
x: x + getWindowScrollBarX_getWindowScrollBarX(element),
y: y
};
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js
// Gets the entire size of the scrollable document area, even extending outside
// of the `<html>` and `<body>` rect bounds if horizontally scrollable
function getDocumentRect_getDocumentRect(element) {
var _element$ownerDocumen;
var html = getDocumentElement_getDocumentElement(element);
var winScroll = getWindowScroll(element);
var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body;
var width = math_max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);
var height = math_max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);
var x = -winScroll.scrollLeft + getWindowScrollBarX_getWindowScrollBarX(element);
var y = -winScroll.scrollTop;
if (getComputedStyle_getComputedStyle(body || html).direction === 'rtl') {
x += math_max(html.clientWidth, body ? body.clientWidth : 0) - width;
}
return {
width: width,
height: height,
x: x,
y: y
};
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/contains.js
function contains_contains(parent, child) {
var rootNode = child.getRootNode && child.getRootNode(); // First, attempt with faster native method
if (parent.contains(child)) {
return true;
} // then fallback to custom implementation with Shadow DOM support
else if (rootNode && instanceOf_isShadowRoot(rootNode)) {
var next = child;
do {
if (next && parent.isSameNode(next)) {
return true;
} // $FlowFixMe[prop-missing]: need a better way to handle this...
next = next.parentNode || next.host;
} while (next);
} // Give up, the result is false
return false;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/rectToClientRect.js
function rectToClientRect_rectToClientRect(rect) {
return Object.assign({}, rect, {
left: rect.x,
top: rect.y,
right: rect.x + rect.width,
bottom: rect.y + rect.height
});
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js
function getClippingRect_getInnerBoundingClientRect(element, strategy) {
var rect = getBoundingClientRect_getBoundingClientRect(element, false, strategy === 'fixed');
rect.top = rect.top + element.clientTop;
rect.left = rect.left + element.clientLeft;
rect.bottom = rect.top + element.clientHeight;
rect.right = rect.left + element.clientWidth;
rect.width = element.clientWidth;
rect.height = element.clientHeight;
rect.x = rect.left;
rect.y = rect.top;
return rect;
}
function getClientRectFromMixedType(element, clippingParent, strategy) {
return clippingParent === viewport ? rectToClientRect_rectToClientRect(getViewportRect_getViewportRect(element, strategy)) : instanceOf_isElement(clippingParent) ? getClippingRect_getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect_rectToClientRect(getDocumentRect_getDocumentRect(getDocumentElement_getDocumentElement(element)));
} // A "clipping parent" is an overflowable container with the characteristic of
// clipping (or hiding) overflowing elements with a position different from
// `initial`
function getClippingParents(element) {
var clippingParents = listScrollParents(getParentNode_getParentNode(element));
var canEscapeClipping = ['absolute', 'fixed'].indexOf(getComputedStyle_getComputedStyle(element).position) >= 0;
var clipperElement = canEscapeClipping && instanceOf_isHTMLElement(element) ? getOffsetParent_getOffsetParent(element) : element;
if (!instanceOf_isElement(clipperElement)) {
return [];
} // $FlowFixMe[incompatible-return]: https://github.com/facebook/flow/issues/1414
return clippingParents.filter(function (clippingParent) {
return instanceOf_isElement(clippingParent) && contains_contains(clippingParent, clipperElement) && getNodeName_getNodeName(clippingParent) !== 'body';
});
} // Gets the maximum area that the element is visible in due to any number of
// clipping parents
function getClippingRect_getClippingRect(element, boundary, rootBoundary, strategy) {
var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary);
var clippingParents = [].concat(mainClippingParents, [rootBoundary]);
var firstClippingParent = clippingParents[0];
var clippingRect = clippingParents.reduce(function (accRect, clippingParent) {
var rect = getClientRectFromMixedType(element, clippingParent, strategy);
accRect.top = math_max(rect.top, accRect.top);
accRect.right = math_min(rect.right, accRect.right);
accRect.bottom = math_min(rect.bottom, accRect.bottom);
accRect.left = math_max(rect.left, accRect.left);
return accRect;
}, getClientRectFromMixedType(element, firstClippingParent, strategy));
clippingRect.width = clippingRect.right - clippingRect.left;
clippingRect.height = clippingRect.bottom - clippingRect.top;
clippingRect.x = clippingRect.left;
clippingRect.y = clippingRect.top;
return clippingRect;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/getFreshSideObject.js
function getFreshSideObject() {
return {
top: 0,
right: 0,
bottom: 0,
left: 0
};
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/mergePaddingObject.js
function mergePaddingObject(paddingObject) {
return Object.assign({}, getFreshSideObject(), paddingObject);
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/expandToHashMap.js
function expandToHashMap(value, keys) {
return keys.reduce(function (hashMap, key) {
hashMap[key] = value;
return hashMap;
}, {});
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/detectOverflow.js
// eslint-disable-next-line import/no-unused-modules
function detectOverflow_detectOverflow(state, options) {
if (options === void 0) {
options = {};
}
var _options = options,
_options$placement = _options.placement,
placement = _options$placement === void 0 ? state.placement : _options$placement,
_options$strategy = _options.strategy,
strategy = _options$strategy === void 0 ? state.strategy : _options$strategy,
_options$boundary = _options.boundary,
boundary = _options$boundary === void 0 ? clippingParents : _options$boundary,
_options$rootBoundary = _options.rootBoundary,
rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary,
_options$elementConte = _options.elementContext,
elementContext = _options$elementConte === void 0 ? popper : _options$elementConte,
_options$altBoundary = _options.altBoundary,
altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary,
_options$padding = _options.padding,
padding = _options$padding === void 0 ? 0 : _options$padding;
var paddingObject = mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));
var altContext = elementContext === popper ? reference : popper;
var popperRect = state.rects.popper;
var element = state.elements[altBoundary ? altContext : elementContext];
var clippingClientRect = getClippingRect_getClippingRect(instanceOf_isElement(element) ? element : element.contextElement || getDocumentElement_getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy);
var referenceClientRect = getBoundingClientRect_getBoundingClientRect(state.elements.reference);
var popperOffsets = computeOffsets({
reference: referenceClientRect,
element: popperRect,
strategy: 'absolute',
placement: placement
});
var popperClientRect = rectToClientRect_rectToClientRect(Object.assign({}, popperRect, popperOffsets));
var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; // positive = overflowing the clipping rect
// 0 or negative = within the clipping rect
var overflowOffsets = {
top: clippingClientRect.top - elementClientRect.top + paddingObject.top,
bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,
left: clippingClientRect.left - elementClientRect.left + paddingObject.left,
right: elementClientRect.right - clippingClientRect.right + paddingObject.right
};
var offsetData = state.modifiersData.offset; // Offsets can be applied only to the popper element
if (elementContext === popper && offsetData) {
var offset = offsetData[placement];
Object.keys(overflowOffsets).forEach(function (key) {
var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1;
var axis = [enums_top, bottom].indexOf(key) >= 0 ? 'y' : 'x';
overflowOffsets[key] += offset[axis] * multiply;
});
}
return overflowOffsets;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js
function computeAutoPlacement(state, options) {
if (options === void 0) {
options = {};
}
var _options = options,
placement = _options.placement,
boundary = _options.boundary,
rootBoundary = _options.rootBoundary,
padding = _options.padding,
flipVariations = _options.flipVariations,
_options$allowedAutoP = _options.allowedAutoPlacements,
allowedAutoPlacements = _options$allowedAutoP === void 0 ? enums_placements : _options$allowedAutoP;
var variation = getVariation(placement);
var placements = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function (placement) {
return getVariation(placement) === variation;
}) : basePlacements;
var allowedPlacements = placements.filter(function (placement) {
return allowedAutoPlacements.indexOf(placement) >= 0;
});
if (allowedPlacements.length === 0) {
allowedPlacements = placements;
} // $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions...
var overflows = allowedPlacements.reduce(function (acc, placement) {
acc[placement] = detectOverflow_detectOverflow(state, {
placement: placement,
boundary: boundary,
rootBoundary: rootBoundary,
padding: padding
})[getBasePlacement(placement)];
return acc;
}, {});
return Object.keys(overflows).sort(function (a, b) {
return overflows[a] - overflows[b];
});
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/flip.js
// eslint-disable-next-line import/no-unused-modules
function getExpandedFallbackPlacements(placement) {
if (getBasePlacement(placement) === enums_auto) {
return [];
}
var oppositePlacement = getOppositePlacement_getOppositePlacement(placement);
return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];
}
function flip_flip(_ref) {
var state = _ref.state,
options = _ref.options,
name = _ref.name;
if (state.modifiersData[name]._skip) {
return;
}
var _options$mainAxis = options.mainAxis,
checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,
_options$altAxis = options.altAxis,
checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis,
specifiedFallbackPlacements = options.fallbackPlacements,
padding = options.padding,
boundary = options.boundary,
rootBoundary = options.rootBoundary,
altBoundary = options.altBoundary,
_options$flipVariatio = options.flipVariations,
flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio,
allowedAutoPlacements = options.allowedAutoPlacements;
var preferredPlacement = state.options.placement;
var basePlacement = getBasePlacement(preferredPlacement);
var isBasePlacement = basePlacement === preferredPlacement;
var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement_getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));
var placements = [preferredPlacement].concat(fallbackPlacements).reduce(function (acc, placement) {
return acc.concat(getBasePlacement(placement) === enums_auto ? computeAutoPlacement(state, {
placement: placement,
boundary: boundary,
rootBoundary: rootBoundary,
padding: padding,
flipVariations: flipVariations,
allowedAutoPlacements: allowedAutoPlacements
}) : placement);
}, []);
var referenceRect = state.rects.reference;
var popperRect = state.rects.popper;
var checksMap = new Map();
var makeFallbackChecks = true;
var firstFittingPlacement = placements[0];
for (var i = 0; i < placements.length; i++) {
var placement = placements[i];
var _basePlacement = getBasePlacement(placement);
var isStartVariation = getVariation(placement) === start;
var isVertical = [enums_top, bottom].indexOf(_basePlacement) >= 0;
var len = isVertical ? 'width' : 'height';
var overflow = detectOverflow_detectOverflow(state, {
placement: placement,
boundary: boundary,
rootBoundary: rootBoundary,
altBoundary: altBoundary,
padding: padding
});
var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : enums_top;
if (referenceRect[len] > popperRect[len]) {
mainVariationSide = getOppositePlacement_getOppositePlacement(mainVariationSide);
}
var altVariationSide = getOppositePlacement_getOppositePlacement(mainVariationSide);
var checks = [];
if (checkMainAxis) {
checks.push(overflow[_basePlacement] <= 0);
}
if (checkAltAxis) {
checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);
}
if (checks.every(function (check) {
return check;
})) {
firstFittingPlacement = placement;
makeFallbackChecks = false;
break;
}
checksMap.set(placement, checks);
}
if (makeFallbackChecks) {
// `2` may be desired in some cases – research later
var numberOfChecks = flipVariations ? 3 : 1;
var _loop = function _loop(_i) {
var fittingPlacement = placements.find(function (placement) {
var checks = checksMap.get(placement);
if (checks) {
return checks.slice(0, _i).every(function (check) {
return check;
});
}
});
if (fittingPlacement) {
firstFittingPlacement = fittingPlacement;
return "break";
}
};
for (var _i = numberOfChecks; _i > 0; _i--) {
var _ret = _loop(_i);
if (_ret === "break") break;
}
}
if (state.placement !== firstFittingPlacement) {
state.modifiersData[name]._skip = true;
state.placement = firstFittingPlacement;
state.reset = true;
}
} // eslint-disable-next-line import/no-unused-modules
/* harmony default export */ var modifiers_flip = ({
name: 'flip',
enabled: true,
phase: 'main',
fn: flip_flip,
requiresIfExists: ['offset'],
data: {
_skip: false
}
});
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/getAltAxis.js
function getAltAxis(axis) {
return axis === 'x' ? 'y' : 'x';
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/within.js
function within(min, value, max) {
return math_max(min, math_min(value, max));
}
function withinMaxClamp(min, value, max) {
var v = within(min, value, max);
return v > max ? max : v;
}
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/preventOverflow.js
function preventOverflow(_ref) {
var state = _ref.state,
options = _ref.options,
name = _ref.name;
var _options$mainAxis = options.mainAxis,
checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,
_options$altAxis = options.altAxis,
checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis,
boundary = options.boundary,
rootBoundary = options.rootBoundary,
altBoundary = options.altBoundary,
padding = options.padding,
_options$tether = options.tether,
tether = _options$tether === void 0 ? true : _options$tether,
_options$tetherOffset = options.tetherOffset,
tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset;
var overflow = detectOverflow_detectOverflow(state, {
boundary: boundary,
rootBoundary: rootBoundary,
padding: padding,
altBoundary: altBoundary
});
var basePlacement = getBasePlacement(state.placement);
var variation = getVariation(state.placement);
var isBasePlacement = !variation;
var mainAxis = getMainAxisFromPlacement_getMainAxisFromPlacement(basePlacement);
var altAxis = getAltAxis(mainAxis);
var popperOffsets = state.modifiersData.popperOffsets;
var referenceRect = state.rects.reference;
var popperRect = state.rects.popper;
var tetherOffsetValue = typeof tetherOffset === 'function' ? tetherOffset(Object.assign({}, state.rects, {
placement: state.placement
})) : tetherOffset;
var normalizedTetherOffsetValue = typeof tetherOffsetValue === 'number' ? {
mainAxis: tetherOffsetValue,
altAxis: tetherOffsetValue
} : Object.assign({
mainAxis: 0,
altAxis: 0
}, tetherOffsetValue);
var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null;
var data = {
x: 0,
y: 0
};
if (!popperOffsets) {
return;
}
if (checkMainAxis) {
var _offsetModifierState$;
var mainSide = mainAxis === 'y' ? enums_top : left;
var altSide = mainAxis === 'y' ? bottom : right;
var len = mainAxis === 'y' ? 'height' : 'width';
var offset = popperOffsets[mainAxis];
var min = offset + overflow[mainSide];
var max = offset - overflow[altSide];
var additive = tether ? -popperRect[len] / 2 : 0;
var minLen = variation === start ? referenceRect[len] : popperRect[len];
var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; // We need to include the arrow in the calculation so the arrow doesn't go
// outside the reference bounds
var arrowElement = state.elements.arrow;
var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {
width: 0,
height: 0
};
var arrowPaddingObject = state.modifiersData['arrow#persistent'] ? state.modifiersData['arrow#persistent'].padding : getFreshSideObject();
var arrowPaddingMin = arrowPaddingObject[mainSide];
var arrowPaddingMax = arrowPaddingObject[altSide]; // If the reference length is smaller than the arrow length, we don't want
// to include its full size in the calculation. If the reference is small
// and near the edge of a boundary, the popper can overflow even if the
// reference is not overflowing as well (e.g. virtual elements with no
// width or height)
var arrowLen = within(0, referenceRect[len], arrowRect[len]);
var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis;
var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis;
var arrowOffsetParent = state.elements.arrow && getOffsetParent_getOffsetParent(state.elements.arrow);
var clientOffset = arrowOffsetParent ? mainAxis === 'y' ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;
var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0;
var tetherMin = offset + minOffset - offsetModifierValue - clientOffset;
var tetherMax = offset + maxOffset - offsetModifierValue;
var preventedOffset = within(tether ? math_min(min, tetherMin) : min, offset, tether ? math_max(max, tetherMax) : max);
popperOffsets[mainAxis] = preventedOffset;
data[mainAxis] = preventedOffset - offset;
}
if (checkAltAxis) {
var _offsetModifierState$2;
var _mainSide = mainAxis === 'x' ? enums_top : left;
var _altSide = mainAxis === 'x' ? bottom : right;
var _offset = popperOffsets[altAxis];
var _len = altAxis === 'y' ? 'height' : 'width';
var _min = _offset + overflow[_mainSide];
var _max = _offset - overflow[_altSide];
var isOriginSide = [enums_top, left].indexOf(basePlacement) !== -1;
var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0;
var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis;
var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max;
var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max);
popperOffsets[altAxis] = _preventedOffset;
data[altAxis] = _preventedOffset - _offset;
}
state.modifiersData[name] = data;
} // eslint-disable-next-line import/no-unused-modules
/* harmony default export */ var modifiers_preventOverflow = ({
name: 'preventOverflow',
enabled: true,
phase: 'main',
fn: preventOverflow,
requiresIfExists: ['offset']
});
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/arrow.js
// eslint-disable-next-line import/no-unused-modules
var toPaddingObject = function toPaddingObject(padding, state) {
padding = typeof padding === 'function' ? padding(Object.assign({}, state.rects, {
placement: state.placement
})) : padding;
return mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));
};
function arrow_arrow(_ref) {
var _state$modifiersData$;
var state = _ref.state,
name = _ref.name,
options = _ref.options;
var arrowElement = state.elements.arrow;
var popperOffsets = state.modifiersData.popperOffsets;
var basePlacement = getBasePlacement(state.placement);
var axis = getMainAxisFromPlacement_getMainAxisFromPlacement(basePlacement);
var isVertical = [left, right].indexOf(basePlacement) >= 0;
var len = isVertical ? 'height' : 'width';
if (!arrowElement || !popperOffsets) {
return;
}
var paddingObject = toPaddingObject(options.padding, state);
var arrowRect = getLayoutRect(arrowElement);
var minProp = axis === 'y' ? enums_top : left;
var maxProp = axis === 'y' ? bottom : right;
var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len];
var startDiff = popperOffsets[axis] - state.rects.reference[axis];
var arrowOffsetParent = getOffsetParent_getOffsetParent(arrowElement);
var clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;
var centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the popper if the center point is
// outside of the popper bounds
var min = paddingObject[minProp];
var max = clientSize - arrowRect[len] - paddingObject[maxProp];
var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;
var offset = within(min, center, max); // Prevents breaking syntax highlighting...
var axisProp = axis;
state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset, _state$modifiersData$.centerOffset = offset - center, _state$modifiersData$);
}
function arrow_effect(_ref2) {
var state = _ref2.state,
options = _ref2.options;
var _options$element = options.element,
arrowElement = _options$element === void 0 ? '[data-popper-arrow]' : _options$element;
if (arrowElement == null) {
return;
} // CSS selector
if (typeof arrowElement === 'string') {
arrowElement = state.elements.popper.querySelector(arrowElement);
if (!arrowElement) {
return;
}
}
if (!contains_contains(state.elements.popper, arrowElement)) {
return;
}
state.elements.arrow = arrowElement;
} // eslint-disable-next-line import/no-unused-modules
/* harmony default export */ var modifiers_arrow = ({
name: 'arrow',
enabled: true,
phase: 'main',
fn: arrow_arrow,
effect: arrow_effect,
requires: ['popperOffsets'],
requiresIfExists: ['preventOverflow']
});
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/hide.js
function hide_getSideOffsets(overflow, rect, preventedOffsets) {
if (preventedOffsets === void 0) {
preventedOffsets = {
x: 0,
y: 0
};
}
return {
top: overflow.top - rect.height - preventedOffsets.y,
right: overflow.right - rect.width + preventedOffsets.x,
bottom: overflow.bottom - rect.height + preventedOffsets.y,
left: overflow.left - rect.width - preventedOffsets.x
};
}
function hide_isAnySideFullyClipped(overflow) {
return [enums_top, right, bottom, left].some(function (side) {
return overflow[side] >= 0;
});
}
function hide_hide(_ref) {
var state = _ref.state,
name = _ref.name;
var referenceRect = state.rects.reference;
var popperRect = state.rects.popper;
var preventedOffsets = state.modifiersData.preventOverflow;
var referenceOverflow = detectOverflow_detectOverflow(state, {
elementContext: 'reference'
});
var popperAltOverflow = detectOverflow_detectOverflow(state, {
altBoundary: true
});
var referenceClippingOffsets = hide_getSideOffsets(referenceOverflow, referenceRect);
var popperEscapeOffsets = hide_getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);
var isReferenceHidden = hide_isAnySideFullyClipped(referenceClippingOffsets);
var hasPopperEscaped = hide_isAnySideFullyClipped(popperEscapeOffsets);
state.modifiersData[name] = {
referenceClippingOffsets: referenceClippingOffsets,
popperEscapeOffsets: popperEscapeOffsets,
isReferenceHidden: isReferenceHidden,
hasPopperEscaped: hasPopperEscaped
};
state.attributes.popper = Object.assign({}, state.attributes.popper, {
'data-popper-reference-hidden': isReferenceHidden,
'data-popper-escaped': hasPopperEscaped
});
} // eslint-disable-next-line import/no-unused-modules
/* harmony default export */ var modifiers_hide = ({
name: 'hide',
enabled: true,
phase: 'main',
requiresIfExists: ['preventOverflow'],
fn: hide_hide
});
;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/popper.js
var defaultModifiers = [eventListeners, modifiers_popperOffsets, modifiers_computeStyles, modifiers_applyStyles, modifiers_offset, modifiers_flip, modifiers_preventOverflow, modifiers_arrow, modifiers_hide];
var popper_createPopper = /*#__PURE__*/popperGenerator({
defaultModifiers: defaultModifiers
}); // eslint-disable-next-line import/no-unused-modules
// eslint-disable-next-line import/no-unused-modules
// eslint-disable-next-line import/no-unused-modules
;// CONCATENATED MODULE: ./node_modules/reakit/es/Disclosure/DisclosureState.js
function useLastValue(value) {
var lastValue = (0,external_React_.useRef)(null);
useIsomorphicEffect(function () {
lastValue.current = value;
}, [value]);
return lastValue;
}
function useDisclosureState(initialState) {
if (initialState === void 0) {
initialState = {};
}
var _useSealedState = useSealedState(initialState),
_useSealedState$visib = _useSealedState.visible,
initialVisible = _useSealedState$visib === void 0 ? false : _useSealedState$visib,
_useSealedState$anima = _useSealedState.animated,
initialAnimated = _useSealedState$anima === void 0 ? false : _useSealedState$anima,
sealed = _objectWithoutPropertiesLoose(_useSealedState, ["visible", "animated"]);
var id = unstable_useIdState(sealed);
var _React$useState = (0,external_React_.useState)(initialVisible),
visible = _React$useState[0],
setVisible = _React$useState[1];
var _React$useState2 = (0,external_React_.useState)(initialAnimated),
animated = _React$useState2[0],
setAnimated = _React$useState2[1];
var _React$useState3 = (0,external_React_.useState)(false),
animating = _React$useState3[0],
setAnimating = _React$useState3[1];
var lastVisible = useLastValue(visible);
var visibleHasChanged = lastVisible.current != null && lastVisible.current !== visible;
if (animated && !animating && visibleHasChanged) {
// Sets animating to true when when visible is updated
setAnimating(true);
}
(0,external_React_.useEffect)(function () {
if (typeof animated === "number" && animating) {
var timeout = setTimeout(function () {
return setAnimating(false);
}, animated);
return function () {
clearTimeout(timeout);
};
}
if (animated && animating && "production" === "development") { var _timeout; }
return function () {};
}, [animated, animating]);
var show = (0,external_React_.useCallback)(function () {
return setVisible(true);
}, []);
var hide = (0,external_React_.useCallback)(function () {
return setVisible(false);
}, []);
var toggle = (0,external_React_.useCallback)(function () {
return setVisible(function (v) {
return !v;
});
}, []);
var stopAnimation = (0,external_React_.useCallback)(function () {
return setAnimating(false);
}, []);
return _objectSpread2(_objectSpread2({}, id), {}, {
visible: visible,
animated: animated,
animating: animating,
show: show,
hide: hide,
toggle: toggle,
setVisible: setVisible,
setAnimated: setAnimated,
stopAnimation: stopAnimation
});
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/Dialog/DialogState.js
function useDialogState(initialState) {
if (initialState === void 0) {
initialState = {};
}
var _useSealedState = useSealedState(initialState),
_useSealedState$modal = _useSealedState.modal,
initialModal = _useSealedState$modal === void 0 ? true : _useSealedState$modal,
sealed = _objectWithoutPropertiesLoose(_useSealedState, ["modal"]);
var disclosure = useDisclosureState(sealed);
var _React$useState = (0,external_React_.useState)(initialModal),
modal = _React$useState[0],
setModal = _React$useState[1];
var disclosureRef = (0,external_React_.useRef)(null);
return _objectSpread2(_objectSpread2({}, disclosure), {}, {
modal: modal,
setModal: setModal,
unstable_disclosureRef: disclosureRef
});
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/Popover/PopoverState.js
var isSafari = isUA("Mac") && !isUA("Chrome") && isUA("Safari");
function PopoverState_applyStyles(styles) {
return function (prevStyles) {
if (styles && !shallowEqual(prevStyles, styles)) {
return styles;
}
return prevStyles;
};
}
function usePopoverState(initialState) {
if (initialState === void 0) {
initialState = {};
}
var _useSealedState = useSealedState(initialState),
_useSealedState$gutte = _useSealedState.gutter,
gutter = _useSealedState$gutte === void 0 ? 12 : _useSealedState$gutte,
_useSealedState$place = _useSealedState.placement,
sealedPlacement = _useSealedState$place === void 0 ? "bottom" : _useSealedState$place,
_useSealedState$unsta = _useSealedState.unstable_flip,
flip = _useSealedState$unsta === void 0 ? true : _useSealedState$unsta,
sealedOffset = _useSealedState.unstable_offset,
_useSealedState$unsta2 = _useSealedState.unstable_preventOverflow,
preventOverflow = _useSealedState$unsta2 === void 0 ? true : _useSealedState$unsta2,
_useSealedState$unsta3 = _useSealedState.unstable_fixed,
fixed = _useSealedState$unsta3 === void 0 ? false : _useSealedState$unsta3,
_useSealedState$modal = _useSealedState.modal,
modal = _useSealedState$modal === void 0 ? false : _useSealedState$modal,
sealed = _objectWithoutPropertiesLoose(_useSealedState, ["gutter", "placement", "unstable_flip", "unstable_offset", "unstable_preventOverflow", "unstable_fixed", "modal"]);
var popper = (0,external_React_.useRef)(null);
var referenceRef = (0,external_React_.useRef)(null);
var popoverRef = (0,external_React_.useRef)(null);
var arrowRef = (0,external_React_.useRef)(null);
var _React$useState = (0,external_React_.useState)(sealedPlacement),
originalPlacement = _React$useState[0],
place = _React$useState[1];
var _React$useState2 = (0,external_React_.useState)(sealedPlacement),
placement = _React$useState2[0],
setPlacement = _React$useState2[1];
var _React$useState3 = (0,external_React_.useState)(sealedOffset || [0, gutter]),
offset = _React$useState3[0];
var _React$useState4 = (0,external_React_.useState)({
position: "fixed",
left: "100%",
top: "100%"
}),
popoverStyles = _React$useState4[0],
setPopoverStyles = _React$useState4[1];
var _React$useState5 = (0,external_React_.useState)({}),
arrowStyles = _React$useState5[0],
setArrowStyles = _React$useState5[1];
var dialog = useDialogState(_objectSpread2({
modal: modal
}, sealed));
var update = (0,external_React_.useCallback)(function () {
if (popper.current) {
popper.current.forceUpdate();
return true;
}
return false;
}, []);
var updateState = (0,external_React_.useCallback)(function (state) {
if (state.placement) {
setPlacement(state.placement);
}
if (state.styles) {
setPopoverStyles(PopoverState_applyStyles(state.styles.popper));
if (arrowRef.current) {
setArrowStyles(PopoverState_applyStyles(state.styles.arrow));
}
}
}, []);
useIsomorphicEffect(function () {
if (referenceRef.current && popoverRef.current) {
popper.current = popper_createPopper(referenceRef.current, popoverRef.current, {
// https://popper.js.org/docs/v2/constructors/#options
placement: originalPlacement,
strategy: fixed ? "fixed" : "absolute",
// Safari needs styles to be applied in the first render, otherwise
// hovering over the popover when it gets visible for the first time
// will change its dimensions unexpectedly.
onFirstUpdate: isSafari ? updateState : undefined,
modifiers: [{
// https://popper.js.org/docs/v2/modifiers/event-listeners/
name: "eventListeners",
enabled: dialog.visible
}, {
// https://popper.js.org/docs/v2/modifiers/apply-styles/
name: "applyStyles",
enabled: false
}, {
// https://popper.js.org/docs/v2/modifiers/flip/
name: "flip",
enabled: flip,
options: {
padding: 8
}
}, {
// https://popper.js.org/docs/v2/modifiers/offset/
name: "offset",
options: {
offset: offset
}
}, {
// https://popper.js.org/docs/v2/modifiers/prevent-overflow/
name: "preventOverflow",
enabled: preventOverflow,
options: {
tetherOffset: function tetherOffset() {
var _arrowRef$current;
return ((_arrowRef$current = arrowRef.current) === null || _arrowRef$current === void 0 ? void 0 : _arrowRef$current.clientWidth) || 0;
}
}
}, {
// https://popper.js.org/docs/v2/modifiers/arrow/
name: "arrow",
enabled: !!arrowRef.current,
options: {
element: arrowRef.current
}
}, {
// https://popper.js.org/docs/v2/modifiers/#custom-modifiers
name: "updateState",
phase: "write",
requires: ["computeStyles"],
enabled: dialog.visible && "production" !== "test",
fn: function fn(_ref) {
var state = _ref.state;
return updateState(state);
}
}]
});
}
return function () {
if (popper.current) {
popper.current.destroy();
popper.current = null;
}
};
}, [originalPlacement, fixed, dialog.visible, flip, offset, preventOverflow]); // Ensure that the popover will be correctly positioned with an additional
// update.
(0,external_React_.useEffect)(function () {
if (!dialog.visible) return undefined;
var id = window.requestAnimationFrame(function () {
var _popper$current;
(_popper$current = popper.current) === null || _popper$current === void 0 ? void 0 : _popper$current.forceUpdate();
});
return function () {
window.cancelAnimationFrame(id);
};
}, [dialog.visible]);
return _objectSpread2(_objectSpread2({}, dialog), {}, {
unstable_referenceRef: referenceRef,
unstable_popoverRef: popoverRef,
unstable_arrowRef: arrowRef,
unstable_popoverStyles: popoverStyles,
unstable_arrowStyles: arrowStyles,
unstable_update: update,
unstable_originalPlacement: originalPlacement,
placement: placement,
place: place
});
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/__globalState-300469f0.js
var globalState = {
currentTooltipId: null,
listeners: new Set(),
subscribe: function subscribe(listener) {
var _this = this;
this.listeners.add(listener);
return function () {
_this.listeners.delete(listener);
};
},
show: function show(id) {
this.currentTooltipId = id;
this.listeners.forEach(function (listener) {
return listener(id);
});
},
hide: function hide(id) {
if (this.currentTooltipId === id) {
this.currentTooltipId = null;
this.listeners.forEach(function (listener) {
return listener(null);
});
}
}
};
;// CONCATENATED MODULE: ./node_modules/reakit/es/Tooltip/TooltipState.js
function useTooltipState(initialState) {
if (initialState === void 0) {
initialState = {};
}
var _useSealedState = useSealedState(initialState),
_useSealedState$place = _useSealedState.placement,
placement = _useSealedState$place === void 0 ? "top" : _useSealedState$place,
_useSealedState$unsta = _useSealedState.unstable_timeout,
initialTimeout = _useSealedState$unsta === void 0 ? 0 : _useSealedState$unsta,
sealed = _objectWithoutPropertiesLoose(_useSealedState, ["placement", "unstable_timeout"]);
var _React$useState = (0,external_React_.useState)(initialTimeout),
timeout = _React$useState[0],
setTimeout = _React$useState[1];
var showTimeout = (0,external_React_.useRef)(null);
var hideTimeout = (0,external_React_.useRef)(null);
var _usePopoverState = usePopoverState(_objectSpread2(_objectSpread2({}, sealed), {}, {
placement: placement
})),
modal = _usePopoverState.modal,
setModal = _usePopoverState.setModal,
popover = _objectWithoutPropertiesLoose(_usePopoverState, ["modal", "setModal"]);
var clearTimeouts = (0,external_React_.useCallback)(function () {
if (showTimeout.current !== null) {
window.clearTimeout(showTimeout.current);
}
if (hideTimeout.current !== null) {
window.clearTimeout(hideTimeout.current);
}
}, []);
var hide = (0,external_React_.useCallback)(function () {
clearTimeouts();
popover.hide(); // Let's give some time so people can move from a reference to another
// and still show tooltips immediately
hideTimeout.current = window.setTimeout(function () {
globalState.hide(popover.baseId);
}, timeout);
}, [clearTimeouts, popover.hide, timeout, popover.baseId]);
var show = (0,external_React_.useCallback)(function () {
clearTimeouts();
if (!timeout || globalState.currentTooltipId) {
// If there's no timeout or a tooltip visible already, we can show this
// immediately
globalState.show(popover.baseId);
popover.show();
} else {
// There may be a reference with focus whose tooltip is still not visible
// In this case, we want to update it before it gets shown.
globalState.show(null); // Otherwise, wait a little bit to show the tooltip
showTimeout.current = window.setTimeout(function () {
globalState.show(popover.baseId);
popover.show();
}, timeout);
}
}, [clearTimeouts, timeout, popover.show, popover.baseId]);
(0,external_React_.useEffect)(function () {
return globalState.subscribe(function (id) {
if (id !== popover.baseId) {
clearTimeouts();
if (popover.visible) {
// Make sure there will be only one tooltip visible
popover.hide();
}
}
});
}, [popover.baseId, clearTimeouts, popover.visible, popover.hide]);
(0,external_React_.useEffect)(function () {
return function () {
clearTimeouts();
globalState.hide(popover.baseId);
};
}, [clearTimeouts, popover.baseId]);
return _objectSpread2(_objectSpread2({}, popover), {}, {
hide: hide,
show: show,
unstable_timeout: timeout,
unstable_setTimeout: setTimeout
});
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/__keys-d101cb3b.js
// Automatically generated
var TOOLTIP_STATE_KEYS = ["baseId", "unstable_idCountRef", "visible", "animated", "animating", "setBaseId", "show", "hide", "toggle", "setVisible", "setAnimated", "stopAnimation", "unstable_disclosureRef", "unstable_referenceRef", "unstable_popoverRef", "unstable_arrowRef", "unstable_popoverStyles", "unstable_arrowStyles", "unstable_originalPlacement", "unstable_update", "placement", "place", "unstable_timeout", "unstable_setTimeout"];
var TOOLTIP_KEYS = [].concat(TOOLTIP_STATE_KEYS, ["unstable_portal"]);
var TOOLTIP_ARROW_KEYS = TOOLTIP_STATE_KEYS;
var TOOLTIP_REFERENCE_KEYS = TOOLTIP_ARROW_KEYS;
;// CONCATENATED MODULE: ./node_modules/reakit/es/Tooltip/TooltipReference.js
var useTooltipReference = createHook({
name: "TooltipReference",
compose: useRole,
keys: TOOLTIP_REFERENCE_KEYS,
useProps: function useProps(options, _ref) {
var htmlRef = _ref.ref,
htmlOnFocus = _ref.onFocus,
htmlOnBlur = _ref.onBlur,
htmlOnMouseEnter = _ref.onMouseEnter,
htmlOnMouseLeave = _ref.onMouseLeave,
htmlProps = _objectWithoutPropertiesLoose(_ref, ["ref", "onFocus", "onBlur", "onMouseEnter", "onMouseLeave"]);
var onFocusRef = useLiveRef(htmlOnFocus);
var onBlurRef = useLiveRef(htmlOnBlur);
var onMouseEnterRef = useLiveRef(htmlOnMouseEnter);
var onMouseLeaveRef = useLiveRef(htmlOnMouseLeave);
var onFocus = (0,external_React_.useCallback)(function (event) {
var _onFocusRef$current, _options$show;
(_onFocusRef$current = onFocusRef.current) === null || _onFocusRef$current === void 0 ? void 0 : _onFocusRef$current.call(onFocusRef, event);
if (event.defaultPrevented) return;
(_options$show = options.show) === null || _options$show === void 0 ? void 0 : _options$show.call(options);
}, [options.show]);
var onBlur = (0,external_React_.useCallback)(function (event) {
var _onBlurRef$current, _options$hide;
(_onBlurRef$current = onBlurRef.current) === null || _onBlurRef$current === void 0 ? void 0 : _onBlurRef$current.call(onBlurRef, event);
if (event.defaultPrevented) return;
(_options$hide = options.hide) === null || _options$hide === void 0 ? void 0 : _options$hide.call(options);
}, [options.hide]);
var onMouseEnter = (0,external_React_.useCallback)(function (event) {
var _onMouseEnterRef$curr, _options$show2;
(_onMouseEnterRef$curr = onMouseEnterRef.current) === null || _onMouseEnterRef$curr === void 0 ? void 0 : _onMouseEnterRef$curr.call(onMouseEnterRef, event);
if (event.defaultPrevented) return;
(_options$show2 = options.show) === null || _options$show2 === void 0 ? void 0 : _options$show2.call(options);
}, [options.show]);
var onMouseLeave = (0,external_React_.useCallback)(function (event) {
var _onMouseLeaveRef$curr, _options$hide2;
(_onMouseLeaveRef$curr = onMouseLeaveRef.current) === null || _onMouseLeaveRef$curr === void 0 ? void 0 : _onMouseLeaveRef$curr.call(onMouseLeaveRef, event);
if (event.defaultPrevented) return;
(_options$hide2 = options.hide) === null || _options$hide2 === void 0 ? void 0 : _options$hide2.call(options);
}, [options.hide]);
return _objectSpread2({
ref: useForkRef(options.unstable_referenceRef, htmlRef),
tabIndex: 0,
onFocus: onFocus,
onBlur: onBlur,
onMouseEnter: onMouseEnter,
onMouseLeave: onMouseLeave,
"aria-describedby": options.baseId
}, htmlProps);
}
});
var TooltipReference = createComponent({
as: "div",
useHook: useTooltipReference
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/tooltip/context.js
/**
* WordPress dependencies
*/
/**
* @type {import('react').Context<{ tooltip?: import('reakit').TooltipState }>}
*/
const TooltipContext = (0,external_wp_element_namespaceObject.createContext)({});
const useTooltipContext = () => (0,external_wp_element_namespaceObject.useContext)(TooltipContext);
;// CONCATENATED MODULE: ./node_modules/reakit/es/__keys-e6a5cfbe.js
// Automatically generated
var DISCLOSURE_STATE_KEYS = ["baseId", "unstable_idCountRef", "visible", "animated", "animating", "setBaseId", "show", "hide", "toggle", "setVisible", "setAnimated", "stopAnimation"];
var DISCLOSURE_KEYS = DISCLOSURE_STATE_KEYS;
var DISCLOSURE_CONTENT_KEYS = DISCLOSURE_KEYS;
;// CONCATENATED MODULE: ./node_modules/reakit/es/Disclosure/DisclosureContent.js
var useDisclosureContent = createHook({
name: "DisclosureContent",
compose: useRole,
keys: DISCLOSURE_CONTENT_KEYS,
useProps: function useProps(options, _ref) {
var htmlOnTransitionEnd = _ref.onTransitionEnd,
htmlOnAnimationEnd = _ref.onAnimationEnd,
htmlStyle = _ref.style,
htmlProps = _objectWithoutPropertiesLoose(_ref, ["onTransitionEnd", "onAnimationEnd", "style"]);
var animating = options.animated && options.animating;
var _React$useState = (0,external_React_.useState)(null),
transition = _React$useState[0],
setTransition = _React$useState[1];
var hidden = !options.visible && !animating;
var style = hidden ? _objectSpread2({
display: "none"
}, htmlStyle) : htmlStyle;
var onTransitionEndRef = useLiveRef(htmlOnTransitionEnd);
var onAnimationEndRef = useLiveRef(htmlOnAnimationEnd);
var raf = (0,external_React_.useRef)(0);
(0,external_React_.useEffect)(function () {
if (!options.animated) return undefined; // Double RAF is needed so the browser has enough time to paint the
// default styles before processing the `data-enter` attribute. Otherwise
// it wouldn't be considered a transition.
// See https://github.com/reakit/reakit/issues/643
raf.current = window.requestAnimationFrame(function () {
raf.current = window.requestAnimationFrame(function () {
if (options.visible) {
setTransition("enter");
} else if (animating) {
setTransition("leave");
} else {
setTransition(null);
}
});
});
return function () {
return window.cancelAnimationFrame(raf.current);
};
}, [options.animated, options.visible, animating]);
var onEnd = (0,external_React_.useCallback)(function (event) {
if (!isSelfTarget(event)) return;
if (!animating) return; // Ignores number animated
if (options.animated === true) {
var _options$stopAnimatio;
(_options$stopAnimatio = options.stopAnimation) === null || _options$stopAnimatio === void 0 ? void 0 : _options$stopAnimatio.call(options);
}
}, [options.animated, animating, options.stopAnimation]);
var onTransitionEnd = (0,external_React_.useCallback)(function (event) {
var _onTransitionEndRef$c;
(_onTransitionEndRef$c = onTransitionEndRef.current) === null || _onTransitionEndRef$c === void 0 ? void 0 : _onTransitionEndRef$c.call(onTransitionEndRef, event);
onEnd(event);
}, [onEnd]);
var onAnimationEnd = (0,external_React_.useCallback)(function (event) {
var _onAnimationEndRef$cu;
(_onAnimationEndRef$cu = onAnimationEndRef.current) === null || _onAnimationEndRef$cu === void 0 ? void 0 : _onAnimationEndRef$cu.call(onAnimationEndRef, event);
onEnd(event);
}, [onEnd]);
return _objectSpread2({
id: options.baseId,
"data-enter": transition === "enter" ? "" : undefined,
"data-leave": transition === "leave" ? "" : undefined,
onTransitionEnd: onTransitionEnd,
onAnimationEnd: onAnimationEnd,
hidden: hidden,
style: style
}, htmlProps);
}
});
var DisclosureContent = createComponent({
as: "div",
useHook: useDisclosureContent
});
;// CONCATENATED MODULE: ./node_modules/reakit/es/Portal/Portal.js
function getBodyElement() {
return canUseDOM ? document.body : null;
}
var PortalContext = /*#__PURE__*/(0,external_React_.createContext)(getBodyElement());
function Portal(_ref) {
var children = _ref.children;
// if it's a nested portal, context is the parent portal
// otherwise it's document.body
// https://github.com/reakit/reakit/issues/513
var context = (0,external_React_.useContext)(PortalContext) || getBodyElement();
var _React$useState = (0,external_React_.useState)(function () {
if (canUseDOM) {
var element = document.createElement("div");
element.className = Portal.__className;
return element;
} // ssr
return null;
}),
hostNode = _React$useState[0];
useIsomorphicEffect(function () {
if (!hostNode || !context) return undefined;
context.appendChild(hostNode);
return function () {
context.removeChild(hostNode);
};
}, [hostNode, context]);
if (hostNode) {
return /*#__PURE__*/(0,external_ReactDOM_namespaceObject.createPortal)( /*#__PURE__*/(0,external_React_.createElement)(PortalContext.Provider, {
value: hostNode
}, children), hostNode);
} // ssr
return null;
}
Portal.__className = "__reakit-portal";
Portal.__selector = "." + Portal.__className;
;// CONCATENATED MODULE: ./node_modules/reakit/es/Tooltip/Tooltip.js
function globallyHideTooltipOnEscape(event) {
if (event.defaultPrevented) return;
if (event.key === "Escape") {
globalState.show(null);
}
}
var useTooltip = createHook({
name: "Tooltip",
compose: useDisclosureContent,
keys: TOOLTIP_KEYS,
useOptions: function useOptions(_ref) {
var _ref$unstable_portal = _ref.unstable_portal,
unstable_portal = _ref$unstable_portal === void 0 ? true : _ref$unstable_portal,
options = _objectWithoutPropertiesLoose(_ref, ["unstable_portal"]);
return _objectSpread2({
unstable_portal: unstable_portal
}, options);
},
useProps: function useProps(options, _ref2) {
var htmlRef = _ref2.ref,
htmlStyle = _ref2.style,
htmlWrapElement = _ref2.wrapElement,
htmlProps = _objectWithoutPropertiesLoose(_ref2, ["ref", "style", "wrapElement"]);
(0,external_React_.useEffect)(function () {
var _options$unstable_pop;
var document = getDocument((_options$unstable_pop = options.unstable_popoverRef) === null || _options$unstable_pop === void 0 ? void 0 : _options$unstable_pop.current);
document.addEventListener("keydown", globallyHideTooltipOnEscape);
}, []);
var wrapElement = (0,external_React_.useCallback)(function (element) {
if (options.unstable_portal) {
element = /*#__PURE__*/(0,external_React_.createElement)(Portal, null, element);
}
if (htmlWrapElement) {
return htmlWrapElement(element);
}
return element;
}, [options.unstable_portal, htmlWrapElement]);
return _objectSpread2({
ref: useForkRef(options.unstable_popoverRef, htmlRef),
role: "tooltip",
style: _objectSpread2(_objectSpread2({}, options.unstable_popoverStyles), {}, {
pointerEvents: "none"
}, htmlStyle),
wrapElement: wrapElement
}, htmlProps);
}
});
var Tooltip_Tooltip = createComponent({
as: "div",
memo: true,
useHook: useTooltip
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/shortcut/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function component_Shortcut(props, forwardedRef) {
const {
as: asProp = 'span',
shortcut,
className,
...otherProps
} = useContextSystem(props, 'Shortcut');
if (!shortcut) {
return null;
}
let displayText;
let ariaLabel;
if (typeof shortcut === 'string') {
displayText = shortcut;
} else {
displayText = shortcut.display;
ariaLabel = shortcut.ariaLabel;
}
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({
as: asProp,
className: className,
"aria-label": ariaLabel,
ref: forwardedRef
}, otherProps), displayText);
}
const ConnectedShortcut = contextConnect(component_Shortcut, 'Shortcut');
/* harmony default export */ var shortcut_component = (ConnectedShortcut);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/z-index.js
const Flyout = 10000;
const z_index_Tooltip = 1000002;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/tooltip/styles.js
function tooltip_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const TooltipContent = /*#__PURE__*/emotion_react_browser_esm_css("z-index:", z_index_Tooltip, ";box-sizing:border-box;opacity:0;outline:none;transform-origin:top center;transition:opacity ", config_values.transitionDurationFastest, " ease;font-size:", config_values.fontSize, ";&[data-enter]{opacity:1;}" + ( true ? "" : 0), true ? "" : 0);
const TooltipPopoverView = createStyled("div", true ? {
target: "e7tfjmw1"
} : 0)("background:rgba( 0, 0, 0, 0.8 );border-radius:2px;box-shadow:0 0 0 1px rgba( 255, 255, 255, 0.04 );color:", COLORS.white, ";padding:4px 8px;" + ( true ? "" : 0));
const noOutline = true ? {
name: "12mkfdx",
styles: "outline:none"
} : 0;
const TooltipShortcut = /*#__PURE__*/createStyled(shortcut_component, true ? {
target: "e7tfjmw0"
} : 0)("display:inline-block;margin-left:", space(1), ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/tooltip/content.js
/**
* External dependencies
*/
// eslint-disable-next-line no-restricted-imports
/**
* Internal dependencies
*/
const {
TooltipPopoverView: content_TooltipPopoverView
} = tooltip_styles_namespaceObject;
/**
*
* @param {import('../context').WordPressComponentProps<import('./types').ContentProps, 'div'>} props
* @param {import('react').ForwardedRef<any>} forwardedRef
*/
function content_TooltipContent(props, forwardedRef) {
const {
children,
className,
...otherProps
} = useContextSystem(props, 'TooltipContent');
const {
tooltip
} = useTooltipContext();
const cx = useCx();
const classes = cx(TooltipContent, className);
return (0,external_wp_element_namespaceObject.createElement)(Tooltip_Tooltip, extends_extends({
as: component
}, otherProps, tooltip, {
className: classes,
ref: forwardedRef
}), (0,external_wp_element_namespaceObject.createElement)(content_TooltipPopoverView, null, children));
}
/* harmony default export */ var tooltip_content = (contextConnect(content_TooltipContent, 'TooltipContent'));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/ui/tooltip/component.js
/**
* External dependencies
*/
// eslint-disable-next-line no-restricted-imports
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* @param {import('../context').WordPressComponentProps<import('./types').Props, 'div'>} props
* @param {import('react').ForwardedRef<any>} forwardedRef
*/
function component_Tooltip(props, forwardedRef) {
const {
animated = true,
animationDuration = 160,
baseId,
children,
content,
focusable = true,
gutter = 4,
id,
modal = true,
placement,
visible = false,
shortcut,
...otherProps
} = useContextSystem(props, 'Tooltip');
const tooltip = useTooltipState({
animated: animated ? animationDuration : undefined,
baseId: baseId || id,
gutter,
placement,
visible,
...otherProps
});
const contextProps = (0,external_wp_element_namespaceObject.useMemo)(() => ({
tooltip
}), [tooltip]);
return (0,external_wp_element_namespaceObject.createElement)(TooltipContext.Provider, {
value: contextProps
}, content && (0,external_wp_element_namespaceObject.createElement)(tooltip_content, {
unstable_portal: modal,
ref: forwardedRef
}, content, shortcut && (0,external_wp_element_namespaceObject.createElement)(TooltipShortcut, {
shortcut: shortcut
})), children && (0,external_wp_element_namespaceObject.createElement)(TooltipReference, extends_extends({}, tooltip, children.props, {
// @ts-ignore If ref doesn't exist that's fine with us, it'll just be undefined, but it can exist on ReactElement and there's no reason to try to scope this (it'll just overcomplicate things)
ref: children === null || children === void 0 ? void 0 : children.ref
}), referenceProps => {
if (!focusable) {
referenceProps.tabIndex = undefined;
}
return (0,external_wp_element_namespaceObject.cloneElement)(children, referenceProps);
}));
}
/**
* `Tooltip` is a component that provides context for a user interface element.
*
* @example
* ```jsx
* import { Tooltip, Text } from `@wordpress/components/ui`;
*
* function Example() {
* return (
* <Tooltip content="Code is Poetry">
* <Text>WordPress.org</Text>
* </Tooltip>
* )
* }
* ```
*/
const ConnectedTooltip = contextConnect(component_Tooltip, 'Tooltip');
/* harmony default export */ var tooltip_component = (ConnectedTooltip);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-picker/color-copy-button.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const ColorCopyButton = props => {
const {
color,
colorType
} = props;
const [copiedColor, setCopiedColor] = (0,external_wp_element_namespaceObject.useState)(null);
const copyTimer = (0,external_wp_element_namespaceObject.useRef)();
const copyRef = (0,external_wp_compose_namespaceObject.useCopyToClipboard)(() => {
switch (colorType) {
case 'hsl':
{
return color.toHslString();
}
case 'rgb':
{
return color.toRgbString();
}
default:
case 'hex':
{
return color.toHex();
}
}
}, () => {
if (copyTimer.current) {
clearTimeout(copyTimer.current);
}
setCopiedColor(color.toHex());
copyTimer.current = setTimeout(() => {
setCopiedColor(null);
copyTimer.current = undefined;
}, 3000);
});
(0,external_wp_element_namespaceObject.useEffect)(() => {
// Clear copyTimer on component unmount.
return () => {
if (copyTimer.current) {
clearTimeout(copyTimer.current);
}
};
}, []);
return (0,external_wp_element_namespaceObject.createElement)(tooltip_component, {
content: (0,external_wp_element_namespaceObject.createElement)(text_component, {
color: "white"
}, copiedColor === color.toHex() ? (0,external_wp_i18n_namespaceObject.__)('Copied!') : (0,external_wp_i18n_namespaceObject.__)('Copy')),
placement: "bottom"
}, (0,external_wp_element_namespaceObject.createElement)(CopyButton, {
isSmall: true,
ref: copyRef,
icon: library_copy,
showTooltip: false
}));
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-picker/input-with-slider.js
/**
* Internal dependencies
*/
const InputWithSlider = _ref => {
let {
min,
max,
label,
abbreviation,
onChange,
value
} = _ref;
const onNumberControlChange = newValue => {
if (!newValue) {
onChange(0);
return;
}
if (typeof newValue === 'string') {
onChange(parseInt(newValue, 10));
return;
}
onChange(newValue);
};
return (0,external_wp_element_namespaceObject.createElement)(h_stack_component, {
spacing: 4
}, (0,external_wp_element_namespaceObject.createElement)(NumberControlWrapper, {
min: min,
max: max,
label: label,
hideLabelFromVision: true,
value: value,
onChange: onNumberControlChange,
prefix: (0,external_wp_element_namespaceObject.createElement)(spacer_component, {
as: text_component,
paddingLeft: space(4),
color: COLORS.ui.theme,
lineHeight: 1
}, abbreviation),
spinControls: "none",
size: "__unstable-large"
}), (0,external_wp_element_namespaceObject.createElement)(styles_RangeControl, {
__nextHasNoMarginBottom: true,
label: label,
hideLabelFromVision: true,
min: min,
max: max,
value: value // @ts-expect-error
// See: https://github.com/WordPress/gutenberg/pull/40535#issuecomment-1172418185
,
onChange: onChange,
withInputField: false
}));
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-picker/rgb-input.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const RgbInput = _ref => {
let {
color,
onChange,
enableAlpha
} = _ref;
const {
r,
g,
b,
a
} = color.toRgb();
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(InputWithSlider, {
min: 0,
max: 255,
label: "Red",
abbreviation: "R",
value: r,
onChange: nextR => onChange(colord_w({
r: nextR,
g,
b,
a
}))
}), (0,external_wp_element_namespaceObject.createElement)(InputWithSlider, {
min: 0,
max: 255,
label: "Green",
abbreviation: "G",
value: g,
onChange: nextG => onChange(colord_w({
r,
g: nextG,
b,
a
}))
}), (0,external_wp_element_namespaceObject.createElement)(InputWithSlider, {
min: 0,
max: 255,
label: "Blue",
abbreviation: "B",
value: b,
onChange: nextB => onChange(colord_w({
r,
g,
b: nextB,
a
}))
}), enableAlpha && (0,external_wp_element_namespaceObject.createElement)(InputWithSlider, {
min: 0,
max: 100,
label: "Alpha",
abbreviation: "A",
value: Math.trunc(a * 100),
onChange: nextA => onChange(colord_w({
r,
g,
b,
a: nextA / 100
}))
}));
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-picker/hsl-input.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const HslInput = _ref => {
let {
color,
onChange,
enableAlpha
} = _ref;
const {
h,
s,
l,
a
} = color.toHsl();
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(InputWithSlider, {
min: 0,
max: 359,
label: "Hue",
abbreviation: "H",
value: h,
onChange: nextH => {
onChange(colord_w({
h: nextH,
s,
l,
a
}));
}
}), (0,external_wp_element_namespaceObject.createElement)(InputWithSlider, {
min: 0,
max: 100,
label: "Saturation",
abbreviation: "S",
value: s,
onChange: nextS => {
onChange(colord_w({
h,
s: nextS,
l,
a
}));
}
}), (0,external_wp_element_namespaceObject.createElement)(InputWithSlider, {
min: 0,
max: 100,
label: "Lightness",
abbreviation: "L",
value: l,
onChange: nextL => {
onChange(colord_w({
h,
s,
l: nextL,
a
}));
}
}), enableAlpha && (0,external_wp_element_namespaceObject.createElement)(InputWithSlider, {
min: 0,
max: 100,
label: "Alpha",
abbreviation: "A",
value: Math.trunc(100 * a),
onChange: nextA => {
onChange(colord_w({
h,
s,
l,
a: nextA / 100
}));
}
}));
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-picker/hex-input.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const HexInput = _ref => {
let {
color,
onChange,
enableAlpha
} = _ref;
const handleChange = nextValue => {
if (!nextValue) return;
const hexValue = nextValue.startsWith('#') ? nextValue : '#' + nextValue;
onChange(colord_w(hexValue));
};
const stateReducer = (state, action) => {
var _action$payload, _action$payload$event, _state$value, _state$value2;
const nativeEvent = (_action$payload = action.payload) === null || _action$payload === void 0 ? void 0 : (_action$payload$event = _action$payload.event) === null || _action$payload$event === void 0 ? void 0 : _action$payload$event.nativeEvent;
if ('insertFromPaste' !== (nativeEvent === null || nativeEvent === void 0 ? void 0 : nativeEvent.inputType)) {
return { ...state
};
}
const value = (_state$value = state.value) !== null && _state$value !== void 0 && _state$value.startsWith('#') ? state.value.slice(1).toUpperCase() : (_state$value2 = state.value) === null || _state$value2 === void 0 ? void 0 : _state$value2.toUpperCase();
return { ...state,
value
};
};
return (0,external_wp_element_namespaceObject.createElement)(InputControl, {
prefix: (0,external_wp_element_namespaceObject.createElement)(spacer_component, {
as: text_component,
marginLeft: space(4),
color: COLORS.ui.theme,
lineHeight: 1
}, "#"),
value: color.toHex().slice(1).toUpperCase(),
onChange: handleChange,
maxLength: enableAlpha ? 9 : 7,
label: (0,external_wp_i18n_namespaceObject.__)('Hex color'),
hideLabelFromVision: true,
size: "__unstable-large",
__unstableStateReducer: stateReducer,
__unstableInputWidth: "9em"
});
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-picker/color-input.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const ColorInput = _ref => {
let {
colorType,
color,
onChange,
enableAlpha
} = _ref;
const props = {
color,
onChange,
enableAlpha
};
switch (colorType) {
case 'hsl':
return (0,external_wp_element_namespaceObject.createElement)(HslInput, props);
case 'rgb':
return (0,external_wp_element_namespaceObject.createElement)(RgbInput, props);
default:
case 'hex':
return (0,external_wp_element_namespaceObject.createElement)(HexInput, props);
}
};
;// CONCATENATED MODULE: ./node_modules/react-colorful/dist/index.mjs
function dist_u(){return(dist_u=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e}).apply(this,arguments)}function dist_c(e,r){if(null==e)return{};var t,n,o={},a=Object.keys(e);for(n=0;n<a.length;n++)r.indexOf(t=a[n])>=0||(o[t]=e[t]);return o}function dist_i(e){var t=(0,external_React_.useRef)(e),n=(0,external_React_.useRef)(function(e){t.current&&t.current(e)});return t.current=e,n.current}var dist_s=function(e,r,t){return void 0===r&&(r=0),void 0===t&&(t=1),e>t?t:e<r?r:e},dist_f=function(e){return"touches"in e},dist_v=function(e){return e&&e.ownerDocument.defaultView||self},dist_d=function(e,r,t){var n=e.getBoundingClientRect(),o=dist_f(r)?function(e,r){for(var t=0;t<e.length;t++)if(e[t].identifier===r)return e[t];return e[0]}(r.touches,t):r;return{left:dist_s((o.pageX-(n.left+dist_v(e).pageXOffset))/n.width),top:dist_s((o.pageY-(n.top+dist_v(e).pageYOffset))/n.height)}},dist_h=function(e){!dist_f(e)&&e.preventDefault()},dist_m=external_React_.memo(function(o){var a=o.onMove,l=o.onKey,s=dist_c(o,["onMove","onKey"]),m=(0,external_React_.useRef)(null),g=dist_i(a),p=dist_i(l),b=(0,external_React_.useRef)(null),_=(0,external_React_.useRef)(!1),x=(0,external_React_.useMemo)(function(){var e=function(e){dist_h(e),(dist_f(e)?e.touches.length>0:e.buttons>0)&&m.current?g(dist_d(m.current,e,b.current)):t(!1)},r=function(){return t(!1)};function t(t){var n=_.current,o=dist_v(m.current),a=t?o.addEventListener:o.removeEventListener;a(n?"touchmove":"mousemove",e),a(n?"touchend":"mouseup",r)}return[function(e){var r=e.nativeEvent,n=m.current;if(n&&(dist_h(r),!function(e,r){return r&&!dist_f(e)}(r,_.current)&&n)){if(dist_f(r)){_.current=!0;var o=r.changedTouches||[];o.length&&(b.current=o[0].identifier)}n.focus(),g(dist_d(n,r,b.current)),t(!0)}},function(e){var r=e.which||e.keyCode;r<37||r>40||(e.preventDefault(),p({left:39===r?.05:37===r?-.05:0,top:40===r?.05:38===r?-.05:0}))},t]},[p,g]),C=x[0],E=x[1],H=x[2];return (0,external_React_.useEffect)(function(){return H},[H]),external_React_.createElement("div",dist_u({},s,{onTouchStart:C,onMouseDown:C,className:"react-colorful__interactive",ref:m,onKeyDown:E,tabIndex:0,role:"slider"}))}),dist_g=function(e){return e.filter(Boolean).join(" ")},dist_p=function(r){var t=r.color,n=r.left,o=r.top,a=void 0===o?.5:o,l=dist_g(["react-colorful__pointer",r.className]);return external_React_.createElement("div",{className:l,style:{top:100*a+"%",left:100*n+"%"}},external_React_.createElement("div",{className:"react-colorful__pointer-fill",style:{backgroundColor:t}}))},dist_b=function(e,r,t){return void 0===r&&(r=0),void 0===t&&(t=Math.pow(10,r)),Math.round(t*e)/t},_={grad:.9,turn:360,rad:360/(2*Math.PI)},dist_x=function(e){return L(C(e))},C=function(e){return"#"===e[0]&&(e=e.substring(1)),e.length<6?{r:parseInt(e[0]+e[0],16),g:parseInt(e[1]+e[1],16),b:parseInt(e[2]+e[2],16),a:4===e.length?dist_b(parseInt(e[3]+e[3],16)/255,2):1}:{r:parseInt(e.substring(0,2),16),g:parseInt(e.substring(2,4),16),b:parseInt(e.substring(4,6),16),a:8===e.length?dist_b(parseInt(e.substring(6,8),16)/255,2):1}},dist_E=function(e,r){return void 0===r&&(r="deg"),Number(e)*(_[r]||1)},dist_H=function(e){var r=/hsla?\(?\s*(-?\d*\.?\d+)(deg|rad|grad|turn)?[,\s]+(-?\d*\.?\d+)%?[,\s]+(-?\d*\.?\d+)%?,?\s*[/\s]*(-?\d*\.?\d+)?(%)?\s*\)?/i.exec(e);return r?dist_N({h:dist_E(r[1],r[2]),s:Number(r[3]),l:Number(r[4]),a:void 0===r[5]?1:Number(r[5])/(r[6]?100:1)}):{h:0,s:0,v:0,a:1}},dist_M=dist_H,dist_N=function(e){var r=e.s,t=e.l;return{h:e.h,s:(r*=(t<50?t:100-t)/100)>0?2*r/(t+r)*100:0,v:t+r,a:e.a}},dist_w=function(e){return K(dist_I(e))},dist_y=function(e){var r=e.s,t=e.v,n=e.a,o=(200-r)*t/100;return{h:dist_b(e.h),s:dist_b(o>0&&o<200?r*t/100/(o<=100?o:200-o)*100:0),l:dist_b(o/2),a:dist_b(n,2)}},q=function(e){var r=dist_y(e);return"hsl("+r.h+", "+r.s+"%, "+r.l+"%)"},dist_k=function(e){var r=dist_y(e);return"hsla("+r.h+", "+r.s+"%, "+r.l+"%, "+r.a+")"},dist_I=function(e){var r=e.h,t=e.s,n=e.v,o=e.a;r=r/360*6,t/=100,n/=100;var a=Math.floor(r),l=n*(1-t),u=n*(1-(r-a)*t),c=n*(1-(1-r+a)*t),i=a%6;return{r:dist_b(255*[n,u,l,l,c,n][i]),g:dist_b(255*[c,n,n,u,l,l][i]),b:dist_b(255*[l,l,c,n,n,u][i]),a:dist_b(o,2)}},dist_O=function(e){var r=/hsva?\(?\s*(-?\d*\.?\d+)(deg|rad|grad|turn)?[,\s]+(-?\d*\.?\d+)%?[,\s]+(-?\d*\.?\d+)%?,?\s*[/\s]*(-?\d*\.?\d+)?(%)?\s*\)?/i.exec(e);return r?A({h:dist_E(r[1],r[2]),s:Number(r[3]),v:Number(r[4]),a:void 0===r[5]?1:Number(r[5])/(r[6]?100:1)}):{h:0,s:0,v:0,a:1}},dist_j=dist_O,z=function(e){var r=/rgba?\(?\s*(-?\d*\.?\d+)(%)?[,\s]+(-?\d*\.?\d+)(%)?[,\s]+(-?\d*\.?\d+)(%)?,?\s*[/\s]*(-?\d*\.?\d+)?(%)?\s*\)?/i.exec(e);return r?L({r:Number(r[1])/(r[2]?100/255:1),g:Number(r[3])/(r[4]?100/255:1),b:Number(r[5])/(r[6]?100/255:1),a:void 0===r[7]?1:Number(r[7])/(r[8]?100:1)}):{h:0,s:0,v:0,a:1}},B=z,D=function(e){var r=e.toString(16);return r.length<2?"0"+r:r},K=function(e){var r=e.r,t=e.g,n=e.b,o=e.a,a=o<1?D(dist_b(255*o)):"";return"#"+D(r)+D(t)+D(n)+a},L=function(e){var r=e.r,t=e.g,n=e.b,o=e.a,a=Math.max(r,t,n),l=a-Math.min(r,t,n),u=l?a===r?(t-n)/l:a===t?2+(n-r)/l:4+(r-t)/l:0;return{h:dist_b(60*(u<0?u+6:u)),s:dist_b(a?l/a*100:0),v:dist_b(a/255*100),a:o}},A=function(e){return{h:dist_b(e.h),s:dist_b(e.s),v:dist_b(e.v),a:dist_b(e.a,2)}},dist_S=external_React_.memo(function(r){var t=r.hue,n=r.onChange,o=dist_g(["react-colorful__hue",r.className]);return external_React_.createElement("div",{className:o},external_React_.createElement(dist_m,{onMove:function(e){n({h:360*e.left})},onKey:function(e){n({h:dist_s(t+360*e.left,0,360)})},"aria-label":"Hue","aria-valuenow":dist_b(t),"aria-valuemax":"360","aria-valuemin":"0"},external_React_.createElement(dist_p,{className:"react-colorful__hue-pointer",left:t/360,color:q({h:t,s:100,v:100,a:1})})))}),T=external_React_.memo(function(r){var t=r.hsva,n=r.onChange,o={backgroundColor:q({h:t.h,s:100,v:100,a:1})};return external_React_.createElement("div",{className:"react-colorful__saturation",style:o},external_React_.createElement(dist_m,{onMove:function(e){n({s:100*e.left,v:100-100*e.top})},onKey:function(e){n({s:dist_s(t.s+100*e.left,0,100),v:dist_s(t.v-100*e.top,0,100)})},"aria-label":"Color","aria-valuetext":"Saturation "+dist_b(t.s)+"%, Brightness "+dist_b(t.v)+"%"},external_React_.createElement(dist_p,{className:"react-colorful__saturation-pointer",top:1-t.v/100,left:t.s/100,color:q(t)})))}),F=function(e,r){if(e===r)return!0;for(var t in e)if(e[t]!==r[t])return!1;return!0},P=function(e,r){return e.replace(/\s/g,"")===r.replace(/\s/g,"")},X=function(e,r){return e.toLowerCase()===r.toLowerCase()||F(C(e),C(r))};function Y(e,t,l){var u=dist_i(l),c=(0,external_React_.useState)(function(){return e.toHsva(t)}),s=c[0],f=c[1],v=(0,external_React_.useRef)({color:t,hsva:s});(0,external_React_.useEffect)(function(){if(!e.equal(t,v.current.color)){var r=e.toHsva(t);v.current={hsva:r,color:t},f(r)}},[t,e]),(0,external_React_.useEffect)(function(){var r;F(s,v.current.hsva)||e.equal(r=e.fromHsva(s),v.current.color)||(v.current={hsva:s,color:r},u(r))},[s,e,u]);var d=(0,external_React_.useCallback)(function(e){f(function(r){return Object.assign({},r,e)})},[]);return[s,d]}var R,dist_V="undefined"!=typeof window?external_React_.useLayoutEffect:external_React_.useEffect,dist_$=function(){return R||( true?__webpack_require__.nc:0)},G=function(e){R=e},J=new Map,Q=function(e){dist_V(function(){var r=e.current?e.current.ownerDocument:document;if(void 0!==r&&!J.has(r)){var t=r.createElement("style");t.innerHTML='.react-colorful{position:relative;display:flex;flex-direction:column;width:200px;height:200px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:default}.react-colorful__saturation{position:relative;flex-grow:1;border-color:transparent;border-bottom:12px solid #000;border-radius:8px 8px 0 0;background-image:linear-gradient(0deg,#000,transparent),linear-gradient(90deg,#fff,hsla(0,0%,100%,0))}.react-colorful__alpha-gradient,.react-colorful__pointer-fill{content:"";position:absolute;left:0;top:0;right:0;bottom:0;pointer-events:none;border-radius:inherit}.react-colorful__alpha-gradient,.react-colorful__saturation{box-shadow:inset 0 0 0 1px rgba(0,0,0,.05)}.react-colorful__alpha,.react-colorful__hue{position:relative;height:24px}.react-colorful__hue{background:linear-gradient(90deg,red 0,#ff0 17%,#0f0 33%,#0ff 50%,#00f 67%,#f0f 83%,red)}.react-colorful__last-control{border-radius:0 0 8px 8px}.react-colorful__interactive{position:absolute;left:0;top:0;right:0;bottom:0;border-radius:inherit;outline:none;touch-action:none}.react-colorful__pointer{position:absolute;z-index:1;box-sizing:border-box;width:28px;height:28px;transform:translate(-50%,-50%);background-color:#fff;border:2px solid #fff;border-radius:50%;box-shadow:0 2px 4px rgba(0,0,0,.2)}.react-colorful__interactive:focus .react-colorful__pointer{transform:translate(-50%,-50%) scale(1.1)}.react-colorful__alpha,.react-colorful__alpha-pointer{background-color:#fff;background-image:url(\'data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill-opacity=".05"><path d="M8 0h8v8H8zM0 8h8v8H0z"/></svg>\')}.react-colorful__saturation-pointer{z-index:3}.react-colorful__hue-pointer{z-index:2}',J.set(r,t);var n=dist_$();n&&t.setAttribute("nonce",n),r.head.appendChild(t)}},[])},U=function(t){var n=t.className,o=t.colorModel,a=t.color,l=void 0===a?o.defaultColor:a,i=t.onChange,s=dist_c(t,["className","colorModel","color","onChange"]),f=(0,external_React_.useRef)(null);Q(f);var v=Y(o,l,i),d=v[0],h=v[1],m=dist_g(["react-colorful",n]);return external_React_.createElement("div",dist_u({},s,{ref:f,className:m}),external_React_.createElement(T,{hsva:d,onChange:h}),external_React_.createElement(dist_S,{hue:d.h,onChange:h,className:"react-colorful__last-control"}))},W={defaultColor:"000",toHsva:dist_x,fromHsva:function(e){return dist_w({h:e.h,s:e.s,v:e.v,a:1})},equal:X},Z=function(r){return e.createElement(U,dist_u({},r,{colorModel:W}))},ee=function(r){var t=r.className,n=r.hsva,o=r.onChange,a={backgroundImage:"linear-gradient(90deg, "+dist_k(Object.assign({},n,{a:0}))+", "+dist_k(Object.assign({},n,{a:1}))+")"},l=dist_g(["react-colorful__alpha",t]),u=dist_b(100*n.a);return external_React_.createElement("div",{className:l},external_React_.createElement("div",{className:"react-colorful__alpha-gradient",style:a}),external_React_.createElement(dist_m,{onMove:function(e){o({a:e.left})},onKey:function(e){o({a:dist_s(n.a+e.left)})},"aria-label":"Alpha","aria-valuetext":u+"%","aria-valuenow":u,"aria-valuemin":"0","aria-valuemax":"100"},external_React_.createElement(dist_p,{className:"react-colorful__alpha-pointer",left:n.a,color:dist_k(n)})))},re=function(t){var n=t.className,o=t.colorModel,a=t.color,l=void 0===a?o.defaultColor:a,i=t.onChange,s=dist_c(t,["className","colorModel","color","onChange"]),f=(0,external_React_.useRef)(null);Q(f);var v=Y(o,l,i),d=v[0],h=v[1],m=dist_g(["react-colorful",n]);return external_React_.createElement("div",dist_u({},s,{ref:f,className:m}),external_React_.createElement(T,{hsva:d,onChange:h}),external_React_.createElement(dist_S,{hue:d.h,onChange:h}),external_React_.createElement(ee,{hsva:d,onChange:h,className:"react-colorful__last-control"}))},te={defaultColor:"0001",toHsva:dist_x,fromHsva:dist_w,equal:X},ne=function(r){return e.createElement(re,dist_u({},r,{colorModel:te}))},oe={defaultColor:{h:0,s:0,l:0,a:1},toHsva:dist_N,fromHsva:dist_y,equal:F},ae=function(r){return e.createElement(re,dist_u({},r,{colorModel:oe}))},le={defaultColor:"hsla(0, 0%, 0%, 1)",toHsva:dist_H,fromHsva:dist_k,equal:P},ue=function(r){return e.createElement(re,dist_u({},r,{colorModel:le}))},ce={defaultColor:{h:0,s:0,l:0},toHsva:function(e){return dist_N({h:e.h,s:e.s,l:e.l,a:1})},fromHsva:function(e){return{h:(r=dist_y(e)).h,s:r.s,l:r.l};var r},equal:F},ie=function(r){return e.createElement(U,dist_u({},r,{colorModel:ce}))},se={defaultColor:"hsl(0, 0%, 0%)",toHsva:dist_M,fromHsva:q,equal:P},fe=function(r){return e.createElement(U,dist_u({},r,{colorModel:se}))},ve={defaultColor:{h:0,s:0,v:0,a:1},toHsva:function(e){return e},fromHsva:A,equal:F},de=function(r){return e.createElement(re,dist_u({},r,{colorModel:ve}))},he={defaultColor:"hsva(0, 0%, 0%, 1)",toHsva:dist_O,fromHsva:function(e){var r=A(e);return"hsva("+r.h+", "+r.s+"%, "+r.v+"%, "+r.a+")"},equal:P},me=function(r){return e.createElement(re,dist_u({},r,{colorModel:he}))},ge={defaultColor:{h:0,s:0,v:0},toHsva:function(e){return{h:e.h,s:e.s,v:e.v,a:1}},fromHsva:function(e){var r=A(e);return{h:r.h,s:r.s,v:r.v}},equal:F},pe=function(r){return e.createElement(U,dist_u({},r,{colorModel:ge}))},be={defaultColor:"hsv(0, 0%, 0%)",toHsva:dist_j,fromHsva:function(e){var r=A(e);return"hsv("+r.h+", "+r.s+"%, "+r.v+"%)"},equal:P},_e=function(r){return e.createElement(U,dist_u({},r,{colorModel:be}))},xe={defaultColor:{r:0,g:0,b:0,a:1},toHsva:L,fromHsva:dist_I,equal:F},Ce=function(r){return e.createElement(re,dist_u({},r,{colorModel:xe}))},Ee={defaultColor:"rgba(0, 0, 0, 1)",toHsva:z,fromHsva:function(e){var r=dist_I(e);return"rgba("+r.r+", "+r.g+", "+r.b+", "+r.a+")"},equal:P},He=function(r){return external_React_.createElement(re,dist_u({},r,{colorModel:Ee}))},Me={defaultColor:{r:0,g:0,b:0},toHsva:function(e){return L({r:e.r,g:e.g,b:e.b,a:1})},fromHsva:function(e){return{r:(r=dist_I(e)).r,g:r.g,b:r.b};var r},equal:F},Ne=function(r){return e.createElement(U,dist_u({},r,{colorModel:Me}))},we={defaultColor:"rgb(0, 0, 0)",toHsva:B,fromHsva:function(e){var r=dist_I(e);return"rgb("+r.r+", "+r.g+", "+r.b+")"},equal:P},ye=function(r){return external_React_.createElement(U,dist_u({},r,{colorModel:we}))},qe=/^#?([0-9A-F]{3,8})$/i,ke=function(r){var t=r.color,l=void 0===t?"":t,s=r.onChange,f=r.onBlur,v=r.escape,d=r.validate,h=r.format,m=r.process,g=dist_c(r,["color","onChange","onBlur","escape","validate","format","process"]),p=o(function(){return v(l)}),b=p[0],_=p[1],x=dist_i(s),C=dist_i(f),E=a(function(e){var r=v(e.target.value);_(r),d(r)&&x(m?m(r):r)},[v,m,d,x]),H=a(function(e){d(e.target.value)||_(v(l)),C(e)},[l,v,d,C]);return n(function(){_(v(l))},[l,v]),e.createElement("input",dist_u({},g,{value:h?h(b):b,spellCheck:"false",onChange:E,onBlur:H}))},Ie=function(e){return"#"+e},Oe=function(r){var t=r.prefixed,n=r.alpha,o=dist_c(r,["prefixed","alpha"]),l=a(function(e){return e.replace(/([^0-9A-F]+)/gi,"").substring(0,n?8:6)},[n]),i=a(function(e){return function(e,r){var t=qe.exec(e),n=t?t[1].length:0;return 3===n||6===n||!!r&&4===n||!!r&&8===n}(e,n)},[n]);return e.createElement(ke,dist_u({},o,{escape:l,format:t?Ie:void 0,process:Ie,validate:i}))};
//# sourceMappingURL=index.module.js.map
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-picker/picker.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
const Picker = _ref => {
let {
color,
enableAlpha,
onChange
} = _ref;
const Component = enableAlpha ? He : ye;
const rgbColor = (0,external_wp_element_namespaceObject.useMemo)(() => color.toRgbString(), [color]);
return (0,external_wp_element_namespaceObject.createElement)(Component, {
color: rgbColor,
onChange: nextColor => {
onChange(colord_w(nextColor));
}
});
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/hooks/use-controlled-value.js
/**
* WordPress dependencies
*/
/**
* Simplified and improved implementation of useControlledState.
*
* @param props
* @param props.defaultValue
* @param props.value
* @param props.onChange
* @return The controlled value and the value setter.
*/
function useControlledValue(_ref) {
let {
defaultValue,
onChange,
value: valueProp
} = _ref;
const hasValue = typeof valueProp !== 'undefined';
const initialValue = hasValue ? valueProp : defaultValue;
const [state, setState] = (0,external_wp_element_namespaceObject.useState)(initialValue);
const value = hasValue ? valueProp : state;
let setValue;
if (hasValue && typeof onChange === 'function') {
setValue = onChange;
} else if (!hasValue && typeof onChange === 'function') {
setValue = nextValue => {
onChange(nextValue);
setState(nextValue);
};
} else {
setValue = setState;
}
return [value, setValue];
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-picker/component.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
k([names]);
const options = [{
label: 'RGB',
value: 'rgb'
}, {
label: 'HSL',
value: 'hsl'
}, {
label: 'Hex',
value: 'hex'
}];
const ColorPicker = (props, forwardedRef) => {
const {
enableAlpha = false,
color: colorProp,
onChange,
defaultValue = '#fff',
copyFormat,
...divProps
} = useContextSystem(props, 'ColorPicker'); // Use a safe default value for the color and remove the possibility of `undefined`.
const [color, setColor] = useControlledValue({
onChange,
value: colorProp,
defaultValue
});
const safeColordColor = (0,external_wp_element_namespaceObject.useMemo)(() => {
return colord_w(color || '');
}, [color]);
const debouncedSetColor = (0,external_wp_compose_namespaceObject.useDebounce)(setColor);
const handleChange = (0,external_wp_element_namespaceObject.useCallback)(nextValue => {
debouncedSetColor(nextValue.toHex());
}, [debouncedSetColor]);
const [colorType, setColorType] = (0,external_wp_element_namespaceObject.useState)(copyFormat || 'hex');
return (0,external_wp_element_namespaceObject.createElement)(ColorfulWrapper, extends_extends({
ref: forwardedRef
}, divProps), (0,external_wp_element_namespaceObject.createElement)(Picker, {
onChange: handleChange,
color: safeColordColor,
enableAlpha: enableAlpha
}), (0,external_wp_element_namespaceObject.createElement)(AuxiliaryColorArtefactWrapper, null, (0,external_wp_element_namespaceObject.createElement)(AuxiliaryColorArtefactHStackHeader, {
justify: "space-between"
}, (0,external_wp_element_namespaceObject.createElement)(styles_SelectControl, {
__nextHasNoMarginBottom: true,
options: options,
value: colorType,
onChange: nextColorType => setColorType(nextColorType),
label: (0,external_wp_i18n_namespaceObject.__)('Color format'),
hideLabelFromVision: true
}), (0,external_wp_element_namespaceObject.createElement)(ColorCopyButton, {
color: safeColordColor,
colorType: copyFormat || colorType
})), (0,external_wp_element_namespaceObject.createElement)(ColorInputWrapper, {
direction: "column",
gap: 2
}, (0,external_wp_element_namespaceObject.createElement)(ColorInput, {
colorType: colorType,
color: safeColordColor,
onChange: handleChange,
enableAlpha: enableAlpha
}))));
};
const ConnectedColorPicker = contextConnect(ColorPicker, 'ColorPicker');
/* harmony default export */ var color_picker_component = (ConnectedColorPicker);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-picker/use-deprecated-props.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function isLegacyProps(props) {
var _props$color;
return typeof props.onChangeComplete !== 'undefined' || typeof props.disableAlpha !== 'undefined' || typeof ((_props$color = props.color) === null || _props$color === void 0 ? void 0 : _props$color.hex) === 'string';
}
function getColorFromLegacyProps(color) {
if (color === undefined) return;
if (typeof color === 'string') return color;
if (color.hex) return color.hex;
return undefined;
}
const transformColorStringToLegacyColor = memize_default()(color => {
const colordColor = colord_w(color);
const hex = colordColor.toHex();
const rgb = colordColor.toRgb();
const hsv = colordColor.toHsv();
const hsl = colordColor.toHsl();
return {
hex,
rgb,
hsv,
hsl,
source: 'hex',
oldHue: hsl.h
};
});
function use_deprecated_props_useDeprecatedProps(props) {
const {
onChangeComplete
} = props;
const legacyChangeHandler = (0,external_wp_element_namespaceObject.useCallback)(color => {
onChangeComplete(transformColorStringToLegacyColor(color));
}, [onChangeComplete]);
if (isLegacyProps(props)) {
return {
color: getColorFromLegacyProps(props.color),
enableAlpha: !props.disableAlpha,
onChange: legacyChangeHandler
};
}
return { ...props,
color: props.color,
enableAlpha: props.enableAlpha,
onChange: props.onChange
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-picker/legacy-adapter.js
/**
* Internal dependencies
*/
const LegacyAdapter = props => {
return (0,external_wp_element_namespaceObject.createElement)(color_picker_component, use_deprecated_props_useDeprecatedProps(props));
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/check.js
/**
* WordPress dependencies
*/
const check = (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: "M16.7 7.1l-6.3 8.5-3.3-2.5-.9 1.2 4.5 3.4L17.9 8z"
}));
/* harmony default export */ var library_check = (check);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/circular-option-picker/index.js
// @ts-nocheck
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function Option(props) {
const {
className,
isSelected,
selectedIconProps,
tooltipText,
...additionalProps
} = props;
const optionButton = (0,external_wp_element_namespaceObject.createElement)(build_module_button, extends_extends({
isPressed: isSelected,
className: "components-circular-option-picker__option"
}, additionalProps));
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()(className, 'components-circular-option-picker__option-wrapper')
}, tooltipText ? (0,external_wp_element_namespaceObject.createElement)(tooltip, {
text: tooltipText
}, optionButton) : optionButton, isSelected && (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, extends_extends({
icon: library_check
}, selectedIconProps ? selectedIconProps : {})));
}
function DropdownLinkAction(props) {
const {
buttonProps,
className,
dropdownProps,
linkText
} = props;
return (0,external_wp_element_namespaceObject.createElement)(dropdown, extends_extends({
className: classnames_default()('components-circular-option-picker__dropdown-link-action', className),
renderToggle: _ref => {
let {
isOpen,
onToggle
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(build_module_button, extends_extends({
"aria-expanded": isOpen,
"aria-haspopup": "true",
onClick: onToggle,
variant: "link"
}, buttonProps), linkText);
}
}, dropdownProps));
}
function ButtonAction(props) {
const {
className,
children,
...additionalProps
} = props;
return (0,external_wp_element_namespaceObject.createElement)(build_module_button, extends_extends({
className: classnames_default()('components-circular-option-picker__clear', className),
variant: "tertiary"
}, additionalProps), children);
}
function CircularOptionPicker(props) {
const {
actions,
className,
options,
children
} = props;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('components-circular-option-picker', className)
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-circular-option-picker__swatches"
}, options), children, actions && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-circular-option-picker__custom-clear-wrapper"
}, actions));
}
CircularOptionPicker.Option = Option;
CircularOptionPicker.ButtonAction = ButtonAction;
CircularOptionPicker.DropdownLinkAction = DropdownLinkAction;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/v-stack/hook.js
/**
* Internal dependencies
*/
function useVStack(props) {
const {
expanded = false,
...otherProps
} = useContextSystem(props, 'VStack');
const hStackProps = useHStack({
direction: 'column',
expanded,
...otherProps
});
return hStackProps;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/v-stack/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedVStack(props, forwardedRef) {
const vStackProps = useVStack(props);
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({}, vStackProps, {
ref: forwardedRef
}));
}
/**
* `VStack` (or Vertical Stack) is a layout component that arranges child
* elements in a vertical line.
*
* `VStack` can render anything inside.
*
* ```jsx
* import {
* __experimentalText as Text,
* __experimentalVStack as VStack,
* } from `@wordpress/components`;
*
* function Example() {
* return (
* <VStack>
* <Text>Code</Text>
* <Text>is</Text>
* <Text>Poetry</Text>
* </VStack>
* );
* }
* ```
*/
const VStack = contextConnect(UnconnectedVStack, 'VStack');
/* harmony default export */ var v_stack_component = (VStack);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/truncate/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedTruncate(props, forwardedRef) {
const truncateProps = useTruncate(props);
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({
as: "span"
}, truncateProps, {
ref: forwardedRef
}));
}
/**
* `Truncate` is a typography primitive that trims text content.
* For almost all cases, it is recommended that `Text`, `Heading`, or
* `Subheading` is used to render text content. However,`Truncate` is
* available for custom implementations.
*
* ```jsx
* import { __experimentalTruncate as Truncate } from `@wordpress/components`;
*
* function Example() {
* return (
* <Truncate>
* Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc ex
* neque, vulputate a diam et, luctus convallis lacus. Vestibulum ac
* mollis mi. Morbi id elementum massa.
* </Truncate>
* );
* }
* ```
*/
const component_Truncate = contextConnect(UnconnectedTruncate, 'Truncate');
/* harmony default export */ var truncate_component = (component_Truncate);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/heading/hook.js
/**
* Internal dependencies
*/
function useHeading(props) {
const {
as: asProp,
level = 2,
...otherProps
} = useContextSystem(props, 'Heading');
const as = asProp || `h${level}`;
const a11yProps = {};
if (typeof as === 'string' && as[0] !== 'h') {
// If not a semantic `h` element, add a11y props:
a11yProps.role = 'heading';
a11yProps['aria-level'] = typeof level === 'string' ? parseInt(level) : level;
}
const textProps = useText({
color: COLORS.gray[900],
size: getHeadingFontSize(level),
isBlock: true,
weight: config_values.fontWeightHeading,
...otherProps
});
return { ...textProps,
...a11yProps,
as
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/heading/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedHeading(props, forwardedRef) {
const headerProps = useHeading(props);
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({}, headerProps, {
ref: forwardedRef
}));
}
/**
* `Heading` renders headings and titles using the library's typography system.
*
* ```jsx
* import { __experimentalHeading as Heading } from "@wordpress/components";
*
* function Example() {
* return <Heading>Code is Poetry</Heading>;
* }
* ```
*/
const Heading = contextConnect(UnconnectedHeading, 'Heading');
/* harmony default export */ var heading_component = (Heading);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-palette/styles.js
function color_palette_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const ColorHeading = /*#__PURE__*/createStyled(heading_component, true ? {
target: "ev9wop70"
} : 0)( true ? {
name: "13lxv2o",
styles: "text-transform:uppercase;line-height:24px;font-weight:500;&&&{font-size:11px;margin-bottom:0;}"
} : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/dropdown/styles.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const padding = _ref => {
let {
paddingSize = 'small'
} = _ref;
if (paddingSize === 'none') return;
const paddingValues = {
small: space(2),
medium: space(4)
};
return /*#__PURE__*/emotion_react_browser_esm_css("padding:", paddingValues[paddingSize] || paddingValues.small, ";" + ( true ? "" : 0), true ? "" : 0);
};
const DropdownContentWrapperDiv = createStyled("div", true ? {
target: "eovvns30"
} : 0)("margin-left:", space(-2), ";margin-right:", space(-2), ";&:first-of-type{margin-top:", space(-2), ";}&:last-of-type{margin-bottom:", space(-2), ";}", padding, ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/dropdown/dropdown-content-wrapper.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedDropdownContentWrapper(props, forwardedRef) {
const {
paddingSize = 'small',
...derivedProps
} = useContextSystem(props, 'DropdownContentWrapper');
return (0,external_wp_element_namespaceObject.createElement)(DropdownContentWrapperDiv, extends_extends({}, derivedProps, {
paddingSize: paddingSize,
ref: forwardedRef
}));
}
/**
* A convenience wrapper for the `renderContent` when you want to apply
* different padding. (Default is `paddingSize="small"`).
*
* ```jsx
* import {
* Dropdown,
* __experimentalDropdownContentWrapper as DropdownContentWrapper,
* } from '@wordpress/components';
*
* <Dropdown
* renderContent={ () => (
* <DropdownContentWrapper paddingSize="medium">
* My dropdown content
* </DropdownContentWrapper>
* ) }
* />
* ```
*/
const DropdownContentWrapper = contextConnect(UnconnectedDropdownContentWrapper, 'DropdownContentWrapper');
/* harmony default export */ var dropdown_content_wrapper = (DropdownContentWrapper);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-palette/utils.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
k([names, a11y]);
const extractColorNameFromCurrentValue = function (currentValue) {
let colors = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
let showMultiplePalettes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (!currentValue) {
return '';
}
const currentValueIsCssVariable = /^var\(/.test(currentValue);
const normalizedCurrentValue = currentValueIsCssVariable ? currentValue : colord_w(currentValue).toHex(); // Normalize format of `colors` to simplify the following loop
const colorPalettes = showMultiplePalettes ? colors : [{
colors: colors
}];
for (const {
colors: paletteColors
} of colorPalettes) {
for (const {
name: colorName,
color: colorValue
} of paletteColors) {
const normalizedColorValue = currentValueIsCssVariable ? colorValue : colord_w(colorValue).toHex();
if (normalizedCurrentValue === normalizedColorValue) {
return colorName;
}
}
} // translators: shown when the user has picked a custom color (i.e not in the palette of colors).
return (0,external_wp_i18n_namespaceObject.__)('Custom');
};
const showTransparentBackground = currentValue => {
if (typeof currentValue === 'undefined') {
return true;
}
return colord_w(currentValue).alpha() === 0;
}; // The PaletteObject type has a `colors` property (an array of ColorObject),
// while the ColorObject type has a `color` property (the CSS color value).
const isMultiplePaletteObject = obj => Array.isArray(obj.colors) && !('color' in obj);
const isMultiplePaletteArray = arr => {
return arr.length > 0 && arr.every(colorObj => isMultiplePaletteObject(colorObj));
};
/**
* Transform a CSS variable used as background color into the color value itself.
*
* @param value The color value that may be a CSS variable.
* @param element The element for which to get the computed style.
* @return The background color value computed from a element.
*/
const normalizeColorValue = (value, element) => {
const currentValueIsCssVariable = /^var\(/.test(value !== null && value !== void 0 ? value : '');
if (!currentValueIsCssVariable || element === null) {
return value;
}
const {
ownerDocument
} = element;
const {
defaultView
} = ownerDocument;
const computedBackgroundColor = defaultView === null || defaultView === void 0 ? void 0 : defaultView.getComputedStyle(element).backgroundColor;
return computedBackgroundColor ? colord_w(computedBackgroundColor).toHex() : value;
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-palette/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
k([names, a11y]);
function SinglePalette(_ref) {
let {
className,
clearColor,
colors,
onChange,
value,
actions
} = _ref;
const colorOptions = (0,external_wp_element_namespaceObject.useMemo)(() => {
return colors.map((_ref2, index) => {
let {
color,
name
} = _ref2;
const colordColor = colord_w(color);
const isSelected = value === color;
return (0,external_wp_element_namespaceObject.createElement)(CircularOptionPicker.Option, {
key: `${color}-${index}`,
isSelected: isSelected,
selectedIconProps: isSelected ? {
fill: colordColor.contrast() > colordColor.contrast('#000') ? '#fff' : '#000'
} : {},
tooltipText: name || // translators: %s: color hex code e.g: "#f00".
(0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('Color code: %s'), color),
style: {
backgroundColor: color,
color
},
onClick: isSelected ? clearColor : () => onChange(color, index),
"aria-label": name ? // translators: %s: The name of the color e.g: "vivid red".
(0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('Color: %s'), name) : // translators: %s: color hex code e.g: "#f00".
(0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('Color code: %s'), color)
});
});
}, [colors, value, onChange, clearColor]);
return (0,external_wp_element_namespaceObject.createElement)(CircularOptionPicker, {
className: className,
options: colorOptions,
actions: actions
});
}
function MultiplePalettes(_ref3) {
let {
className,
clearColor,
colors,
onChange,
value,
actions
} = _ref3;
if (colors.length === 0) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
spacing: 3,
className: className
}, colors.map((_ref4, index) => {
let {
name,
colors: colorPalette
} = _ref4;
return (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
spacing: 2,
key: index
}, (0,external_wp_element_namespaceObject.createElement)(ColorHeading, null, name), (0,external_wp_element_namespaceObject.createElement)(SinglePalette, {
clearColor: clearColor,
colors: colorPalette,
onChange: newColor => onChange(newColor, index),
value: value,
actions: colors.length === index + 1 ? actions : null
}));
}));
}
function CustomColorPickerDropdown(_ref5) {
let {
isRenderedInSidebar,
popoverProps: receivedPopoverProps,
...props
} = _ref5;
const popoverProps = (0,external_wp_element_namespaceObject.useMemo)(() => ({
shift: true,
...(isRenderedInSidebar ? {
// When in the sidebar: open to the left (stacking),
// leaving the same gap as the parent popover.
placement: 'left-start',
offset: 34
} : {
// Default behavior: open below the anchor
placement: 'bottom',
offset: 8
}),
...receivedPopoverProps
}), [isRenderedInSidebar, receivedPopoverProps]);
return (0,external_wp_element_namespaceObject.createElement)(dropdown, extends_extends({
contentClassName: "components-color-palette__custom-color-dropdown-content",
popoverProps: popoverProps
}, props));
}
function UnforwardedColorPalette(props, forwardedRef) {
const {
clearable = true,
colors = [],
disableCustomColors = false,
enableAlpha = false,
onChange,
value,
__experimentalIsRenderedInSidebar = false,
...otherProps
} = props;
const [normalizedColorValue, setNormalizedColorValue] = (0,external_wp_element_namespaceObject.useState)(value);
const clearColor = (0,external_wp_element_namespaceObject.useCallback)(() => onChange(undefined), [onChange]);
const customColorPaletteCallbackRef = (0,external_wp_element_namespaceObject.useCallback)(node => {
setNormalizedColorValue(normalizeColorValue(value, node));
}, [value]);
const hasMultipleColorOrigins = isMultiplePaletteArray(colors);
const buttonLabelName = (0,external_wp_element_namespaceObject.useMemo)(() => extractColorNameFromCurrentValue(value, colors, hasMultipleColorOrigins), [value, colors, hasMultipleColorOrigins]);
const renderCustomColorPicker = () => (0,external_wp_element_namespaceObject.createElement)(dropdown_content_wrapper, {
paddingSize: "none"
}, (0,external_wp_element_namespaceObject.createElement)(LegacyAdapter, {
color: normalizedColorValue,
onChange: color => onChange(color),
enableAlpha: enableAlpha
}));
const colordColor = colord_w(normalizedColorValue !== null && normalizedColorValue !== void 0 ? normalizedColorValue : '');
const valueWithoutLeadingHash = value !== null && value !== void 0 && value.startsWith('#') ? value.substring(1) : value !== null && value !== void 0 ? value : '';
const customColorAccessibleLabel = !!valueWithoutLeadingHash ? (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %1$s: The name of the color e.g: "vivid red". %2$s: The color's hex code e.g: "#f00".
(0,external_wp_i18n_namespaceObject.__)('Custom color picker. The currently selected color is called "%1$s" and has a value of "%2$s".'), buttonLabelName, valueWithoutLeadingHash) : (0,external_wp_i18n_namespaceObject.__)('Custom color picker.');
const paletteCommonProps = {
clearable,
clearColor,
onChange,
value,
actions: !!clearable && (0,external_wp_element_namespaceObject.createElement)(CircularOptionPicker.ButtonAction, {
onClick: clearColor
}, (0,external_wp_i18n_namespaceObject.__)('Clear'))
};
return (0,external_wp_element_namespaceObject.createElement)(v_stack_component, extends_extends({
spacing: 3,
ref: forwardedRef
}, otherProps), !disableCustomColors && (0,external_wp_element_namespaceObject.createElement)(CustomColorPickerDropdown, {
isRenderedInSidebar: __experimentalIsRenderedInSidebar,
renderContent: renderCustomColorPicker,
renderToggle: _ref6 => {
let {
isOpen,
onToggle
} = _ref6;
return (0,external_wp_element_namespaceObject.createElement)(flex_component, {
as: 'button',
ref: customColorPaletteCallbackRef,
justify: "space-between",
align: "flex-start",
className: "components-color-palette__custom-color",
"aria-expanded": isOpen,
"aria-haspopup": "true",
onClick: onToggle,
"aria-label": customColorAccessibleLabel,
style: showTransparentBackground(value) ? {
color: '#000'
} : {
background: value,
color: colordColor.contrast() > colordColor.contrast('#000') ? '#fff' : '#000'
}
}, (0,external_wp_element_namespaceObject.createElement)(flex_item_component, {
isBlock: true,
as: truncate_component,
className: "components-color-palette__custom-color-name"
}, buttonLabelName), (0,external_wp_element_namespaceObject.createElement)(flex_item_component, {
as: "span",
className: "components-color-palette__custom-color-value"
}, valueWithoutLeadingHash));
}
}), hasMultipleColorOrigins ? (0,external_wp_element_namespaceObject.createElement)(MultiplePalettes, extends_extends({}, paletteCommonProps, {
colors: colors
})) : (0,external_wp_element_namespaceObject.createElement)(SinglePalette, extends_extends({}, paletteCommonProps, {
colors: colors
})));
}
/**
* Allows the user to pick a color from a list of pre-defined color entries.
*
* ```jsx
* import { ColorPalette } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyColorPalette = () => {
* const [ color, setColor ] = useState ( '#f00' )
* const colors = [
* { name: 'red', color: '#f00' },
* { name: 'white', color: '#fff' },
* { name: 'blue', color: '#00f' },
* ];
* return (
* <ColorPalette
* colors={ colors }
* value={ color }
* onChange={ ( color ) => setColor( color ) }
* />
* );
* } );
* ```
*/
const ColorPalette = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedColorPalette);
/* harmony default export */ var color_palette = (ColorPalette);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/unit-control/utils.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const isWeb = external_wp_element_namespaceObject.Platform.OS === 'web';
const allUnits = {
px: {
value: 'px',
label: isWeb ? 'px' : (0,external_wp_i18n_namespaceObject.__)('Pixels (px)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Pixels (px)'),
step: 1
},
'%': {
value: '%',
label: isWeb ? '%' : (0,external_wp_i18n_namespaceObject.__)('Percentage (%)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Percent (%)'),
step: 0.1
},
em: {
value: 'em',
label: isWeb ? 'em' : (0,external_wp_i18n_namespaceObject.__)('Relative to parent font size (em)'),
a11yLabel: (0,external_wp_i18n_namespaceObject._x)('ems', 'Relative to parent font size (em)'),
step: 0.01
},
rem: {
value: 'rem',
label: isWeb ? 'rem' : (0,external_wp_i18n_namespaceObject.__)('Relative to root font size (rem)'),
a11yLabel: (0,external_wp_i18n_namespaceObject._x)('rems', 'Relative to root font size (rem)'),
step: 0.01
},
vw: {
value: 'vw',
label: isWeb ? 'vw' : (0,external_wp_i18n_namespaceObject.__)('Viewport width (vw)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Viewport width (vw)'),
step: 0.1
},
vh: {
value: 'vh',
label: isWeb ? 'vh' : (0,external_wp_i18n_namespaceObject.__)('Viewport height (vh)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Viewport height (vh)'),
step: 0.1
},
vmin: {
value: 'vmin',
label: isWeb ? 'vmin' : (0,external_wp_i18n_namespaceObject.__)('Viewport smallest dimension (vmin)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Viewport smallest dimension (vmin)'),
step: 0.1
},
vmax: {
value: 'vmax',
label: isWeb ? 'vmax' : (0,external_wp_i18n_namespaceObject.__)('Viewport largest dimension (vmax)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Viewport largest dimension (vmax)'),
step: 0.1
},
ch: {
value: 'ch',
label: isWeb ? 'ch' : (0,external_wp_i18n_namespaceObject.__)('Width of the zero (0) character (ch)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Width of the zero (0) character (ch)'),
step: 0.01
},
ex: {
value: 'ex',
label: isWeb ? 'ex' : (0,external_wp_i18n_namespaceObject.__)('x-height of the font (ex)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('x-height of the font (ex)'),
step: 0.01
},
cm: {
value: 'cm',
label: isWeb ? 'cm' : (0,external_wp_i18n_namespaceObject.__)('Centimeters (cm)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Centimeters (cm)'),
step: 0.001
},
mm: {
value: 'mm',
label: isWeb ? 'mm' : (0,external_wp_i18n_namespaceObject.__)('Millimeters (mm)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Millimeters (mm)'),
step: 0.1
},
in: {
value: 'in',
label: isWeb ? 'in' : (0,external_wp_i18n_namespaceObject.__)('Inches (in)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Inches (in)'),
step: 0.001
},
pc: {
value: 'pc',
label: isWeb ? 'pc' : (0,external_wp_i18n_namespaceObject.__)('Picas (pc)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Picas (pc)'),
step: 1
},
pt: {
value: 'pt',
label: isWeb ? 'pt' : (0,external_wp_i18n_namespaceObject.__)('Points (pt)'),
a11yLabel: (0,external_wp_i18n_namespaceObject.__)('Points (pt)'),
step: 1
}
};
/**
* An array of all available CSS length units.
*/
const ALL_CSS_UNITS = Object.values(allUnits);
/**
* Units of measurements. `a11yLabel` is used by screenreaders.
*/
const CSS_UNITS = [allUnits.px, allUnits['%'], allUnits.em, allUnits.rem, allUnits.vw, allUnits.vh];
const DEFAULT_UNIT = allUnits.px;
/**
* Handles legacy value + unit handling.
* This component use to manage both incoming value and units separately.
*
* Moving forward, ideally the value should be a string that contains both
* the value and unit, example: '10px'
*
* @param rawValue The raw value as a string (may or may not contain the unit)
* @param fallbackUnit The unit used as a fallback, if not unit is detected in the `value`
* @param allowedUnits Units to derive from.
* @return The extracted quantity and unit. The quantity can be `undefined` in case the raw value
* could not be parsed to a number correctly. The unit can be `undefined` in case the unit parse
* from the raw value could not be matched against the list of allowed units.
*/
function getParsedQuantityAndUnit(rawValue, fallbackUnit, allowedUnits) {
const initialValue = fallbackUnit ? `${rawValue !== null && rawValue !== void 0 ? rawValue : ''}${fallbackUnit}` : rawValue;
return parseQuantityAndUnitFromRawValue(initialValue, allowedUnits);
}
/**
* Checks if units are defined.
*
* @param units List of units.
* @return Whether the list actually contains any units.
*/
function hasUnits(units) {
// Although the `isArray` check shouldn't be necessary (given the signature of
// this typed function), it's better to stay on the side of caution, since
// this function may be called from un-typed environments.
return Array.isArray(units) && !!units.length;
}
/**
* Parses a quantity and unit from a raw string value, given a list of allowed
* units and otherwise falling back to the default unit.
*
* @param rawValue The raw value as a string (may or may not contain the unit)
* @param allowedUnits Units to derive from.
* @return The extracted quantity and unit. The quantity can be `undefined` in case the raw value
* could not be parsed to a number correctly. The unit can be `undefined` in case the unit parsed
* from the raw value could not be matched against the list of allowed units.
*/
function parseQuantityAndUnitFromRawValue(rawValue) {
var _trimmedValue, _unitMatch$;
let allowedUnits = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ALL_CSS_UNITS;
let trimmedValue;
let quantityToReturn;
if (typeof rawValue !== 'undefined' || rawValue === null) {
trimmedValue = `${rawValue}`.trim();
const parsedQuantity = parseFloat(trimmedValue);
quantityToReturn = !isFinite(parsedQuantity) ? undefined : parsedQuantity;
}
const unitMatch = (_trimmedValue = trimmedValue) === null || _trimmedValue === void 0 ? void 0 : _trimmedValue.match(/[\d.\-\+]*\s*(.*)/);
const matchedUnit = unitMatch === null || unitMatch === void 0 ? void 0 : (_unitMatch$ = unitMatch[1]) === null || _unitMatch$ === void 0 ? void 0 : _unitMatch$.toLowerCase();
let unitToReturn;
if (hasUnits(allowedUnits)) {
const match = allowedUnits.find(item => item.value === matchedUnit);
unitToReturn = match === null || match === void 0 ? void 0 : match.value;
} else {
unitToReturn = DEFAULT_UNIT.value;
}
return [quantityToReturn, unitToReturn];
}
/**
* Parses quantity and unit from a raw value. Validates parsed value, using fallback
* value if invalid.
*
* @param rawValue The next value.
* @param allowedUnits Units to derive from.
* @param fallbackQuantity The fallback quantity, used in case it's not possible to parse a valid quantity from the raw value.
* @param fallbackUnit The fallback unit, used in case it's not possible to parse a valid unit from the raw value.
* @return The extracted quantity and unit. The quantity can be `undefined` in case the raw value
* could not be parsed to a number correctly, and the `fallbackQuantity` was also `undefined`. The
* unit can be `undefined` only if the unit parsed from the raw value could not be matched against
* the list of allowed units, the `fallbackQuantity` is also `undefined` and the list of
* `allowedUnits` is passed empty.
*/
function getValidParsedQuantityAndUnit(rawValue, allowedUnits, fallbackQuantity, fallbackUnit) {
const [parsedQuantity, parsedUnit] = parseQuantityAndUnitFromRawValue(rawValue, allowedUnits); // The parsed value from `parseQuantityAndUnitFromRawValue` should now be
// either a real number or undefined. If undefined, use the fallback value.
const quantityToReturn = parsedQuantity !== null && parsedQuantity !== void 0 ? parsedQuantity : fallbackQuantity; // If no unit is parsed from the raw value, or if the fallback unit is not
// defined, use the first value from the list of allowed units as fallback.
let unitToReturn = parsedUnit || fallbackUnit;
if (!unitToReturn && hasUnits(allowedUnits)) {
unitToReturn = allowedUnits[0].value;
}
return [quantityToReturn, unitToReturn];
}
/**
* Takes a unit value and finds the matching accessibility label for the
* unit abbreviation.
*
* @param unit Unit value (example: `px`)
* @return a11y label for the unit abbreviation
*/
function getAccessibleLabelForUnit(unit) {
const match = ALL_CSS_UNITS.find(item => item.value === unit);
return match !== null && match !== void 0 && match.a11yLabel ? match === null || match === void 0 ? void 0 : match.a11yLabel : match === null || match === void 0 ? void 0 : match.value;
}
/**
* Filters available units based on values defined a list of allowed unit values.
*
* @param allowedUnitValues Collection of allowed unit value strings.
* @param availableUnits Collection of available unit objects.
* @return Filtered units.
*/
function filterUnitsWithSettings() {
let allowedUnitValues = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
let availableUnits = arguments.length > 1 ? arguments[1] : undefined;
// Although the `isArray` check shouldn't be necessary (given the signature of
// this typed function), it's better to stay on the side of caution, since
// this function may be called from un-typed environments.
return Array.isArray(availableUnits) ? availableUnits.filter(unit => allowedUnitValues.includes(unit.value)) : [];
}
/**
* Custom hook to retrieve and consolidate units setting from add_theme_support().
* TODO: ideally this hook shouldn't be needed
* https://github.com/WordPress/gutenberg/pull/31822#discussion_r633280823
*
* @param args An object containing units, settingPath & defaultUnits.
* @param args.units Collection of all potentially available units.
* @param args.availableUnits Collection of unit value strings for filtering available units.
* @param args.defaultValues Collection of default values for defined units. Example: `{ px: 350, em: 15 }`.
*
* @return Filtered list of units, with their default values updated following the `defaultValues`
* argument's property.
*/
const useCustomUnits = _ref => {
let {
units = ALL_CSS_UNITS,
availableUnits = [],
defaultValues
} = _ref;
const customUnitsToReturn = filterUnitsWithSettings(availableUnits, units);
if (defaultValues) {
customUnitsToReturn.forEach((unit, i) => {
if (defaultValues[unit.value]) {
const [parsedDefaultValue] = parseQuantityAndUnitFromRawValue(defaultValues[unit.value]);
customUnitsToReturn[i].default = parsedDefaultValue;
}
});
}
return customUnitsToReturn;
};
/**
* Get available units with the unit for the currently selected value
* prepended if it is not available in the list of units.
*
* This is useful to ensure that the current value's unit is always
* accurately displayed in the UI, even if the intention is to hide
* the availability of that unit.
*
* @param rawValue Selected value to parse.
* @param legacyUnit Legacy unit value, if rawValue needs it appended.
* @param units List of available units.
*
* @return A collection of units containing the unit for the current value.
*/
function getUnitsWithCurrentUnit(rawValue, legacyUnit) {
let units = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ALL_CSS_UNITS;
const unitsToReturn = Array.isArray(units) ? [...units] : [];
const [, currentUnit] = getParsedQuantityAndUnit(rawValue, legacyUnit, ALL_CSS_UNITS);
if (currentUnit && !unitsToReturn.some(unit => unit.value === currentUnit)) {
if (allUnits[currentUnit]) {
unitsToReturn.unshift(allUnits[currentUnit]);
}
}
return unitsToReturn;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-control/border-control-dropdown/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useBorderControlDropdown(props) {
const {
border,
className,
colors = [],
enableAlpha = false,
enableStyle = true,
onChange,
previousStyleSelection,
size = 'default',
__experimentalIsRenderedInSidebar = false,
...otherProps
} = useContextSystem(props, 'BorderControlDropdown');
const [widthValue] = parseQuantityAndUnitFromRawValue(border === null || border === void 0 ? void 0 : border.width);
const hasZeroWidth = widthValue === 0;
const onColorChange = color => {
const style = (border === null || border === void 0 ? void 0 : border.style) === 'none' ? previousStyleSelection : border === null || border === void 0 ? void 0 : border.style;
const width = hasZeroWidth && !!color ? '1px' : border === null || border === void 0 ? void 0 : border.width;
onChange({
color,
style,
width
});
};
const onStyleChange = style => {
const width = hasZeroWidth && !!style ? '1px' : border === null || border === void 0 ? void 0 : border.width;
onChange({ ...border,
style,
width
});
};
const onReset = () => {
onChange({ ...border,
color: undefined,
style: undefined
});
}; // Generate class names.
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderControlDropdown(size), className);
}, [className, cx, size]);
const indicatorClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderColorIndicator);
}, [cx]);
const indicatorWrapperClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(colorIndicatorWrapper(border, size));
}, [border, cx, size]);
const popoverControlsClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderControlPopoverControls);
}, [cx]);
const popoverContentClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderControlPopoverContent);
}, [cx]);
const resetButtonClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(resetButton);
}, [cx]);
return { ...otherProps,
border,
className: classes,
colors,
enableAlpha,
enableStyle,
indicatorClassName,
indicatorWrapperClassName,
onColorChange,
onStyleChange,
onReset,
popoverContentClassName,
popoverControlsClassName,
resetButtonClassName,
__experimentalIsRenderedInSidebar
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-control/border-control-dropdown/component.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const getColorObject = (colorValue, colors) => {
if (!colorValue || !colors) {
return;
}
if (isMultiplePaletteArray(colors)) {
// Multiple origins
let matchedColor;
colors.some(origin => origin.colors.some(color => {
if (color.color === colorValue) {
matchedColor = color;
return true;
}
return false;
}));
return matchedColor;
} // Single origin
return colors.find(color => color.color === colorValue);
};
const getToggleAriaLabel = (colorValue, colorObject, style, isStyleEnabled) => {
if (isStyleEnabled) {
if (colorObject) {
return style ? (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %1$s: The name of the color e.g. "vivid red". %2$s: The color's hex code e.g.: "#f00:". %3$s: The current border style selection e.g. "solid".
'Border color and style picker. The currently selected color is called "%1$s" and has a value of "%2$s". The currently selected style is "%3$s".', colorObject.name, colorObject.color, style) : (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %1$s: The name of the color e.g. "vivid red". %2$s: The color's hex code e.g.: "#f00:".
'Border color and style picker. The currently selected color is called "%1$s" and has a value of "%2$s".', colorObject.name, colorObject.color);
}
if (colorValue) {
return style ? (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %1$s: The color's hex code e.g.: "#f00:". %2$s: The current border style selection e.g. "solid".
'Border color and style picker. The currently selected color has a value of "%1$s". The currently selected style is "%2$s".', colorValue, style) : (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %1$s: The color's hex code e.g.: "#f00:".
'Border color and style picker. The currently selected color has a value of "%1$s".', colorValue);
}
return (0,external_wp_i18n_namespaceObject.__)('Border color and style picker.');
}
if (colorObject) {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %1$s: The name of the color e.g. "vivid red". %2$s: The color's hex code e.g.: "#f00:".
'Border color picker. The currently selected color is called "%1$s" and has a value of "%2$s".', colorObject.name, colorObject.color);
}
if (colorValue) {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %1$s: The color's hex code e.g.: "#f00:".
'Border color picker. The currently selected color has a value of "%1$s".', colorValue);
}
return (0,external_wp_i18n_namespaceObject.__)('Border color picker.');
};
const BorderControlDropdown = (props, forwardedRef) => {
const {
__experimentalIsRenderedInSidebar,
border,
colors,
disableCustomColors,
enableAlpha,
enableStyle,
indicatorClassName,
indicatorWrapperClassName,
onReset,
onColorChange,
onStyleChange,
popoverContentClassName,
popoverControlsClassName,
resetButtonClassName,
showDropdownHeader,
__unstablePopoverProps,
...otherProps
} = useBorderControlDropdown(props);
const {
color,
style
} = border || {};
const colorObject = getColorObject(color, colors);
const toggleAriaLabel = getToggleAriaLabel(color, colorObject, style, enableStyle);
const showResetButton = color || style && style !== 'none';
const dropdownPosition = __experimentalIsRenderedInSidebar ? 'bottom left' : undefined;
const renderToggle = _ref => {
let {
onToggle
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
onClick: onToggle,
variant: "tertiary",
"aria-label": toggleAriaLabel,
tooltipPosition: dropdownPosition,
label: (0,external_wp_i18n_namespaceObject.__)('Border color and style picker'),
showTooltip: true
}, (0,external_wp_element_namespaceObject.createElement)("span", {
className: indicatorWrapperClassName
}, (0,external_wp_element_namespaceObject.createElement)(color_indicator, {
className: indicatorClassName,
colorValue: color
})));
};
const renderContent = _ref2 => {
let {
onClose
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(dropdown_content_wrapper, {
paddingSize: "medium"
}, (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
className: popoverControlsClassName,
spacing: 6
}, showDropdownHeader ? (0,external_wp_element_namespaceObject.createElement)(h_stack_component, null, (0,external_wp_element_namespaceObject.createElement)(StyledLabel, null, (0,external_wp_i18n_namespaceObject.__)('Border color')), (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
isSmall: true,
label: (0,external_wp_i18n_namespaceObject.__)('Close border color'),
icon: close_small,
onClick: onClose
})) : undefined, (0,external_wp_element_namespaceObject.createElement)(color_palette, {
className: popoverContentClassName,
value: color,
onChange: onColorChange,
colors,
disableCustomColors,
__experimentalIsRenderedInSidebar: __experimentalIsRenderedInSidebar,
clearable: false,
enableAlpha: enableAlpha
}), enableStyle && (0,external_wp_element_namespaceObject.createElement)(border_control_style_picker_component, {
label: (0,external_wp_i18n_namespaceObject.__)('Style'),
value: style,
onChange: onStyleChange
}))), showResetButton && (0,external_wp_element_namespaceObject.createElement)(dropdown_content_wrapper, {
paddingSize: "none"
}, (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: resetButtonClassName,
variant: "tertiary",
onClick: () => {
onReset();
onClose();
}
}, (0,external_wp_i18n_namespaceObject.__)('Reset to default'))));
};
return (0,external_wp_element_namespaceObject.createElement)(dropdown, extends_extends({
renderToggle: renderToggle,
renderContent: renderContent,
popoverProps: { ...__unstablePopoverProps
}
}, otherProps, {
ref: forwardedRef
}));
};
const ConnectedBorderControlDropdown = contextConnect(BorderControlDropdown, 'BorderControlDropdown');
/* harmony default export */ var border_control_dropdown_component = (ConnectedBorderControlDropdown);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/unit-control/unit-select-control.js
/**
* External dependencies
*/
function UnitSelectControl(_ref) {
let {
className,
isUnitSelectTabbable: isTabbable = true,
onChange,
size = 'default',
unit = 'px',
units = CSS_UNITS,
...props
} = _ref;
if (!hasUnits(units) || (units === null || units === void 0 ? void 0 : units.length) === 1) {
return (0,external_wp_element_namespaceObject.createElement)(UnitLabel, {
className: "components-unit-control__unit-label",
selectSize: size
}, unit);
}
const handleOnChange = event => {
const {
value: unitValue
} = event.target;
const data = units.find(option => option.value === unitValue);
onChange === null || onChange === void 0 ? void 0 : onChange(unitValue, {
event,
data
});
};
const classes = classnames_default()('components-unit-control__select', className);
return (0,external_wp_element_namespaceObject.createElement)(UnitSelect, extends_extends({
className: classes,
onChange: handleOnChange,
selectSize: size,
tabIndex: isTabbable ? undefined : -1,
value: unit
}, props), units.map(option => (0,external_wp_element_namespaceObject.createElement)("option", {
value: option.value,
key: option.value
}, option.label)));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/unit-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedUnitControl(unitControlProps, forwardedRef) {
const {
__unstableStateReducer: stateReducerProp,
autoComplete = 'off',
// @ts-expect-error Ensure that children is omitted from restProps
children,
className,
disabled = false,
disableUnits = false,
isPressEnterToChange = false,
isResetValueOnUnitChange = false,
isUnitSelectTabbable = true,
label,
onChange: onChangeProp,
onUnitChange,
size = 'default',
unit: unitProp,
units: unitsProp = CSS_UNITS,
value: valueProp,
onBlur: onBlurProp,
onFocus: onFocusProp,
...props
} = unitControlProps;
if ('unit' in unitControlProps) {
external_wp_deprecated_default()('UnitControl unit prop', {
since: '5.6',
hint: 'The unit should be provided within the `value` prop.',
version: '6.2'
});
} // The `value` prop, in theory, should not be `null`, but the following line
// ensures it fallback to `undefined` in case a consumer of `UnitControl`
// still passes `null` as a `value`.
const nonNullValueProp = valueProp !== null && valueProp !== void 0 ? valueProp : undefined;
const units = (0,external_wp_element_namespaceObject.useMemo)(() => getUnitsWithCurrentUnit(nonNullValueProp, unitProp, unitsProp), [nonNullValueProp, unitProp, unitsProp]);
const [parsedQuantity, parsedUnit] = getParsedQuantityAndUnit(nonNullValueProp, unitProp, units);
const [unit, setUnit] = use_controlled_state(units.length === 1 ? units[0].value : unitProp, {
initial: parsedUnit,
fallback: ''
});
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (parsedUnit !== undefined) {
setUnit(parsedUnit);
}
}, [parsedUnit, setUnit]); // Stores parsed value for hand-off in state reducer.
const refParsedQuantity = (0,external_wp_element_namespaceObject.useRef)(undefined);
const classes = classnames_default()('components-unit-control', // This class is added for legacy purposes to maintain it on the outer
// wrapper. See: https://github.com/WordPress/gutenberg/pull/45139
'components-unit-control-wrapper', className);
const handleOnQuantityChange = (nextQuantityValue, changeProps) => {
if (nextQuantityValue === '' || typeof nextQuantityValue === 'undefined' || nextQuantityValue === null) {
onChangeProp === null || onChangeProp === void 0 ? void 0 : onChangeProp('', changeProps);
return;
}
/*
* Customizing the onChange callback.
* This allows as to broadcast a combined value+unit to onChange.
*/
const onChangeValue = getValidParsedQuantityAndUnit(nextQuantityValue, units, parsedQuantity, unit).join('');
onChangeProp === null || onChangeProp === void 0 ? void 0 : onChangeProp(onChangeValue, changeProps);
};
const handleOnUnitChange = (nextUnitValue, changeProps) => {
const {
data
} = changeProps;
let nextValue = `${parsedQuantity !== null && parsedQuantity !== void 0 ? parsedQuantity : ''}${nextUnitValue}`;
if (isResetValueOnUnitChange && (data === null || data === void 0 ? void 0 : data.default) !== undefined) {
nextValue = `${data.default}${nextUnitValue}`;
}
onChangeProp === null || onChangeProp === void 0 ? void 0 : onChangeProp(nextValue, changeProps);
onUnitChange === null || onUnitChange === void 0 ? void 0 : onUnitChange(nextUnitValue, changeProps);
setUnit(nextUnitValue);
};
const mayUpdateUnit = event => {
if (!isNaN(Number(event.currentTarget.value))) {
refParsedQuantity.current = undefined;
return;
}
const [validParsedQuantity, validParsedUnit] = getValidParsedQuantityAndUnit(event.currentTarget.value, units, parsedQuantity, unit);
refParsedQuantity.current = validParsedQuantity;
if (isPressEnterToChange && validParsedUnit !== unit) {
const data = Array.isArray(units) ? units.find(option => option.value === validParsedUnit) : undefined;
const changeProps = {
event,
data
}; // The `onChange` callback already gets called, no need to call it explicitly.
onUnitChange === null || onUnitChange === void 0 ? void 0 : onUnitChange(validParsedUnit, changeProps);
setUnit(validParsedUnit);
}
};
const handleOnBlur = event => {
mayUpdateUnit(event);
onBlurProp === null || onBlurProp === void 0 ? void 0 : onBlurProp(event);
};
const handleOnKeyDown = event => {
const {
key
} = event;
if (key === 'Enter') {
mayUpdateUnit(event);
}
};
/**
* "Middleware" function that intercepts updates from InputControl.
* This allows us to tap into actions to transform the (next) state for
* InputControl.
*
* @param state State from InputControl
* @param action Action triggering state change
* @return The updated state to apply to InputControl
*/
const unitControlStateReducer = (state, action) => {
const nextState = { ...state
};
/*
* On commits (when pressing ENTER and on blur if
* isPressEnterToChange is true), if a parse has been performed
* then use that result to update the state.
*/
if (action.type === COMMIT) {
if (refParsedQuantity.current !== undefined) {
var _refParsedQuantity$cu;
nextState.value = ((_refParsedQuantity$cu = refParsedQuantity.current) !== null && _refParsedQuantity$cu !== void 0 ? _refParsedQuantity$cu : '').toString();
refParsedQuantity.current = undefined;
}
}
return nextState;
};
let stateReducer = unitControlStateReducer;
if (stateReducerProp) {
stateReducer = (state, action) => {
const baseState = unitControlStateReducer(state, action);
return stateReducerProp(baseState, action);
};
}
const inputSuffix = !disableUnits ? (0,external_wp_element_namespaceObject.createElement)(UnitSelectControl, {
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Select unit'),
disabled: disabled,
isUnitSelectTabbable: isUnitSelectTabbable,
onChange: handleOnUnitChange,
size: size,
unit: unit,
units: units,
onBlur: onBlurProp,
onFocus: onFocusProp
}) : null;
let step = props.step;
/*
* If no step prop has been passed, lookup the active unit and
* try to get step from `units`, or default to a value of `1`
*/
if (!step && units) {
var _activeUnit$step;
const activeUnit = units.find(option => option.value === unit);
step = (_activeUnit$step = activeUnit === null || activeUnit === void 0 ? void 0 : activeUnit.step) !== null && _activeUnit$step !== void 0 ? _activeUnit$step : 1;
}
return (0,external_wp_element_namespaceObject.createElement)(ValueInput, extends_extends({
type: isPressEnterToChange ? 'text' : 'number'
}, props, {
autoComplete: autoComplete,
className: classes,
disabled: disabled,
spinControls: "none",
isPressEnterToChange: isPressEnterToChange,
label: label,
onBlur: handleOnBlur,
onKeyDown: handleOnKeyDown,
onChange: handleOnQuantityChange,
ref: forwardedRef,
size: size,
suffix: inputSuffix,
value: parsedQuantity !== null && parsedQuantity !== void 0 ? parsedQuantity : '',
step: step,
__unstableStateReducer: stateReducer,
onFocus: onFocusProp
}));
}
/**
* `UnitControl` allows the user to set a numeric quantity as well as a unit (e.g. `px`).
*
*
* @example
* ```jsx
* import { __experimentalUnitControl as UnitControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const Example = () => {
* const [ value, setValue ] = useState( '10px' );
*
* return <UnitControl onChange={ setValue } value={ value } />;
* };
* ```
*/
const UnitControl = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedUnitControl);
/* harmony default export */ var unit_control = (UnitControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-control/border-control/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const sanitizeBorder = border => {
const hasNoWidth = (border === null || border === void 0 ? void 0 : border.width) === undefined || border.width === '';
const hasNoColor = (border === null || border === void 0 ? void 0 : border.color) === undefined; // If width and color are undefined, unset any style selection as well.
if (hasNoWidth && hasNoColor) {
return undefined;
}
return border;
};
function useBorderControl(props) {
const {
className,
colors = [],
isCompact,
onChange,
enableAlpha = true,
enableStyle = true,
shouldSanitizeBorder = true,
size = 'default',
value: border,
width,
__experimentalIsRenderedInSidebar = false,
...otherProps
} = useContextSystem(props, 'BorderControl');
const [widthValue, originalWidthUnit] = parseQuantityAndUnitFromRawValue(border === null || border === void 0 ? void 0 : border.width);
const widthUnit = originalWidthUnit || 'px';
const hadPreviousZeroWidth = widthValue === 0;
const [colorSelection, setColorSelection] = (0,external_wp_element_namespaceObject.useState)();
const [styleSelection, setStyleSelection] = (0,external_wp_element_namespaceObject.useState)();
const onBorderChange = (0,external_wp_element_namespaceObject.useCallback)(newBorder => {
if (shouldSanitizeBorder) {
return onChange(sanitizeBorder(newBorder));
}
onChange(newBorder);
}, [onChange, shouldSanitizeBorder]);
const onWidthChange = (0,external_wp_element_namespaceObject.useCallback)(newWidth => {
const newWidthValue = newWidth === '' ? undefined : newWidth;
const [parsedValue] = parseQuantityAndUnitFromRawValue(newWidth);
const hasZeroWidth = parsedValue === 0;
const updatedBorder = { ...border,
width: newWidthValue
}; // Setting the border width explicitly to zero will also set the
// border style to `none` and clear the border color.
if (hasZeroWidth && !hadPreviousZeroWidth) {
// Before clearing the color and style selections, keep track of
// the current selections so they can be restored when the width
// changes to a non-zero value.
setColorSelection(border === null || border === void 0 ? void 0 : border.color);
setStyleSelection(border === null || border === void 0 ? void 0 : border.style); // Clear the color and style border properties.
updatedBorder.color = undefined;
updatedBorder.style = 'none';
} // Selection has changed from zero border width to non-zero width.
if (!hasZeroWidth && hadPreviousZeroWidth) {
// Restore previous border color and style selections if width
// is now not zero.
if (updatedBorder.color === undefined) {
updatedBorder.color = colorSelection;
}
if (updatedBorder.style === 'none') {
updatedBorder.style = styleSelection;
}
}
onBorderChange(updatedBorder);
}, [border, hadPreviousZeroWidth, colorSelection, styleSelection, onBorderChange]);
const onSliderChange = (0,external_wp_element_namespaceObject.useCallback)(value => {
onWidthChange(`${value}${widthUnit}`);
}, [onWidthChange, widthUnit]); // Generate class names.
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderControl, className);
}, [className, cx]);
let wrapperWidth = width;
if (isCompact) {
// Widths below represent the minimum usable width for compact controls.
// Taller controls contain greater internal padding, thus greater width.
wrapperWidth = size === '__unstable-large' ? '116px' : '90px';
}
const innerWrapperClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
const widthStyle = !!wrapperWidth && styles_wrapperWidth;
const heightStyle = wrapperHeight(size);
return cx(innerWrapper(), widthStyle, heightStyle);
}, [wrapperWidth, cx, size]);
const sliderClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderSlider());
}, [cx]);
return { ...otherProps,
className: classes,
colors,
enableAlpha,
enableStyle,
innerWrapperClassName,
inputWidth: wrapperWidth,
onBorderChange,
onSliderChange,
onWidthChange,
previousStyleSelection: styleSelection,
sliderClassName,
value: border,
widthUnit,
widthValue,
size,
__experimentalIsRenderedInSidebar
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-control/border-control/component.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const BorderLabel = props => {
const {
label,
hideLabelFromVision
} = props;
if (!label) {
return null;
}
return hideLabelFromVision ? (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, {
as: "legend"
}, label) : (0,external_wp_element_namespaceObject.createElement)(StyledLabel, {
as: "legend"
}, label);
};
const UnconnectedBorderControl = (props, forwardedRef) => {
const {
colors,
disableCustomColors,
disableUnits,
enableAlpha,
enableStyle,
hideLabelFromVision,
innerWrapperClassName,
inputWidth,
label,
onBorderChange,
onSliderChange,
onWidthChange,
placeholder,
__unstablePopoverProps,
previousStyleSelection,
showDropdownHeader,
size,
sliderClassName,
value: border,
widthUnit,
widthValue,
withSlider,
__experimentalIsRenderedInSidebar,
...otherProps
} = useBorderControl(props);
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({
as: "fieldset"
}, otherProps, {
ref: forwardedRef
}), (0,external_wp_element_namespaceObject.createElement)(BorderLabel, {
label: label,
hideLabelFromVision: hideLabelFromVision
}), (0,external_wp_element_namespaceObject.createElement)(h_stack_component, {
spacing: 4,
className: innerWrapperClassName
}, (0,external_wp_element_namespaceObject.createElement)(unit_control, {
prefix: (0,external_wp_element_namespaceObject.createElement)(border_control_dropdown_component, {
border: border,
colors: colors,
__unstablePopoverProps: __unstablePopoverProps,
disableCustomColors: disableCustomColors,
enableAlpha: enableAlpha,
enableStyle: enableStyle,
onChange: onBorderChange,
previousStyleSelection: previousStyleSelection,
showDropdownHeader: showDropdownHeader,
__experimentalIsRenderedInSidebar: __experimentalIsRenderedInSidebar,
size: size
}),
label: (0,external_wp_i18n_namespaceObject.__)('Border width'),
hideLabelFromVision: true,
min: 0,
onChange: onWidthChange,
value: (border === null || border === void 0 ? void 0 : border.width) || '',
placeholder: placeholder,
disableUnits: disableUnits,
__unstableInputWidth: inputWidth,
size: size
}), withSlider && (0,external_wp_element_namespaceObject.createElement)(range_control, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Border width'),
hideLabelFromVision: true,
className: sliderClassName,
initialPosition: 0,
max: 100,
min: 0,
onChange: onSliderChange,
step: ['px', '%'].includes(widthUnit) ? 1 : 0.1,
value: widthValue || undefined,
withInputField: false
})));
};
/**
* The `BorderControl` brings together internal sub-components which allow users to
* set the various properties of a border. The first sub-component, a
* `BorderDropdown` contains options representing border color and style. The
* border width is controlled via a `UnitControl` and an optional `RangeControl`.
*
* Border radius is not covered by this control as it may be desired separate to
* color, style, and width. For example, the border radius may be absorbed under
* a "shape" abstraction.
*
* ```jsx
* import { __experimentalBorderControl as BorderControl } from '@wordpress/components';
* import { __ } from '@wordpress/i18n';
*
* const colors = [
* { name: 'Blue 20', color: '#72aee6' },
* // ...
* ];
*
* const MyBorderControl = () => {
* const [ border, setBorder ] = useState();
* const onChange = ( newBorder ) => setBorder( newBorder );
*
* return (
* <BorderControl
* colors={ colors }
* label={ __( 'Border' ) }
* onChange={ onChange }
* value={ border }
* />
* );
* };
* ```
*/
const BorderControl = contextConnect(UnconnectedBorderControl, 'BorderControl');
/* harmony default export */ var border_control_component = (BorderControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/grid/utils.js
/**
* External dependencies
*/
const utils_ALIGNMENTS = {
bottom: {
alignItems: 'flex-end',
justifyContent: 'center'
},
bottomLeft: {
alignItems: 'flex-start',
justifyContent: 'flex-end'
},
bottomRight: {
alignItems: 'flex-end',
justifyContent: 'flex-end'
},
center: {
alignItems: 'center',
justifyContent: 'center'
},
spaced: {
alignItems: 'center',
justifyContent: 'space-between'
},
left: {
alignItems: 'center',
justifyContent: 'flex-start'
},
right: {
alignItems: 'center',
justifyContent: 'flex-end'
},
stretch: {
alignItems: 'stretch'
},
top: {
alignItems: 'flex-start',
justifyContent: 'center'
},
topLeft: {
alignItems: 'flex-start',
justifyContent: 'flex-start'
},
topRight: {
alignItems: 'flex-start',
justifyContent: 'flex-end'
}
};
function utils_getAlignmentProps(alignment) {
const alignmentProps = alignment ? utils_ALIGNMENTS[alignment] : {};
return alignmentProps;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/grid/hook.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useGrid(props) {
const {
align,
alignment,
className,
columnGap,
columns = 2,
gap = 3,
isInline = false,
justify,
rowGap,
rows,
templateColumns,
templateRows,
...otherProps
} = useContextSystem(props, 'Grid');
const columnsAsArray = Array.isArray(columns) ? columns : [columns];
const column = useResponsiveValue(columnsAsArray);
const rowsAsArray = Array.isArray(rows) ? rows : [rows];
const row = useResponsiveValue(rowsAsArray);
const gridTemplateColumns = templateColumns || !!columns && `repeat( ${column}, 1fr )`;
const gridTemplateRows = templateRows || !!rows && `repeat( ${row}, 1fr )`;
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
const alignmentProps = utils_getAlignmentProps(alignment);
const gridClasses = /*#__PURE__*/emotion_react_browser_esm_css({
alignItems: align,
display: isInline ? 'inline-grid' : 'grid',
gap: `calc( ${config_values.gridBase} * ${gap} )`,
gridTemplateColumns: gridTemplateColumns || undefined,
gridTemplateRows: gridTemplateRows || undefined,
gridRowGap: rowGap,
gridColumnGap: columnGap,
justifyContent: justify,
verticalAlign: isInline ? 'middle' : undefined,
...alignmentProps
}, true ? "" : 0, true ? "" : 0);
return cx(gridClasses, className);
}, [align, alignment, className, columnGap, cx, gap, gridTemplateColumns, gridTemplateRows, isInline, justify, rowGap]);
return { ...otherProps,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/grid/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedGrid(props, forwardedRef) {
const gridProps = useGrid(props);
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({}, gridProps, {
ref: forwardedRef
}));
}
/**
* `Grid` is a primitive layout component that can arrange content in a grid configuration.
*
* ```jsx
* import {
* __experimentalGrid as Grid,
* __experimentalText as Text
* } from `@wordpress/components`;
*
* function Example() {
* return (
* <Grid columns={ 3 }>
* <Text>Code</Text>
* <Text>is</Text>
* <Text>Poetry</Text>
* </Grid>
* );
* }
* ```
*/
const Grid = contextConnect(UnconnectedGrid, 'Grid');
/* harmony default export */ var grid_component = (Grid);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-box-control/border-box-control-split-controls/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useBorderBoxControlSplitControls(props) {
const {
className,
colors = [],
enableAlpha = false,
enableStyle = true,
size = 'default',
__experimentalIsRenderedInSidebar = false,
...otherProps
} = useContextSystem(props, 'BorderBoxControlSplitControls'); // Generate class names.
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderBoxControlSplitControls(size), className);
}, [cx, className, size]);
const centeredClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(centeredBorderControl, className);
}, [cx, className]);
const rightAlignedClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(rightBorderControl(), className);
}, [cx, className]);
return { ...otherProps,
centeredClassName,
className: classes,
colors,
enableAlpha,
enableStyle,
rightAlignedClassName,
size,
__experimentalIsRenderedInSidebar
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-box-control/border-box-control-split-controls/component.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const BorderBoxControlSplitControls = (props, forwardedRef) => {
const {
centeredClassName,
colors,
disableCustomColors,
enableAlpha,
enableStyle,
onChange,
popoverPlacement,
popoverOffset,
rightAlignedClassName,
size = 'default',
value,
__experimentalIsRenderedInSidebar,
...otherProps
} = useBorderBoxControlSplitControls(props); // Use internal state instead of a ref to make sure that the component
// re-renders when the popover's anchor updates.
const [popoverAnchor, setPopoverAnchor] = (0,external_wp_element_namespaceObject.useState)(null); // Memoize popoverProps to avoid returning a new object every time.
const popoverProps = (0,external_wp_element_namespaceObject.useMemo)(() => popoverPlacement ? {
placement: popoverPlacement,
offset: popoverOffset,
anchor: popoverAnchor,
shift: true
} : undefined, [popoverPlacement, popoverOffset, popoverAnchor]);
const sharedBorderControlProps = {
colors,
disableCustomColors,
enableAlpha,
enableStyle,
isCompact: true,
__experimentalIsRenderedInSidebar,
size
};
const mergedRef = (0,external_wp_compose_namespaceObject.useMergeRefs)([setPopoverAnchor, forwardedRef]);
return (0,external_wp_element_namespaceObject.createElement)(grid_component, extends_extends({}, otherProps, {
ref: mergedRef,
gap: 4
}), (0,external_wp_element_namespaceObject.createElement)(border_box_control_visualizer_component, {
value: value,
size: size
}), (0,external_wp_element_namespaceObject.createElement)(border_control_component, extends_extends({
className: centeredClassName,
hideLabelFromVision: true,
label: (0,external_wp_i18n_namespaceObject.__)('Top border'),
onChange: newBorder => onChange(newBorder, 'top'),
__unstablePopoverProps: popoverProps,
value: value === null || value === void 0 ? void 0 : value.top
}, sharedBorderControlProps)), (0,external_wp_element_namespaceObject.createElement)(border_control_component, extends_extends({
hideLabelFromVision: true,
label: (0,external_wp_i18n_namespaceObject.__)('Left border'),
onChange: newBorder => onChange(newBorder, 'left'),
__unstablePopoverProps: popoverProps,
value: value === null || value === void 0 ? void 0 : value.left
}, sharedBorderControlProps)), (0,external_wp_element_namespaceObject.createElement)(border_control_component, extends_extends({
className: rightAlignedClassName,
hideLabelFromVision: true,
label: (0,external_wp_i18n_namespaceObject.__)('Right border'),
onChange: newBorder => onChange(newBorder, 'right'),
__unstablePopoverProps: popoverProps,
value: value === null || value === void 0 ? void 0 : value.right
}, sharedBorderControlProps)), (0,external_wp_element_namespaceObject.createElement)(border_control_component, extends_extends({
className: centeredClassName,
hideLabelFromVision: true,
label: (0,external_wp_i18n_namespaceObject.__)('Bottom border'),
onChange: newBorder => onChange(newBorder, 'bottom'),
__unstablePopoverProps: popoverProps,
value: value === null || value === void 0 ? void 0 : value.bottom
}, sharedBorderControlProps)));
};
const ConnectedBorderBoxControlSplitControls = contextConnect(BorderBoxControlSplitControls, 'BorderBoxControlSplitControls');
/* harmony default export */ var border_box_control_split_controls_component = (ConnectedBorderBoxControlSplitControls);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/unit-values.js
const UNITED_VALUE_REGEX = /^([\d.\-+]*)\s*(fr|cm|mm|Q|in|pc|pt|px|em|ex|ch|rem|lh|vw|vh|vmin|vmax|%|cap|ic|rlh|vi|vb|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?$/;
/**
* Parses a number and unit from a value.
*
* @param toParse Value to parse
*
* @return The extracted number and unit.
*/
function parseCSSUnitValue(toParse) {
const value = toParse.trim();
const matched = value.match(UNITED_VALUE_REGEX);
if (!matched) {
return [undefined, undefined];
}
const [, num, unit] = matched;
let numParsed = parseFloat(num);
numParsed = Number.isNaN(numParsed) ? undefined : numParsed;
return [numParsed, unit];
}
/**
* Combines a value and a unit into a unit value.
*
* @param value
* @param unit
*
* @return The unit value.
*/
function createCSSUnitValue(value, unit) {
return `${value}${unit}`;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-box-control/utils.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const utils_sides = ['top', 'right', 'bottom', 'left'];
const borderProps = ['color', 'style', 'width'];
const isEmptyBorder = border => {
if (!border) {
return true;
}
return !borderProps.some(prop => border[prop] !== undefined);
};
const isDefinedBorder = border => {
// No border, no worries :)
if (!border) {
return false;
} // If we have individual borders per side within the border object we
// need to check whether any of those side borders have been set.
if (hasSplitBorders(border)) {
const allSidesEmpty = utils_sides.every(side => isEmptyBorder(border[side]));
return !allSidesEmpty;
} // If we have a top-level border only, check if that is empty. e.g.
// { color: undefined, style: undefined, width: undefined }
// Border radius can still be set within the border object as it is
// handled separately.
return !isEmptyBorder(border);
};
const isCompleteBorder = border => {
if (!border) {
return false;
}
return borderProps.every(prop => border[prop] !== undefined);
};
const hasSplitBorders = function () {
let border = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return Object.keys(border).some(side => utils_sides.indexOf(side) !== -1);
};
const hasMixedBorders = borders => {
if (!hasSplitBorders(borders)) {
return false;
}
const shorthandBorders = utils_sides.map(side => getShorthandBorderStyle(borders === null || borders === void 0 ? void 0 : borders[side]));
return !shorthandBorders.every(border => border === shorthandBorders[0]);
};
const getSplitBorders = border => {
if (!border || isEmptyBorder(border)) {
return undefined;
}
return {
top: border,
right: border,
bottom: border,
left: border
};
};
const getBorderDiff = (original, updated) => {
const diff = {};
if (original.color !== updated.color) {
diff.color = updated.color;
}
if (original.style !== updated.style) {
diff.style = updated.style;
}
if (original.width !== updated.width) {
diff.width = updated.width;
}
return diff;
};
const getCommonBorder = borders => {
if (!borders) {
return undefined;
}
const colors = [];
const styles = [];
const widths = [];
utils_sides.forEach(side => {
var _borders$side, _borders$side2, _borders$side3;
colors.push((_borders$side = borders[side]) === null || _borders$side === void 0 ? void 0 : _borders$side.color);
styles.push((_borders$side2 = borders[side]) === null || _borders$side2 === void 0 ? void 0 : _borders$side2.style);
widths.push((_borders$side3 = borders[side]) === null || _borders$side3 === void 0 ? void 0 : _borders$side3.width);
});
const allColorsMatch = colors.every(value => value === colors[0]);
const allStylesMatch = styles.every(value => value === styles[0]);
const allWidthsMatch = widths.every(value => value === widths[0]);
return {
color: allColorsMatch ? colors[0] : undefined,
style: allStylesMatch ? styles[0] : undefined,
width: allWidthsMatch ? widths[0] : getMostCommonUnit(widths)
};
};
const getShorthandBorderStyle = (border, fallbackBorder) => {
if (isEmptyBorder(border)) {
return fallbackBorder;
}
const {
color: fallbackColor,
style: fallbackStyle,
width: fallbackWidth
} = fallbackBorder || {};
const {
color = fallbackColor,
style = fallbackStyle,
width = fallbackWidth
} = border;
const hasVisibleBorder = !!width && width !== '0' || !!color;
const borderStyle = hasVisibleBorder ? style || 'solid' : style;
return [width, borderStyle, color].filter(Boolean).join(' ');
};
const getMostCommonUnit = values => {
// Collect all the CSS units.
const units = values.map(value => value === undefined ? undefined : parseCSSUnitValue(`${value}`)[1]); // Return the most common unit out of only the defined CSS units.
const filteredUnits = units.filter(value => value !== undefined);
return mode(filteredUnits);
};
/**
* Finds the mode value out of the array passed favouring the first value
* as a tiebreaker.
*
* @param values Values to determine the mode from.
*
* @return The mode value.
*/
function mode(values) {
if (values.length === 0) {
return undefined;
}
const map = {};
let maxCount = 0;
let currentMode;
values.forEach(value => {
map[value] = map[value] === undefined ? 1 : map[value] + 1;
if (map[value] > maxCount) {
currentMode = value;
maxCount = map[value];
}
});
return currentMode;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-box-control/border-box-control/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useBorderBoxControl(props) {
const {
className,
colors = [],
onChange,
enableAlpha = false,
enableStyle = true,
size = 'default',
value,
__experimentalIsRenderedInSidebar = false,
...otherProps
} = useContextSystem(props, 'BorderBoxControl');
const mixedBorders = hasMixedBorders(value);
const splitBorders = hasSplitBorders(value);
const linkedValue = splitBorders ? getCommonBorder(value) : value;
const splitValue = splitBorders ? value : getSplitBorders(value); // If no numeric width value is set, the unit select will be disabled.
const hasWidthValue = !isNaN(parseFloat(`${linkedValue === null || linkedValue === void 0 ? void 0 : linkedValue.width}`));
const [isLinked, setIsLinked] = (0,external_wp_element_namespaceObject.useState)(!mixedBorders);
const toggleLinked = () => setIsLinked(!isLinked);
const onLinkedChange = newBorder => {
if (!newBorder) {
return onChange(undefined);
} // If we have all props defined on the new border apply it.
if (!mixedBorders || isCompleteBorder(newBorder)) {
return onChange(isEmptyBorder(newBorder) ? undefined : newBorder);
} // If we had mixed borders we might have had some shared border props
// that we need to maintain. For example; we could have mixed borders
// with all the same color but different widths. Then from the linked
// control we change the color. We should keep the separate widths.
const changes = getBorderDiff(linkedValue, newBorder);
const updatedBorders = {
top: { ...(value === null || value === void 0 ? void 0 : value.top),
...changes
},
right: { ...(value === null || value === void 0 ? void 0 : value.right),
...changes
},
bottom: { ...(value === null || value === void 0 ? void 0 : value.bottom),
...changes
},
left: { ...(value === null || value === void 0 ? void 0 : value.left),
...changes
}
};
if (hasMixedBorders(updatedBorders)) {
return onChange(updatedBorders);
}
const filteredResult = isEmptyBorder(updatedBorders.top) ? undefined : updatedBorders.top;
onChange(filteredResult);
};
const onSplitChange = (newBorder, side) => {
const updatedBorders = { ...splitValue,
[side]: newBorder
};
if (hasMixedBorders(updatedBorders)) {
onChange(updatedBorders);
} else {
onChange(newBorder);
}
};
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(borderBoxControl, className);
}, [cx, className]);
const linkedControlClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(linkedBorderControl());
}, [cx]);
const wrapperClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(wrapper);
}, [cx]);
return { ...otherProps,
className: classes,
colors,
disableUnits: mixedBorders && !hasWidthValue,
enableAlpha,
enableStyle,
hasMixedBorders: mixedBorders,
isLinked,
linkedControlClassName,
onLinkedChange,
onSplitChange,
toggleLinked,
linkedValue,
size,
splitValue,
wrapperClassName,
__experimentalIsRenderedInSidebar
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/border-box-control/border-box-control/component.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const component_BorderLabel = props => {
const {
label,
hideLabelFromVision
} = props;
if (!label) {
return null;
}
return hideLabelFromVision ? (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, {
as: "label"
}, label) : (0,external_wp_element_namespaceObject.createElement)(StyledLabel, null, label);
};
const UnconnectedBorderBoxControl = (props, forwardedRef) => {
const {
className,
colors,
disableCustomColors,
disableUnits,
enableAlpha,
enableStyle,
hasMixedBorders,
hideLabelFromVision,
isLinked,
label,
linkedControlClassName,
linkedValue,
onLinkedChange,
onSplitChange,
popoverPlacement,
popoverOffset,
size,
splitValue,
toggleLinked,
wrapperClassName,
__experimentalIsRenderedInSidebar,
...otherProps
} = useBorderBoxControl(props); // Use internal state instead of a ref to make sure that the component
// re-renders when the popover's anchor updates.
const [popoverAnchor, setPopoverAnchor] = (0,external_wp_element_namespaceObject.useState)(null); // Memoize popoverProps to avoid returning a new object every time.
const popoverProps = (0,external_wp_element_namespaceObject.useMemo)(() => popoverPlacement ? {
placement: popoverPlacement,
offset: popoverOffset,
anchor: popoverAnchor,
shift: true
} : undefined, [popoverPlacement, popoverOffset, popoverAnchor]);
const mergedRef = (0,external_wp_compose_namespaceObject.useMergeRefs)([setPopoverAnchor, forwardedRef]);
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({
className: className
}, otherProps, {
ref: mergedRef
}), (0,external_wp_element_namespaceObject.createElement)(component_BorderLabel, {
label: label,
hideLabelFromVision: hideLabelFromVision
}), (0,external_wp_element_namespaceObject.createElement)(component, {
className: wrapperClassName
}, isLinked ? (0,external_wp_element_namespaceObject.createElement)(border_control_component, {
className: linkedControlClassName,
colors: colors,
disableUnits: disableUnits,
disableCustomColors: disableCustomColors,
enableAlpha: enableAlpha,
enableStyle: enableStyle,
onChange: onLinkedChange,
placeholder: hasMixedBorders ? (0,external_wp_i18n_namespaceObject.__)('Mixed') : undefined,
__unstablePopoverProps: popoverProps,
shouldSanitizeBorder: false // This component will handle that.
,
value: linkedValue,
withSlider: true,
width: size === '__unstable-large' ? '116px' : '110px',
__experimentalIsRenderedInSidebar: __experimentalIsRenderedInSidebar,
size: size
}) : (0,external_wp_element_namespaceObject.createElement)(border_box_control_split_controls_component, {
colors: colors,
disableCustomColors: disableCustomColors,
enableAlpha: enableAlpha,
enableStyle: enableStyle,
onChange: onSplitChange,
popoverPlacement: popoverPlacement,
popoverOffset: popoverOffset,
value: splitValue,
__experimentalIsRenderedInSidebar: __experimentalIsRenderedInSidebar,
size: size
}), (0,external_wp_element_namespaceObject.createElement)(border_box_control_linked_button_component, {
onClick: toggleLinked,
isLinked: isLinked,
size: size
})));
};
/**
* The `BorderBoxControl` effectively has two view states. The first, a "linked"
* view, allows configuration of a flat border via a single `BorderControl`.
* The second, a "split" view, contains a `BorderControl` for each side
* as well as a visualizer for the currently selected borders. Each view also
* contains a button to toggle between the two.
*
* When switching from the "split" view to "linked", if the individual side
* borders are not consistent, the "linked" view will display any border
* properties selections that are consistent while showing a mixed state for
* those that aren't. For example, if all borders had the same color and style
* but different widths, then the border dropdown in the "linked" view's
* `BorderControl` would show that consistent color and style but the "linked"
* view's width input would show "Mixed" placeholder text.
*
* ```jsx
* import { __experimentalBorderBoxControl as BorderBoxControl } from '@wordpress/components';
* import { __ } from '@wordpress/i18n';
*
* const colors = [
* { name: 'Blue 20', color: '#72aee6' },
* // ...
* ];
*
* const MyBorderBoxControl = () => {
* const defaultBorder = {
* color: '#72aee6',
* style: 'dashed',
* width: '1px',
* };
* const [ borders, setBorders ] = useState( {
* top: defaultBorder,
* right: defaultBorder,
* bottom: defaultBorder,
* left: defaultBorder,
* } );
* const onChange = ( newBorders ) => setBorders( newBorders );
*
* return (
* <BorderBoxControl
* colors={ colors }
* label={ __( 'Borders' ) }
* onChange={ onChange }
* value={ borders }
* />
* );
* };
* ```
*/
const BorderBoxControl = contextConnect(UnconnectedBorderBoxControl, 'BorderBoxControl');
/* harmony default export */ var border_box_control_component = (BorderBoxControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/box-control/styles/box-control-styles.js
function box_control_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const box_control_styles_Root = createStyled("div", true ? {
target: "e7pk0lh6"
} : 0)( true ? {
name: "14bvcyk",
styles: "box-sizing:border-box;max-width:235px;padding-bottom:12px;width:100%"
} : 0);
const Header = /*#__PURE__*/createStyled(flex_component, true ? {
target: "e7pk0lh5"
} : 0)( true ? {
name: "5bhc30",
styles: "margin-bottom:8px"
} : 0);
const HeaderControlWrapper = /*#__PURE__*/createStyled(flex_component, true ? {
target: "e7pk0lh4"
} : 0)( true ? {
name: "aujtid",
styles: "min-height:30px;gap:0"
} : 0);
const UnitControlWrapper = createStyled("div", true ? {
target: "e7pk0lh3"
} : 0)( true ? {
name: "112jwab",
styles: "box-sizing:border-box;max-width:80px"
} : 0);
const LayoutContainer = /*#__PURE__*/createStyled(flex_component, true ? {
target: "e7pk0lh2"
} : 0)( true ? {
name: "xy18ro",
styles: "justify-content:center;padding-top:8px"
} : 0);
const Layout = /*#__PURE__*/createStyled(flex_component, true ? {
target: "e7pk0lh1"
} : 0)( true ? {
name: "3tw5wk",
styles: "position:relative;height:100%;width:100%;justify-content:flex-start"
} : 0);
var box_control_styles_ref = true ? {
name: "1ch9yvl",
styles: "border-radius:0"
} : 0;
var box_control_styles_ref2 = true ? {
name: "tg3mx0",
styles: "border-radius:2px"
} : 0;
const unitControlBorderRadiusStyles = _ref3 => {
let {
isFirst,
isLast,
isOnly
} = _ref3;
if (isFirst) {
return rtl({
borderTopRightRadius: 0,
borderBottomRightRadius: 0
})();
}
if (isLast) {
return rtl({
borderTopLeftRadius: 0,
borderBottomLeftRadius: 0
})();
}
if (isOnly) {
return box_control_styles_ref2;
}
return box_control_styles_ref;
};
const unitControlMarginStyles = _ref4 => {
let {
isFirst,
isOnly
} = _ref4;
const marginLeft = isFirst || isOnly ? 0 : -1;
return rtl({
marginLeft
})();
};
const box_control_styles_UnitControl = /*#__PURE__*/createStyled(unit_control, true ? {
target: "e7pk0lh0"
} : 0)("max-width:60px;", unitControlBorderRadiusStyles, ";", unitControlMarginStyles, ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/box-control/unit-control.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const unit_control_noop = () => {};
function BoxUnitControl(_ref) {
let {
isFirst,
isLast,
isOnly,
onHoverOn = unit_control_noop,
onHoverOff = unit_control_noop,
label,
value,
...props
} = _ref;
const bindHoverGesture = useHover(_ref2 => {
let {
event,
...state
} = _ref2;
if (state.hovering) {
onHoverOn(event, state);
} else {
onHoverOff(event, state);
}
});
return (0,external_wp_element_namespaceObject.createElement)(UnitControlWrapper, bindHoverGesture(), (0,external_wp_element_namespaceObject.createElement)(unit_control_Tooltip, {
text: label
}, (0,external_wp_element_namespaceObject.createElement)(box_control_styles_UnitControl, extends_extends({
"aria-label": label,
className: "component-box-control__unit-control",
isFirst: isFirst,
isLast: isLast,
isOnly: isOnly,
isPressEnterToChange: true,
isResetValueOnUnitChange: false,
value: value
}, props))));
}
function unit_control_Tooltip(_ref3) {
let {
children,
text
} = _ref3;
if (!text) return children;
/**
* Wrapping the children in a `<div />` as Tooltip as it attempts
* to render the <UnitControl />. Using a plain `<div />` appears to
* resolve this issue.
*
* Originally discovered and referenced here:
* https://github.com/WordPress/gutenberg/pull/24966#issuecomment-685875026
*/
return (0,external_wp_element_namespaceObject.createElement)(tooltip, {
text: text,
position: "top"
}, (0,external_wp_element_namespaceObject.createElement)("div", null, children));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/box-control/utils.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const LABELS = {
all: (0,external_wp_i18n_namespaceObject.__)('All'),
top: (0,external_wp_i18n_namespaceObject.__)('Top'),
bottom: (0,external_wp_i18n_namespaceObject.__)('Bottom'),
left: (0,external_wp_i18n_namespaceObject.__)('Left'),
right: (0,external_wp_i18n_namespaceObject.__)('Right'),
mixed: (0,external_wp_i18n_namespaceObject.__)('Mixed'),
vertical: (0,external_wp_i18n_namespaceObject.__)('Vertical'),
horizontal: (0,external_wp_i18n_namespaceObject.__)('Horizontal')
};
const DEFAULT_VALUES = {
top: undefined,
right: undefined,
bottom: undefined,
left: undefined
};
const ALL_SIDES = ['top', 'right', 'bottom', 'left'];
/**
* Gets an items with the most occurrence within an array
* https://stackoverflow.com/a/20762713
*
* @param {Array<any>} arr Array of items to check.
* @return {any} The item with the most occurrences.
*/
function utils_mode(arr) {
return arr.sort((a, b) => arr.filter(v => v === a).length - arr.filter(v => v === b).length).pop();
}
/**
* Gets the 'all' input value and unit from values data.
*
* @param {Object} values Box values.
* @param {Object} selectedUnits Box units.
* @param {Array} availableSides Available box sides to evaluate.
*
* @return {string} A value + unit for the 'all' input.
*/
function getAllValue() {
let values = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let selectedUnits = arguments.length > 1 ? arguments[1] : undefined;
let availableSides = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ALL_SIDES;
const sides = normalizeSides(availableSides);
const parsedQuantitiesAndUnits = sides.map(side => parseQuantityAndUnitFromRawValue(values[side]));
const allParsedQuantities = parsedQuantitiesAndUnits.map(value => {
var _value$;
return (_value$ = value[0]) !== null && _value$ !== void 0 ? _value$ : '';
});
const allParsedUnits = parsedQuantitiesAndUnits.map(value => value[1]);
const commonQuantity = allParsedQuantities.every(v => v === allParsedQuantities[0]) ? allParsedQuantities[0] : '';
/**
* The typeof === 'number' check is important. On reset actions, the incoming value
* may be null or an empty string.
*
* Also, the value may also be zero (0), which is considered a valid unit value.
*
* typeof === 'number' is more specific for these cases, rather than relying on a
* simple truthy check.
*/
let commonUnit;
if (typeof commonQuantity === 'number') {
commonUnit = utils_mode(allParsedUnits);
} else {
var _getAllUnitFallback;
// Set meaningful unit selection if no commonQuantity and user has previously
// selected units without assigning values while controls were unlinked.
commonUnit = (_getAllUnitFallback = getAllUnitFallback(selectedUnits)) !== null && _getAllUnitFallback !== void 0 ? _getAllUnitFallback : utils_mode(allParsedUnits);
}
return [commonQuantity, commonUnit].join('');
}
/**
* Determine the most common unit selection to use as a fallback option.
*
* @param {Object} selectedUnits Current unit selections for individual sides.
* @return {string} Most common unit selection.
*/
function getAllUnitFallback(selectedUnits) {
if (!selectedUnits || typeof selectedUnits !== 'object') {
return undefined;
}
const filteredUnits = Object.values(selectedUnits).filter(Boolean);
return utils_mode(filteredUnits);
}
/**
* Checks to determine if values are mixed.
*
* @param {Object} values Box values.
* @param {Object} selectedUnits Box units.
* @param {Array} sides Available box sides to evaluate.
*
* @return {boolean} Whether values are mixed.
*/
function isValuesMixed() {
let values = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let selectedUnits = arguments.length > 1 ? arguments[1] : undefined;
let sides = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ALL_SIDES;
const allValue = getAllValue(values, selectedUnits, sides);
const isMixed = isNaN(parseFloat(allValue));
return isMixed;
}
/**
* Checks to determine if values are defined.
*
* @param {Object} values Box values.
*
* @return {boolean} Whether values are mixed.
*/
function isValuesDefined(values) {
return values !== undefined && Object.values(values).filter( // Switching units when input is empty causes values only
// containing units. This gives false positive on mixed values
// unless filtered.
value => !!value && /\d/.test(value)).length > 0;
}
/**
* Get initial selected side, factoring in whether the sides are linked,
* and whether the vertical / horizontal directions are grouped via splitOnAxis.
*
* @param {boolean} isLinked Whether the box control's fields are linked.
* @param {boolean} splitOnAxis Whether splitting by horizontal or vertical axis.
* @return {string} The initial side.
*/
function getInitialSide(isLinked, splitOnAxis) {
let initialSide = 'all';
if (!isLinked) {
initialSide = splitOnAxis ? 'vertical' : 'top';
}
return initialSide;
}
/**
* Normalizes provided sides configuration to an array containing only top,
* right, bottom and left. This essentially just maps `horizontal` or `vertical`
* to their appropriate sides to facilitate correctly determining value for
* all input control.
*
* @param {Array} sides Available sides for box control.
* @return {Array} Normalized sides configuration.
*/
function normalizeSides(sides) {
const filteredSides = [];
if (!(sides !== null && sides !== void 0 && sides.length)) {
return ALL_SIDES;
}
if (sides.includes('vertical')) {
filteredSides.push(...['top', 'bottom']);
} else if (sides.includes('horizontal')) {
filteredSides.push(...['left', 'right']);
} else {
const newSides = ALL_SIDES.filter(side => sides.includes(side));
filteredSides.push(...newSides);
}
return filteredSides;
}
/**
* Applies a value to an object representing top, right, bottom and left sides
* while taking into account any custom side configuration.
*
* @param {Object} currentValues The current values for each side.
* @param {string|number} newValue The value to apply to the sides object.
* @param {string[]} sides Array defining valid sides.
*
* @return {Object} Object containing the updated values for each side.
*/
function applyValueToSides(currentValues, newValue, sides) {
const newValues = { ...currentValues
};
if (sides !== null && sides !== void 0 && sides.length) {
sides.forEach(side => {
if (side === 'vertical') {
newValues.top = newValue;
newValues.bottom = newValue;
} else if (side === 'horizontal') {
newValues.left = newValue;
newValues.right = newValue;
} else {
newValues[side] = newValue;
}
});
} else {
ALL_SIDES.forEach(side => newValues[side] = newValue);
}
return newValues;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/box-control/all-input-control.js
/**
* Internal dependencies
*/
const all_input_control_noop = () => {};
function AllInputControl(_ref) {
let {
onChange = all_input_control_noop,
onFocus = all_input_control_noop,
onHoverOn = all_input_control_noop,
onHoverOff = all_input_control_noop,
values,
sides,
selectedUnits,
setSelectedUnits,
...props
} = _ref;
const allValue = getAllValue(values, selectedUnits, sides);
const hasValues = isValuesDefined(values);
const isMixed = hasValues && isValuesMixed(values, selectedUnits, sides);
const allPlaceholder = isMixed ? LABELS.mixed : null;
const handleOnFocus = event => {
onFocus(event, {
side: 'all'
});
};
const handleOnChange = next => {
const isNumeric = !isNaN(parseFloat(next));
const nextValue = isNumeric ? next : undefined;
const nextValues = applyValueToSides(values, nextValue, sides);
onChange(nextValues);
}; // Set selected unit so it can be used as fallback by unlinked controls
// when individual sides do not have a value containing a unit.
const handleOnUnitChange = unit => {
const newUnits = applyValueToSides(selectedUnits, unit, sides);
setSelectedUnits(newUnits);
};
const handleOnHoverOn = () => {
onHoverOn({
top: true,
bottom: true,
left: true,
right: true
});
};
const handleOnHoverOff = () => {
onHoverOff({
top: false,
bottom: false,
left: false,
right: false
});
};
return (0,external_wp_element_namespaceObject.createElement)(BoxUnitControl, extends_extends({}, props, {
disableUnits: isMixed,
isOnly: true,
value: allValue,
onChange: handleOnChange,
onUnitChange: handleOnUnitChange,
onFocus: handleOnFocus,
onHoverOn: handleOnHoverOn,
onHoverOff: handleOnHoverOff,
placeholder: allPlaceholder
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/box-control/input-controls.js
/**
* Internal dependencies
*/
const input_controls_noop = () => {};
function BoxInputControls(_ref) {
let {
onChange = input_controls_noop,
onFocus = input_controls_noop,
onHoverOn = input_controls_noop,
onHoverOff = input_controls_noop,
values,
selectedUnits,
setSelectedUnits,
sides,
...props
} = _ref;
const createHandleOnFocus = side => event => {
onFocus(event, {
side
});
};
const createHandleOnHoverOn = side => () => {
onHoverOn({
[side]: true
});
};
const createHandleOnHoverOff = side => () => {
onHoverOff({
[side]: false
});
};
const handleOnChange = nextValues => {
onChange(nextValues);
};
const createHandleOnChange = side => (next, _ref2) => {
let {
event
} = _ref2;
const {
altKey
} = event;
const nextValues = { ...values
};
const isNumeric = !isNaN(parseFloat(next));
const nextValue = isNumeric ? next : undefined;
nextValues[side] = nextValue;
/**
* Supports changing pair sides. For example, holding the ALT key
* when changing the TOP will also update BOTTOM.
*/
if (altKey) {
switch (side) {
case 'top':
nextValues.bottom = nextValue;
break;
case 'bottom':
nextValues.top = nextValue;
break;
case 'left':
nextValues.right = nextValue;
break;
case 'right':
nextValues.left = nextValue;
break;
}
}
handleOnChange(nextValues);
};
const createHandleOnUnitChange = side => next => {
const newUnits = { ...selectedUnits
};
newUnits[side] = next;
setSelectedUnits(newUnits);
}; // Filter sides if custom configuration provided, maintaining default order.
const filteredSides = sides !== null && sides !== void 0 && sides.length ? ALL_SIDES.filter(side => sides.includes(side)) : ALL_SIDES;
const first = filteredSides[0];
const last = filteredSides[filteredSides.length - 1];
const only = first === last && first;
return (0,external_wp_element_namespaceObject.createElement)(LayoutContainer, {
className: "component-box-control__input-controls-wrapper"
}, (0,external_wp_element_namespaceObject.createElement)(Layout, {
gap: 0,
align: "top",
className: "component-box-control__input-controls"
}, filteredSides.map(side => {
const [parsedQuantity, parsedUnit] = parseQuantityAndUnitFromRawValue(values[side]);
const computedUnit = values[side] ? parsedUnit : selectedUnits[side];
return (0,external_wp_element_namespaceObject.createElement)(BoxUnitControl, extends_extends({}, props, {
isFirst: first === side,
isLast: last === side,
isOnly: only === side,
value: [parsedQuantity, computedUnit].join(''),
onChange: createHandleOnChange(side),
onUnitChange: createHandleOnUnitChange(side),
onFocus: createHandleOnFocus(side),
onHoverOn: createHandleOnHoverOn(side),
onHoverOff: createHandleOnHoverOff(side),
label: LABELS[side],
key: `box-control-${side}`
}));
})));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/box-control/axial-input-controls.js
/**
* Internal dependencies
*/
const groupedSides = ['vertical', 'horizontal'];
function AxialInputControls(_ref) {
let {
onChange,
onFocus,
onHoverOn,
onHoverOff,
values,
selectedUnits,
setSelectedUnits,
sides,
...props
} = _ref;
const createHandleOnFocus = side => event => {
if (!onFocus) {
return;
}
onFocus(event, {
side
});
};
const createHandleOnHoverOn = side => () => {
if (!onHoverOn) {
return;
}
if (side === 'vertical') {
onHoverOn({
top: true,
bottom: true
});
}
if (side === 'horizontal') {
onHoverOn({
left: true,
right: true
});
}
};
const createHandleOnHoverOff = side => () => {
if (!onHoverOff) {
return;
}
if (side === 'vertical') {
onHoverOff({
top: false,
bottom: false
});
}
if (side === 'horizontal') {
onHoverOff({
left: false,
right: false
});
}
};
const createHandleOnChange = side => next => {
if (!onChange) {
return;
}
const nextValues = { ...values
};
const isNumeric = !isNaN(parseFloat(next));
const nextValue = isNumeric ? next : undefined;
if (side === 'vertical') {
nextValues.top = nextValue;
nextValues.bottom = nextValue;
}
if (side === 'horizontal') {
nextValues.left = nextValue;
nextValues.right = nextValue;
}
onChange(nextValues);
};
const createHandleOnUnitChange = side => next => {
const newUnits = { ...selectedUnits
};
if (side === 'vertical') {
newUnits.top = next;
newUnits.bottom = next;
}
if (side === 'horizontal') {
newUnits.left = next;
newUnits.right = next;
}
setSelectedUnits(newUnits);
}; // Filter sides if custom configuration provided, maintaining default order.
const filteredSides = sides !== null && sides !== void 0 && sides.length ? groupedSides.filter(side => sides.includes(side)) : groupedSides;
const first = filteredSides[0];
const last = filteredSides[filteredSides.length - 1];
const only = first === last && first;
return (0,external_wp_element_namespaceObject.createElement)(Layout, {
gap: 0,
align: "top",
className: "component-box-control__vertical-horizontal-input-controls"
}, filteredSides.map(side => {
const [parsedQuantity, parsedUnit] = parseQuantityAndUnitFromRawValue(side === 'vertical' ? values.top : values.left);
const selectedUnit = side === 'vertical' ? selectedUnits.top : selectedUnits.left;
return (0,external_wp_element_namespaceObject.createElement)(BoxUnitControl, extends_extends({}, props, {
isFirst: first === side,
isLast: last === side,
isOnly: only === side,
value: [parsedQuantity, selectedUnit !== null && selectedUnit !== void 0 ? selectedUnit : parsedUnit].join(''),
onChange: createHandleOnChange(side),
onUnitChange: createHandleOnUnitChange(side),
onFocus: createHandleOnFocus(side),
onHoverOn: createHandleOnHoverOn(side),
onHoverOff: createHandleOnHoverOff(side),
label: LABELS[side],
key: side
}));
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/box-control/styles/box-control-icon-styles.js
function box_control_icon_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
const box_control_icon_styles_Root = createStyled("span", true ? {
target: "eaw9yqk8"
} : 0)( true ? {
name: "1w884gc",
styles: "box-sizing:border-box;display:block;width:24px;height:24px;position:relative;padding:4px"
} : 0);
const Viewbox = createStyled("span", true ? {
target: "eaw9yqk7"
} : 0)( true ? {
name: "i6vjox",
styles: "box-sizing:border-box;display:block;position:relative;width:100%;height:100%"
} : 0);
const strokeFocus = _ref => {
let {
isFocused
} = _ref;
return /*#__PURE__*/emotion_react_browser_esm_css({
backgroundColor: 'currentColor',
opacity: isFocused ? 1 : 0.3
}, true ? "" : 0, true ? "" : 0);
};
const Stroke = createStyled("span", true ? {
target: "eaw9yqk6"
} : 0)("box-sizing:border-box;display:block;pointer-events:none;position:absolute;", strokeFocus, ";" + ( true ? "" : 0));
const VerticalStroke = /*#__PURE__*/createStyled(Stroke, true ? {
target: "eaw9yqk5"
} : 0)( true ? {
name: "1k2w39q",
styles: "bottom:3px;top:3px;width:2px"
} : 0);
const HorizontalStroke = /*#__PURE__*/createStyled(Stroke, true ? {
target: "eaw9yqk4"
} : 0)( true ? {
name: "1q9b07k",
styles: "height:2px;left:3px;right:3px"
} : 0);
const TopStroke = /*#__PURE__*/createStyled(HorizontalStroke, true ? {
target: "eaw9yqk3"
} : 0)( true ? {
name: "abcix4",
styles: "top:0"
} : 0);
const RightStroke = /*#__PURE__*/createStyled(VerticalStroke, true ? {
target: "eaw9yqk2"
} : 0)( true ? {
name: "1wf8jf",
styles: "right:0"
} : 0);
const BottomStroke = /*#__PURE__*/createStyled(HorizontalStroke, true ? {
target: "eaw9yqk1"
} : 0)( true ? {
name: "8tapst",
styles: "bottom:0"
} : 0);
const LeftStroke = /*#__PURE__*/createStyled(VerticalStroke, true ? {
target: "eaw9yqk0"
} : 0)( true ? {
name: "1ode3cm",
styles: "left:0"
} : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/box-control/icon.js
/**
* Internal dependencies
*/
const BASE_ICON_SIZE = 24;
function BoxControlIcon(_ref) {
let {
size = 24,
side = 'all',
sides,
...props
} = _ref;
const isSideDisabled = value => (sides === null || sides === void 0 ? void 0 : sides.length) && !sides.includes(value);
const hasSide = value => {
if (isSideDisabled(value)) {
return false;
}
return side === 'all' || side === value;
};
const top = hasSide('top') || hasSide('vertical');
const right = hasSide('right') || hasSide('horizontal');
const bottom = hasSide('bottom') || hasSide('vertical');
const left = hasSide('left') || hasSide('horizontal'); // Simulates SVG Icon scaling.
const scale = size / BASE_ICON_SIZE;
return (0,external_wp_element_namespaceObject.createElement)(box_control_icon_styles_Root, extends_extends({
style: {
transform: `scale(${scale})`
}
}, props), (0,external_wp_element_namespaceObject.createElement)(Viewbox, null, (0,external_wp_element_namespaceObject.createElement)(TopStroke, {
isFocused: top
}), (0,external_wp_element_namespaceObject.createElement)(RightStroke, {
isFocused: right
}), (0,external_wp_element_namespaceObject.createElement)(BottomStroke, {
isFocused: bottom
}), (0,external_wp_element_namespaceObject.createElement)(LeftStroke, {
isFocused: left
})));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/box-control/linked-button.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function LinkedButton(_ref) {
let {
isLinked,
...props
} = _ref;
const label = isLinked ? (0,external_wp_i18n_namespaceObject.__)('Unlink sides') : (0,external_wp_i18n_namespaceObject.__)('Link sides');
return (0,external_wp_element_namespaceObject.createElement)(tooltip, {
text: label
}, (0,external_wp_element_namespaceObject.createElement)(build_module_button, extends_extends({}, props, {
className: "component-box-control__linked-button",
isSmall: true,
icon: isLinked ? library_link : link_off,
iconSize: 24,
"aria-label": label
})));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/box-control/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const defaultInputProps = {
min: 0
};
const box_control_noop = () => {};
function box_control_useUniqueId(idProp) {
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(BoxControl, 'inspector-box-control');
return idProp || instanceId;
}
function BoxControl(_ref) {
let {
id: idProp,
inputProps = defaultInputProps,
onChange = box_control_noop,
label = (0,external_wp_i18n_namespaceObject.__)('Box Control'),
values: valuesProp,
units,
sides,
splitOnAxis = false,
allowReset = true,
resetValues = DEFAULT_VALUES,
onMouseOver,
onMouseOut
} = _ref;
const [values, setValues] = use_controlled_state(valuesProp, {
fallback: DEFAULT_VALUES
});
const inputValues = values || DEFAULT_VALUES;
const hasInitialValue = isValuesDefined(valuesProp);
const hasOneSide = (sides === null || sides === void 0 ? void 0 : sides.length) === 1;
const [isDirty, setIsDirty] = (0,external_wp_element_namespaceObject.useState)(hasInitialValue);
const [isLinked, setIsLinked] = (0,external_wp_element_namespaceObject.useState)(!hasInitialValue || !isValuesMixed(inputValues) || hasOneSide);
const [side, setSide] = (0,external_wp_element_namespaceObject.useState)(getInitialSide(isLinked, splitOnAxis)); // Tracking selected units via internal state allows filtering of CSS unit
// only values from being saved while maintaining preexisting unit selection
// behaviour. Filtering CSS only values prevents invalid style values.
const [selectedUnits, setSelectedUnits] = (0,external_wp_element_namespaceObject.useState)({
top: parseQuantityAndUnitFromRawValue(valuesProp === null || valuesProp === void 0 ? void 0 : valuesProp.top)[1],
right: parseQuantityAndUnitFromRawValue(valuesProp === null || valuesProp === void 0 ? void 0 : valuesProp.right)[1],
bottom: parseQuantityAndUnitFromRawValue(valuesProp === null || valuesProp === void 0 ? void 0 : valuesProp.bottom)[1],
left: parseQuantityAndUnitFromRawValue(valuesProp === null || valuesProp === void 0 ? void 0 : valuesProp.left)[1]
});
const id = box_control_useUniqueId(idProp);
const headingId = `${id}-heading`;
const toggleLinked = () => {
setIsLinked(!isLinked);
setSide(getInitialSide(!isLinked, splitOnAxis));
};
const handleOnFocus = (event, _ref2) => {
let {
side: nextSide
} = _ref2;
setSide(nextSide);
};
const handleOnChange = nextValues => {
onChange(nextValues);
setValues(nextValues);
setIsDirty(true);
};
const handleOnReset = () => {
onChange(resetValues);
setValues(resetValues);
setSelectedUnits(resetValues);
setIsDirty(false);
};
const inputControlProps = { ...inputProps,
onChange: handleOnChange,
onFocus: handleOnFocus,
isLinked,
units,
selectedUnits,
setSelectedUnits,
sides,
values: inputValues,
onMouseOver,
onMouseOut
};
return (0,external_wp_element_namespaceObject.createElement)(box_control_styles_Root, {
id: id,
role: "group",
"aria-labelledby": headingId
}, (0,external_wp_element_namespaceObject.createElement)(Header, {
className: "component-box-control__header"
}, (0,external_wp_element_namespaceObject.createElement)(flex_item_component, null, (0,external_wp_element_namespaceObject.createElement)(BaseControl.VisualLabel, {
id: headingId
}, label)), allowReset && (0,external_wp_element_namespaceObject.createElement)(flex_item_component, null, (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "component-box-control__reset-button",
isSecondary: true,
isSmall: true,
onClick: handleOnReset,
disabled: !isDirty
}, (0,external_wp_i18n_namespaceObject.__)('Reset')))), (0,external_wp_element_namespaceObject.createElement)(HeaderControlWrapper, {
className: "component-box-control__header-control-wrapper"
}, (0,external_wp_element_namespaceObject.createElement)(flex_item_component, null, (0,external_wp_element_namespaceObject.createElement)(BoxControlIcon, {
side: side,
sides: sides
})), isLinked && (0,external_wp_element_namespaceObject.createElement)(flex_block_component, null, (0,external_wp_element_namespaceObject.createElement)(AllInputControl, extends_extends({
"aria-label": label
}, inputControlProps))), !isLinked && splitOnAxis && (0,external_wp_element_namespaceObject.createElement)(flex_block_component, null, (0,external_wp_element_namespaceObject.createElement)(AxialInputControls, inputControlProps)), !hasOneSide && (0,external_wp_element_namespaceObject.createElement)(flex_item_component, null, (0,external_wp_element_namespaceObject.createElement)(LinkedButton, {
onClick: toggleLinked,
isLinked: isLinked
}))), !isLinked && !splitOnAxis && (0,external_wp_element_namespaceObject.createElement)(BoxInputControls, inputControlProps));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/button-group/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedButtonGroup(props, ref) {
const {
className,
...restProps
} = props;
const classes = classnames_default()('components-button-group', className);
return (0,external_wp_element_namespaceObject.createElement)("div", extends_extends({
ref: ref,
role: "group",
className: classes
}, restProps));
}
/**
* ButtonGroup can be used to group any related buttons together. To emphasize
* related buttons, a group should share a common container.
*
* ```jsx
* import { Button, ButtonGroup } from '@wordpress/components';
*
* const MyButtonGroup = () => (
* <ButtonGroup>
* <Button variant="primary">Button 1</Button>
* <Button variant="primary">Button 2</Button>
* </ButtonGroup>
* );
* ```
*/
const ButtonGroup = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedButtonGroup);
/* harmony default export */ var button_group = (ButtonGroup);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/elevation/styles.js
function elevation_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
const Elevation = true ? {
name: "12ip69d",
styles: "background:transparent;display:block;margin:0!important;pointer-events:none;position:absolute;will-change:box-shadow"
} : 0;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/elevation/hook.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function getBoxShadow(value) {
const boxShadowColor = `rgba(0, 0, 0, ${value / 20})`;
const boxShadow = `0 ${value}px ${value * 2}px 0
${boxShadowColor}`;
return boxShadow;
}
function useElevation(props) {
const {
active,
borderRadius = 'inherit',
className,
focus,
hover,
isInteractive = false,
offset = 0,
value = 0,
...otherProps
} = useContextSystem(props, 'Elevation');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
let hoverValue = isValueDefined(hover) ? hover : value * 2;
let activeValue = isValueDefined(active) ? active : value / 2;
if (!isInteractive) {
hoverValue = isValueDefined(hover) ? hover : undefined;
activeValue = isValueDefined(active) ? active : undefined;
}
const transition = `box-shadow ${config_values.transitionDuration} ${config_values.transitionTimingFunction}`;
const sx = {};
sx.Base = /*#__PURE__*/emotion_react_browser_esm_css({
borderRadius,
bottom: offset,
boxShadow: getBoxShadow(value),
opacity: config_values.elevationIntensity,
left: offset,
right: offset,
top: offset,
transition
}, reduceMotion('transition'), true ? "" : 0, true ? "" : 0);
if (isValueDefined(hoverValue)) {
sx.hover = /*#__PURE__*/emotion_react_browser_esm_css("*:hover>&{box-shadow:", getBoxShadow(hoverValue), ";}" + ( true ? "" : 0), true ? "" : 0);
}
if (isValueDefined(activeValue)) {
sx.active = /*#__PURE__*/emotion_react_browser_esm_css("*:active>&{box-shadow:", getBoxShadow(activeValue), ";}" + ( true ? "" : 0), true ? "" : 0);
}
if (isValueDefined(focus)) {
sx.focus = /*#__PURE__*/emotion_react_browser_esm_css("*:focus>&{box-shadow:", getBoxShadow(focus), ";}" + ( true ? "" : 0), true ? "" : 0);
}
return cx(Elevation, sx.Base, sx.hover, sx.focus, sx.active, className);
}, [active, borderRadius, className, cx, focus, hover, isInteractive, offset, value]);
return { ...otherProps,
className: classes,
'aria-hidden': true
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/elevation/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedElevation(props, forwardedRef) {
const elevationProps = useElevation(props);
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({}, elevationProps, {
ref: forwardedRef
}));
}
/**
* `Elevation` is a core component that renders shadow, using the component
* system's shadow system.
*
* The shadow effect is generated using the `value` prop.
*
* ```jsx
* import {
* __experimentalElevation as Elevation,
* __experimentalSurface as Surface,
* __experimentalText as Text,
* } from '@wordpress/components';
*
* function Example() {
* return (
* <Surface>
* <Text>Code is Poetry</Text>
* <Elevation value={ 5 } />
* </Surface>
* );
* }
* ```
*/
const component_Elevation = contextConnect(UnconnectedElevation, 'Elevation');
/* harmony default export */ var elevation_component = (component_Elevation);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/styles.js
function card_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
// Since the border for `Card` is rendered via the `box-shadow` property
// (as opposed to the `border` property), the value of the border radius needs
// to be adjusted by removing 1px (this is because the `box-shadow` renders
// as an "outer radius").
const adjustedBorderRadius = `calc(${config_values.cardBorderRadius} - 1px)`;
const Card = /*#__PURE__*/emotion_react_browser_esm_css("box-shadow:0 0 0 1px ", config_values.surfaceBorderColor, ";outline:none;" + ( true ? "" : 0), true ? "" : 0);
const styles_Header = true ? {
name: "1showjb",
styles: "border-bottom:1px solid;box-sizing:border-box;&:last-child{border-bottom:none;}"
} : 0;
const Footer = true ? {
name: "14n5oej",
styles: "border-top:1px solid;box-sizing:border-box;&:first-of-type{border-top:none;}"
} : 0;
const Content = true ? {
name: "13udsys",
styles: "height:100%"
} : 0;
const Body = true ? {
name: "6ywzd",
styles: "box-sizing:border-box;height:auto;max-height:100%"
} : 0;
const Media = true ? {
name: "dq805e",
styles: "box-sizing:border-box;overflow:hidden;&>img,&>iframe{display:block;height:auto;max-width:100%;width:100%;}"
} : 0;
const Divider = true ? {
name: "c990dr",
styles: "box-sizing:border-box;display:block;width:100%"
} : 0;
const borderRadius = /*#__PURE__*/emotion_react_browser_esm_css("&:first-of-type{border-top-left-radius:", adjustedBorderRadius, ";border-top-right-radius:", adjustedBorderRadius, ";}&:last-of-type{border-bottom-left-radius:", adjustedBorderRadius, ";border-bottom-right-radius:", adjustedBorderRadius, ";}" + ( true ? "" : 0), true ? "" : 0);
const borderColor = /*#__PURE__*/emotion_react_browser_esm_css("border-color:", config_values.colorDivider, ";" + ( true ? "" : 0), true ? "" : 0);
const boxShadowless = true ? {
name: "1t90u8d",
styles: "box-shadow:none"
} : 0;
const borderless = true ? {
name: "1e1ncky",
styles: "border:none"
} : 0;
const rounded = /*#__PURE__*/emotion_react_browser_esm_css("border-radius:", adjustedBorderRadius, ";" + ( true ? "" : 0), true ? "" : 0);
const xSmallCardPadding = /*#__PURE__*/emotion_react_browser_esm_css("padding:", config_values.cardPaddingXSmall, ";" + ( true ? "" : 0), true ? "" : 0);
const cardPaddings = {
large: /*#__PURE__*/emotion_react_browser_esm_css("padding:", config_values.cardPaddingLarge, ";" + ( true ? "" : 0), true ? "" : 0),
medium: /*#__PURE__*/emotion_react_browser_esm_css("padding:", config_values.cardPaddingMedium, ";" + ( true ? "" : 0), true ? "" : 0),
small: /*#__PURE__*/emotion_react_browser_esm_css("padding:", config_values.cardPaddingSmall, ";" + ( true ? "" : 0), true ? "" : 0),
xSmall: xSmallCardPadding,
// The `extraSmall` size is not officially documented, but the following styles
// are kept for legacy reasons to support older values of the `size` prop.
extraSmall: xSmallCardPadding
};
const shady = /*#__PURE__*/emotion_react_browser_esm_css("background-color:", COLORS.ui.backgroundDisabled, ";" + ( true ? "" : 0), true ? "" : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/surface/styles.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const Surface = /*#__PURE__*/emotion_react_browser_esm_css("background-color:", config_values.surfaceColor, ";color:", COLORS.gray[900], ";position:relative;" + ( true ? "" : 0), true ? "" : 0);
const background = /*#__PURE__*/emotion_react_browser_esm_css("background-color:", config_values.surfaceBackgroundColor, ";" + ( true ? "" : 0), true ? "" : 0);
function getBorders(_ref) {
let {
borderBottom,
borderLeft,
borderRight,
borderTop
} = _ref;
const borderStyle = `1px solid ${config_values.surfaceBorderColor}`;
return /*#__PURE__*/emotion_react_browser_esm_css({
borderBottom: borderBottom ? borderStyle : undefined,
borderLeft: borderLeft ? borderStyle : undefined,
borderRight: borderRight ? borderStyle : undefined,
borderTop: borderTop ? borderStyle : undefined
}, true ? "" : 0, true ? "" : 0);
}
const primary = /*#__PURE__*/emotion_react_browser_esm_css( true ? "" : 0, true ? "" : 0);
const secondary = /*#__PURE__*/emotion_react_browser_esm_css("background:", config_values.surfaceBackgroundTintColor, ";" + ( true ? "" : 0), true ? "" : 0);
const tertiary = /*#__PURE__*/emotion_react_browser_esm_css("background:", config_values.surfaceBackgroundTertiaryColor, ";" + ( true ? "" : 0), true ? "" : 0);
const customBackgroundSize = surfaceBackgroundSize => [surfaceBackgroundSize, surfaceBackgroundSize].join(' ');
const dottedBackground1 = surfaceBackgroundSizeDotted => ['90deg', [config_values.surfaceBackgroundColor, surfaceBackgroundSizeDotted].join(' '), 'transparent 1%'].join(',');
const dottedBackground2 = surfaceBackgroundSizeDotted => [[config_values.surfaceBackgroundColor, surfaceBackgroundSizeDotted].join(' '), 'transparent 1%'].join(',');
const dottedBackgroundCombined = surfaceBackgroundSizeDotted => [`linear-gradient( ${dottedBackground1(surfaceBackgroundSizeDotted)} ) center`, `linear-gradient( ${dottedBackground2(surfaceBackgroundSizeDotted)} ) center`, config_values.surfaceBorderBoldColor].join(',');
const getDotted = (surfaceBackgroundSize, surfaceBackgroundSizeDotted) => /*#__PURE__*/emotion_react_browser_esm_css("background:", dottedBackgroundCombined(surfaceBackgroundSizeDotted), ";background-size:", customBackgroundSize(surfaceBackgroundSize), ";" + ( true ? "" : 0), true ? "" : 0);
const gridBackground1 = [`${config_values.surfaceBorderSubtleColor} 1px`, 'transparent 1px'].join(',');
const gridBackground2 = ['90deg', `${config_values.surfaceBorderSubtleColor} 1px`, 'transparent 1px'].join(',');
const gridBackgroundCombined = [`linear-gradient( ${gridBackground1} )`, `linear-gradient( ${gridBackground2} )`].join(',');
const getGrid = surfaceBackgroundSize => {
return /*#__PURE__*/emotion_react_browser_esm_css("background:", config_values.surfaceBackgroundColor, ";background-image:", gridBackgroundCombined, ";background-size:", customBackgroundSize(surfaceBackgroundSize), ";" + ( true ? "" : 0), true ? "" : 0);
};
const getVariant = (variant, surfaceBackgroundSize, surfaceBackgroundSizeDotted) => {
switch (variant) {
case 'dotted':
{
return getDotted(surfaceBackgroundSize, surfaceBackgroundSizeDotted);
}
case 'grid':
{
return getGrid(surfaceBackgroundSize);
}
case 'primary':
{
return primary;
}
case 'secondary':
{
return secondary;
}
case 'tertiary':
{
return tertiary;
}
}
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/surface/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useSurface(props) {
const {
backgroundSize = 12,
borderBottom = false,
borderLeft = false,
borderRight = false,
borderTop = false,
className,
variant = 'primary',
...otherProps
} = useContextSystem(props, 'Surface');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
const sx = {
borders: getBorders({
borderBottom,
borderLeft,
borderRight,
borderTop
})
};
return cx(Surface, sx.borders, getVariant(variant, `${backgroundSize}px`, `${backgroundSize - 1}px`), className);
}, [backgroundSize, borderBottom, borderLeft, borderRight, borderTop, className, cx, variant]);
return { ...otherProps,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function card_hook_useDeprecatedProps(_ref) {
let {
elevation,
isElevated,
...otherProps
} = _ref;
const propsToReturn = { ...otherProps
};
let computedElevation = elevation;
if (isElevated) {
var _computedElevation;
external_wp_deprecated_default()('Card isElevated prop', {
since: '5.9',
alternative: 'elevation'
});
(_computedElevation = computedElevation) !== null && _computedElevation !== void 0 ? _computedElevation : computedElevation = 2;
} // The `elevation` prop should only be passed when it's not `undefined`,
// otherwise it will override the value that gets derived from `useContextSystem`.
if (typeof computedElevation !== 'undefined') {
propsToReturn.elevation = computedElevation;
}
return propsToReturn;
}
function useCard(props) {
const {
className,
elevation = 0,
isBorderless = false,
isRounded = true,
size = 'medium',
...otherProps
} = useContextSystem(card_hook_useDeprecatedProps(props), 'Card');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(Card, isBorderless && boxShadowless, isRounded && rounded, className);
}, [className, cx, isBorderless, isRounded]);
const surfaceProps = useSurface({ ...otherProps,
className: classes
});
return { ...surfaceProps,
elevation,
isBorderless,
isRounded,
size
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card/component.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedCard(props, forwardedRef) {
const {
children,
elevation,
isBorderless,
isRounded,
size,
...otherProps
} = useCard(props);
const elevationBorderRadius = isRounded ? config_values.cardBorderRadius : 0;
const cx = useCx();
const elevationClassName = (0,external_wp_element_namespaceObject.useMemo)(() => cx( /*#__PURE__*/emotion_react_browser_esm_css({
borderRadius: elevationBorderRadius
}, true ? "" : 0, true ? "" : 0)), [cx, elevationBorderRadius]);
const contextProviderValue = (0,external_wp_element_namespaceObject.useMemo)(() => {
const contextProps = {
size,
isBorderless
};
return {
CardBody: contextProps,
CardHeader: contextProps,
CardFooter: contextProps
};
}, [isBorderless, size]);
return (0,external_wp_element_namespaceObject.createElement)(ContextSystemProvider, {
value: contextProviderValue
}, (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({}, otherProps, {
ref: forwardedRef
}), (0,external_wp_element_namespaceObject.createElement)(component, {
className: cx(Content)
}, children), (0,external_wp_element_namespaceObject.createElement)(elevation_component, {
className: elevationClassName,
isInteractive: false,
value: elevation ? 1 : 0
}), (0,external_wp_element_namespaceObject.createElement)(elevation_component, {
className: elevationClassName,
isInteractive: false,
value: elevation
})));
}
/**
* `Card` provides a flexible and extensible content container.
* `Card` also provides a convenient set of sub-components such as `CardBody`,
* `CardHeader`, `CardFooter`, and more.
*
* ```jsx
* import {
* Card,
* CardHeader,
* CardBody,
* CardFooter,
* Text,
* Heading,
* } from `@wordpress/components`;
*
* function Example() {
* return (
* <Card>
* <CardHeader>
* <Heading size={ 4 }>Card Title</Heading>
* </CardHeader>
* <CardBody>
* <Text>Card Content</Text>
* </CardBody>
* <CardFooter>
* <Text>Card Footer</Text>
* </CardFooter>
* </Card>
* );
* }
* ```
*/
const component_Card = contextConnect(UnconnectedCard, 'Card');
/* harmony default export */ var card_component = (component_Card);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/scrollable/styles.js
function scrollable_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const scrollableScrollbar = /*#__PURE__*/emotion_react_browser_esm_css("@media only screen and ( min-device-width: 40em ){&::-webkit-scrollbar{height:12px;width:12px;}&::-webkit-scrollbar-track{background-color:transparent;}&::-webkit-scrollbar-track{background:", config_values.colorScrollbarTrack, ";border-radius:8px;}&::-webkit-scrollbar-thumb{background-clip:padding-box;background-color:", config_values.colorScrollbarThumb, ";border:2px solid rgba( 0, 0, 0, 0 );border-radius:7px;}&:hover::-webkit-scrollbar-thumb{background-color:", config_values.colorScrollbarThumbHover, ";}}" + ( true ? "" : 0), true ? "" : 0);
const Scrollable = true ? {
name: "13udsys",
styles: "height:100%"
} : 0;
const styles_Content = true ? {
name: "bjn8wh",
styles: "position:relative"
} : 0;
const styles_smoothScroll = true ? {
name: "7zq9w",
styles: "scroll-behavior:smooth"
} : 0;
const scrollX = true ? {
name: "q33xhg",
styles: "overflow-x:auto;overflow-y:hidden"
} : 0;
const scrollY = true ? {
name: "103x71s",
styles: "overflow-x:hidden;overflow-y:auto"
} : 0;
const scrollAuto = true ? {
name: "umwchj",
styles: "overflow-y:auto"
} : 0;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/scrollable/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useScrollable(props) {
const {
className,
scrollDirection = 'y',
smoothScroll = false,
...otherProps
} = useContextSystem(props, 'Scrollable');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => cx(Scrollable, scrollableScrollbar, smoothScroll && styles_smoothScroll, scrollDirection === 'x' && scrollX, scrollDirection === 'y' && scrollY, scrollDirection === 'auto' && scrollAuto, className), [className, cx, scrollDirection, smoothScroll]);
return { ...otherProps,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/scrollable/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedScrollable(props, forwardedRef) {
const scrollableProps = useScrollable(props);
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({}, scrollableProps, {
ref: forwardedRef
}));
}
/**
* `Scrollable` is a layout component that content in a scrollable container.
*
* ```jsx
* import { __experimentalScrollable as Scrollable } from `@wordpress/components`;
*
* function Example() {
* return (
* <Scrollable style={ { maxHeight: 200 } }>
* <div style={ { height: 500 } }>...</div>
* </Scrollable>
* );
* }
* ```
*/
const component_Scrollable = contextConnect(UnconnectedScrollable, 'Scrollable');
/* harmony default export */ var scrollable_component = (component_Scrollable);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card-body/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useCardBody(props) {
const {
className,
isScrollable = false,
isShady = false,
size = 'medium',
...otherProps
} = useContextSystem(props, 'CardBody');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => cx(Body, borderRadius, cardPaddings[size], isShady && shady, // This classname is added for legacy compatibility reasons.
'components-card__body', className), [className, cx, isShady, size]);
return { ...otherProps,
className: classes,
isScrollable
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card-body/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedCardBody(props, forwardedRef) {
const {
isScrollable,
...otherProps
} = useCardBody(props);
if (isScrollable) {
return (0,external_wp_element_namespaceObject.createElement)(scrollable_component, extends_extends({}, otherProps, {
ref: forwardedRef
}));
}
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({}, otherProps, {
ref: forwardedRef
}));
}
/**
* `CardBody` renders an optional content area for a `Card`.
* Multiple `CardBody` components can be used within `Card` if needed.
*
* ```jsx
* import { Card, CardBody } from `@wordpress/components`;
*
* <Card>
* <CardBody>
* ...
* </CardBody>
* </Card>
* ```
*/
const CardBody = contextConnect(UnconnectedCardBody, 'CardBody');
/* harmony default export */ var card_body_component = (CardBody);
;// CONCATENATED MODULE: ./node_modules/reakit/es/Separator/Separator.js
// Automatically generated
var SEPARATOR_KEYS = ["orientation"];
var useSeparator = createHook({
name: "Separator",
compose: useRole,
keys: SEPARATOR_KEYS,
useOptions: function useOptions(_ref) {
var _ref$orientation = _ref.orientation,
orientation = _ref$orientation === void 0 ? "horizontal" : _ref$orientation,
options = _objectWithoutPropertiesLoose(_ref, ["orientation"]);
return _objectSpread2({
orientation: orientation
}, options);
},
useProps: function useProps(options, htmlProps) {
return _objectSpread2({
role: "separator",
"aria-orientation": options.orientation
}, htmlProps);
}
});
var Separator = createComponent({
as: "hr",
memo: true,
useHook: useSeparator
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/divider/styles.js
function divider_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const MARGIN_DIRECTIONS = {
vertical: {
start: 'marginLeft',
end: 'marginRight'
},
horizontal: {
start: 'marginTop',
end: 'marginBottom'
}
}; // Renders the correct margins given the Divider's `orientation` and the writing direction.
// When both the generic `margin` and the specific `marginStart|marginEnd` props are defined,
// the latter will take priority.
const renderMargin = _ref2 => {
let {
'aria-orientation': orientation = 'horizontal',
margin,
marginStart,
marginEnd
} = _ref2;
return /*#__PURE__*/emotion_react_browser_esm_css(rtl({
[MARGIN_DIRECTIONS[orientation].start]: space(marginStart !== null && marginStart !== void 0 ? marginStart : margin),
[MARGIN_DIRECTIONS[orientation].end]: space(marginEnd !== null && marginEnd !== void 0 ? marginEnd : margin)
})(), true ? "" : 0, true ? "" : 0);
};
var styles_ref = true ? {
name: "1u4hpl4",
styles: "display:inline"
} : 0;
const renderDisplay = _ref3 => {
let {
'aria-orientation': orientation = 'horizontal'
} = _ref3;
return orientation === 'vertical' ? styles_ref : undefined;
};
const renderBorder = _ref4 => {
let {
'aria-orientation': orientation = 'horizontal'
} = _ref4;
return /*#__PURE__*/emotion_react_browser_esm_css({
[orientation === 'vertical' ? 'borderRight' : 'borderBottom']: '1px solid currentColor'
}, true ? "" : 0, true ? "" : 0);
};
const renderSize = _ref5 => {
let {
'aria-orientation': orientation = 'horizontal'
} = _ref5;
return /*#__PURE__*/emotion_react_browser_esm_css({
height: orientation === 'vertical' ? 'auto' : 0,
width: orientation === 'vertical' ? 0 : 'auto'
}, true ? "" : 0, true ? "" : 0);
};
const DividerView = createStyled("hr", true ? {
target: "e19on6iw0"
} : 0)("border:0;margin:0;", renderDisplay, " ", renderBorder, " ", renderSize, " ", renderMargin, ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/divider/component.js
/**
* External dependencies
*/
// eslint-disable-next-line no-restricted-imports
/**
* Internal dependencies
*/
function UnconnectedDivider(props, forwardedRef) {
const contextProps = useContextSystem(props, 'Divider');
return (0,external_wp_element_namespaceObject.createElement)(Separator, extends_extends({
as: DividerView
}, contextProps, {
ref: forwardedRef
}));
}
/**
* `Divider` is a layout component that separates groups of related content.
*
* ```js
* import {
* __experimentalDivider as Divider,
* __experimentalText as Text,
* __experimentalVStack as VStack,
* } from `@wordpress/components`;
*
* function Example() {
* return (
* <VStack spacing={4}>
* <Text>Some text here</Text>
* <Divider />
* <Text>Some more text here</Text>
* </VStack>
* );
* }
* ```
*/
const component_Divider = contextConnect(UnconnectedDivider, 'Divider');
/* harmony default export */ var divider_component = (component_Divider);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card-divider/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useCardDivider(props) {
const {
className,
...otherProps
} = useContextSystem(props, 'CardDivider');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => cx(Divider, borderColor, // This classname is added for legacy compatibility reasons.
'components-card__divider', className), [className, cx]);
return { ...otherProps,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card-divider/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedCardDivider(props, forwardedRef) {
const dividerProps = useCardDivider(props);
return (0,external_wp_element_namespaceObject.createElement)(divider_component, extends_extends({}, dividerProps, {
ref: forwardedRef
}));
}
/**
* `CardDivider` renders an optional divider within a `Card`.
* It is typically used to divide multiple `CardBody` components from each other.
*
* ```jsx
* import { Card, CardBody, CardDivider } from `@wordpress/components`;
*
* <Card>
* <CardBody>...</CardBody>
* <CardDivider />
* <CardBody>...</CardBody>
* </Card>
* ```
*/
const CardDivider = contextConnect(UnconnectedCardDivider, 'CardDivider');
/* harmony default export */ var card_divider_component = (CardDivider);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card-footer/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useCardFooter(props) {
const {
className,
justify,
isBorderless = false,
isShady = false,
size = 'medium',
...otherProps
} = useContextSystem(props, 'CardFooter');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => cx(Footer, borderRadius, borderColor, cardPaddings[size], isBorderless && borderless, isShady && shady, // This classname is added for legacy compatibility reasons.
'components-card__footer', className), [className, cx, isBorderless, isShady, size]);
return { ...otherProps,
className: classes,
justify
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card-footer/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedCardFooter(props, forwardedRef) {
const footerProps = useCardFooter(props);
return (0,external_wp_element_namespaceObject.createElement)(flex_component, extends_extends({}, footerProps, {
ref: forwardedRef
}));
}
/**
* `CardFooter` renders an optional footer within a `Card`.
*
* ```jsx
* import { Card, CardBody, CardFooter } from `@wordpress/components`;
*
* <Card>
* <CardBody>...</CardBody>
* <CardFooter>...</CardFooter>
* </Card>
* ```
*/
const CardFooter = contextConnect(UnconnectedCardFooter, 'CardFooter');
/* harmony default export */ var card_footer_component = (CardFooter);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card-header/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useCardHeader(props) {
const {
className,
isBorderless = false,
isShady = false,
size = 'medium',
...otherProps
} = useContextSystem(props, 'CardHeader');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => cx(styles_Header, borderRadius, borderColor, cardPaddings[size], isBorderless && borderless, isShady && shady, // This classname is added for legacy compatibility reasons.
'components-card__header', className), [className, cx, isBorderless, isShady, size]);
return { ...otherProps,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card-header/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedCardHeader(props, forwardedRef) {
const headerProps = useCardHeader(props);
return (0,external_wp_element_namespaceObject.createElement)(flex_component, extends_extends({}, headerProps, {
ref: forwardedRef
}));
}
/**
* `CardHeader` renders an optional header within a `Card`.
*
* ```jsx
* import { Card, CardBody, CardHeader } from `@wordpress/components`;
*
* <Card>
* <CardHeader>...</CardHeader>
* <CardBody>...</CardBody>
* </Card>
* ```
*/
const CardHeader = contextConnect(UnconnectedCardHeader, 'CardHeader');
/* harmony default export */ var card_header_component = (CardHeader);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card-media/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useCardMedia(props) {
const {
className,
...otherProps
} = useContextSystem(props, 'CardMedia');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => cx(Media, borderRadius, // This classname is added for legacy compatibility reasons.
'components-card__media', className), [className, cx]);
return { ...otherProps,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/card/card-media/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedCardMedia(props, forwardedRef) {
const cardMediaProps = useCardMedia(props);
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({}, cardMediaProps, {
ref: forwardedRef
}));
}
/**
* `CardMedia` provides a container for media elements within a `Card`.
*
* @example
* ```jsx
* import { Card, CardBody, CardMedia } from '@wordpress/components';
*
* const Example = () => (
* <Card>
* <CardMedia>
* <img src="..." />
* </CardMedia>
* <CardBody>...</CardBody>
* </Card>
* );
* ```
*/
const CardMedia = contextConnect(UnconnectedCardMedia, 'CardMedia');
/* harmony default export */ var card_media_component = (CardMedia);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/checkbox-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Checkboxes allow the user to select one or more items from a set.
*
* ```jsx
* import { CheckboxControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyCheckboxControl = () => {
* const [ isChecked, setChecked ] = useState( true );
* return (
* <CheckboxControl
* label="Is author"
* help="Is the user a author or not?"
* checked={ isChecked }
* onChange={ setChecked }
* />
* );
* };
* ```
*/
function CheckboxControl(props) {
const {
__nextHasNoMarginBottom,
label,
className,
heading,
checked,
indeterminate,
help,
onChange,
...additionalProps
} = props;
if (heading) {
external_wp_deprecated_default()('`heading` prop in `CheckboxControl`', {
alternative: 'a separate element to implement a heading',
since: '5.8'
});
}
const [showCheckedIcon, setShowCheckedIcon] = (0,external_wp_element_namespaceObject.useState)(false);
const [showIndeterminateIcon, setShowIndeterminateIcon] = (0,external_wp_element_namespaceObject.useState)(false); // Run the following callback every time the `ref` (and the additional
// dependencies) change.
const ref = (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
if (!node) {
return;
} // It cannot be set using an HTML attribute.
node.indeterminate = !!indeterminate;
setShowCheckedIcon(node.matches(':checked'));
setShowIndeterminateIcon(node.matches(':indeterminate'));
}, [checked, indeterminate]);
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(CheckboxControl);
const id = `inspector-checkbox-control-${instanceId}`;
const onChangeValue = event => onChange(event.target.checked);
return (0,external_wp_element_namespaceObject.createElement)(base_control, {
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
label: heading,
id: id,
help: help,
className: classnames_default()('components-checkbox-control', className)
}, (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-checkbox-control__input-container"
}, (0,external_wp_element_namespaceObject.createElement)("input", extends_extends({
ref: ref,
id: id,
className: "components-checkbox-control__input",
type: "checkbox",
value: "1",
onChange: onChangeValue,
checked: checked,
"aria-describedby": !!help ? id + '__help' : undefined
}, additionalProps)), showIndeterminateIcon ? (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, {
icon: library_reset,
className: "components-checkbox-control__indeterminate",
role: "presentation"
}) : null, showCheckedIcon ? (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, {
icon: library_check,
className: "components-checkbox-control__checked",
role: "presentation"
}) : null), (0,external_wp_element_namespaceObject.createElement)("label", {
className: "components-checkbox-control__label",
htmlFor: id
}, label));
}
/* harmony default export */ var checkbox_control = (CheckboxControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/clipboard-button/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const TIMEOUT = 4000;
/**
* @param {Object} props
* @param {string} [props.className]
* @param {import('react').ReactNode} props.children
* @param {() => void} props.onCopy
* @param {() => void} [props.onFinishCopy]
* @param {string} props.text
*/
function ClipboardButton(_ref) {
let {
className,
children,
onCopy,
onFinishCopy,
text,
...buttonProps
} = _ref;
external_wp_deprecated_default()('wp.components.ClipboardButton', {
since: '5.8',
alternative: 'wp.compose.useCopyToClipboard'
});
/** @type {import('react').MutableRefObject<ReturnType<setTimeout> | undefined>} */
const timeoutId = (0,external_wp_element_namespaceObject.useRef)();
const ref = (0,external_wp_compose_namespaceObject.useCopyToClipboard)(text, () => {
onCopy(); // @ts-expect-error: Should check if .current is defined, but not changing because this component is deprecated.
clearTimeout(timeoutId.current);
if (onFinishCopy) {
timeoutId.current = setTimeout(() => onFinishCopy(), TIMEOUT);
}
});
(0,external_wp_element_namespaceObject.useEffect)(() => {
// @ts-expect-error: Should check if .current is defined, but not changing because this component is deprecated.
clearTimeout(timeoutId.current);
}, []);
const classes = classnames_default()('components-clipboard-button', className); // Workaround for inconsistent behavior in Safari, where <textarea> is not
// the document.activeElement at the moment when the copy event fires.
// This causes documentHasSelection() in the copy-handler component to
// mistakenly override the ClipboardButton, and copy a serialized string
// of the current block instead.
/** @type {import('react').ClipboardEventHandler<HTMLButtonElement>} */
const focusOnCopyEventTarget = event => {
// @ts-expect-error: Should be currentTarget, but not changing because this component is deprecated.
event.target.focus();
};
return (0,external_wp_element_namespaceObject.createElement)(build_module_button, extends_extends({}, buttonProps, {
className: classes,
ref: ref,
onCopy: focusOnCopyEventTarget
}), children);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/more-vertical.js
/**
* WordPress dependencies
*/
const moreVertical = (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: "M13 19h-2v-2h2v2zm0-6h-2v-2h2v2zm0-6h-2V5h2v2z"
}));
/* harmony default export */ var more_vertical = (moreVertical);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/item-group/styles.js
function item_group_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const unstyledButton = /*#__PURE__*/emotion_react_browser_esm_css("appearance:none;border:1px solid transparent;cursor:pointer;background:none;text-align:start;&:hover{color:", COLORS.ui.theme, ";}&:focus{background-color:transparent;color:", COLORS.ui.theme, ";border-color:", COLORS.ui.theme, ";outline:3px solid transparent;}" + ( true ? "" : 0), true ? "" : 0);
const itemWrapper = true ? {
name: "1bcj5ek",
styles: "width:100%;display:block"
} : 0;
const item = true ? {
name: "150ruhm",
styles: "box-sizing:border-box;width:100%;display:block;margin:0;color:inherit"
} : 0;
const bordered = /*#__PURE__*/emotion_react_browser_esm_css("border:1px solid ", config_values.surfaceBorderColor, ";" + ( true ? "" : 0), true ? "" : 0);
const separated = /*#__PURE__*/emotion_react_browser_esm_css(">*:not( marquee )>*{border-bottom:1px solid ", config_values.surfaceBorderColor, ";}>*:last-of-type>*:not( :focus ){border-bottom-color:transparent;}" + ( true ? "" : 0), true ? "" : 0);
const styles_borderRadius = config_values.controlBorderRadius;
const styles_spacedAround = /*#__PURE__*/emotion_react_browser_esm_css("border-radius:", styles_borderRadius, ";" + ( true ? "" : 0), true ? "" : 0);
const styles_rounded = /*#__PURE__*/emotion_react_browser_esm_css("border-radius:", styles_borderRadius, ";>*:first-of-type>*{border-top-left-radius:", styles_borderRadius, ";border-top-right-radius:", styles_borderRadius, ";}>*:last-of-type>*{border-bottom-left-radius:", styles_borderRadius, ";border-bottom-right-radius:", styles_borderRadius, ";}" + ( true ? "" : 0), true ? "" : 0);
const baseFontHeight = `calc(${config_values.fontSize} * ${config_values.fontLineHeightBase})`;
/*
* Math:
* - Use the desired height as the base value
* - Subtract the computed height of (default) text
* - Subtract the effects of border
* - Divide the calculated number by 2, in order to get an individual top/bottom padding
*/
const paddingY = `calc((${config_values.controlHeight} - ${baseFontHeight} - 2px) / 2)`;
const paddingYSmall = `calc((${config_values.controlHeightSmall} - ${baseFontHeight} - 2px) / 2)`;
const paddingYLarge = `calc((${config_values.controlHeightLarge} - ${baseFontHeight} - 2px) / 2)`;
const itemSizes = {
small: /*#__PURE__*/emotion_react_browser_esm_css("padding:", paddingYSmall, " ", config_values.controlPaddingXSmall, ";" + ( true ? "" : 0), true ? "" : 0),
medium: /*#__PURE__*/emotion_react_browser_esm_css("padding:", paddingY, " ", config_values.controlPaddingX, ";" + ( true ? "" : 0), true ? "" : 0),
large: /*#__PURE__*/emotion_react_browser_esm_css("padding:", paddingYLarge, " ", config_values.controlPaddingXLarge, ";" + ( true ? "" : 0), true ? "" : 0)
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/item-group/item-group/hook.js
/**
* Internal dependencies
*/
/**
* Internal dependencies
*/
function useItemGroup(props) {
const {
className,
isBordered = false,
isRounded = true,
isSeparated = false,
role = 'list',
...otherProps
} = useContextSystem(props, 'ItemGroup');
const cx = useCx();
const classes = cx(isBordered && bordered, isSeparated && separated, isRounded && styles_rounded, className);
return {
isBordered,
className: classes,
role,
isSeparated,
...otherProps
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/item-group/context.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const ItemGroupContext = (0,external_wp_element_namespaceObject.createContext)({
size: 'medium'
});
const useItemGroupContext = () => (0,external_wp_element_namespaceObject.useContext)(ItemGroupContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/item-group/item-group/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedItemGroup(props, forwardedRef) {
const {
isBordered,
isSeparated,
size: sizeProp,
...otherProps
} = useItemGroup(props);
const {
size: contextSize
} = useItemGroupContext();
const spacedAround = !isBordered && !isSeparated;
const size = sizeProp || contextSize;
const contextValue = {
spacedAround,
size
};
return (0,external_wp_element_namespaceObject.createElement)(ItemGroupContext.Provider, {
value: contextValue
}, (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({}, otherProps, {
ref: forwardedRef
})));
}
/**
* `ItemGroup` displays a list of `Item`s grouped and styled together.
*
* @example
* ```jsx
* import {
* __experimentalItemGroup as ItemGroup,
* __experimentalItem as Item,
* } from '@wordpress/components';
*
* function Example() {
* return (
* <ItemGroup>
* <Item>Code</Item>
* <Item>is</Item>
* <Item>Poetry</Item>
* </ItemGroup>
* );
* }
* ```
*/
const ItemGroup = contextConnect(UnconnectedItemGroup, 'ItemGroup');
/* harmony default export */ var item_group_component = (ItemGroup);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/custom-gradient-picker/gradient-bar/constants.js
const GRADIENT_MARKERS_WIDTH = 16;
const INSERT_POINT_WIDTH = 16;
const MINIMUM_DISTANCE_BETWEEN_INSERTER_AND_POINT = 10;
const MINIMUM_DISTANCE_BETWEEN_POINTS = 0;
const MINIMUM_SIGNIFICANT_MOVE = 5;
const KEYBOARD_CONTROL_POINT_VARIATION = MINIMUM_DISTANCE_BETWEEN_INSERTER_AND_POINT;
const MINIMUM_DISTANCE_BETWEEN_INSERTER_AND_MARKER = (INSERT_POINT_WIDTH + GRADIENT_MARKERS_WIDTH) / 2;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/custom-gradient-picker/gradient-bar/utils.js
/**
* Internal dependencies
*/
/**
* Control point for the gradient bar.
*
* @typedef {Object} ControlPoint
* @property {string} color Color of the control point.
* @property {number} position Integer position of the control point as a percentage.
*/
/**
* Color as parsed from the gradient by gradient-parser.
*
* @typedef {Object} Color
* @property {string} r Red component.
* @property {string} g Green component.
* @property {string} b Green component.
* @property {string} [a] Optional alpha component.
*/
/**
* Clamps a number between 0 and 100.
*
* @param {number} value Value to clamp.
*
* @return {number} Value clamped between 0 and 100.
*/
function clampPercent(value) {
return Math.max(0, Math.min(100, value));
}
/**
* Check if a control point is overlapping with another.
*
* @param {ControlPoint[]} value Array of control points.
* @param {number} initialIndex Index of the position to test.
* @param {number} newPosition New position of the control point.
* @param {number} minDistance Distance considered to be overlapping.
*
* @return {boolean} True if the point is overlapping.
*/
function isOverlapping(value, initialIndex, newPosition) {
let minDistance = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : MINIMUM_DISTANCE_BETWEEN_POINTS;
const initialPosition = value[initialIndex].position;
const minPosition = Math.min(initialPosition, newPosition);
const maxPosition = Math.max(initialPosition, newPosition);
return value.some((_ref, index) => {
let {
position
} = _ref;
return index !== initialIndex && (Math.abs(position - newPosition) < minDistance || minPosition < position && position < maxPosition);
});
}
/**
* Adds a control point from an array and returns the new array.
*
* @param {ControlPoint[]} points Array of control points.
* @param {number} position Position to insert the new point.
* @param {Color} color Color to update the control point at index.
*
* @return {ControlPoint[]} New array of control points.
*/
function addControlPoint(points, position, color) {
const nextIndex = points.findIndex(point => point.position > position);
const newPoint = {
color,
position
};
const newPoints = points.slice();
newPoints.splice(nextIndex - 1, 0, newPoint);
return newPoints;
}
/**
* Removes a control point from an array and returns the new array.
*
* @param {ControlPoint[]} points Array of control points.
* @param {number} index Index to remove.
*
* @return {ControlPoint[]} New array of control points.
*/
function removeControlPoint(points, index) {
return points.filter((point, pointIndex) => {
return pointIndex !== index;
});
}
/**
* Updates a control point from an array and returns the new array.
*
* @param {ControlPoint[]} points Array of control points.
* @param {number} index Index to update.
* @param {ControlPoint[]} newPoint New control point to replace the index.
*
* @return {ControlPoint[]} New array of control points.
*/
function updateControlPoint(points, index, newPoint) {
const newValue = points.slice();
newValue[index] = newPoint;
return newValue;
}
/**
* Updates the position of a control point from an array and returns the new array.
*
* @param {ControlPoint[]} points Array of control points.
* @param {number} index Index to update.
* @param {number} newPosition Position to move the control point at index.
*
* @return {ControlPoint[]} New array of control points.
*/
function updateControlPointPosition(points, index, newPosition) {
if (isOverlapping(points, index, newPosition)) {
return points;
}
const newPoint = { ...points[index],
position: newPosition
};
return updateControlPoint(points, index, newPoint);
}
/**
* Updates the position of a control point from an array and returns the new array.
*
* @param {ControlPoint[]} points Array of control points.
* @param {number} index Index to update.
* @param {Color} newColor Color to update the control point at index.
*
* @return {ControlPoint[]} New array of control points.
*/
function updateControlPointColor(points, index, newColor) {
const newPoint = { ...points[index],
color: newColor
};
return updateControlPoint(points, index, newPoint);
}
/**
* Updates the position of a control point from an array and returns the new array.
*
* @param {ControlPoint[]} points Array of control points.
* @param {number} position Position of the color stop.
* @param {string} newColor Color to update the control point at index.
*
* @return {ControlPoint[]} New array of control points.
*/
function updateControlPointColorByPosition(points, position, newColor) {
const index = points.findIndex(point => point.position === position);
return updateControlPointColor(points, index, newColor);
}
/**
* Gets the horizontal coordinate when dragging a control point with the mouse.
*
* @param {number} mouseXCoordinate Horizontal coordinate of the mouse position.
* @param {Element} containerElement Container for the gradient picker.
*
* @return {number | undefined} Whole number percentage from the left.
*/
function getHorizontalRelativeGradientPosition(mouseXCoordinate, containerElement) {
if (!containerElement) {
return;
}
const {
x,
width
} = containerElement.getBoundingClientRect();
const absolutePositionValue = mouseXCoordinate - x;
return Math.round(clampPercent(absolutePositionValue * 100 / width));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/custom-gradient-picker/gradient-bar/control-points.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ControlPointButton(_ref) {
let {
isOpen,
position,
color,
...additionalProps
} = _ref;
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(ControlPointButton);
const descriptionId = `components-custom-gradient-picker__control-point-button-description-${instanceId}`;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(build_module_button, extends_extends({
"aria-label": (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %1$s: gradient position e.g: 70, %2$s: gradient color code e.g: rgb(52,121,151).
(0,external_wp_i18n_namespaceObject.__)('Gradient control point at position %1$s%% with color code %2$s.'), position, color),
"aria-describedby": descriptionId,
"aria-haspopup": "true",
"aria-expanded": isOpen,
className: classnames_default()('components-custom-gradient-picker__control-point-button', {
'is-active': isOpen
})
}, additionalProps)), (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, {
id: descriptionId
}, (0,external_wp_i18n_namespaceObject.__)('Use your left or right arrow keys or drag and drop with the mouse to change the gradient position. Press the button to change the color or remove the control point.')));
}
function GradientColorPickerDropdown(_ref2) {
let {
isRenderedInSidebar,
className,
...props
} = _ref2;
// Open the popover below the gradient control/insertion point
const popoverProps = (0,external_wp_element_namespaceObject.useMemo)(() => ({
placement: 'bottom',
offset: 8
}), []);
const mergedClassName = classnames_default()('components-custom-gradient-picker__control-point-dropdown', className);
return (0,external_wp_element_namespaceObject.createElement)(CustomColorPickerDropdown, extends_extends({
isRenderedInSidebar: isRenderedInSidebar,
popoverProps: popoverProps,
className: mergedClassName
}, props));
}
function ControlPoints(_ref3) {
let {
disableRemove,
disableAlpha,
gradientPickerDomRef,
ignoreMarkerPosition,
value: controlPoints,
onChange,
onStartControlPointChange,
onStopControlPointChange,
__experimentalIsRenderedInSidebar
} = _ref3;
const controlPointMoveState = (0,external_wp_element_namespaceObject.useRef)();
const onMouseMove = event => {
const relativePosition = getHorizontalRelativeGradientPosition(event.clientX, gradientPickerDomRef.current);
const {
initialPosition,
index,
significantMoveHappened
} = controlPointMoveState.current;
if (!significantMoveHappened && Math.abs(initialPosition - relativePosition) >= MINIMUM_SIGNIFICANT_MOVE) {
controlPointMoveState.current.significantMoveHappened = true;
}
onChange(updateControlPointPosition(controlPoints, index, relativePosition));
};
const cleanEventListeners = () => {
if (window && window.removeEventListener && controlPointMoveState.current && controlPointMoveState.current.listenersActivated) {
window.removeEventListener('mousemove', onMouseMove);
window.removeEventListener('mouseup', cleanEventListeners);
onStopControlPointChange();
controlPointMoveState.current.listenersActivated = false;
}
}; // Adding `cleanEventListeners` to the dependency array below requires the function itself to be wrapped in a `useCallback`
// This memoization would prevent the event listeners from being properly cleaned.
// Instead, we'll pass a ref to the function in our `useEffect` so `cleanEventListeners` itself is no longer a dependency.
const cleanEventListenersRef = (0,external_wp_element_namespaceObject.useRef)();
cleanEventListenersRef.current = cleanEventListeners;
(0,external_wp_element_namespaceObject.useEffect)(() => {
return () => {
cleanEventListenersRef.current();
};
}, []);
return controlPoints.map((point, index) => {
const initialPosition = point === null || point === void 0 ? void 0 : point.position;
return ignoreMarkerPosition !== initialPosition && (0,external_wp_element_namespaceObject.createElement)(GradientColorPickerDropdown, {
isRenderedInSidebar: __experimentalIsRenderedInSidebar,
key: index,
onClose: onStopControlPointChange,
renderToggle: _ref4 => {
let {
isOpen,
onToggle
} = _ref4;
return (0,external_wp_element_namespaceObject.createElement)(ControlPointButton, {
key: index,
onClick: () => {
if (controlPointMoveState.current && controlPointMoveState.current.significantMoveHappened) {
return;
}
if (isOpen) {
onStopControlPointChange();
} else {
onStartControlPointChange();
}
onToggle();
},
onMouseDown: () => {
if (window && window.addEventListener) {
controlPointMoveState.current = {
initialPosition,
index,
significantMoveHappened: false,
listenersActivated: true
};
onStartControlPointChange();
window.addEventListener('mousemove', onMouseMove);
window.addEventListener('mouseup', cleanEventListeners);
}
},
onKeyDown: event => {
if (event.code === 'ArrowLeft') {
// Stop propagation of the key press event to avoid focus moving
// to another editor area.
event.stopPropagation();
onChange(updateControlPointPosition(controlPoints, index, clampPercent(point.position - KEYBOARD_CONTROL_POINT_VARIATION)));
} else if (event.code === 'ArrowRight') {
// Stop propagation of the key press event to avoid focus moving
// to another editor area.
event.stopPropagation();
onChange(updateControlPointPosition(controlPoints, index, clampPercent(point.position + KEYBOARD_CONTROL_POINT_VARIATION)));
}
},
isOpen: isOpen,
position: point.position,
color: point.color
});
},
renderContent: _ref5 => {
let {
onClose
} = _ref5;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(LegacyAdapter, {
enableAlpha: !disableAlpha,
color: point.color,
onChange: color => {
onChange(updateControlPointColor(controlPoints, index, colord_w(color).toRgbString()));
}
}), !disableRemove && controlPoints.length > 2 && (0,external_wp_element_namespaceObject.createElement)(h_stack_component, {
className: "components-custom-gradient-picker__remove-control-point-wrapper",
alignment: "center"
}, (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
onClick: () => {
onChange(removeControlPoint(controlPoints, index));
onClose();
},
variant: "link"
}, (0,external_wp_i18n_namespaceObject.__)('Remove Control Point'))));
},
style: {
left: `${point.position}%`,
transform: 'translateX( -50% )'
}
});
});
}
function InsertPoint(_ref6) {
let {
value: controlPoints,
onChange,
onOpenInserter,
onCloseInserter,
insertPosition,
disableAlpha,
__experimentalIsRenderedInSidebar
} = _ref6;
const [alreadyInsertedPoint, setAlreadyInsertedPoint] = (0,external_wp_element_namespaceObject.useState)(false);
return (0,external_wp_element_namespaceObject.createElement)(GradientColorPickerDropdown, {
isRenderedInSidebar: __experimentalIsRenderedInSidebar,
className: "components-custom-gradient-picker__inserter",
onClose: () => {
onCloseInserter();
},
renderToggle: _ref7 => {
let {
isOpen,
onToggle
} = _ref7;
return (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
"aria-expanded": isOpen,
"aria-haspopup": "true",
onClick: () => {
if (isOpen) {
onCloseInserter();
} else {
setAlreadyInsertedPoint(false);
onOpenInserter();
}
onToggle();
},
className: "components-custom-gradient-picker__insert-point-dropdown",
icon: library_plus
});
},
renderContent: () => (0,external_wp_element_namespaceObject.createElement)(LegacyAdapter, {
enableAlpha: !disableAlpha,
onChange: color => {
if (!alreadyInsertedPoint) {
onChange(addControlPoint(controlPoints, insertPosition, colord_w(color).toRgbString()));
setAlreadyInsertedPoint(true);
} else {
onChange(updateControlPointColorByPosition(controlPoints, insertPosition, colord_w(color).toRgbString()));
}
}
}),
style: insertPosition !== null ? {
left: `${insertPosition}%`,
transform: 'translateX( -50% )'
} : undefined
});
}
ControlPoints.InsertPoint = InsertPoint;
/* harmony default export */ var control_points = (ControlPoints);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/custom-gradient-picker/gradient-bar/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function customGradientBarReducer(state, action) {
switch (action.type) {
case 'MOVE_INSERTER':
if (state.id === 'IDLE' || state.id === 'MOVING_INSERTER') {
return {
id: 'MOVING_INSERTER',
insertPosition: action.insertPosition
};
}
break;
case 'STOP_INSERTER_MOVE':
if (state.id === 'MOVING_INSERTER') {
return {
id: 'IDLE'
};
}
break;
case 'OPEN_INSERTER':
if (state.id === 'MOVING_INSERTER') {
return {
id: 'INSERTING_CONTROL_POINT',
insertPosition: state.insertPosition
};
}
break;
case 'CLOSE_INSERTER':
if (state.id === 'INSERTING_CONTROL_POINT') {
return {
id: 'IDLE'
};
}
break;
case 'START_CONTROL_CHANGE':
if (state.id === 'IDLE') {
return {
id: 'MOVING_CONTROL_POINT'
};
}
break;
case 'STOP_CONTROL_CHANGE':
if (state.id === 'MOVING_CONTROL_POINT') {
return {
id: 'IDLE'
};
}
break;
}
return state;
}
const customGradientBarReducerInitialState = {
id: 'IDLE'
};
function CustomGradientBar(_ref) {
let {
background,
hasGradient,
value: controlPoints,
onChange,
disableInserter = false,
disableAlpha = false,
__experimentalIsRenderedInSidebar
} = _ref;
const gradientMarkersContainerDomRef = (0,external_wp_element_namespaceObject.useRef)();
const [gradientBarState, gradientBarStateDispatch] = (0,external_wp_element_namespaceObject.useReducer)(customGradientBarReducer, customGradientBarReducerInitialState);
const onMouseEnterAndMove = event => {
const insertPosition = getHorizontalRelativeGradientPosition(event.clientX, gradientMarkersContainerDomRef.current); // If the insert point is close to an existing control point don't show it.
if (controlPoints.some(_ref2 => {
let {
position
} = _ref2;
return Math.abs(insertPosition - position) < MINIMUM_DISTANCE_BETWEEN_INSERTER_AND_POINT;
})) {
if (gradientBarState.id === 'MOVING_INSERTER') {
gradientBarStateDispatch({
type: 'STOP_INSERTER_MOVE'
});
}
return;
}
gradientBarStateDispatch({
type: 'MOVE_INSERTER',
insertPosition
});
};
const onMouseLeave = () => {
gradientBarStateDispatch({
type: 'STOP_INSERTER_MOVE'
});
};
const isMovingInserter = gradientBarState.id === 'MOVING_INSERTER';
const isInsertingControlPoint = gradientBarState.id === 'INSERTING_CONTROL_POINT';
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('components-custom-gradient-picker__gradient-bar', {
'has-gradient': hasGradient
}),
onMouseEnter: onMouseEnterAndMove,
onMouseMove: onMouseEnterAndMove,
style: {
background
},
onMouseLeave: onMouseLeave
}, (0,external_wp_element_namespaceObject.createElement)("div", {
ref: gradientMarkersContainerDomRef,
className: "components-custom-gradient-picker__markers-container"
}, !disableInserter && (isMovingInserter || isInsertingControlPoint) && (0,external_wp_element_namespaceObject.createElement)(control_points.InsertPoint, {
__experimentalIsRenderedInSidebar: __experimentalIsRenderedInSidebar,
disableAlpha: disableAlpha,
insertPosition: gradientBarState.insertPosition,
value: controlPoints,
onChange: onChange,
onOpenInserter: () => {
gradientBarStateDispatch({
type: 'OPEN_INSERTER'
});
},
onCloseInserter: () => {
gradientBarStateDispatch({
type: 'CLOSE_INSERTER'
});
}
}), (0,external_wp_element_namespaceObject.createElement)(control_points, {
__experimentalIsRenderedInSidebar: __experimentalIsRenderedInSidebar,
disableAlpha: disableAlpha,
disableRemove: disableInserter,
gradientPickerDomRef: gradientMarkersContainerDomRef,
ignoreMarkerPosition: isInsertingControlPoint ? gradientBarState.insertPosition : undefined,
value: controlPoints,
onChange: onChange,
onStartControlPointChange: () => {
gradientBarStateDispatch({
type: 'START_CONTROL_CHANGE'
});
},
onStopControlPointChange: () => {
gradientBarStateDispatch({
type: 'STOP_CONTROL_CHANGE'
});
}
})));
}
// EXTERNAL MODULE: ./node_modules/gradient-parser/build/node.js
var build_node = __webpack_require__(7115);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/custom-gradient-picker/constants.js
/**
* WordPress dependencies
*/
const DEFAULT_GRADIENT = 'linear-gradient(135deg, rgba(6, 147, 227, 1) 0%, rgb(155, 81, 224) 100%)';
const DEFAULT_LINEAR_GRADIENT_ANGLE = 180;
const HORIZONTAL_GRADIENT_ORIENTATION = {
type: 'angular',
value: 90
};
const GRADIENT_OPTIONS = [{
value: 'linear-gradient',
label: (0,external_wp_i18n_namespaceObject.__)('Linear')
}, {
value: 'radial-gradient',
label: (0,external_wp_i18n_namespaceObject.__)('Radial')
}];
const DIRECTIONAL_ORIENTATION_ANGLE_MAP = {
top: 0,
'top right': 45,
'right top': 45,
right: 90,
'right bottom': 135,
'bottom right': 135,
bottom: 180,
'bottom left': 225,
'left bottom': 225,
left: 270,
'top left': 315,
'left top': 315
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/custom-gradient-picker/serializer.js
function serializeGradientColor(_ref) {
let {
type,
value
} = _ref;
if (type === 'literal') {
return value;
}
if (type === 'hex') {
return `#${value}`;
}
return `${type}(${value.join(',')})`;
}
function serializeGradientPosition(position) {
if (!position) {
return '';
}
const {
value,
type
} = position;
return `${value}${type}`;
}
function serializeGradientColorStop(_ref2) {
let {
type,
value,
length
} = _ref2;
return `${serializeGradientColor({
type,
value
})} ${serializeGradientPosition(length)}`;
}
function serializeGradientOrientation(orientation) {
if (!orientation || orientation.type !== 'angular') {
return;
}
return `${orientation.value}deg`;
}
function serializeGradient(_ref3) {
let {
type,
orientation,
colorStops
} = _ref3;
const serializedOrientation = serializeGradientOrientation(orientation);
const serializedColorStops = colorStops.sort((colorStop1, colorStop2) => {
var _colorStop1$length$va, _colorStop1$length, _colorStop2$length$va, _colorStop2$length;
return ((_colorStop1$length$va = colorStop1 === null || colorStop1 === void 0 ? void 0 : (_colorStop1$length = colorStop1.length) === null || _colorStop1$length === void 0 ? void 0 : _colorStop1$length.value) !== null && _colorStop1$length$va !== void 0 ? _colorStop1$length$va : 0) - ((_colorStop2$length$va = colorStop2 === null || colorStop2 === void 0 ? void 0 : (_colorStop2$length = colorStop2.length) === null || _colorStop2$length === void 0 ? void 0 : _colorStop2$length.value) !== null && _colorStop2$length$va !== void 0 ? _colorStop2$length$va : 0);
}).map(serializeGradientColorStop);
return `${type}(${[serializedOrientation, ...serializedColorStops].filter(Boolean).join(',')})`;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/custom-gradient-picker/utils.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
k([names]);
function getLinearGradientRepresentation(gradientAST) {
return serializeGradient({
type: 'linear-gradient',
orientation: HORIZONTAL_GRADIENT_ORIENTATION,
colorStops: gradientAST.colorStops
});
}
function hasUnsupportedLength(item) {
return item.length === undefined || item.length.type !== '%';
}
function getGradientAstWithDefault(value) {
var _gradientAST$orientat;
// gradientAST will contain the gradient AST as parsed by gradient-parser npm module.
// More information of its structure available at https://www.npmjs.com/package/gradient-parser#ast.
let gradientAST;
try {
gradientAST = build_node.parse(value)[0];
gradientAST.value = value;
} catch (error) {
gradientAST = build_node.parse(DEFAULT_GRADIENT)[0];
gradientAST.value = DEFAULT_GRADIENT;
}
if (((_gradientAST$orientat = gradientAST.orientation) === null || _gradientAST$orientat === void 0 ? void 0 : _gradientAST$orientat.type) === 'directional') {
gradientAST.orientation.type = 'angular';
gradientAST.orientation.value = DIRECTIONAL_ORIENTATION_ANGLE_MAP[gradientAST.orientation.value].toString();
}
if (gradientAST.colorStops.some(hasUnsupportedLength)) {
const {
colorStops
} = gradientAST;
const step = 100 / (colorStops.length - 1);
colorStops.forEach((stop, index) => {
stop.length = {
value: step * index,
type: '%'
};
});
gradientAST.value = serializeGradient(gradientAST);
}
return gradientAST;
}
function getGradientAstWithControlPoints(gradientAST, newControlPoints) {
return { ...gradientAST,
colorStops: newControlPoints.map(_ref => {
let {
position,
color
} = _ref;
const {
r,
g,
b,
a
} = colord_w(color).toRgb();
return {
length: {
type: '%',
value: position === null || position === void 0 ? void 0 : position.toString()
},
type: a < 1 ? 'rgba' : 'rgb',
value: a < 1 ? [r, g, b, a] : [r, g, b]
};
})
};
}
function getStopCssColor(colorStop) {
switch (colorStop.type) {
case 'hex':
return `#${colorStop.value}`;
case 'literal':
return colorStop.value;
case 'rgb':
case 'rgba':
return `${colorStop.type}(${colorStop.value.join(',')})`;
default:
// Should be unreachable if passing an AST from gradient-parser.
// See https://github.com/rafaelcaricio/gradient-parser#ast.
return 'transparent';
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/custom-gradient-picker/styles/custom-gradient-picker-styles.js
function custom_gradient_picker_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const SelectWrapper = /*#__PURE__*/createStyled(flex_block_component, true ? {
target: "e99xvul1"
} : 0)( true ? {
name: "1gvx10y",
styles: "flex-grow:5"
} : 0);
const AccessoryWrapper = /*#__PURE__*/createStyled(flex_block_component, true ? {
target: "e99xvul0"
} : 0)( true ? {
name: "1gvx10y",
styles: "flex-grow:5"
} : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/custom-gradient-picker/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const GradientAnglePicker = _ref => {
var _gradientAST$orientat, _gradientAST$orientat2;
let {
gradientAST,
hasGradient,
onChange
} = _ref;
const angle = (_gradientAST$orientat = gradientAST === null || gradientAST === void 0 ? void 0 : (_gradientAST$orientat2 = gradientAST.orientation) === null || _gradientAST$orientat2 === void 0 ? void 0 : _gradientAST$orientat2.value) !== null && _gradientAST$orientat !== void 0 ? _gradientAST$orientat : DEFAULT_LINEAR_GRADIENT_ANGLE;
const onAngleChange = newAngle => {
onChange(serializeGradient({ ...gradientAST,
orientation: {
type: 'angular',
value: newAngle
}
}));
};
return (0,external_wp_element_namespaceObject.createElement)(AnglePickerControl, {
__nextHasNoMarginBottom: true,
onChange: onAngleChange,
labelPosition: "top",
value: hasGradient ? angle : ''
});
};
const GradientTypePicker = _ref2 => {
let {
gradientAST,
hasGradient,
onChange
} = _ref2;
const {
type
} = gradientAST;
const onSetLinearGradient = () => {
onChange(serializeGradient({ ...gradientAST,
...(gradientAST.orientation ? {} : {
orientation: HORIZONTAL_GRADIENT_ORIENTATION
}),
type: 'linear-gradient'
}));
};
const onSetRadialGradient = () => {
const {
orientation,
...restGradientAST
} = gradientAST;
onChange(serializeGradient({ ...restGradientAST,
type: 'radial-gradient'
}));
};
const handleOnChange = next => {
if (next === 'linear-gradient') {
onSetLinearGradient();
}
if (next === 'radial-gradient') {
onSetRadialGradient();
}
};
return (0,external_wp_element_namespaceObject.createElement)(select_control, {
__nextHasNoMarginBottom: true,
className: "components-custom-gradient-picker__type-picker",
label: (0,external_wp_i18n_namespaceObject.__)('Type'),
labelPosition: "top",
onChange: handleOnChange,
options: GRADIENT_OPTIONS,
size: "__unstable-large",
value: hasGradient && type
});
};
function CustomGradientPicker(_ref3) {
let {
/** Start opting into the new margin-free styles that will become the default in a future version. */
__nextHasNoMargin = false,
value,
onChange,
__experimentalIsRenderedInSidebar
} = _ref3;
const gradientAST = getGradientAstWithDefault(value); // On radial gradients the bar should display a linear gradient.
// On radial gradients the bar represents a slice of the gradient from the center until the outside.
// On liner gradients the bar represents the color stops from left to right independently of the angle.
const background = getLinearGradientRepresentation(gradientAST);
const hasGradient = gradientAST.value !== DEFAULT_GRADIENT; // Control points color option may be hex from presets, custom colors will be rgb.
// The position should always be a percentage.
const controlPoints = gradientAST.colorStops.map(colorStop => ({
color: getStopCssColor(colorStop),
position: parseInt(colorStop.length.value)
}));
if (!__nextHasNoMargin) {
external_wp_deprecated_default()('Outer margin styles for wp.components.CustomGradientPicker', {
since: '6.1',
version: '6.4',
hint: 'Set the `__nextHasNoMargin` prop to true to start opting into the new styles, which will become the default in a future version'
});
}
return (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
spacing: 4,
className: classnames_default()('components-custom-gradient-picker', {
'is-next-has-no-margin': __nextHasNoMargin
})
}, (0,external_wp_element_namespaceObject.createElement)(CustomGradientBar, {
__experimentalIsRenderedInSidebar: __experimentalIsRenderedInSidebar,
background: background,
hasGradient: hasGradient,
value: controlPoints,
onChange: newControlPoints => {
onChange(serializeGradient(getGradientAstWithControlPoints(gradientAST, newControlPoints)));
}
}), (0,external_wp_element_namespaceObject.createElement)(flex_component, {
gap: 3,
className: "components-custom-gradient-picker__ui-line"
}, (0,external_wp_element_namespaceObject.createElement)(SelectWrapper, null, (0,external_wp_element_namespaceObject.createElement)(GradientTypePicker, {
gradientAST: gradientAST,
hasGradient: hasGradient,
onChange: onChange
})), (0,external_wp_element_namespaceObject.createElement)(AccessoryWrapper, null, gradientAST.type === 'linear-gradient' && (0,external_wp_element_namespaceObject.createElement)(GradientAnglePicker, {
gradientAST: gradientAST,
hasGradient: hasGradient,
onChange: onChange
}))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/gradient-picker/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
// The Multiple Origin Gradients have a `gradients` property (an array of
// gradient objects), while Single Origin ones have a `gradient` property.
const isMultipleOriginObject = obj => Array.isArray(obj.gradients) && !('gradient' in obj);
const isMultipleOriginArray = arr => {
return arr.length > 0 && arr.every(gradientObj => isMultipleOriginObject(gradientObj));
};
function SingleOrigin(_ref) {
let {
className,
clearGradient,
gradients,
onChange,
value,
actions
} = _ref;
const gradientOptions = (0,external_wp_element_namespaceObject.useMemo)(() => {
return gradients.map((_ref2, index) => {
let {
gradient,
name
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(CircularOptionPicker.Option, {
key: gradient,
value: gradient,
isSelected: value === gradient,
tooltipText: name || // translators: %s: gradient code e.g: "linear-gradient(90deg, rgba(98,16,153,1) 0%, rgba(172,110,22,1) 100%);".
(0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('Gradient code: %s'), gradient),
style: {
color: 'rgba( 0,0,0,0 )',
background: gradient
},
onClick: value === gradient ? clearGradient : () => onChange(gradient, index),
"aria-label": name ? // translators: %s: The name of the gradient e.g: "Angular red to blue".
(0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('Gradient: %s'), name) : // translators: %s: gradient code e.g: "linear-gradient(90deg, rgba(98,16,153,1) 0%, rgba(172,110,22,1) 100%);".
(0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('Gradient code: %s'), gradient)
});
});
}, [gradients, value, onChange, clearGradient]);
return (0,external_wp_element_namespaceObject.createElement)(CircularOptionPicker, {
className: className,
options: gradientOptions,
actions: actions
});
}
function MultipleOrigin(_ref3) {
let {
className,
clearGradient,
gradients,
onChange,
value,
actions
} = _ref3;
return (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
spacing: 3,
className: className
}, gradients.map((_ref4, index) => {
let {
name,
gradients: gradientSet
} = _ref4;
return (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
spacing: 2,
key: index
}, (0,external_wp_element_namespaceObject.createElement)(ColorHeading, null, name), (0,external_wp_element_namespaceObject.createElement)(SingleOrigin, extends_extends({
clearGradient: clearGradient,
gradients: gradientSet,
onChange: gradient => onChange(gradient, index),
value: value
}, gradients.length === index + 1 ? {
actions
} : {})));
}));
}
function GradientPicker(_ref5) {
let {
/** Start opting into the new margin-free styles that will become the default in a future version. */
__nextHasNoMargin = false,
className,
gradients,
onChange,
value,
clearable = true,
disableCustomGradients = false,
__experimentalIsRenderedInSidebar
} = _ref5;
const clearGradient = (0,external_wp_element_namespaceObject.useCallback)(() => onChange(undefined), [onChange]);
const Component = isMultipleOriginArray(gradients) ? MultipleOrigin : SingleOrigin;
if (!__nextHasNoMargin) {
external_wp_deprecated_default()('Outer margin styles for wp.components.GradientPicker', {
since: '6.1',
version: '6.4',
hint: 'Set the `__nextHasNoMargin` prop to true to start opting into the new styles, which will become the default in a future version'
});
}
const deprecatedMarginSpacerProps = !__nextHasNoMargin ? {
marginTop: !(gradients !== null && gradients !== void 0 && gradients.length) ? 3 : undefined,
marginBottom: !clearable ? 6 : 0
} : {};
return (// Outmost Spacer wrapper can be removed when deprecation period is over
(0,external_wp_element_namespaceObject.createElement)(spacer_component, extends_extends({
marginBottom: 0
}, deprecatedMarginSpacerProps), (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
spacing: gradients !== null && gradients !== void 0 && gradients.length ? 4 : 0
}, !disableCustomGradients && (0,external_wp_element_namespaceObject.createElement)(CustomGradientPicker, {
__nextHasNoMargin: true,
__experimentalIsRenderedInSidebar: __experimentalIsRenderedInSidebar,
value: value,
onChange: onChange
}), ((gradients === null || gradients === void 0 ? void 0 : gradients.length) || clearable) && (0,external_wp_element_namespaceObject.createElement)(Component, {
className: className,
clearable: clearable,
clearGradient: clearGradient,
gradients: gradients,
onChange: onChange,
value: value,
actions: clearable && !disableCustomGradients && (0,external_wp_element_namespaceObject.createElement)(CircularOptionPicker.ButtonAction, {
onClick: clearGradient
}, (0,external_wp_i18n_namespaceObject.__)('Clear'))
})))
);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/menu.js
/**
* WordPress dependencies
*/
const menu = (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: "M5 5v1.5h14V5H5zm0 7.8h14v-1.5H5v1.5zM5 19h14v-1.5H5V19z"
}));
/* harmony default export */ var library_menu = (menu);
;// CONCATENATED MODULE: external ["wp","dom"]
var external_wp_dom_namespaceObject = window["wp"]["dom"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigable-container/container.js
// @ts-nocheck
/**
* WordPress dependencies
*/
const container_noop = () => {};
const MENU_ITEM_ROLES = ['menuitem', 'menuitemradio', 'menuitemcheckbox'];
function cycleValue(value, total, offset) {
const nextValue = value + offset;
if (nextValue < 0) {
return total + nextValue;
} else if (nextValue >= total) {
return nextValue - total;
}
return nextValue;
}
class NavigableContainer extends external_wp_element_namespaceObject.Component {
constructor() {
super(...arguments);
this.onKeyDown = this.onKeyDown.bind(this);
this.bindContainer = this.bindContainer.bind(this);
this.getFocusableContext = this.getFocusableContext.bind(this);
this.getFocusableIndex = this.getFocusableIndex.bind(this);
}
componentDidMount() {
// We use DOM event listeners instead of React event listeners
// because we want to catch events from the underlying DOM tree
// The React Tree can be different from the DOM tree when using
// portals. Block Toolbars for instance are rendered in a separate
// React Trees.
this.container.addEventListener('keydown', this.onKeyDown);
this.container.addEventListener('focus', this.onFocus);
}
componentWillUnmount() {
this.container.removeEventListener('keydown', this.onKeyDown);
this.container.removeEventListener('focus', this.onFocus);
}
bindContainer(ref) {
const {
forwardedRef
} = this.props;
this.container = ref;
if (typeof forwardedRef === 'function') {
forwardedRef(ref);
} else if (forwardedRef && 'current' in forwardedRef) {
forwardedRef.current = ref;
}
}
getFocusableContext(target) {
const {
onlyBrowserTabstops
} = this.props;
const finder = onlyBrowserTabstops ? external_wp_dom_namespaceObject.focus.tabbable : external_wp_dom_namespaceObject.focus.focusable;
const focusables = finder.find(this.container);
const index = this.getFocusableIndex(focusables, target);
if (index > -1 && target) {
return {
index,
target,
focusables
};
}
return null;
}
getFocusableIndex(focusables, target) {
const directIndex = focusables.indexOf(target);
if (directIndex !== -1) {
return directIndex;
}
}
onKeyDown(event) {
if (this.props.onKeyDown) {
this.props.onKeyDown(event);
}
const {
getFocusableContext
} = this;
const {
cycle = true,
eventToOffset,
onNavigate = container_noop,
stopNavigationEvents
} = this.props;
const offset = eventToOffset(event); // eventToOffset returns undefined if the event is not handled by the component.
if (offset !== undefined && stopNavigationEvents) {
// Prevents arrow key handlers bound to the document directly interfering.
event.stopImmediatePropagation(); // When navigating a collection of items, prevent scroll containers
// from scrolling. The preventDefault also prevents Voiceover from
// 'handling' the event, as voiceover will try to use arrow keys
// for highlighting text.
const targetRole = event.target.getAttribute('role');
const targetHasMenuItemRole = MENU_ITEM_ROLES.includes(targetRole); // `preventDefault()` on tab to avoid having the browser move the focus
// after this component has already moved it.
const isTab = event.code === 'Tab';
if (targetHasMenuItemRole || isTab) {
event.preventDefault();
}
}
if (!offset) {
return;
}
const context = getFocusableContext(event.target.ownerDocument.activeElement);
if (!context) {
return;
}
const {
index,
focusables
} = context;
const nextIndex = cycle ? cycleValue(index, focusables.length, offset) : index + offset;
if (nextIndex >= 0 && nextIndex < focusables.length) {
focusables[nextIndex].focus();
onNavigate(nextIndex, focusables[nextIndex]);
}
}
render() {
const {
children,
stopNavigationEvents,
eventToOffset,
onNavigate,
onKeyDown,
cycle,
onlyBrowserTabstops,
forwardedRef,
...restProps
} = this.props;
return (0,external_wp_element_namespaceObject.createElement)("div", extends_extends({
ref: this.bindContainer
}, restProps), children);
}
}
const forwardedNavigableContainer = (props, ref) => {
return (0,external_wp_element_namespaceObject.createElement)(NavigableContainer, extends_extends({}, props, {
forwardedRef: ref
}));
};
forwardedNavigableContainer.displayName = 'NavigableContainer';
/* harmony default export */ var container = ((0,external_wp_element_namespaceObject.forwardRef)(forwardedNavigableContainer));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigable-container/menu.js
// @ts-nocheck
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function NavigableMenu(_ref, ref) {
let {
role = 'menu',
orientation = 'vertical',
...rest
} = _ref;
const eventToOffset = evt => {
const {
code
} = evt;
let next = ['ArrowDown'];
let previous = ['ArrowUp'];
if (orientation === 'horizontal') {
next = ['ArrowRight'];
previous = ['ArrowLeft'];
}
if (orientation === 'both') {
next = ['ArrowRight', 'ArrowDown'];
previous = ['ArrowLeft', 'ArrowUp'];
}
if (next.includes(code)) {
return 1;
} else if (previous.includes(code)) {
return -1;
} else if (['ArrowDown', 'ArrowUp', 'ArrowLeft', 'ArrowRight'].includes(code)) {
// Key press should be handled, e.g. have event propagation and
// default behavior handled by NavigableContainer but not result
// in an offset.
return 0;
}
};
return (0,external_wp_element_namespaceObject.createElement)(container, extends_extends({
ref: ref,
stopNavigationEvents: true,
onlyBrowserTabstops: false,
role: role,
"aria-orientation": role === 'presentation' ? null : orientation,
eventToOffset: eventToOffset
}, rest));
}
/* harmony default export */ var navigable_container_menu = ((0,external_wp_element_namespaceObject.forwardRef)(NavigableMenu));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/dropdown-menu/index.js
// @ts-nocheck
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function mergeProps() {
let defaultProps = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const mergedProps = { ...defaultProps,
...props
};
if (props.className && defaultProps.className) {
mergedProps.className = classnames_default()(props.className, defaultProps.className);
}
return mergedProps;
}
/**
* Whether the argument is a function.
*
* @param {*} maybeFunc The argument to check.
* @return {boolean} True if the argument is a function, false otherwise.
*/
function dropdown_menu_isFunction(maybeFunc) {
return typeof maybeFunc === 'function';
}
function DropdownMenu(dropdownMenuProps) {
const {
children,
className,
controls,
icon = library_menu,
label,
popoverProps,
toggleProps,
menuProps,
disableOpenOnArrowDown = false,
text,
noIcons
} = dropdownMenuProps;
if (!(controls !== null && controls !== void 0 && controls.length) && !dropdown_menu_isFunction(children)) {
return null;
} // Normalize controls to nested array of objects (sets of controls)
let controlSets;
if (controls !== null && controls !== void 0 && controls.length) {
controlSets = controls;
if (!Array.isArray(controlSets[0])) {
controlSets = [controlSets];
}
}
const mergedPopoverProps = mergeProps({
className: 'components-dropdown-menu__popover'
}, popoverProps);
return (0,external_wp_element_namespaceObject.createElement)(dropdown, {
className: classnames_default()('components-dropdown-menu', className),
popoverProps: mergedPopoverProps,
renderToggle: _ref => {
var _toggleProps$showTool;
let {
isOpen,
onToggle
} = _ref;
const openOnArrowDown = event => {
if (disableOpenOnArrowDown) {
return;
}
if (!isOpen && event.code === 'ArrowDown') {
event.preventDefault();
onToggle();
}
};
const {
as: Toggle = build_module_button,
...restToggleProps
} = toggleProps !== null && toggleProps !== void 0 ? toggleProps : {};
const mergedToggleProps = mergeProps({
className: classnames_default()('components-dropdown-menu__toggle', {
'is-opened': isOpen
})
}, restToggleProps);
return (0,external_wp_element_namespaceObject.createElement)(Toggle, extends_extends({}, mergedToggleProps, {
icon: icon,
onClick: event => {
onToggle(event);
if (mergedToggleProps.onClick) {
mergedToggleProps.onClick(event);
}
},
onKeyDown: event => {
openOnArrowDown(event);
if (mergedToggleProps.onKeyDown) {
mergedToggleProps.onKeyDown(event);
}
},
"aria-haspopup": "true",
"aria-expanded": isOpen,
label: label,
text: text,
showTooltip: (_toggleProps$showTool = toggleProps === null || toggleProps === void 0 ? void 0 : toggleProps.showTooltip) !== null && _toggleProps$showTool !== void 0 ? _toggleProps$showTool : true
}), mergedToggleProps.children);
},
renderContent: props => {
var _controlSets;
const mergedMenuProps = mergeProps({
'aria-label': label,
className: classnames_default()('components-dropdown-menu__menu', {
'no-icons': noIcons
})
}, menuProps);
return (0,external_wp_element_namespaceObject.createElement)(navigable_container_menu, extends_extends({}, mergedMenuProps, {
role: "menu"
}), dropdown_menu_isFunction(children) ? children(props) : null, (_controlSets = controlSets) === null || _controlSets === void 0 ? void 0 : _controlSets.flatMap((controlSet, indexOfSet) => controlSet.map((control, indexOfControl) => (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
key: [indexOfSet, indexOfControl].join(),
onClick: event => {
event.stopPropagation();
props.onClose();
if (control.onClick) {
control.onClick();
}
},
className: classnames_default()('components-dropdown-menu__menu-item', {
'has-separator': indexOfSet > 0 && indexOfControl === 0,
'is-active': control.isActive,
'is-icon-only': !control.title
}),
icon: control.icon,
label: control.label,
"aria-checked": control.role === 'menuitemcheckbox' || control.role === 'menuitemradio' ? control.isActive : undefined,
role: control.role === 'menuitemcheckbox' || control.role === 'menuitemradio' ? control.role : 'menuitem',
disabled: control.isDisabled
}, control.title))));
}
});
}
/* harmony default export */ var dropdown_menu = (DropdownMenu);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/palette-edit/styles.js
function palette_edit_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const IndicatorStyled = /*#__PURE__*/createStyled(CircularOptionPicker.Option, true ? {
target: "e5bw3229"
} : 0)("width:", space(6), ";height:", space(6), ";pointer-events:none;" + ( true ? "" : 0));
const NameInputControl = /*#__PURE__*/createStyled(input_control, true ? {
target: "e5bw3228"
} : 0)(Container, "{background:", COLORS.gray[100], ";border-radius:", config_values.controlBorderRadius, ";", Input, Input, Input, Input, "{height:", space(8), ";}", BackdropUI, BackdropUI, BackdropUI, "{border-color:transparent;box-shadow:none;}}" + ( true ? "" : 0));
const PaletteItem = /*#__PURE__*/createStyled(component, true ? {
target: "e5bw3227"
} : 0)("padding:3px 0 3px ", space(3), ";height:calc( 40px - ", config_values.borderWidth, " );border:1px solid ", config_values.surfaceBorderColor, ";border-bottom-color:transparent;&:first-of-type{border-top-left-radius:", config_values.controlBorderRadius, ";border-top-right-radius:", config_values.controlBorderRadius, ";}&:last-of-type{border-bottom-left-radius:", config_values.controlBorderRadius, ";border-bottom-right-radius:", config_values.controlBorderRadius, ";border-bottom-color:", config_values.surfaceBorderColor, ";}&.is-selected+&{border-top-color:transparent;}&.is-selected{border-color:", COLORS.ui.theme, ";}" + ( true ? "" : 0));
const NameContainer = createStyled("div", true ? {
target: "e5bw3226"
} : 0)("line-height:", space(8), ";margin-left:", space(2), ";margin-right:", space(2), ";white-space:nowrap;overflow:hidden;", PaletteItem, ":hover &{color:", COLORS.ui.theme, ";}" + ( true ? "" : 0));
const PaletteHeading = /*#__PURE__*/createStyled(heading_component, true ? {
target: "e5bw3225"
} : 0)("text-transform:uppercase;line-height:", space(6), ";font-weight:500;&&&{font-size:11px;margin-bottom:0;}" + ( true ? "" : 0));
const PaletteActionsContainer = /*#__PURE__*/createStyled(component, true ? {
target: "e5bw3224"
} : 0)("height:", space(6), ";display:flex;" + ( true ? "" : 0));
const PaletteHStackHeader = /*#__PURE__*/createStyled(h_stack_component, true ? {
target: "e5bw3223"
} : 0)("margin-bottom:", space(2), ";" + ( true ? "" : 0));
const PaletteEditStyles = /*#__PURE__*/createStyled(component, true ? {
target: "e5bw3222"
} : 0)( true ? {
name: "u6wnko",
styles: "&&&{.components-button.has-icon{min-width:0;padding:0;}}"
} : 0);
const DoneButton = /*#__PURE__*/createStyled(build_module_button, true ? {
target: "e5bw3221"
} : 0)("&&{color:", COLORS.ui.theme, ";}" + ( true ? "" : 0));
const RemoveButton = /*#__PURE__*/createStyled(build_module_button, true ? {
target: "e5bw3220"
} : 0)("&&{margin-top:", space(1), ";}" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/palette-edit/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const DEFAULT_COLOR = '#000';
function NameInput(_ref) {
let {
value,
onChange,
label
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(NameInputControl, {
label: label,
hideLabelFromVision: true,
value: value,
onChange: onChange
});
}
/**
* Returns a temporary name for a palette item in the format "Color + id".
* To ensure there are no duplicate ids, this function checks all slugs for temporary names.
* It expects slugs to be in the format: slugPrefix + color- + number.
* It then sets the id component of the new name based on the incremented id of the highest existing slug id.
*
* @param {string} elements An array of color palette items.
* @param {string} slugPrefix The slug prefix used to match the element slug.
*
* @return {string} A unique name for a palette item.
*/
function getNameForPosition(elements, slugPrefix) {
const temporaryNameRegex = new RegExp(`^${slugPrefix}color-([\\d]+)$`);
const position = elements.reduce((previousValue, currentValue) => {
if (typeof (currentValue === null || currentValue === void 0 ? void 0 : currentValue.slug) === 'string') {
const matches = currentValue === null || currentValue === void 0 ? void 0 : currentValue.slug.match(temporaryNameRegex);
if (matches) {
const id = parseInt(matches[1], 10);
if (id >= previousValue) {
return id + 1;
}
}
}
return previousValue;
}, 1);
return (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: is a temporary id for a custom color */
(0,external_wp_i18n_namespaceObject.__)('Color %s'), position);
}
function ColorPickerPopover(_ref2) {
let {
isGradient,
element,
onChange,
onClose = () => {}
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(popover, {
placement: "left-start",
offset: 20,
className: "components-palette-edit__popover",
onClose: onClose
}, !isGradient && (0,external_wp_element_namespaceObject.createElement)(LegacyAdapter, {
color: element.color,
enableAlpha: true,
onChange: newColor => onChange({ ...element,
color: newColor
})
}), isGradient && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-palette-edit__popover-gradient-picker"
}, (0,external_wp_element_namespaceObject.createElement)(CustomGradientPicker, {
__nextHasNoMargin: true,
__experimentalIsRenderedInSidebar: true,
value: element.gradient,
onChange: newGradient => onChange({ ...element,
gradient: newGradient
})
})));
}
function palette_edit_Option(_ref3) {
let {
canOnlyChangeValues,
element,
onChange,
isEditing,
onStartEditing,
onRemove,
onStopEditing,
slugPrefix,
isGradient
} = _ref3;
const focusOutsideProps = (0,external_wp_compose_namespaceObject.__experimentalUseFocusOutside)(onStopEditing);
const value = isGradient ? element.gradient : element.color;
return (0,external_wp_element_namespaceObject.createElement)(PaletteItem, extends_extends({
className: isEditing ? 'is-selected' : undefined,
as: "div",
onClick: onStartEditing
}, isEditing ? { ...focusOutsideProps
} : {
style: {
cursor: 'pointer'
}
}), (0,external_wp_element_namespaceObject.createElement)(h_stack_component, {
justify: "flex-start"
}, (0,external_wp_element_namespaceObject.createElement)(flex_item_component, null, (0,external_wp_element_namespaceObject.createElement)(IndicatorStyled, {
style: {
background: value,
color: 'transparent'
}
})), (0,external_wp_element_namespaceObject.createElement)(flex_item_component, null, isEditing && !canOnlyChangeValues ? (0,external_wp_element_namespaceObject.createElement)(NameInput, {
label: isGradient ? (0,external_wp_i18n_namespaceObject.__)('Gradient name') : (0,external_wp_i18n_namespaceObject.__)('Color name'),
value: element.name,
onChange: nextName => onChange({ ...element,
name: nextName,
slug: slugPrefix + (0,external_lodash_namespaceObject.kebabCase)(nextName)
})
}) : (0,external_wp_element_namespaceObject.createElement)(NameContainer, null, element.name)), isEditing && !canOnlyChangeValues && (0,external_wp_element_namespaceObject.createElement)(flex_item_component, null, (0,external_wp_element_namespaceObject.createElement)(RemoveButton, {
isSmall: true,
icon: line_solid,
label: (0,external_wp_i18n_namespaceObject.__)('Remove color'),
onClick: onRemove
}))), isEditing && (0,external_wp_element_namespaceObject.createElement)(ColorPickerPopover, {
isGradient: isGradient,
onChange: onChange,
element: element
}));
}
function isTemporaryElement(slugPrefix, _ref4) {
let {
slug,
color,
gradient
} = _ref4;
const regex = new RegExp(`^${slugPrefix}color-([\\d]+)$`);
return regex.test(slug) && (!!color && color === DEFAULT_COLOR || !!gradient && gradient === DEFAULT_GRADIENT);
}
function PaletteEditListView(_ref5) {
let {
elements,
onChange,
editingElement,
setEditingElement,
canOnlyChangeValues,
slugPrefix,
isGradient
} = _ref5;
// When unmounting the component if there are empty elements (the user did not complete the insertion) clean them.
const elementsReference = (0,external_wp_element_namespaceObject.useRef)();
(0,external_wp_element_namespaceObject.useEffect)(() => {
elementsReference.current = elements;
}, [elements]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
return () => {
if (elementsReference.current.some((element, index) => isTemporaryElement(slugPrefix, element, index))) {
const newElements = elementsReference.current.filter(element => !isTemporaryElement(slugPrefix, element));
onChange(newElements.length ? newElements : undefined);
}
}; // Disable reason: adding the missing dependency here would cause breaking changes that will require
// a heavier refactor to avoid. See https://github.com/WordPress/gutenberg/pull/43911
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const debounceOnChange = (0,external_wp_compose_namespaceObject.useDebounce)(onChange, 100);
return (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
spacing: 3
}, (0,external_wp_element_namespaceObject.createElement)(item_group_component, {
isRounded: true
}, elements.map((element, index) => (0,external_wp_element_namespaceObject.createElement)(palette_edit_Option, {
isGradient: isGradient,
canOnlyChangeValues: canOnlyChangeValues,
key: index,
element: element,
onStartEditing: () => {
if (editingElement !== index) {
setEditingElement(index);
}
},
onChange: newElement => {
debounceOnChange(elements.map((currentElement, currentIndex) => {
if (currentIndex === index) {
return newElement;
}
return currentElement;
}));
},
onRemove: () => {
setEditingElement(null);
const newElements = elements.filter((_currentElement, currentIndex) => {
if (currentIndex === index) {
return false;
}
return true;
});
onChange(newElements.length ? newElements : undefined);
},
isEditing: index === editingElement,
onStopEditing: () => {
if (index === editingElement) {
setEditingElement(null);
}
},
slugPrefix: slugPrefix
}))));
}
const EMPTY_ARRAY = [];
function PaletteEdit(_ref6) {
let {
gradients,
colors = EMPTY_ARRAY,
onChange,
paletteLabel,
emptyMessage,
canOnlyChangeValues,
canReset,
slugPrefix = ''
} = _ref6;
const isGradient = !!gradients;
const elements = isGradient ? gradients : colors;
const [isEditing, setIsEditing] = (0,external_wp_element_namespaceObject.useState)(false);
const [editingElement, setEditingElement] = (0,external_wp_element_namespaceObject.useState)(null);
const isAdding = isEditing && editingElement && elements[editingElement] && !elements[editingElement].slug;
const elementsLength = elements.length;
const hasElements = elementsLength > 0;
const debounceOnChange = (0,external_wp_compose_namespaceObject.useDebounce)(onChange, 100);
const onSelectPaletteItem = (0,external_wp_element_namespaceObject.useCallback)((value, newEditingElementIndex) => {
const selectedElement = elements[newEditingElementIndex];
const key = isGradient ? 'gradient' : 'color'; // Ensures that the index returned matches a known element value.
if (!!selectedElement && selectedElement[key] === value) {
setEditingElement(newEditingElementIndex);
} else {
setIsEditing(true);
}
}, [isGradient, elements]);
return (0,external_wp_element_namespaceObject.createElement)(PaletteEditStyles, null, (0,external_wp_element_namespaceObject.createElement)(PaletteHStackHeader, null, (0,external_wp_element_namespaceObject.createElement)(PaletteHeading, null, paletteLabel), (0,external_wp_element_namespaceObject.createElement)(PaletteActionsContainer, null, hasElements && isEditing && (0,external_wp_element_namespaceObject.createElement)(DoneButton, {
isSmall: true,
onClick: () => {
setIsEditing(false);
setEditingElement(null);
}
}, (0,external_wp_i18n_namespaceObject.__)('Done')), !canOnlyChangeValues && (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
isSmall: true,
isPressed: isAdding,
icon: library_plus,
label: isGradient ? (0,external_wp_i18n_namespaceObject.__)('Add gradient') : (0,external_wp_i18n_namespaceObject.__)('Add color'),
onClick: () => {
const tempOptionName = getNameForPosition(elements, slugPrefix);
onChange([...elements, { ...(isGradient ? {
gradient: DEFAULT_GRADIENT
} : {
color: DEFAULT_COLOR
}),
name: tempOptionName,
slug: slugPrefix + (0,external_lodash_namespaceObject.kebabCase)(tempOptionName)
}]);
setIsEditing(true);
setEditingElement(elements.length);
}
}), hasElements && (!isEditing || !canOnlyChangeValues || canReset) && (0,external_wp_element_namespaceObject.createElement)(dropdown_menu, {
icon: more_vertical,
label: isGradient ? (0,external_wp_i18n_namespaceObject.__)('Gradient options') : (0,external_wp_i18n_namespaceObject.__)('Color options'),
toggleProps: {
isSmall: true
}
}, _ref7 => {
let {
onClose
} = _ref7;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(navigable_container_menu, {
role: "menu"
}, !isEditing && (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
variant: "tertiary",
onClick: () => {
setIsEditing(true);
onClose();
},
className: "components-palette-edit__menu-button"
}, (0,external_wp_i18n_namespaceObject.__)('Show details')), !canOnlyChangeValues && (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
variant: "tertiary",
onClick: () => {
setEditingElement(null);
setIsEditing(false);
onChange();
onClose();
},
className: "components-palette-edit__menu-button"
}, isGradient ? (0,external_wp_i18n_namespaceObject.__)('Remove all gradients') : (0,external_wp_i18n_namespaceObject.__)('Remove all colors')), canReset && (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
variant: "tertiary",
onClick: () => {
setEditingElement(null);
onChange();
onClose();
}
}, isGradient ? (0,external_wp_i18n_namespaceObject.__)('Reset gradient') : (0,external_wp_i18n_namespaceObject.__)('Reset colors'))));
}))), hasElements && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, isEditing && (0,external_wp_element_namespaceObject.createElement)(PaletteEditListView, {
canOnlyChangeValues: canOnlyChangeValues,
elements: elements,
onChange: onChange,
editingElement: editingElement,
setEditingElement: setEditingElement,
slugPrefix: slugPrefix,
isGradient: isGradient
}), !isEditing && editingElement !== null && (0,external_wp_element_namespaceObject.createElement)(ColorPickerPopover, {
isGradient: isGradient,
onClose: () => setEditingElement(null),
onChange: newElement => {
debounceOnChange(elements.map((currentElement, currentIndex) => {
if (currentIndex === editingElement) {
return newElement;
}
return currentElement;
}));
},
element: elements[editingElement]
}), !isEditing && (isGradient ? (0,external_wp_element_namespaceObject.createElement)(GradientPicker, {
__nextHasNoMargin: true,
gradients: gradients,
onChange: onSelectPaletteItem,
clearable: false,
disableCustomGradients: true
}) : (0,external_wp_element_namespaceObject.createElement)(color_palette, {
colors: colors,
onChange: onSelectPaletteItem,
clearable: false,
disableCustomColors: true
}))), !hasElements && emptyMessage);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/combobox-control/styles.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const deprecatedDefaultSize = _ref => {
let {
__next36pxDefaultSize
} = _ref;
return !__next36pxDefaultSize && /*#__PURE__*/emotion_react_browser_esm_css("height:28px;padding-left:", space(1), ";padding-right:", space(1), ";" + ( true ? "" : 0), true ? "" : 0);
};
const InputWrapperFlex = /*#__PURE__*/createStyled(flex_component, true ? {
target: "evuatpg0"
} : 0)("height:34px;padding-left:", space(2), ";padding-right:", space(2), ";", deprecatedDefaultSize, ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/form-token-field/token-input.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnForwardedTokenInput(props, ref) {
const {
value,
isExpanded,
instanceId,
selectedSuggestionIndex,
className,
onChange,
onFocus,
onBlur,
...restProps
} = props;
const [hasFocus, setHasFocus] = (0,external_wp_element_namespaceObject.useState)(false);
const size = value ? value.length + 1 : 0;
const onChangeHandler = event => {
if (onChange) {
onChange({
value: event.target.value
});
}
};
const onFocusHandler = e => {
setHasFocus(true);
onFocus === null || onFocus === void 0 ? void 0 : onFocus(e);
};
const onBlurHandler = e => {
setHasFocus(false);
onBlur === null || onBlur === void 0 ? void 0 : onBlur(e);
};
return (0,external_wp_element_namespaceObject.createElement)("input", extends_extends({
ref: ref,
id: `components-form-token-input-${instanceId}`,
type: "text"
}, restProps, {
value: value || '',
onChange: onChangeHandler,
onFocus: onFocusHandler,
onBlur: onBlurHandler,
size: size,
className: classnames_default()(className, 'components-form-token-field__input'),
autoComplete: "off",
role: "combobox",
"aria-expanded": isExpanded,
"aria-autocomplete": "list",
"aria-owns": isExpanded ? `components-form-token-suggestions-${instanceId}` : undefined,
"aria-activedescendant": // Only add the `aria-activedescendant` attribute when:
// - the user is actively interacting with the input (`hasFocus`)
// - there is a selected suggestion (`selectedSuggestionIndex !== -1`)
// - the list of suggestions are rendered in the DOM (`isExpanded`)
hasFocus && selectedSuggestionIndex !== -1 && isExpanded ? `components-form-token-suggestions-${instanceId}-${selectedSuggestionIndex}` : undefined,
"aria-describedby": `components-form-token-suggestions-howto-${instanceId}`
}));
}
const TokenInput = (0,external_wp_element_namespaceObject.forwardRef)(UnForwardedTokenInput);
/* harmony default export */ var token_input = (TokenInput);
// EXTERNAL MODULE: ./node_modules/dom-scroll-into-view/lib/index.js
var lib = __webpack_require__(5425);
var lib_default = /*#__PURE__*/__webpack_require__.n(lib);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/form-token-field/suggestions-list.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const handleMouseDown = e => {
// By preventing default here, we will not lose focus of <input> when clicking a suggestion.
e.preventDefault();
};
function SuggestionsList(_ref) {
let {
selectedIndex,
scrollIntoView,
match,
onHover,
onSelect,
suggestions = [],
displayTransform,
instanceId,
__experimentalRenderItem
} = _ref;
const [scrollingIntoView, setScrollingIntoView] = (0,external_wp_element_namespaceObject.useState)(false);
const listRef = (0,external_wp_compose_namespaceObject.useRefEffect)(listNode => {
// only have to worry about scrolling selected suggestion into view
// when already expanded.
let rafId;
if (selectedIndex > -1 && scrollIntoView && listNode.children[selectedIndex]) {
setScrollingIntoView(true);
lib_default()(listNode.children[selectedIndex], listNode, {
onlyScrollIfNeeded: true
});
rafId = requestAnimationFrame(() => {
setScrollingIntoView(false);
});
}
return () => {
if (rafId !== undefined) {
cancelAnimationFrame(rafId);
}
};
}, [selectedIndex, scrollIntoView]);
const handleHover = suggestion => {
return () => {
if (!scrollingIntoView) {
onHover === null || onHover === void 0 ? void 0 : onHover(suggestion);
}
};
};
const handleClick = suggestion => {
return () => {
onSelect === null || onSelect === void 0 ? void 0 : onSelect(suggestion);
};
};
const computeSuggestionMatch = suggestion => {
const matchText = displayTransform(match).toLocaleLowerCase();
if (matchText.length === 0) {
return null;
}
const transformedSuggestion = displayTransform(suggestion);
const indexOfMatch = transformedSuggestion.toLocaleLowerCase().indexOf(matchText);
return {
suggestionBeforeMatch: transformedSuggestion.substring(0, indexOfMatch),
suggestionMatch: transformedSuggestion.substring(indexOfMatch, indexOfMatch + matchText.length),
suggestionAfterMatch: transformedSuggestion.substring(indexOfMatch + matchText.length)
};
};
return (0,external_wp_element_namespaceObject.createElement)("ul", {
ref: listRef,
className: "components-form-token-field__suggestions-list",
id: `components-form-token-suggestions-${instanceId}`,
role: "listbox"
}, suggestions.map((suggestion, index) => {
const matchText = computeSuggestionMatch(suggestion);
const className = classnames_default()('components-form-token-field__suggestion', {
'is-selected': index === selectedIndex
});
let output;
if (typeof __experimentalRenderItem === 'function') {
output = __experimentalRenderItem({
item: suggestion
});
} else if (matchText) {
output = (0,external_wp_element_namespaceObject.createElement)("span", {
"aria-label": displayTransform(suggestion)
}, matchText.suggestionBeforeMatch, (0,external_wp_element_namespaceObject.createElement)("strong", {
className: "components-form-token-field__suggestion-match"
}, matchText.suggestionMatch), matchText.suggestionAfterMatch);
} else {
output = displayTransform(suggestion);
}
/* eslint-disable jsx-a11y/click-events-have-key-events */
return (0,external_wp_element_namespaceObject.createElement)("li", {
id: `components-form-token-suggestions-${instanceId}-${index}`,
role: "option",
className: className,
key: typeof suggestion === 'object' && 'value' in suggestion ? suggestion === null || suggestion === void 0 ? void 0 : suggestion.value : displayTransform(suggestion),
onMouseDown: handleMouseDown,
onClick: handleClick(suggestion),
onMouseEnter: handleHover(suggestion),
"aria-selected": index === selectedIndex
}, output);
/* eslint-enable jsx-a11y/click-events-have-key-events */
}));
}
/* harmony default export */ var suggestions_list = (SuggestionsList);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/higher-order/with-focus-outside/index.js
//@ts-nocheck
/**
* WordPress dependencies
*/
/* harmony default export */ var with_focus_outside = ((0,external_wp_compose_namespaceObject.createHigherOrderComponent)(WrappedComponent => props => {
const [handleFocusOutside, setHandleFocusOutside] = (0,external_wp_element_namespaceObject.useState)();
const bindFocusOutsideHandler = (0,external_wp_element_namespaceObject.useCallback)(node => setHandleFocusOutside(() => node !== null && node !== void 0 && node.handleFocusOutside ? node.handleFocusOutside.bind(node) : undefined), []);
return (0,external_wp_element_namespaceObject.createElement)("div", (0,external_wp_compose_namespaceObject.__experimentalUseFocusOutside)(handleFocusOutside), (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, extends_extends({
ref: bindFocusOutsideHandler
}, props)));
}, 'withFocusOutside'));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/combobox-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const combobox_control_noop = () => {};
const DetectOutside = with_focus_outside(class extends external_wp_element_namespaceObject.Component {
handleFocusOutside(event) {
this.props.onFocusOutside(event);
}
render() {
return this.props.children;
}
});
function ComboboxControl(_ref) {
var _currentOption$label;
let {
/** Start opting into the new margin-free styles that will become the default in a future version. */
__nextHasNoMarginBottom = false,
__next36pxDefaultSize,
value: valueProp,
label,
options,
onChange: onChangeProp,
onFilterValueChange = combobox_control_noop,
hideLabelFromVision,
help,
allowReset = true,
className,
messages = {
selected: (0,external_wp_i18n_namespaceObject.__)('Item selected.')
},
__experimentalRenderItem
} = _ref;
const [value, setValue] = useControlledValue({
value: valueProp,
onChange: onChangeProp
});
const currentOption = options.find(option => option.value === value);
const currentLabel = (_currentOption$label = currentOption === null || currentOption === void 0 ? void 0 : currentOption.label) !== null && _currentOption$label !== void 0 ? _currentOption$label : ''; // Use a custom prefix when generating the `instanceId` to avoid having
// duplicate input IDs when rendering this component and `FormTokenField`
// in the same page (see https://github.com/WordPress/gutenberg/issues/42112).
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(ComboboxControl, 'combobox-control');
const [selectedSuggestion, setSelectedSuggestion] = (0,external_wp_element_namespaceObject.useState)(currentOption || null);
const [isExpanded, setIsExpanded] = (0,external_wp_element_namespaceObject.useState)(false);
const [inputHasFocus, setInputHasFocus] = (0,external_wp_element_namespaceObject.useState)(false);
const [inputValue, setInputValue] = (0,external_wp_element_namespaceObject.useState)('');
const inputContainer = (0,external_wp_element_namespaceObject.useRef)();
const matchingSuggestions = (0,external_wp_element_namespaceObject.useMemo)(() => {
const startsWithMatch = [];
const containsMatch = [];
const match = normalizeTextString(inputValue);
options.forEach(option => {
const index = normalizeTextString(option.label).indexOf(match);
if (index === 0) {
startsWithMatch.push(option);
} else if (index > 0) {
containsMatch.push(option);
}
});
return startsWithMatch.concat(containsMatch);
}, [inputValue, options]);
const onSuggestionSelected = newSelectedSuggestion => {
setValue(newSelectedSuggestion.value);
(0,external_wp_a11y_namespaceObject.speak)(messages.selected, 'assertive');
setSelectedSuggestion(newSelectedSuggestion);
setInputValue('');
setIsExpanded(false);
};
const handleArrowNavigation = function () {
let offset = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
const index = matchingSuggestions.indexOf(selectedSuggestion);
let nextIndex = index + offset;
if (nextIndex < 0) {
nextIndex = matchingSuggestions.length - 1;
} else if (nextIndex >= matchingSuggestions.length) {
nextIndex = 0;
}
setSelectedSuggestion(matchingSuggestions[nextIndex]);
setIsExpanded(true);
};
const onKeyDown = event => {
let preventDefault = false;
if (event.defaultPrevented || // Ignore keydowns from IMEs
event.nativeEvent.isComposing || // Workaround for Mac Safari where the final Enter/Backspace of an IME composition
// is `isComposing=false`, even though it's technically still part of the composition.
// These can only be detected by keyCode.
event.keyCode === 229) {
return;
}
switch (event.code) {
case 'Enter':
if (selectedSuggestion) {
onSuggestionSelected(selectedSuggestion);
preventDefault = true;
}
break;
case 'ArrowUp':
handleArrowNavigation(-1);
preventDefault = true;
break;
case 'ArrowDown':
handleArrowNavigation(1);
preventDefault = true;
break;
case 'Escape':
setIsExpanded(false);
setSelectedSuggestion(null);
preventDefault = true;
break;
default:
break;
}
if (preventDefault) {
event.preventDefault();
}
};
const onBlur = () => {
setInputHasFocus(false);
};
const onFocus = () => {
setInputHasFocus(true);
setIsExpanded(true);
onFilterValueChange('');
setInputValue('');
};
const onFocusOutside = () => {
setIsExpanded(false);
};
const onInputChange = event => {
const text = event.value;
setInputValue(text);
onFilterValueChange(text);
if (inputHasFocus) {
setIsExpanded(true);
}
};
const handleOnReset = () => {
setValue(null);
inputContainer.current.focus();
}; // Update current selections when the filter input changes.
(0,external_wp_element_namespaceObject.useEffect)(() => {
const hasMatchingSuggestions = matchingSuggestions.length > 0;
const hasSelectedMatchingSuggestions = matchingSuggestions.indexOf(selectedSuggestion) > 0;
if (hasMatchingSuggestions && !hasSelectedMatchingSuggestions) {
// If the current selection isn't present in the list of suggestions, then automatically select the first item from the list of suggestions.
setSelectedSuggestion(matchingSuggestions[0]);
}
}, [matchingSuggestions, selectedSuggestion]); // Announcements.
(0,external_wp_element_namespaceObject.useEffect)(() => {
const hasMatchingSuggestions = matchingSuggestions.length > 0;
if (isExpanded) {
const message = hasMatchingSuggestions ? (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %d: number of results. */
(0,external_wp_i18n_namespaceObject._n)('%d result found, use up and down arrow keys to navigate.', '%d results found, use up and down arrow keys to navigate.', matchingSuggestions.length), matchingSuggestions.length) : (0,external_wp_i18n_namespaceObject.__)('No results.');
(0,external_wp_a11y_namespaceObject.speak)(message, 'polite');
}
}, [matchingSuggestions, isExpanded]); // Disable reason: There is no appropriate role which describes the
// input container intended accessible usability.
// TODO: Refactor click detection to use blur to stop propagation.
/* eslint-disable jsx-a11y/no-static-element-interactions */
return (0,external_wp_element_namespaceObject.createElement)(DetectOutside, {
onFocusOutside: onFocusOutside
}, (0,external_wp_element_namespaceObject.createElement)(base_control, {
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
className: classnames_default()(className, 'components-combobox-control'),
tabIndex: "-1",
label: label,
id: `components-form-token-input-${instanceId}`,
hideLabelFromVision: hideLabelFromVision,
help: help
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-combobox-control__suggestions-container",
tabIndex: "-1",
onKeyDown: onKeyDown
}, (0,external_wp_element_namespaceObject.createElement)(InputWrapperFlex, {
__next36pxDefaultSize: __next36pxDefaultSize
}, (0,external_wp_element_namespaceObject.createElement)(flex_block_component, null, (0,external_wp_element_namespaceObject.createElement)(token_input, {
className: "components-combobox-control__input",
instanceId: instanceId,
ref: inputContainer,
value: isExpanded ? inputValue : currentLabel,
onFocus: onFocus,
onBlur: onBlur,
isExpanded: isExpanded,
selectedSuggestionIndex: matchingSuggestions.indexOf(selectedSuggestion),
onChange: onInputChange
})), allowReset && (0,external_wp_element_namespaceObject.createElement)(flex_item_component, null, (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-combobox-control__reset",
icon: close_small,
disabled: !value,
onClick: handleOnReset,
label: (0,external_wp_i18n_namespaceObject.__)('Reset')
}))), isExpanded && (0,external_wp_element_namespaceObject.createElement)(suggestions_list, {
instanceId: instanceId,
match: {
label: inputValue
},
displayTransform: suggestion => suggestion.label,
suggestions: matchingSuggestions,
selectedIndex: matchingSuggestions.indexOf(selectedSuggestion),
onHover: setSelectedSuggestion,
onSelect: onSuggestionSelected,
scrollIntoView: true,
__experimentalRenderItem: __experimentalRenderItem
}))));
/* eslint-enable jsx-a11y/no-static-element-interactions */
}
/* harmony default export */ var combobox_control = (ComboboxControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/modal/aria-helper.js
const LIVE_REGION_ARIA_ROLES = new Set(['alert', 'status', 'log', 'marquee', 'timer']);
let hiddenElements = [],
isHidden = false;
/**
* Hides all elements in the body element from screen-readers except
* the provided element and elements that should not be hidden from
* screen-readers.
*
* The reason we do this is because `aria-modal="true"` currently is bugged
* in Safari, and support is spotty in other browsers overall. In the future
* we should consider removing these helper functions in favor of
* `aria-modal="true"`.
*
* @param {HTMLDivElement} unhiddenElement The element that should not be hidden.
*/
function hideApp(unhiddenElement) {
if (isHidden) {
return;
}
const elements = Array.from(document.body.children);
elements.forEach(element => {
if (element === unhiddenElement) {
return;
}
if (elementShouldBeHidden(element)) {
element.setAttribute('aria-hidden', 'true');
hiddenElements.push(element);
}
});
isHidden = true;
}
/**
* Determines if the passed element should not be hidden from screen readers.
*
* @param {HTMLElement} element The element that should be checked.
*
* @return {boolean} Whether the element should not be hidden from screen-readers.
*/
function elementShouldBeHidden(element) {
const role = element.getAttribute('role');
return !(element.tagName === 'SCRIPT' || element.hasAttribute('aria-hidden') || element.hasAttribute('aria-live') || role && LIVE_REGION_ARIA_ROLES.has(role));
}
/**
* Makes all elements in the body that have been hidden by `hideApp`
* visible again to screen-readers.
*/
function showApp() {
if (!isHidden) {
return;
}
hiddenElements.forEach(element => {
element.removeAttribute('aria-hidden');
});
hiddenElements = [];
isHidden = false;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/modal/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
// Used to count the number of open modals.
let openModalCount = 0;
function UnforwardedModal(props, forwardedRef) {
const {
bodyOpenClassName = 'modal-open',
role = 'dialog',
title = null,
focusOnMount = true,
shouldCloseOnEsc = true,
shouldCloseOnClickOutside = true,
isDismissible = true,
/* Accessibility. */
aria = {
labelledby: undefined,
describedby: undefined
},
onRequestClose,
icon,
closeButtonLabel,
children,
style,
overlayClassName,
className,
contentLabel,
onKeyDown,
isFullScreen = false,
__experimentalHideHeader = false
} = props;
const ref = (0,external_wp_element_namespaceObject.useRef)();
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(Modal);
const headingId = title ? `components-modal-header-${instanceId}` : aria.labelledby;
const focusOnMountRef = (0,external_wp_compose_namespaceObject.useFocusOnMount)(focusOnMount);
const constrainedTabbingRef = (0,external_wp_compose_namespaceObject.useConstrainedTabbing)();
const focusReturnRef = (0,external_wp_compose_namespaceObject.useFocusReturn)();
const focusOutsideProps = (0,external_wp_compose_namespaceObject.__experimentalUseFocusOutside)(onRequestClose);
const [hasScrolledContent, setHasScrolledContent] = (0,external_wp_element_namespaceObject.useState)(false);
(0,external_wp_element_namespaceObject.useEffect)(() => {
openModalCount++;
if (openModalCount === 1) {
hideApp(ref.current);
document.body.classList.add(bodyOpenClassName);
}
return () => {
openModalCount--;
if (openModalCount === 0) {
document.body.classList.remove(bodyOpenClassName);
showApp();
}
};
}, [bodyOpenClassName]);
function handleEscapeKeyDown(event) {
if ( // Ignore keydowns from IMEs
event.nativeEvent.isComposing || // Workaround for Mac Safari where the final Enter/Backspace of an IME composition
// is `isComposing=false`, even though it's technically still part of the composition.
// These can only be detected by keyCode.
event.keyCode === 229) {
return;
}
if (shouldCloseOnEsc && event.code === 'Escape' && !event.defaultPrevented) {
event.preventDefault();
if (onRequestClose) {
onRequestClose(event);
}
}
}
const onContentContainerScroll = (0,external_wp_element_namespaceObject.useCallback)(e => {
var _e$currentTarget$scro, _e$currentTarget;
const scrollY = (_e$currentTarget$scro = e === null || e === void 0 ? void 0 : (_e$currentTarget = e.currentTarget) === null || _e$currentTarget === void 0 ? void 0 : _e$currentTarget.scrollTop) !== null && _e$currentTarget$scro !== void 0 ? _e$currentTarget$scro : -1;
if (!hasScrolledContent && scrollY > 0) {
setHasScrolledContent(true);
} else if (hasScrolledContent && scrollY <= 0) {
setHasScrolledContent(false);
}
}, [hasScrolledContent]);
return (0,external_wp_element_namespaceObject.createPortal)( // eslint-disable-next-line jsx-a11y/no-static-element-interactions
(0,external_wp_element_namespaceObject.createElement)("div", {
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([ref, forwardedRef]),
className: classnames_default()('components-modal__screen-overlay', overlayClassName),
onKeyDown: handleEscapeKeyDown
}, (0,external_wp_element_namespaceObject.createElement)(style_provider, {
document: document
}, (0,external_wp_element_namespaceObject.createElement)("div", extends_extends({
className: classnames_default()('components-modal__frame', className, {
'is-full-screen': isFullScreen
}),
style: style,
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([constrainedTabbingRef, focusReturnRef, focusOnMountRef]),
role: role,
"aria-label": contentLabel,
"aria-labelledby": contentLabel ? undefined : headingId,
"aria-describedby": aria.describedby,
tabIndex: -1
}, shouldCloseOnClickOutside ? focusOutsideProps : {}, {
onKeyDown: onKeyDown
}), (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('components-modal__content', {
'hide-header': __experimentalHideHeader,
'has-scrolled-content': hasScrolledContent
}),
role: "document",
onScroll: onContentContainerScroll
}, !__experimentalHideHeader && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-modal__header"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-modal__header-heading-container"
}, icon && (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-modal__icon-container",
"aria-hidden": true
}, icon), title && (0,external_wp_element_namespaceObject.createElement)("h1", {
id: headingId,
className: "components-modal__header-heading"
}, title)), isDismissible && (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
onClick: onRequestClose,
icon: library_close,
label: closeButtonLabel || (0,external_wp_i18n_namespaceObject.__)('Close')
})), children)))), document.body);
}
/**
* Modals give users information and choices related to a task they’re trying to
* accomplish. They can contain critical information, require decisions, or
* involve multiple tasks.
*
* ```jsx
* import { Button, Modal } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyModal = () => {
* const [ isOpen, setOpen ] = useState( false );
* const openModal = () => setOpen( true );
* const closeModal = () => setOpen( false );
*
* return (
* <>
* <Button variant="secondary" onClick={ openModal }>
* Open Modal
* </Button>
* { isOpen && (
* <Modal title="This is my modal" onRequestClose={ closeModal }>
* <Button variant="secondary" onClick={ closeModal }>
* My custom close button
* </Button>
* </Modal>
* ) }
* </>
* );
* };
* ```
*/
const Modal = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedModal);
/* harmony default export */ var modal = (Modal);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/confirm-dialog/styles.js
function confirm_dialog_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* The z-index for ConfirmDialog is being set here instead of in
* packages/base-styles/_z-index.scss, because this component uses
* emotion instead of sass.
*
* ConfirmDialog needs this higher z-index to ensure it renders on top of
* any parent Popover component.
*/
const styles_wrapper = true ? {
name: "7g5ii0",
styles: "&&{z-index:1000001;}"
} : 0;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/confirm-dialog/component.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ConfirmDialog(props, forwardedRef) {
const {
isOpen: isOpenProp,
onConfirm,
onCancel,
children,
confirmButtonText,
cancelButtonText,
...otherProps
} = useContextSystem(props, 'ConfirmDialog');
const cx = useCx();
const wrapperClassName = cx(styles_wrapper);
const [isOpen, setIsOpen] = (0,external_wp_element_namespaceObject.useState)();
const [shouldSelfClose, setShouldSelfClose] = (0,external_wp_element_namespaceObject.useState)();
(0,external_wp_element_namespaceObject.useEffect)(() => {
// We only allow the dialog to close itself if `isOpenProp` is *not* set.
// If `isOpenProp` is set, then it (probably) means it's controlled by a
// parent component. In that case, `shouldSelfClose` might do more harm than
// good, so we disable it.
const isIsOpenSet = typeof isOpenProp !== 'undefined';
setIsOpen(isIsOpenSet ? isOpenProp : true);
setShouldSelfClose(!isIsOpenSet);
}, [isOpenProp]);
const handleEvent = (0,external_wp_element_namespaceObject.useCallback)(callback => event => {
callback === null || callback === void 0 ? void 0 : callback(event);
if (shouldSelfClose) {
setIsOpen(false);
}
}, [shouldSelfClose, setIsOpen]);
const handleEnter = (0,external_wp_element_namespaceObject.useCallback)(event => {
if (event.key === 'Enter') {
handleEvent(onConfirm)(event);
}
}, [handleEvent, onConfirm]);
const cancelLabel = cancelButtonText !== null && cancelButtonText !== void 0 ? cancelButtonText : (0,external_wp_i18n_namespaceObject.__)('Cancel');
const confirmLabel = confirmButtonText !== null && confirmButtonText !== void 0 ? confirmButtonText : (0,external_wp_i18n_namespaceObject.__)('OK');
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, isOpen && (0,external_wp_element_namespaceObject.createElement)(modal, extends_extends({
onRequestClose: handleEvent(onCancel),
onKeyDown: handleEnter,
closeButtonLabel: cancelLabel,
isDismissible: true,
ref: forwardedRef,
overlayClassName: wrapperClassName,
__experimentalHideHeader: true
}, otherProps), (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
spacing: 8
}, (0,external_wp_element_namespaceObject.createElement)(text_component, null, children), (0,external_wp_element_namespaceObject.createElement)(flex_component, {
direction: "row",
justify: "flex-end"
}, (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
variant: "tertiary",
onClick: handleEvent(onCancel)
}, cancelLabel), (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
variant: "primary",
onClick: handleEvent(onConfirm)
}, confirmLabel)))));
}
/* harmony default export */ var confirm_dialog_component = (contextConnect(ConfirmDialog, 'ConfirmDialog'));
// EXTERNAL MODULE: ./node_modules/prop-types/index.js
var prop_types = __webpack_require__(2652);
var prop_types_default = /*#__PURE__*/__webpack_require__.n(prop_types);
// EXTERNAL MODULE: ./node_modules/downshift/node_modules/react-is/index.js
var react_is = __webpack_require__(2797);
;// CONCATENATED MODULE: ./node_modules/compute-scroll-into-view/dist/index.mjs
function dist_t(t){return"object"==typeof t&&null!=t&&1===t.nodeType}function dist_e(t,e){return(!e||"hidden"!==t)&&"visible"!==t&&"clip"!==t}function dist_n(t,n){if(t.clientHeight<t.scrollHeight||t.clientWidth<t.scrollWidth){var r=getComputedStyle(t,null);return dist_e(r.overflowY,n)||dist_e(r.overflowX,n)||function(t){var e=function(t){if(!t.ownerDocument||!t.ownerDocument.defaultView)return null;try{return t.ownerDocument.defaultView.frameElement}catch(t){return null}}(t);return!!e&&(e.clientHeight<t.scrollHeight||e.clientWidth<t.scrollWidth)}(t)}return!1}function dist_r(t,e,n,r,i,o,l,d){return o<t&&l>e||o>t&&l<e?0:o<=t&&d<=n||l>=e&&d>=n?o-t-r:l>e&&d<n||o<t&&d>n?l-e+i:0}var compute_scroll_into_view_dist_i=function(e,i){var o=window,l=i.scrollMode,d=i.block,f=i.inline,h=i.boundary,u=i.skipOverflowHiddenElements,s="function"==typeof h?h:function(t){return t!==h};if(!dist_t(e))throw new TypeError("Invalid target");for(var a,c,g=document.scrollingElement||document.documentElement,p=[],m=e;dist_t(m)&&s(m);){if((m=null==(c=(a=m).parentElement)?a.getRootNode().host||null:c)===g){p.push(m);break}null!=m&&m===document.body&&dist_n(m)&&!dist_n(document.documentElement)||null!=m&&dist_n(m,u)&&p.push(m)}for(var w=o.visualViewport?o.visualViewport.width:innerWidth,v=o.visualViewport?o.visualViewport.height:innerHeight,W=window.scrollX||pageXOffset,H=window.scrollY||pageYOffset,b=e.getBoundingClientRect(),y=b.height,E=b.width,M=b.top,V=b.right,x=b.bottom,I=b.left,C="start"===d||"nearest"===d?M:"end"===d?x:M+y/2,R="center"===f?I+E/2:"end"===f?V:I,T=[],k=0;k<p.length;k++){var B=p[k],D=B.getBoundingClientRect(),O=D.height,X=D.width,Y=D.top,L=D.right,S=D.bottom,j=D.left;if("if-needed"===l&&M>=0&&I>=0&&x<=v&&V<=w&&M>=Y&&x<=S&&I>=j&&V<=L)return T;var N=getComputedStyle(B),q=parseInt(N.borderLeftWidth,10),z=parseInt(N.borderTopWidth,10),A=parseInt(N.borderRightWidth,10),F=parseInt(N.borderBottomWidth,10),G=0,J=0,K="offsetWidth"in B?B.offsetWidth-B.clientWidth-q-A:0,P="offsetHeight"in B?B.offsetHeight-B.clientHeight-z-F:0,Q="offsetWidth"in B?0===B.offsetWidth?0:X/B.offsetWidth:0,U="offsetHeight"in B?0===B.offsetHeight?0:O/B.offsetHeight:0;if(g===B)G="start"===d?C:"end"===d?C-v:"nearest"===d?dist_r(H,H+v,v,z,F,H+C,H+C+y,y):C-v/2,J="start"===f?R:"center"===f?R-w/2:"end"===f?R-w:dist_r(W,W+w,w,q,A,W+R,W+R+E,E),G=Math.max(0,G+H),J=Math.max(0,J+W);else{G="start"===d?C-Y-z:"end"===d?C-S+F+P:"nearest"===d?dist_r(Y,S,O,z,F+P,C,C+y,y):C-(Y+O/2)+P/2,J="start"===f?R-j-q:"center"===f?R-(j+X/2)+K/2:"end"===f?R-L+A+K:dist_r(j,L,X,q,A+K,R,R+E,E);var Z=B.scrollLeft,$=B.scrollTop;C+=$-(G=Math.max(0,Math.min($+G/U,B.scrollHeight-O/U+P))),R+=Z-(J=Math.max(0,Math.min(Z+J/Q,B.scrollWidth-X/Q+K)))}T.push({el:B,top:G,left:J})}return T};
//# sourceMappingURL=index.mjs.map
;// CONCATENATED MODULE: ./node_modules/tslib/tslib.es6.js
/*! *****************************************************************************
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 */
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 __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 (_) 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;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (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: n === "return" } : 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;
}
;// CONCATENATED MODULE: ./node_modules/downshift/dist/downshift.esm.js
let idCounter = 0;
/**
* Accepts a parameter and returns it if it's a function
* or a noop function if it's not. This allows us to
* accept a callback, but not worry about it if it's not
* passed.
* @param {Function} cb the callback
* @return {Function} a function
*/
function cbToCb(cb) {
return typeof cb === 'function' ? cb : downshift_esm_noop;
}
function downshift_esm_noop() {}
/**
* Scroll node into view if necessary
* @param {HTMLElement} node the element that should scroll into view
* @param {HTMLElement} menuNode the menu element of the component
*/
function scrollIntoView(node, menuNode) {
if (!node) {
return;
}
const actions = compute_scroll_into_view_dist_i(node, {
boundary: menuNode,
block: 'nearest',
scrollMode: 'if-needed'
});
actions.forEach(_ref => {
let {
el,
top,
left
} = _ref;
el.scrollTop = top;
el.scrollLeft = left;
});
}
/**
* @param {HTMLElement} parent the parent node
* @param {HTMLElement} child the child node
* @param {Window} environment The window context where downshift renders.
* @return {Boolean} whether the parent is the child or the child is in the parent
*/
function isOrContainsNode(parent, child, environment) {
const result = parent === child || child instanceof environment.Node && parent.contains && parent.contains(child);
return result;
}
/**
* Simple debounce implementation. Will call the given
* function once after the time given has passed since
* it was last called.
* @param {Function} fn the function to call after the time
* @param {Number} time the time to wait
* @return {Function} the debounced function
*/
function downshift_esm_debounce(fn, time) {
let timeoutId;
function cancel() {
if (timeoutId) {
clearTimeout(timeoutId);
}
}
function wrapper() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
cancel();
timeoutId = setTimeout(() => {
timeoutId = null;
fn(...args);
}, time);
}
wrapper.cancel = cancel;
return wrapper;
}
/**
* This is intended to be used to compose event handlers.
* They are executed in order until one of them sets
* `event.preventDownshiftDefault = true`.
* @param {...Function} fns the event handler functions
* @return {Function} the event handler to add to an element
*/
function callAllEventHandlers() {
for (var _len2 = arguments.length, fns = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
fns[_key2] = arguments[_key2];
}
return function (event) {
for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
args[_key3 - 1] = arguments[_key3];
}
return fns.some(fn => {
if (fn) {
fn(event, ...args);
}
return event.preventDownshiftDefault || event.hasOwnProperty('nativeEvent') && event.nativeEvent.preventDownshiftDefault;
});
};
}
function handleRefs() {
for (var _len4 = arguments.length, refs = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
refs[_key4] = arguments[_key4];
}
return node => {
refs.forEach(ref => {
if (typeof ref === 'function') {
ref(node);
} else if (ref) {
ref.current = node;
}
});
};
}
/**
* This generates a unique ID for an instance of Downshift
* @return {String} the unique ID
*/
function generateId() {
return String(idCounter++);
}
/**
* Resets idCounter to 0. Used for SSR.
*/
function resetIdCounter() {
idCounter = 0;
}
/**
* Default implementation for status message. Only added when menu is open.
* Will specify if there are results in the list, and if so, how many,
* and what keys are relevant.
*
* @param {Object} param the downshift state and other relevant properties
* @return {String} the a11y status message
*/
function getA11yStatusMessage$1(_ref2) {
let {
isOpen,
resultCount,
previousResultCount
} = _ref2;
if (!isOpen) {
return '';
}
if (!resultCount) {
return 'No results are available.';
}
if (resultCount !== previousResultCount) {
return `${resultCount} result${resultCount === 1 ? ' is' : 's are'} available, use up and down arrow keys to navigate. Press Enter key to select.`;
}
return '';
}
/**
* Takes an argument and if it's an array, returns the first item in the array
* otherwise returns the argument
* @param {*} arg the maybe-array
* @param {*} defaultValue the value if arg is falsey not defined
* @return {*} the arg or it's first item
*/
function unwrapArray(arg, defaultValue) {
arg = Array.isArray(arg) ?
/* istanbul ignore next (preact) */
arg[0] : arg;
if (!arg && defaultValue) {
return defaultValue;
} else {
return arg;
}
}
/**
* @param {Object} element (P)react element
* @return {Boolean} whether it's a DOM element
*/
function isDOMElement(element) {
return typeof element.type === 'string';
}
/**
* @param {Object} element (P)react element
* @return {Object} the props
*/
function getElementProps(element) {
return element.props;
}
/**
* Throws a helpful error message for required properties. Useful
* to be used as a default in destructuring or object params.
* @param {String} fnName the function name
* @param {String} propName the prop name
*/
function requiredProp(fnName, propName) {
// eslint-disable-next-line no-console
console.error(`The property "${propName}" is required in "${fnName}"`);
}
const stateKeys = ['highlightedIndex', 'inputValue', 'isOpen', 'selectedItem', 'type'];
/**
* @param {Object} state the state object
* @return {Object} state that is relevant to downshift
*/
function pickState(state) {
if (state === void 0) {
state = {};
}
const result = {};
stateKeys.forEach(k => {
if (state.hasOwnProperty(k)) {
result[k] = state[k];
}
});
return result;
}
/**
* This will perform a shallow merge of the given state object
* with the state coming from props
* (for the controlled component scenario)
* This is used in state updater functions so they're referencing
* the right state regardless of where it comes from.
*
* @param {Object} state The state of the component/hook.
* @param {Object} props The props that may contain controlled values.
* @returns {Object} The merged controlled state.
*/
function getState(state, props) {
return Object.keys(state).reduce((prevState, key) => {
prevState[key] = isControlledProp(props, key) ? props[key] : state[key];
return prevState;
}, {});
}
/**
* This determines whether a prop is a "controlled prop" meaning it is
* state which is controlled by the outside of this component rather
* than within this component.
*
* @param {Object} props The props that may contain controlled values.
* @param {String} key the key to check
* @return {Boolean} whether it is a controlled controlled prop
*/
function isControlledProp(props, key) {
return props[key] !== undefined;
}
/**
* Normalizes the 'key' property of a KeyboardEvent in IE/Edge
* @param {Object} event a keyboardEvent object
* @return {String} keyboard key
*/
function normalizeArrowKey(event) {
const {
key,
keyCode
} = event;
/* istanbul ignore next (ie) */
if (keyCode >= 37 && keyCode <= 40 && key.indexOf('Arrow') !== 0) {
return `Arrow${key}`;
}
return key;
}
/**
* Simple check if the value passed is object literal
* @param {*} obj any things
* @return {Boolean} whether it's object literal
*/
function downshift_esm_isPlainObject(obj) {
return Object.prototype.toString.call(obj) === '[object Object]';
}
/**
* Returns the new index in the list, in a circular way. If next value is out of bonds from the total,
* it will wrap to either 0 or itemCount - 1.
*
* @param {number} moveAmount Number of positions to move. Negative to move backwards, positive forwards.
* @param {number} baseIndex The initial position to move from.
* @param {number} itemCount The total number of items.
* @param {Function} getItemNodeFromIndex Used to check if item is disabled.
* @param {boolean} circular Specify if navigation is circular. Default is true.
* @returns {number} The new index after the move.
*/
function getNextWrappingIndex(moveAmount, baseIndex, itemCount, getItemNodeFromIndex, circular) {
if (circular === void 0) {
circular = true;
}
if (itemCount === 0) {
return -1;
}
const itemsLastIndex = itemCount - 1;
if (typeof baseIndex !== 'number' || baseIndex < 0 || baseIndex >= itemCount) {
baseIndex = moveAmount > 0 ? -1 : itemsLastIndex + 1;
}
let newIndex = baseIndex + moveAmount;
if (newIndex < 0) {
newIndex = circular ? itemsLastIndex : 0;
} else if (newIndex > itemsLastIndex) {
newIndex = circular ? 0 : itemsLastIndex;
}
const nonDisabledNewIndex = getNextNonDisabledIndex(moveAmount, newIndex, itemCount, getItemNodeFromIndex, circular);
if (nonDisabledNewIndex === -1) {
return baseIndex >= itemCount ? -1 : baseIndex;
}
return nonDisabledNewIndex;
}
/**
* Returns the next index in the list of an item that is not disabled.
*
* @param {number} moveAmount Number of positions to move. Negative to move backwards, positive forwards.
* @param {number} baseIndex The initial position to move from.
* @param {number} itemCount The total number of items.
* @param {Function} getItemNodeFromIndex Used to check if item is disabled.
* @param {boolean} circular Specify if navigation is circular. Default is true.
* @returns {number} The new index. Returns baseIndex if item is not disabled. Returns next non-disabled item otherwise. If no non-disabled found it will return -1.
*/
function getNextNonDisabledIndex(moveAmount, baseIndex, itemCount, getItemNodeFromIndex, circular) {
const currentElementNode = getItemNodeFromIndex(baseIndex);
if (!currentElementNode || !currentElementNode.hasAttribute('disabled')) {
return baseIndex;
}
if (moveAmount > 0) {
for (let index = baseIndex + 1; index < itemCount; index++) {
if (!getItemNodeFromIndex(index).hasAttribute('disabled')) {
return index;
}
}
} else {
for (let index = baseIndex - 1; index >= 0; index--) {
if (!getItemNodeFromIndex(index).hasAttribute('disabled')) {
return index;
}
}
}
if (circular) {
return moveAmount > 0 ? getNextNonDisabledIndex(1, 0, itemCount, getItemNodeFromIndex, false) : getNextNonDisabledIndex(-1, itemCount - 1, itemCount, getItemNodeFromIndex, false);
}
return -1;
}
/**
* Checks if event target is within the downshift elements.
*
* @param {EventTarget} target Target to check.
* @param {HTMLElement[]} downshiftElements The elements that form downshift (list, toggle button etc).
* @param {Window} environment The window context where downshift renders.
* @param {boolean} checkActiveElement Whether to also check activeElement.
*
* @returns {boolean} Whether or not the target is within downshift elements.
*/
function targetWithinDownshift(target, downshiftElements, environment, checkActiveElement) {
if (checkActiveElement === void 0) {
checkActiveElement = true;
}
return downshiftElements.some(contextNode => contextNode && (isOrContainsNode(contextNode, target, environment) || checkActiveElement && isOrContainsNode(contextNode, environment.document.activeElement, environment)));
} // eslint-disable-next-line import/no-mutable-exports
let validateControlledUnchanged = (/* unused pure expression or super */ null && (downshift_esm_noop));
/* istanbul ignore next */
if (false) {}
const cleanupStatus = downshift_esm_debounce(documentProp => {
getStatusDiv(documentProp).textContent = '';
}, 500);
/**
* @param {String} status the status message
* @param {Object} documentProp document passed by the user.
*/
function setStatus(status, documentProp) {
const div = getStatusDiv(documentProp);
if (!status) {
return;
}
div.textContent = status;
cleanupStatus(documentProp);
}
/**
* Get the status node or create it if it does not already exist.
* @param {Object} documentProp document passed by the user.
* @return {HTMLElement} the status node.
*/
function getStatusDiv(documentProp) {
if (documentProp === void 0) {
documentProp = document;
}
let statusDiv = documentProp.getElementById('a11y-status-message');
if (statusDiv) {
return statusDiv;
}
statusDiv = documentProp.createElement('div');
statusDiv.setAttribute('id', 'a11y-status-message');
statusDiv.setAttribute('role', 'status');
statusDiv.setAttribute('aria-live', 'polite');
statusDiv.setAttribute('aria-relevant', 'additions text');
Object.assign(statusDiv.style, {
border: '0',
clip: 'rect(0 0 0 0)',
height: '1px',
margin: '-1px',
overflow: 'hidden',
padding: '0',
position: 'absolute',
width: '1px'
});
documentProp.body.appendChild(statusDiv);
return statusDiv;
}
const unknown = false ? 0 : 0;
const mouseUp = false ? 0 : 1;
const itemMouseEnter = false ? 0 : 2;
const keyDownArrowUp = false ? 0 : 3;
const keyDownArrowDown = false ? 0 : 4;
const keyDownEscape = false ? 0 : 5;
const keyDownEnter = false ? 0 : 6;
const keyDownHome = false ? 0 : 7;
const keyDownEnd = false ? 0 : 8;
const clickItem = false ? 0 : 9;
const blurInput = false ? 0 : 10;
const changeInput = false ? 0 : 11;
const keyDownSpaceButton = false ? 0 : 12;
const clickButton = false ? 0 : 13;
const blurButton = false ? 0 : 14;
const controlledPropUpdatedSelectedItem = false ? 0 : 15;
const touchEnd = false ? 0 : 16;
var stateChangeTypes$3 = /*#__PURE__*/Object.freeze({
__proto__: null,
unknown: unknown,
mouseUp: mouseUp,
itemMouseEnter: itemMouseEnter,
keyDownArrowUp: keyDownArrowUp,
keyDownArrowDown: keyDownArrowDown,
keyDownEscape: keyDownEscape,
keyDownEnter: keyDownEnter,
keyDownHome: keyDownHome,
keyDownEnd: keyDownEnd,
clickItem: clickItem,
blurInput: blurInput,
changeInput: changeInput,
keyDownSpaceButton: keyDownSpaceButton,
clickButton: clickButton,
blurButton: blurButton,
controlledPropUpdatedSelectedItem: controlledPropUpdatedSelectedItem,
touchEnd: touchEnd
});
/* eslint camelcase:0 */
const Downshift = /*#__PURE__*/(() => {
class Downshift extends external_React_.Component {
constructor(_props) {
var _this;
super(_props);
_this = this;
this.id = this.props.id || `downshift-${generateId()}`;
this.menuId = this.props.menuId || `${this.id}-menu`;
this.labelId = this.props.labelId || `${this.id}-label`;
this.inputId = this.props.inputId || `${this.id}-input`;
this.getItemId = this.props.getItemId || (index => `${this.id}-item-${index}`);
this.input = null;
this.items = [];
this.itemCount = null;
this.previousResultCount = 0;
this.timeoutIds = [];
this.internalSetTimeout = (fn, time) => {
const id = setTimeout(() => {
this.timeoutIds = this.timeoutIds.filter(i => i !== id);
fn();
}, time);
this.timeoutIds.push(id);
};
this.setItemCount = count => {
this.itemCount = count;
};
this.unsetItemCount = () => {
this.itemCount = null;
};
this.setHighlightedIndex = function (highlightedIndex, otherStateToSet) {
if (highlightedIndex === void 0) {
highlightedIndex = _this.props.defaultHighlightedIndex;
}
if (otherStateToSet === void 0) {
otherStateToSet = {};
}
otherStateToSet = pickState(otherStateToSet);
_this.internalSetState({
highlightedIndex,
...otherStateToSet
});
};
this.clearSelection = cb => {
this.internalSetState({
selectedItem: null,
inputValue: '',
highlightedIndex: this.props.defaultHighlightedIndex,
isOpen: this.props.defaultIsOpen
}, cb);
};
this.selectItem = (item, otherStateToSet, cb) => {
otherStateToSet = pickState(otherStateToSet);
this.internalSetState({
isOpen: this.props.defaultIsOpen,
highlightedIndex: this.props.defaultHighlightedIndex,
selectedItem: item,
inputValue: this.props.itemToString(item),
...otherStateToSet
}, cb);
};
this.selectItemAtIndex = (itemIndex, otherStateToSet, cb) => {
const item = this.items[itemIndex];
if (item == null) {
return;
}
this.selectItem(item, otherStateToSet, cb);
};
this.selectHighlightedItem = (otherStateToSet, cb) => {
return this.selectItemAtIndex(this.getState().highlightedIndex, otherStateToSet, cb);
};
this.internalSetState = (stateToSet, cb) => {
let isItemSelected, onChangeArg;
const onStateChangeArg = {};
const isStateToSetFunction = typeof stateToSet === 'function'; // we want to call `onInputValueChange` before the `setState` call
// so someone controlling the `inputValue` state gets notified of
// the input change as soon as possible. This avoids issues with
// preserving the cursor position.
// See https://github.com/downshift-js/downshift/issues/217 for more info.
if (!isStateToSetFunction && stateToSet.hasOwnProperty('inputValue')) {
this.props.onInputValueChange(stateToSet.inputValue, { ...this.getStateAndHelpers(),
...stateToSet
});
}
return this.setState(state => {
state = this.getState(state);
let newStateToSet = isStateToSetFunction ? stateToSet(state) : stateToSet; // Your own function that could modify the state that will be set.
newStateToSet = this.props.stateReducer(state, newStateToSet); // checks if an item is selected, regardless of if it's different from
// what was selected before
// used to determine if onSelect and onChange callbacks should be called
isItemSelected = newStateToSet.hasOwnProperty('selectedItem'); // this keeps track of the object we want to call with setState
const nextState = {}; // this is just used to tell whether the state changed
// and we're trying to update that state. OR if the selection has changed and we're
// trying to update the selection
if (isItemSelected && newStateToSet.selectedItem !== state.selectedItem) {
onChangeArg = newStateToSet.selectedItem;
}
newStateToSet.type = newStateToSet.type || unknown;
Object.keys(newStateToSet).forEach(key => {
// onStateChangeArg should only have the state that is
// actually changing
if (state[key] !== newStateToSet[key]) {
onStateChangeArg[key] = newStateToSet[key];
} // the type is useful for the onStateChangeArg
// but we don't actually want to set it in internal state.
// this is an undocumented feature for now... Not all internalSetState
// calls support it and I'm not certain we want them to yet.
// But it enables users controlling the isOpen state to know when
// the isOpen state changes due to mouseup events which is quite handy.
if (key === 'type') {
return;
}
newStateToSet[key]; // if it's coming from props, then we don't care to set it internally
if (!isControlledProp(this.props, key)) {
nextState[key] = newStateToSet[key];
}
}); // if stateToSet is a function, then we weren't able to call onInputValueChange
// earlier, so we'll call it now that we know what the inputValue state will be.
if (isStateToSetFunction && newStateToSet.hasOwnProperty('inputValue')) {
this.props.onInputValueChange(newStateToSet.inputValue, { ...this.getStateAndHelpers(),
...newStateToSet
});
}
return nextState;
}, () => {
// call the provided callback if it's a function
cbToCb(cb)(); // only call the onStateChange and onChange callbacks if
// we have relevant information to pass them.
const hasMoreStateThanType = Object.keys(onStateChangeArg).length > 1;
if (hasMoreStateThanType) {
this.props.onStateChange(onStateChangeArg, this.getStateAndHelpers());
}
if (isItemSelected) {
this.props.onSelect(stateToSet.selectedItem, this.getStateAndHelpers());
}
if (onChangeArg !== undefined) {
this.props.onChange(onChangeArg, this.getStateAndHelpers());
} // this is currently undocumented and therefore subject to change
// We'll try to not break it, but just be warned.
this.props.onUserAction(onStateChangeArg, this.getStateAndHelpers());
});
};
this.rootRef = node => this._rootNode = node;
this.getRootProps = function (_temp, _temp2) {
let {
refKey = 'ref',
ref,
...rest
} = _temp === void 0 ? {} : _temp;
let {
suppressRefError = false
} = _temp2 === void 0 ? {} : _temp2;
// this is used in the render to know whether the user has called getRootProps.
// It uses that to know whether to apply the props automatically
_this.getRootProps.called = true;
_this.getRootProps.refKey = refKey;
_this.getRootProps.suppressRefError = suppressRefError;
const {
isOpen
} = _this.getState();
return {
[refKey]: handleRefs(ref, _this.rootRef),
role: 'combobox',
'aria-expanded': isOpen,
'aria-haspopup': 'listbox',
'aria-owns': isOpen ? _this.menuId : null,
'aria-labelledby': _this.labelId,
...rest
};
};
this.keyDownHandlers = {
ArrowDown(event) {
event.preventDefault();
if (this.getState().isOpen) {
const amount = event.shiftKey ? 5 : 1;
this.moveHighlightedIndex(amount, {
type: keyDownArrowDown
});
} else {
this.internalSetState({
isOpen: true,
type: keyDownArrowDown
}, () => {
const itemCount = this.getItemCount();
if (itemCount > 0) {
const {
highlightedIndex
} = this.getState();
const nextHighlightedIndex = getNextWrappingIndex(1, highlightedIndex, itemCount, index => this.getItemNodeFromIndex(index));
this.setHighlightedIndex(nextHighlightedIndex, {
type: keyDownArrowDown
});
}
});
}
},
ArrowUp(event) {
event.preventDefault();
if (this.getState().isOpen) {
const amount = event.shiftKey ? -5 : -1;
this.moveHighlightedIndex(amount, {
type: keyDownArrowUp
});
} else {
this.internalSetState({
isOpen: true,
type: keyDownArrowUp
}, () => {
const itemCount = this.getItemCount();
if (itemCount > 0) {
const {
highlightedIndex
} = this.getState();
const nextHighlightedIndex = getNextWrappingIndex(-1, highlightedIndex, itemCount, index => this.getItemNodeFromIndex(index));
this.setHighlightedIndex(nextHighlightedIndex, {
type: keyDownArrowUp
});
}
});
}
},
Enter(event) {
if (event.which === 229) {
return;
}
const {
isOpen,
highlightedIndex
} = this.getState();
if (isOpen && highlightedIndex != null) {
event.preventDefault();
const item = this.items[highlightedIndex];
const itemNode = this.getItemNodeFromIndex(highlightedIndex);
if (item == null || itemNode && itemNode.hasAttribute('disabled')) {
return;
}
this.selectHighlightedItem({
type: keyDownEnter
});
}
},
Escape(event) {
event.preventDefault();
this.reset({
type: keyDownEscape,
...(!this.state.isOpen && {
selectedItem: null,
inputValue: ''
})
});
}
};
this.buttonKeyDownHandlers = { ...this.keyDownHandlers,
' '(event) {
event.preventDefault();
this.toggleMenu({
type: keyDownSpaceButton
});
}
};
this.inputKeyDownHandlers = { ...this.keyDownHandlers,
Home(event) {
const {
isOpen
} = this.getState();
if (!isOpen) {
return;
}
event.preventDefault();
const itemCount = this.getItemCount();
if (itemCount <= 0 || !isOpen) {
return;
} // get next non-disabled starting downwards from 0 if that's disabled.
const newHighlightedIndex = getNextNonDisabledIndex(1, 0, itemCount, index => this.getItemNodeFromIndex(index), false);
this.setHighlightedIndex(newHighlightedIndex, {
type: keyDownHome
});
},
End(event) {
const {
isOpen
} = this.getState();
if (!isOpen) {
return;
}
event.preventDefault();
const itemCount = this.getItemCount();
if (itemCount <= 0 || !isOpen) {
return;
} // get next non-disabled starting upwards from last index if that's disabled.
const newHighlightedIndex = getNextNonDisabledIndex(-1, itemCount - 1, itemCount, index => this.getItemNodeFromIndex(index), false);
this.setHighlightedIndex(newHighlightedIndex, {
type: keyDownEnd
});
}
};
this.getToggleButtonProps = function (_temp3) {
let {
onClick,
onPress,
onKeyDown,
onKeyUp,
onBlur,
...rest
} = _temp3 === void 0 ? {} : _temp3;
const {
isOpen
} = _this.getState();
const enabledEventHandlers = {
onClick: callAllEventHandlers(onClick, _this.buttonHandleClick),
onKeyDown: callAllEventHandlers(onKeyDown, _this.buttonHandleKeyDown),
onKeyUp: callAllEventHandlers(onKeyUp, _this.buttonHandleKeyUp),
onBlur: callAllEventHandlers(onBlur, _this.buttonHandleBlur)
};
const eventHandlers = rest.disabled ? {} : enabledEventHandlers;
return {
type: 'button',
role: 'button',
'aria-label': isOpen ? 'close menu' : 'open menu',
'aria-haspopup': true,
'data-toggle': true,
...eventHandlers,
...rest
};
};
this.buttonHandleKeyUp = event => {
// Prevent click event from emitting in Firefox
event.preventDefault();
};
this.buttonHandleKeyDown = event => {
const key = normalizeArrowKey(event);
if (this.buttonKeyDownHandlers[key]) {
this.buttonKeyDownHandlers[key].call(this, event);
}
};
this.buttonHandleClick = event => {
event.preventDefault(); // handle odd case for Safari and Firefox which
// don't give the button the focus properly.
/* istanbul ignore if (can't reasonably test this) */
if (this.props.environment.document.activeElement === this.props.environment.document.body) {
event.target.focus();
} // to simplify testing components that use downshift, we'll not wrap this in a setTimeout
// if the NODE_ENV is test. With the proper build system, this should be dead code eliminated
// when building for production and should therefore have no impact on production code.
if (false) {} else {
// Ensure that toggle of menu occurs after the potential blur event in iOS
this.internalSetTimeout(() => this.toggleMenu({
type: clickButton
}));
}
};
this.buttonHandleBlur = event => {
const blurTarget = event.target; // Save blur target for comparison with activeElement later
// Need setTimeout, so that when the user presses Tab, the activeElement is the next focused element, not body element
this.internalSetTimeout(() => {
if (!this.isMouseDown && (this.props.environment.document.activeElement == null || this.props.environment.document.activeElement.id !== this.inputId) && this.props.environment.document.activeElement !== blurTarget // Do nothing if we refocus the same element again (to solve issue in Safari on iOS)
) {
this.reset({
type: blurButton
});
}
});
};
this.getLabelProps = props => {
return {
htmlFor: this.inputId,
id: this.labelId,
...props
};
};
this.getInputProps = function (_temp4) {
let {
onKeyDown,
onBlur,
onChange,
onInput,
onChangeText,
...rest
} = _temp4 === void 0 ? {} : _temp4;
let onChangeKey;
let eventHandlers = {};
/* istanbul ignore next (preact) */
{
onChangeKey = 'onChange';
}
const {
inputValue,
isOpen,
highlightedIndex
} = _this.getState();
if (!rest.disabled) {
eventHandlers = {
[onChangeKey]: callAllEventHandlers(onChange, onInput, _this.inputHandleChange),
onKeyDown: callAllEventHandlers(onKeyDown, _this.inputHandleKeyDown),
onBlur: callAllEventHandlers(onBlur, _this.inputHandleBlur)
};
}
return {
'aria-autocomplete': 'list',
'aria-activedescendant': isOpen && typeof highlightedIndex === 'number' && highlightedIndex >= 0 ? _this.getItemId(highlightedIndex) : null,
'aria-controls': isOpen ? _this.menuId : null,
'aria-labelledby': _this.labelId,
// https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion
// revert back since autocomplete="nope" is ignored on latest Chrome and Opera
autoComplete: 'off',
value: inputValue,
id: _this.inputId,
...eventHandlers,
...rest
};
};
this.inputHandleKeyDown = event => {
const key = normalizeArrowKey(event);
if (key && this.inputKeyDownHandlers[key]) {
this.inputKeyDownHandlers[key].call(this, event);
}
};
this.inputHandleChange = event => {
this.internalSetState({
type: changeInput,
isOpen: true,
inputValue: event.target.value,
highlightedIndex: this.props.defaultHighlightedIndex
});
};
this.inputHandleBlur = () => {
// Need setTimeout, so that when the user presses Tab, the activeElement is the next focused element, not the body element
this.internalSetTimeout(() => {
const downshiftButtonIsActive = this.props.environment.document && !!this.props.environment.document.activeElement && !!this.props.environment.document.activeElement.dataset && this.props.environment.document.activeElement.dataset.toggle && this._rootNode && this._rootNode.contains(this.props.environment.document.activeElement);
if (!this.isMouseDown && !downshiftButtonIsActive) {
this.reset({
type: blurInput
});
}
});
};
this.menuRef = node => {
this._menuNode = node;
};
this.getMenuProps = function (_temp5, _temp6) {
let {
refKey = 'ref',
ref,
...props
} = _temp5 === void 0 ? {} : _temp5;
let {
suppressRefError = false
} = _temp6 === void 0 ? {} : _temp6;
_this.getMenuProps.called = true;
_this.getMenuProps.refKey = refKey;
_this.getMenuProps.suppressRefError = suppressRefError;
return {
[refKey]: handleRefs(ref, _this.menuRef),
role: 'listbox',
'aria-labelledby': props && props['aria-label'] ? null : _this.labelId,
id: _this.menuId,
...props
};
};
this.getItemProps = function (_temp7) {
let {
onMouseMove,
onMouseDown,
onClick,
onPress,
index,
item = true ?
/* istanbul ignore next */
undefined : 0,
...rest
} = _temp7 === void 0 ? {} : _temp7;
if (index === undefined) {
_this.items.push(item);
index = _this.items.indexOf(item);
} else {
_this.items[index] = item;
}
const onSelectKey = 'onClick';
const customClickHandler = onClick;
const enabledEventHandlers = {
// onMouseMove is used over onMouseEnter here. onMouseMove
// is only triggered on actual mouse movement while onMouseEnter
// can fire on DOM changes, interrupting keyboard navigation
onMouseMove: callAllEventHandlers(onMouseMove, () => {
if (index === _this.getState().highlightedIndex) {
return;
}
_this.setHighlightedIndex(index, {
type: itemMouseEnter
}); // We never want to manually scroll when changing state based
// on `onMouseMove` because we will be moving the element out
// from under the user which is currently scrolling/moving the
// cursor
_this.avoidScrolling = true;
_this.internalSetTimeout(() => _this.avoidScrolling = false, 250);
}),
onMouseDown: callAllEventHandlers(onMouseDown, event => {
// This prevents the activeElement from being changed
// to the item so it can remain with the current activeElement
// which is a more common use case.
event.preventDefault();
}),
[onSelectKey]: callAllEventHandlers(customClickHandler, () => {
_this.selectItemAtIndex(index, {
type: clickItem
});
})
}; // Passing down the onMouseDown handler to prevent redirect
// of the activeElement if clicking on disabled items
const eventHandlers = rest.disabled ? {
onMouseDown: enabledEventHandlers.onMouseDown
} : enabledEventHandlers;
return {
id: _this.getItemId(index),
role: 'option',
'aria-selected': _this.getState().highlightedIndex === index,
...eventHandlers,
...rest
};
};
this.clearItems = () => {
this.items = [];
};
this.reset = function (otherStateToSet, cb) {
if (otherStateToSet === void 0) {
otherStateToSet = {};
}
otherStateToSet = pickState(otherStateToSet);
_this.internalSetState(_ref => {
let {
selectedItem
} = _ref;
return {
isOpen: _this.props.defaultIsOpen,
highlightedIndex: _this.props.defaultHighlightedIndex,
inputValue: _this.props.itemToString(selectedItem),
...otherStateToSet
};
}, cb);
};
this.toggleMenu = function (otherStateToSet, cb) {
if (otherStateToSet === void 0) {
otherStateToSet = {};
}
otherStateToSet = pickState(otherStateToSet);
_this.internalSetState(_ref2 => {
let {
isOpen
} = _ref2;
return {
isOpen: !isOpen,
...(isOpen && {
highlightedIndex: _this.props.defaultHighlightedIndex
}),
...otherStateToSet
};
}, () => {
const {
isOpen,
highlightedIndex
} = _this.getState();
if (isOpen) {
if (_this.getItemCount() > 0 && typeof highlightedIndex === 'number') {
_this.setHighlightedIndex(highlightedIndex, otherStateToSet);
}
}
cbToCb(cb)();
});
};
this.openMenu = cb => {
this.internalSetState({
isOpen: true
}, cb);
};
this.closeMenu = cb => {
this.internalSetState({
isOpen: false
}, cb);
};
this.updateStatus = downshift_esm_debounce(() => {
const state = this.getState();
const item = this.items[state.highlightedIndex];
const resultCount = this.getItemCount();
const status = this.props.getA11yStatusMessage({
itemToString: this.props.itemToString,
previousResultCount: this.previousResultCount,
resultCount,
highlightedItem: item,
...state
});
this.previousResultCount = resultCount;
setStatus(status, this.props.environment.document);
}, 200);
// fancy destructuring + defaults + aliases
// this basically says each value of state should either be set to
// the initial value or the default value if the initial value is not provided
const {
defaultHighlightedIndex,
initialHighlightedIndex: _highlightedIndex = defaultHighlightedIndex,
defaultIsOpen,
initialIsOpen: _isOpen = defaultIsOpen,
initialInputValue: _inputValue = '',
initialSelectedItem: _selectedItem = null
} = this.props;
const _state = this.getState({
highlightedIndex: _highlightedIndex,
isOpen: _isOpen,
inputValue: _inputValue,
selectedItem: _selectedItem
});
if (_state.selectedItem != null && this.props.initialInputValue === undefined) {
_state.inputValue = this.props.itemToString(_state.selectedItem);
}
this.state = _state;
}
/**
* Clear all running timeouts
*/
internalClearTimeouts() {
this.timeoutIds.forEach(id => {
clearTimeout(id);
});
this.timeoutIds = [];
}
/**
* Gets the state based on internal state or props
* If a state value is passed via props, then that
* is the value given, otherwise it's retrieved from
* stateToMerge
*
* @param {Object} stateToMerge defaults to this.state
* @return {Object} the state
*/
getState(stateToMerge) {
if (stateToMerge === void 0) {
stateToMerge = this.state;
}
return getState(stateToMerge, this.props);
}
getItemCount() {
// things read better this way. They're in priority order:
// 1. `this.itemCount`
// 2. `this.props.itemCount`
// 3. `this.items.length`
let itemCount = this.items.length;
if (this.itemCount != null) {
itemCount = this.itemCount;
} else if (this.props.itemCount !== undefined) {
itemCount = this.props.itemCount;
}
return itemCount;
}
getItemNodeFromIndex(index) {
return this.props.environment.document.getElementById(this.getItemId(index));
}
scrollHighlightedItemIntoView() {
/* istanbul ignore else (react-native) */
{
const node = this.getItemNodeFromIndex(this.getState().highlightedIndex);
this.props.scrollIntoView(node, this._menuNode);
}
}
moveHighlightedIndex(amount, otherStateToSet) {
const itemCount = this.getItemCount();
const {
highlightedIndex
} = this.getState();
if (itemCount > 0) {
const nextHighlightedIndex = getNextWrappingIndex(amount, highlightedIndex, itemCount, index => this.getItemNodeFromIndex(index));
this.setHighlightedIndex(nextHighlightedIndex, otherStateToSet);
}
}
getStateAndHelpers() {
const {
highlightedIndex,
inputValue,
selectedItem,
isOpen
} = this.getState();
const {
itemToString
} = this.props;
const {
id
} = this;
const {
getRootProps,
getToggleButtonProps,
getLabelProps,
getMenuProps,
getInputProps,
getItemProps,
openMenu,
closeMenu,
toggleMenu,
selectItem,
selectItemAtIndex,
selectHighlightedItem,
setHighlightedIndex,
clearSelection,
clearItems,
reset,
setItemCount,
unsetItemCount,
internalSetState: setState
} = this;
return {
// prop getters
getRootProps,
getToggleButtonProps,
getLabelProps,
getMenuProps,
getInputProps,
getItemProps,
// actions
reset,
openMenu,
closeMenu,
toggleMenu,
selectItem,
selectItemAtIndex,
selectHighlightedItem,
setHighlightedIndex,
clearSelection,
clearItems,
setItemCount,
unsetItemCount,
setState,
// props
itemToString,
// derived
id,
// state
highlightedIndex,
inputValue,
isOpen,
selectedItem
};
} //////////////////////////// ROOT
componentDidMount() {
/* istanbul ignore if (react-native) */
if (false) {}
/* istanbul ignore if (react-native) */
{
// this.isMouseDown helps us track whether the mouse is currently held down.
// This is useful when the user clicks on an item in the list, but holds the mouse
// down long enough for the list to disappear (because the blur event fires on the input)
// this.isMouseDown is used in the blur handler on the input to determine whether the blur event should
// trigger hiding the menu.
const onMouseDown = () => {
this.isMouseDown = true;
};
const onMouseUp = event => {
this.isMouseDown = false; // if the target element or the activeElement is within a downshift node
// then we don't want to reset downshift
const contextWithinDownshift = targetWithinDownshift(event.target, [this._rootNode, this._menuNode], this.props.environment);
if (!contextWithinDownshift && this.getState().isOpen) {
this.reset({
type: mouseUp
}, () => this.props.onOuterClick(this.getStateAndHelpers()));
}
}; // Touching an element in iOS gives focus and hover states, but touching out of
// the element will remove hover, and persist the focus state, resulting in the
// blur event not being triggered.
// this.isTouchMove helps us track whether the user is tapping or swiping on a touch screen.
// If the user taps outside of Downshift, the component should be reset,
// but not if the user is swiping
const onTouchStart = () => {
this.isTouchMove = false;
};
const onTouchMove = () => {
this.isTouchMove = true;
};
const onTouchEnd = event => {
const contextWithinDownshift = targetWithinDownshift(event.target, [this._rootNode, this._menuNode], this.props.environment, false);
if (!this.isTouchMove && !contextWithinDownshift && this.getState().isOpen) {
this.reset({
type: touchEnd
}, () => this.props.onOuterClick(this.getStateAndHelpers()));
}
};
const {
environment
} = this.props;
environment.addEventListener('mousedown', onMouseDown);
environment.addEventListener('mouseup', onMouseUp);
environment.addEventListener('touchstart', onTouchStart);
environment.addEventListener('touchmove', onTouchMove);
environment.addEventListener('touchend', onTouchEnd);
this.cleanup = () => {
this.internalClearTimeouts();
this.updateStatus.cancel();
environment.removeEventListener('mousedown', onMouseDown);
environment.removeEventListener('mouseup', onMouseUp);
environment.removeEventListener('touchstart', onTouchStart);
environment.removeEventListener('touchmove', onTouchMove);
environment.removeEventListener('touchend', onTouchEnd);
};
}
}
shouldScroll(prevState, prevProps) {
const {
highlightedIndex: currentHighlightedIndex
} = this.props.highlightedIndex === undefined ? this.getState() : this.props;
const {
highlightedIndex: prevHighlightedIndex
} = prevProps.highlightedIndex === undefined ? prevState : prevProps;
const scrollWhenOpen = currentHighlightedIndex && this.getState().isOpen && !prevState.isOpen;
const scrollWhenNavigating = currentHighlightedIndex !== prevHighlightedIndex;
return scrollWhenOpen || scrollWhenNavigating;
}
componentDidUpdate(prevProps, prevState) {
if (false) {}
if (isControlledProp(this.props, 'selectedItem') && this.props.selectedItemChanged(prevProps.selectedItem, this.props.selectedItem)) {
this.internalSetState({
type: controlledPropUpdatedSelectedItem,
inputValue: this.props.itemToString(this.props.selectedItem)
});
}
if (!this.avoidScrolling && this.shouldScroll(prevState, prevProps)) {
this.scrollHighlightedItemIntoView();
}
/* istanbul ignore else (react-native) */
{
this.updateStatus();
}
}
componentWillUnmount() {
this.cleanup(); // avoids memory leak
}
render() {
const children = unwrapArray(this.props.children, downshift_esm_noop); // because the items are rerendered every time we call the children
// we clear this out each render and it will be populated again as
// getItemProps is called.
this.clearItems(); // we reset this so we know whether the user calls getRootProps during
// this render. If they do then we don't need to do anything,
// if they don't then we need to clone the element they return and
// apply the props for them.
this.getRootProps.called = false;
this.getRootProps.refKey = undefined;
this.getRootProps.suppressRefError = undefined; // we do something similar for getMenuProps
this.getMenuProps.called = false;
this.getMenuProps.refKey = undefined;
this.getMenuProps.suppressRefError = undefined; // we do something similar for getLabelProps
this.getLabelProps.called = false; // and something similar for getInputProps
this.getInputProps.called = false;
const element = unwrapArray(children(this.getStateAndHelpers()));
if (!element) {
return null;
}
if (this.getRootProps.called || this.props.suppressRefError) {
if (false) {}
return element;
} else if (isDOMElement(element)) {
// they didn't apply the root props, but we can clone
// this and apply the props ourselves
return /*#__PURE__*/(0,external_React_.cloneElement)(element, this.getRootProps(getElementProps(element)));
}
/* istanbul ignore else */
if (false) {}
/* istanbul ignore next */
return undefined;
}
}
Downshift.defaultProps = {
defaultHighlightedIndex: null,
defaultIsOpen: false,
getA11yStatusMessage: getA11yStatusMessage$1,
itemToString: i => {
if (i == null) {
return '';
}
if (false) {}
return String(i);
},
onStateChange: downshift_esm_noop,
onInputValueChange: downshift_esm_noop,
onUserAction: downshift_esm_noop,
onChange: downshift_esm_noop,
onSelect: downshift_esm_noop,
onOuterClick: downshift_esm_noop,
selectedItemChanged: (prevItem, item) => prevItem !== item,
environment:
/* istanbul ignore next (ssr) */
typeof window === 'undefined' ? {} : window,
stateReducer: (state, stateToSet) => stateToSet,
suppressRefError: false,
scrollIntoView
};
Downshift.stateChangeTypes = stateChangeTypes$3;
return Downshift;
})();
false ? 0 : void 0;
var Downshift$1 = Downshift;
function validateGetMenuPropsCalledCorrectly(node, _ref3) {
let {
refKey
} = _ref3;
if (!node) {
// eslint-disable-next-line no-console
console.error(`downshift: The ref prop "${refKey}" from getMenuProps was not applied correctly on your menu element.`);
}
}
function validateGetRootPropsCalledCorrectly(element, _ref4) {
let {
refKey
} = _ref4;
const refKeySpecified = refKey !== 'ref';
const isComposite = !isDOMElement(element);
if (isComposite && !refKeySpecified && !isForwardRef(element)) {
// eslint-disable-next-line no-console
console.error('downshift: You returned a non-DOM element. You must specify a refKey in getRootProps');
} else if (!isComposite && refKeySpecified) {
// eslint-disable-next-line no-console
console.error(`downshift: You returned a DOM element. You should not specify a refKey in getRootProps. You specified "${refKey}"`);
}
if (!isForwardRef(element) && !getElementProps(element)[refKey]) {
// eslint-disable-next-line no-console
console.error(`downshift: You must apply the ref prop "${refKey}" from getRootProps onto your root element.`);
}
}
const dropdownDefaultStateValues = {
highlightedIndex: -1,
isOpen: false,
selectedItem: null,
inputValue: ''
};
function callOnChangeProps(action, state, newState) {
const {
props,
type
} = action;
const changes = {};
Object.keys(state).forEach(key => {
invokeOnChangeHandler(key, action, state, newState);
if (newState[key] !== state[key]) {
changes[key] = newState[key];
}
});
if (props.onStateChange && Object.keys(changes).length) {
props.onStateChange({
type,
...changes
});
}
}
function invokeOnChangeHandler(key, action, state, newState) {
const {
props,
type
} = action;
const handler = `on${capitalizeString(key)}Change`;
if (props[handler] && newState[key] !== undefined && newState[key] !== state[key]) {
props[handler]({
type,
...newState
});
}
}
/**
* Default state reducer that returns the changes.
*
* @param {Object} s state.
* @param {Object} a action with changes.
* @returns {Object} changes.
*/
function stateReducer(s, a) {
return a.changes;
}
/**
* Returns a message to be added to aria-live region when item is selected.
*
* @param {Object} selectionParameters Parameters required to build the message.
* @returns {string} The a11y message.
*/
function getA11ySelectionMessage(selectionParameters) {
const {
selectedItem,
itemToString: itemToStringLocal
} = selectionParameters;
return selectedItem ? `${itemToStringLocal(selectedItem)} has been selected.` : '';
}
/**
* Debounced call for updating the a11y message.
*/
const updateA11yStatus = downshift_esm_debounce((getA11yMessage, document) => {
setStatus(getA11yMessage(), document);
}, 200); // istanbul ignore next
const downshift_esm_useIsomorphicLayoutEffect = typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined' ? external_React_.useLayoutEffect : external_React_.useEffect;
function useElementIds(_ref) {
let {
id = `downshift-${generateId()}`,
labelId,
menuId,
getItemId,
toggleButtonId,
inputId
} = _ref;
const elementIdsRef = (0,external_React_.useRef)({
labelId: labelId || `${id}-label`,
menuId: menuId || `${id}-menu`,
getItemId: getItemId || (index => `${id}-item-${index}`),
toggleButtonId: toggleButtonId || `${id}-toggle-button`,
inputId: inputId || `${id}-input`
});
return elementIdsRef.current;
}
function getItemIndex(index, item, items) {
if (index !== undefined) {
return index;
}
if (items.length === 0) {
return -1;
}
return items.indexOf(item);
}
function itemToString(item) {
return item ? String(item) : '';
}
function isAcceptedCharacterKey(key) {
return /^\S{1}$/.test(key);
}
function capitalizeString(string) {
return `${string.slice(0, 1).toUpperCase()}${string.slice(1)}`;
}
function downshift_esm_useLatestRef(val) {
const ref = (0,external_React_.useRef)(val); // technically this is not "concurrent mode safe" because we're manipulating
// the value during render (so it's not idempotent). However, the places this
// hook is used is to support memoizing callbacks which will be called
// *during* render, so we need the latest values *during* render.
// If not for this, then we'd probably want to use useLayoutEffect instead.
ref.current = val;
return ref;
}
/**
* Computes the controlled state using a the previous state, props,
* two reducers, one from downshift and an optional one from the user.
* Also calls the onChange handlers for state values that have changed.
*
* @param {Function} reducer Reducer function from downshift.
* @param {Object} initialState Initial state of the hook.
* @param {Object} props The hook props.
* @returns {Array} An array with the state and an action dispatcher.
*/
function useEnhancedReducer(reducer, initialState, props) {
const prevStateRef = (0,external_React_.useRef)();
const actionRef = (0,external_React_.useRef)();
const enhancedReducer = (0,external_React_.useCallback)((state, action) => {
actionRef.current = action;
state = getState(state, action.props);
const changes = reducer(state, action);
const newState = action.props.stateReducer(state, { ...action,
changes
});
return newState;
}, [reducer]);
const [state, dispatch] = (0,external_React_.useReducer)(enhancedReducer, initialState);
const propsRef = downshift_esm_useLatestRef(props);
const dispatchWithProps = (0,external_React_.useCallback)(action => dispatch({
props: propsRef.current,
...action
}), [propsRef]);
const action = actionRef.current;
(0,external_React_.useEffect)(() => {
if (action && prevStateRef.current && prevStateRef.current !== state) {
callOnChangeProps(action, getState(prevStateRef.current, action.props), state);
}
prevStateRef.current = state;
}, [state, props, action]);
return [state, dispatchWithProps];
}
/**
* Wraps the useEnhancedReducer and applies the controlled prop values before
* returning the new state.
*
* @param {Function} reducer Reducer function from downshift.
* @param {Object} initialState Initial state of the hook.
* @param {Object} props The hook props.
* @returns {Array} An array with the state and an action dispatcher.
*/
function useControlledReducer$1(reducer, initialState, props) {
const [state, dispatch] = useEnhancedReducer(reducer, initialState, props);
return [getState(state, props), dispatch];
}
const defaultProps$3 = {
itemToString,
stateReducer,
getA11ySelectionMessage,
scrollIntoView,
circularNavigation: false,
environment:
/* istanbul ignore next (ssr) */
typeof window === 'undefined' ? {} : window
};
function getDefaultValue$1(props, propKey, defaultStateValues) {
if (defaultStateValues === void 0) {
defaultStateValues = dropdownDefaultStateValues;
}
const defaultValue = props[`default${capitalizeString(propKey)}`];
if (defaultValue !== undefined) {
return defaultValue;
}
return defaultStateValues[propKey];
}
function getInitialValue$1(props, propKey, defaultStateValues) {
if (defaultStateValues === void 0) {
defaultStateValues = dropdownDefaultStateValues;
}
const value = props[propKey];
if (value !== undefined) {
return value;
}
const initialValue = props[`initial${capitalizeString(propKey)}`];
if (initialValue !== undefined) {
return initialValue;
}
return getDefaultValue$1(props, propKey, defaultStateValues);
}
function getInitialState$2(props) {
const selectedItem = getInitialValue$1(props, 'selectedItem');
const isOpen = getInitialValue$1(props, 'isOpen');
const highlightedIndex = getInitialValue$1(props, 'highlightedIndex');
const inputValue = getInitialValue$1(props, 'inputValue');
return {
highlightedIndex: highlightedIndex < 0 && selectedItem && isOpen ? props.items.indexOf(selectedItem) : highlightedIndex,
isOpen,
selectedItem,
inputValue
};
}
function getHighlightedIndexOnOpen(props, state, offset, getItemNodeFromIndex) {
const {
items,
initialHighlightedIndex,
defaultHighlightedIndex
} = props;
const {
selectedItem,
highlightedIndex
} = state;
if (items.length === 0) {
return -1;
} // initialHighlightedIndex will give value to highlightedIndex on initial state only.
if (initialHighlightedIndex !== undefined && highlightedIndex === initialHighlightedIndex) {
return initialHighlightedIndex;
}
if (defaultHighlightedIndex !== undefined) {
return defaultHighlightedIndex;
}
if (selectedItem) {
if (offset === 0) {
return items.indexOf(selectedItem);
}
return getNextWrappingIndex(offset, items.indexOf(selectedItem), items.length, getItemNodeFromIndex, false);
}
if (offset === 0) {
return -1;
}
return offset < 0 ? items.length - 1 : 0;
}
/**
* Reuse the movement tracking of mouse and touch events.
*
* @param {boolean} isOpen Whether the dropdown is open or not.
* @param {Array<Object>} downshiftElementRefs Downshift element refs to track movement (toggleButton, menu etc.)
* @param {Object} environment Environment where component/hook exists.
* @param {Function} handleBlur Handler on blur from mouse or touch.
* @returns {Object} Ref containing whether mouseDown or touchMove event is happening
*/
function useMouseAndTouchTracker(isOpen, downshiftElementRefs, environment, handleBlur) {
const mouseAndTouchTrackersRef = (0,external_React_.useRef)({
isMouseDown: false,
isTouchMove: false
});
(0,external_React_.useEffect)(() => {
// The same strategy for checking if a click occurred inside or outside downsift
// as in downshift.js.
const onMouseDown = () => {
mouseAndTouchTrackersRef.current.isMouseDown = true;
};
const onMouseUp = event => {
mouseAndTouchTrackersRef.current.isMouseDown = false;
if (isOpen && !targetWithinDownshift(event.target, downshiftElementRefs.map(ref => ref.current), environment)) {
handleBlur();
}
};
const onTouchStart = () => {
mouseAndTouchTrackersRef.current.isTouchMove = false;
};
const onTouchMove = () => {
mouseAndTouchTrackersRef.current.isTouchMove = true;
};
const onTouchEnd = event => {
if (isOpen && !mouseAndTouchTrackersRef.current.isTouchMove && !targetWithinDownshift(event.target, downshiftElementRefs.map(ref => ref.current), environment, false)) {
handleBlur();
}
};
environment.addEventListener('mousedown', onMouseDown);
environment.addEventListener('mouseup', onMouseUp);
environment.addEventListener('touchstart', onTouchStart);
environment.addEventListener('touchmove', onTouchMove);
environment.addEventListener('touchend', onTouchEnd);
return function cleanup() {
environment.removeEventListener('mousedown', onMouseDown);
environment.removeEventListener('mouseup', onMouseUp);
environment.removeEventListener('touchstart', onTouchStart);
environment.removeEventListener('touchmove', onTouchMove);
environment.removeEventListener('touchend', onTouchEnd);
}; // eslint-disable-next-line react-hooks/exhaustive-deps
}, [isOpen, environment]);
return mouseAndTouchTrackersRef;
}
/* istanbul ignore next */
// eslint-disable-next-line import/no-mutable-exports
let useGetterPropsCalledChecker = () => downshift_esm_noop;
/**
* Custom hook that checks if getter props are called correctly.
*
* @param {...any} propKeys Getter prop names to be handled.
* @returns {Function} Setter function called inside getter props to set call information.
*/
/* istanbul ignore next */
if (false) {}
function useA11yMessageSetter(getA11yMessage, dependencyArray, _ref2) {
let {
isInitialMount,
highlightedIndex,
items,
environment,
...rest
} = _ref2;
// Sets a11y status message on changes in state.
(0,external_React_.useEffect)(() => {
if (isInitialMount || false) {
return;
}
updateA11yStatus(() => getA11yMessage({
highlightedIndex,
highlightedItem: items[highlightedIndex],
resultCount: items.length,
...rest
}), environment.document); // eslint-disable-next-line react-hooks/exhaustive-deps
}, dependencyArray);
}
function useScrollIntoView(_ref3) {
let {
highlightedIndex,
isOpen,
itemRefs,
getItemNodeFromIndex,
menuElement,
scrollIntoView: scrollIntoViewProp
} = _ref3;
// used not to scroll on highlight by mouse.
const shouldScrollRef = (0,external_React_.useRef)(true); // Scroll on highlighted item if change comes from keyboard.
downshift_esm_useIsomorphicLayoutEffect(() => {
if (highlightedIndex < 0 || !isOpen || !Object.keys(itemRefs.current).length) {
return;
}
if (shouldScrollRef.current === false) {
shouldScrollRef.current = true;
} else {
scrollIntoViewProp(getItemNodeFromIndex(highlightedIndex), menuElement);
} // eslint-disable-next-line react-hooks/exhaustive-deps
}, [highlightedIndex]);
return shouldScrollRef;
} // eslint-disable-next-line import/no-mutable-exports
let useControlPropsValidator = downshift_esm_noop;
/* istanbul ignore next */
if (false) {}
/* eslint-disable complexity */
function downshiftCommonReducer(state, action, stateChangeTypes) {
const {
type,
props
} = action;
let changes;
switch (type) {
case stateChangeTypes.ItemMouseMove:
changes = {
highlightedIndex: action.disabled ? -1 : action.index
};
break;
case stateChangeTypes.MenuMouseLeave:
changes = {
highlightedIndex: -1
};
break;
case stateChangeTypes.ToggleButtonClick:
case stateChangeTypes.FunctionToggleMenu:
changes = {
isOpen: !state.isOpen,
highlightedIndex: state.isOpen ? -1 : getHighlightedIndexOnOpen(props, state, 0)
};
break;
case stateChangeTypes.FunctionOpenMenu:
changes = {
isOpen: true,
highlightedIndex: getHighlightedIndexOnOpen(props, state, 0)
};
break;
case stateChangeTypes.FunctionCloseMenu:
changes = {
isOpen: false
};
break;
case stateChangeTypes.FunctionSetHighlightedIndex:
changes = {
highlightedIndex: action.highlightedIndex
};
break;
case stateChangeTypes.FunctionSetInputValue:
changes = {
inputValue: action.inputValue
};
break;
case stateChangeTypes.FunctionReset:
changes = {
highlightedIndex: getDefaultValue$1(props, 'highlightedIndex'),
isOpen: getDefaultValue$1(props, 'isOpen'),
selectedItem: getDefaultValue$1(props, 'selectedItem'),
inputValue: getDefaultValue$1(props, 'inputValue')
};
break;
default:
throw new Error('Reducer called without proper action type.');
}
return { ...state,
...changes
};
}
/* eslint-enable complexity */
function getItemIndexByCharacterKey(_a) {
var keysSoFar = _a.keysSoFar, highlightedIndex = _a.highlightedIndex, items = _a.items, itemToString = _a.itemToString, getItemNodeFromIndex = _a.getItemNodeFromIndex;
var lowerCasedKeysSoFar = keysSoFar.toLowerCase();
for (var index = 0; index < items.length; index++) {
var offsetIndex = (index + highlightedIndex + 1) % items.length;
var item = items[offsetIndex];
if (item !== undefined &&
itemToString(item)
.toLowerCase()
.startsWith(lowerCasedKeysSoFar)) {
var element = getItemNodeFromIndex(offsetIndex);
if (!(element === null || element === void 0 ? void 0 : element.hasAttribute('disabled'))) {
return offsetIndex;
}
}
}
return highlightedIndex;
}
var propTypes$2 = {
items: (prop_types_default()).array.isRequired,
itemToString: (prop_types_default()).func,
getA11yStatusMessage: (prop_types_default()).func,
getA11ySelectionMessage: (prop_types_default()).func,
circularNavigation: (prop_types_default()).bool,
highlightedIndex: (prop_types_default()).number,
defaultHighlightedIndex: (prop_types_default()).number,
initialHighlightedIndex: (prop_types_default()).number,
isOpen: (prop_types_default()).bool,
defaultIsOpen: (prop_types_default()).bool,
initialIsOpen: (prop_types_default()).bool,
selectedItem: (prop_types_default()).any,
initialSelectedItem: (prop_types_default()).any,
defaultSelectedItem: (prop_types_default()).any,
id: (prop_types_default()).string,
labelId: (prop_types_default()).string,
menuId: (prop_types_default()).string,
getItemId: (prop_types_default()).func,
toggleButtonId: (prop_types_default()).string,
stateReducer: (prop_types_default()).func,
onSelectedItemChange: (prop_types_default()).func,
onHighlightedIndexChange: (prop_types_default()).func,
onStateChange: (prop_types_default()).func,
onIsOpenChange: (prop_types_default()).func,
environment: prop_types_default().shape({
addEventListener: (prop_types_default()).func,
removeEventListener: (prop_types_default()).func,
document: prop_types_default().shape({
getElementById: (prop_types_default()).func,
activeElement: (prop_types_default()).any,
body: (prop_types_default()).any
})
})
};
/**
* Default implementation for status message. Only added when menu is open.
* Will specift if there are results in the list, and if so, how many,
* and what keys are relevant.
*
* @param {Object} param the downshift state and other relevant properties
* @return {String} the a11y status message
*/
function getA11yStatusMessage(_a) {
var isOpen = _a.isOpen, resultCount = _a.resultCount, previousResultCount = _a.previousResultCount;
if (!isOpen) {
return '';
}
if (!resultCount) {
return 'No results are available.';
}
if (resultCount !== previousResultCount) {
return "".concat(resultCount, " result").concat(resultCount === 1 ? ' is' : 's are', " available, use up and down arrow keys to navigate. Press Enter or Space Bar keys to select.");
}
return '';
}
var defaultProps$2 = __assign(__assign({}, defaultProps$3), { getA11yStatusMessage: getA11yStatusMessage });
// eslint-disable-next-line import/no-mutable-exports
var validatePropTypes$2 = downshift_esm_noop;
/* istanbul ignore next */
if (false) {}
const MenuKeyDownArrowDown = false ? 0 : 0;
const MenuKeyDownArrowUp = false ? 0 : 1;
const MenuKeyDownEscape = false ? 0 : 2;
const MenuKeyDownHome = false ? 0 : 3;
const MenuKeyDownEnd = false ? 0 : 4;
const MenuKeyDownEnter = false ? 0 : 5;
const MenuKeyDownSpaceButton = false ? 0 : 6;
const MenuKeyDownCharacter = false ? 0 : 7;
const MenuBlur = false ? 0 : 8;
const MenuMouseLeave$1 = false ? 0 : 9;
const ItemMouseMove$1 = false ? 0 : 10;
const ItemClick$1 = false ? 0 : 11;
const ToggleButtonClick$1 = false ? 0 : 12;
const ToggleButtonKeyDownArrowDown = false ? 0 : 13;
const ToggleButtonKeyDownArrowUp = false ? 0 : 14;
const ToggleButtonKeyDownCharacter = false ? 0 : 15;
const FunctionToggleMenu$1 = false ? 0 : 16;
const FunctionOpenMenu$1 = false ? 0 : 17;
const FunctionCloseMenu$1 = false ? 0 : 18;
const FunctionSetHighlightedIndex$1 = false ? 0 : 19;
const FunctionSelectItem$1 = false ? 0 : 20;
const FunctionSetInputValue$1 = false ? 0 : 21;
const FunctionReset$2 = false ? 0 : 22;
var stateChangeTypes$2 = /*#__PURE__*/Object.freeze({
__proto__: null,
MenuKeyDownArrowDown: MenuKeyDownArrowDown,
MenuKeyDownArrowUp: MenuKeyDownArrowUp,
MenuKeyDownEscape: MenuKeyDownEscape,
MenuKeyDownHome: MenuKeyDownHome,
MenuKeyDownEnd: MenuKeyDownEnd,
MenuKeyDownEnter: MenuKeyDownEnter,
MenuKeyDownSpaceButton: MenuKeyDownSpaceButton,
MenuKeyDownCharacter: MenuKeyDownCharacter,
MenuBlur: MenuBlur,
MenuMouseLeave: MenuMouseLeave$1,
ItemMouseMove: ItemMouseMove$1,
ItemClick: ItemClick$1,
ToggleButtonClick: ToggleButtonClick$1,
ToggleButtonKeyDownArrowDown: ToggleButtonKeyDownArrowDown,
ToggleButtonKeyDownArrowUp: ToggleButtonKeyDownArrowUp,
ToggleButtonKeyDownCharacter: ToggleButtonKeyDownCharacter,
FunctionToggleMenu: FunctionToggleMenu$1,
FunctionOpenMenu: FunctionOpenMenu$1,
FunctionCloseMenu: FunctionCloseMenu$1,
FunctionSetHighlightedIndex: FunctionSetHighlightedIndex$1,
FunctionSelectItem: FunctionSelectItem$1,
FunctionSetInputValue: FunctionSetInputValue$1,
FunctionReset: FunctionReset$2
});
/* eslint-disable complexity */
function downshiftSelectReducer(state, action) {
const {
type,
props,
shiftKey
} = action;
let changes;
switch (type) {
case ItemClick$1:
changes = {
isOpen: getDefaultValue$1(props, 'isOpen'),
highlightedIndex: getDefaultValue$1(props, 'highlightedIndex'),
selectedItem: props.items[action.index]
};
break;
case ToggleButtonKeyDownCharacter:
{
const lowercasedKey = action.key;
const inputValue = `${state.inputValue}${lowercasedKey}`;
const itemIndex = getItemIndexByCharacterKey({
keysSoFar: inputValue,
highlightedIndex: state.selectedItem ? props.items.indexOf(state.selectedItem) : -1,
items: props.items,
itemToString: props.itemToString,
getItemNodeFromIndex: action.getItemNodeFromIndex
});
changes = {
inputValue,
...(itemIndex >= 0 && {
selectedItem: props.items[itemIndex]
})
};
}
break;
case ToggleButtonKeyDownArrowDown:
changes = {
highlightedIndex: getHighlightedIndexOnOpen(props, state, 1, action.getItemNodeFromIndex),
isOpen: true
};
break;
case ToggleButtonKeyDownArrowUp:
changes = {
highlightedIndex: getHighlightedIndexOnOpen(props, state, -1, action.getItemNodeFromIndex),
isOpen: true
};
break;
case MenuKeyDownEnter:
case MenuKeyDownSpaceButton:
changes = {
isOpen: getDefaultValue$1(props, 'isOpen'),
highlightedIndex: getDefaultValue$1(props, 'highlightedIndex'),
...(state.highlightedIndex >= 0 && {
selectedItem: props.items[state.highlightedIndex]
})
};
break;
case MenuKeyDownHome:
changes = {
highlightedIndex: getNextNonDisabledIndex(1, 0, props.items.length, action.getItemNodeFromIndex, false)
};
break;
case MenuKeyDownEnd:
changes = {
highlightedIndex: getNextNonDisabledIndex(-1, props.items.length - 1, props.items.length, action.getItemNodeFromIndex, false)
};
break;
case MenuKeyDownEscape:
changes = {
isOpen: false,
highlightedIndex: -1
};
break;
case MenuBlur:
changes = {
isOpen: false,
highlightedIndex: -1
};
break;
case MenuKeyDownCharacter:
{
const lowercasedKey = action.key;
const inputValue = `${state.inputValue}${lowercasedKey}`;
const highlightedIndex = getItemIndexByCharacterKey({
keysSoFar: inputValue,
highlightedIndex: state.highlightedIndex,
items: props.items,
itemToString: props.itemToString,
getItemNodeFromIndex: action.getItemNodeFromIndex
});
changes = {
inputValue,
...(highlightedIndex >= 0 && {
highlightedIndex
})
};
}
break;
case MenuKeyDownArrowDown:
changes = {
highlightedIndex: getNextWrappingIndex(shiftKey ? 5 : 1, state.highlightedIndex, props.items.length, action.getItemNodeFromIndex, props.circularNavigation)
};
break;
case MenuKeyDownArrowUp:
changes = {
highlightedIndex: getNextWrappingIndex(shiftKey ? -5 : -1, state.highlightedIndex, props.items.length, action.getItemNodeFromIndex, props.circularNavigation)
};
break;
case FunctionSelectItem$1:
changes = {
selectedItem: action.selectedItem
};
break;
default:
return downshiftCommonReducer(state, action, stateChangeTypes$2);
}
return { ...state,
...changes
};
}
/* eslint-enable complexity */
/* eslint-disable max-statements */
useSelect.stateChangeTypes = stateChangeTypes$2;
function useSelect(userProps) {
if (userProps === void 0) {
userProps = {};
}
validatePropTypes$2(userProps, useSelect); // Props defaults and destructuring.
const props = { ...defaultProps$2,
...userProps
};
const {
items,
scrollIntoView,
environment,
initialIsOpen,
defaultIsOpen,
itemToString,
getA11ySelectionMessage,
getA11yStatusMessage
} = props; // Initial state depending on controlled props.
const initialState = getInitialState$2(props);
const [state, dispatch] = useControlledReducer$1(downshiftSelectReducer, initialState, props);
const {
isOpen,
highlightedIndex,
selectedItem,
inputValue
} = state; // Element efs.
const toggleButtonRef = (0,external_React_.useRef)(null);
const menuRef = (0,external_React_.useRef)(null);
const itemRefs = (0,external_React_.useRef)({}); // used not to trigger menu blur action in some scenarios.
const shouldBlurRef = (0,external_React_.useRef)(true); // used to keep the inputValue clearTimeout object between renders.
const clearTimeoutRef = (0,external_React_.useRef)(null); // prevent id re-generation between renders.
const elementIds = useElementIds(props); // used to keep track of how many items we had on previous cycle.
const previousResultCountRef = (0,external_React_.useRef)();
const isInitialMountRef = (0,external_React_.useRef)(true); // utility callback to get item element.
const latest = downshift_esm_useLatestRef({
state,
props
}); // Some utils.
const getItemNodeFromIndex = (0,external_React_.useCallback)(index => itemRefs.current[elementIds.getItemId(index)], [elementIds]); // Effects.
// Sets a11y status message on changes in state.
useA11yMessageSetter(getA11yStatusMessage, [isOpen, highlightedIndex, inputValue, items], {
isInitialMount: isInitialMountRef.current,
previousResultCount: previousResultCountRef.current,
items,
environment,
itemToString,
...state
}); // Sets a11y status message on changes in selectedItem.
useA11yMessageSetter(getA11ySelectionMessage, [selectedItem], {
isInitialMount: isInitialMountRef.current,
previousResultCount: previousResultCountRef.current,
items,
environment,
itemToString,
...state
}); // Scroll on highlighted item if change comes from keyboard.
const shouldScrollRef = useScrollIntoView({
menuElement: menuRef.current,
highlightedIndex,
isOpen,
itemRefs,
scrollIntoView,
getItemNodeFromIndex
}); // Sets cleanup for the keysSoFar callback, debounded after 500ms.
(0,external_React_.useEffect)(() => {
// init the clean function here as we need access to dispatch.
clearTimeoutRef.current = downshift_esm_debounce(outerDispatch => {
outerDispatch({
type: FunctionSetInputValue$1,
inputValue: ''
});
}, 500); // Cancel any pending debounced calls on mount
return () => {
clearTimeoutRef.current.cancel();
};
}, []); // Invokes the keysSoFar callback set up above.
(0,external_React_.useEffect)(() => {
if (!inputValue) {
return;
}
clearTimeoutRef.current(dispatch);
}, [dispatch, inputValue]);
useControlPropsValidator({
isInitialMount: isInitialMountRef.current,
props,
state
});
/* Controls the focus on the menu or the toggle button. */
(0,external_React_.useEffect)(() => {
// Don't focus menu on first render.
if (isInitialMountRef.current) {
// Unless it was initialised as open.
if ((initialIsOpen || defaultIsOpen || isOpen) && menuRef.current) {
menuRef.current.focus();
}
return;
} // Focus menu on open.
if (isOpen) {
// istanbul ignore else
if (menuRef.current) {
menuRef.current.focus();
}
return;
} // Focus toggleButton on close, but not if it was closed with (Shift+)Tab.
if (environment.document.activeElement === menuRef.current) {
// istanbul ignore else
if (toggleButtonRef.current) {
shouldBlurRef.current = false;
toggleButtonRef.current.focus();
}
} // eslint-disable-next-line react-hooks/exhaustive-deps
}, [isOpen]);
(0,external_React_.useEffect)(() => {
if (isInitialMountRef.current) {
return;
}
previousResultCountRef.current = items.length;
}); // Add mouse/touch events to document.
const mouseAndTouchTrackersRef = useMouseAndTouchTracker(isOpen, [menuRef, toggleButtonRef], environment, () => {
dispatch({
type: MenuBlur
});
});
const setGetterPropCallInfo = useGetterPropsCalledChecker('getMenuProps', 'getToggleButtonProps'); // Make initial ref false.
(0,external_React_.useEffect)(() => {
isInitialMountRef.current = false;
}, []); // Reset itemRefs on close.
(0,external_React_.useEffect)(() => {
if (!isOpen) {
itemRefs.current = {};
}
}, [isOpen]); // Event handler functions.
const toggleButtonKeyDownHandlers = (0,external_React_.useMemo)(() => ({
ArrowDown(event) {
event.preventDefault();
dispatch({
type: ToggleButtonKeyDownArrowDown,
getItemNodeFromIndex,
shiftKey: event.shiftKey
});
},
ArrowUp(event) {
event.preventDefault();
dispatch({
type: ToggleButtonKeyDownArrowUp,
getItemNodeFromIndex,
shiftKey: event.shiftKey
});
}
}), [dispatch, getItemNodeFromIndex]);
const menuKeyDownHandlers = (0,external_React_.useMemo)(() => ({
ArrowDown(event) {
event.preventDefault();
dispatch({
type: MenuKeyDownArrowDown,
getItemNodeFromIndex,
shiftKey: event.shiftKey
});
},
ArrowUp(event) {
event.preventDefault();
dispatch({
type: MenuKeyDownArrowUp,
getItemNodeFromIndex,
shiftKey: event.shiftKey
});
},
Home(event) {
event.preventDefault();
dispatch({
type: MenuKeyDownHome,
getItemNodeFromIndex
});
},
End(event) {
event.preventDefault();
dispatch({
type: MenuKeyDownEnd,
getItemNodeFromIndex
});
},
Escape() {
dispatch({
type: MenuKeyDownEscape
});
},
Enter(event) {
event.preventDefault();
dispatch({
type: MenuKeyDownEnter
});
},
' '(event) {
event.preventDefault();
dispatch({
type: MenuKeyDownSpaceButton
});
}
}), [dispatch, getItemNodeFromIndex]); // Action functions.
const toggleMenu = (0,external_React_.useCallback)(() => {
dispatch({
type: FunctionToggleMenu$1
});
}, [dispatch]);
const closeMenu = (0,external_React_.useCallback)(() => {
dispatch({
type: FunctionCloseMenu$1
});
}, [dispatch]);
const openMenu = (0,external_React_.useCallback)(() => {
dispatch({
type: FunctionOpenMenu$1
});
}, [dispatch]);
const setHighlightedIndex = (0,external_React_.useCallback)(newHighlightedIndex => {
dispatch({
type: FunctionSetHighlightedIndex$1,
highlightedIndex: newHighlightedIndex
});
}, [dispatch]);
const selectItem = (0,external_React_.useCallback)(newSelectedItem => {
dispatch({
type: FunctionSelectItem$1,
selectedItem: newSelectedItem
});
}, [dispatch]);
const reset = (0,external_React_.useCallback)(() => {
dispatch({
type: FunctionReset$2
});
}, [dispatch]);
const setInputValue = (0,external_React_.useCallback)(newInputValue => {
dispatch({
type: FunctionSetInputValue$1,
inputValue: newInputValue
});
}, [dispatch]); // Getter functions.
const getLabelProps = (0,external_React_.useCallback)(labelProps => ({
id: elementIds.labelId,
htmlFor: elementIds.toggleButtonId,
...labelProps
}), [elementIds]);
const getMenuProps = (0,external_React_.useCallback)(function (_temp, _temp2) {
let {
onMouseLeave,
refKey = 'ref',
onKeyDown,
onBlur,
ref,
...rest
} = _temp === void 0 ? {} : _temp;
let {
suppressRefError = false
} = _temp2 === void 0 ? {} : _temp2;
const latestState = latest.current.state;
const menuHandleKeyDown = event => {
const key = normalizeArrowKey(event);
if (key && menuKeyDownHandlers[key]) {
menuKeyDownHandlers[key](event);
} else if (isAcceptedCharacterKey(key)) {
dispatch({
type: MenuKeyDownCharacter,
key,
getItemNodeFromIndex
});
}
};
const menuHandleBlur = () => {
// if the blur was a result of selection, we don't trigger this action.
if (shouldBlurRef.current === false) {
shouldBlurRef.current = true;
return;
}
const shouldBlur = !mouseAndTouchTrackersRef.current.isMouseDown;
/* istanbul ignore else */
if (shouldBlur) {
dispatch({
type: MenuBlur
});
}
};
const menuHandleMouseLeave = () => {
dispatch({
type: MenuMouseLeave$1
});
};
setGetterPropCallInfo('getMenuProps', suppressRefError, refKey, menuRef);
return {
[refKey]: handleRefs(ref, menuNode => {
menuRef.current = menuNode;
}),
id: elementIds.menuId,
role: 'listbox',
'aria-labelledby': elementIds.labelId,
tabIndex: -1,
...(latestState.isOpen && latestState.highlightedIndex > -1 && {
'aria-activedescendant': elementIds.getItemId(latestState.highlightedIndex)
}),
onMouseLeave: callAllEventHandlers(onMouseLeave, menuHandleMouseLeave),
onKeyDown: callAllEventHandlers(onKeyDown, menuHandleKeyDown),
onBlur: callAllEventHandlers(onBlur, menuHandleBlur),
...rest
};
}, [dispatch, latest, menuKeyDownHandlers, mouseAndTouchTrackersRef, setGetterPropCallInfo, elementIds, getItemNodeFromIndex]);
const getToggleButtonProps = (0,external_React_.useCallback)(function (_temp3, _temp4) {
let {
onClick,
onKeyDown,
refKey = 'ref',
ref,
...rest
} = _temp3 === void 0 ? {} : _temp3;
let {
suppressRefError = false
} = _temp4 === void 0 ? {} : _temp4;
const toggleButtonHandleClick = () => {
dispatch({
type: ToggleButtonClick$1
});
};
const toggleButtonHandleKeyDown = event => {
const key = normalizeArrowKey(event);
if (key && toggleButtonKeyDownHandlers[key]) {
toggleButtonKeyDownHandlers[key](event);
} else if (isAcceptedCharacterKey(key)) {
dispatch({
type: ToggleButtonKeyDownCharacter,
key,
getItemNodeFromIndex
});
}
};
const toggleProps = {
[refKey]: handleRefs(ref, toggleButtonNode => {
toggleButtonRef.current = toggleButtonNode;
}),
id: elementIds.toggleButtonId,
'aria-haspopup': 'listbox',
'aria-expanded': latest.current.state.isOpen,
'aria-labelledby': `${elementIds.labelId} ${elementIds.toggleButtonId}`,
...rest
};
if (!rest.disabled) {
toggleProps.onClick = callAllEventHandlers(onClick, toggleButtonHandleClick);
toggleProps.onKeyDown = callAllEventHandlers(onKeyDown, toggleButtonHandleKeyDown);
}
setGetterPropCallInfo('getToggleButtonProps', suppressRefError, refKey, toggleButtonRef);
return toggleProps;
}, [dispatch, latest, toggleButtonKeyDownHandlers, setGetterPropCallInfo, elementIds, getItemNodeFromIndex]);
const getItemProps = (0,external_React_.useCallback)(function (_temp5) {
let {
item,
index,
onMouseMove,
onClick,
refKey = 'ref',
ref,
disabled,
...rest
} = _temp5 === void 0 ? {} : _temp5;
const {
state: latestState,
props: latestProps
} = latest.current;
const itemHandleMouseMove = () => {
if (index === latestState.highlightedIndex) {
return;
}
shouldScrollRef.current = false;
dispatch({
type: ItemMouseMove$1,
index,
disabled
});
};
const itemHandleClick = () => {
dispatch({
type: ItemClick$1,
index
});
};
const itemIndex = getItemIndex(index, item, latestProps.items);
if (itemIndex < 0) {
throw new Error('Pass either item or item index in getItemProps!');
}
const itemProps = {
disabled,
role: 'option',
'aria-selected': `${itemIndex === latestState.highlightedIndex}`,
id: elementIds.getItemId(itemIndex),
[refKey]: handleRefs(ref, itemNode => {
if (itemNode) {
itemRefs.current[elementIds.getItemId(itemIndex)] = itemNode;
}
}),
...rest
};
if (!disabled) {
itemProps.onClick = callAllEventHandlers(onClick, itemHandleClick);
}
itemProps.onMouseMove = callAllEventHandlers(onMouseMove, itemHandleMouseMove);
return itemProps;
}, [dispatch, latest, shouldScrollRef, elementIds]);
return {
// prop getters.
getToggleButtonProps,
getLabelProps,
getMenuProps,
getItemProps,
// actions.
toggleMenu,
openMenu,
closeMenu,
setHighlightedIndex,
selectItem,
reset,
setInputValue,
// state.
highlightedIndex,
isOpen,
selectedItem,
inputValue
};
}
const InputKeyDownArrowDown = false ? 0 : 0;
const InputKeyDownArrowUp = false ? 0 : 1;
const InputKeyDownEscape = false ? 0 : 2;
const InputKeyDownHome = false ? 0 : 3;
const InputKeyDownEnd = false ? 0 : 4;
const InputKeyDownEnter = false ? 0 : 5;
const InputChange = false ? 0 : 6;
const InputBlur = false ? 0 : 7;
const MenuMouseLeave = false ? 0 : 8;
const ItemMouseMove = false ? 0 : 9;
const ItemClick = false ? 0 : 10;
const ToggleButtonClick = false ? 0 : 11;
const FunctionToggleMenu = false ? 0 : 12;
const FunctionOpenMenu = false ? 0 : 13;
const FunctionCloseMenu = false ? 0 : 14;
const FunctionSetHighlightedIndex = false ? 0 : 15;
const FunctionSelectItem = false ? 0 : 16;
const FunctionSetInputValue = false ? 0 : 17;
const FunctionReset$1 = false ? 0 : 18;
const ControlledPropUpdatedSelectedItem = false ? 0 : 19;
var stateChangeTypes$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
InputKeyDownArrowDown: InputKeyDownArrowDown,
InputKeyDownArrowUp: InputKeyDownArrowUp,
InputKeyDownEscape: InputKeyDownEscape,
InputKeyDownHome: InputKeyDownHome,
InputKeyDownEnd: InputKeyDownEnd,
InputKeyDownEnter: InputKeyDownEnter,
InputChange: InputChange,
InputBlur: InputBlur,
MenuMouseLeave: MenuMouseLeave,
ItemMouseMove: ItemMouseMove,
ItemClick: ItemClick,
ToggleButtonClick: ToggleButtonClick,
FunctionToggleMenu: FunctionToggleMenu,
FunctionOpenMenu: FunctionOpenMenu,
FunctionCloseMenu: FunctionCloseMenu,
FunctionSetHighlightedIndex: FunctionSetHighlightedIndex,
FunctionSelectItem: FunctionSelectItem,
FunctionSetInputValue: FunctionSetInputValue,
FunctionReset: FunctionReset$1,
ControlledPropUpdatedSelectedItem: ControlledPropUpdatedSelectedItem
});
function getInitialState$1(props) {
const initialState = getInitialState$2(props);
const {
selectedItem
} = initialState;
let {
inputValue
} = initialState;
if (inputValue === '' && selectedItem && props.defaultInputValue === undefined && props.initialInputValue === undefined && props.inputValue === undefined) {
inputValue = props.itemToString(selectedItem);
}
return { ...initialState,
inputValue
};
}
const propTypes$1 = {
items: (prop_types_default()).array.isRequired,
itemToString: (prop_types_default()).func,
getA11yStatusMessage: (prop_types_default()).func,
getA11ySelectionMessage: (prop_types_default()).func,
circularNavigation: (prop_types_default()).bool,
highlightedIndex: (prop_types_default()).number,
defaultHighlightedIndex: (prop_types_default()).number,
initialHighlightedIndex: (prop_types_default()).number,
isOpen: (prop_types_default()).bool,
defaultIsOpen: (prop_types_default()).bool,
initialIsOpen: (prop_types_default()).bool,
selectedItem: (prop_types_default()).any,
initialSelectedItem: (prop_types_default()).any,
defaultSelectedItem: (prop_types_default()).any,
inputValue: (prop_types_default()).string,
defaultInputValue: (prop_types_default()).string,
initialInputValue: (prop_types_default()).string,
id: (prop_types_default()).string,
labelId: (prop_types_default()).string,
menuId: (prop_types_default()).string,
getItemId: (prop_types_default()).func,
inputId: (prop_types_default()).string,
toggleButtonId: (prop_types_default()).string,
stateReducer: (prop_types_default()).func,
onSelectedItemChange: (prop_types_default()).func,
onHighlightedIndexChange: (prop_types_default()).func,
onStateChange: (prop_types_default()).func,
onIsOpenChange: (prop_types_default()).func,
onInputValueChange: (prop_types_default()).func,
environment: prop_types_default().shape({
addEventListener: (prop_types_default()).func,
removeEventListener: (prop_types_default()).func,
document: prop_types_default().shape({
getElementById: (prop_types_default()).func,
activeElement: (prop_types_default()).any,
body: (prop_types_default()).any
})
})
};
/**
* The useCombobox version of useControlledReducer, which also
* checks if the controlled prop selectedItem changed between
* renders. If so, it will also update inputValue with its
* string equivalent. It uses the common useEnhancedReducer to
* compute the rest of the state.
*
* @param {Function} reducer Reducer function from downshift.
* @param {Object} initialState Initial state of the hook.
* @param {Object} props The hook props.
* @returns {Array} An array with the state and an action dispatcher.
*/
function useControlledReducer(reducer, initialState, props) {
const previousSelectedItemRef = (0,external_React_.useRef)();
const [state, dispatch] = useEnhancedReducer(reducer, initialState, props); // ToDo: if needed, make same approach as selectedItemChanged from Downshift.
(0,external_React_.useEffect)(() => {
if (isControlledProp(props, 'selectedItem')) {
if (previousSelectedItemRef.current !== props.selectedItem) {
dispatch({
type: ControlledPropUpdatedSelectedItem,
inputValue: props.itemToString(props.selectedItem)
});
}
previousSelectedItemRef.current = state.selectedItem === previousSelectedItemRef.current ? props.selectedItem : state.selectedItem;
}
});
return [getState(state, props), dispatch];
} // eslint-disable-next-line import/no-mutable-exports
let validatePropTypes$1 = downshift_esm_noop;
/* istanbul ignore next */
if (false) {}
const defaultProps$1 = { ...defaultProps$3,
getA11yStatusMessage: getA11yStatusMessage$1,
circularNavigation: true
};
/* eslint-disable complexity */
function downshiftUseComboboxReducer(state, action) {
const {
type,
props,
shiftKey
} = action;
let changes;
switch (type) {
case ItemClick:
changes = {
isOpen: getDefaultValue$1(props, 'isOpen'),
highlightedIndex: getDefaultValue$1(props, 'highlightedIndex'),
selectedItem: props.items[action.index],
inputValue: props.itemToString(props.items[action.index])
};
break;
case InputKeyDownArrowDown:
if (state.isOpen) {
changes = {
highlightedIndex: getNextWrappingIndex(shiftKey ? 5 : 1, state.highlightedIndex, props.items.length, action.getItemNodeFromIndex, props.circularNavigation)
};
} else {
changes = {
highlightedIndex: getHighlightedIndexOnOpen(props, state, 1, action.getItemNodeFromIndex),
isOpen: props.items.length >= 0
};
}
break;
case InputKeyDownArrowUp:
if (state.isOpen) {
changes = {
highlightedIndex: getNextWrappingIndex(shiftKey ? -5 : -1, state.highlightedIndex, props.items.length, action.getItemNodeFromIndex, props.circularNavigation)
};
} else {
changes = {
highlightedIndex: getHighlightedIndexOnOpen(props, state, -1, action.getItemNodeFromIndex),
isOpen: props.items.length >= 0
};
}
break;
case InputKeyDownEnter:
changes = { ...(state.isOpen && state.highlightedIndex >= 0 && {
selectedItem: props.items[state.highlightedIndex],
isOpen: getDefaultValue$1(props, 'isOpen'),
highlightedIndex: getDefaultValue$1(props, 'highlightedIndex'),
inputValue: props.itemToString(props.items[state.highlightedIndex])
})
};
break;
case InputKeyDownEscape:
changes = {
isOpen: false,
highlightedIndex: -1,
...(!state.isOpen && {
selectedItem: null,
inputValue: ''
})
};
break;
case InputKeyDownHome:
changes = {
highlightedIndex: getNextNonDisabledIndex(1, 0, props.items.length, action.getItemNodeFromIndex, false)
};
break;
case InputKeyDownEnd:
changes = {
highlightedIndex: getNextNonDisabledIndex(-1, props.items.length - 1, props.items.length, action.getItemNodeFromIndex, false)
};
break;
case InputBlur:
changes = {
isOpen: false,
highlightedIndex: -1,
...(state.highlightedIndex >= 0 && action.selectItem && {
selectedItem: props.items[state.highlightedIndex],
inputValue: props.itemToString(props.items[state.highlightedIndex])
})
};
break;
case InputChange:
changes = {
isOpen: true,
highlightedIndex: getDefaultValue$1(props, 'highlightedIndex'),
inputValue: action.inputValue
};
break;
case FunctionSelectItem:
changes = {
selectedItem: action.selectedItem,
inputValue: props.itemToString(action.selectedItem)
};
break;
case ControlledPropUpdatedSelectedItem:
changes = {
inputValue: action.inputValue
};
break;
default:
return downshiftCommonReducer(state, action, stateChangeTypes$1);
}
return { ...state,
...changes
};
}
/* eslint-enable complexity */
/* eslint-disable max-statements */
useCombobox.stateChangeTypes = stateChangeTypes$1;
function useCombobox(userProps) {
if (userProps === void 0) {
userProps = {};
}
validatePropTypes$1(userProps, useCombobox); // Props defaults and destructuring.
const props = { ...defaultProps$1,
...userProps
};
const {
initialIsOpen,
defaultIsOpen,
items,
scrollIntoView,
environment,
getA11yStatusMessage,
getA11ySelectionMessage,
itemToString
} = props; // Initial state depending on controlled props.
const initialState = getInitialState$1(props);
const [state, dispatch] = useControlledReducer(downshiftUseComboboxReducer, initialState, props);
const {
isOpen,
highlightedIndex,
selectedItem,
inputValue
} = state; // Element refs.
const menuRef = (0,external_React_.useRef)(null);
const itemRefs = (0,external_React_.useRef)({});
const inputRef = (0,external_React_.useRef)(null);
const toggleButtonRef = (0,external_React_.useRef)(null);
const comboboxRef = (0,external_React_.useRef)(null);
const isInitialMountRef = (0,external_React_.useRef)(true); // prevent id re-generation between renders.
const elementIds = useElementIds(props); // used to keep track of how many items we had on previous cycle.
const previousResultCountRef = (0,external_React_.useRef)(); // utility callback to get item element.
const latest = downshift_esm_useLatestRef({
state,
props
});
const getItemNodeFromIndex = (0,external_React_.useCallback)(index => itemRefs.current[elementIds.getItemId(index)], [elementIds]); // Effects.
// Sets a11y status message on changes in state.
useA11yMessageSetter(getA11yStatusMessage, [isOpen, highlightedIndex, inputValue, items], {
isInitialMount: isInitialMountRef.current,
previousResultCount: previousResultCountRef.current,
items,
environment,
itemToString,
...state
}); // Sets a11y status message on changes in selectedItem.
useA11yMessageSetter(getA11ySelectionMessage, [selectedItem], {
isInitialMount: isInitialMountRef.current,
previousResultCount: previousResultCountRef.current,
items,
environment,
itemToString,
...state
}); // Scroll on highlighted item if change comes from keyboard.
const shouldScrollRef = useScrollIntoView({
menuElement: menuRef.current,
highlightedIndex,
isOpen,
itemRefs,
scrollIntoView,
getItemNodeFromIndex
});
useControlPropsValidator({
isInitialMount: isInitialMountRef.current,
props,
state
}); // Focus the input on first render if required.
(0,external_React_.useEffect)(() => {
const focusOnOpen = initialIsOpen || defaultIsOpen || isOpen;
if (focusOnOpen && inputRef.current) {
inputRef.current.focus();
} // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
(0,external_React_.useEffect)(() => {
if (isInitialMountRef.current) {
return;
}
previousResultCountRef.current = items.length;
}); // Add mouse/touch events to document.
const mouseAndTouchTrackersRef = useMouseAndTouchTracker(isOpen, [comboboxRef, menuRef, toggleButtonRef], environment, () => {
dispatch({
type: InputBlur,
selectItem: false
});
});
const setGetterPropCallInfo = useGetterPropsCalledChecker('getInputProps', 'getComboboxProps', 'getMenuProps'); // Make initial ref false.
(0,external_React_.useEffect)(() => {
isInitialMountRef.current = false;
}, []); // Reset itemRefs on close.
(0,external_React_.useEffect)(() => {
if (!isOpen) {
itemRefs.current = {};
}
}, [isOpen]);
/* Event handler functions */
const inputKeyDownHandlers = (0,external_React_.useMemo)(() => ({
ArrowDown(event) {
event.preventDefault();
dispatch({
type: InputKeyDownArrowDown,
shiftKey: event.shiftKey,
getItemNodeFromIndex
});
},
ArrowUp(event) {
event.preventDefault();
dispatch({
type: InputKeyDownArrowUp,
shiftKey: event.shiftKey,
getItemNodeFromIndex
});
},
Home(event) {
if (!latest.current.state.isOpen) {
return;
}
event.preventDefault();
dispatch({
type: InputKeyDownHome,
getItemNodeFromIndex
});
},
End(event) {
if (!latest.current.state.isOpen) {
return;
}
event.preventDefault();
dispatch({
type: InputKeyDownEnd,
getItemNodeFromIndex
});
},
Escape(event) {
const latestState = latest.current.state;
if (latestState.isOpen || latestState.inputValue || latestState.selectedItem || latestState.highlightedIndex > -1) {
event.preventDefault();
dispatch({
type: InputKeyDownEscape
});
}
},
Enter(event) {
const latestState = latest.current.state; // if closed or no highlighted index, do nothing.
if (!latestState.isOpen || latestState.highlightedIndex < 0 || event.which === 229 // if IME composing, wait for next Enter keydown event.
) {
return;
}
event.preventDefault();
dispatch({
type: InputKeyDownEnter,
getItemNodeFromIndex
});
}
}), [dispatch, latest, getItemNodeFromIndex]); // Getter props.
const getLabelProps = (0,external_React_.useCallback)(labelProps => ({
id: elementIds.labelId,
htmlFor: elementIds.inputId,
...labelProps
}), [elementIds]);
const getMenuProps = (0,external_React_.useCallback)(function (_temp, _temp2) {
let {
onMouseLeave,
refKey = 'ref',
ref,
...rest
} = _temp === void 0 ? {} : _temp;
let {
suppressRefError = false
} = _temp2 === void 0 ? {} : _temp2;
setGetterPropCallInfo('getMenuProps', suppressRefError, refKey, menuRef);
return {
[refKey]: handleRefs(ref, menuNode => {
menuRef.current = menuNode;
}),
id: elementIds.menuId,
role: 'listbox',
'aria-labelledby': elementIds.labelId,
onMouseLeave: callAllEventHandlers(onMouseLeave, () => {
dispatch({
type: MenuMouseLeave
});
}),
...rest
};
}, [dispatch, setGetterPropCallInfo, elementIds]);
const getItemProps = (0,external_React_.useCallback)(function (_temp3) {
let {
item,
index,
refKey = 'ref',
ref,
onMouseMove,
onMouseDown,
onClick,
onPress,
disabled,
...rest
} = _temp3 === void 0 ? {} : _temp3;
const {
props: latestProps,
state: latestState
} = latest.current;
const itemIndex = getItemIndex(index, item, latestProps.items);
if (itemIndex < 0) {
throw new Error('Pass either item or item index in getItemProps!');
}
const onSelectKey = 'onClick';
const customClickHandler = onClick;
const itemHandleMouseMove = () => {
if (index === latestState.highlightedIndex) {
return;
}
shouldScrollRef.current = false;
dispatch({
type: ItemMouseMove,
index,
disabled
});
};
const itemHandleClick = () => {
dispatch({
type: ItemClick,
index
});
};
const itemHandleMouseDown = e => e.preventDefault();
return {
[refKey]: handleRefs(ref, itemNode => {
if (itemNode) {
itemRefs.current[elementIds.getItemId(itemIndex)] = itemNode;
}
}),
disabled,
role: 'option',
'aria-selected': `${itemIndex === latestState.highlightedIndex}`,
id: elementIds.getItemId(itemIndex),
...(!disabled && {
[onSelectKey]: callAllEventHandlers(customClickHandler, itemHandleClick)
}),
onMouseMove: callAllEventHandlers(onMouseMove, itemHandleMouseMove),
onMouseDown: callAllEventHandlers(onMouseDown, itemHandleMouseDown),
...rest
};
}, [dispatch, latest, shouldScrollRef, elementIds]);
const getToggleButtonProps = (0,external_React_.useCallback)(function (_temp4) {
let {
onClick,
onPress,
refKey = 'ref',
ref,
...rest
} = _temp4 === void 0 ? {} : _temp4;
const toggleButtonHandleClick = () => {
dispatch({
type: ToggleButtonClick
});
if (!latest.current.state.isOpen && inputRef.current) {
inputRef.current.focus();
}
};
return {
[refKey]: handleRefs(ref, toggleButtonNode => {
toggleButtonRef.current = toggleButtonNode;
}),
id: elementIds.toggleButtonId,
tabIndex: -1,
...(!rest.disabled && { ...({
onClick: callAllEventHandlers(onClick, toggleButtonHandleClick)
})
}),
...rest
};
}, [dispatch, latest, elementIds]);
const getInputProps = (0,external_React_.useCallback)(function (_temp5, _temp6) {
let {
onKeyDown,
onChange,
onInput,
onBlur,
onChangeText,
refKey = 'ref',
ref,
...rest
} = _temp5 === void 0 ? {} : _temp5;
let {
suppressRefError = false
} = _temp6 === void 0 ? {} : _temp6;
setGetterPropCallInfo('getInputProps', suppressRefError, refKey, inputRef);
const latestState = latest.current.state;
const inputHandleKeyDown = event => {
const key = normalizeArrowKey(event);
if (key && inputKeyDownHandlers[key]) {
inputKeyDownHandlers[key](event);
}
};
const inputHandleChange = event => {
dispatch({
type: InputChange,
inputValue: event.target.value
});
};
const inputHandleBlur = () => {
/* istanbul ignore else */
if (latestState.isOpen && !mouseAndTouchTrackersRef.current.isMouseDown) {
dispatch({
type: InputBlur,
selectItem: true
});
}
};
/* istanbul ignore next (preact) */
const onChangeKey = 'onChange';
let eventHandlers = {};
if (!rest.disabled) {
eventHandlers = {
[onChangeKey]: callAllEventHandlers(onChange, onInput, inputHandleChange),
onKeyDown: callAllEventHandlers(onKeyDown, inputHandleKeyDown),
onBlur: callAllEventHandlers(onBlur, inputHandleBlur)
};
}
return {
[refKey]: handleRefs(ref, inputNode => {
inputRef.current = inputNode;
}),
id: elementIds.inputId,
'aria-autocomplete': 'list',
'aria-controls': elementIds.menuId,
...(latestState.isOpen && latestState.highlightedIndex > -1 && {
'aria-activedescendant': elementIds.getItemId(latestState.highlightedIndex)
}),
'aria-labelledby': elementIds.labelId,
// https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion
// revert back since autocomplete="nope" is ignored on latest Chrome and Opera
autoComplete: 'off',
value: latestState.inputValue,
...eventHandlers,
...rest
};
}, [dispatch, inputKeyDownHandlers, latest, mouseAndTouchTrackersRef, setGetterPropCallInfo, elementIds]);
const getComboboxProps = (0,external_React_.useCallback)(function (_temp7, _temp8) {
let {
refKey = 'ref',
ref,
...rest
} = _temp7 === void 0 ? {} : _temp7;
let {
suppressRefError = false
} = _temp8 === void 0 ? {} : _temp8;
setGetterPropCallInfo('getComboboxProps', suppressRefError, refKey, comboboxRef);
return {
[refKey]: handleRefs(ref, comboboxNode => {
comboboxRef.current = comboboxNode;
}),
role: 'combobox',
'aria-haspopup': 'listbox',
'aria-owns': elementIds.menuId,
'aria-expanded': latest.current.state.isOpen,
...rest
};
}, [latest, setGetterPropCallInfo, elementIds]); // returns
const toggleMenu = (0,external_React_.useCallback)(() => {
dispatch({
type: FunctionToggleMenu
});
}, [dispatch]);
const closeMenu = (0,external_React_.useCallback)(() => {
dispatch({
type: FunctionCloseMenu
});
}, [dispatch]);
const openMenu = (0,external_React_.useCallback)(() => {
dispatch({
type: FunctionOpenMenu
});
}, [dispatch]);
const setHighlightedIndex = (0,external_React_.useCallback)(newHighlightedIndex => {
dispatch({
type: FunctionSetHighlightedIndex,
highlightedIndex: newHighlightedIndex
});
}, [dispatch]);
const selectItem = (0,external_React_.useCallback)(newSelectedItem => {
dispatch({
type: FunctionSelectItem,
selectedItem: newSelectedItem
});
}, [dispatch]);
const setInputValue = (0,external_React_.useCallback)(newInputValue => {
dispatch({
type: FunctionSetInputValue,
inputValue: newInputValue
});
}, [dispatch]);
const reset = (0,external_React_.useCallback)(() => {
dispatch({
type: FunctionReset$1
});
}, [dispatch]);
return {
// prop getters.
getItemProps,
getLabelProps,
getMenuProps,
getInputProps,
getComboboxProps,
getToggleButtonProps,
// actions.
toggleMenu,
openMenu,
closeMenu,
setHighlightedIndex,
setInputValue,
selectItem,
reset,
// state.
highlightedIndex,
isOpen,
selectedItem,
inputValue
};
}
const defaultStateValues = {
activeIndex: -1,
selectedItems: []
};
/**
* Returns the initial value for a state key in the following order:
* 1. controlled prop, 2. initial prop, 3. default prop, 4. default
* value from Downshift.
*
* @param {Object} props Props passed to the hook.
* @param {string} propKey Props key to generate the value for.
* @returns {any} The initial value for that prop.
*/
function getInitialValue(props, propKey) {
return getInitialValue$1(props, propKey, defaultStateValues);
}
/**
* Returns the default value for a state key in the following order:
* 1. controlled prop, 2. default prop, 3. default value from Downshift.
*
* @param {Object} props Props passed to the hook.
* @param {string} propKey Props key to generate the value for.
* @returns {any} The initial value for that prop.
*/
function getDefaultValue(props, propKey) {
return getDefaultValue$1(props, propKey, defaultStateValues);
}
/**
* Gets the initial state based on the provided props. It uses initial, default
* and controlled props related to state in order to compute the initial value.
*
* @param {Object} props Props passed to the hook.
* @returns {Object} The initial state.
*/
function getInitialState(props) {
const activeIndex = getInitialValue(props, 'activeIndex');
const selectedItems = getInitialValue(props, 'selectedItems');
return {
activeIndex,
selectedItems
};
}
/**
* Returns true if dropdown keydown operation is permitted. Should not be
* allowed on keydown with modifier keys (ctrl, alt, shift, meta), on
* input element with text content that is either highlighted or selection
* cursor is not at the starting position.
*
* @param {KeyboardEvent} event The event from keydown.
* @returns {boolean} Whether the operation is allowed.
*/
function isKeyDownOperationPermitted(event) {
if (event.shiftKey || event.metaKey || event.ctrlKey || event.altKey) {
return false;
}
const element = event.target;
if (element instanceof HTMLInputElement && // if element is a text input
element.value !== '' && ( // and we have text in it
// and cursor is either not at the start or is currently highlighting text.
element.selectionStart !== 0 || element.selectionEnd !== 0)) {
return false;
}
return true;
}
/**
* Returns a message to be added to aria-live region when item is removed.
*
* @param {Object} selectionParameters Parameters required to build the message.
* @returns {string} The a11y message.
*/
function getA11yRemovalMessage(selectionParameters) {
const {
removedSelectedItem,
itemToString: itemToStringLocal
} = selectionParameters;
return `${itemToStringLocal(removedSelectedItem)} has been removed.`;
}
const propTypes = {
selectedItems: (prop_types_default()).array,
initialSelectedItems: (prop_types_default()).array,
defaultSelectedItems: (prop_types_default()).array,
itemToString: (prop_types_default()).func,
getA11yRemovalMessage: (prop_types_default()).func,
stateReducer: (prop_types_default()).func,
activeIndex: (prop_types_default()).number,
initialActiveIndex: (prop_types_default()).number,
defaultActiveIndex: (prop_types_default()).number,
onActiveIndexChange: (prop_types_default()).func,
onSelectedItemsChange: (prop_types_default()).func,
keyNavigationNext: (prop_types_default()).string,
keyNavigationPrevious: (prop_types_default()).string,
environment: prop_types_default().shape({
addEventListener: (prop_types_default()).func,
removeEventListener: (prop_types_default()).func,
document: prop_types_default().shape({
getElementById: (prop_types_default()).func,
activeElement: (prop_types_default()).any,
body: (prop_types_default()).any
})
})
};
const defaultProps = {
itemToString: defaultProps$3.itemToString,
stateReducer: defaultProps$3.stateReducer,
environment: defaultProps$3.environment,
getA11yRemovalMessage,
keyNavigationNext: 'ArrowRight',
keyNavigationPrevious: 'ArrowLeft'
}; // eslint-disable-next-line import/no-mutable-exports
let validatePropTypes = downshift_esm_noop;
/* istanbul ignore next */
if (false) {}
const SelectedItemClick = false ? 0 : 0;
const SelectedItemKeyDownDelete = false ? 0 : 1;
const SelectedItemKeyDownBackspace = false ? 0 : 2;
const SelectedItemKeyDownNavigationNext = false ? 0 : 3;
const SelectedItemKeyDownNavigationPrevious = false ? 0 : 4;
const DropdownKeyDownNavigationPrevious = false ? 0 : 5;
const DropdownKeyDownBackspace = false ? 0 : 6;
const DropdownClick = false ? 0 : 7;
const FunctionAddSelectedItem = false ? 0 : 8;
const FunctionRemoveSelectedItem = false ? 0 : 9;
const FunctionSetSelectedItems = false ? 0 : 10;
const FunctionSetActiveIndex = false ? 0 : 11;
const FunctionReset = false ? 0 : 12;
var stateChangeTypes = /*#__PURE__*/Object.freeze({
__proto__: null,
SelectedItemClick: SelectedItemClick,
SelectedItemKeyDownDelete: SelectedItemKeyDownDelete,
SelectedItemKeyDownBackspace: SelectedItemKeyDownBackspace,
SelectedItemKeyDownNavigationNext: SelectedItemKeyDownNavigationNext,
SelectedItemKeyDownNavigationPrevious: SelectedItemKeyDownNavigationPrevious,
DropdownKeyDownNavigationPrevious: DropdownKeyDownNavigationPrevious,
DropdownKeyDownBackspace: DropdownKeyDownBackspace,
DropdownClick: DropdownClick,
FunctionAddSelectedItem: FunctionAddSelectedItem,
FunctionRemoveSelectedItem: FunctionRemoveSelectedItem,
FunctionSetSelectedItems: FunctionSetSelectedItems,
FunctionSetActiveIndex: FunctionSetActiveIndex,
FunctionReset: FunctionReset
});
/* eslint-disable complexity */
function downshiftMultipleSelectionReducer(state, action) {
const {
type,
index,
props,
selectedItem
} = action;
const {
activeIndex,
selectedItems
} = state;
let changes;
switch (type) {
case SelectedItemClick:
changes = {
activeIndex: index
};
break;
case SelectedItemKeyDownNavigationPrevious:
changes = {
activeIndex: activeIndex - 1 < 0 ? 0 : activeIndex - 1
};
break;
case SelectedItemKeyDownNavigationNext:
changes = {
activeIndex: activeIndex + 1 >= selectedItems.length ? -1 : activeIndex + 1
};
break;
case SelectedItemKeyDownBackspace:
case SelectedItemKeyDownDelete:
{
let newActiveIndex = activeIndex;
if (selectedItems.length === 1) {
newActiveIndex = -1;
} else if (activeIndex === selectedItems.length - 1) {
newActiveIndex = selectedItems.length - 2;
}
changes = {
selectedItems: [...selectedItems.slice(0, activeIndex), ...selectedItems.slice(activeIndex + 1)],
...{
activeIndex: newActiveIndex
}
};
break;
}
case DropdownKeyDownNavigationPrevious:
changes = {
activeIndex: selectedItems.length - 1
};
break;
case DropdownKeyDownBackspace:
changes = {
selectedItems: selectedItems.slice(0, selectedItems.length - 1)
};
break;
case FunctionAddSelectedItem:
changes = {
selectedItems: [...selectedItems, selectedItem]
};
break;
case DropdownClick:
changes = {
activeIndex: -1
};
break;
case FunctionRemoveSelectedItem:
{
let newActiveIndex = activeIndex;
const selectedItemIndex = selectedItems.indexOf(selectedItem);
if (selectedItemIndex >= 0) {
if (selectedItems.length === 1) {
newActiveIndex = -1;
} else if (selectedItemIndex === selectedItems.length - 1) {
newActiveIndex = selectedItems.length - 2;
}
changes = {
selectedItems: [...selectedItems.slice(0, selectedItemIndex), ...selectedItems.slice(selectedItemIndex + 1)],
activeIndex: newActiveIndex
};
}
break;
}
case FunctionSetSelectedItems:
{
const {
selectedItems: newSelectedItems
} = action;
changes = {
selectedItems: newSelectedItems
};
break;
}
case FunctionSetActiveIndex:
{
const {
activeIndex: newActiveIndex
} = action;
changes = {
activeIndex: newActiveIndex
};
break;
}
case FunctionReset:
changes = {
activeIndex: getDefaultValue(props, 'activeIndex'),
selectedItems: getDefaultValue(props, 'selectedItems')
};
break;
default:
throw new Error('Reducer called without proper action type.');
}
return { ...state,
...changes
};
}
useMultipleSelection.stateChangeTypes = stateChangeTypes;
function useMultipleSelection(userProps) {
if (userProps === void 0) {
userProps = {};
}
validatePropTypes(userProps, useMultipleSelection); // Props defaults and destructuring.
const props = { ...defaultProps,
...userProps
};
const {
getA11yRemovalMessage,
itemToString,
environment,
keyNavigationNext,
keyNavigationPrevious
} = props; // Reducer init.
const [state, dispatch] = useControlledReducer$1(downshiftMultipleSelectionReducer, getInitialState(props), props);
const {
activeIndex,
selectedItems
} = state; // Refs.
const isInitialMountRef = (0,external_React_.useRef)(true);
const dropdownRef = (0,external_React_.useRef)(null);
const previousSelectedItemsRef = (0,external_React_.useRef)(selectedItems);
const selectedItemRefs = (0,external_React_.useRef)();
selectedItemRefs.current = [];
const latest = downshift_esm_useLatestRef({
state,
props
}); // Effects.
/* Sets a11y status message on changes in selectedItem. */
(0,external_React_.useEffect)(() => {
if (isInitialMountRef.current) {
return;
}
if (selectedItems.length < previousSelectedItemsRef.current.length) {
const removedSelectedItem = previousSelectedItemsRef.current.find(item => selectedItems.indexOf(item) < 0);
setStatus(getA11yRemovalMessage({
itemToString,
resultCount: selectedItems.length,
removedSelectedItem,
activeIndex,
activeSelectedItem: selectedItems[activeIndex]
}), environment.document);
}
previousSelectedItemsRef.current = selectedItems; // eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedItems.length]); // Sets focus on active item.
(0,external_React_.useEffect)(() => {
if (isInitialMountRef.current) {
return;
}
if (activeIndex === -1 && dropdownRef.current) {
dropdownRef.current.focus();
} else if (selectedItemRefs.current[activeIndex]) {
selectedItemRefs.current[activeIndex].focus();
}
}, [activeIndex]);
useControlPropsValidator({
isInitialMount: isInitialMountRef.current,
props,
state
});
const setGetterPropCallInfo = useGetterPropsCalledChecker('getDropdownProps'); // Make initial ref false.
(0,external_React_.useEffect)(() => {
isInitialMountRef.current = false;
}, []); // Event handler functions.
const selectedItemKeyDownHandlers = (0,external_React_.useMemo)(() => ({
[keyNavigationPrevious]() {
dispatch({
type: SelectedItemKeyDownNavigationPrevious
});
},
[keyNavigationNext]() {
dispatch({
type: SelectedItemKeyDownNavigationNext
});
},
Delete() {
dispatch({
type: SelectedItemKeyDownDelete
});
},
Backspace() {
dispatch({
type: SelectedItemKeyDownBackspace
});
}
}), [dispatch, keyNavigationNext, keyNavigationPrevious]);
const dropdownKeyDownHandlers = (0,external_React_.useMemo)(() => ({
[keyNavigationPrevious](event) {
if (isKeyDownOperationPermitted(event)) {
dispatch({
type: DropdownKeyDownNavigationPrevious
});
}
},
Backspace(event) {
if (isKeyDownOperationPermitted(event)) {
dispatch({
type: DropdownKeyDownBackspace
});
}
}
}), [dispatch, keyNavigationPrevious]); // Getter props.
const getSelectedItemProps = (0,external_React_.useCallback)(function (_temp) {
let {
refKey = 'ref',
ref,
onClick,
onKeyDown,
selectedItem,
index,
...rest
} = _temp === void 0 ? {} : _temp;
const {
state: latestState
} = latest.current;
const itemIndex = getItemIndex(index, selectedItem, latestState.selectedItems);
if (itemIndex < 0) {
throw new Error('Pass either selectedItem or index in getSelectedItemProps!');
}
const selectedItemHandleClick = () => {
dispatch({
type: SelectedItemClick,
index
});
};
const selectedItemHandleKeyDown = event => {
const key = normalizeArrowKey(event);
if (key && selectedItemKeyDownHandlers[key]) {
selectedItemKeyDownHandlers[key](event);
}
};
return {
[refKey]: handleRefs(ref, selectedItemNode => {
if (selectedItemNode) {
selectedItemRefs.current.push(selectedItemNode);
}
}),
tabIndex: index === latestState.activeIndex ? 0 : -1,
onClick: callAllEventHandlers(onClick, selectedItemHandleClick),
onKeyDown: callAllEventHandlers(onKeyDown, selectedItemHandleKeyDown),
...rest
};
}, [dispatch, latest, selectedItemKeyDownHandlers]);
const getDropdownProps = (0,external_React_.useCallback)(function (_temp2, _temp3) {
let {
refKey = 'ref',
ref,
onKeyDown,
onClick,
preventKeyAction = false,
...rest
} = _temp2 === void 0 ? {} : _temp2;
let {
suppressRefError = false
} = _temp3 === void 0 ? {} : _temp3;
setGetterPropCallInfo('getDropdownProps', suppressRefError, refKey, dropdownRef);
const dropdownHandleKeyDown = event => {
const key = normalizeArrowKey(event);
if (key && dropdownKeyDownHandlers[key]) {
dropdownKeyDownHandlers[key](event);
}
};
const dropdownHandleClick = () => {
dispatch({
type: DropdownClick
});
};
return {
[refKey]: handleRefs(ref, dropdownNode => {
if (dropdownNode) {
dropdownRef.current = dropdownNode;
}
}),
...(!preventKeyAction && {
onKeyDown: callAllEventHandlers(onKeyDown, dropdownHandleKeyDown),
onClick: callAllEventHandlers(onClick, dropdownHandleClick)
}),
...rest
};
}, [dispatch, dropdownKeyDownHandlers, setGetterPropCallInfo]); // returns
const addSelectedItem = (0,external_React_.useCallback)(selectedItem => {
dispatch({
type: FunctionAddSelectedItem,
selectedItem
});
}, [dispatch]);
const removeSelectedItem = (0,external_React_.useCallback)(selectedItem => {
dispatch({
type: FunctionRemoveSelectedItem,
selectedItem
});
}, [dispatch]);
const setSelectedItems = (0,external_React_.useCallback)(newSelectedItems => {
dispatch({
type: FunctionSetSelectedItems,
selectedItems: newSelectedItems
});
}, [dispatch]);
const setActiveIndex = (0,external_React_.useCallback)(newActiveIndex => {
dispatch({
type: FunctionSetActiveIndex,
activeIndex: newActiveIndex
});
}, [dispatch]);
const reset = (0,external_React_.useCallback)(() => {
dispatch({
type: FunctionReset
});
}, [dispatch]);
return {
getSelectedItemProps,
getDropdownProps,
addSelectedItem,
removeSelectedItem,
setSelectedItems,
setActiveIndex,
reset,
selectedItems,
activeIndex
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/custom-select-control/styles.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const backCompatMinWidth = props => !props.__nextUnconstrainedWidth ? /*#__PURE__*/emotion_react_browser_esm_css(Container, "{min-width:130px;}" + ( true ? "" : 0), true ? "" : 0) : '';
const InputBaseWithBackCompatMinWidth = /*#__PURE__*/createStyled(input_base, true ? {
target: "eswuck60"
} : 0)(backCompatMinWidth, ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/custom-select-control/index.js
// @ts-nocheck
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const custom_select_control_itemToString = item => item === null || item === void 0 ? void 0 : item.name; // This is needed so that in Windows, where
// the menu does not necessarily open on
// key up/down, you can still switch between
// options with the menu closed.
const custom_select_control_stateReducer = (_ref, _ref2) => {
let {
selectedItem
} = _ref;
let {
type,
changes,
props: {
items
}
} = _ref2;
switch (type) {
case useSelect.stateChangeTypes.ToggleButtonKeyDownArrowDown:
// If we already have a selected item, try to select the next one,
// without circular navigation. Otherwise, select the first item.
return {
selectedItem: items[selectedItem ? Math.min(items.indexOf(selectedItem) + 1, items.length - 1) : 0]
};
case useSelect.stateChangeTypes.ToggleButtonKeyDownArrowUp:
// If we already have a selected item, try to select the previous one,
// without circular navigation. Otherwise, select the last item.
return {
selectedItem: items[selectedItem ? Math.max(items.indexOf(selectedItem) - 1, 0) : items.length - 1]
};
default:
return changes;
}
};
function CustomSelectControl(props) {
var _menuProps$ariaActiv;
const {
/** Start opting into the larger default height that will become the default size in a future version. */
__next36pxDefaultSize = false,
/** Start opting into the unconstrained width that will become the default in a future version. */
__nextUnconstrainedWidth = false,
className,
hideLabelFromVision,
label,
describedBy,
options: items,
onChange: onSelectedItemChange,
/** @type {import('../select-control/types').SelectControlProps.size} */
size = 'default',
value: _selectedItem,
onMouseOver,
onMouseOut,
onFocus,
onBlur,
__experimentalShowSelectedHint = false
} = props;
const {
getLabelProps,
getToggleButtonProps,
getMenuProps,
getItemProps,
isOpen,
highlightedIndex,
selectedItem
} = useSelect({
initialSelectedItem: items[0],
items,
itemToString: custom_select_control_itemToString,
onSelectedItemChange,
...(typeof _selectedItem !== 'undefined' && _selectedItem !== null ? {
selectedItem: _selectedItem
} : undefined),
stateReducer: custom_select_control_stateReducer
});
const [isFocused, setIsFocused] = (0,external_wp_element_namespaceObject.useState)(false);
function handleOnFocus(e) {
setIsFocused(true);
onFocus === null || onFocus === void 0 ? void 0 : onFocus(e);
}
function handleOnBlur(e) {
setIsFocused(false);
onBlur === null || onBlur === void 0 ? void 0 : onBlur(e);
}
if (!__nextUnconstrainedWidth) {
external_wp_deprecated_default()('Constrained width styles for wp.components.CustomSelectControl', {
since: '6.1',
version: '6.4',
hint: 'Set the `__nextUnconstrainedWidth` prop to true to start opting into the new styles, which will become the default in a future version'
});
}
function getDescribedBy() {
if (describedBy) {
return describedBy;
}
if (!selectedItem) {
return (0,external_wp_i18n_namespaceObject.__)('No selection');
} // translators: %s: The selected option.
return (0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('Currently selected: %s'), selectedItem.name);
}
const menuProps = getMenuProps({
className: 'components-custom-select-control__menu',
'aria-hidden': !isOpen
});
const onKeyDownHandler = (0,external_wp_element_namespaceObject.useCallback)(e => {
var _menuProps$onKeyDown;
e.stopPropagation();
menuProps === null || menuProps === void 0 ? void 0 : (_menuProps$onKeyDown = menuProps.onKeyDown) === null || _menuProps$onKeyDown === void 0 ? void 0 : _menuProps$onKeyDown.call(menuProps, e);
}, [menuProps]); // We need this here, because the null active descendant is not fully ARIA compliant.
if ((_menuProps$ariaActiv = menuProps['aria-activedescendant']) !== null && _menuProps$ariaActiv !== void 0 && _menuProps$ariaActiv.startsWith('downshift-null')) {
delete menuProps['aria-activedescendant'];
}
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('components-custom-select-control', className)
}, hideLabelFromVision ? (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, extends_extends({
as: "label"
}, getLabelProps()), label) :
/* eslint-disable-next-line jsx-a11y/label-has-associated-control, jsx-a11y/label-has-for */
(0,external_wp_element_namespaceObject.createElement)(StyledLabel, getLabelProps({
className: 'components-custom-select-control__label'
}), label), (0,external_wp_element_namespaceObject.createElement)(InputBaseWithBackCompatMinWidth, {
__next36pxDefaultSize: __next36pxDefaultSize,
__nextUnconstrainedWidth: __nextUnconstrainedWidth,
isFocused: isOpen || isFocused,
__unstableInputWidth: __nextUnconstrainedWidth ? undefined : 'auto',
labelPosition: __nextUnconstrainedWidth ? undefined : 'top',
size: size,
suffix: (0,external_wp_element_namespaceObject.createElement)(select_control_chevron_down, null)
}, (0,external_wp_element_namespaceObject.createElement)(Select, extends_extends({
onMouseOver: onMouseOver,
onMouseOut: onMouseOut,
as: "button",
onFocus: handleOnFocus,
onBlur: handleOnBlur,
selectSize: size,
__next36pxDefaultSize: __next36pxDefaultSize
}, getToggleButtonProps({
// This is needed because some speech recognition software don't support `aria-labelledby`.
'aria-label': label,
'aria-labelledby': undefined,
className: 'components-custom-select-control__button',
describedBy: getDescribedBy()
})), custom_select_control_itemToString(selectedItem), __experimentalShowSelectedHint && selectedItem.__experimentalHint && (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-custom-select-control__hint"
}, selectedItem.__experimentalHint))), (0,external_wp_element_namespaceObject.createElement)("ul", extends_extends({}, menuProps, {
onKeyDown: onKeyDownHandler
}), isOpen && items.map((item, index) => // eslint-disable-next-line react/jsx-key
(0,external_wp_element_namespaceObject.createElement)("li", getItemProps({
item,
index,
key: item.key,
className: classnames_default()(item.className, 'components-custom-select-control__item', {
'is-highlighted': index === highlightedIndex,
'has-hint': !!item.__experimentalHint,
'is-next-36px-default-size': __next36pxDefaultSize
}),
style: item.style
}), item.name, item.__experimentalHint && (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-custom-select-control__item-hint"
}, item.__experimentalHint), item === selectedItem && (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, {
icon: library_check,
className: "components-custom-select-control__item-icon"
})))));
}
function StableCustomSelectControl(props) {
return (0,external_wp_element_namespaceObject.createElement)(CustomSelectControl, extends_extends({}, props, {
__experimentalShowSelectedHint: false
}));
}
;// CONCATENATED MODULE: ./node_modules/use-lilius/build/index.es.js
/**
* @name toDate
* @category Common Helpers
* @summary Convert the given argument to an instance of Date.
*
* @description
* Convert the given argument to an instance of Date.
*
* If the argument is an instance of Date, the function returns its clone.
*
* If the argument is a number, it is treated as a timestamp.
*
* If the argument is none of the above, the function returns Invalid Date.
*
* **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
*
* @param argument - The value to convert
*
* @returns The parsed date in the local time zone
*
* @example
* // Clone the date:
* const result = toDate(new Date(2014, 1, 11, 11, 30, 30))
* //=> Tue Feb 11 2014 11:30:30
*
* @example
* // Convert the timestamp to date:
* const result = toDate(1392098430000)
* //=> Tue Feb 11 2014 11:30:30
*/
function toDate(argument) {
const argStr = Object.prototype.toString.call(argument);
// Clone the date
if (
argument instanceof Date ||
(typeof argument === "object" && argStr === "[object Date]")
) {
// Prevent the date to lose the milliseconds when passed to new Date() in IE10
return new argument.constructor(+argument);
} else if (
typeof argument === "number" ||
argStr === "[object Number]" ||
typeof argument === "string" ||
argStr === "[object String]"
) {
// TODO: Can we get rid of as?
return new Date(argument);
} else {
// TODO: Can we get rid of as?
return new Date(NaN);
}
}
/**
* @name constructFrom
* @category Generic Helpers
* @summary Constructs a date using the reference date and the value
*
* @description
* The function constructs a new date using the constructor from the reference
* date and the given value. It helps to build generic functions that accept
* date extensions.
*
* It defaults to `Date` if the passed reference date is a number or a string.
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
*
* @param date - The reference date to take constructor from
* @param value - The value to create the date
*
* @returns Date initialized using the given date and value
*
* @example
* import { constructFrom } from 'date-fns'
*
* // A function that clones a date preserving the original type
* function cloneDate<DateType extends Date(date: DateType): DateType {
* return constructFrom(
* date, // Use contrustor from the given date
* date.getTime() // Use the date value to create a new date
* )
* }
*/
function constructFrom(date, value) {
if (date instanceof Date) {
return new date.constructor(value);
} else {
return new Date(value);
}
}
/**
* @name addDays
* @category Day Helpers
* @summary Add the specified number of days to the given date.
*
* @description
* Add the specified number of days to the given date.
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
*
* @param date - The date to be changed
* @param amount - The amount of days to be added.
*
* @returns The new date with the days added
*
* @example
* // Add 10 days to 1 September 2014:
* const result = addDays(new Date(2014, 8, 1), 10)
* //=> Thu Sep 11 2014 00:00:00
*/
function addDays(date, amount) {
const _date = toDate(date);
if (isNaN(amount)) return constructFrom(date, NaN);
if (!amount) {
// If 0 days, no-op to avoid changing times in the hour before end of DST
return _date;
}
_date.setDate(_date.getDate() + amount);
return _date;
}
/**
* @name addMonths
* @category Month Helpers
* @summary Add the specified number of months to the given date.
*
* @description
* Add the specified number of months to the given date.
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
*
* @param date - The date to be changed
* @param amount - The amount of months to be added.
*
* @returns The new date with the months added
*
* @example
* // Add 5 months to 1 September 2014:
* const result = addMonths(new Date(2014, 8, 1), 5)
* //=> Sun Feb 01 2015 00:00:00
*
* // Add one month to 30 January 2023:
* const result = addMonths(new Date(2023, 0, 30), 1)
* //=> Tue Feb 28 2023 00:00:00
*/
function addMonths(date, amount) {
const _date = toDate(date);
if (isNaN(amount)) return constructFrom(date, NaN);
if (!amount) {
// If 0 months, no-op to avoid changing times in the hour before end of DST
return _date;
}
const dayOfMonth = _date.getDate();
// The JS Date object supports date math by accepting out-of-bounds values for
// month, day, etc. For example, new Date(2020, 0, 0) returns 31 Dec 2019 and
// new Date(2020, 13, 1) returns 1 Feb 2021. This is *almost* the behavior we
// want except that dates will wrap around the end of a month, meaning that
// new Date(2020, 13, 31) will return 3 Mar 2021 not 28 Feb 2021 as desired. So
// we'll default to the end of the desired month by adding 1 to the desired
// month and using a date of 0 to back up one day to the end of the desired
// month.
const endOfDesiredMonth = constructFrom(date, _date.getTime());
endOfDesiredMonth.setMonth(_date.getMonth() + amount + 1, 0);
const daysInMonth = endOfDesiredMonth.getDate();
if (dayOfMonth >= daysInMonth) {
// If we're already at the end of the month, then this is the correct date
// and we're done.
return endOfDesiredMonth;
} else {
// Otherwise, we now know that setting the original day-of-month value won't
// cause an overflow, so set the desired day-of-month. Note that we can't
// just set the date of `endOfDesiredMonth` because that object may have had
// its time changed in the unusual case where where a DST transition was on
// the last day of the month and its local time was in the hour skipped or
// repeated next to a DST transition. So we use `date` instead which is
// guaranteed to still have the original time.
_date.setFullYear(
endOfDesiredMonth.getFullYear(),
endOfDesiredMonth.getMonth(),
dayOfMonth,
);
return _date;
}
}
let index_es_defaultOptions = {};
function getDefaultOptions() {
return index_es_defaultOptions;
}
/**
* The {@link startOfWeek} function options.
*/
/**
* @name startOfWeek
* @category Week Helpers
* @summary Return the start of a week for the given date.
*
* @description
* Return the start of a week for the given date.
* The result will be in the local timezone.
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
*
* @param date - The original date
* @param options - An object with options
*
* @returns The start of a week
*
* @example
* // The start of a week for 2 September 2014 11:55:00:
* const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0))
* //=> Sun Aug 31 2014 00:00:00
*
* @example
* // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00:
* const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })
* //=> Mon Sep 01 2014 00:00:00
*/
function startOfWeek(date, options) {
const defaultOptions = getDefaultOptions();
const weekStartsOn =
options?.weekStartsOn ??
options?.locale?.options?.weekStartsOn ??
defaultOptions.weekStartsOn ??
defaultOptions.locale?.options?.weekStartsOn ??
0;
const _date = toDate(date);
const day = _date.getDay();
const diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
_date.setDate(_date.getDate() - diff);
_date.setHours(0, 0, 0, 0);
return _date;
}
/**
* @name startOfDay
* @category Day Helpers
* @summary Return the start of a day for the given date.
*
* @description
* Return the start of a day for the given date.
* The result will be in the local timezone.
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
*
* @param date - The original date
*
* @returns The start of a day
*
* @example
* // The start of a day for 2 September 2014 11:55:00:
* const result = startOfDay(new Date(2014, 8, 2, 11, 55, 0))
* //=> Tue Sep 02 2014 00:00:00
*/
function startOfDay(date) {
const _date = toDate(date);
_date.setHours(0, 0, 0, 0);
return _date;
}
/**
* @name addWeeks
* @category Week Helpers
* @summary Add the specified number of weeks to the given date.
*
* @description
* Add the specified number of week to the given date.
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
*
* @param date - The date to be changed
* @param amount - The amount of weeks to be added.
*
* @returns The new date with the weeks added
*
* @example
* // Add 4 weeks to 1 September 2014:
* const result = addWeeks(new Date(2014, 8, 1), 4)
* //=> Mon Sep 29 2014 00:00:00
*/
function addWeeks(date, amount) {
const days = amount * 7;
return addDays(date, days);
}
/**
* @name addYears
* @category Year Helpers
* @summary Add the specified number of years to the given date.
*
* @description
* Add the specified number of years to the given date.
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
*
* @param date - The date to be changed
* @param amount - The amount of years to be added.
*
* @returns The new date with the years added
*
* @example
* // Add 5 years to 1 September 2014:
* const result = addYears(new Date(2014, 8, 1), 5)
* //=> Sun Sep 01 2019 00:00:00
*/
function addYears(date, amount) {
return addMonths(date, amount * 12);
}
/**
* @name endOfMonth
* @category Month Helpers
* @summary Return the end of a month for the given date.
*
* @description
* Return the end of a month for the given date.
* The result will be in the local timezone.
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
*
* @param date - The original date
*
* @returns The end of a month
*
* @example
* // The end of a month for 2 September 2014 11:55:00:
* const result = endOfMonth(new Date(2014, 8, 2, 11, 55, 0))
* //=> Tue Sep 30 2014 23:59:59.999
*/
function endOfMonth(date) {
const _date = toDate(date);
const month = _date.getMonth();
_date.setFullYear(_date.getFullYear(), month + 1, 0);
_date.setHours(23, 59, 59, 999);
return _date;
}
/**
* The {@link eachDayOfInterval} function options.
*/
/**
* @name eachDayOfInterval
* @category Interval Helpers
* @summary Return the array of dates within the specified time interval.
*
* @description
* Return the array of dates within the specified time interval.
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
*
* @param interval - The interval.
* @param options - An object with options.
*
* @returns The array with starts of days from the day of the interval start to the day of the interval end
*
* @example
* // Each day between 6 October 2014 and 10 October 2014:
* const result = eachDayOfInterval({
* start: new Date(2014, 9, 6),
* end: new Date(2014, 9, 10)
* })
* //=> [
* // Mon Oct 06 2014 00:00:00,
* // Tue Oct 07 2014 00:00:00,
* // Wed Oct 08 2014 00:00:00,
* // Thu Oct 09 2014 00:00:00,
* // Fri Oct 10 2014 00:00:00
* // ]
*/
function eachDayOfInterval(interval, options) {
const startDate = toDate(interval.start);
const endDate = toDate(interval.end);
let reversed = +startDate > +endDate;
const endTime = reversed ? +startDate : +endDate;
const currentDate = reversed ? endDate : startDate;
currentDate.setHours(0, 0, 0, 0);
let step = options?.step ?? 1;
if (!step) return [];
if (step < 0) {
step = -step;
reversed = !reversed;
}
const dates = [];
while (+currentDate <= endTime) {
dates.push(toDate(currentDate));
currentDate.setDate(currentDate.getDate() + step);
currentDate.setHours(0, 0, 0, 0);
}
return reversed ? dates.reverse() : dates;
}
/**
* The {@link eachMonthOfInterval} function options.
*/
/**
* @name eachMonthOfInterval
* @category Interval Helpers
* @summary Return the array of months within the specified time interval.
*
* @description
* Return the array of months within the specified time interval.
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
*
* @param interval - The interval
*
* @returns The array with starts of months from the month of the interval start to the month of the interval end
*
* @example
* // Each month between 6 February 2014 and 10 August 2014:
* const result = eachMonthOfInterval({
* start: new Date(2014, 1, 6),
* end: new Date(2014, 7, 10)
* })
* //=> [
* // Sat Feb 01 2014 00:00:00,
* // Sat Mar 01 2014 00:00:00,
* // Tue Apr 01 2014 00:00:00,
* // Thu May 01 2014 00:00:00,
* // Sun Jun 01 2014 00:00:00,
* // Tue Jul 01 2014 00:00:00,
* // Fri Aug 01 2014 00:00:00
* // ]
*/
function eachMonthOfInterval(interval, options) {
const startDate = toDate(interval.start);
const endDate = toDate(interval.end);
let reversed = +startDate > +endDate;
const endTime = reversed ? +startDate : +endDate;
const currentDate = reversed ? endDate : startDate;
currentDate.setHours(0, 0, 0, 0);
currentDate.setDate(1);
let step = options?.step ?? 1;
if (!step) return [];
if (step < 0) {
step = -step;
reversed = !reversed;
}
const dates = [];
while (+currentDate <= endTime) {
dates.push(toDate(currentDate));
currentDate.setMonth(currentDate.getMonth() + step);
}
return reversed ? dates.reverse() : dates;
}
/**
* The {@link eachWeekOfInterval} function options.
*/
/**
* @name eachWeekOfInterval
* @category Interval Helpers
* @summary Return the array of weeks within the specified time interval.
*
* @description
* Return the array of weeks within the specified time interval.
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
*
* @param interval - The interval.
* @param options - An object with options.
*
* @returns The array with starts of weeks from the week of the interval start to the week of the interval end
*
* @example
* // Each week within interval 6 October 2014 - 23 November 2014:
* const result = eachWeekOfInterval({
* start: new Date(2014, 9, 6),
* end: new Date(2014, 10, 23)
* })
* //=> [
* // Sun Oct 05 2014 00:00:00,
* // Sun Oct 12 2014 00:00:00,
* // Sun Oct 19 2014 00:00:00,
* // Sun Oct 26 2014 00:00:00,
* // Sun Nov 02 2014 00:00:00,
* // Sun Nov 09 2014 00:00:00,
* // Sun Nov 16 2014 00:00:00,
* // Sun Nov 23 2014 00:00:00
* // ]
*/
function eachWeekOfInterval(interval, options) {
const startDate = toDate(interval.start);
const endDate = toDate(interval.end);
let reversed = +startDate > +endDate;
const startDateWeek = reversed
? startOfWeek(endDate, options)
: startOfWeek(startDate, options);
const endDateWeek = reversed
? startOfWeek(startDate, options)
: startOfWeek(endDate, options);
// Some timezones switch DST at midnight, making start of day unreliable in these timezones, 3pm is a safe bet
startDateWeek.setHours(15);
endDateWeek.setHours(15);
const endTime = +endDateWeek.getTime();
let currentDate = startDateWeek;
let step = options?.step ?? 1;
if (!step) return [];
if (step < 0) {
step = -step;
reversed = !reversed;
}
const dates = [];
while (+currentDate <= endTime) {
currentDate.setHours(0);
dates.push(toDate(currentDate));
currentDate = addWeeks(currentDate, step);
currentDate.setHours(15);
}
return reversed ? dates.reverse() : dates;
}
/**
* @name startOfMonth
* @category Month Helpers
* @summary Return the start of a month for the given date.
*
* @description
* Return the start of a month for the given date.
* The result will be in the local timezone.
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
*
* @param date - The original date
*
* @returns The start of a month
*
* @example
* // The start of a month for 2 September 2014 11:55:00:
* const result = startOfMonth(new Date(2014, 8, 2, 11, 55, 0))
* //=> Mon Sep 01 2014 00:00:00
*/
function startOfMonth(date) {
const _date = toDate(date);
_date.setDate(1);
_date.setHours(0, 0, 0, 0);
return _date;
}
/**
* The {@link endOfWeek} function options.
*/
/**
* @name endOfWeek
* @category Week Helpers
* @summary Return the end of a week for the given date.
*
* @description
* Return the end of a week for the given date.
* The result will be in the local timezone.
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
*
* @param date - The original date
* @param options - An object with options
*
* @returns The end of a week
*
* @example
* // The end of a week for 2 September 2014 11:55:00:
* const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0))
* //=> Sat Sep 06 2014 23:59:59.999
*
* @example
* // If the week starts on Monday, the end of the week for 2 September 2014 11:55:00:
* const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })
* //=> Sun Sep 07 2014 23:59:59.999
*/
function endOfWeek(date, options) {
const defaultOptions = getDefaultOptions();
const weekStartsOn =
options?.weekStartsOn ??
options?.locale?.options?.weekStartsOn ??
defaultOptions.weekStartsOn ??
defaultOptions.locale?.options?.weekStartsOn ??
0;
const _date = toDate(date);
const day = _date.getDay();
const diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn);
_date.setDate(_date.getDate() + diff);
_date.setHours(23, 59, 59, 999);
return _date;
}
/**
* @name getDaysInMonth
* @category Month Helpers
* @summary Get the number of days in a month of the given date.
*
* @description
* Get the number of days in a month of the given date.
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
*
* @param date - The given date
*
* @returns The number of days in a month
*
* @example
* // How many days are in February 2000?
* const result = getDaysInMonth(new Date(2000, 1))
* //=> 29
*/
function getDaysInMonth(date) {
const _date = toDate(date);
const year = _date.getFullYear();
const monthIndex = _date.getMonth();
const lastDayOfMonth = constructFrom(date, 0);
lastDayOfMonth.setFullYear(year, monthIndex + 1, 0);
lastDayOfMonth.setHours(0, 0, 0, 0);
return lastDayOfMonth.getDate();
}
/**
* @name isAfter
* @category Common Helpers
* @summary Is the first date after the second one?
*
* @description
* Is the first date after the second one?
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
*
* @param date - The date that should be after the other one to return true
* @param dateToCompare - The date to compare with
*
* @returns The first date is after the second date
*
* @example
* // Is 10 July 1989 after 11 February 1987?
* const result = isAfter(new Date(1989, 6, 10), new Date(1987, 1, 11))
* //=> true
*/
function isAfter(date, dateToCompare) {
const _date = toDate(date);
const _dateToCompare = toDate(dateToCompare);
return _date.getTime() > _dateToCompare.getTime();
}
/**
* @name isBefore
* @category Common Helpers
* @summary Is the first date before the second one?
*
* @description
* Is the first date before the second one?
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
*
* @param date - The date that should be before the other one to return true
* @param dateToCompare - The date to compare with
*
* @returns The first date is before the second date
*
* @example
* // Is 10 July 1989 before 11 February 1987?
* const result = isBefore(new Date(1989, 6, 10), new Date(1987, 1, 11))
* //=> false
*/
function isBefore(date, dateToCompare) {
const _date = toDate(date);
const _dateToCompare = toDate(dateToCompare);
return +_date < +_dateToCompare;
}
/**
* @name isEqual
* @category Common Helpers
* @summary Are the given dates equal?
*
* @description
* Are the given dates equal?
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
*
* @param dateLeft - The first date to compare
* @param dateRight - The second date to compare
*
* @returns The dates are equal
*
* @example
* // Are 2 July 2014 06:30:45.000 and 2 July 2014 06:30:45.500 equal?
* const result = isEqual(
* new Date(2014, 6, 2, 6, 30, 45, 0),
* new Date(2014, 6, 2, 6, 30, 45, 500)
* )
* //=> false
*/
function isEqual(leftDate, rightDate) {
const _dateLeft = toDate(leftDate);
const _dateRight = toDate(rightDate);
return +_dateLeft === +_dateRight;
}
/**
* @name setMonth
* @category Month Helpers
* @summary Set the month to the given date.
*
* @description
* Set the month to the given date.
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
*
* @param date - The date to be changed
* @param month - The month index to set (0-11)
*
* @returns The new date with the month set
*
* @example
* // Set February to 1 September 2014:
* const result = setMonth(new Date(2014, 8, 1), 1)
* //=> Sat Feb 01 2014 00:00:00
*/
function setMonth(date, month) {
const _date = toDate(date);
const year = _date.getFullYear();
const day = _date.getDate();
const dateWithDesiredMonth = constructFrom(date, 0);
dateWithDesiredMonth.setFullYear(year, month, 15);
dateWithDesiredMonth.setHours(0, 0, 0, 0);
const daysInMonth = getDaysInMonth(dateWithDesiredMonth);
// Set the last day of the new month
// if the original date was the last day of the longer month
_date.setMonth(month, Math.min(day, daysInMonth));
return _date;
}
/**
* @name set
* @category Common Helpers
* @summary Set date values to a given date.
*
* @description
* Set date values to a given date.
*
* Sets time values to date from object `values`.
* A value is not set if it is undefined or null or doesn't exist in `values`.
*
* Note about bundle size: `set` does not internally use `setX` functions from date-fns but instead opts
* to use native `Date#setX` methods. If you use this function, you may not want to include the
* other `setX` functions that date-fns provides if you are concerned about the bundle size.
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
*
* @param date - The date to be changed
* @param values - The date values to be set
*
* @returns The new date with options set
*
* @example
* // Transform 1 September 2014 into 20 October 2015 in a single line:
* const result = set(new Date(2014, 8, 20), { year: 2015, month: 9, date: 20 })
* //=> Tue Oct 20 2015 00:00:00
*
* @example
* // Set 12 PM to 1 September 2014 01:23:45 to 1 September 2014 12:00:00:
* const result = set(new Date(2014, 8, 1, 1, 23, 45), { hours: 12 })
* //=> Mon Sep 01 2014 12:23:45
*/
function set(date, values) {
let _date = toDate(date);
// Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date
if (isNaN(+_date)) {
return constructFrom(date, NaN);
}
if (values.year != null) {
_date.setFullYear(values.year);
}
if (values.month != null) {
_date = setMonth(_date, values.month);
}
if (values.date != null) {
_date.setDate(values.date);
}
if (values.hours != null) {
_date.setHours(values.hours);
}
if (values.minutes != null) {
_date.setMinutes(values.minutes);
}
if (values.seconds != null) {
_date.setSeconds(values.seconds);
}
if (values.milliseconds != null) {
_date.setMilliseconds(values.milliseconds);
}
return _date;
}
/**
* @name setYear
* @category Year Helpers
* @summary Set the year to the given date.
*
* @description
* Set the year to the given date.
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
*
* @param date - The date to be changed
* @param year - The year of the new date
*
* @returns The new date with the year set
*
* @example
* // Set year 2013 to 1 September 2014:
* const result = setYear(new Date(2014, 8, 1), 2013)
* //=> Sun Sep 01 2013 00:00:00
*/
function setYear(date, year) {
const _date = toDate(date);
// Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date
if (isNaN(+_date)) {
return constructFrom(date, NaN);
}
_date.setFullYear(year);
return _date;
}
/**
* @name startOfToday
* @category Day Helpers
* @summary Return the start of today.
* @pure false
*
* @description
* Return the start of today.
*
* @returns The start of today
*
* @example
* // If today is 6 October 2014:
* const result = startOfToday()
* //=> Mon Oct 6 2014 00:00:00
*/
function startOfToday() {
return startOfDay(Date.now());
}
/**
* @name subMonths
* @category Month Helpers
* @summary Subtract the specified number of months from the given date.
*
* @description
* Subtract the specified number of months from the given date.
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
*
* @param date - The date to be changed
* @param amount - The amount of months to be subtracted.
*
* @returns The new date with the months subtracted
*
* @example
* // Subtract 5 months from 1 February 2015:
* const result = subMonths(new Date(2015, 1, 1), 5)
* //=> Mon Sep 01 2014 00:00:00
*/
function subMonths(date, amount) {
return addMonths(date, -amount);
}
/**
* @name subYears
* @category Year Helpers
* @summary Subtract the specified number of years from the given date.
*
* @description
* Subtract the specified number of years from the given date.
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
*
* @param date - The date to be changed
* @param amount - The amount of years to be subtracted.
*
* @returns The new date with the years subtracted
*
* @example
* // Subtract 5 years from 1 September 2014:
* const result = subYears(new Date(2014, 8, 1), 5)
* //=> Tue Sep 01 2009 00:00:00
*/
function subYears(date, amount) {
return addYears(date, -amount);
}
var Month;
(function (Month) {
Month[Month["JANUARY"] = 0] = "JANUARY";
Month[Month["FEBRUARY"] = 1] = "FEBRUARY";
Month[Month["MARCH"] = 2] = "MARCH";
Month[Month["APRIL"] = 3] = "APRIL";
Month[Month["MAY"] = 4] = "MAY";
Month[Month["JUNE"] = 5] = "JUNE";
Month[Month["JULY"] = 6] = "JULY";
Month[Month["AUGUST"] = 7] = "AUGUST";
Month[Month["SEPTEMBER"] = 8] = "SEPTEMBER";
Month[Month["OCTOBER"] = 9] = "OCTOBER";
Month[Month["NOVEMBER"] = 10] = "NOVEMBER";
Month[Month["DECEMBER"] = 11] = "DECEMBER";
})(Month || (Month = {}));
var Day;
(function (Day) {
Day[Day["SUNDAY"] = 0] = "SUNDAY";
Day[Day["MONDAY"] = 1] = "MONDAY";
Day[Day["TUESDAY"] = 2] = "TUESDAY";
Day[Day["WEDNESDAY"] = 3] = "WEDNESDAY";
Day[Day["THURSDAY"] = 4] = "THURSDAY";
Day[Day["FRIDAY"] = 5] = "FRIDAY";
Day[Day["SATURDAY"] = 6] = "SATURDAY";
})(Day || (Day = {}));
var inRange = function (date, min, max) {
return (isEqual(date, min) || isAfter(date, min)) && (isEqual(date, max) || isBefore(date, max));
};
var clearTime = function (date) { return set(date, { hours: 0, minutes: 0, seconds: 0, milliseconds: 0 }); };
var useLilius = function (_a) {
var _b = _a === void 0 ? {} : _a, _c = _b.weekStartsOn, weekStartsOn = _c === void 0 ? Day.SUNDAY : _c, _d = _b.viewing, initialViewing = _d === void 0 ? new Date() : _d, _e = _b.selected, initialSelected = _e === void 0 ? [] : _e, _f = _b.numberOfMonths, numberOfMonths = _f === void 0 ? 1 : _f;
var _g = (0,external_React_.useState)(initialViewing), viewing = _g[0], setViewing = _g[1];
var viewToday = (0,external_React_.useCallback)(function () { return setViewing(startOfToday()); }, [setViewing]);
var viewMonth = (0,external_React_.useCallback)(function (month) { return setViewing(function (v) { return setMonth(v, month); }); }, []);
var viewPreviousMonth = (0,external_React_.useCallback)(function () { return setViewing(function (v) { return subMonths(v, 1); }); }, []);
var viewNextMonth = (0,external_React_.useCallback)(function () { return setViewing(function (v) { return addMonths(v, 1); }); }, []);
var viewYear = (0,external_React_.useCallback)(function (year) { return setViewing(function (v) { return setYear(v, year); }); }, []);
var viewPreviousYear = (0,external_React_.useCallback)(function () { return setViewing(function (v) { return subYears(v, 1); }); }, []);
var viewNextYear = (0,external_React_.useCallback)(function () { return setViewing(function (v) { return addYears(v, 1); }); }, []);
var _h = (0,external_React_.useState)(initialSelected.map(clearTime)), selected = _h[0], setSelected = _h[1];
var clearSelected = function () { return setSelected([]); };
var isSelected = (0,external_React_.useCallback)(function (date) { return selected.findIndex(function (s) { return isEqual(s, date); }) > -1; }, [selected]);
var select = (0,external_React_.useCallback)(function (date, replaceExisting) {
if (replaceExisting) {
setSelected(Array.isArray(date) ? date : [date]);
}
else {
setSelected(function (selectedItems) { return selectedItems.concat(Array.isArray(date) ? date : [date]); });
}
}, []);
var deselect = (0,external_React_.useCallback)(function (date) {
return setSelected(function (selectedItems) {
return Array.isArray(date)
? selectedItems.filter(function (s) { return !date.map(function (d) { return d.getTime(); }).includes(s.getTime()); })
: selectedItems.filter(function (s) { return !isEqual(s, date); });
});
}, []);
var toggle = (0,external_React_.useCallback)(function (date, replaceExisting) { return (isSelected(date) ? deselect(date) : select(date, replaceExisting)); }, [deselect, isSelected, select]);
var selectRange = (0,external_React_.useCallback)(function (start, end, replaceExisting) {
if (replaceExisting) {
setSelected(eachDayOfInterval({ start: start, end: end }));
}
else {
setSelected(function (selectedItems) { return selectedItems.concat(eachDayOfInterval({ start: start, end: end })); });
}
}, []);
var deselectRange = (0,external_React_.useCallback)(function (start, end) {
setSelected(function (selectedItems) {
return selectedItems.filter(function (s) {
return !eachDayOfInterval({ start: start, end: end })
.map(function (d) { return d.getTime(); })
.includes(s.getTime());
});
});
}, []);
var calendar = (0,external_React_.useMemo)(function () {
return eachMonthOfInterval({
start: startOfMonth(viewing),
end: endOfMonth(addMonths(viewing, numberOfMonths - 1)),
}).map(function (month) {
return eachWeekOfInterval({
start: startOfMonth(month),
end: endOfMonth(month),
}, { weekStartsOn: weekStartsOn }).map(function (week) {
return eachDayOfInterval({
start: startOfWeek(week, { weekStartsOn: weekStartsOn }),
end: endOfWeek(week, { weekStartsOn: weekStartsOn }),
});
});
});
}, [viewing, weekStartsOn, numberOfMonths]);
return {
clearTime: clearTime,
inRange: inRange,
viewing: viewing,
setViewing: setViewing,
viewToday: viewToday,
viewMonth: viewMonth,
viewPreviousMonth: viewPreviousMonth,
viewNextMonth: viewNextMonth,
viewYear: viewYear,
viewPreviousYear: viewPreviousYear,
viewNextYear: viewNextYear,
selected: selected,
setSelected: setSelected,
clearSelected: clearSelected,
isSelected: isSelected,
select: select,
deselect: deselect,
toggle: toggle,
selectRange: selectRange,
deselectRange: deselectRange,
calendar: calendar,
};
};
;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/typeof.js
function _typeof(o) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
return typeof o;
} : function (o) {
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
}, _typeof(o);
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/requiredArgs/index.js
function requiredArgs(required, args) {
if (args.length < required) {
throw new TypeError(required + ' argument' + (required > 1 ? 's' : '') + ' required, but only ' + args.length + ' present');
}
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/toDate/index.js
/**
* @name toDate
* @category Common Helpers
* @summary Convert the given argument to an instance of Date.
*
* @description
* Convert the given argument to an instance of Date.
*
* If the argument is an instance of Date, the function returns its clone.
*
* If the argument is a number, it is treated as a timestamp.
*
* If the argument is none of the above, the function returns Invalid Date.
*
* **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.
*
* @param {Date|Number} argument - the value to convert
* @returns {Date} the parsed date in the local time zone
* @throws {TypeError} 1 argument required
*
* @example
* // Clone the date:
* const result = toDate(new Date(2014, 1, 11, 11, 30, 30))
* //=> Tue Feb 11 2014 11:30:30
*
* @example
* // Convert the timestamp to date:
* const result = toDate(1392098430000)
* //=> Tue Feb 11 2014 11:30:30
*/
function toDate_toDate(argument) {
requiredArgs(1, arguments);
var argStr = Object.prototype.toString.call(argument);
// Clone the date
if (argument instanceof Date || _typeof(argument) === 'object' && argStr === '[object Date]') {
// Prevent the date to lose the milliseconds when passed to new Date() in IE10
return new Date(argument.getTime());
} else if (typeof argument === 'number' || argStr === '[object Number]') {
return new Date(argument);
} else {
if ((typeof argument === 'string' || argStr === '[object String]') && typeof console !== 'undefined') {
// eslint-disable-next-line no-console
console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments");
// eslint-disable-next-line no-console
console.warn(new Error().stack);
}
return new Date(NaN);
}
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/startOfDay/index.js
/**
* @name startOfDay
* @category Day Helpers
* @summary Return the start of a day for the given date.
*
* @description
* Return the start of a day for the given date.
* The result will be in the local timezone.
*
* @param {Date|Number} date - the original date
* @returns {Date} the start of a day
* @throws {TypeError} 1 argument required
*
* @example
* // The start of a day for 2 September 2014 11:55:00:
* const result = startOfDay(new Date(2014, 8, 2, 11, 55, 0))
* //=> Tue Sep 02 2014 00:00:00
*/
function startOfDay_startOfDay(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate_toDate(dirtyDate);
date.setHours(0, 0, 0, 0);
return date;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/toInteger/index.js
function toInteger(dirtyNumber) {
if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) {
return NaN;
}
var number = Number(dirtyNumber);
if (isNaN(number)) {
return number;
}
return number < 0 ? Math.ceil(number) : Math.floor(number);
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/addMonths/index.js
/**
* @name addMonths
* @category Month Helpers
* @summary Add the specified number of months to the given date.
*
* @description
* Add the specified number of months to the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of months to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the months added
* @throws {TypeError} 2 arguments required
*
* @example
* // Add 5 months to 1 September 2014:
* const result = addMonths(new Date(2014, 8, 1), 5)
* //=> Sun Feb 01 2015 00:00:00
*/
function addMonths_addMonths(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var date = toDate_toDate(dirtyDate);
var amount = toInteger(dirtyAmount);
if (isNaN(amount)) {
return new Date(NaN);
}
if (!amount) {
// If 0 months, no-op to avoid changing times in the hour before end of DST
return date;
}
var dayOfMonth = date.getDate();
// The JS Date object supports date math by accepting out-of-bounds values for
// month, day, etc. For example, new Date(2020, 0, 0) returns 31 Dec 2019 and
// new Date(2020, 13, 1) returns 1 Feb 2021. This is *almost* the behavior we
// want except that dates will wrap around the end of a month, meaning that
// new Date(2020, 13, 31) will return 3 Mar 2021 not 28 Feb 2021 as desired. So
// we'll default to the end of the desired month by adding 1 to the desired
// month and using a date of 0 to back up one day to the end of the desired
// month.
var endOfDesiredMonth = new Date(date.getTime());
endOfDesiredMonth.setMonth(date.getMonth() + amount + 1, 0);
var daysInMonth = endOfDesiredMonth.getDate();
if (dayOfMonth >= daysInMonth) {
// If we're already at the end of the month, then this is the correct date
// and we're done.
return endOfDesiredMonth;
} else {
// Otherwise, we now know that setting the original day-of-month value won't
// cause an overflow, so set the desired day-of-month. Note that we can't
// just set the date of `endOfDesiredMonth` because that object may have had
// its time changed in the unusual case where where a DST transition was on
// the last day of the month and its local time was in the hour skipped or
// repeated next to a DST transition. So we use `date` instead which is
// guaranteed to still have the original time.
date.setFullYear(endOfDesiredMonth.getFullYear(), endOfDesiredMonth.getMonth(), dayOfMonth);
return date;
}
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/subMonths/index.js
/**
* @name subMonths
* @category Month Helpers
* @summary Subtract the specified number of months from the given date.
*
* @description
* Subtract the specified number of months from the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of months to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the months subtracted
* @throws {TypeError} 2 arguments required
*
* @example
* // Subtract 5 months from 1 February 2015:
* const result = subMonths(new Date(2015, 1, 1), 5)
* //=> Mon Sep 01 2014 00:00:00
*/
function subMonths_subMonths(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var amount = toInteger(dirtyAmount);
return addMonths_addMonths(dirtyDate, -amount);
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/isDate/index.js
/**
* @name isDate
* @category Common Helpers
* @summary Is the given value a date?
*
* @description
* Returns true if the given value is an instance of Date. The function works for dates transferred across iframes.
*
* @param {*} value - the value to check
* @returns {boolean} true if the given value is a date
* @throws {TypeError} 1 arguments required
*
* @example
* // For a valid date:
* const result = isDate(new Date())
* //=> true
*
* @example
* // For an invalid date:
* const result = isDate(new Date(NaN))
* //=> true
*
* @example
* // For some value:
* const result = isDate('2014-02-31')
* //=> false
*
* @example
* // For an object:
* const result = isDate({})
* //=> false
*/
function isDate(value) {
requiredArgs(1, arguments);
return value instanceof Date || _typeof(value) === 'object' && Object.prototype.toString.call(value) === '[object Date]';
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/isValid/index.js
/**
* @name isValid
* @category Common Helpers
* @summary Is the given date valid?
*
* @description
* Returns false if argument is Invalid Date and true otherwise.
* Argument is converted to Date using `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate}
* Invalid Date is a Date, whose time value is NaN.
*
* Time value of Date: http://es5.github.io/#x15.9.1.1
*
* @param {*} date - the date to check
* @returns {Boolean} the date is valid
* @throws {TypeError} 1 argument required
*
* @example
* // For the valid date:
* const result = isValid(new Date(2014, 1, 31))
* //=> true
*
* @example
* // For the value, convertable into a date:
* const result = isValid(1393804800000)
* //=> true
*
* @example
* // For the invalid date:
* const result = isValid(new Date(''))
* //=> false
*/
function isValid(dirtyDate) {
requiredArgs(1, arguments);
if (!isDate(dirtyDate) && typeof dirtyDate !== 'number') {
return false;
}
var date = toDate_toDate(dirtyDate);
return !isNaN(Number(date));
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/addMilliseconds/index.js
/**
* @name addMilliseconds
* @category Millisecond Helpers
* @summary Add the specified number of milliseconds to the given date.
*
* @description
* Add the specified number of milliseconds to the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of milliseconds to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the milliseconds added
* @throws {TypeError} 2 arguments required
*
* @example
* // Add 750 milliseconds to 10 July 2014 12:45:30.000:
* const result = addMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750)
* //=> Thu Jul 10 2014 12:45:30.750
*/
function addMilliseconds(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var timestamp = toDate_toDate(dirtyDate).getTime();
var amount = toInteger(dirtyAmount);
return new Date(timestamp + amount);
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/subMilliseconds/index.js
/**
* @name subMilliseconds
* @category Millisecond Helpers
* @summary Subtract the specified number of milliseconds from the given date.
*
* @description
* Subtract the specified number of milliseconds from the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of milliseconds to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the milliseconds subtracted
* @throws {TypeError} 2 arguments required
*
* @example
* // Subtract 750 milliseconds from 10 July 2014 12:45:30.000:
* const result = subMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750)
* //=> Thu Jul 10 2014 12:45:29.250
*/
function subMilliseconds(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var amount = toInteger(dirtyAmount);
return addMilliseconds(dirtyDate, -amount);
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/getUTCDayOfYear/index.js
var MILLISECONDS_IN_DAY = 86400000;
function getUTCDayOfYear(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate_toDate(dirtyDate);
var timestamp = date.getTime();
date.setUTCMonth(0, 1);
date.setUTCHours(0, 0, 0, 0);
var startOfYearTimestamp = date.getTime();
var difference = timestamp - startOfYearTimestamp;
return Math.floor(difference / MILLISECONDS_IN_DAY) + 1;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/startOfUTCISOWeek/index.js
function startOfUTCISOWeek(dirtyDate) {
requiredArgs(1, arguments);
var weekStartsOn = 1;
var date = toDate_toDate(dirtyDate);
var day = date.getUTCDay();
var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
date.setUTCDate(date.getUTCDate() - diff);
date.setUTCHours(0, 0, 0, 0);
return date;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/getUTCISOWeekYear/index.js
function getUTCISOWeekYear(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate_toDate(dirtyDate);
var year = date.getUTCFullYear();
var fourthOfJanuaryOfNextYear = new Date(0);
fourthOfJanuaryOfNextYear.setUTCFullYear(year + 1, 0, 4);
fourthOfJanuaryOfNextYear.setUTCHours(0, 0, 0, 0);
var startOfNextYear = startOfUTCISOWeek(fourthOfJanuaryOfNextYear);
var fourthOfJanuaryOfThisYear = new Date(0);
fourthOfJanuaryOfThisYear.setUTCFullYear(year, 0, 4);
fourthOfJanuaryOfThisYear.setUTCHours(0, 0, 0, 0);
var startOfThisYear = startOfUTCISOWeek(fourthOfJanuaryOfThisYear);
if (date.getTime() >= startOfNextYear.getTime()) {
return year + 1;
} else if (date.getTime() >= startOfThisYear.getTime()) {
return year;
} else {
return year - 1;
}
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/startOfUTCISOWeekYear/index.js
function startOfUTCISOWeekYear(dirtyDate) {
requiredArgs(1, arguments);
var year = getUTCISOWeekYear(dirtyDate);
var fourthOfJanuary = new Date(0);
fourthOfJanuary.setUTCFullYear(year, 0, 4);
fourthOfJanuary.setUTCHours(0, 0, 0, 0);
var date = startOfUTCISOWeek(fourthOfJanuary);
return date;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/getUTCISOWeek/index.js
var MILLISECONDS_IN_WEEK = 604800000;
function getUTCISOWeek(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate_toDate(dirtyDate);
var diff = startOfUTCISOWeek(date).getTime() - startOfUTCISOWeekYear(date).getTime();
// Round the number of days to the nearest integer
// because the number of milliseconds in a week is not constant
// (e.g. it's different in the week of the daylight saving time clock shift)
return Math.round(diff / MILLISECONDS_IN_WEEK) + 1;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/defaultOptions/index.js
var defaultOptions_defaultOptions = {};
function defaultOptions_getDefaultOptions() {
return defaultOptions_defaultOptions;
}
function setDefaultOptions(newOptions) {
defaultOptions_defaultOptions = newOptions;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/startOfUTCWeek/index.js
function startOfUTCWeek(dirtyDate, options) {
var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
requiredArgs(1, arguments);
var defaultOptions = defaultOptions_getDefaultOptions();
var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0);
// Test if weekStartsOn is between 0 and 6 _and_ is not NaN
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
}
var date = toDate_toDate(dirtyDate);
var day = date.getUTCDay();
var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
date.setUTCDate(date.getUTCDate() - diff);
date.setUTCHours(0, 0, 0, 0);
return date;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/getUTCWeekYear/index.js
function getUTCWeekYear(dirtyDate, options) {
var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
requiredArgs(1, arguments);
var date = toDate_toDate(dirtyDate);
var year = date.getUTCFullYear();
var defaultOptions = defaultOptions_getDefaultOptions();
var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1);
// Test if weekStartsOn is between 1 and 7 _and_ is not NaN
if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
}
var firstWeekOfNextYear = new Date(0);
firstWeekOfNextYear.setUTCFullYear(year + 1, 0, firstWeekContainsDate);
firstWeekOfNextYear.setUTCHours(0, 0, 0, 0);
var startOfNextYear = startOfUTCWeek(firstWeekOfNextYear, options);
var firstWeekOfThisYear = new Date(0);
firstWeekOfThisYear.setUTCFullYear(year, 0, firstWeekContainsDate);
firstWeekOfThisYear.setUTCHours(0, 0, 0, 0);
var startOfThisYear = startOfUTCWeek(firstWeekOfThisYear, options);
if (date.getTime() >= startOfNextYear.getTime()) {
return year + 1;
} else if (date.getTime() >= startOfThisYear.getTime()) {
return year;
} else {
return year - 1;
}
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/startOfUTCWeekYear/index.js
function startOfUTCWeekYear(dirtyDate, options) {
var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
requiredArgs(1, arguments);
var defaultOptions = defaultOptions_getDefaultOptions();
var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1);
var year = getUTCWeekYear(dirtyDate, options);
var firstWeek = new Date(0);
firstWeek.setUTCFullYear(year, 0, firstWeekContainsDate);
firstWeek.setUTCHours(0, 0, 0, 0);
var date = startOfUTCWeek(firstWeek, options);
return date;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/getUTCWeek/index.js
var getUTCWeek_MILLISECONDS_IN_WEEK = 604800000;
function getUTCWeek(dirtyDate, options) {
requiredArgs(1, arguments);
var date = toDate_toDate(dirtyDate);
var diff = startOfUTCWeek(date, options).getTime() - startOfUTCWeekYear(date, options).getTime();
// Round the number of days to the nearest integer
// because the number of milliseconds in a week is not constant
// (e.g. it's different in the week of the daylight saving time clock shift)
return Math.round(diff / getUTCWeek_MILLISECONDS_IN_WEEK) + 1;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/addLeadingZeros/index.js
function addLeadingZeros(number, targetLength) {
var sign = number < 0 ? '-' : '';
var output = Math.abs(number).toString();
while (output.length < targetLength) {
output = '0' + output;
}
return sign + output;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/format/lightFormatters/index.js
/*
* | | Unit | | Unit |
* |-----|--------------------------------|-----|--------------------------------|
* | a | AM, PM | A* | |
* | d | Day of month | D | |
* | h | Hour [1-12] | H | Hour [0-23] |
* | m | Minute | M | Month |
* | s | Second | S | Fraction of second |
* | y | Year (abs) | Y | |
*
* Letters marked by * are not implemented but reserved by Unicode standard.
*/
var formatters = {
// Year
y: function y(date, token) {
// From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_tokens
// | Year | y | yy | yyy | yyyy | yyyyy |
// |----------|-------|----|-------|-------|-------|
// | AD 1 | 1 | 01 | 001 | 0001 | 00001 |
// | AD 12 | 12 | 12 | 012 | 0012 | 00012 |
// | AD 123 | 123 | 23 | 123 | 0123 | 00123 |
// | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 |
// | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 |
var signedYear = date.getUTCFullYear();
// Returns 1 for 1 BC (which is year 0 in JavaScript)
var year = signedYear > 0 ? signedYear : 1 - signedYear;
return addLeadingZeros(token === 'yy' ? year % 100 : year, token.length);
},
// Month
M: function M(date, token) {
var month = date.getUTCMonth();
return token === 'M' ? String(month + 1) : addLeadingZeros(month + 1, 2);
},
// Day of the month
d: function d(date, token) {
return addLeadingZeros(date.getUTCDate(), token.length);
},
// AM or PM
a: function a(date, token) {
var dayPeriodEnumValue = date.getUTCHours() / 12 >= 1 ? 'pm' : 'am';
switch (token) {
case 'a':
case 'aa':
return dayPeriodEnumValue.toUpperCase();
case 'aaa':
return dayPeriodEnumValue;
case 'aaaaa':
return dayPeriodEnumValue[0];
case 'aaaa':
default:
return dayPeriodEnumValue === 'am' ? 'a.m.' : 'p.m.';
}
},
// Hour [1-12]
h: function h(date, token) {
return addLeadingZeros(date.getUTCHours() % 12 || 12, token.length);
},
// Hour [0-23]
H: function H(date, token) {
return addLeadingZeros(date.getUTCHours(), token.length);
},
// Minute
m: function m(date, token) {
return addLeadingZeros(date.getUTCMinutes(), token.length);
},
// Second
s: function s(date, token) {
return addLeadingZeros(date.getUTCSeconds(), token.length);
},
// Fraction of second
S: function S(date, token) {
var numberOfDigits = token.length;
var milliseconds = date.getUTCMilliseconds();
var fractionalSeconds = Math.floor(milliseconds * Math.pow(10, numberOfDigits - 3));
return addLeadingZeros(fractionalSeconds, token.length);
}
};
/* harmony default export */ var lightFormatters = (formatters);
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/format/formatters/index.js
var dayPeriodEnum = {
am: 'am',
pm: 'pm',
midnight: 'midnight',
noon: 'noon',
morning: 'morning',
afternoon: 'afternoon',
evening: 'evening',
night: 'night'
};
/*
* | | Unit | | Unit |
* |-----|--------------------------------|-----|--------------------------------|
* | a | AM, PM | A* | Milliseconds in day |
* | b | AM, PM, noon, midnight | B | Flexible day period |
* | c | Stand-alone local day of week | C* | Localized hour w/ day period |
* | d | Day of month | D | Day of year |
* | e | Local day of week | E | Day of week |
* | f | | F* | Day of week in month |
* | g* | Modified Julian day | G | Era |
* | h | Hour [1-12] | H | Hour [0-23] |
* | i! | ISO day of week | I! | ISO week of year |
* | j* | Localized hour w/ day period | J* | Localized hour w/o day period |
* | k | Hour [1-24] | K | Hour [0-11] |
* | l* | (deprecated) | L | Stand-alone month |
* | m | Minute | M | Month |
* | n | | N | |
* | o! | Ordinal number modifier | O | Timezone (GMT) |
* | p! | Long localized time | P! | Long localized date |
* | q | Stand-alone quarter | Q | Quarter |
* | r* | Related Gregorian year | R! | ISO week-numbering year |
* | s | Second | S | Fraction of second |
* | t! | Seconds timestamp | T! | Milliseconds timestamp |
* | u | Extended year | U* | Cyclic year |
* | v* | Timezone (generic non-locat.) | V* | Timezone (location) |
* | w | Local week of year | W* | Week of month |
* | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) |
* | y | Year (abs) | Y | Local week-numbering year |
* | z | Timezone (specific non-locat.) | Z* | Timezone (aliases) |
*
* Letters marked by * are not implemented but reserved by Unicode standard.
*
* Letters marked by ! are non-standard, but implemented by date-fns:
* - `o` modifies the previous token to turn it into an ordinal (see `format` docs)
* - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,
* i.e. 7 for Sunday, 1 for Monday, etc.
* - `I` is ISO week of year, as opposed to `w` which is local week of year.
* - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.
* `R` is supposed to be used in conjunction with `I` and `i`
* for universal ISO week-numbering date, whereas
* `Y` is supposed to be used in conjunction with `w` and `e`
* for week-numbering date specific to the locale.
* - `P` is long localized date format
* - `p` is long localized time format
*/
var formatters_formatters = {
// Era
G: function G(date, token, localize) {
var era = date.getUTCFullYear() > 0 ? 1 : 0;
switch (token) {
// AD, BC
case 'G':
case 'GG':
case 'GGG':
return localize.era(era, {
width: 'abbreviated'
});
// A, B
case 'GGGGG':
return localize.era(era, {
width: 'narrow'
});
// Anno Domini, Before Christ
case 'GGGG':
default:
return localize.era(era, {
width: 'wide'
});
}
},
// Year
y: function y(date, token, localize) {
// Ordinal number
if (token === 'yo') {
var signedYear = date.getUTCFullYear();
// Returns 1 for 1 BC (which is year 0 in JavaScript)
var year = signedYear > 0 ? signedYear : 1 - signedYear;
return localize.ordinalNumber(year, {
unit: 'year'
});
}
return lightFormatters.y(date, token);
},
// Local week-numbering year
Y: function Y(date, token, localize, options) {
var signedWeekYear = getUTCWeekYear(date, options);
// Returns 1 for 1 BC (which is year 0 in JavaScript)
var weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear;
// Two digit year
if (token === 'YY') {
var twoDigitYear = weekYear % 100;
return addLeadingZeros(twoDigitYear, 2);
}
// Ordinal number
if (token === 'Yo') {
return localize.ordinalNumber(weekYear, {
unit: 'year'
});
}
// Padding
return addLeadingZeros(weekYear, token.length);
},
// ISO week-numbering year
R: function R(date, token) {
var isoWeekYear = getUTCISOWeekYear(date);
// Padding
return addLeadingZeros(isoWeekYear, token.length);
},
// Extended year. This is a single number designating the year of this calendar system.
// The main difference between `y` and `u` localizers are B.C. years:
// | Year | `y` | `u` |
// |------|-----|-----|
// | AC 1 | 1 | 1 |
// | BC 1 | 1 | 0 |
// | BC 2 | 2 | -1 |
// Also `yy` always returns the last two digits of a year,
// while `uu` pads single digit years to 2 characters and returns other years unchanged.
u: function u(date, token) {
var year = date.getUTCFullYear();
return addLeadingZeros(year, token.length);
},
// Quarter
Q: function Q(date, token, localize) {
var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
switch (token) {
// 1, 2, 3, 4
case 'Q':
return String(quarter);
// 01, 02, 03, 04
case 'QQ':
return addLeadingZeros(quarter, 2);
// 1st, 2nd, 3rd, 4th
case 'Qo':
return localize.ordinalNumber(quarter, {
unit: 'quarter'
});
// Q1, Q2, Q3, Q4
case 'QQQ':
return localize.quarter(quarter, {
width: 'abbreviated',
context: 'formatting'
});
// 1, 2, 3, 4 (narrow quarter; could be not numerical)
case 'QQQQQ':
return localize.quarter(quarter, {
width: 'narrow',
context: 'formatting'
});
// 1st quarter, 2nd quarter, ...
case 'QQQQ':
default:
return localize.quarter(quarter, {
width: 'wide',
context: 'formatting'
});
}
},
// Stand-alone quarter
q: function q(date, token, localize) {
var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
switch (token) {
// 1, 2, 3, 4
case 'q':
return String(quarter);
// 01, 02, 03, 04
case 'qq':
return addLeadingZeros(quarter, 2);
// 1st, 2nd, 3rd, 4th
case 'qo':
return localize.ordinalNumber(quarter, {
unit: 'quarter'
});
// Q1, Q2, Q3, Q4
case 'qqq':
return localize.quarter(quarter, {
width: 'abbreviated',
context: 'standalone'
});
// 1, 2, 3, 4 (narrow quarter; could be not numerical)
case 'qqqqq':
return localize.quarter(quarter, {
width: 'narrow',
context: 'standalone'
});
// 1st quarter, 2nd quarter, ...
case 'qqqq':
default:
return localize.quarter(quarter, {
width: 'wide',
context: 'standalone'
});
}
},
// Month
M: function M(date, token, localize) {
var month = date.getUTCMonth();
switch (token) {
case 'M':
case 'MM':
return lightFormatters.M(date, token);
// 1st, 2nd, ..., 12th
case 'Mo':
return localize.ordinalNumber(month + 1, {
unit: 'month'
});
// Jan, Feb, ..., Dec
case 'MMM':
return localize.month(month, {
width: 'abbreviated',
context: 'formatting'
});
// J, F, ..., D
case 'MMMMM':
return localize.month(month, {
width: 'narrow',
context: 'formatting'
});
// January, February, ..., December
case 'MMMM':
default:
return localize.month(month, {
width: 'wide',
context: 'formatting'
});
}
},
// Stand-alone month
L: function L(date, token, localize) {
var month = date.getUTCMonth();
switch (token) {
// 1, 2, ..., 12
case 'L':
return String(month + 1);
// 01, 02, ..., 12
case 'LL':
return addLeadingZeros(month + 1, 2);
// 1st, 2nd, ..., 12th
case 'Lo':
return localize.ordinalNumber(month + 1, {
unit: 'month'
});
// Jan, Feb, ..., Dec
case 'LLL':
return localize.month(month, {
width: 'abbreviated',
context: 'standalone'
});
// J, F, ..., D
case 'LLLLL':
return localize.month(month, {
width: 'narrow',
context: 'standalone'
});
// January, February, ..., December
case 'LLLL':
default:
return localize.month(month, {
width: 'wide',
context: 'standalone'
});
}
},
// Local week of year
w: function w(date, token, localize, options) {
var week = getUTCWeek(date, options);
if (token === 'wo') {
return localize.ordinalNumber(week, {
unit: 'week'
});
}
return addLeadingZeros(week, token.length);
},
// ISO week of year
I: function I(date, token, localize) {
var isoWeek = getUTCISOWeek(date);
if (token === 'Io') {
return localize.ordinalNumber(isoWeek, {
unit: 'week'
});
}
return addLeadingZeros(isoWeek, token.length);
},
// Day of the month
d: function d(date, token, localize) {
if (token === 'do') {
return localize.ordinalNumber(date.getUTCDate(), {
unit: 'date'
});
}
return lightFormatters.d(date, token);
},
// Day of year
D: function D(date, token, localize) {
var dayOfYear = getUTCDayOfYear(date);
if (token === 'Do') {
return localize.ordinalNumber(dayOfYear, {
unit: 'dayOfYear'
});
}
return addLeadingZeros(dayOfYear, token.length);
},
// Day of week
E: function E(date, token, localize) {
var dayOfWeek = date.getUTCDay();
switch (token) {
// Tue
case 'E':
case 'EE':
case 'EEE':
return localize.day(dayOfWeek, {
width: 'abbreviated',
context: 'formatting'
});
// T
case 'EEEEE':
return localize.day(dayOfWeek, {
width: 'narrow',
context: 'formatting'
});
// Tu
case 'EEEEEE':
return localize.day(dayOfWeek, {
width: 'short',
context: 'formatting'
});
// Tuesday
case 'EEEE':
default:
return localize.day(dayOfWeek, {
width: 'wide',
context: 'formatting'
});
}
},
// Local day of week
e: function e(date, token, localize, options) {
var dayOfWeek = date.getUTCDay();
var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
switch (token) {
// Numerical value (Nth day of week with current locale or weekStartsOn)
case 'e':
return String(localDayOfWeek);
// Padded numerical value
case 'ee':
return addLeadingZeros(localDayOfWeek, 2);
// 1st, 2nd, ..., 7th
case 'eo':
return localize.ordinalNumber(localDayOfWeek, {
unit: 'day'
});
case 'eee':
return localize.day(dayOfWeek, {
width: 'abbreviated',
context: 'formatting'
});
// T
case 'eeeee':
return localize.day(dayOfWeek, {
width: 'narrow',
context: 'formatting'
});
// Tu
case 'eeeeee':
return localize.day(dayOfWeek, {
width: 'short',
context: 'formatting'
});
// Tuesday
case 'eeee':
default:
return localize.day(dayOfWeek, {
width: 'wide',
context: 'formatting'
});
}
},
// Stand-alone local day of week
c: function c(date, token, localize, options) {
var dayOfWeek = date.getUTCDay();
var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
switch (token) {
// Numerical value (same as in `e`)
case 'c':
return String(localDayOfWeek);
// Padded numerical value
case 'cc':
return addLeadingZeros(localDayOfWeek, token.length);
// 1st, 2nd, ..., 7th
case 'co':
return localize.ordinalNumber(localDayOfWeek, {
unit: 'day'
});
case 'ccc':
return localize.day(dayOfWeek, {
width: 'abbreviated',
context: 'standalone'
});
// T
case 'ccccc':
return localize.day(dayOfWeek, {
width: 'narrow',
context: 'standalone'
});
// Tu
case 'cccccc':
return localize.day(dayOfWeek, {
width: 'short',
context: 'standalone'
});
// Tuesday
case 'cccc':
default:
return localize.day(dayOfWeek, {
width: 'wide',
context: 'standalone'
});
}
},
// ISO day of week
i: function i(date, token, localize) {
var dayOfWeek = date.getUTCDay();
var isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;
switch (token) {
// 2
case 'i':
return String(isoDayOfWeek);
// 02
case 'ii':
return addLeadingZeros(isoDayOfWeek, token.length);
// 2nd
case 'io':
return localize.ordinalNumber(isoDayOfWeek, {
unit: 'day'
});
// Tue
case 'iii':
return localize.day(dayOfWeek, {
width: 'abbreviated',
context: 'formatting'
});
// T
case 'iiiii':
return localize.day(dayOfWeek, {
width: 'narrow',
context: 'formatting'
});
// Tu
case 'iiiiii':
return localize.day(dayOfWeek, {
width: 'short',
context: 'formatting'
});
// Tuesday
case 'iiii':
default:
return localize.day(dayOfWeek, {
width: 'wide',
context: 'formatting'
});
}
},
// AM or PM
a: function a(date, token, localize) {
var hours = date.getUTCHours();
var dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am';
switch (token) {
case 'a':
case 'aa':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'abbreviated',
context: 'formatting'
});
case 'aaa':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'abbreviated',
context: 'formatting'
}).toLowerCase();
case 'aaaaa':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'narrow',
context: 'formatting'
});
case 'aaaa':
default:
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'wide',
context: 'formatting'
});
}
},
// AM, PM, midnight, noon
b: function b(date, token, localize) {
var hours = date.getUTCHours();
var dayPeriodEnumValue;
if (hours === 12) {
dayPeriodEnumValue = dayPeriodEnum.noon;
} else if (hours === 0) {
dayPeriodEnumValue = dayPeriodEnum.midnight;
} else {
dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am';
}
switch (token) {
case 'b':
case 'bb':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'abbreviated',
context: 'formatting'
});
case 'bbb':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'abbreviated',
context: 'formatting'
}).toLowerCase();
case 'bbbbb':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'narrow',
context: 'formatting'
});
case 'bbbb':
default:
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'wide',
context: 'formatting'
});
}
},
// in the morning, in the afternoon, in the evening, at night
B: function B(date, token, localize) {
var hours = date.getUTCHours();
var dayPeriodEnumValue;
if (hours >= 17) {
dayPeriodEnumValue = dayPeriodEnum.evening;
} else if (hours >= 12) {
dayPeriodEnumValue = dayPeriodEnum.afternoon;
} else if (hours >= 4) {
dayPeriodEnumValue = dayPeriodEnum.morning;
} else {
dayPeriodEnumValue = dayPeriodEnum.night;
}
switch (token) {
case 'B':
case 'BB':
case 'BBB':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'abbreviated',
context: 'formatting'
});
case 'BBBBB':
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'narrow',
context: 'formatting'
});
case 'BBBB':
default:
return localize.dayPeriod(dayPeriodEnumValue, {
width: 'wide',
context: 'formatting'
});
}
},
// Hour [1-12]
h: function h(date, token, localize) {
if (token === 'ho') {
var hours = date.getUTCHours() % 12;
if (hours === 0) hours = 12;
return localize.ordinalNumber(hours, {
unit: 'hour'
});
}
return lightFormatters.h(date, token);
},
// Hour [0-23]
H: function H(date, token, localize) {
if (token === 'Ho') {
return localize.ordinalNumber(date.getUTCHours(), {
unit: 'hour'
});
}
return lightFormatters.H(date, token);
},
// Hour [0-11]
K: function K(date, token, localize) {
var hours = date.getUTCHours() % 12;
if (token === 'Ko') {
return localize.ordinalNumber(hours, {
unit: 'hour'
});
}
return addLeadingZeros(hours, token.length);
},
// Hour [1-24]
k: function k(date, token, localize) {
var hours = date.getUTCHours();
if (hours === 0) hours = 24;
if (token === 'ko') {
return localize.ordinalNumber(hours, {
unit: 'hour'
});
}
return addLeadingZeros(hours, token.length);
},
// Minute
m: function m(date, token, localize) {
if (token === 'mo') {
return localize.ordinalNumber(date.getUTCMinutes(), {
unit: 'minute'
});
}
return lightFormatters.m(date, token);
},
// Second
s: function s(date, token, localize) {
if (token === 'so') {
return localize.ordinalNumber(date.getUTCSeconds(), {
unit: 'second'
});
}
return lightFormatters.s(date, token);
},
// Fraction of second
S: function S(date, token) {
return lightFormatters.S(date, token);
},
// Timezone (ISO-8601. If offset is 0, output is always `'Z'`)
X: function X(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
if (timezoneOffset === 0) {
return 'Z';
}
switch (token) {
// Hours and optional minutes
case 'X':
return formatTimezoneWithOptionalMinutes(timezoneOffset);
// Hours, minutes and optional seconds without `:` delimiter
// Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
// so this token always has the same output as `XX`
case 'XXXX':
case 'XX':
// Hours and minutes without `:` delimiter
return formatTimezone(timezoneOffset);
// Hours, minutes and optional seconds with `:` delimiter
// Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
// so this token always has the same output as `XXX`
case 'XXXXX':
case 'XXX': // Hours and minutes with `:` delimiter
default:
return formatTimezone(timezoneOffset, ':');
}
},
// Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)
x: function x(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
switch (token) {
// Hours and optional minutes
case 'x':
return formatTimezoneWithOptionalMinutes(timezoneOffset);
// Hours, minutes and optional seconds without `:` delimiter
// Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
// so this token always has the same output as `xx`
case 'xxxx':
case 'xx':
// Hours and minutes without `:` delimiter
return formatTimezone(timezoneOffset);
// Hours, minutes and optional seconds with `:` delimiter
// Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
// so this token always has the same output as `xxx`
case 'xxxxx':
case 'xxx': // Hours and minutes with `:` delimiter
default:
return formatTimezone(timezoneOffset, ':');
}
},
// Timezone (GMT)
O: function O(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
switch (token) {
// Short
case 'O':
case 'OO':
case 'OOO':
return 'GMT' + formatTimezoneShort(timezoneOffset, ':');
// Long
case 'OOOO':
default:
return 'GMT' + formatTimezone(timezoneOffset, ':');
}
},
// Timezone (specific non-location)
z: function z(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
switch (token) {
// Short
case 'z':
case 'zz':
case 'zzz':
return 'GMT' + formatTimezoneShort(timezoneOffset, ':');
// Long
case 'zzzz':
default:
return 'GMT' + formatTimezone(timezoneOffset, ':');
}
},
// Seconds timestamp
t: function t(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timestamp = Math.floor(originalDate.getTime() / 1000);
return addLeadingZeros(timestamp, token.length);
},
// Milliseconds timestamp
T: function T(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timestamp = originalDate.getTime();
return addLeadingZeros(timestamp, token.length);
}
};
function formatTimezoneShort(offset, dirtyDelimiter) {
var sign = offset > 0 ? '-' : '+';
var absOffset = Math.abs(offset);
var hours = Math.floor(absOffset / 60);
var minutes = absOffset % 60;
if (minutes === 0) {
return sign + String(hours);
}
var delimiter = dirtyDelimiter || '';
return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2);
}
function formatTimezoneWithOptionalMinutes(offset, dirtyDelimiter) {
if (offset % 60 === 0) {
var sign = offset > 0 ? '-' : '+';
return sign + addLeadingZeros(Math.abs(offset) / 60, 2);
}
return formatTimezone(offset, dirtyDelimiter);
}
function formatTimezone(offset, dirtyDelimiter) {
var delimiter = dirtyDelimiter || '';
var sign = offset > 0 ? '-' : '+';
var absOffset = Math.abs(offset);
var hours = addLeadingZeros(Math.floor(absOffset / 60), 2);
var minutes = addLeadingZeros(absOffset % 60, 2);
return sign + hours + delimiter + minutes;
}
/* harmony default export */ var format_formatters = (formatters_formatters);
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/format/longFormatters/index.js
var dateLongFormatter = function dateLongFormatter(pattern, formatLong) {
switch (pattern) {
case 'P':
return formatLong.date({
width: 'short'
});
case 'PP':
return formatLong.date({
width: 'medium'
});
case 'PPP':
return formatLong.date({
width: 'long'
});
case 'PPPP':
default:
return formatLong.date({
width: 'full'
});
}
};
var timeLongFormatter = function timeLongFormatter(pattern, formatLong) {
switch (pattern) {
case 'p':
return formatLong.time({
width: 'short'
});
case 'pp':
return formatLong.time({
width: 'medium'
});
case 'ppp':
return formatLong.time({
width: 'long'
});
case 'pppp':
default:
return formatLong.time({
width: 'full'
});
}
};
var dateTimeLongFormatter = function dateTimeLongFormatter(pattern, formatLong) {
var matchResult = pattern.match(/(P+)(p+)?/) || [];
var datePattern = matchResult[1];
var timePattern = matchResult[2];
if (!timePattern) {
return dateLongFormatter(pattern, formatLong);
}
var dateTimeFormat;
switch (datePattern) {
case 'P':
dateTimeFormat = formatLong.dateTime({
width: 'short'
});
break;
case 'PP':
dateTimeFormat = formatLong.dateTime({
width: 'medium'
});
break;
case 'PPP':
dateTimeFormat = formatLong.dateTime({
width: 'long'
});
break;
case 'PPPP':
default:
dateTimeFormat = formatLong.dateTime({
width: 'full'
});
break;
}
return dateTimeFormat.replace('{{date}}', dateLongFormatter(datePattern, formatLong)).replace('{{time}}', timeLongFormatter(timePattern, formatLong));
};
var longFormatters = {
p: timeLongFormatter,
P: dateTimeLongFormatter
};
/* harmony default export */ var format_longFormatters = (longFormatters);
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/getTimezoneOffsetInMilliseconds/index.js
/**
* Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds.
* They usually appear for dates that denote time before the timezones were introduced
* (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891
* and GMT+01:00:00 after that date)
*
* Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above,
* which would lead to incorrect calculations.
*
* This function returns the timezone offset in milliseconds that takes seconds in account.
*/
function getTimezoneOffsetInMilliseconds(date) {
var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()));
utcDate.setUTCFullYear(date.getFullYear());
return date.getTime() - utcDate.getTime();
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/protectedTokens/index.js
var protectedDayOfYearTokens = ['D', 'DD'];
var protectedWeekYearTokens = ['YY', 'YYYY'];
function isProtectedDayOfYearToken(token) {
return protectedDayOfYearTokens.indexOf(token) !== -1;
}
function isProtectedWeekYearToken(token) {
return protectedWeekYearTokens.indexOf(token) !== -1;
}
function throwProtectedError(token, format, input) {
if (token === 'YYYY') {
throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(format, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
} else if (token === 'YY') {
throw new RangeError("Use `yy` instead of `YY` (in `".concat(format, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
} else if (token === 'D') {
throw new RangeError("Use `d` instead of `D` (in `".concat(format, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
} else if (token === 'DD') {
throw new RangeError("Use `dd` instead of `DD` (in `".concat(format, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
}
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/locale/en-US/_lib/formatDistance/index.js
var formatDistanceLocale = {
lessThanXSeconds: {
one: 'less than a second',
other: 'less than {{count}} seconds'
},
xSeconds: {
one: '1 second',
other: '{{count}} seconds'
},
halfAMinute: 'half a minute',
lessThanXMinutes: {
one: 'less than a minute',
other: 'less than {{count}} minutes'
},
xMinutes: {
one: '1 minute',
other: '{{count}} minutes'
},
aboutXHours: {
one: 'about 1 hour',
other: 'about {{count}} hours'
},
xHours: {
one: '1 hour',
other: '{{count}} hours'
},
xDays: {
one: '1 day',
other: '{{count}} days'
},
aboutXWeeks: {
one: 'about 1 week',
other: 'about {{count}} weeks'
},
xWeeks: {
one: '1 week',
other: '{{count}} weeks'
},
aboutXMonths: {
one: 'about 1 month',
other: 'about {{count}} months'
},
xMonths: {
one: '1 month',
other: '{{count}} months'
},
aboutXYears: {
one: 'about 1 year',
other: 'about {{count}} years'
},
xYears: {
one: '1 year',
other: '{{count}} years'
},
overXYears: {
one: 'over 1 year',
other: 'over {{count}} years'
},
almostXYears: {
one: 'almost 1 year',
other: 'almost {{count}} years'
}
};
var formatDistance = function formatDistance(token, count, options) {
var result;
var tokenValue = formatDistanceLocale[token];
if (typeof tokenValue === 'string') {
result = tokenValue;
} else if (count === 1) {
result = tokenValue.one;
} else {
result = tokenValue.other.replace('{{count}}', count.toString());
}
if (options !== null && options !== void 0 && options.addSuffix) {
if (options.comparison && options.comparison > 0) {
return 'in ' + result;
} else {
return result + ' ago';
}
}
return result;
};
/* harmony default export */ var _lib_formatDistance = (formatDistance);
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/locale/_lib/buildFormatLongFn/index.js
function buildFormatLongFn(args) {
return function () {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
// TODO: Remove String()
var width = options.width ? String(options.width) : args.defaultWidth;
var format = args.formats[width] || args.formats[args.defaultWidth];
return format;
};
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/locale/en-US/_lib/formatLong/index.js
var dateFormats = {
full: 'EEEE, MMMM do, y',
long: 'MMMM do, y',
medium: 'MMM d, y',
short: 'MM/dd/yyyy'
};
var timeFormats = {
full: 'h:mm:ss a zzzz',
long: 'h:mm:ss a z',
medium: 'h:mm:ss a',
short: 'h:mm a'
};
var dateTimeFormats = {
full: "{{date}} 'at' {{time}}",
long: "{{date}} 'at' {{time}}",
medium: '{{date}}, {{time}}',
short: '{{date}}, {{time}}'
};
var formatLong = {
date: buildFormatLongFn({
formats: dateFormats,
defaultWidth: 'full'
}),
time: buildFormatLongFn({
formats: timeFormats,
defaultWidth: 'full'
}),
dateTime: buildFormatLongFn({
formats: dateTimeFormats,
defaultWidth: 'full'
})
};
/* harmony default export */ var _lib_formatLong = (formatLong);
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/locale/en-US/_lib/formatRelative/index.js
var formatRelativeLocale = {
lastWeek: "'last' eeee 'at' p",
yesterday: "'yesterday at' p",
today: "'today at' p",
tomorrow: "'tomorrow at' p",
nextWeek: "eeee 'at' p",
other: 'P'
};
var formatRelative = function formatRelative(token, _date, _baseDate, _options) {
return formatRelativeLocale[token];
};
/* harmony default export */ var _lib_formatRelative = (formatRelative);
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/locale/_lib/buildLocalizeFn/index.js
function buildLocalizeFn(args) {
return function (dirtyIndex, options) {
var context = options !== null && options !== void 0 && options.context ? String(options.context) : 'standalone';
var valuesArray;
if (context === 'formatting' && args.formattingValues) {
var defaultWidth = args.defaultFormattingWidth || args.defaultWidth;
var width = options !== null && options !== void 0 && options.width ? String(options.width) : defaultWidth;
valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth];
} else {
var _defaultWidth = args.defaultWidth;
var _width = options !== null && options !== void 0 && options.width ? String(options.width) : args.defaultWidth;
valuesArray = args.values[_width] || args.values[_defaultWidth];
}
var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex;
// @ts-ignore: For some reason TypeScript just don't want to match it, no matter how hard we try. I challenge you to try to remove it!
return valuesArray[index];
};
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/locale/en-US/_lib/localize/index.js
var eraValues = {
narrow: ['B', 'A'],
abbreviated: ['BC', 'AD'],
wide: ['Before Christ', 'Anno Domini']
};
var quarterValues = {
narrow: ['1', '2', '3', '4'],
abbreviated: ['Q1', 'Q2', 'Q3', 'Q4'],
wide: ['1st quarter', '2nd quarter', '3rd quarter', '4th quarter']
};
// Note: in English, the names of days of the week and months are capitalized.
// If you are making a new locale based on this one, check if the same is true for the language you're working on.
// Generally, formatted dates should look like they are in the middle of a sentence,
// e.g. in Spanish language the weekdays and months should be in the lowercase.
var monthValues = {
narrow: ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
abbreviated: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
wide: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
};
var dayValues = {
narrow: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
short: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
abbreviated: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
wide: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
};
var dayPeriodValues = {
narrow: {
am: 'a',
pm: 'p',
midnight: 'mi',
noon: 'n',
morning: 'morning',
afternoon: 'afternoon',
evening: 'evening',
night: 'night'
},
abbreviated: {
am: 'AM',
pm: 'PM',
midnight: 'midnight',
noon: 'noon',
morning: 'morning',
afternoon: 'afternoon',
evening: 'evening',
night: 'night'
},
wide: {
am: 'a.m.',
pm: 'p.m.',
midnight: 'midnight',
noon: 'noon',
morning: 'morning',
afternoon: 'afternoon',
evening: 'evening',
night: 'night'
}
};
var formattingDayPeriodValues = {
narrow: {
am: 'a',
pm: 'p',
midnight: 'mi',
noon: 'n',
morning: 'in the morning',
afternoon: 'in the afternoon',
evening: 'in the evening',
night: 'at night'
},
abbreviated: {
am: 'AM',
pm: 'PM',
midnight: 'midnight',
noon: 'noon',
morning: 'in the morning',
afternoon: 'in the afternoon',
evening: 'in the evening',
night: 'at night'
},
wide: {
am: 'a.m.',
pm: 'p.m.',
midnight: 'midnight',
noon: 'noon',
morning: 'in the morning',
afternoon: 'in the afternoon',
evening: 'in the evening',
night: 'at night'
}
};
var ordinalNumber = function ordinalNumber(dirtyNumber, _options) {
var number = Number(dirtyNumber);
// If ordinal numbers depend on context, for example,
// if they are different for different grammatical genders,
// use `options.unit`.
//
// `unit` can be 'year', 'quarter', 'month', 'week', 'date', 'dayOfYear',
// 'day', 'hour', 'minute', 'second'.
var rem100 = number % 100;
if (rem100 > 20 || rem100 < 10) {
switch (rem100 % 10) {
case 1:
return number + 'st';
case 2:
return number + 'nd';
case 3:
return number + 'rd';
}
}
return number + 'th';
};
var localize = {
ordinalNumber: ordinalNumber,
era: buildLocalizeFn({
values: eraValues,
defaultWidth: 'wide'
}),
quarter: buildLocalizeFn({
values: quarterValues,
defaultWidth: 'wide',
argumentCallback: function argumentCallback(quarter) {
return quarter - 1;
}
}),
month: buildLocalizeFn({
values: monthValues,
defaultWidth: 'wide'
}),
day: buildLocalizeFn({
values: dayValues,
defaultWidth: 'wide'
}),
dayPeriod: buildLocalizeFn({
values: dayPeriodValues,
defaultWidth: 'wide',
formattingValues: formattingDayPeriodValues,
defaultFormattingWidth: 'wide'
})
};
/* harmony default export */ var _lib_localize = (localize);
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/locale/_lib/buildMatchFn/index.js
function buildMatchFn(args) {
return function (string) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var width = options.width;
var matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth];
var matchResult = string.match(matchPattern);
if (!matchResult) {
return null;
}
var matchedString = matchResult[0];
var parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth];
var key = Array.isArray(parsePatterns) ? findIndex(parsePatterns, function (pattern) {
return pattern.test(matchedString);
}) : findKey(parsePatterns, function (pattern) {
return pattern.test(matchedString);
});
var value;
value = args.valueCallback ? args.valueCallback(key) : key;
value = options.valueCallback ? options.valueCallback(value) : value;
var rest = string.slice(matchedString.length);
return {
value: value,
rest: rest
};
};
}
function findKey(object, predicate) {
for (var key in object) {
if (object.hasOwnProperty(key) && predicate(object[key])) {
return key;
}
}
return undefined;
}
function findIndex(array, predicate) {
for (var key = 0; key < array.length; key++) {
if (predicate(array[key])) {
return key;
}
}
return undefined;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/locale/_lib/buildMatchPatternFn/index.js
function buildMatchPatternFn(args) {
return function (string) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var matchResult = string.match(args.matchPattern);
if (!matchResult) return null;
var matchedString = matchResult[0];
var parseResult = string.match(args.parsePattern);
if (!parseResult) return null;
var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0];
value = options.valueCallback ? options.valueCallback(value) : value;
var rest = string.slice(matchedString.length);
return {
value: value,
rest: rest
};
};
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/locale/en-US/_lib/match/index.js
var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i;
var parseOrdinalNumberPattern = /\d+/i;
var matchEraPatterns = {
narrow: /^(b|a)/i,
abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,
wide: /^(before christ|before common era|anno domini|common era)/i
};
var parseEraPatterns = {
any: [/^b/i, /^(a|c)/i]
};
var matchQuarterPatterns = {
narrow: /^[1234]/i,
abbreviated: /^q[1234]/i,
wide: /^[1234](th|st|nd|rd)? quarter/i
};
var parseQuarterPatterns = {
any: [/1/i, /2/i, /3/i, /4/i]
};
var matchMonthPatterns = {
narrow: /^[jfmasond]/i,
abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,
wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i
};
var parseMonthPatterns = {
narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i],
any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i]
};
var matchDayPatterns = {
narrow: /^[smtwf]/i,
short: /^(su|mo|tu|we|th|fr|sa)/i,
abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,
wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i
};
var parseDayPatterns = {
narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],
any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i]
};
var matchDayPeriodPatterns = {
narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,
any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i
};
var parseDayPeriodPatterns = {
any: {
am: /^a/i,
pm: /^p/i,
midnight: /^mi/i,
noon: /^no/i,
morning: /morning/i,
afternoon: /afternoon/i,
evening: /evening/i,
night: /night/i
}
};
var match_match = {
ordinalNumber: buildMatchPatternFn({
matchPattern: matchOrdinalNumberPattern,
parsePattern: parseOrdinalNumberPattern,
valueCallback: function valueCallback(value) {
return parseInt(value, 10);
}
}),
era: buildMatchFn({
matchPatterns: matchEraPatterns,
defaultMatchWidth: 'wide',
parsePatterns: parseEraPatterns,
defaultParseWidth: 'any'
}),
quarter: buildMatchFn({
matchPatterns: matchQuarterPatterns,
defaultMatchWidth: 'wide',
parsePatterns: parseQuarterPatterns,
defaultParseWidth: 'any',
valueCallback: function valueCallback(index) {
return index + 1;
}
}),
month: buildMatchFn({
matchPatterns: matchMonthPatterns,
defaultMatchWidth: 'wide',
parsePatterns: parseMonthPatterns,
defaultParseWidth: 'any'
}),
day: buildMatchFn({
matchPatterns: matchDayPatterns,
defaultMatchWidth: 'wide',
parsePatterns: parseDayPatterns,
defaultParseWidth: 'any'
}),
dayPeriod: buildMatchFn({
matchPatterns: matchDayPeriodPatterns,
defaultMatchWidth: 'any',
parsePatterns: parseDayPeriodPatterns,
defaultParseWidth: 'any'
})
};
/* harmony default export */ var _lib_match = (match_match);
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/locale/en-US/index.js
/**
* @type {Locale}
* @category Locales
* @summary English locale (United States).
* @language English
* @iso-639-2 eng
* @author Sasha Koss [@kossnocorp]{@link https://github.com/kossnocorp}
* @author Lesha Koss [@leshakoss]{@link https://github.com/leshakoss}
*/
var locale = {
code: 'en-US',
formatDistance: _lib_formatDistance,
formatLong: _lib_formatLong,
formatRelative: _lib_formatRelative,
localize: _lib_localize,
match: _lib_match,
options: {
weekStartsOn: 0 /* Sunday */,
firstWeekContainsDate: 1
}
};
/* harmony default export */ var en_US = (locale);
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/defaultLocale/index.js
/* harmony default export */ var defaultLocale = (en_US);
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/format/index.js
// This RegExp consists of three parts separated by `|`:
// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token
// (one of the certain letters followed by `o`)
// - (\w)\1* matches any sequences of the same letter
// - '' matches two quote characters in a row
// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),
// except a single quote symbol, which ends the sequence.
// Two quote characters do not end the sequence.
// If there is no matching single quote
// then the sequence will continue until the end of the string.
// - . matches any single character unmatched by previous parts of the RegExps
var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g;
// This RegExp catches symbols escaped by quotes, and also
// sequences of symbols P, p, and the combinations like `PPPPPPPppppp`
var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
var escapedStringRegExp = /^'([^]*?)'?$/;
var doubleQuoteRegExp = /''/g;
var unescapedLatinCharacterRegExp = /[a-zA-Z]/;
/**
* @name format
* @category Common Helpers
* @summary Format the date.
*
* @description
* Return the formatted date string in the given format. The result may vary by locale.
*
* > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries.
* > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
*
* The characters wrapped between two single quotes characters (') are escaped.
* Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.
* (see the last example)
*
* Format of the string is based on Unicode Technical Standard #35:
* https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
* with a few additions (see note 7 below the table).
*
* Accepted patterns:
* | Unit | Pattern | Result examples | Notes |
* |---------------------------------|---------|-----------------------------------|-------|
* | Era | G..GGG | AD, BC | |
* | | GGGG | Anno Domini, Before Christ | 2 |
* | | GGGGG | A, B | |
* | Calendar year | y | 44, 1, 1900, 2017 | 5 |
* | | yo | 44th, 1st, 0th, 17th | 5,7 |
* | | yy | 44, 01, 00, 17 | 5 |
* | | yyy | 044, 001, 1900, 2017 | 5 |
* | | yyyy | 0044, 0001, 1900, 2017 | 5 |
* | | yyyyy | ... | 3,5 |
* | Local week-numbering year | Y | 44, 1, 1900, 2017 | 5 |
* | | Yo | 44th, 1st, 1900th, 2017th | 5,7 |
* | | YY | 44, 01, 00, 17 | 5,8 |
* | | YYY | 044, 001, 1900, 2017 | 5 |
* | | YYYY | 0044, 0001, 1900, 2017 | 5,8 |
* | | YYYYY | ... | 3,5 |
* | ISO week-numbering year | R | -43, 0, 1, 1900, 2017 | 5,7 |
* | | RR | -43, 00, 01, 1900, 2017 | 5,7 |
* | | RRR | -043, 000, 001, 1900, 2017 | 5,7 |
* | | RRRR | -0043, 0000, 0001, 1900, 2017 | 5,7 |
* | | RRRRR | ... | 3,5,7 |
* | Extended year | u | -43, 0, 1, 1900, 2017 | 5 |
* | | uu | -43, 01, 1900, 2017 | 5 |
* | | uuu | -043, 001, 1900, 2017 | 5 |
* | | uuuu | -0043, 0001, 1900, 2017 | 5 |
* | | uuuuu | ... | 3,5 |
* | Quarter (formatting) | Q | 1, 2, 3, 4 | |
* | | Qo | 1st, 2nd, 3rd, 4th | 7 |
* | | QQ | 01, 02, 03, 04 | |
* | | QQQ | Q1, Q2, Q3, Q4 | |
* | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |
* | | QQQQQ | 1, 2, 3, 4 | 4 |
* | Quarter (stand-alone) | q | 1, 2, 3, 4 | |
* | | qo | 1st, 2nd, 3rd, 4th | 7 |
* | | qq | 01, 02, 03, 04 | |
* | | qqq | Q1, Q2, Q3, Q4 | |
* | | qqqq | 1st quarter, 2nd quarter, ... | 2 |
* | | qqqqq | 1, 2, 3, 4 | 4 |
* | Month (formatting) | M | 1, 2, ..., 12 | |
* | | Mo | 1st, 2nd, ..., 12th | 7 |
* | | MM | 01, 02, ..., 12 | |
* | | MMM | Jan, Feb, ..., Dec | |
* | | MMMM | January, February, ..., December | 2 |
* | | MMMMM | J, F, ..., D | |
* | Month (stand-alone) | L | 1, 2, ..., 12 | |
* | | Lo | 1st, 2nd, ..., 12th | 7 |
* | | LL | 01, 02, ..., 12 | |
* | | LLL | Jan, Feb, ..., Dec | |
* | | LLLL | January, February, ..., December | 2 |
* | | LLLLL | J, F, ..., D | |
* | Local week of year | w | 1, 2, ..., 53 | |
* | | wo | 1st, 2nd, ..., 53th | 7 |
* | | ww | 01, 02, ..., 53 | |
* | ISO week of year | I | 1, 2, ..., 53 | 7 |
* | | Io | 1st, 2nd, ..., 53th | 7 |
* | | II | 01, 02, ..., 53 | 7 |
* | Day of month | d | 1, 2, ..., 31 | |
* | | do | 1st, 2nd, ..., 31st | 7 |
* | | dd | 01, 02, ..., 31 | |
* | Day of year | D | 1, 2, ..., 365, 366 | 9 |
* | | Do | 1st, 2nd, ..., 365th, 366th | 7 |
* | | DD | 01, 02, ..., 365, 366 | 9 |
* | | DDD | 001, 002, ..., 365, 366 | |
* | | DDDD | ... | 3 |
* | Day of week (formatting) | E..EEE | Mon, Tue, Wed, ..., Sun | |
* | | EEEE | Monday, Tuesday, ..., Sunday | 2 |
* | | EEEEE | M, T, W, T, F, S, S | |
* | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | |
* | ISO day of week (formatting) | i | 1, 2, 3, ..., 7 | 7 |
* | | io | 1st, 2nd, ..., 7th | 7 |
* | | ii | 01, 02, ..., 07 | 7 |
* | | iii | Mon, Tue, Wed, ..., Sun | 7 |
* | | iiii | Monday, Tuesday, ..., Sunday | 2,7 |
* | | iiiii | M, T, W, T, F, S, S | 7 |
* | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 7 |
* | Local day of week (formatting) | e | 2, 3, 4, ..., 1 | |
* | | eo | 2nd, 3rd, ..., 1st | 7 |
* | | ee | 02, 03, ..., 01 | |
* | | eee | Mon, Tue, Wed, ..., Sun | |
* | | eeee | Monday, Tuesday, ..., Sunday | 2 |
* | | eeeee | M, T, W, T, F, S, S | |
* | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | |
* | Local day of week (stand-alone) | c | 2, 3, 4, ..., 1 | |
* | | co | 2nd, 3rd, ..., 1st | 7 |
* | | cc | 02, 03, ..., 01 | |
* | | ccc | Mon, Tue, Wed, ..., Sun | |
* | | cccc | Monday, Tuesday, ..., Sunday | 2 |
* | | ccccc | M, T, W, T, F, S, S | |
* | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | |
* | AM, PM | a..aa | AM, PM | |
* | | aaa | am, pm | |
* | | aaaa | a.m., p.m. | 2 |
* | | aaaaa | a, p | |
* | AM, PM, noon, midnight | b..bb | AM, PM, noon, midnight | |
* | | bbb | am, pm, noon, midnight | |
* | | bbbb | a.m., p.m., noon, midnight | 2 |
* | | bbbbb | a, p, n, mi | |
* | Flexible day period | B..BBB | at night, in the morning, ... | |
* | | BBBB | at night, in the morning, ... | 2 |
* | | BBBBB | at night, in the morning, ... | |
* | Hour [1-12] | h | 1, 2, ..., 11, 12 | |
* | | ho | 1st, 2nd, ..., 11th, 12th | 7 |
* | | hh | 01, 02, ..., 11, 12 | |
* | Hour [0-23] | H | 0, 1, 2, ..., 23 | |
* | | Ho | 0th, 1st, 2nd, ..., 23rd | 7 |
* | | HH | 00, 01, 02, ..., 23 | |
* | Hour [0-11] | K | 1, 2, ..., 11, 0 | |
* | | Ko | 1st, 2nd, ..., 11th, 0th | 7 |
* | | KK | 01, 02, ..., 11, 00 | |
* | Hour [1-24] | k | 24, 1, 2, ..., 23 | |
* | | ko | 24th, 1st, 2nd, ..., 23rd | 7 |
* | | kk | 24, 01, 02, ..., 23 | |
* | Minute | m | 0, 1, ..., 59 | |
* | | mo | 0th, 1st, ..., 59th | 7 |
* | | mm | 00, 01, ..., 59 | |
* | Second | s | 0, 1, ..., 59 | |
* | | so | 0th, 1st, ..., 59th | 7 |
* | | ss | 00, 01, ..., 59 | |
* | Fraction of second | S | 0, 1, ..., 9 | |
* | | SS | 00, 01, ..., 99 | |
* | | SSS | 000, 001, ..., 999 | |
* | | SSSS | ... | 3 |
* | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z | |
* | | XX | -0800, +0530, Z | |
* | | XXX | -08:00, +05:30, Z | |
* | | XXXX | -0800, +0530, Z, +123456 | 2 |
* | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |
* | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 | |
* | | xx | -0800, +0530, +0000 | |
* | | xxx | -08:00, +05:30, +00:00 | 2 |
* | | xxxx | -0800, +0530, +0000, +123456 | |
* | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |
* | Timezone (GMT) | O...OOO | GMT-8, GMT+5:30, GMT+0 | |
* | | OOOO | GMT-08:00, GMT+05:30, GMT+00:00 | 2 |
* | Timezone (specific non-locat.) | z...zzz | GMT-8, GMT+5:30, GMT+0 | 6 |
* | | zzzz | GMT-08:00, GMT+05:30, GMT+00:00 | 2,6 |
* | Seconds timestamp | t | 512969520 | 7 |
* | | tt | ... | 3,7 |
* | Milliseconds timestamp | T | 512969520900 | 7 |
* | | TT | ... | 3,7 |
* | Long localized date | P | 04/29/1453 | 7 |
* | | PP | Apr 29, 1453 | 7 |
* | | PPP | April 29th, 1453 | 7 |
* | | PPPP | Friday, April 29th, 1453 | 2,7 |
* | Long localized time | p | 12:00 AM | 7 |
* | | pp | 12:00:00 AM | 7 |
* | | ppp | 12:00:00 AM GMT+2 | 7 |
* | | pppp | 12:00:00 AM GMT+02:00 | 2,7 |
* | Combination of date and time | Pp | 04/29/1453, 12:00 AM | 7 |
* | | PPpp | Apr 29, 1453, 12:00:00 AM | 7 |
* | | PPPppp | April 29th, 1453 at ... | 7 |
* | | PPPPpppp| Friday, April 29th, 1453 at ... | 2,7 |
* Notes:
* 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale
* are the same as "stand-alone" units, but are different in some languages.
* "Formatting" units are declined according to the rules of the language
* in the context of a date. "Stand-alone" units are always nominative singular:
*
* `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`
*
* `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`
*
* 2. Any sequence of the identical letters is a pattern, unless it is escaped by
* the single quote characters (see below).
* If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`)
* the output will be the same as default pattern for this unit, usually
* the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units
* are marked with "2" in the last column of the table.
*
* `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'`
*
* `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'`
*
* `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'`
*
* `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'`
*
* `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'`
*
* 3. Some patterns could be unlimited length (such as `yyyyyyyy`).
* The output will be padded with zeros to match the length of the pattern.
*
* `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'`
*
* 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.
* These tokens represent the shortest form of the quarter.
*
* 5. The main difference between `y` and `u` patterns are B.C. years:
*
* | Year | `y` | `u` |
* |------|-----|-----|
* | AC 1 | 1 | 1 |
* | BC 1 | 1 | 0 |
* | BC 2 | 2 | -1 |
*
* Also `yy` always returns the last two digits of a year,
* while `uu` pads single digit years to 2 characters and returns other years unchanged:
*
* | Year | `yy` | `uu` |
* |------|------|------|
* | 1 | 01 | 01 |
* | 14 | 14 | 14 |
* | 376 | 76 | 376 |
* | 1453 | 53 | 1453 |
*
* The same difference is true for local and ISO week-numbering years (`Y` and `R`),
* except local week-numbering years are dependent on `options.weekStartsOn`
* and `options.firstWeekContainsDate` (compare [getISOWeekYear]{@link https://date-fns.org/docs/getISOWeekYear}
* and [getWeekYear]{@link https://date-fns.org/docs/getWeekYear}).
*
* 6. Specific non-location timezones are currently unavailable in `date-fns`,
* so right now these tokens fall back to GMT timezones.
*
* 7. These patterns are not in the Unicode Technical Standard #35:
* - `i`: ISO day of week
* - `I`: ISO week of year
* - `R`: ISO week-numbering year
* - `t`: seconds timestamp
* - `T`: milliseconds timestamp
* - `o`: ordinal number modifier
* - `P`: long localized date
* - `p`: long localized time
*
* 8. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.
* You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
*
* 9. `D` and `DD` tokens represent days of the year but they are often confused with days of the month.
* You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
*
* @param {Date|Number} date - the original date
* @param {String} format - the string of tokens
* @param {Object} [options] - an object with options.
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @param {Number} [options.firstWeekContainsDate=1] - the day of January, which is
* @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`;
* see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
* @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`;
* see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
* @returns {String} the formatted date string
* @throws {TypeError} 2 arguments required
* @throws {RangeError} `date` must not be Invalid Date
* @throws {RangeError} `options.locale` must contain `localize` property
* @throws {RangeError} `options.locale` must contain `formatLong` property
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
* @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7
* @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
* @throws {RangeError} use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
* @throws {RangeError} use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
* @throws {RangeError} use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
* @throws {RangeError} format string contains an unescaped latin alphabet character
*
* @example
* // Represent 11 February 2014 in middle-endian format:
* const result = format(new Date(2014, 1, 11), 'MM/dd/yyyy')
* //=> '02/11/2014'
*
* @example
* // Represent 2 July 2014 in Esperanto:
* import { eoLocale } from 'date-fns/locale/eo'
* const result = format(new Date(2014, 6, 2), "do 'de' MMMM yyyy", {
* locale: eoLocale
* })
* //=> '2-a de julio 2014'
*
* @example
* // Escape string by single quote characters:
* const result = format(new Date(2014, 6, 2, 15), "h 'o''clock'")
* //=> "3 o'clock"
*/
function format(dirtyDate, dirtyFormatStr, options) {
var _ref, _options$locale, _ref2, _ref3, _ref4, _options$firstWeekCon, _options$locale2, _options$locale2$opti, _defaultOptions$local, _defaultOptions$local2, _ref5, _ref6, _ref7, _options$weekStartsOn, _options$locale3, _options$locale3$opti, _defaultOptions$local3, _defaultOptions$local4;
requiredArgs(2, arguments);
var formatStr = String(dirtyFormatStr);
var defaultOptions = defaultOptions_getDefaultOptions();
var locale = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions.locale) !== null && _ref !== void 0 ? _ref : defaultLocale;
var firstWeekContainsDate = toInteger((_ref2 = (_ref3 = (_ref4 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale2 = options.locale) === null || _options$locale2 === void 0 ? void 0 : (_options$locale2$opti = _options$locale2.options) === null || _options$locale2$opti === void 0 ? void 0 : _options$locale2$opti.firstWeekContainsDate) !== null && _ref4 !== void 0 ? _ref4 : defaultOptions.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : 1);
// Test if weekStartsOn is between 1 and 7 _and_ is not NaN
if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
}
var weekStartsOn = toInteger((_ref5 = (_ref6 = (_ref7 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale3 = options.locale) === null || _options$locale3 === void 0 ? void 0 : (_options$locale3$opti = _options$locale3.options) === null || _options$locale3$opti === void 0 ? void 0 : _options$locale3$opti.weekStartsOn) !== null && _ref7 !== void 0 ? _ref7 : defaultOptions.weekStartsOn) !== null && _ref6 !== void 0 ? _ref6 : (_defaultOptions$local3 = defaultOptions.locale) === null || _defaultOptions$local3 === void 0 ? void 0 : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 ? void 0 : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 ? _ref5 : 0);
// Test if weekStartsOn is between 0 and 6 _and_ is not NaN
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
}
if (!locale.localize) {
throw new RangeError('locale must contain localize property');
}
if (!locale.formatLong) {
throw new RangeError('locale must contain formatLong property');
}
var originalDate = toDate_toDate(dirtyDate);
if (!isValid(originalDate)) {
throw new RangeError('Invalid time value');
}
// Convert the date in system timezone to the same date in UTC+00:00 timezone.
// This ensures that when UTC functions will be implemented, locales will be compatible with them.
// See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/376
var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate);
var utcDate = subMilliseconds(originalDate, timezoneOffset);
var formatterOptions = {
firstWeekContainsDate: firstWeekContainsDate,
weekStartsOn: weekStartsOn,
locale: locale,
_originalDate: originalDate
};
var result = formatStr.match(longFormattingTokensRegExp).map(function (substring) {
var firstCharacter = substring[0];
if (firstCharacter === 'p' || firstCharacter === 'P') {
var longFormatter = format_longFormatters[firstCharacter];
return longFormatter(substring, locale.formatLong);
}
return substring;
}).join('').match(formattingTokensRegExp).map(function (substring) {
// Replace two single quote characters with one single quote character
if (substring === "''") {
return "'";
}
var firstCharacter = substring[0];
if (firstCharacter === "'") {
return cleanEscapedString(substring);
}
var formatter = format_formatters[firstCharacter];
if (formatter) {
if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && isProtectedWeekYearToken(substring)) {
throwProtectedError(substring, dirtyFormatStr, String(dirtyDate));
}
if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && isProtectedDayOfYearToken(substring)) {
throwProtectedError(substring, dirtyFormatStr, String(dirtyDate));
}
return formatter(utcDate, substring, locale.localize, formatterOptions);
}
if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`');
}
return substring;
}).join('');
return result;
}
function cleanEscapedString(input) {
var matched = input.match(escapedStringRegExp);
if (!matched) {
return input;
}
return matched[1].replace(doubleQuoteRegExp, "'");
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/isSameMonth/index.js
/**
* @name isSameMonth
* @category Month Helpers
* @summary Are the given dates in the same month (and year)?
*
* @description
* Are the given dates in the same month (and year)?
*
* @param {Date|Number} dateLeft - the first date to check
* @param {Date|Number} dateRight - the second date to check
* @returns {Boolean} the dates are in the same month (and year)
* @throws {TypeError} 2 arguments required
*
* @example
* // Are 2 September 2014 and 25 September 2014 in the same month?
* const result = isSameMonth(new Date(2014, 8, 2), new Date(2014, 8, 25))
* //=> true
*
* @example
* // Are 2 September 2014 and 25 September 2015 in the same month?
* const result = isSameMonth(new Date(2014, 8, 2), new Date(2015, 8, 25))
* //=> false
*/
function isSameMonth(dirtyDateLeft, dirtyDateRight) {
requiredArgs(2, arguments);
var dateLeft = toDate_toDate(dirtyDateLeft);
var dateRight = toDate_toDate(dirtyDateRight);
return dateLeft.getFullYear() === dateRight.getFullYear() && dateLeft.getMonth() === dateRight.getMonth();
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/isEqual/index.js
/**
* @name isEqual
* @category Common Helpers
* @summary Are the given dates equal?
*
* @description
* Are the given dates equal?
*
* @param {Date|Number} dateLeft - the first date to compare
* @param {Date|Number} dateRight - the second date to compare
* @returns {Boolean} the dates are equal
* @throws {TypeError} 2 arguments required
*
* @example
* // Are 2 July 2014 06:30:45.000 and 2 July 2014 06:30:45.500 equal?
* const result = isEqual(
* new Date(2014, 6, 2, 6, 30, 45, 0),
* new Date(2014, 6, 2, 6, 30, 45, 500)
* )
* //=> false
*/
function isEqual_isEqual(dirtyLeftDate, dirtyRightDate) {
requiredArgs(2, arguments);
var dateLeft = toDate_toDate(dirtyLeftDate);
var dateRight = toDate_toDate(dirtyRightDate);
return dateLeft.getTime() === dateRight.getTime();
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/isSameDay/index.js
/**
* @name isSameDay
* @category Day Helpers
* @summary Are the given dates in the same day (and year and month)?
*
* @description
* Are the given dates in the same day (and year and month)?
*
* @param {Date|Number} dateLeft - the first date to check
* @param {Date|Number} dateRight - the second date to check
* @returns {Boolean} the dates are in the same day (and year and month)
* @throws {TypeError} 2 arguments required
*
* @example
* // Are 4 September 06:00:00 and 4 September 18:00:00 in the same day?
* const result = isSameDay(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 4, 18, 0))
* //=> true
*
* @example
* // Are 4 September and 4 October in the same day?
* const result = isSameDay(new Date(2014, 8, 4), new Date(2014, 9, 4))
* //=> false
*
* @example
* // Are 4 September, 2014 and 4 September, 2015 in the same day?
* const result = isSameDay(new Date(2014, 8, 4), new Date(2015, 8, 4))
* //=> false
*/
function isSameDay(dirtyDateLeft, dirtyDateRight) {
requiredArgs(2, arguments);
var dateLeftStartOfDay = startOfDay_startOfDay(dirtyDateLeft);
var dateRightStartOfDay = startOfDay_startOfDay(dirtyDateRight);
return dateLeftStartOfDay.getTime() === dateRightStartOfDay.getTime();
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/addDays/index.js
/**
* @name addDays
* @category Day Helpers
* @summary Add the specified number of days to the given date.
*
* @description
* Add the specified number of days to the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of days to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} - the new date with the days added
* @throws {TypeError} - 2 arguments required
*
* @example
* // Add 10 days to 1 September 2014:
* const result = addDays(new Date(2014, 8, 1), 10)
* //=> Thu Sep 11 2014 00:00:00
*/
function addDays_addDays(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var date = toDate_toDate(dirtyDate);
var amount = toInteger(dirtyAmount);
if (isNaN(amount)) {
return new Date(NaN);
}
if (!amount) {
// If 0 days, no-op to avoid changing times in the hour before end of DST
return date;
}
date.setDate(date.getDate() + amount);
return date;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/addWeeks/index.js
/**
* @name addWeeks
* @category Week Helpers
* @summary Add the specified number of weeks to the given date.
*
* @description
* Add the specified number of week to the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of weeks to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the weeks added
* @throws {TypeError} 2 arguments required
*
* @example
* // Add 4 weeks to 1 September 2014:
* const result = addWeeks(new Date(2014, 8, 1), 4)
* //=> Mon Sep 29 2014 00:00:00
*/
function addWeeks_addWeeks(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var amount = toInteger(dirtyAmount);
var days = amount * 7;
return addDays_addDays(dirtyDate, days);
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/subWeeks/index.js
/**
* @name subWeeks
* @category Week Helpers
* @summary Subtract the specified number of weeks from the given date.
*
* @description
* Subtract the specified number of weeks from the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} amount - the amount of weeks to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
* @returns {Date} the new date with the weeks subtracted
* @throws {TypeError} 2 arguments required
*
* @example
* // Subtract 4 weeks from 1 September 2014:
* const result = subWeeks(new Date(2014, 8, 1), 4)
* //=> Mon Aug 04 2014 00:00:00
*/
function subWeeks(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var amount = toInteger(dirtyAmount);
return addWeeks_addWeeks(dirtyDate, -amount);
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/startOfWeek/index.js
/**
* @name startOfWeek
* @category Week Helpers
* @summary Return the start of a week for the given date.
*
* @description
* Return the start of a week for the given date.
* The result will be in the local timezone.
*
* @param {Date|Number} date - the original date
* @param {Object} [options] - an object with options.
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @returns {Date} the start of a week
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
*
* @example
* // The start of a week for 2 September 2014 11:55:00:
* const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0))
* //=> Sun Aug 31 2014 00:00:00
*
* @example
* // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00:
* const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })
* //=> Mon Sep 01 2014 00:00:00
*/
function startOfWeek_startOfWeek(dirtyDate, options) {
var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
requiredArgs(1, arguments);
var defaultOptions = defaultOptions_getDefaultOptions();
var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0);
// Test if weekStartsOn is between 0 and 6 _and_ is not NaN
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
}
var date = toDate_toDate(dirtyDate);
var day = date.getDay();
var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
date.setDate(date.getDate() - diff);
date.setHours(0, 0, 0, 0);
return date;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/endOfWeek/index.js
/**
* @name endOfWeek
* @category Week Helpers
* @summary Return the end of a week for the given date.
*
* @description
* Return the end of a week for the given date.
* The result will be in the local timezone.
*
* @param {Date|Number} date - the original date
* @param {Object} [options] - an object with options.
* @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
* @returns {Date} the end of a week
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
*
* @example
* // The end of a week for 2 September 2014 11:55:00:
* const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0))
* //=> Sat Sep 06 2014 23:59:59.999
*
* @example
* // If the week starts on Monday, the end of the week for 2 September 2014 11:55:00:
* const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })
* //=> Sun Sep 07 2014 23:59:59.999
*/
function endOfWeek_endOfWeek(dirtyDate, options) {
var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
requiredArgs(1, arguments);
var defaultOptions = defaultOptions_getDefaultOptions();
var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0);
// Test if weekStartsOn is between 0 and 6 _and_ is not NaN
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
}
var date = toDate_toDate(dirtyDate);
var day = date.getDay();
var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn);
date.setDate(date.getDate() + diff);
date.setHours(23, 59, 59, 999);
return date;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/arrow-right.js
/**
* WordPress dependencies
*/
const arrowRight = (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: "m14.5 6.5-1 1 3.7 3.7H4v1.6h13.2l-3.7 3.7 1 1 5.6-5.5z"
}));
/* harmony default export */ var arrow_right = (arrowRight);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/arrow-left.js
/**
* WordPress dependencies
*/
const arrowLeft = (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: "M20 11.2H6.8l3.7-3.7-1-1L3.9 12l5.6 5.5 1-1-3.7-3.7H20z"
}));
/* harmony default export */ var arrow_left = (arrowLeft);
;// CONCATENATED MODULE: external ["wp","date"]
var external_wp_date_namespaceObject = window["wp"]["date"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/date-time/date/styles.js
function date_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const styles_Wrapper = createStyled("div", true ? {
target: "e105ri6r5"
} : 0)( true ? {
name: "1khn195",
styles: "box-sizing:border-box"
} : 0);
const Navigator = /*#__PURE__*/createStyled(h_stack_component, true ? {
target: "e105ri6r4"
} : 0)("margin-bottom:", space(4), ";" + ( true ? "" : 0));
const NavigatorHeading = /*#__PURE__*/createStyled(heading_component, true ? {
target: "e105ri6r3"
} : 0)("font-size:", config_values.fontSize, ";font-weight:", config_values.fontWeight, ";strong{font-weight:", config_values.fontWeightHeading, ";}" + ( true ? "" : 0));
const Calendar = createStyled("div", true ? {
target: "e105ri6r2"
} : 0)("column-gap:", space(2), ";display:grid;grid-template-columns:0.5fr repeat( 5, 1fr ) 0.5fr;justify-items:center;row-gap:", space(2), ";" + ( true ? "" : 0));
const DayOfWeek = createStyled("div", true ? {
target: "e105ri6r1"
} : 0)("color:", COLORS.gray[700], ";font-size:", config_values.fontSize, ";line-height:", config_values.fontLineHeightBase, ";&:nth-of-type( 1 ){justify-self:start;}&:nth-of-type( 7 ){justify-self:end;}" + ( true ? "" : 0));
const DayButton = /*#__PURE__*/createStyled(build_module_button, true ? {
shouldForwardProp: prop => !['column', 'isSelected', 'isToday', 'hasEvents'].includes(prop),
target: "e105ri6r0"
} : 0)("grid-column:", props => props.column, ";position:relative;justify-content:center;", props => props.column === 1 && `
justify-self: start;
`, " ", props => props.column === 7 && `
justify-self: end;
`, " ", props => props.disabled && `
pointer-events: none;
`, " &&&{border-radius:100%;height:", space(7), ";width:", space(7), ";", props => props.isSelected && `
background: ${COLORS.ui.theme};
color: ${COLORS.white};
`, " ", props => !props.isSelected && props.isToday && `
background: ${COLORS.gray[200]};
`, ";}", props => props.hasEvents && `
::before {
background: ${props.isSelected ? COLORS.white : COLORS.ui.theme};
border-radius: 2px;
bottom: 0;
content: " ";
height: 4px;
left: 50%;
margin-left: -2px;
position: absolute;
width: 4px;
}
`, ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/date-time/utils.js
/**
* External dependencies
*/
/**
* Like date-fn's toDate, but tries to guess the format when a string is
* given.
*
* @param input Value to turn into a date.
*/
function inputToDate(input) {
if (typeof input === 'string') {
return new Date(input);
}
return toDate_toDate(input);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/date-time/constants.js
const TIMEZONELESS_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/date-time/date/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* DatePicker is a React component that renders a calendar for date selection.
*
* ```jsx
* import { DatePicker } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyDatePicker = () => {
* const [ date, setDate ] = useState( new Date() );
*
* return (
* <DatePicker
* currentDate={ date }
* onChange={ ( newDate ) => setDate( newDate ) }
* />
* );
* };
* ```
*/
function DatePicker(_ref) {
let {
currentDate,
onChange,
events = [],
isInvalidDate,
onMonthPreviewed,
startOfWeek: weekStartsOn = 0
} = _ref;
const date = currentDate ? inputToDate(currentDate) : new Date();
const {
calendar,
viewing,
setSelected,
setViewing,
isSelected,
viewPreviousMonth,
viewNextMonth
} = useLilius({
selected: [startOfDay_startOfDay(date)],
viewing: startOfDay_startOfDay(date),
weekStartsOn
}); // Used to implement a roving tab index. Tracks the day that receives focus
// when the user tabs into the calendar.
const [focusable, setFocusable] = (0,external_wp_element_namespaceObject.useState)(startOfDay_startOfDay(date)); // Allows us to only programmatically focus() a day when focus was already
// within the calendar. This stops us stealing focus from e.g. a TimePicker
// input.
const [isFocusWithinCalendar, setIsFocusWithinCalendar] = (0,external_wp_element_namespaceObject.useState)(false); // Update internal state when currentDate prop changes.
const [prevCurrentDate, setPrevCurrentDate] = (0,external_wp_element_namespaceObject.useState)(currentDate);
if (currentDate !== prevCurrentDate) {
setPrevCurrentDate(currentDate);
setSelected([startOfDay_startOfDay(date)]);
setViewing(startOfDay_startOfDay(date));
setFocusable(startOfDay_startOfDay(date));
}
return (0,external_wp_element_namespaceObject.createElement)(styles_Wrapper, {
className: "components-datetime__date",
role: "application",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Calendar')
}, (0,external_wp_element_namespaceObject.createElement)(Navigator, null, (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
icon: (0,external_wp_i18n_namespaceObject.isRTL)() ? arrow_right : arrow_left,
variant: "tertiary",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('View previous month'),
onClick: () => {
viewPreviousMonth();
setFocusable(subMonths_subMonths(focusable, 1));
onMonthPreviewed === null || onMonthPreviewed === void 0 ? void 0 : onMonthPreviewed(format(subMonths_subMonths(viewing, 1), TIMEZONELESS_FORMAT));
}
}), (0,external_wp_element_namespaceObject.createElement)(NavigatorHeading, {
level: 3
}, (0,external_wp_element_namespaceObject.createElement)("strong", null, (0,external_wp_date_namespaceObject.dateI18n)('F', viewing, -viewing.getTimezoneOffset())), ' ', (0,external_wp_date_namespaceObject.dateI18n)('Y', viewing, -viewing.getTimezoneOffset())), (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
icon: (0,external_wp_i18n_namespaceObject.isRTL)() ? arrow_left : arrow_right,
variant: "tertiary",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('View next month'),
onClick: () => {
viewNextMonth();
setFocusable(addMonths_addMonths(focusable, 1));
onMonthPreviewed === null || onMonthPreviewed === void 0 ? void 0 : onMonthPreviewed(format(addMonths_addMonths(viewing, 1), TIMEZONELESS_FORMAT));
}
})), (0,external_wp_element_namespaceObject.createElement)(Calendar, {
onFocus: () => setIsFocusWithinCalendar(true),
onBlur: () => setIsFocusWithinCalendar(false)
}, calendar[0][0].map(day => (0,external_wp_element_namespaceObject.createElement)(DayOfWeek, {
key: day.toString()
}, (0,external_wp_date_namespaceObject.dateI18n)('D', day, -day.getTimezoneOffset()))), calendar[0].map(week => week.map((day, index) => {
if (!isSameMonth(day, viewing)) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(date_Day, {
key: day.toString(),
day: day,
column: index + 1,
isSelected: isSelected(day),
isFocusable: isEqual_isEqual(day, focusable),
isFocusAllowed: isFocusWithinCalendar,
isToday: isSameDay(day, new Date()),
isInvalid: isInvalidDate ? isInvalidDate(day) : false,
numEvents: events.filter(event => isSameDay(event.date, day)).length,
onClick: () => {
setSelected([day]);
setFocusable(day);
onChange === null || onChange === void 0 ? void 0 : onChange(format( // Don't change the selected date's time fields.
new Date(day.getFullYear(), day.getMonth(), day.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()), TIMEZONELESS_FORMAT));
},
onKeyDown: event => {
let nextFocusable;
if (event.key === 'ArrowLeft') {
nextFocusable = addDays_addDays(day, (0,external_wp_i18n_namespaceObject.isRTL)() ? 1 : -1);
}
if (event.key === 'ArrowRight') {
nextFocusable = addDays_addDays(day, (0,external_wp_i18n_namespaceObject.isRTL)() ? -1 : 1);
}
if (event.key === 'ArrowUp') {
nextFocusable = subWeeks(day, 1);
}
if (event.key === 'ArrowDown') {
nextFocusable = addWeeks_addWeeks(day, 1);
}
if (event.key === 'PageUp') {
nextFocusable = subMonths_subMonths(day, 1);
}
if (event.key === 'PageDown') {
nextFocusable = addMonths_addMonths(day, 1);
}
if (event.key === 'Home') {
nextFocusable = startOfWeek_startOfWeek(day);
}
if (event.key === 'End') {
nextFocusable = startOfDay_startOfDay(endOfWeek_endOfWeek(day));
}
if (nextFocusable) {
event.preventDefault();
setFocusable(nextFocusable);
if (!isSameMonth(nextFocusable, viewing)) {
setViewing(nextFocusable);
onMonthPreviewed === null || onMonthPreviewed === void 0 ? void 0 : onMonthPreviewed(format(nextFocusable, TIMEZONELESS_FORMAT));
}
}
}
});
}))));
}
function date_Day(_ref2) {
let {
day,
column,
isSelected,
isFocusable,
isFocusAllowed,
isToday,
isInvalid,
numEvents,
onClick,
onKeyDown
} = _ref2;
const ref = (0,external_wp_element_namespaceObject.useRef)(); // Focus the day when it becomes focusable, e.g. because an arrow key is
// pressed. Only do this if focus is allowed - this stops us stealing focus
// from e.g. a TimePicker input.
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (ref.current && isFocusable && isFocusAllowed) {
ref.current.focus();
} // isFocusAllowed is not a dep as there is no point calling focus() on
// an already focused element.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isFocusable]);
return (0,external_wp_element_namespaceObject.createElement)(DayButton, {
ref: ref,
className: "components-datetime__date__day" // Unused, for backwards compatibility.
,
disabled: isInvalid,
tabIndex: isFocusable ? 0 : -1,
"aria-label": getDayLabel(day, isSelected, numEvents),
column: column,
isSelected: isSelected,
isToday: isToday,
hasEvents: numEvents > 0,
onClick: onClick,
onKeyDown: onKeyDown
}, (0,external_wp_date_namespaceObject.dateI18n)('j', day, -day.getTimezoneOffset()));
}
function getDayLabel(date, isSelected, numEvents) {
const {
formats
} = (0,external_wp_date_namespaceObject.getSettings)();
const localizedDate = (0,external_wp_date_namespaceObject.dateI18n)(formats.date, date, -date.getTimezoneOffset());
if (isSelected && numEvents > 0) {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: 1: The calendar date. 2: Number of events on the calendar date.
(0,external_wp_i18n_namespaceObject._n)('%1$s. Selected. There is %2$d event', '%1$s. Selected. There are %2$d events', numEvents), localizedDate, numEvents);
} else if (isSelected) {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The calendar date.
(0,external_wp_i18n_namespaceObject.__)('%1$s. Selected'), localizedDate);
} else if (numEvents > 0) {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: 1: The calendar date. 2: Number of events on the calendar date.
(0,external_wp_i18n_namespaceObject._n)('%1$s. There is %2$d event', '%1$s. There are %2$d events', numEvents), localizedDate, numEvents);
}
return localizedDate;
}
/* harmony default export */ var date = (DatePicker);
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/startOfMinute/index.js
/**
* @name startOfMinute
* @category Minute Helpers
* @summary Return the start of a minute for the given date.
*
* @description
* Return the start of a minute for the given date.
* The result will be in the local timezone.
*
* @param {Date|Number} date - the original date
* @returns {Date} the start of a minute
* @throws {TypeError} 1 argument required
*
* @example
* // The start of a minute for 1 December 2014 22:15:45.400:
* const result = startOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400))
* //=> Mon Dec 01 2014 22:15:00
*/
function startOfMinute(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate_toDate(dirtyDate);
date.setSeconds(0, 0);
return date;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/getDaysInMonth/index.js
/**
* @name getDaysInMonth
* @category Month Helpers
* @summary Get the number of days in a month of the given date.
*
* @description
* Get the number of days in a month of the given date.
*
* @param {Date|Number} date - the given date
* @returns {Number} the number of days in a month
* @throws {TypeError} 1 argument required
*
* @example
* // How many days are in February 2000?
* const result = getDaysInMonth(new Date(2000, 1))
* //=> 29
*/
function getDaysInMonth_getDaysInMonth(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate_toDate(dirtyDate);
var year = date.getFullYear();
var monthIndex = date.getMonth();
var lastDayOfMonth = new Date(0);
lastDayOfMonth.setFullYear(year, monthIndex + 1, 0);
lastDayOfMonth.setHours(0, 0, 0, 0);
return lastDayOfMonth.getDate();
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/setMonth/index.js
/**
* @name setMonth
* @category Month Helpers
* @summary Set the month to the given date.
*
* @description
* Set the month to the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} month - the month of the new date
* @returns {Date} the new date with the month set
* @throws {TypeError} 2 arguments required
*
* @example
* // Set February to 1 September 2014:
* const result = setMonth(new Date(2014, 8, 1), 1)
* //=> Sat Feb 01 2014 00:00:00
*/
function setMonth_setMonth(dirtyDate, dirtyMonth) {
requiredArgs(2, arguments);
var date = toDate_toDate(dirtyDate);
var month = toInteger(dirtyMonth);
var year = date.getFullYear();
var day = date.getDate();
var dateWithDesiredMonth = new Date(0);
dateWithDesiredMonth.setFullYear(year, month, 15);
dateWithDesiredMonth.setHours(0, 0, 0, 0);
var daysInMonth = getDaysInMonth_getDaysInMonth(dateWithDesiredMonth);
// Set the last day of the new month
// if the original date was the last day of the longer month
date.setMonth(month, Math.min(day, daysInMonth));
return date;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/set/index.js
/**
* @name set
* @category Common Helpers
* @summary Set date values to a given date.
*
* @description
* Set date values to a given date.
*
* Sets time values to date from object `values`.
* A value is not set if it is undefined or null or doesn't exist in `values`.
*
* Note about bundle size: `set` does not internally use `setX` functions from date-fns but instead opts
* to use native `Date#setX` methods. If you use this function, you may not want to include the
* other `setX` functions that date-fns provides if you are concerned about the bundle size.
*
* @param {Date|Number} date - the date to be changed
* @param {Object} values - an object with options
* @param {Number} [values.year] - the number of years to be set
* @param {Number} [values.month] - the number of months to be set
* @param {Number} [values.date] - the number of days to be set
* @param {Number} [values.hours] - the number of hours to be set
* @param {Number} [values.minutes] - the number of minutes to be set
* @param {Number} [values.seconds] - the number of seconds to be set
* @param {Number} [values.milliseconds] - the number of milliseconds to be set
* @returns {Date} the new date with options set
* @throws {TypeError} 2 arguments required
* @throws {RangeError} `values` must be an object
*
* @example
* // Transform 1 September 2014 into 20 October 2015 in a single line:
* const result = set(new Date(2014, 8, 20), { year: 2015, month: 9, date: 20 })
* //=> Tue Oct 20 2015 00:00:00
*
* @example
* // Set 12 PM to 1 September 2014 01:23:45 to 1 September 2014 12:00:00:
* const result = set(new Date(2014, 8, 1, 1, 23, 45), { hours: 12 })
* //=> Mon Sep 01 2014 12:23:45
*/
function set_set(dirtyDate, values) {
requiredArgs(2, arguments);
if (_typeof(values) !== 'object' || values === null) {
throw new RangeError('values parameter must be an object');
}
var date = toDate_toDate(dirtyDate);
// Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date
if (isNaN(date.getTime())) {
return new Date(NaN);
}
if (values.year != null) {
date.setFullYear(values.year);
}
if (values.month != null) {
date = setMonth_setMonth(date, values.month);
}
if (values.date != null) {
date.setDate(toInteger(values.date));
}
if (values.hours != null) {
date.setHours(toInteger(values.hours));
}
if (values.minutes != null) {
date.setMinutes(toInteger(values.minutes));
}
if (values.seconds != null) {
date.setSeconds(toInteger(values.seconds));
}
if (values.milliseconds != null) {
date.setMilliseconds(toInteger(values.milliseconds));
}
return date;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/setHours/index.js
/**
* @name setHours
* @category Hour Helpers
* @summary Set the hours to the given date.
*
* @description
* Set the hours to the given date.
*
* @param {Date|Number} date - the date to be changed
* @param {Number} hours - the hours of the new date
* @returns {Date} the new date with the hours set
* @throws {TypeError} 2 arguments required
*
* @example
* // Set 4 hours to 1 September 2014 11:30:00:
* const result = setHours(new Date(2014, 8, 1, 11, 30), 4)
* //=> Mon Sep 01 2014 04:30:00
*/
function setHours(dirtyDate, dirtyHours) {
requiredArgs(2, arguments);
var date = toDate_toDate(dirtyDate);
var hours = toInteger(dirtyHours);
date.setHours(hours);
return date;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/date-time/time/styles.js
function time_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const time_styles_Wrapper = createStyled("div", true ? {
target: "evcr23110"
} : 0)("box-sizing:border-box;font-size:", config_values.fontSize, ";" + ( true ? "" : 0));
const Fieldset = createStyled("fieldset", true ? {
target: "evcr2319"
} : 0)("border:0;margin:0 0 ", space(2 * 2), " 0;padding:0;&:last-child{margin-bottom:0;}" + ( true ? "" : 0));
const TimeWrapper = createStyled("div", true ? {
target: "evcr2318"
} : 0)( true ? {
name: "pd0mhc",
styles: "direction:ltr;display:flex"
} : 0);
const baseInput = /*#__PURE__*/emotion_react_browser_esm_css("&&& ", Input, "{padding-left:", space(2), ";padding-right:", space(2), ";text-align:center;}" + ( true ? "" : 0), true ? "" : 0);
const HoursInput = /*#__PURE__*/createStyled(number_control, true ? {
target: "evcr2317"
} : 0)(baseInput, " width:", space(9), ";&&& ", Input, "{padding-right:0;}&&& ", BackdropUI, "{border-right:0;border-top-right-radius:0;border-bottom-right-radius:0;}" + ( true ? "" : 0));
const TimeSeparator = createStyled("span", true ? {
target: "evcr2316"
} : 0)("border-top:", config_values.borderWidth, " solid ", COLORS.gray[700], ";border-bottom:", config_values.borderWidth, " solid ", COLORS.gray[700], ";line-height:calc(\n\t\t", config_values.controlHeight, " - ", config_values.borderWidth, " * 2\n\t);display:inline-block;" + ( true ? "" : 0));
const MinutesInput = /*#__PURE__*/createStyled(number_control, true ? {
target: "evcr2315"
} : 0)(baseInput, " width:", space(9), ";&&& ", Input, "{padding-left:0;}&&& ", BackdropUI, "{border-left:0;border-top-left-radius:0;border-bottom-left-radius:0;}" + ( true ? "" : 0)); // Ideally we wouldn't need a wrapper, but can't otherwise target the
// <BaseControl> in <SelectControl>
const MonthSelectWrapper = createStyled("div", true ? {
target: "evcr2314"
} : 0)( true ? {
name: "1ff36h2",
styles: "flex-grow:1"
} : 0);
const MonthSelect = /*#__PURE__*/createStyled(select_control, true ? {
target: "evcr2313"
} : 0)("height:36px;", Select, "{line-height:30px;}" + ( true ? "" : 0));
const DayInput = /*#__PURE__*/createStyled(number_control, true ? {
target: "evcr2312"
} : 0)(baseInput, " width:", space(9), ";" + ( true ? "" : 0));
const YearInput = /*#__PURE__*/createStyled(number_control, true ? {
target: "evcr2311"
} : 0)(baseInput, " width:", space(14), ";" + ( true ? "" : 0));
const TimeZone = createStyled("div", true ? {
target: "evcr2310"
} : 0)( true ? {
name: "ebu3jh",
styles: "text-decoration:underline dotted"
} : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/date-time/time/timezone.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Displays timezone information when user timezone is different from site
* timezone.
*/
const timezone_TimeZone = () => {
const {
timezone
} = (0,external_wp_date_namespaceObject.getSettings)(); // Convert timezone offset to hours.
const userTimezoneOffset = -1 * (new Date().getTimezoneOffset() / 60); // System timezone and user timezone match, nothing needed.
// Compare as numbers because it comes over as string.
if (Number(timezone.offset) === userTimezoneOffset) {
return null;
}
const offsetSymbol = Number(timezone.offset) >= 0 ? '+' : '';
const zoneAbbr = '' !== timezone.abbr && isNaN(Number(timezone.abbr)) ? timezone.abbr : `UTC${offsetSymbol}${timezone.offset}`;
const timezoneDetail = 'UTC' === timezone.string ? (0,external_wp_i18n_namespaceObject.__)('Coordinated Universal Time') : `(${zoneAbbr}) ${timezone.string.replace('_', ' ')}`;
return (0,external_wp_element_namespaceObject.createElement)(tooltip, {
position: "top center",
text: timezoneDetail
}, (0,external_wp_element_namespaceObject.createElement)(TimeZone, {
className: "components-datetime__timezone"
}, zoneAbbr));
};
/* harmony default export */ var timezone = (timezone_TimeZone);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/date-time/time/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function from12hTo24h(hours, isPm) {
return isPm ? (hours % 12 + 12) % 24 : hours % 12;
}
/**
* Creates an InputControl reducer used to pad an input so that it is always a
* given width. For example, the hours and minutes inputs are padded to 2 so
* that '4' appears as '04'.
*
* @param pad How many digits the value should be.
*/
function buildPadInputStateReducer(pad) {
return (state, action) => {
const nextState = { ...state
};
if (action.type === COMMIT || action.type === PRESS_UP || action.type === PRESS_DOWN) {
if (nextState.value !== undefined) {
nextState.value = nextState.value.toString().padStart(pad, '0');
}
}
return nextState;
};
}
/**
* TimePicker is a React component that renders a clock for time selection.
*
* ```jsx
* import { TimePicker } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyTimePicker = () => {
* const [ time, setTime ] = useState( new Date() );
*
* return (
* <TimePicker
* currentTime={ date }
* onChange={ ( newTime ) => setTime( newTime ) }
* is12Hour
* />
* );
* };
* ```
*/
function TimePicker(_ref) {
let {
is12Hour,
currentTime,
onChange
} = _ref;
const [date, setDate] = (0,external_wp_element_namespaceObject.useState)(() => // Truncate the date at the minutes, see: #15495.
currentTime ? startOfMinute(inputToDate(currentTime)) : new Date()); // Reset the state when currentTime changed.
// TODO: useEffect() shouldn't be used like this, causes an unnecessary render
(0,external_wp_element_namespaceObject.useEffect)(() => {
setDate(currentTime ? startOfMinute(inputToDate(currentTime)) : new Date());
}, [currentTime]);
const {
day,
month,
year,
minutes,
hours,
am
} = (0,external_wp_element_namespaceObject.useMemo)(() => ({
day: format(date, 'dd'),
month: format(date, 'MM'),
year: format(date, 'yyyy'),
minutes: format(date, 'mm'),
hours: format(date, is12Hour ? 'hh' : 'HH'),
am: format(date, 'a')
}), [date, is12Hour]);
const buildNumberControlChangeCallback = method => {
const callback = (value, _ref2) => {
let {
event
} = _ref2;
if (!(event.target instanceof HTMLInputElement)) {
return;
}
if (!event.target.validity.valid) {
return;
} // We can safely assume value is a number if target is valid.
let numberValue = Number(value); // If the 12-hour format is being used and the 'PM' period is
// selected, then the incoming value (which ranges 1-12) should be
// increased by 12 to match the expected 24-hour format.
if (method === 'hours' && is12Hour) {
numberValue = from12hTo24h(numberValue, am === 'PM');
}
const newDate = set_set(date, {
[method]: numberValue
});
setDate(newDate);
onChange === null || onChange === void 0 ? void 0 : onChange(format(newDate, TIMEZONELESS_FORMAT));
};
return callback;
};
function buildAmPmChangeCallback(value) {
return () => {
if (am === value) {
return;
}
const parsedHours = parseInt(hours, 10);
const newDate = setHours(date, from12hTo24h(parsedHours, value === 'PM'));
setDate(newDate);
onChange === null || onChange === void 0 ? void 0 : onChange(format(newDate, TIMEZONELESS_FORMAT));
};
}
const dayField = (0,external_wp_element_namespaceObject.createElement)(DayInput, {
className: "components-datetime__time-field components-datetime__time-field-day" // Unused, for backwards compatibility.
,
label: (0,external_wp_i18n_namespaceObject.__)('Day'),
hideLabelFromVision: true,
__next36pxDefaultSize: true,
value: day,
step: 1,
min: 1,
max: 31,
required: true,
spinControls: "none",
isPressEnterToChange: true,
isDragEnabled: false,
isShiftStepEnabled: false,
onChange: buildNumberControlChangeCallback('date')
});
const monthField = (0,external_wp_element_namespaceObject.createElement)(MonthSelectWrapper, null, (0,external_wp_element_namespaceObject.createElement)(MonthSelect, {
className: "components-datetime__time-field components-datetime__time-field-month" // Unused, for backwards compatibility.
,
label: (0,external_wp_i18n_namespaceObject.__)('Month'),
hideLabelFromVision: true,
__nextHasNoMarginBottom: true,
value: month,
options: [{
value: '01',
label: (0,external_wp_i18n_namespaceObject.__)('January')
}, {
value: '02',
label: (0,external_wp_i18n_namespaceObject.__)('February')
}, {
value: '03',
label: (0,external_wp_i18n_namespaceObject.__)('March')
}, {
value: '04',
label: (0,external_wp_i18n_namespaceObject.__)('April')
}, {
value: '05',
label: (0,external_wp_i18n_namespaceObject.__)('May')
}, {
value: '06',
label: (0,external_wp_i18n_namespaceObject.__)('June')
}, {
value: '07',
label: (0,external_wp_i18n_namespaceObject.__)('July')
}, {
value: '08',
label: (0,external_wp_i18n_namespaceObject.__)('August')
}, {
value: '09',
label: (0,external_wp_i18n_namespaceObject.__)('September')
}, {
value: '10',
label: (0,external_wp_i18n_namespaceObject.__)('October')
}, {
value: '11',
label: (0,external_wp_i18n_namespaceObject.__)('November')
}, {
value: '12',
label: (0,external_wp_i18n_namespaceObject.__)('December')
}],
onChange: value => {
const newDate = setMonth_setMonth(date, Number(value) - 1);
setDate(newDate);
onChange === null || onChange === void 0 ? void 0 : onChange(format(newDate, TIMEZONELESS_FORMAT));
}
}));
return (0,external_wp_element_namespaceObject.createElement)(time_styles_Wrapper, {
className: "components-datetime__time" // Unused, for backwards compatibility.
}, (0,external_wp_element_namespaceObject.createElement)(Fieldset, null, (0,external_wp_element_namespaceObject.createElement)(base_control.VisualLabel, {
as: "legend",
className: "components-datetime__time-legend" // Unused, for backwards compatibility.
}, (0,external_wp_i18n_namespaceObject.__)('Time')), (0,external_wp_element_namespaceObject.createElement)(h_stack_component, {
className: "components-datetime__time-wrapper" // Unused, for backwards compatibility.
}, (0,external_wp_element_namespaceObject.createElement)(TimeWrapper, {
className: "components-datetime__time-field components-datetime__time-field-time" // Unused, for backwards compatibility.
}, (0,external_wp_element_namespaceObject.createElement)(HoursInput, {
className: "components-datetime__time-field-hours-input" // Unused, for backwards compatibility.
,
label: (0,external_wp_i18n_namespaceObject.__)('Hours'),
hideLabelFromVision: true,
__next36pxDefaultSize: true,
value: hours,
step: 1,
min: is12Hour ? 1 : 0,
max: is12Hour ? 12 : 23,
required: true,
spinControls: "none",
isPressEnterToChange: true,
isDragEnabled: false,
isShiftStepEnabled: false,
onChange: buildNumberControlChangeCallback('hours'),
__unstableStateReducer: buildPadInputStateReducer(2)
}), (0,external_wp_element_namespaceObject.createElement)(TimeSeparator, {
className: "components-datetime__time-separator" // Unused, for backwards compatibility.
,
"aria-hidden": "true"
}, ":"), (0,external_wp_element_namespaceObject.createElement)(MinutesInput, {
className: "components-datetime__time-field-minutes-input" // Unused, for backwards compatibility.
,
label: (0,external_wp_i18n_namespaceObject.__)('Minutes'),
hideLabelFromVision: true,
__next36pxDefaultSize: true,
value: minutes,
step: 1,
min: 0,
max: 59,
required: true,
spinControls: "none",
isPressEnterToChange: true,
isDragEnabled: false,
isShiftStepEnabled: false,
onChange: buildNumberControlChangeCallback('minutes'),
__unstableStateReducer: buildPadInputStateReducer(2)
})), is12Hour && (0,external_wp_element_namespaceObject.createElement)(button_group, {
className: "components-datetime__time-field components-datetime__time-field-am-pm" // Unused, for backwards compatibility.
}, (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-datetime__time-am-button" // Unused, for backwards compatibility.
,
variant: am === 'AM' ? 'primary' : 'secondary',
onClick: buildAmPmChangeCallback('AM')
}, (0,external_wp_i18n_namespaceObject.__)('AM')), (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-datetime__time-pm-button" // Unused, for backwards compatibility.
,
variant: am === 'PM' ? 'primary' : 'secondary',
onClick: buildAmPmChangeCallback('PM')
}, (0,external_wp_i18n_namespaceObject.__)('PM'))), (0,external_wp_element_namespaceObject.createElement)(spacer_component, null), (0,external_wp_element_namespaceObject.createElement)(timezone, null))), (0,external_wp_element_namespaceObject.createElement)(Fieldset, null, (0,external_wp_element_namespaceObject.createElement)(base_control.VisualLabel, {
as: "legend",
className: "components-datetime__time-legend" // Unused, for backwards compatibility.
}, (0,external_wp_i18n_namespaceObject.__)('Date')), (0,external_wp_element_namespaceObject.createElement)(h_stack_component, {
className: "components-datetime__time-wrapper" // Unused, for backwards compatibility.
}, is12Hour ? (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, monthField, dayField) : (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, dayField, monthField), (0,external_wp_element_namespaceObject.createElement)(YearInput, {
className: "components-datetime__time-field components-datetime__time-field-year" // Unused, for backwards compatibility.
,
label: (0,external_wp_i18n_namespaceObject.__)('Year'),
hideLabelFromVision: true,
__next36pxDefaultSize: true,
value: year,
step: 1,
min: 1,
max: 9999,
required: true,
spinControls: "none",
isPressEnterToChange: true,
isDragEnabled: false,
isShiftStepEnabled: false,
onChange: buildNumberControlChangeCallback('year'),
__unstableStateReducer: buildPadInputStateReducer(4)
}))));
}
/* harmony default export */ var time = (TimePicker);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/date-time/date-time/styles.js
function date_time_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const date_time_styles_Wrapper = /*#__PURE__*/createStyled(v_stack_component, true ? {
target: "e1p5onf01"
} : 0)( true ? {
name: "1khn195",
styles: "box-sizing:border-box"
} : 0);
const CalendarHelp = createStyled("div", true ? {
target: "e1p5onf00"
} : 0)( true ? {
name: "l0rwn2",
styles: "min-width:260px"
} : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/date-time/date-time/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const date_time_noop = () => {};
function UnforwardedDateTimePicker(_ref, ref) {
let {
currentDate,
is12Hour,
isInvalidDate,
onMonthPreviewed = date_time_noop,
onChange,
events,
startOfWeek,
__nextRemoveHelpButton = false,
__nextRemoveResetButton = false
} = _ref;
if (!__nextRemoveHelpButton) {
external_wp_deprecated_default()('Help button in wp.components.DateTimePicker', {
since: '13.4',
version: '15.8',
// One year of plugin releases.
hint: 'Set the `__nextRemoveHelpButton` prop to `true` to remove this warning and opt in to the new behaviour, which will become the default in a future version.'
});
}
if (!__nextRemoveResetButton) {
external_wp_deprecated_default()('Reset button in wp.components.DateTimePicker', {
since: '13.4',
version: '15.8',
// One year of plugin releases.
hint: 'Set the `__nextRemoveResetButton` prop to `true` to remove this warning and opt in to the new behaviour, which will become the default in a future version.'
});
}
const [calendarHelpIsVisible, setCalendarHelpIsVisible] = (0,external_wp_element_namespaceObject.useState)(false);
function onClickDescriptionToggle() {
setCalendarHelpIsVisible(!calendarHelpIsVisible);
}
return (0,external_wp_element_namespaceObject.createElement)(date_time_styles_Wrapper, {
ref: ref,
className: "components-datetime",
spacing: 4
}, !calendarHelpIsVisible && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(time, {
currentTime: currentDate,
onChange: onChange,
is12Hour: is12Hour
}), (0,external_wp_element_namespaceObject.createElement)(date, {
currentDate: currentDate,
onChange: onChange,
isInvalidDate: isInvalidDate,
events: events,
onMonthPreviewed: onMonthPreviewed,
startOfWeek: startOfWeek
})), calendarHelpIsVisible && (0,external_wp_element_namespaceObject.createElement)(CalendarHelp, {
className: "components-datetime__calendar-help" // Unused, for backwards compatibility.
}, (0,external_wp_element_namespaceObject.createElement)(heading_component, {
level: 4
}, (0,external_wp_i18n_namespaceObject.__)('Click to Select')), (0,external_wp_element_namespaceObject.createElement)("ul", null, (0,external_wp_element_namespaceObject.createElement)("li", null, (0,external_wp_i18n_namespaceObject.__)('Click the right or left arrows to select other months in the past or the future.')), (0,external_wp_element_namespaceObject.createElement)("li", null, (0,external_wp_i18n_namespaceObject.__)('Click the desired day to select it.'))), (0,external_wp_element_namespaceObject.createElement)(heading_component, {
level: 4
}, (0,external_wp_i18n_namespaceObject.__)('Navigating with a keyboard')), (0,external_wp_element_namespaceObject.createElement)("ul", null, (0,external_wp_element_namespaceObject.createElement)("li", null, (0,external_wp_element_namespaceObject.createElement)("abbr", {
"aria-label": (0,external_wp_i18n_namespaceObject._x)('Enter', 'keyboard button')
}, "\u21B5"), ' '
/* JSX removes whitespace, but a space is required for screen readers. */
, (0,external_wp_element_namespaceObject.createElement)("span", null, (0,external_wp_i18n_namespaceObject.__)('Select the date in focus.'))), (0,external_wp_element_namespaceObject.createElement)("li", null, (0,external_wp_element_namespaceObject.createElement)("abbr", {
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Left and Right Arrows')
}, "\u2190/\u2192"), ' '
/* JSX removes whitespace, but a space is required for screen readers. */
, (0,external_wp_i18n_namespaceObject.__)('Move backward (left) or forward (right) by one day.')), (0,external_wp_element_namespaceObject.createElement)("li", null, (0,external_wp_element_namespaceObject.createElement)("abbr", {
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Up and Down Arrows')
}, "\u2191/\u2193"), ' '
/* JSX removes whitespace, but a space is required for screen readers. */
, (0,external_wp_i18n_namespaceObject.__)('Move backward (up) or forward (down) by one week.')), (0,external_wp_element_namespaceObject.createElement)("li", null, (0,external_wp_element_namespaceObject.createElement)("abbr", {
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Page Up and Page Down')
}, (0,external_wp_i18n_namespaceObject.__)('PgUp/PgDn')), ' '
/* JSX removes whitespace, but a space is required for screen readers. */
, (0,external_wp_i18n_namespaceObject.__)('Move backward (PgUp) or forward (PgDn) by one month.')), (0,external_wp_element_namespaceObject.createElement)("li", null, (0,external_wp_element_namespaceObject.createElement)("abbr", {
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Home and End')
}, (0,external_wp_i18n_namespaceObject.__)('Home/End')), ' '
/* JSX removes whitespace, but a space is required for screen readers. */
, (0,external_wp_i18n_namespaceObject.__)('Go to the first (Home) or last (End) day of a week.')))), (!__nextRemoveResetButton || !__nextRemoveHelpButton) && (0,external_wp_element_namespaceObject.createElement)(h_stack_component, {
className: "components-datetime__buttons" // Unused, for backwards compatibility.
}, !__nextRemoveResetButton && !calendarHelpIsVisible && currentDate && (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-datetime__date-reset-button" // Unused, for backwards compatibility.
,
variant: "link",
onClick: () => onChange === null || onChange === void 0 ? void 0 : onChange(null)
}, (0,external_wp_i18n_namespaceObject.__)('Reset')), (0,external_wp_element_namespaceObject.createElement)(spacer_component, null), !__nextRemoveHelpButton && (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-datetime__date-help-toggle" // Unused, for backwards compatibility.
,
variant: "link",
onClick: onClickDescriptionToggle
}, calendarHelpIsVisible ? (0,external_wp_i18n_namespaceObject.__)('Close') : (0,external_wp_i18n_namespaceObject.__)('Calendar Help'))));
}
/**
* DateTimePicker is a React component that renders a calendar and clock for
* date and time selection. The calendar and clock components can be accessed
* individually using the `DatePicker` and `TimePicker` components respectively.
*
* ```jsx
* import { DateTimePicker } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyDateTimePicker = () => {
* const [ date, setDate ] = useState( new Date() );
*
* return (
* <DateTimePicker
* currentDate={ date }
* onChange={ ( newDate ) => setDate( newDate ) }
* is12Hour
* __nextRemoveHelpButton
* __nextRemoveResetButton
* />
* );
* };
* ```
*/
const DateTimePicker = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedDateTimePicker);
/* harmony default export */ var date_time = (DateTimePicker);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/date-time/index.js
/**
* Internal dependencies
*/
/* harmony default export */ var build_module_date_time = (date_time);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/dimension-control/sizes.js
/**
* Sizes
*
* defines the sizes used in dimension controls
* all hardcoded `size` values are based on the value of
* the Sass variable `$block-padding` from
* `packages/block-editor/src/components/dimension-control/sizes.js`.
*/
/**
* WordPress dependencies
*/
/**
* Finds the correct size object from the provided sizes
* table by size slug (eg: `medium`)
*
* @param {Array} sizes containing objects for each size definition.
* @param {string} slug a string representation of the size (eg: `medium`).
*
* @return {Object} the matching size definition.
*/
const findSizeBySlug = (sizes, slug) => sizes.find(size => slug === size.slug);
/* harmony default export */ var dimension_control_sizes = ([{
name: (0,external_wp_i18n_namespaceObject._x)('None', 'Size of a UI element'),
slug: 'none'
}, {
name: (0,external_wp_i18n_namespaceObject._x)('Small', 'Size of a UI element'),
slug: 'small'
}, {
name: (0,external_wp_i18n_namespaceObject._x)('Medium', 'Size of a UI element'),
slug: 'medium'
}, {
name: (0,external_wp_i18n_namespaceObject._x)('Large', 'Size of a UI element'),
slug: 'large'
}, {
name: (0,external_wp_i18n_namespaceObject._x)('Extra Large', 'Size of a UI element'),
slug: 'xlarge'
}]);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/dimension-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function DimensionControl(props) {
const {
label,
value,
sizes = dimension_control_sizes,
icon,
onChange,
className = ''
} = props;
const onChangeSpacingSize = val => {
const theSize = findSizeBySlug(sizes, val);
if (!theSize || value === theSize.slug) {
onChange(undefined);
} else if (typeof onChange === 'function') {
onChange(theSize.slug);
}
};
const formatSizesAsOptions = theSizes => {
const options = theSizes.map(_ref => {
let {
name,
slug
} = _ref;
return {
label: name,
value: slug
};
});
return [{
label: (0,external_wp_i18n_namespaceObject.__)('Default'),
value: ''
}].concat(options);
};
const selectLabel = (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, icon && (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: icon
}), label);
return (0,external_wp_element_namespaceObject.createElement)(select_control, {
className: classnames_default()(className, 'block-editor-dimension-control'),
label: selectLabel,
hideLabelFromVision: false,
value: value,
onChange: onChangeSpacingSize,
options: formatSizesAsOptions(sizes)
});
}
/* harmony default export */ var dimension_control = (DimensionControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/disabled/styles/disabled-styles.js
function disabled_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
const disabled_styles_disabledStyles = true ? {
name: "u2jump",
styles: "position:relative;pointer-events:none;&::after{content:'';position:absolute;top:0;right:0;bottom:0;left:0;}*{pointer-events:none;}"
} : 0;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/disabled/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const Context = (0,external_wp_element_namespaceObject.createContext)(false);
const {
Consumer,
Provider: disabled_Provider
} = Context;
/**
* `Disabled` is a component which disables descendant tabbable elements and
* prevents pointer interaction.
*
* _Note: this component may not behave as expected in browsers that don't
* support the `inert` HTML attribute. We recommend adding the official WICG
* polyfill when using this component in your project._
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/inert
*
* ```jsx
* import { Button, Disabled, TextControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyDisabled = () => {
* const [ isDisabled, setIsDisabled ] = useState( true );
*
* let input = <TextControl label="Input" onChange={ () => {} } />;
* if ( isDisabled ) {
* input = <Disabled>{ input }</Disabled>;
* }
*
* const toggleDisabled = () => {
* setIsDisabled( ( state ) => ! state );
* };
*
* return (
* <div>
* { input }
* <Button variant="primary" onClick={ toggleDisabled }>
* Toggle Disabled
* </Button>
* </div>
* );
* };
* ```
*/
function Disabled(_ref) {
let {
className,
children,
isDisabled = true,
...props
} = _ref;
const cx = useCx();
return (0,external_wp_element_namespaceObject.createElement)(disabled_Provider, {
value: isDisabled
}, (0,external_wp_element_namespaceObject.createElement)("div", extends_extends({
// @ts-ignore Reason: inert is a recent HTML attribute
inert: isDisabled ? 'true' : undefined,
className: isDisabled ? cx(disabled_styles_disabledStyles, className, 'components-disabled') : undefined
}, props), children));
}
Disabled.Context = Context;
Disabled.Consumer = Consumer;
/* harmony default export */ var disabled = (Disabled);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/draggable/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const dragImageClass = 'components-draggable__invisible-drag-image';
const cloneWrapperClass = 'components-draggable__clone';
const clonePadding = 0;
const bodyClass = 'is-dragging-components-draggable';
/**
* `Draggable` is a Component that provides a way to set up a cross-browser
* (including IE) customizable drag image and the transfer data for the drag
* event. It decouples the drag handle and the element to drag: use it by
* wrapping the component that will become the drag handle and providing the DOM
* ID of the element to drag.
*
* Note that the drag handle needs to declare the `draggable="true"` property
* and bind the `Draggable`s `onDraggableStart` and `onDraggableEnd` event
* handlers to its own `onDragStart` and `onDragEnd` respectively. `Draggable`
* takes care of the logic to setup the drag image and the transfer data, but is
* not concerned with creating an actual DOM element that is draggable.
*
* ```jsx
* import { Draggable, Panel, PanelBody } from '@wordpress/components';
* import { Icon, more } from '@wordpress/icons';
*
* const MyDraggable = () => (
* <div id="draggable-panel">
* <Panel header="Draggable panel">
* <PanelBody>
* <Draggable elementId="draggable-panel" transferData={ {} }>
* { ( { onDraggableStart, onDraggableEnd } ) => (
* <div
* className="example-drag-handle"
* draggable
* onDragStart={ onDraggableStart }
* onDragEnd={ onDraggableEnd }
* >
* <Icon icon={ more } />
* </div>
* ) }
* </Draggable>
* </PanelBody>
* </Panel>
* </div>
* );
* ```
*/
function Draggable(_ref) {
let {
children,
onDragStart,
onDragOver,
onDragEnd,
cloneClassname,
elementId,
transferData,
__experimentalTransferDataType: transferDataType = 'text',
__experimentalDragComponent: dragComponent
} = _ref;
const dragComponentRef = (0,external_wp_element_namespaceObject.useRef)(null);
const cleanup = (0,external_wp_element_namespaceObject.useRef)(() => {});
/**
* Removes the element clone, resets cursor, and removes drag listener.
*
* @param event The non-custom DragEvent.
*/
function end(event) {
event.preventDefault();
cleanup.current();
if (onDragEnd) {
onDragEnd(event);
}
}
/**
* This method does a couple of things:
*
* - Clones the current element and spawns clone over original element.
* - Adds a fake temporary drag image to avoid browser defaults.
* - Sets transfer data.
* - Adds dragover listener.
*
* @param event The non-custom DragEvent.
*/
function start(event) {
const {
ownerDocument
} = event.target;
event.dataTransfer.setData(transferDataType, JSON.stringify(transferData));
const cloneWrapper = ownerDocument.createElement('div'); // Reset position to 0,0. Natural stacking order will position this lower, even with a transform otherwise.
cloneWrapper.style.top = '0';
cloneWrapper.style.left = '0';
const dragImage = ownerDocument.createElement('div'); // Set a fake drag image to avoid browser defaults. Remove from DOM
// right after. event.dataTransfer.setDragImage is not supported yet in
// IE, we need to check for its existence first.
if ('function' === typeof event.dataTransfer.setDragImage) {
dragImage.classList.add(dragImageClass);
ownerDocument.body.appendChild(dragImage);
event.dataTransfer.setDragImage(dragImage, 0, 0);
}
cloneWrapper.classList.add(cloneWrapperClass);
if (cloneClassname) {
cloneWrapper.classList.add(cloneClassname);
}
let x = 0;
let y = 0; // If a dragComponent is defined, the following logic will clone the
// HTML node and inject it into the cloneWrapper.
if (dragComponentRef.current) {
// Position dragComponent at the same position as the cursor.
x = event.clientX;
y = event.clientY;
cloneWrapper.style.transform = `translate( ${x}px, ${y}px )`;
const clonedDragComponent = ownerDocument.createElement('div');
clonedDragComponent.innerHTML = dragComponentRef.current.innerHTML;
cloneWrapper.appendChild(clonedDragComponent); // Inject the cloneWrapper into the DOM.
ownerDocument.body.appendChild(cloneWrapper);
} else {
const element = ownerDocument.getElementById(elementId); // Prepare element clone and append to element wrapper.
const elementRect = element.getBoundingClientRect();
const elementWrapper = element.parentNode;
const elementTopOffset = elementRect.top;
const elementLeftOffset = elementRect.left;
cloneWrapper.style.width = `${elementRect.width + clonePadding * 2}px`;
const clone = element.cloneNode(true);
clone.id = `clone-${elementId}`; // Position clone right over the original element (20px padding).
x = elementLeftOffset - clonePadding;
y = elementTopOffset - clonePadding;
cloneWrapper.style.transform = `translate( ${x}px, ${y}px )`; // Hack: Remove iFrames as it's causing the embeds drag clone to freeze.
Array.from(clone.querySelectorAll('iframe')).forEach(child => {
var _child$parentNode;
return (_child$parentNode = child.parentNode) === null || _child$parentNode === void 0 ? void 0 : _child$parentNode.removeChild(child);
});
cloneWrapper.appendChild(clone); // Inject the cloneWrapper into the DOM.
elementWrapper === null || elementWrapper === void 0 ? void 0 : elementWrapper.appendChild(cloneWrapper);
} // Mark the current cursor coordinates.
let cursorLeft = event.clientX;
let cursorTop = event.clientY;
function over(e) {
// Skip doing any work if mouse has not moved.
if (cursorLeft === e.clientX && cursorTop === e.clientY) {
return;
}
const nextX = x + e.clientX - cursorLeft;
const nextY = y + e.clientY - cursorTop;
cloneWrapper.style.transform = `translate( ${nextX}px, ${nextY}px )`;
cursorLeft = e.clientX;
cursorTop = e.clientY;
x = nextX;
y = nextY;
if (onDragOver) {
onDragOver(e);
}
} // Aim for 60fps (16 ms per frame) for now. We can potentially use requestAnimationFrame (raf) instead,
// note that browsers may throttle raf below 60fps in certain conditions.
// @ts-ignore
const throttledDragOver = (0,external_wp_compose_namespaceObject.throttle)(over, 16);
ownerDocument.addEventListener('dragover', throttledDragOver); // Update cursor to 'grabbing', document wide.
ownerDocument.body.classList.add(bodyClass); // Allow the Synthetic Event to be accessed from asynchronous code.
// https://reactjs.org/docs/events.html#event-pooling
event.persist();
let timerId;
if (onDragStart) {
timerId = setTimeout(() => onDragStart(event));
}
cleanup.current = () => {
// Remove drag clone.
if (cloneWrapper && cloneWrapper.parentNode) {
cloneWrapper.parentNode.removeChild(cloneWrapper);
}
if (dragImage && dragImage.parentNode) {
dragImage.parentNode.removeChild(dragImage);
} // Reset cursor.
ownerDocument.body.classList.remove(bodyClass);
ownerDocument.removeEventListener('dragover', throttledDragOver);
clearTimeout(timerId);
};
}
(0,external_wp_element_namespaceObject.useEffect)(() => () => {
cleanup.current();
}, []);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, children({
onDraggableStart: start,
onDraggableEnd: end
}), dragComponent && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-draggable-drag-component-root",
style: {
display: 'none'
},
ref: dragComponentRef
}, dragComponent));
}
/* harmony default export */ var draggable = (Draggable);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/upload.js
/**
* WordPress dependencies
*/
const upload = (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: "M18.5 15v3.5H13V6.7l4.5 4.1 1-1.1-6.2-5.8-5.8 5.8 1 1.1 4-4v11.7h-6V15H4v5h16v-5z"
}));
/* harmony default export */ var library_upload = (upload);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/drop-zone/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* `DropZone` is a component creating a drop zone area taking the full size of its parent element. It supports dropping files, HTML content or any other HTML drop event.
*
* ```jsx
* import { DropZone } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyDropZone = () => {
* const [ hasDropped, setHasDropped ] = useState( false );
*
* return (
* <div>
* { hasDropped ? 'Dropped!' : 'Drop something here' }
* <DropZone
* onFilesDrop={ () => setHasDropped( true ) }
* onHTMLDrop={ () => setHasDropped( true ) }
* onDrop={ () => setHasDropped( true ) }
* />
* </div>
* );
* }
* ```
*/
function DropZoneComponent(_ref) {
let {
className,
label,
onFilesDrop,
onHTMLDrop,
onDrop,
...restProps
} = _ref;
const [isDraggingOverDocument, setIsDraggingOverDocument] = (0,external_wp_element_namespaceObject.useState)();
const [isDraggingOverElement, setIsDraggingOverElement] = (0,external_wp_element_namespaceObject.useState)();
const [type, setType] = (0,external_wp_element_namespaceObject.useState)();
const ref = (0,external_wp_compose_namespaceObject.__experimentalUseDropZone)({
onDrop(event) {
var _event$dataTransfer;
const files = event.dataTransfer ? (0,external_wp_dom_namespaceObject.getFilesFromDataTransfer)(event.dataTransfer) : [];
const html = (_event$dataTransfer = event.dataTransfer) === null || _event$dataTransfer === void 0 ? void 0 : _event$dataTransfer.getData('text/html');
/**
* From Windows Chrome 96, the `event.dataTransfer` returns both file object and HTML.
* The order of the checks is important to recognise the HTML drop.
*/
if (html && onHTMLDrop) {
onHTMLDrop(html);
} else if (files.length && onFilesDrop) {
onFilesDrop(files);
} else if (onDrop) {
onDrop(event);
}
},
onDragStart(event) {
var _event$dataTransfer2, _event$dataTransfer3;
setIsDraggingOverDocument(true);
let _type = 'default';
/**
* From Windows Chrome 96, the `event.dataTransfer` returns both file object and HTML.
* The order of the checks is important to recognise the HTML drop.
*/
if ((_event$dataTransfer2 = event.dataTransfer) !== null && _event$dataTransfer2 !== void 0 && _event$dataTransfer2.types.includes('text/html')) {
_type = 'html';
} else if ( // Check for the types because sometimes the files themselves
// are only available on drop.
(_event$dataTransfer3 = event.dataTransfer) !== null && _event$dataTransfer3 !== void 0 && _event$dataTransfer3.types.includes('Files') || (event.dataTransfer ? (0,external_wp_dom_namespaceObject.getFilesFromDataTransfer)(event.dataTransfer) : []).length > 0) {
_type = 'file';
}
setType(_type);
},
onDragEnd() {
setIsDraggingOverDocument(false);
setType(undefined);
},
onDragEnter() {
setIsDraggingOverElement(true);
},
onDragLeave() {
setIsDraggingOverElement(false);
}
});
const disableMotion = (0,external_wp_compose_namespaceObject.useReducedMotion)();
let children;
const backdrop = {
hidden: {
scaleY: 0,
opacity: 0
},
show: {
scaleY: 1,
opacity: 1,
transition: {
type: 'tween',
duration: 0.2,
delay: 0.1,
delayChildren: 0.2
}
},
exit: {
scaleY: 1,
opacity: 0,
transition: {
duration: 0.3,
delayChildren: 0
}
}
};
const foreground = {
hidden: {
opacity: 0,
scale: 0.75
},
show: {
opacity: 1,
scale: 1
},
exit: {
opacity: 0,
scale: 0.9
}
};
if (isDraggingOverElement) {
children = (0,external_wp_element_namespaceObject.createElement)(motion.div, {
variants: backdrop,
initial: disableMotion ? 'show' : 'hidden',
animate: "show",
exit: disableMotion ? 'show' : 'exit',
className: "components-drop-zone__content" // Without this, when this div is shown,
// Safari calls a onDropZoneLeave causing a loop because of this bug
// https://bugs.webkit.org/show_bug.cgi?id=66547
,
style: {
pointerEvents: 'none'
}
}, (0,external_wp_element_namespaceObject.createElement)(motion.div, {
variants: foreground
}, (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, {
icon: library_upload,
className: "components-drop-zone__content-icon"
}), (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-drop-zone__content-text"
}, label ? label : (0,external_wp_i18n_namespaceObject.__)('Drop files to upload'))));
}
const classes = classnames_default()('components-drop-zone', className, {
'is-active': (isDraggingOverDocument || isDraggingOverElement) && (type === 'file' && onFilesDrop || type === 'html' && onHTMLDrop || type === 'default' && onDrop),
'is-dragging-over-document': isDraggingOverDocument,
'is-dragging-over-element': isDraggingOverElement,
[`is-dragging-${type}`]: !!type
});
return (0,external_wp_element_namespaceObject.createElement)("div", extends_extends({}, restProps, {
ref: ref,
className: classes
}), disableMotion ? children : (0,external_wp_element_namespaceObject.createElement)(AnimatePresence, null, children));
}
/* harmony default export */ var drop_zone = (DropZoneComponent);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/drop-zone/provider.js
/**
* WordPress dependencies
*/
function DropZoneProvider(_ref) {
let {
children
} = _ref;
external_wp_deprecated_default()('wp.components.DropZoneProvider', {
since: '5.8',
hint: 'wp.component.DropZone no longer needs a provider. wp.components.DropZoneProvider is safe to remove from your code.'
});
return children;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/swatch.js
/**
* WordPress dependencies
*/
const swatch = (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: "M5 17.7c.4.5.8.9 1.2 1.2l1.1-1.4c-.4-.3-.7-.6-1-1L5 17.7zM5 6.3l1.4 1.1c.3-.4.6-.7 1-1L6.3 5c-.5.4-.9.8-1.3 1.3zm.1 7.8l-1.7.5c.2.6.4 1.1.7 1.6l1.5-.8c-.2-.4-.4-.8-.5-1.3zM4.8 12v-.7L3 11.1v1.8l1.7-.2c.1-.2.1-.5.1-.7zm3 7.9c.5.3 1.1.5 1.6.7l.5-1.7c-.5-.1-.9-.3-1.3-.5l-.8 1.5zM19 6.3c-.4-.5-.8-.9-1.2-1.2l-1.1 1.4c.4.3.7.6 1 1L19 6.3zm-.1 3.6l1.7-.5c-.2-.6-.4-1.1-.7-1.6l-1.5.8c.2.4.4.8.5 1.3zM5.6 8.6l-1.5-.8c-.3.5-.5 1-.7 1.6l1.7.5c.1-.5.3-.9.5-1.3zm2.2-4.5l.8 1.5c.4-.2.8-.4 1.3-.5l-.5-1.7c-.6.2-1.1.4-1.6.7zm8.8 13.5l1.1 1.4c.5-.4.9-.8 1.2-1.2l-1.4-1.1c-.2.3-.5.6-.9.9zm1.8-2.2l1.5.8c.3-.5.5-1.1.7-1.6l-1.7-.5c-.1.5-.3.9-.5 1.3zm2.6-4.3l-1.7.2v1.4l1.7.2V12v-.9zM11.1 3l.2 1.7h1.4l.2-1.7h-1.8zm3 2.1c.5.1.9.3 1.3.5l.8-1.5c-.5-.3-1.1-.5-1.6-.7l-.5 1.7zM12 19.2h-.7l-.2 1.8h1.8l-.2-1.7c-.2-.1-.5-.1-.7-.1zm2.1-.3l.5 1.7c.6-.2 1.1-.4 1.6-.7l-.8-1.5c-.4.2-.8.4-1.3.5z"
}));
/* harmony default export */ var library_swatch = (swatch);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/duotone-picker/utils.js
/**
* External dependencies
*/
k([names]);
/**
* Object representation for a color.
*
* @typedef {Object} RGBColor
* @property {number} r Red component of the color in the range [0,1].
* @property {number} g Green component of the color in the range [0,1].
* @property {number} b Blue component of the color in the range [0,1].
*/
/**
* Calculate the brightest and darkest values from a color palette.
*
* @param {Object[]} palette Color palette for the theme.
*
* @return {string[]} Tuple of the darkest color and brightest color.
*/
function getDefaultColors(palette) {
// A default dark and light color are required.
if (!palette || palette.length < 2) return ['#000', '#fff'];
return palette.map(_ref => {
let {
color
} = _ref;
return {
color,
brightness: colord_w(color).brightness()
};
}).reduce((_ref2, current) => {
let [min, max] = _ref2;
return [current.brightness <= min.brightness ? current : min, current.brightness >= max.brightness ? current : max];
}, [{
brightness: 1
}, {
brightness: 0
}]).map(_ref3 => {
let {
color
} = _ref3;
return color;
});
}
/**
* Generate a duotone gradient from a list of colors.
*
* @param {string[]} colors CSS color strings.
* @param {string} angle CSS gradient angle.
*
* @return {string} CSS gradient string for the duotone swatch.
*/
function getGradientFromCSSColors() {
let colors = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
let angle = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '90deg';
const l = 100 / colors.length;
const stops = colors.map((c, i) => `${c} ${i * l}%, ${c} ${(i + 1) * l}%`).join(', ');
return `linear-gradient( ${angle}, ${stops} )`;
}
/**
* Convert a color array to an array of color stops.
*
* @param {string[]} colors CSS colors array
*
* @return {Object[]} Color stop information.
*/
function getColorStopsFromColors(colors) {
return colors.map((color, i) => ({
position: i * 100 / (colors.length - 1),
color
}));
}
/**
* Convert a color stop array to an array colors.
*
* @param {Object[]} colorStops Color stop information.
*
* @return {string[]} CSS colors array.
*/
function getColorsFromColorStops() {
let colorStops = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
return colorStops.map(_ref4 => {
let {
color
} = _ref4;
return color;
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/duotone-picker/duotone-swatch.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function DuotoneSwatch(_ref) {
let {
values
} = _ref;
return values ? (0,external_wp_element_namespaceObject.createElement)(color_indicator, {
colorValue: getGradientFromCSSColors(values, '135deg')
}) : (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: library_swatch
});
}
/* harmony default export */ var duotone_swatch = (DuotoneSwatch);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/color-list-picker/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ColorOption(_ref) {
let {
label,
value,
colors,
disableCustomColors,
enableAlpha,
onChange
} = _ref;
const [isOpen, setIsOpen] = (0,external_wp_element_namespaceObject.useState)(false);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-color-list-picker__swatch-button",
onClick: () => setIsOpen(prev => !prev)
}, (0,external_wp_element_namespaceObject.createElement)(h_stack_component, {
justify: "flex-start",
spacing: 2
}, value ? (0,external_wp_element_namespaceObject.createElement)(color_indicator, {
colorValue: value,
className: "components-color-list-picker__swatch-color"
}) : (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: library_swatch
}), (0,external_wp_element_namespaceObject.createElement)("span", null, label))), isOpen && (0,external_wp_element_namespaceObject.createElement)(color_palette, {
className: "components-color-list-picker__color-picker",
colors: colors,
value: value,
clearable: false,
onChange: onChange,
disableCustomColors: disableCustomColors,
enableAlpha: enableAlpha
}));
}
function ColorListPicker(_ref2) {
let {
colors,
labels,
value = [],
disableCustomColors,
enableAlpha,
onChange
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-color-list-picker"
}, labels.map((label, index) => (0,external_wp_element_namespaceObject.createElement)(ColorOption, {
key: index,
label: label,
value: value[index],
colors: colors,
disableCustomColors: disableCustomColors,
enableAlpha: enableAlpha,
onChange: newColor => {
const newColors = value.slice();
newColors[index] = newColor;
onChange(newColors);
}
})));
}
/* harmony default export */ var color_list_picker = (ColorListPicker);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/duotone-picker/custom-duotone-bar.js
/**
* Internal dependencies
*/
const PLACEHOLDER_VALUES = ['#333', '#CCC'];
function CustomDuotoneBar(_ref) {
let {
value,
onChange
} = _ref;
const hasGradient = !!value;
const values = hasGradient ? value : PLACEHOLDER_VALUES;
const background = getGradientFromCSSColors(values);
const controlPoints = getColorStopsFromColors(values);
return (0,external_wp_element_namespaceObject.createElement)(CustomGradientBar, {
disableInserter: true,
background: background,
hasGradient: hasGradient,
value: controlPoints,
onChange: newColorStops => {
const newValue = getColorsFromColorStops(newColorStops);
onChange(newValue);
}
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/duotone-picker/duotone-picker.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function DuotonePicker(_ref) {
let {
clearable = true,
unsetable = true,
colorPalette,
duotonePalette,
disableCustomColors,
disableCustomDuotone,
value,
onChange
} = _ref;
const [defaultDark, defaultLight] = (0,external_wp_element_namespaceObject.useMemo)(() => getDefaultColors(colorPalette), [colorPalette]);
const isUnset = value === 'unset';
const unsetOption = (0,external_wp_element_namespaceObject.createElement)(CircularOptionPicker.Option, {
key: "unset",
value: "unset",
isSelected: isUnset,
tooltipText: (0,external_wp_i18n_namespaceObject.__)('Unset'),
className: "components-duotone-picker__color-indicator",
onClick: () => {
onChange(isUnset ? undefined : 'unset');
}
});
const options = duotonePalette.map(_ref2 => {
let {
colors,
slug,
name
} = _ref2;
const style = {
background: getGradientFromCSSColors(colors, '135deg'),
color: 'transparent'
};
const tooltipText = name !== null && name !== void 0 ? name : (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: duotone code e.g: "dark-grayscale" or "7f7f7f-ffffff".
(0,external_wp_i18n_namespaceObject.__)('Duotone code: %s'), slug);
const label = name ? (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The name of the option e.g: "Dark grayscale".
(0,external_wp_i18n_namespaceObject.__)('Duotone: %s'), name) : tooltipText;
const isSelected = es6_default()(colors, value);
return (0,external_wp_element_namespaceObject.createElement)(CircularOptionPicker.Option, {
key: slug,
value: colors,
isSelected: isSelected,
"aria-label": label,
tooltipText: tooltipText,
style: style,
onClick: () => {
onChange(isSelected ? undefined : colors);
}
});
});
return (0,external_wp_element_namespaceObject.createElement)(CircularOptionPicker, {
options: unsetable ? [unsetOption, ...options] : options,
actions: !!clearable && (0,external_wp_element_namespaceObject.createElement)(CircularOptionPicker.ButtonAction, {
onClick: () => onChange(undefined)
}, (0,external_wp_i18n_namespaceObject.__)('Clear'))
}, (0,external_wp_element_namespaceObject.createElement)(spacer_component, {
paddingTop: 4
}, (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
spacing: 3
}, !disableCustomColors && !disableCustomDuotone && (0,external_wp_element_namespaceObject.createElement)(CustomDuotoneBar, {
value: isUnset ? undefined : value,
onChange: onChange
}), !disableCustomDuotone && (0,external_wp_element_namespaceObject.createElement)(color_list_picker, {
labels: [(0,external_wp_i18n_namespaceObject.__)('Shadows'), (0,external_wp_i18n_namespaceObject.__)('Highlights')],
colors: colorPalette,
value: isUnset ? undefined : value,
disableCustomColors: disableCustomColors,
enableAlpha: true,
onChange: newColors => {
if (!newColors[0]) {
newColors[0] = defaultDark;
}
if (!newColors[1]) {
newColors[1] = defaultLight;
}
const newValue = newColors.length >= 2 ? newColors : undefined;
onChange(newValue);
}
}))));
}
/* harmony default export */ var duotone_picker = (DuotonePicker);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/external.js
/**
* WordPress dependencies
*/
const external = (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: "M18.2 17c0 .7-.6 1.2-1.2 1.2H7c-.7 0-1.2-.6-1.2-1.2V7c0-.7.6-1.2 1.2-1.2h3.2V4.2H7C5.5 4.2 4.2 5.5 4.2 7v10c0 1.5 1.2 2.8 2.8 2.8h10c1.5 0 2.8-1.2 2.8-2.8v-3.6h-1.5V17zM14.9 3v1.5h3.7l-6.4 6.4 1.1 1.1 6.4-6.4v3.7h1.5V3h-6.3z"
}));
/* harmony default export */ var library_external = (external);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/external-link/styles/external-link-styles.js
function external_link_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
const StyledIcon = /*#__PURE__*/createStyled(icons_build_module_icon, true ? {
target: "esh4a730"
} : 0)( true ? {
name: "rvs7bx",
styles: "width:1em;height:1em;margin:0;vertical-align:middle;fill:currentColor"
} : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/external-link/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedExternalLink(props, ref) {
const {
href,
children,
className,
rel = '',
...additionalProps
} = props;
const optimizedRel = [...new Set([...rel.split(' '), 'external', 'noreferrer', 'noopener'].filter(Boolean))].join(' ');
const classes = classnames_default()('components-external-link', className);
/* Anchor links are perceived as external links.
This constant helps check for on page anchor links,
to prevent them from being opened in the editor. */
const isInternalAnchor = !!(href !== null && href !== void 0 && href.startsWith('#'));
const onClickHandler = event => {
if (isInternalAnchor) {
event.preventDefault();
}
if (props.onClick) {
props.onClick(event);
}
};
return (
/* eslint-disable react/jsx-no-target-blank */
(0,external_wp_element_namespaceObject.createElement)("a", extends_extends({}, additionalProps, {
className: classes,
href: href,
onClick: onClickHandler,
target: "_blank",
rel: optimizedRel,
ref: ref
}), children, (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, {
as: "span"
},
/* translators: accessibility text */
(0,external_wp_i18n_namespaceObject.__)('(opens in a new tab)')), (0,external_wp_element_namespaceObject.createElement)(StyledIcon, {
icon: library_external,
className: "components-external-link__icon"
}))
/* eslint-enable react/jsx-no-target-blank */
);
}
/**
* Link to an external resource.
*
* ```jsx
* import { ExternalLink } from '@wordpress/components';
*
* const MyExternalLink = () => (
* <ExternalLink href="https://wordpress.org">WordPress.org</ExternalLink>
* );
* ```
*/
const ExternalLink = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedExternalLink);
/* harmony default export */ var external_link = (ExternalLink);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/focal-point-picker/utils.js
const INITIAL_BOUNDS = {
width: 200,
height: 170
};
const VIDEO_EXTENSIONS = ['avi', 'mpg', 'mpeg', 'mov', 'mp4', 'm4v', 'ogg', 'ogv', 'webm', 'wmv'];
/**
* Gets the extension of a file name.
*
* @param filename The file name.
* @return The extension of the file name.
*/
function getExtension() {
let filename = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
const parts = filename.split('.');
return parts[parts.length - 1];
}
/**
* Checks if a file is a video.
*
* @param filename The file name.
* @return Whether the file is a video.
*/
function isVideoType() {
let filename = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
if (!filename) return false;
return filename.startsWith('data:video/') || VIDEO_EXTENSIONS.includes(getExtension(filename));
}
/**
* Transforms a fraction value to a percentage value.
*
* @param fraction The fraction value.
* @return A percentage value.
*/
function fractionToPercentage(fraction) {
return Math.round(fraction * 100);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/focal-point-picker/styles/focal-point-picker-style.js
function focal_point_picker_style_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const MediaWrapper = createStyled("div", true ? {
target: "eeew7dm8"
} : 0)( true ? {
name: "w0nf6b",
styles: "background-color:transparent;text-align:center;width:100%"
} : 0);
const MediaContainer = createStyled("div", true ? {
target: "eeew7dm7"
} : 0)( true ? {
name: "megach",
styles: "align-items:center;box-shadow:0 0 0 1px rgba( 0, 0, 0, 0.2 );cursor:pointer;display:inline-flex;justify-content:center;margin:auto;position:relative;height:100%;img,video{box-sizing:border-box;display:block;height:auto;margin:0;max-height:100%;max-width:100%;pointer-events:none;user-select:none;width:auto;}"
} : 0);
const MediaPlaceholder = createStyled("div", true ? {
target: "eeew7dm6"
} : 0)("background:", COLORS.gray[100], ";box-sizing:border-box;height:", INITIAL_BOUNDS.height, "px;max-width:280px;min-width:", INITIAL_BOUNDS.width, "px;width:100%;" + ( true ? "" : 0));
const StyledUnitControl = /*#__PURE__*/createStyled(unit_control, true ? {
target: "eeew7dm5"
} : 0)( true ? {
name: "1pzk433",
styles: "width:100px"
} : 0);
var focal_point_picker_style_ref2 = true ? {
name: "1mn7kwb",
styles: "padding-bottom:1em"
} : 0;
const focal_point_picker_style_deprecatedBottomMargin = _ref3 => {
let {
__nextHasNoMarginBottom
} = _ref3;
return !__nextHasNoMarginBottom ? focal_point_picker_style_ref2 : undefined;
};
var focal_point_picker_style_ref = true ? {
name: "1mn7kwb",
styles: "padding-bottom:1em"
} : 0;
const extraHelpTextMargin = _ref4 => {
let {
hasHelpText = false
} = _ref4;
return hasHelpText ? focal_point_picker_style_ref : undefined;
};
const ControlWrapper = /*#__PURE__*/createStyled(flex_component, true ? {
target: "eeew7dm4"
} : 0)("max-width:320px;padding-top:1em;", extraHelpTextMargin, " ", focal_point_picker_style_deprecatedBottomMargin, ";" + ( true ? "" : 0));
const GridView = createStyled("div", true ? {
target: "eeew7dm3"
} : 0)("left:50%;overflow:hidden;pointer-events:none;position:absolute;top:50%;transform:translate3d( -50%, -50%, 0 );transition:opacity 120ms linear;z-index:1;opacity:", _ref5 => {
let {
showOverlay
} = _ref5;
return showOverlay ? 1 : 0;
}, ";" + ( true ? "" : 0));
const GridLine = createStyled("div", true ? {
target: "eeew7dm2"
} : 0)( true ? {
name: "1d42i6k",
styles: "background:white;box-shadow:0 0 2px rgba( 0, 0, 0, 0.6 );position:absolute;opacity:0.4;transform:translateZ( 0 )"
} : 0);
const GridLineX = /*#__PURE__*/createStyled(GridLine, true ? {
target: "eeew7dm1"
} : 0)( true ? {
name: "1qp910y",
styles: "height:1px;left:0;right:0"
} : 0);
const GridLineY = /*#__PURE__*/createStyled(GridLine, true ? {
target: "eeew7dm0"
} : 0)( true ? {
name: "1oz3zka",
styles: "width:1px;top:0;bottom:0"
} : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/focal-point-picker/controls.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const TEXTCONTROL_MIN = 0;
const TEXTCONTROL_MAX = 100;
const controls_noop = () => {};
function FocalPointPickerControls(_ref) {
let {
__nextHasNoMarginBottom,
hasHelpText,
onChange = controls_noop,
point = {
x: 0.5,
y: 0.5
}
} = _ref;
const valueX = fractionToPercentage(point.x);
const valueY = fractionToPercentage(point.y);
const handleChange = (value, axis) => {
if (value === undefined) return;
const num = parseInt(value, 10);
if (!isNaN(num)) {
onChange({ ...point,
[axis]: num / 100
});
}
};
return (0,external_wp_element_namespaceObject.createElement)(ControlWrapper, {
className: "focal-point-picker__controls",
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
hasHelpText: hasHelpText
}, (0,external_wp_element_namespaceObject.createElement)(FocalPointUnitControl, {
label: (0,external_wp_i18n_namespaceObject.__)('Left'),
value: [valueX, '%'].join(''),
onChange: next => handleChange(next, 'x'),
dragDirection: "e"
}), (0,external_wp_element_namespaceObject.createElement)(FocalPointUnitControl, {
label: (0,external_wp_i18n_namespaceObject.__)('Top'),
value: [valueY, '%'].join(''),
onChange: next => handleChange(next, 'y'),
dragDirection: "s"
}));
}
function FocalPointUnitControl(props) {
return (0,external_wp_element_namespaceObject.createElement)(StyledUnitControl, extends_extends({
className: "focal-point-picker__controls-position-unit-control",
labelPosition: "top",
max: TEXTCONTROL_MAX,
min: TEXTCONTROL_MIN,
units: [{
value: '%',
label: '%'
}]
}, props));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/focal-point-picker/styles/focal-point-style.js
/**
* External dependencies
*/
const PointerCircle = createStyled("div", true ? {
target: "e19snlhg0"
} : 0)("background-color:transparent;cursor:grab;height:48px;margin:-24px 0 0 -24px;position:absolute;user-select:none;width:48px;will-change:transform;z-index:10000;background:rgba( 255, 255, 255, 0.6 );border-radius:50%;backdrop-filter:blur( 4px );box-shadow:rgb( 0 0 0 / 20% ) 0px 0px 10px;", _ref => {
let {
isDragging
} = _ref;
return isDragging && 'cursor: grabbing;';
}, ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/focal-point-picker/focal-point.js
/**
* Internal dependencies
*/
/**
* External dependencies
*/
function FocalPoint(_ref) {
let {
left = '50%',
top = '50%',
...props
} = _ref;
const classes = classnames_default()('components-focal-point-picker__icon_container');
const style = {
left,
top
};
return (0,external_wp_element_namespaceObject.createElement)(PointerCircle, extends_extends({}, props, {
className: classes,
style: style
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/focal-point-picker/grid.js
/**
* Internal dependencies
*/
function FocalPointPickerGrid(_ref) {
let {
bounds,
...props
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(GridView, extends_extends({}, props, {
className: "components-focal-point-picker__grid",
style: {
width: bounds.width,
height: bounds.height
}
}), (0,external_wp_element_namespaceObject.createElement)(GridLineX, {
style: {
top: '33%'
}
}), (0,external_wp_element_namespaceObject.createElement)(GridLineX, {
style: {
top: '66%'
}
}), (0,external_wp_element_namespaceObject.createElement)(GridLineY, {
style: {
left: '33%'
}
}), (0,external_wp_element_namespaceObject.createElement)(GridLineY, {
style: {
left: '66%'
}
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/focal-point-picker/media.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function media_Media(_ref) {
let {
alt,
autoPlay,
src,
onLoad,
mediaRef,
// Exposing muted prop for test rendering purposes
// https://github.com/testing-library/react-testing-library/issues/470
muted = true,
...props
} = _ref;
if (!src) {
return (0,external_wp_element_namespaceObject.createElement)(MediaPlaceholder, extends_extends({
className: "components-focal-point-picker__media components-focal-point-picker__media--placeholder",
ref: mediaRef
}, props));
}
const isVideo = isVideoType(src);
return isVideo ? (0,external_wp_element_namespaceObject.createElement)("video", extends_extends({}, props, {
autoPlay: autoPlay,
className: "components-focal-point-picker__media components-focal-point-picker__media--video",
loop: true,
muted: muted,
onLoadedData: onLoad,
ref: mediaRef,
src: src
})) : (0,external_wp_element_namespaceObject.createElement)("img", extends_extends({}, props, {
alt: alt,
className: "components-focal-point-picker__media components-focal-point-picker__media--image",
onLoad: onLoad,
ref: mediaRef,
src: src
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/focal-point-picker/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const GRID_OVERLAY_TIMEOUT = 600;
/**
* Focal Point Picker is a component which creates a UI for identifying the most important visual point of an image.
*
* This component addresses a specific problem: with large background images it is common to see undesirable crops,
* especially when viewing on smaller viewports such as mobile phones. This component allows the selection of
* the point with the most important visual information and returns it as a pair of numbers between 0 and 1.
* This value can be easily converted into the CSS `background-position` attribute, and will ensure that the
* focal point is never cropped out, regardless of viewport.
*
* - Example focal point picker value: `{ x: 0.5, y: 0.1 }`
* - Corresponding CSS: `background-position: 50% 10%;`
*
* ```jsx
* import { FocalPointPicker } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const Example = () => {
* const [ focalPoint, setFocalPoint ] = useState( {
* x: 0.5,
* y: 0.5,
* } );
*
* const url = '/path/to/image';
*
* // Example function to render the CSS styles based on Focal Point Picker value
* const style = {
* backgroundImage: `url(${ url })`,
* backgroundPosition: `${ focalPoint.x * 100 }% ${ focalPoint.y * 100 }%`,
* };
*
* return (
* <>
* <FocalPointPicker
* url={ url }
* value={ focalPoint }
* onDragStart={ setFocalPoint }
* onDrag={ setFocalPoint }
* onChange={ setFocalPoint }
* />
* <div style={ style } />
* </>
* );
* };
* ```
*/
function FocalPointPicker(_ref) {
let {
__nextHasNoMarginBottom,
autoPlay = true,
className,
help,
label,
onChange,
onDrag,
onDragEnd,
onDragStart,
resolvePoint,
url,
value: valueProp = {
x: 0.5,
y: 0.5
},
...restProps
} = _ref;
const [point, setPoint] = (0,external_wp_element_namespaceObject.useState)(valueProp);
const [showGridOverlay, setShowGridOverlay] = (0,external_wp_element_namespaceObject.useState)(false);
const {
startDrag,
endDrag,
isDragging
} = (0,external_wp_compose_namespaceObject.__experimentalUseDragging)({
onDragStart: event => {
var _dragAreaRef$current;
(_dragAreaRef$current = dragAreaRef.current) === null || _dragAreaRef$current === void 0 ? void 0 : _dragAreaRef$current.focus();
const value = getValueWithinDragArea(event); // `value` can technically be undefined if getValueWithinDragArea() is
// called before dragAreaRef is set, but this shouldn't happen in reality.
if (!value) return;
onDragStart === null || onDragStart === void 0 ? void 0 : onDragStart(value, event);
setPoint(value);
},
onDragMove: event => {
// Prevents text-selection when dragging.
event.preventDefault();
const value = getValueWithinDragArea(event);
if (!value) return;
onDrag === null || onDrag === void 0 ? void 0 : onDrag(value, event);
setPoint(value);
},
onDragEnd: () => {
onDragEnd === null || onDragEnd === void 0 ? void 0 : onDragEnd();
onChange === null || onChange === void 0 ? void 0 : onChange(point);
}
}); // Uses the internal point while dragging or else the value from props.
const {
x,
y
} = isDragging ? point : valueProp;
const dragAreaRef = (0,external_wp_element_namespaceObject.useRef)(null);
const [bounds, setBounds] = (0,external_wp_element_namespaceObject.useState)(INITIAL_BOUNDS);
const refUpdateBounds = (0,external_wp_element_namespaceObject.useRef)(() => {
if (!dragAreaRef.current) return;
const {
clientWidth: width,
clientHeight: height
} = dragAreaRef.current; // Falls back to initial bounds if the ref has no size. Since styles
// give the drag area dimensions even when the media has not loaded
// this should only happen in unit tests (jsdom).
setBounds(width > 0 && height > 0 ? {
width,
height
} : { ...INITIAL_BOUNDS
});
});
(0,external_wp_element_namespaceObject.useEffect)(() => {
const updateBounds = refUpdateBounds.current;
if (!dragAreaRef.current) return;
const {
defaultView
} = dragAreaRef.current.ownerDocument;
defaultView === null || defaultView === void 0 ? void 0 : defaultView.addEventListener('resize', updateBounds);
return () => defaultView === null || defaultView === void 0 ? void 0 : defaultView.removeEventListener('resize', updateBounds);
}, []); // Updates the bounds to cover cases of unspecified media or load failures.
(0,external_wp_compose_namespaceObject.useIsomorphicLayoutEffect)(() => void refUpdateBounds.current(), []); // TODO: Consider refactoring getValueWithinDragArea() into a pure function.
// https://github.com/WordPress/gutenberg/pull/43872#discussion_r963455173
const getValueWithinDragArea = _ref2 => {
let {
clientX,
clientY,
shiftKey
} = _ref2;
if (!dragAreaRef.current) return;
const {
top,
left
} = dragAreaRef.current.getBoundingClientRect();
let nextX = (clientX - left) / bounds.width;
let nextY = (clientY - top) / bounds.height; // Enables holding shift to jump values by 10%.
if (shiftKey) {
nextX = Math.round(nextX / 0.1) * 0.1;
nextY = Math.round(nextY / 0.1) * 0.1;
}
return getFinalValue({
x: nextX,
y: nextY
});
};
const getFinalValue = value => {
var _resolvePoint;
const resolvedValue = (_resolvePoint = resolvePoint === null || resolvePoint === void 0 ? void 0 : resolvePoint(value)) !== null && _resolvePoint !== void 0 ? _resolvePoint : value;
resolvedValue.x = Math.max(0, Math.min(resolvedValue.x, 1));
resolvedValue.y = Math.max(0, Math.min(resolvedValue.y, 1));
const roundToTwoDecimalPlaces = n => Math.round(n * 1e2) / 1e2;
return {
x: roundToTwoDecimalPlaces(resolvedValue.x),
y: roundToTwoDecimalPlaces(resolvedValue.y)
};
};
const arrowKeyStep = event => {
const {
code,
shiftKey
} = event;
if (!['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(code)) return;
event.preventDefault();
const value = {
x,
y
};
const step = shiftKey ? 0.1 : 0.01;
const delta = code === 'ArrowUp' || code === 'ArrowLeft' ? -1 * step : step;
const axis = code === 'ArrowUp' || code === 'ArrowDown' ? 'y' : 'x';
value[axis] = value[axis] + delta;
onChange === null || onChange === void 0 ? void 0 : onChange(getFinalValue(value));
};
const focalPointPosition = {
left: x * bounds.width,
top: y * bounds.height
};
const classes = classnames_default()('components-focal-point-picker-control', className);
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(FocalPointPicker);
const id = `inspector-focal-point-picker-control-${instanceId}`;
use_update_effect(() => {
setShowGridOverlay(true);
const timeout = window.setTimeout(() => {
setShowGridOverlay(false);
}, GRID_OVERLAY_TIMEOUT);
return () => window.clearTimeout(timeout);
}, [x, y]);
return (0,external_wp_element_namespaceObject.createElement)(base_control, extends_extends({}, restProps, {
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
label: label,
id: id,
help: help,
className: classes
}), (0,external_wp_element_namespaceObject.createElement)(MediaWrapper, {
className: "components-focal-point-picker-wrapper"
}, (0,external_wp_element_namespaceObject.createElement)(MediaContainer, {
className: "components-focal-point-picker",
onKeyDown: arrowKeyStep,
onMouseDown: startDrag,
onBlur: () => {
if (isDragging) endDrag();
},
ref: dragAreaRef,
role: "button",
tabIndex: -1
}, (0,external_wp_element_namespaceObject.createElement)(FocalPointPickerGrid, {
bounds: bounds,
showOverlay: showGridOverlay
}), (0,external_wp_element_namespaceObject.createElement)(media_Media, {
alt: (0,external_wp_i18n_namespaceObject.__)('Media preview'),
autoPlay: autoPlay,
onLoad: refUpdateBounds.current,
src: url
}), (0,external_wp_element_namespaceObject.createElement)(FocalPoint, extends_extends({}, focalPointPosition, {
isDragging: isDragging
})))), (0,external_wp_element_namespaceObject.createElement)(FocalPointPickerControls, {
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
hasHelpText: !!help,
point: {
x,
y
},
onChange: value => {
onChange === null || onChange === void 0 ? void 0 : onChange(getFinalValue(value));
}
}));
}
/* harmony default export */ var focal_point_picker = (FocalPointPicker);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/focusable-iframe/index.js
/**
* WordPress dependencies
*/
/**
* @param {Object} props
* @param {import('react').Ref<HTMLIFrameElement>} props.iframeRef
*/
function FocusableIframe(_ref) {
let {
iframeRef,
...props
} = _ref;
const ref = (0,external_wp_compose_namespaceObject.useMergeRefs)([iframeRef, (0,external_wp_compose_namespaceObject.useFocusableIframe)()]);
external_wp_deprecated_default()('wp.components.FocusableIframe', {
since: '5.9',
alternative: 'wp.compose.useFocusableIframe'
}); // Disable reason: The rendered iframe is a pass-through component,
// assigning props inherited from the rendering parent. It's the
// responsibility of the parent to assign a title.
// eslint-disable-next-line jsx-a11y/iframe-has-title
return (0,external_wp_element_namespaceObject.createElement)("iframe", extends_extends({
ref: ref
}, props));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/settings.js
/**
* WordPress dependencies
*/
const settings = (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: "M14.5 13.8c-1.1 0-2.1.7-2.4 1.8H4V17h8.1c.3 1 1.3 1.8 2.4 1.8s2.1-.7 2.4-1.8H20v-1.5h-3.1c-.3-1-1.3-1.7-2.4-1.7zM11.9 7c-.3-1-1.3-1.8-2.4-1.8S7.4 6 7.1 7H4v1.5h3.1c.3 1 1.3 1.8 2.4 1.8s2.1-.7 2.4-1.8H20V7h-8.1z"
}));
/* harmony default export */ var library_settings = (settings);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/font-size-picker/utils.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Some themes use css vars for their font sizes, so until we
* have the way of calculating them don't display them.
*
* @param value The value that is checked.
* @return Whether the value is a simple css value.
*/
function isSimpleCssValue(value) {
const sizeRegex = /^[\d\.]+(px|em|rem|vw|vh|%)?$/i;
return sizeRegex.test(String(value));
}
/**
* If all of the given font sizes have the same unit (e.g. 'px'), return that
* unit. Otherwise return null.
*
* @param fontSizes List of font sizes.
* @return The common unit, or null.
*/
function getCommonSizeUnit(fontSizes) {
const [firstFontSize, ...otherFontSizes] = fontSizes;
if (!firstFontSize) {
return null;
}
const [, firstUnit] = parseQuantityAndUnitFromRawValue(firstFontSize.size);
const areAllSizesSameUnit = otherFontSizes.every(fontSize => {
const [, unit] = parseQuantityAndUnitFromRawValue(fontSize.size);
return unit === firstUnit;
});
return areAllSizesSameUnit ? firstUnit : null;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/font-size-picker/styles.js
function font_size_picker_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const styles_Container = createStyled("fieldset", true ? {
target: "e8tqeku4"
} : 0)( true ? {
name: "1t1ytme",
styles: "border:0;margin:0;padding:0"
} : 0);
const HeaderLabel = /*#__PURE__*/createStyled(base_control.VisualLabel, true ? {
target: "e8tqeku3"
} : 0)("display:flex;gap:", space(1), ";justify-content:flex-start;margin-bottom:0;" + ( true ? "" : 0));
const HeaderHint = createStyled("span", true ? {
target: "e8tqeku2"
} : 0)("color:", COLORS.gray[700], ";" + ( true ? "" : 0));
const Controls = createStyled("div", true ? {
target: "e8tqeku1"
} : 0)(props => !props.__nextHasNoMarginBottom && `margin-bottom: ${space(6)};`, ";" + ( true ? "" : 0));
const ResetButton = /*#__PURE__*/createStyled(build_module_button, true ? {
target: "e8tqeku0"
} : 0)("&&&{height:", props => props.size === '__unstable-large' ? '40px' : '30px', ";}" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/font-size-picker/font-size-picker-select.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const DEFAULT_OPTION = {
key: 'default',
name: (0,external_wp_i18n_namespaceObject.__)('Default'),
value: undefined
};
const CUSTOM_OPTION = {
key: 'custom',
name: (0,external_wp_i18n_namespaceObject.__)('Custom')
};
const FontSizePickerSelect = props => {
var _options$find;
const {
fontSizes,
value,
disableCustomFontSizes,
size,
onChange,
onSelectCustom
} = props;
const areAllSizesSameUnit = !!getCommonSizeUnit(fontSizes);
const options = [DEFAULT_OPTION, ...fontSizes.map(fontSize => {
let hint;
if (areAllSizesSameUnit) {
const [quantity] = parseQuantityAndUnitFromRawValue(fontSize.size);
if (quantity !== undefined) {
hint = String(quantity);
}
} else if (isSimpleCssValue(fontSize.size)) {
hint = String(fontSize.size);
}
return {
key: fontSize.slug,
name: fontSize.name || fontSize.slug,
value: fontSize.size,
__experimentalHint: hint
};
}), ...(disableCustomFontSizes ? [] : [CUSTOM_OPTION])];
const selectedOption = value ? (_options$find = options.find(option => option.value === value)) !== null && _options$find !== void 0 ? _options$find : CUSTOM_OPTION : DEFAULT_OPTION;
return (0,external_wp_element_namespaceObject.createElement)(CustomSelectControl, {
__nextUnconstrainedWidth: true,
className: "components-font-size-picker__select",
label: (0,external_wp_i18n_namespaceObject.__)('Font size'),
hideLabelFromVision: true,
describedBy: (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: Currently selected font size.
(0,external_wp_i18n_namespaceObject.__)('Currently selected font size: %s'), selectedOption.name),
options: options,
value: selectedOption,
__experimentalShowSelectedHint: true,
onChange: _ref => {
let {
selectedItem
} = _ref;
if (selectedItem === CUSTOM_OPTION) {
onSelectCustom();
} else {
onChange(selectedItem.value);
}
},
size: size
});
};
/* harmony default export */ var font_size_picker_select = (FontSizePickerSelect);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toggle-group-control/toggle-group-control/styles.js
function toggle_group_control_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const ToggleGroupControl = _ref => {
let {
isBlock,
isDeselectable,
size
} = _ref;
return /*#__PURE__*/emotion_react_browser_esm_css("background:", COLORS.ui.background, ";border:1px solid transparent;border-radius:", config_values.controlBorderRadius, ";display:inline-flex;min-width:0;padding:2px;position:relative;transition:transform ", config_values.transitionDurationFastest, " linear;", reduceMotion('transition'), " ", toggleGroupControlSize(size), " ", !isDeselectable && enclosingBorders(isBlock), ";" + ( true ? "" : 0), true ? "" : 0);
};
const enclosingBorders = isBlock => {
const enclosingBorder = /*#__PURE__*/emotion_react_browser_esm_css("border-color:", COLORS.ui.border, ";" + ( true ? "" : 0), true ? "" : 0);
return /*#__PURE__*/emotion_react_browser_esm_css(isBlock && enclosingBorder, " &:hover{border-color:", COLORS.ui.borderHover, ";}&:focus-within{border-color:", COLORS.ui.borderFocus, ";box-shadow:", config_values.controlBoxShadowFocus, ";outline:none;z-index:1;}" + ( true ? "" : 0), true ? "" : 0);
};
const toggleGroupControlSize = size => {
const heights = {
default: '36px',
'__unstable-large': '40px'
};
return /*#__PURE__*/emotion_react_browser_esm_css("min-height:", heights[size], ";" + ( true ? "" : 0), true ? "" : 0);
};
const toggle_group_control_styles_block = true ? {
name: "7whenc",
styles: "display:flex;width:100%"
} : 0;
const BackdropView = createStyled("div", true ? {
target: "eakva831"
} : 0)("background:", COLORS.gray[900], ";border-radius:", config_values.controlBorderRadius, ";left:0;position:absolute;top:2px;bottom:2px;transition:transform ", config_values.transitionDurationFast, " ease;", reduceMotion('transition'), " z-index:1;" + ( true ? "" : 0));
const VisualLabelWrapper = createStyled("div", true ? {
target: "eakva830"
} : 0)( true ? {
name: "zjik7",
styles: "display:flex"
} : 0);
;// CONCATENATED MODULE: ./node_modules/reakit/es/Radio/RadioState.js
function useRadioState(initialState) {
if (initialState === void 0) {
initialState = {};
}
var _useSealedState = useSealedState(initialState),
initialValue = _useSealedState.state,
_useSealedState$loop = _useSealedState.loop,
loop = _useSealedState$loop === void 0 ? true : _useSealedState$loop,
sealed = _objectWithoutPropertiesLoose(_useSealedState, ["state", "loop"]);
var _React$useState = (0,external_React_.useState)(initialValue),
state = _React$useState[0],
setState = _React$useState[1];
var composite = useCompositeState(_objectSpread2(_objectSpread2({}, sealed), {}, {
loop: loop
}));
return _objectSpread2(_objectSpread2({}, composite), {}, {
state: state,
setState: setState
});
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/__keys-d251e56b.js
// Automatically generated
var RADIO_STATE_KEYS = ["baseId", "unstable_idCountRef", "unstable_virtual", "rtl", "orientation", "items", "groups", "currentId", "loop", "wrap", "shift", "unstable_moves", "unstable_hasActiveWidget", "unstable_includesBaseElement", "state", "setBaseId", "registerItem", "unregisterItem", "registerGroup", "unregisterGroup", "move", "next", "previous", "up", "down", "first", "last", "sort", "unstable_setVirtual", "setRTL", "setOrientation", "setCurrentId", "setLoop", "setWrap", "setShift", "reset", "unstable_setIncludesBaseElement", "unstable_setHasActiveWidget", "setState"];
var RADIO_KEYS = [].concat(RADIO_STATE_KEYS, ["value", "checked", "unstable_checkOnFocus"]);
var RADIO_GROUP_KEYS = RADIO_STATE_KEYS;
;// CONCATENATED MODULE: ./node_modules/reakit/es/Radio/RadioGroup.js
var useRadioGroup = createHook({
name: "RadioGroup",
compose: useComposite,
keys: RADIO_GROUP_KEYS,
useProps: function useProps(_, htmlProps) {
return _objectSpread2({
role: "radiogroup"
}, htmlProps);
}
});
var RadioGroup = createComponent({
as: "div",
useHook: useRadioGroup,
useCreateElement: function useCreateElement$1(type, props, children) {
false ? 0 : void 0;
return useCreateElement(type, props, children);
}
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toggle-group-control/toggle-group-control/toggle-group-control-backdrop.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ToggleGroupControlBackdrop(_ref) {
let {
containerRef,
containerWidth,
isAdaptiveWidth,
state
} = _ref;
const [left, setLeft] = (0,external_wp_element_namespaceObject.useState)(0);
const [width, setWidth] = (0,external_wp_element_namespaceObject.useState)(0);
const [canAnimate, setCanAnimate] = (0,external_wp_element_namespaceObject.useState)(false);
const [renderBackdrop, setRenderBackdrop] = (0,external_wp_element_namespaceObject.useState)(false);
(0,external_wp_element_namespaceObject.useEffect)(() => {
const containerNode = containerRef === null || containerRef === void 0 ? void 0 : containerRef.current;
if (!containerNode) return;
/**
* Workaround for Reakit
*/
const targetNode = containerNode.querySelector(`[data-value="${state}"]`);
setRenderBackdrop(!!targetNode);
if (!targetNode) {
return;
}
const computeDimensions = () => {
const {
width: offsetWidth,
x
} = targetNode.getBoundingClientRect();
const {
x: parentX
} = containerNode.getBoundingClientRect();
const borderWidth = 1;
const offsetLeft = x - parentX - borderWidth;
setLeft(offsetLeft);
setWidth(offsetWidth);
}; // Fix to make the component appear as expected inside popovers.
// If the targetNode width is 0 it means the element was not yet rendered we should allow
// some time for the render to happen.
// requestAnimationFrame instead of setTimeout with a small time does not seems to work.
const dimensionsRequestId = window.setTimeout(computeDimensions, 100);
let animationRequestId;
if (!canAnimate) {
animationRequestId = window.requestAnimationFrame(() => {
setCanAnimate(true);
});
}
return () => {
window.clearTimeout(dimensionsRequestId);
window.cancelAnimationFrame(animationRequestId);
};
}, [canAnimate, containerRef, containerWidth, state, isAdaptiveWidth]);
if (!renderBackdrop) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(BackdropView, {
role: "presentation",
style: {
transform: `translateX(${left}px)`,
transition: canAnimate ? undefined : 'none',
width
}
});
}
/* harmony default export */ var toggle_group_control_backdrop = ((0,external_wp_element_namespaceObject.memo)(ToggleGroupControlBackdrop));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toggle-group-control/context.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const ToggleGroupControlContext = (0,external_wp_element_namespaceObject.createContext)({});
const useToggleGroupControlContext = () => (0,external_wp_element_namespaceObject.useContext)(ToggleGroupControlContext);
/* harmony default export */ var toggle_group_control_context = (ToggleGroupControlContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toggle-group-control/toggle-group-control/as-radio-group.js
/**
* External dependencies
*/
// eslint-disable-next-line no-restricted-imports
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedToggleGroupControlAsRadioGroup(_ref, forwardedRef) {
let {
children,
isAdaptiveWidth,
label,
onChange,
size,
value,
...otherProps
} = _ref;
const containerRef = (0,external_wp_element_namespaceObject.useRef)();
const [resizeListener, sizes] = (0,external_wp_compose_namespaceObject.useResizeObserver)();
const baseId = (0,external_wp_compose_namespaceObject.useInstanceId)(ToggleGroupControlAsRadioGroup, 'toggle-group-control-as-radio-group').toString();
const radio = useRadioState({
baseId,
state: value
});
const previousValue = (0,external_wp_compose_namespaceObject.usePrevious)(value); // Propagate radio.state change.
use_update_effect(() => {
// Avoid calling onChange if radio state changed
// from incoming value.
if (previousValue !== radio.state) {
onChange(radio.state);
}
}, [radio.state]); // Sync incoming value with radio.state.
use_update_effect(() => {
if (value !== radio.state) {
radio.setState(value);
}
}, [value]);
return (0,external_wp_element_namespaceObject.createElement)(toggle_group_control_context.Provider, {
value: { ...radio,
isBlock: !isAdaptiveWidth,
size
}
}, (0,external_wp_element_namespaceObject.createElement)(RadioGroup, extends_extends({}, radio, {
"aria-label": label,
as: component
}, otherProps, {
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([containerRef, forwardedRef])
}), resizeListener, (0,external_wp_element_namespaceObject.createElement)(toggle_group_control_backdrop, {
state: radio.state,
containerRef: containerRef,
containerWidth: sizes.width,
isAdaptiveWidth: isAdaptiveWidth
}), children));
}
const ToggleGroupControlAsRadioGroup = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedToggleGroupControlAsRadioGroup);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toggle-group-control/toggle-group-control/as-button-group.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedToggleGroupControlAsButtonGroup(_ref, forwardedRef) {
let {
children,
isAdaptiveWidth,
label,
onChange,
size,
value,
...otherProps
} = _ref;
const containerRef = (0,external_wp_element_namespaceObject.useRef)();
const [resizeListener, sizes] = (0,external_wp_compose_namespaceObject.useResizeObserver)();
const baseId = (0,external_wp_compose_namespaceObject.useInstanceId)(ToggleGroupControlAsButtonGroup, 'toggle-group-control-as-button-group').toString();
const [selectedValue, setSelectedValue] = (0,external_wp_element_namespaceObject.useState)(value);
const groupContext = {
baseId,
state: selectedValue,
setState: setSelectedValue
};
const previousValue = (0,external_wp_compose_namespaceObject.usePrevious)(value); // Propagate groupContext.state change.
use_update_effect(() => {
// Avoid calling onChange if groupContext state changed
// from incoming value.
if (previousValue !== groupContext.state) {
onChange(groupContext.state);
}
}, [groupContext.state]); // Sync incoming value with groupContext.state.
use_update_effect(() => {
if (value !== groupContext.state) {
groupContext.setState(value);
}
}, [value]);
return (0,external_wp_element_namespaceObject.createElement)(toggle_group_control_context.Provider, {
value: { ...groupContext,
isBlock: !isAdaptiveWidth,
isDeselectable: true,
size
}
}, (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({
"aria-label": label
}, otherProps, {
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([containerRef, forwardedRef]),
role: "group"
}), resizeListener, (0,external_wp_element_namespaceObject.createElement)(toggle_group_control_backdrop, {
state: groupContext.state,
containerRef: containerRef,
containerWidth: sizes.width,
isAdaptiveWidth: isAdaptiveWidth
}), children));
}
const ToggleGroupControlAsButtonGroup = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedToggleGroupControlAsButtonGroup);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toggle-group-control/toggle-group-control/component.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const component_noop = () => {};
function UnconnectedToggleGroupControl(props, forwardedRef) {
const {
__nextHasNoMarginBottom = false,
className,
isAdaptiveWidth = false,
isBlock = false,
isDeselectable = false,
label,
hideLabelFromVision = false,
help,
onChange = component_noop,
size = 'default',
value,
children,
...otherProps
} = useContextSystem(props, 'ToggleGroupControl');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => cx(ToggleGroupControl({
isBlock,
isDeselectable,
size
}), isBlock && toggle_group_control_styles_block, className), [className, cx, isBlock, isDeselectable, size]);
const MainControl = isDeselectable ? ToggleGroupControlAsButtonGroup : ToggleGroupControlAsRadioGroup;
return (0,external_wp_element_namespaceObject.createElement)(base_control, {
help: help,
__nextHasNoMarginBottom: __nextHasNoMarginBottom
}, !hideLabelFromVision && (0,external_wp_element_namespaceObject.createElement)(VisualLabelWrapper, null, (0,external_wp_element_namespaceObject.createElement)(base_control.VisualLabel, null, label)), (0,external_wp_element_namespaceObject.createElement)(MainControl, extends_extends({}, otherProps, {
children: children,
className: classes,
isAdaptiveWidth: isAdaptiveWidth,
label: label,
onChange: onChange,
ref: forwardedRef,
size: size,
value: value
})));
}
/**
* `ToggleGroupControl` is a form component that lets users choose options
* represented in horizontal segments. To render options for this control use
* `ToggleGroupControlOption` component.
*
* This component is intended for selecting a single persistent value from a set of options,
* similar to a how a radio button group would work. If you simply want a toggle to switch between views,
* use a `TabPanel` instead.
*
* Only use this control when you know for sure the labels of items inside won't
* wrap. For items with longer labels, you can consider a `SelectControl` or a
* `CustomSelectControl` component instead.
*
* ```jsx
* import {
* __experimentalToggleGroupControl as ToggleGroupControl,
* __experimentalToggleGroupControlOption as ToggleGroupControlOption,
* } from '@wordpress/components';
*
* function Example() {
* return (
* <ToggleGroupControl label="my label" value="vertical" isBlock>
* <ToggleGroupControlOption value="horizontal" label="Horizontal" />
* <ToggleGroupControlOption value="vertical" label="Vertical" />
* </ToggleGroupControl>
* );
* }
* ```
*/
const component_ToggleGroupControl = contextConnect(UnconnectedToggleGroupControl, 'ToggleGroupControl');
/* harmony default export */ var toggle_group_control_component = (component_ToggleGroupControl);
;// CONCATENATED MODULE: ./node_modules/reakit/es/Radio/Radio.js
function getChecked(options) {
if (typeof options.checked !== "undefined") {
return options.checked;
}
return typeof options.value !== "undefined" && options.state === options.value;
}
function useInitialChecked(options) {
var _React$useState = (0,external_React_.useState)(function () {
return getChecked(options);
}),
initialChecked = _React$useState[0];
var _React$useState2 = (0,external_React_.useState)(options.currentId),
initialCurrentId = _React$useState2[0];
var id = options.id,
setCurrentId = options.setCurrentId;
(0,external_React_.useEffect)(function () {
if (initialChecked && id && initialCurrentId !== id) {
setCurrentId === null || setCurrentId === void 0 ? void 0 : setCurrentId(id);
}
}, [initialChecked, id, setCurrentId, initialCurrentId]);
}
function fireChange(element, onChange) {
var event = createEvent(element, "change");
Object.defineProperties(event, {
type: {
value: "change"
},
target: {
value: element
},
currentTarget: {
value: element
}
});
onChange === null || onChange === void 0 ? void 0 : onChange(event);
}
var useRadio = createHook({
name: "Radio",
compose: useCompositeItem,
keys: RADIO_KEYS,
useOptions: function useOptions(_ref, _ref2) {
var _options$value;
var value = _ref2.value,
checked = _ref2.checked;
var _ref$unstable_clickOn = _ref.unstable_clickOnEnter,
unstable_clickOnEnter = _ref$unstable_clickOn === void 0 ? false : _ref$unstable_clickOn,
_ref$unstable_checkOn = _ref.unstable_checkOnFocus,
unstable_checkOnFocus = _ref$unstable_checkOn === void 0 ? true : _ref$unstable_checkOn,
options = _objectWithoutPropertiesLoose(_ref, ["unstable_clickOnEnter", "unstable_checkOnFocus"]);
return _objectSpread2(_objectSpread2({
checked: checked,
unstable_clickOnEnter: unstable_clickOnEnter,
unstable_checkOnFocus: unstable_checkOnFocus
}, options), {}, {
value: (_options$value = options.value) != null ? _options$value : value
});
},
useProps: function useProps(options, _ref3) {
var htmlRef = _ref3.ref,
htmlOnChange = _ref3.onChange,
htmlOnClick = _ref3.onClick,
htmlProps = _objectWithoutPropertiesLoose(_ref3, ["ref", "onChange", "onClick"]);
var ref = (0,external_React_.useRef)(null);
var _React$useState3 = (0,external_React_.useState)(true),
isNativeRadio = _React$useState3[0],
setIsNativeRadio = _React$useState3[1];
var checked = getChecked(options);
var isCurrentItemRef = useLiveRef(options.currentId === options.id);
var onChangeRef = useLiveRef(htmlOnChange);
var onClickRef = useLiveRef(htmlOnClick);
useInitialChecked(options);
(0,external_React_.useEffect)(function () {
var element = ref.current;
if (!element) {
false ? 0 : void 0;
return;
}
if (element.tagName !== "INPUT" || element.type !== "radio") {
setIsNativeRadio(false);
}
}, []);
var onChange = (0,external_React_.useCallback)(function (event) {
var _onChangeRef$current, _options$setState;
(_onChangeRef$current = onChangeRef.current) === null || _onChangeRef$current === void 0 ? void 0 : _onChangeRef$current.call(onChangeRef, event);
if (event.defaultPrevented) return;
if (options.disabled) return;
(_options$setState = options.setState) === null || _options$setState === void 0 ? void 0 : _options$setState.call(options, options.value);
}, [options.disabled, options.setState, options.value]);
var onClick = (0,external_React_.useCallback)(function (event) {
var _onClickRef$current;
(_onClickRef$current = onClickRef.current) === null || _onClickRef$current === void 0 ? void 0 : _onClickRef$current.call(onClickRef, event);
if (event.defaultPrevented) return;
if (isNativeRadio) return;
fireChange(event.currentTarget, onChange);
}, [onChange, isNativeRadio]);
(0,external_React_.useEffect)(function () {
var element = ref.current;
if (!element) return;
if (options.unstable_moves && isCurrentItemRef.current && options.unstable_checkOnFocus) {
fireChange(element, onChange);
}
}, [options.unstable_moves, options.unstable_checkOnFocus, onChange]);
return _objectSpread2({
ref: useForkRef(ref, htmlRef),
role: !isNativeRadio ? "radio" : undefined,
type: isNativeRadio ? "radio" : undefined,
value: isNativeRadio ? options.value : undefined,
name: isNativeRadio ? options.baseId : undefined,
"aria-checked": checked,
checked: checked,
onChange: onChange,
onClick: onClick
}, htmlProps);
}
});
var Radio = createComponent({
as: "input",
memo: true,
useHook: useRadio
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toggle-group-control/toggle-group-control-option-base/styles.js
function toggle_group_control_option_base_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const LabelView = createStyled("div", true ? {
target: "et6ln9s1"
} : 0)( true ? {
name: "sln1fl",
styles: "display:inline-flex;max-width:100%;min-width:0;position:relative"
} : 0);
const labelBlock = true ? {
name: "82a6rk",
styles: "flex:1"
} : 0;
const buttonView = _ref => {
let {
isDeselectable,
isIcon,
isPressed,
size
} = _ref;
return /*#__PURE__*/emotion_react_browser_esm_css("align-items:center;appearance:none;background:transparent;border:none;border-radius:", config_values.controlBorderRadius, ";color:", COLORS.gray[700], ";fill:currentColor;cursor:pointer;display:flex;font-family:inherit;height:100%;justify-content:center;line-height:100%;outline:none;padding:0 12px;position:relative;text-align:center;transition:background ", config_values.transitionDurationFast, " linear,color ", config_values.transitionDurationFast, " linear,font-weight 60ms linear;", reduceMotion('transition'), " user-select:none;width:100%;z-index:2;&::-moz-focus-inner{border:0;}&:active{background:", config_values.toggleGroupControlBackgroundColor, ";}", isDeselectable && deselectable, " ", isIcon && isIconStyles({
size
}), " ", isPressed && pressed, ";" + ( true ? "" : 0), true ? "" : 0);
};
const pressed = /*#__PURE__*/emotion_react_browser_esm_css("color:", COLORS.white, ";&:active{background:transparent;}" + ( true ? "" : 0), true ? "" : 0);
const deselectable = /*#__PURE__*/emotion_react_browser_esm_css("color:", COLORS.gray[900], ";&:focus{box-shadow:inset 0 0 0 1px ", COLORS.white, ",0 0 0 ", config_values.borderWidthFocus, " ", COLORS.ui.theme, ";outline:2px solid transparent;}" + ( true ? "" : 0), true ? "" : 0);
const ButtonContentView = createStyled("div", true ? {
target: "et6ln9s0"
} : 0)("display:flex;font-size:", config_values.fontSize, ";line-height:1;" + ( true ? "" : 0));
const isIconStyles = _ref2 => {
let {
size = 'default'
} = _ref2;
const iconButtonSizes = {
default: '30px',
'__unstable-large': '34px'
};
return /*#__PURE__*/emotion_react_browser_esm_css("color:", COLORS.gray[900], ";width:", iconButtonSizes[size], ";padding-left:0;padding-right:0;" + ( true ? "" : 0), true ? "" : 0);
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toggle-group-control/toggle-group-control-option-base/component.js
/**
* External dependencies
*/
// eslint-disable-next-line no-restricted-imports
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const {
ButtonContentView: component_ButtonContentView,
LabelView: component_LabelView
} = toggle_group_control_option_base_styles_namespaceObject;
const WithToolTip = _ref => {
let {
showTooltip,
text,
children
} = _ref;
if (showTooltip && text) {
return (0,external_wp_element_namespaceObject.createElement)(tooltip, {
text: text,
position: "top center"
}, children);
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, children);
};
function ToggleGroupControlOptionBase(props, forwardedRef) {
const toggleGroupControlContext = useToggleGroupControlContext();
const id = (0,external_wp_compose_namespaceObject.useInstanceId)(ToggleGroupControlOptionBase, toggleGroupControlContext.baseId || 'toggle-group-control-option-base');
const buttonProps = useContextSystem({ ...props,
id
}, 'ToggleGroupControlOptionBase');
const {
isBlock = false,
isDeselectable = false,
size = 'default',
...otherContextProps
/* context props for Ariakit Radio */
} = toggleGroupControlContext;
const {
className,
isIcon = false,
value,
children,
showTooltip = false,
...otherButtonProps
} = buttonProps;
const isPressed = otherContextProps.state === value;
const cx = useCx();
const labelViewClasses = cx(isBlock && labelBlock);
const classes = cx(buttonView({
isDeselectable,
isIcon,
isPressed,
size
}), className);
const buttonOnClick = () => {
if (isDeselectable && isPressed) {
otherContextProps.setState(undefined);
} else {
otherContextProps.setState(value);
}
};
const commonProps = { ...otherButtonProps,
className: classes,
'data-value': value,
ref: forwardedRef
};
return (0,external_wp_element_namespaceObject.createElement)(component_LabelView, {
className: labelViewClasses
}, (0,external_wp_element_namespaceObject.createElement)(WithToolTip, {
showTooltip: showTooltip,
text: otherButtonProps['aria-label']
}, isDeselectable ? (0,external_wp_element_namespaceObject.createElement)("button", extends_extends({}, commonProps, {
"aria-pressed": isPressed,
type: "button",
onClick: buttonOnClick
}), (0,external_wp_element_namespaceObject.createElement)(component_ButtonContentView, null, children)) : (0,external_wp_element_namespaceObject.createElement)(Radio, extends_extends({}, commonProps, otherContextProps
/* these are only for Ariakit Radio */
, {
as: "button",
value: value
}), (0,external_wp_element_namespaceObject.createElement)(component_ButtonContentView, null, children))));
}
/**
* `ToggleGroupControlOptionBase` is a form component and is meant to be used as an internal,
* generic component for any children of `ToggleGroupControl`.
*
* @example
* ```jsx
* import {
* __experimentalToggleGroupControl as ToggleGroupControl,
* __experimentalToggleGroupControlOptionBase as ToggleGroupControlOptionBase,
* } from '@wordpress/components';
*
* function Example() {
* return (
* <ToggleGroupControl label="my label" value="vertical" isBlock>
* <ToggleGroupControlOption value="horizontal" label="Horizontal" />
* <ToggleGroupControlOption value="vertical" label="Vertical" />
* </ToggleGroupControl>
* );
* }
* ```
*/
const ConnectedToggleGroupControlOptionBase = contextConnect(ToggleGroupControlOptionBase, 'ToggleGroupControlOptionBase');
/* harmony default export */ var toggle_group_control_option_base_component = (ConnectedToggleGroupControlOptionBase);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toggle-group-control/toggle-group-control-option/component.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedToggleGroupControlOption(props, ref) {
const {
label,
...restProps
} = props;
const optionLabel = restProps['aria-label'] || label;
return (0,external_wp_element_namespaceObject.createElement)(toggle_group_control_option_base_component, extends_extends({}, restProps, {
"aria-label": optionLabel,
ref: ref
}), label);
}
/**
* `ToggleGroupControlOption` is a form component and is meant to be used as a
* child of `ToggleGroupControl`.
*
* ```jsx
* import {
* __experimentalToggleGroupControl as ToggleGroupControl,
* __experimentalToggleGroupControlOption as ToggleGroupControlOption,
* } from '@wordpress/components';
*
* function Example() {
* return (
* <ToggleGroupControl label="my label" value="vertical" isBlock>
* <ToggleGroupControlOption value="horizontal" label="Horizontal" />
* <ToggleGroupControlOption value="vertical" label="Vertical" />
* </ToggleGroupControl>
* );
* }
* ```
*/
const ToggleGroupControlOption = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedToggleGroupControlOption);
/* harmony default export */ var toggle_group_control_option_component = (ToggleGroupControlOption);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/font-size-picker/constants.js
/**
* WordPress dependencies
*/
/**
* List of T-shirt abbreviations.
*
* When there are 5 font sizes or fewer, we assume that the font sizes are
* ordered by size and show T-shirt labels.
*/
const T_SHIRT_ABBREVIATIONS = [
/* translators: S stands for 'small' and is a size label. */
(0,external_wp_i18n_namespaceObject.__)('S'),
/* translators: M stands for 'medium' and is a size label. */
(0,external_wp_i18n_namespaceObject.__)('M'),
/* translators: L stands for 'large' and is a size label. */
(0,external_wp_i18n_namespaceObject.__)('L'),
/* translators: XL stands for 'extra large' and is a size label. */
(0,external_wp_i18n_namespaceObject.__)('XL'),
/* translators: XXL stands for 'extra extra large' and is a size label. */
(0,external_wp_i18n_namespaceObject.__)('XXL')];
/**
* List of T-shirt names.
*
* When there are 5 font sizes or fewer, we assume that the font sizes are
* ordered by size and show T-shirt labels.
*/
const T_SHIRT_NAMES = [(0,external_wp_i18n_namespaceObject.__)('Small'), (0,external_wp_i18n_namespaceObject.__)('Medium'), (0,external_wp_i18n_namespaceObject.__)('Large'), (0,external_wp_i18n_namespaceObject.__)('Extra Large'), (0,external_wp_i18n_namespaceObject.__)('Extra Extra Large')];
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/font-size-picker/font-size-picker-toggle-group.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const FontSizePickerToggleGroup = props => {
const {
fontSizes,
value,
__nextHasNoMarginBottom,
size,
onChange
} = props;
return (0,external_wp_element_namespaceObject.createElement)(toggle_group_control_component, {
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
label: (0,external_wp_i18n_namespaceObject.__)('Font size'),
hideLabelFromVision: true,
value: value,
onChange: onChange,
isBlock: true,
size: size
}, fontSizes.map((fontSize, index) => (0,external_wp_element_namespaceObject.createElement)(toggle_group_control_option_component, {
key: fontSize.slug,
value: fontSize.size,
label: T_SHIRT_ABBREVIATIONS[index],
"aria-label": fontSize.name || T_SHIRT_NAMES[index],
showTooltip: true
})));
};
/* harmony default export */ var font_size_picker_toggle_group = (FontSizePickerToggleGroup);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/font-size-picker/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const UnforwardedFontSizePicker = (props, ref) => {
var _fontSizes$;
const {
/** Start opting into the new margin-free styles that will become the default in a future version. */
__nextHasNoMarginBottom = false,
fallbackFontSize,
fontSizes = [],
disableCustomFontSizes = false,
onChange,
size = 'default',
value,
withSlider = false,
withReset = true
} = props;
if (!__nextHasNoMarginBottom) {
external_wp_deprecated_default()('Bottom margin styles for wp.components.FontSizePicker', {
since: '6.1',
version: '6.4',
hint: 'Set the `__nextHasNoMarginBottom` prop to true to start opting into the new styles, which will become the default in a future version.'
});
}
const units = useCustomUnits({
availableUnits: ['px', 'em', 'rem']
});
const shouldUseSelectControl = fontSizes.length > 5;
const selectedFontSize = fontSizes.find(fontSize => fontSize.size === value);
const isCustomValue = !!value && !selectedFontSize;
const [showCustomValueControl, setShowCustomValueControl] = (0,external_wp_element_namespaceObject.useState)(!disableCustomFontSizes && isCustomValue);
const headerHint = (0,external_wp_element_namespaceObject.useMemo)(() => {
if (showCustomValueControl) {
return (0,external_wp_i18n_namespaceObject.__)('Custom');
}
if (!shouldUseSelectControl) {
if (selectedFontSize) {
return selectedFontSize.name || T_SHIRT_NAMES[fontSizes.indexOf(selectedFontSize)];
}
return '';
}
const commonUnit = getCommonSizeUnit(fontSizes);
if (commonUnit) {
return `(${commonUnit})`;
}
return '';
}, [showCustomValueControl, shouldUseSelectControl, selectedFontSize, fontSizes]);
if (fontSizes.length === 0 && disableCustomFontSizes) {
return null;
} // If neither the value or first font size is a string, then FontSizePicker
// operates in a legacy "unitless" mode where UnitControl can only be used
// to select px values and onChange() is always called with number values.
const hasUnits = typeof value === 'string' || typeof ((_fontSizes$ = fontSizes[0]) === null || _fontSizes$ === void 0 ? void 0 : _fontSizes$.size) === 'string';
const [valueQuantity, valueUnit] = parseQuantityAndUnitFromRawValue(value, units);
const isValueUnitRelative = !!valueUnit && ['em', 'rem'].includes(valueUnit);
return (0,external_wp_element_namespaceObject.createElement)(styles_Container, {
ref: ref,
className: "components-font-size-picker"
}, (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, {
as: "legend"
}, (0,external_wp_i18n_namespaceObject.__)('Font size')), (0,external_wp_element_namespaceObject.createElement)(spacer_component, null, (0,external_wp_element_namespaceObject.createElement)(h_stack_component, {
className: "components-font-size-picker__header"
}, (0,external_wp_element_namespaceObject.createElement)(HeaderLabel, {
"aria-label": `${(0,external_wp_i18n_namespaceObject.__)('Size')} ${headerHint || ''}`
}, (0,external_wp_i18n_namespaceObject.__)('Size'), headerHint && (0,external_wp_element_namespaceObject.createElement)(HeaderHint, {
className: "components-font-size-picker__header__hint"
}, headerHint)), !disableCustomFontSizes && (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
label: showCustomValueControl ? (0,external_wp_i18n_namespaceObject.__)('Use size preset') : (0,external_wp_i18n_namespaceObject.__)('Set custom size'),
icon: library_settings,
onClick: () => {
setShowCustomValueControl(!showCustomValueControl);
},
isPressed: showCustomValueControl,
isSmall: true
}))), (0,external_wp_element_namespaceObject.createElement)(Controls, {
className: "components-font-size-picker__controls",
__nextHasNoMarginBottom: __nextHasNoMarginBottom
}, !!fontSizes.length && shouldUseSelectControl && !showCustomValueControl && (0,external_wp_element_namespaceObject.createElement)(font_size_picker_select, {
fontSizes: fontSizes,
value: value,
disableCustomFontSizes: disableCustomFontSizes,
size: size,
onChange: newValue => {
if (newValue === undefined) {
onChange === null || onChange === void 0 ? void 0 : onChange(undefined);
} else {
onChange === null || onChange === void 0 ? void 0 : onChange(hasUnits ? newValue : Number(newValue), fontSizes.find(fontSize => fontSize.size === newValue));
}
},
onSelectCustom: () => setShowCustomValueControl(true)
}), !shouldUseSelectControl && !showCustomValueControl && (0,external_wp_element_namespaceObject.createElement)(font_size_picker_toggle_group, {
fontSizes: fontSizes,
value: value,
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
size: size,
onChange: newValue => {
if (newValue === undefined) {
onChange === null || onChange === void 0 ? void 0 : onChange(undefined);
} else {
onChange === null || onChange === void 0 ? void 0 : onChange(hasUnits ? newValue : Number(newValue), fontSizes.find(fontSize => fontSize.size === newValue));
}
}
}), !disableCustomFontSizes && showCustomValueControl && (0,external_wp_element_namespaceObject.createElement)(flex_component, {
className: "components-font-size-picker__custom-size-control"
}, (0,external_wp_element_namespaceObject.createElement)(flex_item_component, {
isBlock: true
}, (0,external_wp_element_namespaceObject.createElement)(unit_control, {
label: (0,external_wp_i18n_namespaceObject.__)('Custom'),
labelPosition: "top",
hideLabelFromVision: true,
value: value,
onChange: newValue => {
if (newValue === undefined) {
onChange === null || onChange === void 0 ? void 0 : onChange(undefined);
} else {
onChange === null || onChange === void 0 ? void 0 : onChange(hasUnits ? newValue : parseInt(newValue, 10));
}
},
size: size,
units: hasUnits ? units : [],
min: 0
})), withSlider && (0,external_wp_element_namespaceObject.createElement)(flex_item_component, {
isBlock: true
}, (0,external_wp_element_namespaceObject.createElement)(spacer_component, {
marginX: 2,
marginBottom: 0
}, (0,external_wp_element_namespaceObject.createElement)(range_control, {
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
className: "components-font-size-picker__custom-input",
label: (0,external_wp_i18n_namespaceObject.__)('Custom Size'),
hideLabelFromVision: true,
value: valueQuantity,
initialPosition: fallbackFontSize,
withInputField: false,
onChange: newValue => {
if (newValue === undefined) {
onChange === null || onChange === void 0 ? void 0 : onChange(undefined);
} else if (hasUnits) {
onChange === null || onChange === void 0 ? void 0 : onChange(newValue + (valueUnit !== null && valueUnit !== void 0 ? valueUnit : 'px'));
} else {
onChange === null || onChange === void 0 ? void 0 : onChange(newValue);
}
},
min: 0,
max: isValueUnitRelative ? 10 : 100,
step: isValueUnitRelative ? 0.1 : 1
}))), withReset && (0,external_wp_element_namespaceObject.createElement)(flex_item_component, null, (0,external_wp_element_namespaceObject.createElement)(ResetButton, {
disabled: value === undefined,
onClick: () => {
onChange === null || onChange === void 0 ? void 0 : onChange(undefined);
},
isSmall: true,
variant: "secondary",
size: size
}, (0,external_wp_i18n_namespaceObject.__)('Reset'))))));
};
const FontSizePicker = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedFontSizePicker);
/* harmony default export */ var font_size_picker = (FontSizePicker);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/form-file-upload/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* FormFileUpload is a component that allows users to select files from their local device.
*
* ```jsx
* import { FormFileUpload } from '@wordpress/components';
*
* const MyFormFileUpload = () => (
* <FormFileUpload
* accept="image/*"
* onChange={ ( event ) => console.log( event.currentTarget.files ) }
* >
* Upload
* </FormFileUpload>
* );
* ```
*/
function FormFileUpload(_ref) {
let {
accept,
children,
multiple = false,
onChange,
onClick,
render,
...props
} = _ref;
const ref = (0,external_wp_element_namespaceObject.useRef)(null);
const openFileDialog = () => {
var _ref$current;
(_ref$current = ref.current) === null || _ref$current === void 0 ? void 0 : _ref$current.click();
};
const ui = render ? render({
openFileDialog
}) : (0,external_wp_element_namespaceObject.createElement)(build_module_button, extends_extends({
onClick: openFileDialog
}, props), children);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-form-file-upload"
}, ui, (0,external_wp_element_namespaceObject.createElement)("input", {
type: "file",
ref: ref,
multiple: multiple,
style: {
display: 'none'
},
accept: accept,
onChange: onChange,
onClick: onClick,
"data-testid": "form-file-upload-input"
}));
}
/* harmony default export */ var form_file_upload = (FormFileUpload);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/form-toggle/index.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const form_toggle_noop = () => {};
/**
* FormToggle switches a single setting on or off.
*
* ```jsx
* import { FormToggle } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyFormToggle = () => {
* const [ isChecked, setChecked ] = useState( true );
*
* return (
* <FormToggle
* checked={ isChecked }
* onChange={ () => setChecked( ( state ) => ! state ) }
* />
* );
* };
* ```
*/
function FormToggle(props) {
const {
className,
checked,
id,
disabled,
onChange = form_toggle_noop,
...additionalProps
} = props;
const wrapperClasses = classnames_default()('components-form-toggle', className, {
'is-checked': checked,
'is-disabled': disabled
});
return (0,external_wp_element_namespaceObject.createElement)("span", {
className: wrapperClasses
}, (0,external_wp_element_namespaceObject.createElement)("input", extends_extends({
className: "components-form-toggle__input",
id: id,
type: "checkbox",
checked: checked,
onChange: onChange,
disabled: disabled
}, additionalProps)), (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-form-toggle__track"
}), (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-form-toggle__thumb"
}));
}
/* harmony default export */ var form_toggle = (FormToggle);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/form-token-field/token.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const token_noop = () => {};
function Token(_ref) {
let {
value,
status,
title,
displayTransform,
isBorderless = false,
disabled = false,
onClickRemove = token_noop,
onMouseEnter,
onMouseLeave,
messages,
termPosition,
termsCount
} = _ref;
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(Token);
const tokenClasses = classnames_default()('components-form-token-field__token', {
'is-error': 'error' === status,
'is-success': 'success' === status,
'is-validating': 'validating' === status,
'is-borderless': isBorderless,
'is-disabled': disabled
});
const onClick = () => onClickRemove({
value
});
const transformedValue = displayTransform(value);
const termPositionAndCount = (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: 1: term name, 2: term position in a set of terms, 3: total term set count. */
(0,external_wp_i18n_namespaceObject.__)('%1$s (%2$s of %3$s)'), transformedValue, termPosition, termsCount);
return (0,external_wp_element_namespaceObject.createElement)("span", {
className: tokenClasses,
onMouseEnter: onMouseEnter,
onMouseLeave: onMouseLeave,
title: title
}, (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-form-token-field__token-text",
id: `components-form-token-field__token-text-${instanceId}`
}, (0,external_wp_element_namespaceObject.createElement)(visually_hidden_component, {
as: "span"
}, termPositionAndCount), (0,external_wp_element_namespaceObject.createElement)("span", {
"aria-hidden": "true"
}, transformedValue)), (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-form-token-field__remove-token",
icon: close_small,
onClick: !disabled ? onClick : undefined,
label: messages.remove,
"aria-describedby": `components-form-token-field__token-text-${instanceId}`
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/form-token-field/styles.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const deprecatedPaddings = _ref => {
let {
__next36pxDefaultSize,
hasTokens
} = _ref;
return !__next36pxDefaultSize && /*#__PURE__*/emotion_react_browser_esm_css("padding-top:", space(hasTokens ? 1 : 0.5), ";padding-bottom:", space(hasTokens ? 1 : 0.5), ";" + ( true ? "" : 0), true ? "" : 0);
};
const TokensAndInputWrapperFlex = /*#__PURE__*/createStyled(flex_component, true ? {
target: "ehq8nmi0"
} : 0)("padding:5px ", space(1), ";", deprecatedPaddings, ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/form-token-field/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const form_token_field_identity = value => value;
/**
* A `FormTokenField` is a field similar to the tags and categories fields in the interim editor chrome,
* or the "to" field in Mail on OS X. Tokens can be entered by typing them or selecting them from a list of suggested tokens.
*
* Up to one hundred suggestions that match what the user has typed so far will be shown from which the user can pick from (auto-complete).
* Tokens are separated by the "," character. Suggestions can be selected with the up or down arrows and added with the tab or enter key.
*
* The `value` property is handled in a manner similar to controlled form components.
* See [Forms](http://facebook.github.io/react/docs/forms.html) in the React Documentation for more information.
*/
function FormTokenField(props) {
const {
autoCapitalize,
autoComplete,
maxLength,
placeholder,
label = (0,external_wp_i18n_namespaceObject.__)('Add item'),
className,
suggestions = [],
maxSuggestions = 100,
value = [],
displayTransform = form_token_field_identity,
saveTransform = token => token.trim(),
onChange = () => {},
onInputChange = () => {},
onFocus = undefined,
isBorderless = false,
disabled = false,
tokenizeOnSpace = false,
messages = {
added: (0,external_wp_i18n_namespaceObject.__)('Item added.'),
removed: (0,external_wp_i18n_namespaceObject.__)('Item removed.'),
remove: (0,external_wp_i18n_namespaceObject.__)('Remove item'),
__experimentalInvalid: (0,external_wp_i18n_namespaceObject.__)('Invalid item')
},
__experimentalRenderItem,
__experimentalExpandOnFocus = false,
__experimentalValidateInput = () => true,
__experimentalShowHowTo = true,
__next36pxDefaultSize = false,
__experimentalAutoSelectFirstMatch = false
} = props;
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(FormTokenField); // We reset to these initial values again in the onBlur
const [incompleteTokenValue, setIncompleteTokenValue] = (0,external_wp_element_namespaceObject.useState)('');
const [inputOffsetFromEnd, setInputOffsetFromEnd] = (0,external_wp_element_namespaceObject.useState)(0);
const [isActive, setIsActive] = (0,external_wp_element_namespaceObject.useState)(false);
const [isExpanded, setIsExpanded] = (0,external_wp_element_namespaceObject.useState)(false);
const [selectedSuggestionIndex, setSelectedSuggestionIndex] = (0,external_wp_element_namespaceObject.useState)(-1);
const [selectedSuggestionScroll, setSelectedSuggestionScroll] = (0,external_wp_element_namespaceObject.useState)(false);
const prevSuggestions = (0,external_wp_compose_namespaceObject.usePrevious)(suggestions);
const prevValue = (0,external_wp_compose_namespaceObject.usePrevious)(value);
const input = (0,external_wp_element_namespaceObject.useRef)(null);
const tokensAndInput = (0,external_wp_element_namespaceObject.useRef)(null);
const debouncedSpeak = (0,external_wp_compose_namespaceObject.useDebounce)(external_wp_a11y_namespaceObject.speak, 500);
(0,external_wp_element_namespaceObject.useEffect)(() => {
// Make sure to focus the input when the isActive state is true.
if (isActive && !hasFocus()) {
focus();
}
}, [isActive]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
const suggestionsDidUpdate = !external_wp_isShallowEqual_default()(suggestions, prevSuggestions || []);
if (suggestionsDidUpdate || value !== prevValue) {
updateSuggestions(suggestionsDidUpdate);
} // TODO: updateSuggestions() should first be refactored so its actual deps are clearer.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [suggestions, prevSuggestions, value, prevValue]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
updateSuggestions(); // eslint-disable-next-line react-hooks/exhaustive-deps
}, [incompleteTokenValue]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
updateSuggestions(); // eslint-disable-next-line react-hooks/exhaustive-deps
}, [__experimentalAutoSelectFirstMatch]);
if (disabled && isActive) {
setIsActive(false);
setIncompleteTokenValue('');
}
function focus() {
var _input$current;
(_input$current = input.current) === null || _input$current === void 0 ? void 0 : _input$current.focus();
}
function hasFocus() {
var _input$current2;
return input.current === ((_input$current2 = input.current) === null || _input$current2 === void 0 ? void 0 : _input$current2.ownerDocument.activeElement);
}
function onFocusHandler(event) {
// If focus is on the input or on the container, set the isActive state to true.
if (hasFocus() || event.target === tokensAndInput.current) {
setIsActive(true);
setIsExpanded(__experimentalExpandOnFocus || isExpanded);
} else {
/*
* Otherwise, focus is on one of the token "remove" buttons and we
* set the isActive state to false to prevent the input to be
* re-focused, see componentDidUpdate().
*/
setIsActive(false);
}
if ('function' === typeof onFocus) {
onFocus(event);
}
}
function onBlur() {
if (inputHasValidValue()) {
setIsActive(false);
} else {
// Reset to initial state
setIncompleteTokenValue('');
setInputOffsetFromEnd(0);
setIsActive(false);
setIsExpanded(false);
setSelectedSuggestionIndex(-1);
setSelectedSuggestionScroll(false);
}
}
function onKeyDown(event) {
let preventDefault = false;
if (event.defaultPrevented || // Ignore keydowns from IMEs
event.nativeEvent.isComposing || // Workaround for Mac Safari where the final Enter/Backspace of an IME composition
// is `isComposing=false`, even though it's technically still part of the composition.
// These can only be detected by keyCode.
event.keyCode === 229) {
return;
}
switch (event.key) {
case 'Backspace':
preventDefault = handleDeleteKey(deleteTokenBeforeInput);
break;
case 'Enter':
preventDefault = addCurrentToken();
break;
case 'ArrowLeft':
preventDefault = handleLeftArrowKey();
break;
case 'ArrowUp':
preventDefault = handleUpArrowKey();
break;
case 'ArrowRight':
preventDefault = handleRightArrowKey();
break;
case 'ArrowDown':
preventDefault = handleDownArrowKey();
break;
case 'Delete':
preventDefault = handleDeleteKey(deleteTokenAfterInput);
break;
case 'Space':
if (tokenizeOnSpace) {
preventDefault = addCurrentToken();
}
break;
case 'Escape':
preventDefault = handleEscapeKey(event);
break;
default:
break;
}
if (preventDefault) {
event.preventDefault();
}
}
function onKeyPress(event) {
let preventDefault = false;
switch (event.key) {
case ',':
preventDefault = handleCommaKey();
break;
default:
break;
}
if (preventDefault) {
event.preventDefault();
}
}
function onContainerTouched(event) {
// Prevent clicking/touching the tokensAndInput container from blurring
// the input and adding the current token.
if (event.target === tokensAndInput.current && isActive) {
event.preventDefault();
}
}
function onTokenClickRemove(event) {
deleteToken(event.value);
focus();
}
function onSuggestionHovered(suggestion) {
const index = getMatchingSuggestions().indexOf(suggestion);
if (index >= 0) {
setSelectedSuggestionIndex(index);
setSelectedSuggestionScroll(false);
}
}
function onSuggestionSelected(suggestion) {
addNewToken(suggestion);
}
function onInputChangeHandler(event) {
const text = event.value;
const separator = tokenizeOnSpace ? /[ ,\t]+/ : /[,\t]+/;
const items = text.split(separator);
const tokenValue = items[items.length - 1] || '';
if (items.length > 1) {
addNewTokens(items.slice(0, -1));
}
setIncompleteTokenValue(tokenValue);
onInputChange(tokenValue);
}
function handleDeleteKey(_deleteToken) {
let preventDefault = false;
if (hasFocus() && isInputEmpty()) {
_deleteToken();
preventDefault = true;
}
return preventDefault;
}
function handleLeftArrowKey() {
let preventDefault = false;
if (isInputEmpty()) {
moveInputBeforePreviousToken();
preventDefault = true;
}
return preventDefault;
}
function handleRightArrowKey() {
let preventDefault = false;
if (isInputEmpty()) {
moveInputAfterNextToken();
preventDefault = true;
}
return preventDefault;
}
function handleUpArrowKey() {
setSelectedSuggestionIndex(index => {
return (index === 0 ? getMatchingSuggestions(incompleteTokenValue, suggestions, value, maxSuggestions, saveTransform).length : index) - 1;
});
setSelectedSuggestionScroll(true);
return true; // PreventDefault.
}
function handleDownArrowKey() {
setSelectedSuggestionIndex(index => {
return (index + 1) % getMatchingSuggestions(incompleteTokenValue, suggestions, value, maxSuggestions, saveTransform).length;
});
setSelectedSuggestionScroll(true);
return true; // PreventDefault.
}
function handleEscapeKey(event) {
if (event.target instanceof HTMLInputElement) {
setIncompleteTokenValue(event.target.value);
setIsExpanded(false);
setSelectedSuggestionIndex(-1);
setSelectedSuggestionScroll(false);
}
return true; // PreventDefault.
}
function handleCommaKey() {
if (inputHasValidValue()) {
addNewToken(incompleteTokenValue);
}
return true; // PreventDefault.
}
function moveInputToIndex(index) {
setInputOffsetFromEnd(value.length - Math.max(index, -1) - 1);
}
function moveInputBeforePreviousToken() {
setInputOffsetFromEnd(prevInputOffsetFromEnd => {
return Math.min(prevInputOffsetFromEnd + 1, value.length);
});
}
function moveInputAfterNextToken() {
setInputOffsetFromEnd(prevInputOffsetFromEnd => {
return Math.max(prevInputOffsetFromEnd - 1, 0);
});
}
function deleteTokenBeforeInput() {
const index = getIndexOfInput() - 1;
if (index > -1) {
deleteToken(value[index]);
}
}
function deleteTokenAfterInput() {
const index = getIndexOfInput();
if (index < value.length) {
deleteToken(value[index]); // Update input offset since it's the offset from the last token.
moveInputToIndex(index);
}
}
function addCurrentToken() {
let preventDefault = false;
const selectedSuggestion = getSelectedSuggestion();
if (selectedSuggestion) {
addNewToken(selectedSuggestion);
preventDefault = true;
} else if (inputHasValidValue()) {
addNewToken(incompleteTokenValue);
preventDefault = true;
}
return preventDefault;
}
function addNewTokens(tokens) {
const tokensToAdd = [...new Set(tokens.map(saveTransform).filter(Boolean).filter(token => !valueContainsToken(token)))];
if (tokensToAdd.length > 0) {
const newValue = [...value];
newValue.splice(getIndexOfInput(), 0, ...tokensToAdd);
onChange(newValue);
}
}
function addNewToken(token) {
if (!__experimentalValidateInput(token)) {
(0,external_wp_a11y_namespaceObject.speak)(messages.__experimentalInvalid, 'assertive');
return;
}
addNewTokens([token]);
(0,external_wp_a11y_namespaceObject.speak)(messages.added, 'assertive');
setIncompleteTokenValue('');
setSelectedSuggestionIndex(-1);
setSelectedSuggestionScroll(false);
setIsExpanded(!__experimentalExpandOnFocus);
if (isActive) {
focus();
}
}
function deleteToken(token) {
const newTokens = value.filter(item => {
return getTokenValue(item) !== getTokenValue(token);
});
onChange(newTokens);
(0,external_wp_a11y_namespaceObject.speak)(messages.removed, 'assertive');
}
function getTokenValue(token) {
if ('object' === typeof token) {
return token.value;
}
return token;
}
function getMatchingSuggestions() {
let searchValue = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : incompleteTokenValue;
let _suggestions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : suggestions;
let _value = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : value;
let _maxSuggestions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : maxSuggestions;
let _saveTransform = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : saveTransform;
let match = _saveTransform(searchValue);
const startsWithMatch = [];
const containsMatch = [];
const normalizedValue = _value.map(item => {
if (typeof item === 'string') {
return item;
}
return item.value;
});
if (match.length === 0) {
_suggestions = _suggestions.filter(suggestion => !normalizedValue.includes(suggestion));
} else {
match = match.toLocaleLowerCase();
_suggestions.forEach(suggestion => {
const index = suggestion.toLocaleLowerCase().indexOf(match);
if (normalizedValue.indexOf(suggestion) === -1) {
if (index === 0) {
startsWithMatch.push(suggestion);
} else if (index > 0) {
containsMatch.push(suggestion);
}
}
});
_suggestions = startsWithMatch.concat(containsMatch);
}
return _suggestions.slice(0, _maxSuggestions);
}
function getSelectedSuggestion() {
if (selectedSuggestionIndex !== -1) {
return getMatchingSuggestions()[selectedSuggestionIndex];
}
return undefined;
}
function valueContainsToken(token) {
return value.some(item => {
return getTokenValue(token) === getTokenValue(item);
});
}
function getIndexOfInput() {
return value.length - inputOffsetFromEnd;
}
function isInputEmpty() {
return incompleteTokenValue.length === 0;
}
function inputHasValidValue() {
return saveTransform(incompleteTokenValue).length > 0;
}
function updateSuggestions() {
let resetSelectedSuggestion = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
const inputHasMinimumChars = incompleteTokenValue.trim().length > 1;
const matchingSuggestions = getMatchingSuggestions(incompleteTokenValue);
const hasMatchingSuggestions = matchingSuggestions.length > 0;
const shouldExpandIfFocuses = hasFocus() && __experimentalExpandOnFocus;
setIsExpanded(shouldExpandIfFocuses || inputHasMinimumChars && hasMatchingSuggestions);
if (resetSelectedSuggestion) {
if (__experimentalAutoSelectFirstMatch && inputHasMinimumChars && hasMatchingSuggestions) {
setSelectedSuggestionIndex(0);
setSelectedSuggestionScroll(true);
} else {
setSelectedSuggestionIndex(-1);
setSelectedSuggestionScroll(false);
}
}
if (inputHasMinimumChars) {
const message = hasMatchingSuggestions ? (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %d: number of results. */
(0,external_wp_i18n_namespaceObject._n)('%d result found, use up and down arrow keys to navigate.', '%d results found, use up and down arrow keys to navigate.', matchingSuggestions.length), matchingSuggestions.length) : (0,external_wp_i18n_namespaceObject.__)('No results.');
debouncedSpeak(message, 'assertive');
}
}
function renderTokensAndInput() {
const components = value.map(renderToken);
components.splice(getIndexOfInput(), 0, renderInput());
return components;
}
function renderToken(token, index, tokens) {
const _value = getTokenValue(token);
const status = typeof token !== 'string' ? token.status : undefined;
const termPosition = index + 1;
const termsCount = tokens.length;
return (0,external_wp_element_namespaceObject.createElement)(flex_item_component, {
key: 'token-' + _value
}, (0,external_wp_element_namespaceObject.createElement)(Token, {
value: _value,
status: status,
title: typeof token !== 'string' ? token.title : undefined,
displayTransform: displayTransform,
onClickRemove: onTokenClickRemove,
isBorderless: typeof token !== 'string' && token.isBorderless || isBorderless,
onMouseEnter: typeof token !== 'string' ? token.onMouseEnter : undefined,
onMouseLeave: typeof token !== 'string' ? token.onMouseLeave : undefined,
disabled: 'error' !== status && disabled,
messages: messages,
termsCount: termsCount,
termPosition: termPosition
}));
}
function renderInput() {
const inputProps = {
instanceId,
autoCapitalize,
autoComplete,
placeholder: value.length === 0 ? placeholder : '',
key: 'input',
disabled,
value: incompleteTokenValue,
onBlur,
isExpanded,
selectedSuggestionIndex
};
return (0,external_wp_element_namespaceObject.createElement)(token_input, extends_extends({}, inputProps, {
onChange: !(maxLength && value.length >= maxLength) ? onInputChangeHandler : undefined,
ref: input
}));
}
const classes = classnames_default()(className, 'components-form-token-field__input-container', {
'is-active': isActive,
'is-disabled': disabled
});
let tokenFieldProps = {
className: 'components-form-token-field',
tabIndex: -1
};
const matchingSuggestions = getMatchingSuggestions();
if (!disabled) {
tokenFieldProps = Object.assign({}, tokenFieldProps, {
onKeyDown,
onKeyPress,
onFocus: onFocusHandler
});
} // Disable reason: There is no appropriate role which describes the
// input container intended accessible usability.
// TODO: Refactor click detection to use blur to stop propagation.
/* eslint-disable jsx-a11y/no-static-element-interactions */
return (0,external_wp_element_namespaceObject.createElement)("div", tokenFieldProps, (0,external_wp_element_namespaceObject.createElement)(StyledLabel, {
htmlFor: `components-form-token-input-${instanceId}`,
className: "components-form-token-field__label"
}, label), (0,external_wp_element_namespaceObject.createElement)("div", {
ref: tokensAndInput,
className: classes,
tabIndex: -1,
onMouseDown: onContainerTouched,
onTouchStart: onContainerTouched
}, (0,external_wp_element_namespaceObject.createElement)(TokensAndInputWrapperFlex, {
justify: "flex-start",
align: "center",
gap: 1,
wrap: true,
__next36pxDefaultSize: __next36pxDefaultSize,
hasTokens: !!value.length
}, renderTokensAndInput()), isExpanded && (0,external_wp_element_namespaceObject.createElement)(suggestions_list, {
instanceId: instanceId,
match: saveTransform(incompleteTokenValue),
displayTransform: displayTransform,
suggestions: matchingSuggestions,
selectedIndex: selectedSuggestionIndex,
scrollIntoView: selectedSuggestionScroll,
onHover: onSuggestionHovered,
onSelect: onSuggestionSelected,
__experimentalRenderItem: __experimentalRenderItem
})), __experimentalShowHowTo && (0,external_wp_element_namespaceObject.createElement)("p", {
id: `components-form-token-suggestions-howto-${instanceId}`,
className: "components-form-token-field__help"
}, tokenizeOnSpace ? (0,external_wp_i18n_namespaceObject.__)('Separate with commas, spaces, or the Enter key.') : (0,external_wp_i18n_namespaceObject.__)('Separate with commas or the Enter key.')));
/* eslint-enable jsx-a11y/no-static-element-interactions */
}
/* harmony default export */ var form_token_field = (FormTokenField);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/guide/icons.js
/**
* WordPress dependencies
*/
const PageControlIcon = _ref => {
let {
isSelected
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
width: "8",
height: "8",
fill: "none",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Circle, {
cx: "4",
cy: "4",
r: "4",
fill: isSelected ? '#419ECD' : '#E1E3E6'
}));
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/guide/page-control.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PageControl(_ref) {
let {
currentPage,
numberOfPages,
setCurrentPage
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("ul", {
className: "components-guide__page-control",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Guide controls')
}, Array.from({
length: numberOfPages
}).map((_, page) => (0,external_wp_element_namespaceObject.createElement)("li", {
key: page // Set aria-current="step" on the active page, see https://www.w3.org/TR/wai-aria-1.1/#aria-current
,
"aria-current": page === currentPage ? 'step' : undefined
}, (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
key: page,
icon: (0,external_wp_element_namespaceObject.createElement)(PageControlIcon, {
isSelected: page === currentPage
}),
"aria-label": (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: 1: current page number 2: total number of pages */
(0,external_wp_i18n_namespaceObject.__)('Page %1$d of %2$d'), page + 1, numberOfPages),
onClick: () => setCurrentPage(page)
}))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/guide/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function Guide(_ref) {
let {
children,
className,
contentLabel,
finishButtonText,
onFinish,
pages = []
} = _ref;
const guideContainer = (0,external_wp_element_namespaceObject.useRef)();
const [currentPage, setCurrentPage] = (0,external_wp_element_namespaceObject.useState)(0);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (external_wp_element_namespaceObject.Children.count(children)) {
external_wp_deprecated_default()('Passing children to <Guide>', {
since: '5.5',
alternative: 'the `pages` prop'
});
}
}, [children]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
// Each time we change the current page, start from the first element of the page.
// This also solves any focus loss that can happen.
if (guideContainer.current) {
var _focus$tabbable$find, _focus$tabbable$find$;
(_focus$tabbable$find = external_wp_dom_namespaceObject.focus.tabbable.find(guideContainer.current)) === null || _focus$tabbable$find === void 0 ? void 0 : (_focus$tabbable$find$ = _focus$tabbable$find[0]) === null || _focus$tabbable$find$ === void 0 ? void 0 : _focus$tabbable$find$.focus();
}
}, [currentPage]);
if (external_wp_element_namespaceObject.Children.count(children)) {
pages = external_wp_element_namespaceObject.Children.map(children, child => ({
content: child
}));
}
const canGoBack = currentPage > 0;
const canGoForward = currentPage < pages.length - 1;
const goBack = () => {
if (canGoBack) {
setCurrentPage(currentPage - 1);
}
};
const goForward = () => {
if (canGoForward) {
setCurrentPage(currentPage + 1);
}
};
if (pages.length === 0) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(modal, {
className: classnames_default()('components-guide', className),
contentLabel: contentLabel,
onRequestClose: onFinish,
onKeyDown: event => {
if (event.code === 'ArrowLeft') {
goBack(); // Do not scroll the modal's contents.
event.preventDefault();
} else if (event.code === 'ArrowRight') {
goForward(); // Do not scroll the modal's contents.
event.preventDefault();
}
},
ref: guideContainer
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-guide__container"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-guide__page"
}, pages[currentPage].image, pages.length > 1 && (0,external_wp_element_namespaceObject.createElement)(PageControl, {
currentPage: currentPage,
numberOfPages: pages.length,
setCurrentPage: setCurrentPage
}), pages[currentPage].content), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-guide__footer"
}, canGoBack && (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-guide__back-button",
onClick: goBack
}, (0,external_wp_i18n_namespaceObject.__)('Previous')), canGoForward && (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-guide__forward-button",
onClick: goForward
}, (0,external_wp_i18n_namespaceObject.__)('Next')), !canGoForward && (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-guide__finish-button",
onClick: onFinish
}, finishButtonText || (0,external_wp_i18n_namespaceObject.__)('Finish')))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/guide/page.js
/**
* WordPress dependencies
*/
function GuidePage(props) {
(0,external_wp_element_namespaceObject.useEffect)(() => {
external_wp_deprecated_default()('<GuidePage>', {
since: '5.5',
alternative: 'the `pages` prop in <Guide>'
});
}, []);
return (0,external_wp_element_namespaceObject.createElement)("div", props);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/button/deprecated.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedIconButton(_ref, ref) {
let {
label,
labelPosition,
size,
tooltip,
...props
} = _ref;
external_wp_deprecated_default()('wp.components.IconButton', {
since: '5.4',
alternative: 'wp.components.Button',
version: '6.2'
});
return (0,external_wp_element_namespaceObject.createElement)(build_module_button, extends_extends({}, props, {
ref: ref,
tooltipPosition: labelPosition,
iconSize: size,
showTooltip: tooltip !== undefined ? !!tooltip : undefined,
label: tooltip || label
}));
}
/* harmony default export */ var deprecated = ((0,external_wp_element_namespaceObject.forwardRef)(UnforwardedIconButton));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/item-group/item/hook.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function hook_useItem(props) {
const {
as: asProp,
className,
onClick,
role = 'listitem',
size: sizeProp,
...otherProps
} = useContextSystem(props, 'Item');
const {
spacedAround,
size: contextSize
} = useItemGroupContext();
const size = sizeProp || contextSize;
const as = asProp || (typeof onClick !== 'undefined' ? 'button' : 'div');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => cx(as === 'button' && unstyledButton, itemSizes[size] || itemSizes.medium, item, spacedAround && styles_spacedAround, className), [as, className, cx, size, spacedAround]);
const wrapperClassName = cx(itemWrapper);
return {
as,
className: classes,
onClick,
wrapperClassName,
role,
...otherProps
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/item-group/item/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedItem(props, forwardedRef) {
const {
role,
wrapperClassName,
...otherProps
} = hook_useItem(props);
return (0,external_wp_element_namespaceObject.createElement)("div", {
role: role,
className: wrapperClassName
}, (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({}, otherProps, {
ref: forwardedRef
})));
}
/**
* `Item` is used in combination with `ItemGroup` to display a list of items
* grouped and styled together.
*
* @example
* ```jsx
* import {
* __experimentalItemGroup as ItemGroup,
* __experimentalItem as Item,
* } from '@wordpress/components';
*
* function Example() {
* return (
* <ItemGroup>
* <Item>Code</Item>
* <Item>is</Item>
* <Item>Poetry</Item>
* </ItemGroup>
* );
* }
* ```
*/
const component_Item = contextConnect(UnconnectedItem, 'Item');
/* harmony default export */ var item_component = (component_Item);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/input-control/input-prefix-wrapper.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedInputControlPrefixWrapper(props, forwardedRef) {
const derivedProps = useContextSystem(props, 'InputControlPrefixWrapper');
return (0,external_wp_element_namespaceObject.createElement)(spacer_component, extends_extends({
marginBottom: 0
}, derivedProps, {
ref: forwardedRef
}));
}
/**
* A convenience wrapper for the `prefix` when you want to apply
* standard padding in accordance with the size variant.
*
* ```jsx
* import {
* __experimentalInputControl as InputControl,
* __experimentalInputControlPrefixWrapper as InputControlPrefixWrapper,
* } from '@wordpress/components';
*
* <InputControl
* prefix={<InputControlPrefixWrapper>@</InputControlPrefixWrapper>}
* />
* ```
*/
const InputControlPrefixWrapper = contextConnect(UnconnectedInputControlPrefixWrapper, 'InputControlPrefixWrapper');
/* harmony default export */ var input_prefix_wrapper = (InputControlPrefixWrapper);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/keyboard-shortcuts/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function KeyboardShortcut(_ref) {
let {
target,
callback,
shortcut,
bindGlobal,
eventName
} = _ref;
(0,external_wp_compose_namespaceObject.useKeyboardShortcut)(shortcut, callback, {
bindGlobal,
target,
eventName
});
return null;
}
/**
* `KeyboardShortcuts` is a component which handles keyboard sequences during the lifetime of the rendering element.
*
* When passed children, it will capture key events which occur on or within the children. If no children are passed, events are captured on the document.
*
* It uses the [Mousetrap](https://craig.is/killing/mice) library to implement keyboard sequence bindings.
*
* ```jsx
* import { KeyboardShortcuts } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyKeyboardShortcuts = () => {
* const [ isAllSelected, setIsAllSelected ] = useState( false );
* const selectAll = () => {
* setIsAllSelected( true );
* };
*
* return (
* <div>
* <KeyboardShortcuts
* shortcuts={ {
* 'mod+a': selectAll,
* } }
* />
* [cmd/ctrl + A] Combination pressed? { isAllSelected ? 'Yes' : 'No' }
* </div>
* );
* };
* ```
*/
function KeyboardShortcuts(_ref2) {
let {
children,
shortcuts,
bindGlobal,
eventName
} = _ref2;
const target = (0,external_wp_element_namespaceObject.useRef)(null);
const element = Object.entries(shortcuts !== null && shortcuts !== void 0 ? shortcuts : {}).map(_ref3 => {
let [shortcut, callback] = _ref3;
return (0,external_wp_element_namespaceObject.createElement)(KeyboardShortcut, {
key: shortcut,
shortcut: shortcut,
callback: callback,
bindGlobal: bindGlobal,
eventName: eventName,
target: target
});
}); // Render as non-visual if there are no children pressed. Keyboard
// events will be bound to the document instead.
if (!external_wp_element_namespaceObject.Children.count(children)) {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, element);
}
return (0,external_wp_element_namespaceObject.createElement)("div", {
ref: target
}, element, children);
}
/* harmony default export */ var keyboard_shortcuts = (KeyboardShortcuts);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/menu-group/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* `MenuGroup` wraps a series of related `MenuItem` components into a common
* section.
*
* ```jsx
* import { MenuGroup, MenuItem } from '@wordpress/components';
*
* const MyMenuGroup = () => (
* <MenuGroup label="Settings">
* <MenuItem>Setting 1</MenuItem>
* <MenuItem>Setting 2</MenuItem>
* </MenuGroup>
* );
* ```
*/
function MenuGroup(props) {
const {
children,
className = '',
label,
hideSeparator
} = props;
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(MenuGroup);
if (!external_wp_element_namespaceObject.Children.count(children)) {
return null;
}
const labelId = `components-menu-group-label-${instanceId}`;
const classNames = classnames_default()(className, 'components-menu-group', {
'has-hidden-separator': hideSeparator
});
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classNames
}, label && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-menu-group__label",
id: labelId,
"aria-hidden": "true"
}, label), (0,external_wp_element_namespaceObject.createElement)("div", {
role: "group",
"aria-labelledby": label ? labelId : undefined
}, children));
}
/* harmony default export */ var menu_group = (MenuGroup);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/menu-item/index.js
// @ts-nocheck
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function MenuItem(props, ref) {
let {
children,
info,
className,
icon,
iconPosition = 'right',
shortcut,
isSelected,
role = 'menuitem',
suffix,
...buttonProps
} = props;
className = classnames_default()('components-menu-item__button', className);
if (info) {
children = (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-menu-item__info-wrapper"
}, (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-menu-item__item"
}, children), (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-menu-item__info"
}, info));
}
if (icon && typeof icon !== 'string') {
icon = (0,external_wp_element_namespaceObject.cloneElement)(icon, {
className: classnames_default()('components-menu-items__item-icon', {
'has-icon-right': iconPosition === 'right'
})
});
}
return (0,external_wp_element_namespaceObject.createElement)(build_module_button, extends_extends({
ref: ref // Make sure aria-checked matches spec https://www.w3.org/TR/wai-aria-1.1/#aria-checked
,
"aria-checked": role === 'menuitemcheckbox' || role === 'menuitemradio' ? isSelected : undefined,
role: role,
icon: iconPosition === 'left' ? icon : undefined,
className: className
}, buttonProps), (0,external_wp_element_namespaceObject.createElement)("span", {
className: "components-menu-item__item"
}, children), !suffix && (0,external_wp_element_namespaceObject.createElement)(build_module_shortcut, {
className: "components-menu-item__shortcut",
shortcut: shortcut
}), !suffix && icon && iconPosition === 'right' && (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: icon
}), suffix);
}
/* harmony default export */ var menu_item = ((0,external_wp_element_namespaceObject.forwardRef)(MenuItem));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/menu-items-choice/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const menu_items_choice_noop = () => {};
function MenuItemsChoice(_ref) {
let {
choices = [],
onHover = menu_items_choice_noop,
onSelect,
value
} = _ref;
return choices.map(item => {
const isSelected = value === item.value;
return (0,external_wp_element_namespaceObject.createElement)(menu_item, {
key: item.value,
role: "menuitemradio",
icon: isSelected && library_check,
info: item.info,
isSelected: isSelected,
shortcut: item.shortcut,
className: "components-menu-items-choice",
onClick: () => {
if (!isSelected) {
onSelect(item.value);
}
},
onMouseEnter: () => onHover(item.value),
onMouseLeave: () => onHover(null),
"aria-label": item['aria-label']
}, item.label);
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigable-container/tabbable.js
// @ts-nocheck
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function TabbableContainer(_ref, ref) {
let {
eventToOffset,
...props
} = _ref;
const innerEventToOffset = evt => {
const {
code,
shiftKey
} = evt;
if ('Tab' === code) {
return shiftKey ? -1 : 1;
} // Allow custom handling of keys besides Tab.
//
// By default, TabbableContainer will move focus forward on Tab and
// backward on Shift+Tab. The handler below will be used for all other
// events. The semantics for `eventToOffset`'s return
// values are the following:
//
// - +1: move focus forward
// - -1: move focus backward
// - 0: don't move focus, but acknowledge event and thus stop it
// - undefined: do nothing, let the event propagate.
if (eventToOffset) {
return eventToOffset(evt);
}
};
return (0,external_wp_element_namespaceObject.createElement)(container, extends_extends({
ref: ref,
stopNavigationEvents: true,
onlyBrowserTabstops: true,
eventToOffset: innerEventToOffset
}, props));
}
/* harmony default export */ var tabbable = ((0,external_wp_element_namespaceObject.forwardRef)(TabbableContainer));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/constants.js
const ROOT_MENU = 'root';
const SEARCH_FOCUS_DELAY = 100;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/context.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const context_noop = () => {};
const NavigationContext = (0,external_wp_element_namespaceObject.createContext)({
activeItem: undefined,
activeMenu: ROOT_MENU,
setActiveMenu: context_noop,
isMenuEmpty: context_noop,
navigationTree: {
items: {},
getItem: context_noop,
addItem: context_noop,
removeItem: context_noop,
menus: {},
getMenu: context_noop,
addMenu: context_noop,
removeMenu: context_noop,
childMenu: {},
traverseMenu: context_noop,
isMenuEmpty: context_noop
}
});
const useNavigationContext = () => (0,external_wp_element_namespaceObject.useContext)(NavigationContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/search.js
/**
* WordPress dependencies
*/
const search = (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: "M13.5 6C10.5 6 8 8.5 8 11.5c0 1.1.3 2.1.9 3l-3.4 3 1 1.1 3.4-2.9c1 .9 2.2 1.4 3.6 1.4 3 0 5.5-2.5 5.5-5.5C19 8.5 16.5 6 13.5 6zm0 9.5c-2.2 0-4-1.8-4-4s1.8-4 4-4 4 1.8 4 4-1.8 4-4 4z"
}));
/* harmony default export */ var library_search = (search);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/search-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedSearchControl(_ref, forwardedRef) {
let {
__nextHasNoMarginBottom,
className,
onChange,
onKeyDown,
value,
label,
placeholder = (0,external_wp_i18n_namespaceObject.__)('Search'),
hideLabelFromVision = true,
help,
onClose,
...restProps
} = _ref;
const searchRef = (0,external_wp_element_namespaceObject.useRef)();
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(SearchControl);
const id = `components-search-control-${instanceId}`;
const renderRightButton = () => {
if (onClose) {
return (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
icon: close_small,
label: (0,external_wp_i18n_namespaceObject.__)('Close search'),
onClick: onClose
});
}
if (!!value) {
return (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
icon: close_small,
label: (0,external_wp_i18n_namespaceObject.__)('Reset search'),
onClick: () => {
var _searchRef$current;
onChange('');
(_searchRef$current = searchRef.current) === null || _searchRef$current === void 0 ? void 0 : _searchRef$current.focus();
}
});
}
return (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, {
icon: library_search
});
};
return (0,external_wp_element_namespaceObject.createElement)(base_control, {
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
label: label,
id: id,
hideLabelFromVision: hideLabelFromVision,
help: help,
className: classnames_default()(className, 'components-search-control')
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-search-control__input-wrapper"
}, (0,external_wp_element_namespaceObject.createElement)("input", extends_extends({}, restProps, {
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([searchRef, forwardedRef]),
className: "components-search-control__input",
id: id,
type: "search",
placeholder: placeholder,
onChange: event => onChange(event.target.value),
onKeyDown: onKeyDown,
autoComplete: "off",
value: value || ''
})), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-search-control__icon"
}, renderRightButton())));
}
/**
* SearchControl components let users display a search control.
*
* ```jsx
* import { SearchControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* function MySearchControl( { className, setState } ) {
* const [ searchInput, setSearchInput ] = useState( '' );
*
* return (
* <SearchControl
* value={ searchInput }
* onChange={ setSearchInput }
* />
* );
* }
* ```
*/
const SearchControl = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedSearchControl);
/* harmony default export */ var search_control = (SearchControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/styles/navigation-styles.js
function navigation_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const NavigationUI = createStyled("div", true ? {
target: "ejwewyf11"
} : 0)("width:100%;box-sizing:border-box;padding:0 ", space(4), ";overflow:hidden;" + ( true ? "" : 0));
const MenuUI = createStyled("div", true ? {
target: "ejwewyf10"
} : 0)("margin-top:", space(6), ";margin-bottom:", space(6), ";display:flex;flex-direction:column;ul{padding:0;margin:0;list-style:none;}.components-navigation__back-button{margin-bottom:", space(6), ";}.components-navigation__group+.components-navigation__group{margin-top:", space(6), ";}" + ( true ? "" : 0));
const MenuBackButtonUI = /*#__PURE__*/createStyled(build_module_button, true ? {
target: "ejwewyf9"
} : 0)( true ? {
name: "26l0q2",
styles: "&.is-tertiary{color:inherit;opacity:0.7;&:hover:not( :disabled ){opacity:1;box-shadow:none;color:inherit;}&:active:not( :disabled ){background:transparent;opacity:1;color:inherit;}}"
} : 0);
const MenuTitleUI = createStyled("div", true ? {
target: "ejwewyf8"
} : 0)( true ? {
name: "1aubja5",
styles: "overflow:hidden;width:100%"
} : 0);
const MenuTitleActionsUI = createStyled("span", true ? {
target: "ejwewyf7"
} : 0)("height:", space(6), ";.components-button.is-small{color:inherit;opacity:0.7;margin-right:", space(1), ";padding:0;&:active:not( :disabled ){background:none;opacity:1;color:inherit;}&:hover:not( :disabled ){box-shadow:none;opacity:1;color:inherit;}}" + ( true ? "" : 0));
const MenuTitleSearchUI = /*#__PURE__*/createStyled(search_control, true ? {
target: "ejwewyf6"
} : 0)( true ? {
name: "za3n3e",
styles: "input[type='search'].components-search-control__input{margin:0;background:#303030;color:#fff;&:focus{background:#434343;color:#fff;}&::placeholder{color:rgba( 255, 255, 255, 0.6 );}}svg{fill:white;}.components-button.has-icon{padding:0;min-width:auto;}"
} : 0);
const GroupTitleUI = /*#__PURE__*/createStyled(heading_component, true ? {
target: "ejwewyf5"
} : 0)("min-height:", space(12), ";align-items:center;color:inherit;display:flex;justify-content:space-between;margin-bottom:", space(2), ";padding:", () => (0,external_wp_i18n_namespaceObject.isRTL)() ? `${space(1)} ${space(4)} ${space(1)} ${space(2)}` : `${space(1)} ${space(2)} ${space(1)} ${space(4)}`, ";" + ( true ? "" : 0));
const ItemBaseUI = createStyled("li", true ? {
target: "ejwewyf4"
} : 0)("border-radius:2px;color:inherit;margin-bottom:0;>button,>a.components-button,>a{width:100%;color:inherit;opacity:0.7;padding:", space(2), " ", space(4), ";", rtl({
textAlign: 'left'
}, {
textAlign: 'right'
}), " &:hover,&:focus:not( [aria-disabled='true'] ):active,&:active:not( [aria-disabled='true'] ):active{color:inherit;opacity:1;}}&.is-active{background-color:", COLORS.ui.theme, ";color:", COLORS.white, ";>button,>a{color:", COLORS.white, ";opacity:1;}}>svg path{color:", COLORS.gray[600], ";}" + ( true ? "" : 0));
const ItemUI = createStyled("div", true ? {
target: "ejwewyf3"
} : 0)("display:flex;align-items:center;height:auto;min-height:40px;margin:0;padding:", space(1.5), " ", space(4), ";font-weight:400;line-height:20px;width:100%;color:inherit;opacity:0.7;" + ( true ? "" : 0));
const ItemIconUI = createStyled("span", true ? {
target: "ejwewyf2"
} : 0)("display:flex;margin-right:", space(2), ";" + ( true ? "" : 0));
const ItemBadgeUI = createStyled("span", true ? {
target: "ejwewyf1"
} : 0)("margin-left:", () => (0,external_wp_i18n_namespaceObject.isRTL)() ? '0' : space(2), ";margin-right:", () => (0,external_wp_i18n_namespaceObject.isRTL)() ? space(2) : '0', ";display:inline-flex;padding:", space(1), " ", space(3), ";border-radius:2px;animation:fade-in 250ms ease-out;@keyframes fade-in{from{opacity:0;}to{opacity:1;}}", reduceMotion('animation'), ";" + ( true ? "" : 0));
const ItemTitleUI = /*#__PURE__*/createStyled(text_component, true ? {
target: "ejwewyf0"
} : 0)(() => (0,external_wp_i18n_namespaceObject.isRTL)() ? 'margin-left: auto;' : 'margin-right: auto;', " font-size:14px;line-height:20px;color:inherit;" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/use-navigation-tree-nodes.js
/**
* WordPress dependencies
*/
const useNavigationTreeNodes = () => {
const [nodes, setNodes] = (0,external_wp_element_namespaceObject.useState)({});
const getNode = key => nodes[key];
const addNode = (key, value) => {
const {
children,
...newNode
} = value;
return setNodes(original => ({ ...original,
[key]: newNode
}));
};
const removeNode = key => {
return setNodes(original => {
const {
[key]: removedNode,
...remainingNodes
} = original;
return remainingNodes;
});
};
return {
nodes,
getNode,
addNode,
removeNode
};
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/use-create-navigation-tree.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const useCreateNavigationTree = () => {
const {
nodes: items,
getNode: getItem,
addNode: addItem,
removeNode: removeItem
} = useNavigationTreeNodes();
const {
nodes: menus,
getNode: getMenu,
addNode: addMenu,
removeNode: removeMenu
} = useNavigationTreeNodes();
/**
* Stores direct nested menus of menus
* This makes it easy to traverse menu tree
*
* Key is the menu prop of the menu
* Value is an array of menu keys
*/
const [childMenu, setChildMenu] = (0,external_wp_element_namespaceObject.useState)({});
const getChildMenu = menu => childMenu[menu] || [];
const traverseMenu = (startMenu, callback) => {
const visited = [];
let queue = [startMenu];
let current;
while (queue.length > 0) {
current = getMenu(queue.shift());
if (!current || visited.includes(current.menu)) {
continue;
}
visited.push(current.menu);
queue = [...queue, ...getChildMenu(current.menu)];
if (callback(current) === false) {
break;
}
}
};
const isMenuEmpty = menuToCheck => {
let isEmpty = true;
traverseMenu(menuToCheck, current => {
if (!current.isEmpty) {
isEmpty = false;
return false;
}
});
return isEmpty;
};
return {
items,
getItem,
addItem,
removeItem,
menus,
getMenu,
addMenu: (key, value) => {
setChildMenu(state => {
const newState = { ...state
};
if (!newState[value.parentMenu]) {
newState[value.parentMenu] = [];
}
newState[value.parentMenu].push(key);
return newState;
});
addMenu(key, value);
},
removeMenu,
childMenu,
traverseMenu,
isMenuEmpty
};
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const navigation_noop = () => {};
function Navigation(_ref) {
let {
activeItem,
activeMenu = ROOT_MENU,
children,
className,
onActivateMenu = navigation_noop
} = _ref;
const [menu, setMenu] = (0,external_wp_element_namespaceObject.useState)(activeMenu);
const [slideOrigin, setSlideOrigin] = (0,external_wp_element_namespaceObject.useState)();
const navigationTree = useCreateNavigationTree();
const defaultSlideOrigin = (0,external_wp_i18n_namespaceObject.isRTL)() ? 'right' : 'left';
const setActiveMenu = function (menuId) {
let slideInOrigin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultSlideOrigin;
if (!navigationTree.getMenu(menuId)) {
return;
}
setSlideOrigin(slideInOrigin);
setMenu(menuId);
onActivateMenu(menuId);
}; // Used to prevent the sliding animation on mount
const isMounted = (0,external_wp_element_namespaceObject.useRef)(false);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (!isMounted.current) {
isMounted.current = true;
}
}, []);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (activeMenu !== menu) {
setActiveMenu(activeMenu);
} // Ignore exhaustive-deps here, as it would require either a larger refactor or some questionable workarounds.
// See https://github.com/WordPress/gutenberg/pull/41612 for context.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeMenu]);
const context = {
activeItem,
activeMenu: menu,
setActiveMenu,
navigationTree
};
const classes = classnames_default()('components-navigation', className);
const animateClassName = getAnimateClassName({
type: 'slide-in',
origin: slideOrigin
});
return (0,external_wp_element_namespaceObject.createElement)(NavigationUI, {
className: classes
}, (0,external_wp_element_namespaceObject.createElement)("div", {
key: menu,
className: classnames_default()({
[animateClassName]: isMounted.current && slideOrigin
})
}, (0,external_wp_element_namespaceObject.createElement)(NavigationContext.Provider, {
value: context
}, children)));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/chevron-right.js
/**
* WordPress dependencies
*/
const chevronRight = (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: "M10.6 6L9.4 7l4.6 5-4.6 5 1.2 1 5.4-6z"
}));
/* harmony default export */ var chevron_right = (chevronRight);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/chevron-left.js
/**
* WordPress dependencies
*/
const chevronLeft = (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: "M14.6 7l-1.2-1L8 12l5.4 6 1.2-1-4.6-5z"
}));
/* harmony default export */ var chevron_left = (chevronLeft);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/back-button/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function NavigationBackButton(_ref, ref) {
var _navigationTree$getMe;
let {
backButtonLabel,
className,
href,
onClick,
parentMenu
} = _ref;
const {
setActiveMenu,
navigationTree
} = useNavigationContext();
const classes = classnames_default()('components-navigation__back-button', className);
const parentMenuTitle = (_navigationTree$getMe = navigationTree.getMenu(parentMenu)) === null || _navigationTree$getMe === void 0 ? void 0 : _navigationTree$getMe.title;
const handleOnClick = event => {
if (typeof onClick === 'function') {
onClick(event);
}
const animationDirection = (0,external_wp_i18n_namespaceObject.isRTL)() ? 'left' : 'right';
if (parentMenu && !event.defaultPrevented) {
setActiveMenu(parentMenu, animationDirection);
}
};
const icon = (0,external_wp_i18n_namespaceObject.isRTL)() ? chevron_right : chevron_left;
return (0,external_wp_element_namespaceObject.createElement)(MenuBackButtonUI, {
className: classes,
href: href,
variant: "tertiary",
ref: ref,
onClick: handleOnClick
}, (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, {
icon: icon
}), backButtonLabel || parentMenuTitle || (0,external_wp_i18n_namespaceObject.__)('Back'));
}
/* harmony default export */ var back_button = ((0,external_wp_element_namespaceObject.forwardRef)(NavigationBackButton));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/group/context.js
/**
* WordPress dependencies
*/
const NavigationGroupContext = (0,external_wp_element_namespaceObject.createContext)({
group: undefined
});
const useNavigationGroupContext = () => (0,external_wp_element_namespaceObject.useContext)(NavigationGroupContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/group/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
let uniqueId = 0;
function NavigationGroup(_ref) {
let {
children,
className,
title
} = _ref;
const [groupId] = (0,external_wp_element_namespaceObject.useState)(`group-${++uniqueId}`);
const {
navigationTree: {
items
}
} = useNavigationContext();
const context = {
group: groupId
}; // Keep the children rendered to make sure invisible items are included in the navigation tree.
if (!Object.values(items).some(item => item.group === groupId && item._isVisible)) {
return (0,external_wp_element_namespaceObject.createElement)(NavigationGroupContext.Provider, {
value: context
}, children);
}
const groupTitleId = `components-navigation__group-title-${groupId}`;
const classes = classnames_default()('components-navigation__group', className);
return (0,external_wp_element_namespaceObject.createElement)(NavigationGroupContext.Provider, {
value: context
}, (0,external_wp_element_namespaceObject.createElement)("li", {
className: classes
}, title && (0,external_wp_element_namespaceObject.createElement)(GroupTitleUI, {
className: "components-navigation__group-title",
id: groupTitleId,
level: 3
}, title), (0,external_wp_element_namespaceObject.createElement)("ul", {
"aria-labelledby": groupTitleId,
role: "group"
}, children)));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/item/base-content.js
/**
* Internal dependencies
*/
function NavigationItemBaseContent(props) {
const {
badge,
title
} = props;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, title && (0,external_wp_element_namespaceObject.createElement)(ItemTitleUI, {
className: "components-navigation__item-title",
variant: "body.small",
as: "span"
}, title), badge && (0,external_wp_element_namespaceObject.createElement)(ItemBadgeUI, {
className: "components-navigation__item-badge"
}, badge));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/menu/context.js
/**
* WordPress dependencies
*/
const NavigationMenuContext = (0,external_wp_element_namespaceObject.createContext)({
menu: undefined,
search: ''
});
const useNavigationMenuContext = () => (0,external_wp_element_namespaceObject.useContext)(NavigationMenuContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/utils.js
/**
* External dependencies
*/
// @see packages/block-editor/src/components/inserter/search-items.js
const normalizeInput = input => remove_accents_default()(input).replace(/^\//, '').toLowerCase();
const normalizedSearch = (title, search) => -1 !== normalizeInput(title).indexOf(normalizeInput(search));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/item/use-navigation-tree-item.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const useNavigationTreeItem = (itemId, props) => {
const {
activeMenu,
navigationTree: {
addItem,
removeItem
}
} = useNavigationContext();
const {
group
} = useNavigationGroupContext();
const {
menu,
search
} = useNavigationMenuContext();
(0,external_wp_element_namespaceObject.useEffect)(() => {
const isMenuActive = activeMenu === menu;
const isItemVisible = !search || normalizedSearch(props.title, search);
addItem(itemId, { ...props,
group,
menu,
_isVisible: isMenuActive && isItemVisible
});
return () => {
removeItem(itemId);
}; // Ignore exhaustive-deps rule for now. See https://github.com/WordPress/gutenberg/pull/41639
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeMenu, search]);
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/item/base.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
let base_uniqueId = 0;
function NavigationItemBase(props) {
var _navigationTree$getIt;
// Also avoid to pass the `title` and `href` props to the ItemBaseUI styled component.
const {
children,
className,
title,
href,
...restProps
} = props;
const [itemId] = (0,external_wp_element_namespaceObject.useState)(`item-${++base_uniqueId}`);
useNavigationTreeItem(itemId, props);
const {
navigationTree
} = useNavigationContext();
if (!((_navigationTree$getIt = navigationTree.getItem(itemId)) !== null && _navigationTree$getIt !== void 0 && _navigationTree$getIt._isVisible)) {
return null;
}
const classes = classnames_default()('components-navigation__item', className);
return (0,external_wp_element_namespaceObject.createElement)(ItemBaseUI, extends_extends({
className: classes
}, restProps), children);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/item/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const item_noop = () => {};
function NavigationItem(props) {
const {
badge,
children,
className,
href,
item,
navigateToMenu,
onClick = item_noop,
title,
icon,
hideIfTargetMenuEmpty,
isText,
...restProps
} = props;
const {
activeItem,
setActiveMenu,
navigationTree: {
isMenuEmpty
}
} = useNavigationContext(); // If hideIfTargetMenuEmpty prop is true
// And the menu we are supposed to navigate to
// Is marked as empty, then we skip rendering the item.
if (hideIfTargetMenuEmpty && navigateToMenu && isMenuEmpty(navigateToMenu)) {
return null;
}
const isActive = item && activeItem === item;
const classes = classnames_default()(className, {
'is-active': isActive
});
const onItemClick = event => {
if (navigateToMenu) {
setActiveMenu(navigateToMenu);
}
onClick(event);
};
const navigationIcon = (0,external_wp_i18n_namespaceObject.isRTL)() ? chevron_left : chevron_right;
const baseProps = children ? props : { ...props,
onClick: undefined
};
const itemProps = isText ? restProps : {
as: build_module_button,
href,
onClick: onItemClick,
'aria-current': isActive ? 'page' : undefined,
...restProps
};
return (0,external_wp_element_namespaceObject.createElement)(NavigationItemBase, extends_extends({}, baseProps, {
className: classes
}), children || (0,external_wp_element_namespaceObject.createElement)(ItemUI, itemProps, icon && (0,external_wp_element_namespaceObject.createElement)(ItemIconUI, null, (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, {
icon: icon
})), (0,external_wp_element_namespaceObject.createElement)(NavigationItemBaseContent, {
title: title,
badge: badge
}), navigateToMenu && (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, {
icon: navigationIcon
})));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/menu/use-navigation-tree-menu.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const useNavigationTreeMenu = props => {
const {
navigationTree: {
addMenu,
removeMenu
}
} = useNavigationContext();
const key = props.menu || ROOT_MENU;
(0,external_wp_element_namespaceObject.useEffect)(() => {
addMenu(key, { ...props,
menu: key
});
return () => {
removeMenu(key);
}; // Ignore exhaustive-deps rule for now. See https://github.com/WordPress/gutenberg/pull/44090
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/higher-order/with-spoken-messages/index.js
/**
* WordPress dependencies
*/
/** @typedef {import('@wordpress/element').WPComponent} WPComponent */
/**
* A Higher Order Component used to be provide speak and debounced speak
* functions.
*
* @see https://developer.wordpress.org/block-editor/packages/packages-a11y/#speak
*
* @param {WPComponent} Component The component to be wrapped.
*
* @return {WPComponent} The wrapped component.
*/
/* harmony default export */ var with_spoken_messages = ((0,external_wp_compose_namespaceObject.createHigherOrderComponent)(Component => props => (0,external_wp_element_namespaceObject.createElement)(Component, extends_extends({}, props, {
speak: external_wp_a11y_namespaceObject.speak,
debouncedSpeak: (0,external_wp_compose_namespaceObject.useDebounce)(external_wp_a11y_namespaceObject.speak, 500)
})), 'withSpokenMessages'));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/menu/menu-title-search.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function MenuTitleSearch(_ref) {
let {
debouncedSpeak,
onCloseSearch,
onSearch,
search,
title
} = _ref;
const {
navigationTree: {
items
}
} = useNavigationContext();
const {
menu
} = useNavigationMenuContext();
const inputRef = (0,external_wp_element_namespaceObject.useRef)(); // Wait for the slide-in animation to complete before autofocusing the input.
// This prevents scrolling to the input during the animation.
(0,external_wp_element_namespaceObject.useEffect)(() => {
const delayedFocus = setTimeout(() => {
inputRef.current.focus();
}, SEARCH_FOCUS_DELAY);
return () => {
clearTimeout(delayedFocus);
};
}, []);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (!search) {
return;
}
const count = Object.values(items).filter(item => item._isVisible).length;
const resultsFoundMessage = (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %d: number of results. */
(0,external_wp_i18n_namespaceObject._n)('%d result found.', '%d results found.', count), count);
debouncedSpeak(resultsFoundMessage); // Ignore exhaustive-deps rule for now. See https://github.com/WordPress/gutenberg/pull/44090
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [items, search]);
const onClose = () => {
onSearch('');
onCloseSearch();
};
function onKeyDown(event) {
if (event.code === 'Escape' && !event.defaultPrevented) {
event.preventDefault();
onClose();
}
}
const inputId = `components-navigation__menu-title-search-${menu}`;
const placeholder = (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: placeholder for menu search box. %s: menu title */
(0,external_wp_i18n_namespaceObject.__)('Search %s'), title === null || title === void 0 ? void 0 : title.toLowerCase()).trim();
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-navigation__menu-title-search"
}, (0,external_wp_element_namespaceObject.createElement)(MenuTitleSearchUI, {
autoComplete: "off",
className: "components-navigation__menu-search-input",
id: inputId,
onChange: value => onSearch(value),
onKeyDown: onKeyDown,
placeholder: placeholder,
onClose: onClose,
ref: inputRef,
type: "search",
value: search
}));
}
/* harmony default export */ var menu_title_search = (with_spoken_messages(MenuTitleSearch));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/menu/menu-title.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function NavigationMenuTitle(_ref) {
let {
hasSearch,
onSearch,
search,
title,
titleAction
} = _ref;
const [isSearching, setIsSearching] = (0,external_wp_element_namespaceObject.useState)(false);
const {
menu
} = useNavigationMenuContext();
const searchButtonRef = (0,external_wp_element_namespaceObject.useRef)();
if (!title) {
return null;
}
const onCloseSearch = () => {
setIsSearching(false); // Wait for the slide-in animation to complete before focusing the search button.
// eslint-disable-next-line @wordpress/react-no-unsafe-timeout
setTimeout(() => {
searchButtonRef.current.focus();
}, SEARCH_FOCUS_DELAY);
};
const menuTitleId = `components-navigation__menu-title-${menu}`;
/* translators: search button label for menu search box. %s: menu title */
const searchButtonLabel = (0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('Search in %s'), title);
return (0,external_wp_element_namespaceObject.createElement)(MenuTitleUI, {
className: "components-navigation__menu-title"
}, !isSearching && (0,external_wp_element_namespaceObject.createElement)(GroupTitleUI, {
as: "h2",
className: "components-navigation__menu-title-heading",
level: 3
}, (0,external_wp_element_namespaceObject.createElement)("span", {
id: menuTitleId
}, title), (hasSearch || titleAction) && (0,external_wp_element_namespaceObject.createElement)(MenuTitleActionsUI, null, titleAction, hasSearch && (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
isSmall: true,
variant: "tertiary",
label: searchButtonLabel,
onClick: () => setIsSearching(true),
ref: searchButtonRef
}, (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, {
icon: library_search
})))), isSearching && (0,external_wp_element_namespaceObject.createElement)("div", {
className: getAnimateClassName({
type: 'slide-in',
origin: 'left'
})
}, (0,external_wp_element_namespaceObject.createElement)(menu_title_search, {
onCloseSearch: onCloseSearch,
onSearch: onSearch,
search: search,
title: title
})));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/menu/search-no-results-found.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function NavigationSearchNoResultsFound(_ref) {
let {
search
} = _ref;
const {
navigationTree: {
items
}
} = useNavigationContext();
const resultsCount = Object.values(items).filter(item => item._isVisible).length;
if (!search || !!resultsCount) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(ItemBaseUI, null, (0,external_wp_element_namespaceObject.createElement)(ItemUI, null, (0,external_wp_i18n_namespaceObject.__)('No results found.'), " "));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigation/menu/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function NavigationMenu(props) {
const {
backButtonLabel,
children,
className,
hasSearch,
menu = ROOT_MENU,
onBackButtonClick,
onSearch: setControlledSearch,
parentMenu,
search: controlledSearch,
isSearchDebouncing,
title,
titleAction
} = props;
const [uncontrolledSearch, setUncontrolledSearch] = (0,external_wp_element_namespaceObject.useState)('');
useNavigationTreeMenu(props);
const {
activeMenu
} = useNavigationContext();
const context = {
menu,
search: uncontrolledSearch
}; // Keep the children rendered to make sure invisible items are included in the navigation tree.
if (activeMenu !== menu) {
return (0,external_wp_element_namespaceObject.createElement)(NavigationMenuContext.Provider, {
value: context
}, children);
}
const isControlledSearch = !!setControlledSearch;
const search = isControlledSearch ? controlledSearch : uncontrolledSearch;
const onSearch = isControlledSearch ? setControlledSearch : setUncontrolledSearch;
const menuTitleId = `components-navigation__menu-title-${menu}`;
const classes = classnames_default()('components-navigation__menu', className);
return (0,external_wp_element_namespaceObject.createElement)(NavigationMenuContext.Provider, {
value: context
}, (0,external_wp_element_namespaceObject.createElement)(MenuUI, {
className: classes
}, (parentMenu || onBackButtonClick) && (0,external_wp_element_namespaceObject.createElement)(back_button, {
backButtonLabel: backButtonLabel,
parentMenu: parentMenu,
onClick: onBackButtonClick
}), title && (0,external_wp_element_namespaceObject.createElement)(NavigationMenuTitle, {
hasSearch: hasSearch,
onSearch: onSearch,
search: search,
title: title,
titleAction: titleAction
}), (0,external_wp_element_namespaceObject.createElement)(navigable_container_menu, null, (0,external_wp_element_namespaceObject.createElement)("ul", {
"aria-labelledby": menuTitleId
}, children, search && !isSearchDebouncing && (0,external_wp_element_namespaceObject.createElement)(NavigationSearchNoResultsFound, {
search: search
})))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigator/context.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const initialContextValue = {
location: {},
goTo: () => {},
goBack: () => {},
goToParent: () => {},
addScreen: () => {},
removeScreen: () => {},
params: {}
};
const NavigatorContext = (0,external_wp_element_namespaceObject.createContext)(initialContextValue);
;// CONCATENATED MODULE: ./node_modules/path-to-regexp/dist.es2015/index.js
/**
* Tokenize input string.
*/
function lexer(str) {
var tokens = [];
var i = 0;
while (i < str.length) {
var char = str[i];
if (char === "*" || char === "+" || char === "?") {
tokens.push({ type: "MODIFIER", index: i, value: str[i++] });
continue;
}
if (char === "\\") {
tokens.push({ type: "ESCAPED_CHAR", index: i++, value: str[i++] });
continue;
}
if (char === "{") {
tokens.push({ type: "OPEN", index: i, value: str[i++] });
continue;
}
if (char === "}") {
tokens.push({ type: "CLOSE", index: i, value: str[i++] });
continue;
}
if (char === ":") {
var name = "";
var j = i + 1;
while (j < str.length) {
var code = str.charCodeAt(j);
if (
// `0-9`
(code >= 48 && code <= 57) ||
// `A-Z`
(code >= 65 && code <= 90) ||
// `a-z`
(code >= 97 && code <= 122) ||
// `_`
code === 95) {
name += str[j++];
continue;
}
break;
}
if (!name)
throw new TypeError("Missing parameter name at ".concat(i));
tokens.push({ type: "NAME", index: i, value: name });
i = j;
continue;
}
if (char === "(") {
var count = 1;
var pattern = "";
var j = i + 1;
if (str[j] === "?") {
throw new TypeError("Pattern cannot start with \"?\" at ".concat(j));
}
while (j < str.length) {
if (str[j] === "\\") {
pattern += str[j++] + str[j++];
continue;
}
if (str[j] === ")") {
count--;
if (count === 0) {
j++;
break;
}
}
else if (str[j] === "(") {
count++;
if (str[j + 1] !== "?") {
throw new TypeError("Capturing groups are not allowed at ".concat(j));
}
}
pattern += str[j++];
}
if (count)
throw new TypeError("Unbalanced pattern at ".concat(i));
if (!pattern)
throw new TypeError("Missing pattern at ".concat(i));
tokens.push({ type: "PATTERN", index: i, value: pattern });
i = j;
continue;
}
tokens.push({ type: "CHAR", index: i, value: str[i++] });
}
tokens.push({ type: "END", index: i, value: "" });
return tokens;
}
/**
* Parse a string for the raw tokens.
*/
function dist_es2015_parse(str, options) {
if (options === void 0) { options = {}; }
var tokens = lexer(str);
var _a = options.prefixes, prefixes = _a === void 0 ? "./" : _a;
var defaultPattern = "[^".concat(escapeString(options.delimiter || "/#?"), "]+?");
var result = [];
var key = 0;
var i = 0;
var path = "";
var tryConsume = function (type) {
if (i < tokens.length && tokens[i].type === type)
return tokens[i++].value;
};
var mustConsume = function (type) {
var value = tryConsume(type);
if (value !== undefined)
return value;
var _a = tokens[i], nextType = _a.type, index = _a.index;
throw new TypeError("Unexpected ".concat(nextType, " at ").concat(index, ", expected ").concat(type));
};
var consumeText = function () {
var result = "";
var value;
while ((value = tryConsume("CHAR") || tryConsume("ESCAPED_CHAR"))) {
result += value;
}
return result;
};
while (i < tokens.length) {
var char = tryConsume("CHAR");
var name = tryConsume("NAME");
var pattern = tryConsume("PATTERN");
if (name || pattern) {
var prefix = char || "";
if (prefixes.indexOf(prefix) === -1) {
path += prefix;
prefix = "";
}
if (path) {
result.push(path);
path = "";
}
result.push({
name: name || key++,
prefix: prefix,
suffix: "",
pattern: pattern || defaultPattern,
modifier: tryConsume("MODIFIER") || "",
});
continue;
}
var value = char || tryConsume("ESCAPED_CHAR");
if (value) {
path += value;
continue;
}
if (path) {
result.push(path);
path = "";
}
var open = tryConsume("OPEN");
if (open) {
var prefix = consumeText();
var name_1 = tryConsume("NAME") || "";
var pattern_1 = tryConsume("PATTERN") || "";
var suffix = consumeText();
mustConsume("CLOSE");
result.push({
name: name_1 || (pattern_1 ? key++ : ""),
pattern: name_1 && !pattern_1 ? defaultPattern : pattern_1,
prefix: prefix,
suffix: suffix,
modifier: tryConsume("MODIFIER") || "",
});
continue;
}
mustConsume("END");
}
return result;
}
/**
* Compile a string to a template function for the path.
*/
function dist_es2015_compile(str, options) {
return tokensToFunction(dist_es2015_parse(str, options), options);
}
/**
* Expose a method for transforming tokens into the path function.
*/
function tokensToFunction(tokens, options) {
if (options === void 0) { options = {}; }
var reFlags = flags(options);
var _a = options.encode, encode = _a === void 0 ? function (x) { return x; } : _a, _b = options.validate, validate = _b === void 0 ? true : _b;
// Compile all the tokens into regexps.
var matches = tokens.map(function (token) {
if (typeof token === "object") {
return new RegExp("^(?:".concat(token.pattern, ")$"), reFlags);
}
});
return function (data) {
var path = "";
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (typeof token === "string") {
path += token;
continue;
}
var value = data ? data[token.name] : undefined;
var optional = token.modifier === "?" || token.modifier === "*";
var repeat = token.modifier === "*" || token.modifier === "+";
if (Array.isArray(value)) {
if (!repeat) {
throw new TypeError("Expected \"".concat(token.name, "\" to not repeat, but got an array"));
}
if (value.length === 0) {
if (optional)
continue;
throw new TypeError("Expected \"".concat(token.name, "\" to not be empty"));
}
for (var j = 0; j < value.length; j++) {
var segment = encode(value[j], token);
if (validate && !matches[i].test(segment)) {
throw new TypeError("Expected all \"".concat(token.name, "\" to match \"").concat(token.pattern, "\", but got \"").concat(segment, "\""));
}
path += token.prefix + segment + token.suffix;
}
continue;
}
if (typeof value === "string" || typeof value === "number") {
var segment = encode(String(value), token);
if (validate && !matches[i].test(segment)) {
throw new TypeError("Expected \"".concat(token.name, "\" to match \"").concat(token.pattern, "\", but got \"").concat(segment, "\""));
}
path += token.prefix + segment + token.suffix;
continue;
}
if (optional)
continue;
var typeOfMessage = repeat ? "an array" : "a string";
throw new TypeError("Expected \"".concat(token.name, "\" to be ").concat(typeOfMessage));
}
return path;
};
}
/**
* Create path match function from `path-to-regexp` spec.
*/
function dist_es2015_match(str, options) {
var keys = [];
var re = pathToRegexp(str, keys, options);
return regexpToFunction(re, keys, options);
}
/**
* Create a path match function from `path-to-regexp` output.
*/
function regexpToFunction(re, keys, options) {
if (options === void 0) { options = {}; }
var _a = options.decode, decode = _a === void 0 ? function (x) { return x; } : _a;
return function (pathname) {
var m = re.exec(pathname);
if (!m)
return false;
var path = m[0], index = m.index;
var params = Object.create(null);
var _loop_1 = function (i) {
if (m[i] === undefined)
return "continue";
var key = keys[i - 1];
if (key.modifier === "*" || key.modifier === "+") {
params[key.name] = m[i].split(key.prefix + key.suffix).map(function (value) {
return decode(value, key);
});
}
else {
params[key.name] = decode(m[i], key);
}
};
for (var i = 1; i < m.length; i++) {
_loop_1(i);
}
return { path: path, index: index, params: params };
};
}
/**
* Escape a regular expression string.
*/
function escapeString(str) {
return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, "\\$1");
}
/**
* Get the flags for a regexp from the options.
*/
function flags(options) {
return options && options.sensitive ? "" : "i";
}
/**
* Pull out keys from a regexp.
*/
function regexpToRegexp(path, keys) {
if (!keys)
return path;
var groupsRegex = /\((?:\?<(.*?)>)?(?!\?)/g;
var index = 0;
var execResult = groupsRegex.exec(path.source);
while (execResult) {
keys.push({
// Use parenthesized substring match if available, index otherwise
name: execResult[1] || index++,
prefix: "",
suffix: "",
modifier: "",
pattern: "",
});
execResult = groupsRegex.exec(path.source);
}
return path;
}
/**
* Transform an array into a regexp.
*/
function arrayToRegexp(paths, keys, options) {
var parts = paths.map(function (path) { return pathToRegexp(path, keys, options).source; });
return new RegExp("(?:".concat(parts.join("|"), ")"), flags(options));
}
/**
* Create a path regexp from string input.
*/
function stringToRegexp(path, keys, options) {
return tokensToRegexp(dist_es2015_parse(path, options), keys, options);
}
/**
* Expose a function for taking tokens and returning a RegExp.
*/
function tokensToRegexp(tokens, keys, options) {
if (options === void 0) { options = {}; }
var _a = options.strict, strict = _a === void 0 ? false : _a, _b = options.start, start = _b === void 0 ? true : _b, _c = options.end, end = _c === void 0 ? true : _c, _d = options.encode, encode = _d === void 0 ? function (x) { return x; } : _d, _e = options.delimiter, delimiter = _e === void 0 ? "/#?" : _e, _f = options.endsWith, endsWith = _f === void 0 ? "" : _f;
var endsWithRe = "[".concat(escapeString(endsWith), "]|$");
var delimiterRe = "[".concat(escapeString(delimiter), "]");
var route = start ? "^" : "";
// Iterate over the tokens and create our regexp string.
for (var _i = 0, tokens_1 = tokens; _i < tokens_1.length; _i++) {
var token = tokens_1[_i];
if (typeof token === "string") {
route += escapeString(encode(token));
}
else {
var prefix = escapeString(encode(token.prefix));
var suffix = escapeString(encode(token.suffix));
if (token.pattern) {
if (keys)
keys.push(token);
if (prefix || suffix) {
if (token.modifier === "+" || token.modifier === "*") {
var mod = token.modifier === "*" ? "?" : "";
route += "(?:".concat(prefix, "((?:").concat(token.pattern, ")(?:").concat(suffix).concat(prefix, "(?:").concat(token.pattern, "))*)").concat(suffix, ")").concat(mod);
}
else {
route += "(?:".concat(prefix, "(").concat(token.pattern, ")").concat(suffix, ")").concat(token.modifier);
}
}
else {
if (token.modifier === "+" || token.modifier === "*") {
route += "((?:".concat(token.pattern, ")").concat(token.modifier, ")");
}
else {
route += "(".concat(token.pattern, ")").concat(token.modifier);
}
}
}
else {
route += "(?:".concat(prefix).concat(suffix, ")").concat(token.modifier);
}
}
}
if (end) {
if (!strict)
route += "".concat(delimiterRe, "?");
route += !options.endsWith ? "$" : "(?=".concat(endsWithRe, ")");
}
else {
var endToken = tokens[tokens.length - 1];
var isEndDelimited = typeof endToken === "string"
? delimiterRe.indexOf(endToken[endToken.length - 1]) > -1
: endToken === undefined;
if (!strict) {
route += "(?:".concat(delimiterRe, "(?=").concat(endsWithRe, "))?");
}
if (!isEndDelimited) {
route += "(?=".concat(delimiterRe, "|").concat(endsWithRe, ")");
}
}
return new RegExp(route, flags(options));
}
/**
* Normalize the given path string, returning a regular expression.
*
* An empty array can be passed in for the keys, which will hold the
* placeholder key descriptions. For example, using `/user/:id`, `keys` will
* contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
*/
function pathToRegexp(path, keys, options) {
if (path instanceof RegExp)
return regexpToRegexp(path, keys);
if (Array.isArray(path))
return arrayToRegexp(path, keys, options);
return stringToRegexp(path, keys, options);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigator/utils/router.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function matchPath(path, pattern) {
const matchingFunction = dist_es2015_match(pattern, {
decode: decodeURIComponent
});
return matchingFunction(path);
}
function patternMatch(path, screens) {
for (const screen of screens) {
const matched = matchPath(path, screen.path);
if (matched) {
return {
params: matched.params,
id: screen.id
};
}
}
return undefined;
}
function findParent(path, screens) {
if (!path.startsWith('/')) {
return undefined;
}
const pathParts = path.split('/');
let parentPath;
while (pathParts.length > 1 && parentPath === undefined) {
pathParts.pop();
const potentialParentPath = pathParts.join('/') === '' ? '/' : pathParts.join('/');
if (screens.find(screen => {
return matchPath(potentialParentPath, screen.path) !== false;
})) {
parentPath = potentialParentPath;
}
}
return parentPath;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigator/navigator-provider/component.js
function component_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const MAX_HISTORY_LENGTH = 50;
function screensReducer() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'add':
return [...state, action.screen];
case 'remove':
return state.filter(s => s.id !== action.screen.id);
}
return state;
}
var component_ref = true ? {
name: "15bx5k",
styles: "overflow-x:hidden"
} : 0;
function UnconnectedNavigatorProvider(props, forwardedRef) {
const {
initialPath,
children,
className,
...otherProps
} = useContextSystem(props, 'NavigatorProvider');
const [locationHistory, setLocationHistory] = (0,external_wp_element_namespaceObject.useState)([{
path: initialPath
}]);
const currentLocationHistory = (0,external_wp_element_namespaceObject.useRef)([]);
const [screens, dispatch] = (0,external_wp_element_namespaceObject.useReducer)(screensReducer, []);
const currentScreens = (0,external_wp_element_namespaceObject.useRef)([]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
currentScreens.current = screens;
}, [screens]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
currentLocationHistory.current = locationHistory;
}, [locationHistory]);
const currentMatch = (0,external_wp_element_namespaceObject.useRef)();
const matchedPath = (0,external_wp_element_namespaceObject.useMemo)(() => {
let currentPath;
if (locationHistory.length === 0 || (currentPath = locationHistory[locationHistory.length - 1].path) === undefined) {
currentMatch.current = undefined;
return undefined;
}
const resolvePath = path => {
const newMatch = patternMatch(path, screens); // If the new match is the same as the current match,
// return the previous one for performance reasons.
if (currentMatch.current && newMatch && external_wp_isShallowEqual_default()(newMatch.params, currentMatch.current.params) && newMatch.id === currentMatch.current.id) {
return currentMatch.current;
}
return newMatch;
};
const newMatch = resolvePath(currentPath);
currentMatch.current = newMatch;
return newMatch;
}, [screens, locationHistory]);
const addScreen = (0,external_wp_element_namespaceObject.useCallback)(screen => dispatch({
type: 'add',
screen
}), []);
const removeScreen = (0,external_wp_element_namespaceObject.useCallback)(screen => dispatch({
type: 'remove',
screen
}), []);
const goBack = (0,external_wp_element_namespaceObject.useCallback)(() => {
setLocationHistory(prevLocationHistory => {
if (prevLocationHistory.length <= 1) {
return prevLocationHistory;
}
return [...prevLocationHistory.slice(0, -2), { ...prevLocationHistory[prevLocationHistory.length - 2],
isBack: true,
hasRestoredFocus: false
}];
});
}, []);
const goTo = (0,external_wp_element_namespaceObject.useCallback)(function (path) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const {
focusTargetSelector,
isBack = false,
...restOptions
} = options;
const isNavigatingToPreviousPath = isBack && currentLocationHistory.current.length > 1 && currentLocationHistory.current[currentLocationHistory.current.length - 2].path === path;
if (isNavigatingToPreviousPath) {
goBack();
return;
}
setLocationHistory(prevLocationHistory => {
const newLocation = { ...restOptions,
path,
isBack,
hasRestoredFocus: false
};
if (prevLocationHistory.length < 1) {
return [newLocation];
}
return [...prevLocationHistory.slice(prevLocationHistory.length > MAX_HISTORY_LENGTH - 1 ? 1 : 0, -1), // Assign `focusTargetSelector` to the previous location in history
// (the one we just navigated from).
{ ...prevLocationHistory[prevLocationHistory.length - 1],
focusTargetSelector
}, newLocation];
});
}, [goBack]);
const goToParent = (0,external_wp_element_namespaceObject.useCallback)(() => {
const currentPath = currentLocationHistory.current[currentLocationHistory.current.length - 1].path;
if (currentPath === undefined) {
return;
}
const parentPath = findParent(currentPath, currentScreens.current);
if (parentPath === undefined) {
return;
}
goTo(parentPath, {
isBack: true
});
}, [goTo]);
const navigatorContextValue = (0,external_wp_element_namespaceObject.useMemo)(() => ({
location: { ...locationHistory[locationHistory.length - 1],
isInitial: locationHistory.length === 1
},
params: matchedPath ? matchedPath.params : {},
match: matchedPath ? matchedPath.id : undefined,
goTo,
goBack,
goToParent,
addScreen,
removeScreen
}), [locationHistory, matchedPath, goTo, goBack, goToParent, addScreen, removeScreen]);
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)( // Prevents horizontal overflow while animating screen transitions.
() => cx(component_ref, className), [className, cx]);
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({
ref: forwardedRef,
className: classes
}, otherProps), (0,external_wp_element_namespaceObject.createElement)(NavigatorContext.Provider, {
value: navigatorContextValue
}, children));
}
/**
* The `NavigatorProvider` component allows rendering nested views/panels/menus
* (via the `NavigatorScreen` component and navigate between these different
* view (via the `NavigatorButton` and `NavigatorBackButton` components or the
* `useNavigator` hook).
*
* @example
* ```jsx
* import {
* __experimentalNavigatorProvider as NavigatorProvider,
* __experimentalNavigatorScreen as NavigatorScreen,
* __experimentalNavigatorButton as NavigatorButton,
* __experimentalNavigatorBackButton as NavigatorBackButton,
* } from '@wordpress/components';
*
* const MyNavigation = () => (
* <NavigatorProvider initialPath="/">
* <NavigatorScreen path="/">
* <p>This is the home screen.</p>
* <NavigatorButton path="/child">
* Navigate to child screen.
* </NavigatorButton>
* </NavigatorScreen>
*
* <NavigatorScreen path="/child">
* <p>This is the child screen.</p>
* <NavigatorBackButton>
* Go back
* </NavigatorBackButton>
* </NavigatorScreen>
* </NavigatorProvider>
* );
* ```
*/
const NavigatorProvider = contextConnect(UnconnectedNavigatorProvider, 'NavigatorProvider');
/* harmony default export */ var navigator_provider_component = (NavigatorProvider);
;// CONCATENATED MODULE: external ["wp","escapeHtml"]
var external_wp_escapeHtml_namespaceObject = window["wp"]["escapeHtml"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigator/navigator-screen/component.js
function navigator_screen_component_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
// eslint-disable-next-line no-restricted-imports
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const animationEnterDelay = 0;
const animationEnterDuration = 0.14;
const animationExitDuration = 0.14;
const animationExitDelay = 0; // Props specific to `framer-motion` can't be currently passed to `NavigatorScreen`,
// as some of them would overlap with HTML props (e.g. `onAnimationStart`, ...)
var navigator_screen_component_ref = true ? {
name: "14x3t6z",
styles: "overflow-x:auto;max-height:100%"
} : 0;
function UnconnectedNavigatorScreen(props, forwardedRef) {
const screenId = (0,external_wp_element_namespaceObject.useId)();
const {
children,
className,
path,
...otherProps
} = useContextSystem(props, 'NavigatorScreen');
const prefersReducedMotion = (0,external_wp_compose_namespaceObject.useReducedMotion)();
const {
location,
match,
addScreen,
removeScreen
} = (0,external_wp_element_namespaceObject.useContext)(NavigatorContext);
const isMatch = match === screenId;
const wrapperRef = (0,external_wp_element_namespaceObject.useRef)(null);
(0,external_wp_element_namespaceObject.useEffect)(() => {
const screen = {
id: screenId,
path: (0,external_wp_escapeHtml_namespaceObject.escapeAttribute)(path)
};
addScreen(screen);
return () => removeScreen(screen);
}, [screenId, path, addScreen, removeScreen]);
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => cx(navigator_screen_component_ref, className), [className, cx]);
const locationRef = (0,external_wp_element_namespaceObject.useRef)(location);
(0,external_wp_element_namespaceObject.useEffect)(() => {
locationRef.current = location;
}, [location]); // Focus restoration
const isInitialLocation = location.isInitial && !location.isBack;
(0,external_wp_element_namespaceObject.useEffect)(() => {
// Only attempt to restore focus:
// - if the current location is not the initial one (to avoid moving focus on page load)
// - when the screen becomes visible
// - if the wrapper ref has been assigned
// - if focus hasn't already been restored for the current location
if (isInitialLocation || !isMatch || !wrapperRef.current || locationRef.current.hasRestoredFocus) {
return;
}
const activeElement = wrapperRef.current.ownerDocument.activeElement; // If an element is already focused within the wrapper do not focus the
// element. This prevents inputs or buttons from losing focus unnecessarily.
if (wrapperRef.current.contains(activeElement)) {
return;
}
let elementToFocus = null; // When navigating back, if a selector is provided, use it to look for the
// target element (assumed to be a node inside the current NavigatorScreen)
if (location.isBack && location !== null && location !== void 0 && location.focusTargetSelector) {
elementToFocus = wrapperRef.current.querySelector(location.focusTargetSelector);
} // If the previous query didn't run or find any element to focus, fallback
// to the first tabbable element in the screen (or the screen itself).
if (!elementToFocus) {
const firstTabbable = external_wp_dom_namespaceObject.focus.tabbable.find(wrapperRef.current)[0];
elementToFocus = firstTabbable !== null && firstTabbable !== void 0 ? firstTabbable : wrapperRef.current;
}
locationRef.current.hasRestoredFocus = true;
elementToFocus.focus();
}, [isInitialLocation, isMatch, location.isBack, location.focusTargetSelector]);
const mergedWrapperRef = (0,external_wp_compose_namespaceObject.useMergeRefs)([forwardedRef, wrapperRef]);
if (!isMatch) {
return null;
}
if (prefersReducedMotion) {
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({
ref: mergedWrapperRef,
className: classes
}, otherProps), children);
}
const animate = {
opacity: 1,
transition: {
delay: animationEnterDelay,
duration: animationEnterDuration,
ease: 'easeInOut'
},
x: 0
};
const initial = {
opacity: 0,
x: (0,external_wp_i18n_namespaceObject.isRTL)() && location.isBack || !(0,external_wp_i18n_namespaceObject.isRTL)() && !location.isBack ? 50 : -50
};
const exit = {
delay: animationExitDelay,
opacity: 0,
x: !(0,external_wp_i18n_namespaceObject.isRTL)() && location.isBack || (0,external_wp_i18n_namespaceObject.isRTL)() && !location.isBack ? 50 : -50,
transition: {
duration: animationExitDuration,
ease: 'easeInOut'
}
};
const animatedProps = {
animate,
exit,
initial
};
return (0,external_wp_element_namespaceObject.createElement)(motion.div, extends_extends({
ref: mergedWrapperRef,
className: classes
}, otherProps, animatedProps), children);
}
/**
* The `NavigatorScreen` component represents a single view/screen/panel and
* should be used in combination with the `NavigatorProvider`, the
* `NavigatorButton` and the `NavigatorBackButton` components (or the `useNavigator`
* hook).
*
* @example
* ```jsx
* import {
* __experimentalNavigatorProvider as NavigatorProvider,
* __experimentalNavigatorScreen as NavigatorScreen,
* __experimentalNavigatorButton as NavigatorButton,
* __experimentalNavigatorBackButton as NavigatorBackButton,
* } from '@wordpress/components';
*
* const MyNavigation = () => (
* <NavigatorProvider initialPath="/">
* <NavigatorScreen path="/">
* <p>This is the home screen.</p>
* <NavigatorButton path="/child">
* Navigate to child screen.
* </NavigatorButton>
* </NavigatorScreen>
*
* <NavigatorScreen path="/child">
* <p>This is the child screen.</p>
* <NavigatorBackButton>
* Go back
* </NavigatorBackButton>
* </NavigatorScreen>
* </NavigatorProvider>
* );
* ```
*/
const NavigatorScreen = contextConnect(UnconnectedNavigatorScreen, 'NavigatorScreen');
/* harmony default export */ var navigator_screen_component = (NavigatorScreen);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigator/use-navigator.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Retrieves a `navigator` instance.
*/
function useNavigator() {
const {
location,
params,
goTo,
goBack,
goToParent
} = (0,external_wp_element_namespaceObject.useContext)(NavigatorContext);
return {
location,
goTo,
goBack,
goToParent,
params
};
}
/* harmony default export */ var use_navigator = (useNavigator);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigator/navigator-button/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const cssSelectorForAttribute = (attrName, attrValue) => `[${attrName}="${attrValue}"]`;
function useNavigatorButton(props) {
const {
path,
onClick,
as = build_module_button,
attributeName = 'id',
...otherProps
} = useContextSystem(props, 'NavigatorButton');
const escapedPath = (0,external_wp_escapeHtml_namespaceObject.escapeAttribute)(path);
const {
goTo
} = use_navigator();
const handleClick = (0,external_wp_element_namespaceObject.useCallback)(e => {
e.preventDefault();
goTo(escapedPath, {
focusTargetSelector: cssSelectorForAttribute(attributeName, escapedPath)
});
onClick === null || onClick === void 0 ? void 0 : onClick(e);
}, [goTo, onClick, attributeName, escapedPath]);
return {
as,
onClick: handleClick,
...otherProps,
[attributeName]: escapedPath
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigator/navigator-button/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedNavigatorButton(props, forwardedRef) {
const navigatorButtonProps = useNavigatorButton(props);
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({
ref: forwardedRef
}, navigatorButtonProps));
}
/**
* The `NavigatorButton` component can be used to navigate to a screen and should
* be used in combination with the `NavigatorProvider`, the `NavigatorScreen`
* and the `NavigatorBackButton` components (or the `useNavigator` hook).
*
* @example
* ```jsx
* import {
* __experimentalNavigatorProvider as NavigatorProvider,
* __experimentalNavigatorScreen as NavigatorScreen,
* __experimentalNavigatorButton as NavigatorButton,
* __experimentalNavigatorBackButton as NavigatorBackButton,
* } from '@wordpress/components';
*
* const MyNavigation = () => (
* <NavigatorProvider initialPath="/">
* <NavigatorScreen path="/">
* <p>This is the home screen.</p>
* <NavigatorButton path="/child">
* Navigate to child screen.
* </NavigatorButton>
* </NavigatorScreen>
*
* <NavigatorScreen path="/child">
* <p>This is the child screen.</p>
* <NavigatorBackButton>
* Go back
* </NavigatorBackButton>
* </NavigatorScreen>
* </NavigatorProvider>
* );
* ```
*/
const NavigatorButton = contextConnect(UnconnectedNavigatorButton, 'NavigatorButton');
/* harmony default export */ var navigator_button_component = (NavigatorButton);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigator/navigator-back-button/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useNavigatorBackButton(props) {
const {
onClick,
as = build_module_button,
goToParent: goToParentProp = false,
...otherProps
} = useContextSystem(props, 'NavigatorBackButton');
const {
goBack,
goToParent
} = use_navigator();
const handleClick = (0,external_wp_element_namespaceObject.useCallback)(e => {
e.preventDefault();
if (goToParentProp) {
goToParent();
} else {
goBack();
}
onClick === null || onClick === void 0 ? void 0 : onClick(e);
}, [goToParentProp, goToParent, goBack, onClick]);
return {
as,
onClick: handleClick,
...otherProps
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigator/navigator-back-button/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedNavigatorBackButton(props, forwardedRef) {
const navigatorBackButtonProps = useNavigatorBackButton(props);
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({
ref: forwardedRef
}, navigatorBackButtonProps));
}
/**
* The `NavigatorBackButton` component can be used to navigate to a screen and
* should be used in combination with the `NavigatorProvider`, the
* `NavigatorScreen` and the `NavigatorButton` components (or the `useNavigator`
* hook).
*
* @example
* ```jsx
* import {
* __experimentalNavigatorProvider as NavigatorProvider,
* __experimentalNavigatorScreen as NavigatorScreen,
* __experimentalNavigatorButton as NavigatorButton,
* __experimentalNavigatorBackButton as NavigatorBackButton,
* } from '@wordpress/components';
*
* const MyNavigation = () => (
* <NavigatorProvider initialPath="/">
* <NavigatorScreen path="/">
* <p>This is the home screen.</p>
* <NavigatorButton path="/child">
* Navigate to child screen.
* </NavigatorButton>
* </NavigatorScreen>
*
* <NavigatorScreen path="/child">
* <p>This is the child screen.</p>
* <NavigatorBackButton>
* Go back
* </NavigatorBackButton>
* </NavigatorScreen>
* </NavigatorProvider>
* );
* ```
*/
const NavigatorBackButton = contextConnect(UnconnectedNavigatorBackButton, 'NavigatorBackButton');
/* harmony default export */ var navigator_back_button_component = (NavigatorBackButton);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/navigator/navigator-to-parent-button/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedNavigatorToParentButton(props, forwardedRef) {
const navigatorToParentButtonProps = useNavigatorBackButton({ ...props,
goToParent: true
});
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({
ref: forwardedRef
}, navigatorToParentButtonProps));
}
/*
* The `NavigatorToParentButton` component can be used to navigate to a screen and
* should be used in combination with the `NavigatorProvider`, the
* `NavigatorScreen` and the `NavigatorButton` components (or the `useNavigator`
* hook).
*
* @example
* ```jsx
* import {
* __experimentalNavigatorProvider as NavigatorProvider,
* __experimentalNavigatorScreen as NavigatorScreen,
* __experimentalNavigatorButton as NavigatorButton,
* __experimentalNavigatorToParentButton as NavigatorToParentButton,
* } from '@wordpress/components';
*
* const MyNavigation = () => (
* <NavigatorProvider initialPath="/">
* <NavigatorScreen path="/">
* <p>This is the home screen.</p>
* <NavigatorButton path="/child">
* Navigate to child screen.
* </NavigatorButton>
* </NavigatorScreen>
*
* <NavigatorScreen path="/child">
* <p>This is the child screen.</p>
* <NavigatorToParentButton>
* Go to parent
* </NavigatorToParentButton>
* </NavigatorScreen>
* </NavigatorProvider>
* );
* ```
*/
const NavigatorToParentButton = contextConnect(UnconnectedNavigatorToParentButton, 'NavigatorToParentButton');
/* harmony default export */ var navigator_to_parent_button_component = (NavigatorToParentButton);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/notice/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const notice_noop = () => {};
/**
* Custom hook which announces the message with the given politeness, if a
* valid message is provided.
*/
function useSpokenMessage(message, politeness) {
const spokenMessage = typeof message === 'string' ? message : (0,external_wp_element_namespaceObject.renderToString)(message);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (spokenMessage) {
(0,external_wp_a11y_namespaceObject.speak)(spokenMessage, politeness);
}
}, [spokenMessage, politeness]);
}
function getDefaultPoliteness(status) {
switch (status) {
case 'success':
case 'warning':
case 'info':
return 'polite';
case 'error':
default:
return 'assertive';
}
}
/**
* `Notice` is a component used to communicate feedback to the user.
*
*```jsx
* import { Notice } from `@wordpress/components`;
*
* const MyNotice = () => (
* <Notice status="error">An unknown error occurred.</Notice>
* );
* ```
*/
function Notice(_ref) {
let {
className,
status = 'info',
children,
spokenMessage = children,
onRemove = notice_noop,
isDismissible = true,
actions = [],
politeness = getDefaultPoliteness(status),
__unstableHTML,
// onDismiss is a callback executed when the notice is dismissed.
// It is distinct from onRemove, which _looks_ like a callback but is
// actually the function to call to remove the notice from the UI.
onDismiss = notice_noop
} = _ref;
useSpokenMessage(spokenMessage, politeness);
const classes = classnames_default()(className, 'components-notice', 'is-' + status, {
'is-dismissible': isDismissible
});
if (__unstableHTML && typeof children === 'string') {
children = (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.RawHTML, null, children);
}
const onDismissNotice = event => {
var _event$preventDefault;
event === null || event === void 0 ? void 0 : (_event$preventDefault = event.preventDefault) === null || _event$preventDefault === void 0 ? void 0 : _event$preventDefault.call(event);
onDismiss();
onRemove();
};
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classes
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-notice__content"
}, children, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-notice__actions"
}, actions.map((_ref2, index) => {
let {
className: buttonCustomClasses,
label,
isPrimary,
variant,
noDefaultClasses = false,
onClick,
url
} = _ref2;
let computedVariant = variant;
if (variant !== 'primary' && !noDefaultClasses) {
computedVariant = !url ? 'secondary' : 'link';
}
if (typeof computedVariant === 'undefined' && isPrimary) {
computedVariant = 'primary';
}
return (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
key: index,
href: url,
variant: computedVariant,
onClick: url ? undefined : onClick,
className: classnames_default()('components-notice__action', buttonCustomClasses)
}, label);
}))), isDismissible && (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
className: "components-notice__dismiss",
icon: library_close,
label: (0,external_wp_i18n_namespaceObject.__)('Dismiss this notice'),
onClick: onDismissNotice,
showTooltip: false
}));
}
/* harmony default export */ var build_module_notice = (Notice);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/notice/list.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const list_noop = () => {};
/**
* `NoticeList` is a component used to render a collection of notices.
*
*```jsx
* import { Notice, NoticeList } from `@wordpress/components`;
*
* const MyNoticeList = () => {
* const [ notices, setNotices ] = useState( [
* {
* id: 'second-notice',
* content: 'second notice content',
* },
* {
* id: 'fist-notice',
* content: 'first notice content',
* },
* ] );
*
* const removeNotice = ( id ) => {
* setNotices( notices.filter( ( notice ) => notice.id !== id ) );
* };
*
* return <NoticeList notices={ notices } onRemove={ removeNotice } />;
*};
*```
*/
function NoticeList(_ref) {
let {
notices,
onRemove = list_noop,
className,
children
} = _ref;
const removeNotice = id => () => onRemove(id);
className = classnames_default()('components-notice-list', className);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: className
}, children, [...notices].reverse().map(notice => {
const {
content,
...restNotice
} = notice;
return (0,external_wp_element_namespaceObject.createElement)(build_module_notice, extends_extends({}, restNotice, {
key: notice.id,
onRemove: removeNotice(notice.id)
}), notice.content);
}));
}
/* harmony default export */ var list = (NoticeList);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/panel/header.js
function PanelHeader(_ref) {
let {
label,
children
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-panel__header"
}, label && (0,external_wp_element_namespaceObject.createElement)("h2", null, label), children);
}
/* harmony default export */ var panel_header = (PanelHeader);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/panel/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function Panel(_ref, ref) {
let {
header,
className,
children
} = _ref;
const classNames = classnames_default()(className, 'components-panel');
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classNames,
ref: ref
}, header && (0,external_wp_element_namespaceObject.createElement)(panel_header, {
label: header
}), children);
}
/* harmony default export */ var panel = ((0,external_wp_element_namespaceObject.forwardRef)(Panel));
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/chevron-up.js
/**
* WordPress dependencies
*/
const chevronUp = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M6.5 12.4L12 8l5.5 4.4-.9 1.2L12 10l-4.5 3.6-1-1.2z"
}));
/* harmony default export */ var chevron_up = (chevronUp);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/panel/body.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const body_noop = () => {};
function PanelBody(_ref, ref) {
let {
buttonProps = {},
children,
className,
icon,
initialOpen,
onToggle = body_noop,
opened,
title,
scrollAfterOpen = true
} = _ref;
const [isOpened, setIsOpened] = use_controlled_state(opened, {
initial: initialOpen === undefined ? true : initialOpen
});
const nodeRef = (0,external_wp_element_namespaceObject.useRef)(); // Defaults to 'smooth' scrolling
// https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
const scrollBehavior = (0,external_wp_compose_namespaceObject.useReducedMotion)() ? 'auto' : 'smooth';
const handleOnToggle = event => {
event.preventDefault();
const next = !isOpened;
setIsOpened(next);
onToggle(next);
}; // Ref is used so that the effect does not re-run upon scrollAfterOpen changing value.
const scrollAfterOpenRef = (0,external_wp_element_namespaceObject.useRef)();
scrollAfterOpenRef.current = scrollAfterOpen; // Runs after initial render.
use_update_effect(() => {
var _nodeRef$current;
if (isOpened && scrollAfterOpenRef.current && (_nodeRef$current = nodeRef.current) !== null && _nodeRef$current !== void 0 && _nodeRef$current.scrollIntoView) {
/*
* Scrolls the content into view when visible.
* This improves the UX when there are multiple stacking <PanelBody />
* components in a scrollable container.
*/
nodeRef.current.scrollIntoView({
inline: 'nearest',
block: 'nearest',
behavior: scrollBehavior
});
}
}, [isOpened, scrollBehavior]);
const classes = classnames_default()('components-panel__body', className, {
'is-opened': isOpened
});
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classes,
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([nodeRef, ref])
}, (0,external_wp_element_namespaceObject.createElement)(PanelBodyTitle, extends_extends({
icon: icon,
isOpened: isOpened,
onClick: handleOnToggle,
title: title
}, buttonProps)), typeof children === 'function' ? children({
opened: isOpened
}) : isOpened && children);
}
const PanelBodyTitle = (0,external_wp_element_namespaceObject.forwardRef)((_ref2, ref) => {
let {
isOpened,
icon,
title,
...props
} = _ref2;
if (!title) return null;
return (0,external_wp_element_namespaceObject.createElement)("h2", {
className: "components-panel__body-title"
}, (0,external_wp_element_namespaceObject.createElement)(build_module_button, extends_extends({
className: "components-panel__body-toggle",
"aria-expanded": isOpened,
ref: ref
}, props), (0,external_wp_element_namespaceObject.createElement)("span", {
"aria-hidden": "true"
}, (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
className: "components-panel__arrow",
icon: isOpened ? chevron_up : chevron_down
})), title, icon && (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: icon,
className: "components-panel__icon",
size: 20
})));
});
const body_ForwardedComponent = (0,external_wp_element_namespaceObject.forwardRef)(PanelBody);
body_ForwardedComponent.displayName = 'PanelBody';
/* harmony default export */ var body = (body_ForwardedComponent);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/panel/row.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
const PanelRow = (_ref, ref) => {
let {
className,
children
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('components-panel__row', className),
ref: ref
}, children);
};
/* harmony default export */ var row = ((0,external_wp_element_namespaceObject.forwardRef)(PanelRow));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/placeholder/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const PlaceholderIllustration = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
className: "components-placeholder__illustration",
fill: "none",
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 60 60",
preserveAspectRatio: "none"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
vectorEffect: "non-scaling-stroke",
d: "M60 60 0 0"
}));
/**
* Renders a placeholder. Normally used by blocks to render their empty state.
*
* ```jsx
* import { Placeholder } from '@wordpress/components';
* import { more } from '@wordpress/icons';
*
* const MyPlaceholder = () => <Placeholder icon={ more } label="Placeholder" />;
* ```
*/
function Placeholder(props) {
const {
icon,
children,
label,
instructions,
className,
notices,
preview,
isColumnLayout,
withIllustration,
...additionalProps
} = props;
const [resizeListener, {
width
}] = (0,external_wp_compose_namespaceObject.useResizeObserver)(); // Since `useResizeObserver` will report a width of `null` until after the
// first render, avoid applying any modifier classes until width is known.
let modifierClassNames;
if (typeof width === 'number') {
modifierClassNames = {
'is-large': width >= 480,
'is-medium': width >= 160 && width < 480,
'is-small': width < 160
};
}
const classes = classnames_default()('components-placeholder', className, modifierClassNames, withIllustration ? 'has-illustration' : null);
const fieldsetClasses = classnames_default()('components-placeholder__fieldset', {
'is-column-layout': isColumnLayout
});
return (0,external_wp_element_namespaceObject.createElement)("div", extends_extends({}, additionalProps, {
className: classes
}), withIllustration ? PlaceholderIllustration : null, resizeListener, notices, preview && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-placeholder__preview"
}, preview), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-placeholder__label"
}, (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: icon
}), label), (0,external_wp_element_namespaceObject.createElement)("fieldset", {
className: fieldsetClasses
}, !!instructions && (0,external_wp_element_namespaceObject.createElement)("legend", {
className: "components-placeholder__instructions"
}, instructions), children));
}
/* harmony default export */ var placeholder = (Placeholder);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/query-controls/terms.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
/**
* Returns terms in a tree form.
*
* @param flatTerms Array of terms in flat format.
*
* @return Terms in tree format.
*/
function buildTermsTree(flatTerms) {
const flatTermsWithParentAndChildren = flatTerms.map(term => {
return {
children: [],
parent: null,
...term,
id: String(term.id)
};
});
const termsByParent = (0,external_lodash_namespaceObject.groupBy)(flatTermsWithParentAndChildren, 'parent');
if (termsByParent.null && termsByParent.null.length) {
return flatTermsWithParentAndChildren;
}
const fillWithChildren = terms => {
return terms.map(term => {
const children = termsByParent[term.id];
return { ...term,
children: children && children.length ? fillWithChildren(children) : []
};
});
};
return fillWithChildren(termsByParent['0'] || []);
}
;// CONCATENATED MODULE: external ["wp","htmlEntities"]
var external_wp_htmlEntities_namespaceObject = window["wp"]["htmlEntities"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tree-select/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function getSelectOptions(tree) {
let level = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
return tree.flatMap(treeNode => [{
value: treeNode.id,
label: '\u00A0'.repeat(level * 3) + (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(treeNode.name)
}, ...getSelectOptions(treeNode.children || [], level + 1)]);
}
/**
* TreeSelect component is used to generate select input fields.
*
* @example
* ```jsx
* import { TreeSelect } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyTreeSelect = () => {
* const [ page, setPage ] = useState( 'p21' );
*
* return (
* <TreeSelect
* label="Parent page"
* noOptionLabel="No parent page"
* onChange={ ( newPage ) => setPage( newPage ) }
* selectedId={ page }
* tree={ [
* {
* name: 'Page 1',
* id: 'p1',
* children: [
* { name: 'Descend 1 of page 1', id: 'p11' },
* { name: 'Descend 2 of page 1', id: 'p12' },
* ],
* },
* {
* name: 'Page 2',
* id: 'p2',
* children: [
* {
* name: 'Descend 1 of page 2',
* id: 'p21',
* children: [
* {
* name: 'Descend 1 of Descend 1 of page 2',
* id: 'p211',
* },
* ],
* },
* ],
* },
* ] }
* />
* );
* }
* ```
*/
function TreeSelect(_ref) {
let {
label,
noOptionLabel,
onChange,
selectedId,
tree = [],
...props
} = _ref;
const options = (0,external_wp_element_namespaceObject.useMemo)(() => {
return [noOptionLabel && {
value: '',
label: noOptionLabel
}, ...getSelectOptions(tree)].filter(option => !!option);
}, [noOptionLabel, tree]);
return (0,external_wp_element_namespaceObject.createElement)(SelectControl, extends_extends({
label,
options,
onChange,
value: selectedId
}, props));
}
/* harmony default export */ var tree_select = (TreeSelect);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/query-controls/author-select.js
/**
* Internal dependencies
*/
function AuthorSelect(_ref) {
let {
label,
noOptionLabel,
authorList,
selectedAuthorId,
onChange: onChangeProp
} = _ref;
if (!authorList) return null;
const termsTree = buildTermsTree(authorList);
return (0,external_wp_element_namespaceObject.createElement)(tree_select, {
label,
noOptionLabel,
// Since the `multiple` attribute is not passed to `TreeSelect`, it is
// safe to assume that the argument of `onChange` cannot be `string[]`.
// The correct solution would be to type `SelectControl` better, so that
// the type of `value` and `onChange` vary depending on `multiple`.
onChange: onChangeProp,
tree: termsTree,
selectedId: selectedAuthorId !== undefined ? String(selectedAuthorId) : undefined
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/query-controls/category-select.js
/**
* Internal dependencies
*/
/**
* WordPress dependencies
*/
function CategorySelect(_ref) {
let {
label,
noOptionLabel,
categoriesList,
selectedCategoryId,
onChange: onChangeProp,
...props
} = _ref;
const termsTree = (0,external_wp_element_namespaceObject.useMemo)(() => {
return buildTermsTree(categoriesList);
}, [categoriesList]);
return (0,external_wp_element_namespaceObject.createElement)(tree_select, extends_extends({
label,
noOptionLabel,
// Since the `multiple` attribute is not passed to `TreeSelect`, it is
// safe to assume that the argument of `onChange` cannot be `string[]`.
// The correct solution would be to type `SelectControl` better, so that
// the type of `value` and `onChange` vary depending on `multiple`.
onChange: onChangeProp,
tree: termsTree,
selectedId: selectedCategoryId !== undefined ? String(selectedCategoryId) : undefined
}, props));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/query-controls/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const DEFAULT_MIN_ITEMS = 1;
const DEFAULT_MAX_ITEMS = 100;
const MAX_CATEGORIES_SUGGESTIONS = 20;
function isSingleCategorySelection(props) {
return 'categoriesList' in props;
}
function isMultipleCategorySelection(props) {
return 'categorySuggestions' in props;
}
/**
* Controls to query for posts.
*
* ```jsx
* const MyQueryControls = () => (
* <QueryControls
* { ...{ maxItems, minItems, numberOfItems, order, orderBy } }
* onOrderByChange={ ( newOrderBy ) => {
* updateQuery( { orderBy: newOrderBy } )
* }
* onOrderChange={ ( newOrder ) => {
* updateQuery( { order: newOrder } )
* }
* categoriesList={ categories }
* selectedCategoryId={ category }
* onCategoryChange={ ( newCategory ) => {
* updateQuery( { category: newCategory } )
* }
* onNumberOfItemsChange={ ( newNumberOfItems ) => {
* updateQuery( { numberOfItems: newNumberOfItems } )
* } }
* />
* );
* ```
*/
function QueryControls(_ref) {
let {
authorList,
selectedAuthorId,
numberOfItems,
order,
orderBy,
maxItems = DEFAULT_MAX_ITEMS,
minItems = DEFAULT_MIN_ITEMS,
onAuthorChange,
onNumberOfItemsChange,
onOrderChange,
onOrderByChange,
// Props for single OR multiple category selection are not destructured here,
// but instead are destructured inline where necessary.
...props
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, [onOrderChange && onOrderByChange && (0,external_wp_element_namespaceObject.createElement)(select_control, {
__nextHasNoMarginBottom: true,
key: "query-controls-order-select",
label: (0,external_wp_i18n_namespaceObject.__)('Order by'),
value: `${orderBy}/${order}`,
options: [{
label: (0,external_wp_i18n_namespaceObject.__)('Newest to oldest'),
value: 'date/desc'
}, {
label: (0,external_wp_i18n_namespaceObject.__)('Oldest to newest'),
value: 'date/asc'
}, {
/* translators: label for ordering posts by title in ascending order */
label: (0,external_wp_i18n_namespaceObject.__)('A → Z'),
value: 'title/asc'
}, {
/* translators: label for ordering posts by title in descending order */
label: (0,external_wp_i18n_namespaceObject.__)('Z → A'),
value: 'title/desc'
}],
onChange: value => {
if (typeof value !== 'string') {
return;
}
const [newOrderBy, newOrder] = value.split('/');
if (newOrder !== order) {
onOrderChange(newOrder);
}
if (newOrderBy !== orderBy) {
onOrderByChange(newOrderBy);
}
}
}), isSingleCategorySelection(props) && props.categoriesList && props.onCategoryChange && (0,external_wp_element_namespaceObject.createElement)(CategorySelect, {
key: "query-controls-category-select",
categoriesList: props.categoriesList,
label: (0,external_wp_i18n_namespaceObject.__)('Category'),
noOptionLabel: (0,external_wp_i18n_namespaceObject.__)('All'),
selectedCategoryId: props.selectedCategoryId,
onChange: props.onCategoryChange
}), isMultipleCategorySelection(props) && props.categorySuggestions && props.onCategoryChange && (0,external_wp_element_namespaceObject.createElement)(form_token_field, {
key: "query-controls-categories-select",
label: (0,external_wp_i18n_namespaceObject.__)('Categories'),
value: props.selectedCategories && props.selectedCategories.map(item => ({
id: item.id,
// Keeping the fallback to `item.value` for legacy reasons,
// even if items of `selectedCategories` should not have a
// `value` property.
// @ts-expect-error
value: item.name || item.value
})),
suggestions: Object.keys(props.categorySuggestions),
onChange: props.onCategoryChange,
maxSuggestions: MAX_CATEGORIES_SUGGESTIONS
}), onAuthorChange && (0,external_wp_element_namespaceObject.createElement)(AuthorSelect, {
key: "query-controls-author-select",
authorList: authorList,
label: (0,external_wp_i18n_namespaceObject.__)('Author'),
noOptionLabel: (0,external_wp_i18n_namespaceObject.__)('All'),
selectedAuthorId: selectedAuthorId,
onChange: onAuthorChange
}), onNumberOfItemsChange && (0,external_wp_element_namespaceObject.createElement)(range_control, {
__nextHasNoMarginBottom: true,
key: "query-controls-range-control",
label: (0,external_wp_i18n_namespaceObject.__)('Number of items'),
value: numberOfItems,
onChange: onNumberOfItemsChange,
min: minItems,
max: maxItems,
required: true
})]);
}
/* harmony default export */ var query_controls = (QueryControls);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/radio-group/radio-context/index.js
/**
* WordPress dependencies
*/
const RadioContext = (0,external_wp_element_namespaceObject.createContext)({
state: null,
setState: () => {}
});
/* harmony default export */ var radio_context = (RadioContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/radio-group/radio/index.js
// @ts-nocheck
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function radio_Radio(_ref, ref) {
let {
children,
value,
...props
} = _ref;
const radioContext = (0,external_wp_element_namespaceObject.useContext)(radio_context);
const checked = radioContext.state === value;
return (0,external_wp_element_namespaceObject.createElement)(Radio, extends_extends({
ref: ref,
as: build_module_button,
variant: checked ? 'primary' : 'secondary',
value: value
}, radioContext, props), children || value);
}
/**
* @deprecated Use `RadioControl` or `ToggleGroupControl` instead.
*/
/* harmony default export */ var radio_group_radio = ((0,external_wp_element_namespaceObject.forwardRef)(radio_Radio));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/radio-group/index.js
// @ts-nocheck
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function radio_group_RadioGroup(_ref, ref) {
let {
label,
checked,
defaultChecked,
disabled,
onChange,
...props
} = _ref;
const radioState = useRadioState({
state: defaultChecked,
baseId: props.id
});
const radioContext = { ...radioState,
disabled,
// Controlled or uncontrolled.
state: checked !== null && checked !== void 0 ? checked : radioState.state,
setState: onChange !== null && onChange !== void 0 ? onChange : radioState.setState
};
return (0,external_wp_element_namespaceObject.createElement)(radio_context.Provider, {
value: radioContext
}, (0,external_wp_element_namespaceObject.createElement)(RadioGroup, extends_extends({
ref: ref,
as: button_group,
"aria-label": label
}, radioState, props)));
}
/**
* @deprecated Use `RadioControl` or `ToggleGroupControl` instead.
*/
/* harmony default export */ var radio_group = ((0,external_wp_element_namespaceObject.forwardRef)(radio_group_RadioGroup));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/radio-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Render a user interface to select the user type using radio inputs.
*
* ```jsx
* import { RadioControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyRadioControl = () => {
* const [ option, setOption ] = useState( 'a' );
*
* return (
* <RadioControl
* label="User type"
* help="The type of the current user"
* selected={ option }
* options={ [
* { label: 'Author', value: 'a' },
* { label: 'Editor', value: 'e' },
* ] }
* onChange={ ( value ) => setOption( value ) }
* />
* );
* };
* ```
*/
function RadioControl(props) {
const {
label,
className,
selected,
help,
onChange,
hideLabelFromVision,
options = [],
...additionalProps
} = props;
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(RadioControl);
const id = `inspector-radio-control-${instanceId}`;
const onChangeValue = event => onChange(event.target.value);
if (!(options !== null && options !== void 0 && options.length)) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(base_control, {
__nextHasNoMarginBottom: true,
label: label,
id: id,
hideLabelFromVision: hideLabelFromVision,
help: help,
className: classnames_default()(className, 'components-radio-control')
}, (0,external_wp_element_namespaceObject.createElement)(v_stack_component, {
spacing: 1
}, options.map((option, index) => (0,external_wp_element_namespaceObject.createElement)("div", {
key: `${id}-${index}`,
className: "components-radio-control__option"
}, (0,external_wp_element_namespaceObject.createElement)("input", extends_extends({
id: `${id}-${index}`,
className: "components-radio-control__input",
type: "radio",
name: id,
value: option.value,
onChange: onChangeValue,
checked: option.value === selected,
"aria-describedby": !!help ? `${id}__help` : undefined
}, additionalProps)), (0,external_wp_element_namespaceObject.createElement)("label", {
htmlFor: `${id}-${index}`
}, option.label)))));
}
/* harmony default export */ var radio_control = (RadioControl);
;// CONCATENATED MODULE: ./node_modules/re-resizable/lib/resizer.js
var resizer_extends = (undefined && undefined.__extends) || (function () {
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);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var resizer_assign = (undefined && undefined.__assign) || function () {
resizer_assign = Object.assign || function(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 resizer_assign.apply(this, arguments);
};
var rowSizeBase = {
width: '100%',
height: '10px',
top: '0px',
left: '0px',
cursor: 'row-resize',
};
var colSizeBase = {
width: '10px',
height: '100%',
top: '0px',
left: '0px',
cursor: 'col-resize',
};
var edgeBase = {
width: '20px',
height: '20px',
position: 'absolute',
};
var styles = {
top: resizer_assign(resizer_assign({}, rowSizeBase), { top: '-5px' }),
right: resizer_assign(resizer_assign({}, colSizeBase), { left: undefined, right: '-5px' }),
bottom: resizer_assign(resizer_assign({}, rowSizeBase), { top: undefined, bottom: '-5px' }),
left: resizer_assign(resizer_assign({}, colSizeBase), { left: '-5px' }),
topRight: resizer_assign(resizer_assign({}, edgeBase), { right: '-10px', top: '-10px', cursor: 'ne-resize' }),
bottomRight: resizer_assign(resizer_assign({}, edgeBase), { right: '-10px', bottom: '-10px', cursor: 'se-resize' }),
bottomLeft: resizer_assign(resizer_assign({}, edgeBase), { left: '-10px', bottom: '-10px', cursor: 'sw-resize' }),
topLeft: resizer_assign(resizer_assign({}, edgeBase), { left: '-10px', top: '-10px', cursor: 'nw-resize' }),
};
var Resizer = /** @class */ (function (_super) {
resizer_extends(Resizer, _super);
function Resizer() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.onMouseDown = function (e) {
_this.props.onResizeStart(e, _this.props.direction);
};
_this.onTouchStart = function (e) {
_this.props.onResizeStart(e, _this.props.direction);
};
return _this;
}
Resizer.prototype.render = function () {
return (external_React_.createElement("div", { className: this.props.className || '', style: resizer_assign(resizer_assign({ position: 'absolute', userSelect: 'none' }, styles[this.props.direction]), (this.props.replaceStyles || {})), onMouseDown: this.onMouseDown, onTouchStart: this.onTouchStart }, this.props.children));
};
return Resizer;
}(external_React_.PureComponent));
;// CONCATENATED MODULE: ./node_modules/re-resizable/lib/index.js
var lib_extends = (undefined && undefined.__extends) || (function () {
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);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var lib_assign = (undefined && undefined.__assign) || function () {
lib_assign = Object.assign || function(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 lib_assign.apply(this, arguments);
};
var DEFAULT_SIZE = {
width: 'auto',
height: 'auto',
};
var lib_clamp = function (n, min, max) { return Math.max(Math.min(n, max), min); };
var snap = function (n, size) { return Math.round(n / size) * size; };
var hasDirection = function (dir, target) {
return new RegExp(dir, 'i').test(target);
};
// INFO: In case of window is a Proxy and does not porxy Events correctly, use isTouchEvent & isMouseEvent to distinguish event type instead of `instanceof`.
var lib_isTouchEvent = function (event) {
return Boolean(event.touches && event.touches.length);
};
var lib_isMouseEvent = function (event) {
return Boolean((event.clientX || event.clientX === 0) &&
(event.clientY || event.clientY === 0));
};
var findClosestSnap = function (n, snapArray, snapGap) {
if (snapGap === void 0) { snapGap = 0; }
var closestGapIndex = snapArray.reduce(function (prev, curr, index) { return (Math.abs(curr - n) < Math.abs(snapArray[prev] - n) ? index : prev); }, 0);
var gap = Math.abs(snapArray[closestGapIndex] - n);
return snapGap === 0 || gap < snapGap ? snapArray[closestGapIndex] : n;
};
var getStringSize = function (n) {
n = n.toString();
if (n === 'auto') {
return n;
}
if (n.endsWith('px')) {
return n;
}
if (n.endsWith('%')) {
return n;
}
if (n.endsWith('vh')) {
return n;
}
if (n.endsWith('vw')) {
return n;
}
if (n.endsWith('vmax')) {
return n;
}
if (n.endsWith('vmin')) {
return n;
}
return n + "px";
};
var getPixelSize = function (size, parentSize, innerWidth, innerHeight) {
if (size && typeof size === 'string') {
if (size.endsWith('px')) {
return Number(size.replace('px', ''));
}
if (size.endsWith('%')) {
var ratio = Number(size.replace('%', '')) / 100;
return parentSize * ratio;
}
if (size.endsWith('vw')) {
var ratio = Number(size.replace('vw', '')) / 100;
return innerWidth * ratio;
}
if (size.endsWith('vh')) {
var ratio = Number(size.replace('vh', '')) / 100;
return innerHeight * ratio;
}
}
return size;
};
var calculateNewMax = function (parentSize, innerWidth, innerHeight, maxWidth, maxHeight, minWidth, minHeight) {
maxWidth = getPixelSize(maxWidth, parentSize.width, innerWidth, innerHeight);
maxHeight = getPixelSize(maxHeight, parentSize.height, innerWidth, innerHeight);
minWidth = getPixelSize(minWidth, parentSize.width, innerWidth, innerHeight);
minHeight = getPixelSize(minHeight, parentSize.height, innerWidth, innerHeight);
return {
maxWidth: typeof maxWidth === 'undefined' ? undefined : Number(maxWidth),
maxHeight: typeof maxHeight === 'undefined' ? undefined : Number(maxHeight),
minWidth: typeof minWidth === 'undefined' ? undefined : Number(minWidth),
minHeight: typeof minHeight === 'undefined' ? undefined : Number(minHeight),
};
};
/**
* transform T | [T, T] to [T, T]
* @param val
* @returns
*/
// tslint:disable-next-line
var normalizeToPair = function (val) { return (Array.isArray(val) ? val : [val, val]); };
var definedProps = [
'as',
'ref',
'style',
'className',
'grid',
'snap',
'bounds',
'boundsByDirection',
'size',
'defaultSize',
'minWidth',
'minHeight',
'maxWidth',
'maxHeight',
'lockAspectRatio',
'lockAspectRatioExtraWidth',
'lockAspectRatioExtraHeight',
'enable',
'handleStyles',
'handleClasses',
'handleWrapperStyle',
'handleWrapperClass',
'children',
'onResizeStart',
'onResize',
'onResizeStop',
'handleComponent',
'scale',
'resizeRatio',
'snapGap',
];
// HACK: This class is used to calculate % size.
var baseClassName = '__resizable_base__';
var Resizable = /** @class */ (function (_super) {
lib_extends(Resizable, _super);
function Resizable(props) {
var _a, _b, _c, _d;
var _this = _super.call(this, props) || this;
_this.ratio = 1;
_this.resizable = null;
// For parent boundary
_this.parentLeft = 0;
_this.parentTop = 0;
// For boundary
_this.resizableLeft = 0;
_this.resizableRight = 0;
_this.resizableTop = 0;
_this.resizableBottom = 0;
// For target boundary
_this.targetLeft = 0;
_this.targetTop = 0;
_this.appendBase = function () {
if (!_this.resizable || !_this.window) {
return null;
}
var parent = _this.parentNode;
if (!parent) {
return null;
}
var element = _this.window.document.createElement('div');
element.style.width = '100%';
element.style.height = '100%';
element.style.position = 'absolute';
element.style.transform = 'scale(0, 0)';
element.style.left = '0';
element.style.flex = '0 0 100%';
if (element.classList) {
element.classList.add(baseClassName);
}
else {
element.className += baseClassName;
}
parent.appendChild(element);
return element;
};
_this.removeBase = function (base) {
var parent = _this.parentNode;
if (!parent) {
return;
}
parent.removeChild(base);
};
_this.state = {
isResizing: false,
width: (_b = (_a = _this.propsSize) === null || _a === void 0 ? void 0 : _a.width) !== null && _b !== void 0 ? _b : 'auto',
height: (_d = (_c = _this.propsSize) === null || _c === void 0 ? void 0 : _c.height) !== null && _d !== void 0 ? _d : 'auto',
direction: 'right',
original: {
x: 0,
y: 0,
width: 0,
height: 0,
},
backgroundStyle: {
height: '100%',
width: '100%',
backgroundColor: 'rgba(0,0,0,0)',
cursor: 'auto',
opacity: 0,
position: 'fixed',
zIndex: 9999,
top: '0',
left: '0',
bottom: '0',
right: '0',
},
flexBasis: undefined,
};
_this.onResizeStart = _this.onResizeStart.bind(_this);
_this.onMouseMove = _this.onMouseMove.bind(_this);
_this.onMouseUp = _this.onMouseUp.bind(_this);
return _this;
}
Object.defineProperty(Resizable.prototype, "parentNode", {
get: function () {
if (!this.resizable) {
return null;
}
return this.resizable.parentNode;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Resizable.prototype, "window", {
get: function () {
if (!this.resizable) {
return null;
}
if (!this.resizable.ownerDocument) {
return null;
}
return this.resizable.ownerDocument.defaultView;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Resizable.prototype, "propsSize", {
get: function () {
return this.props.size || this.props.defaultSize || DEFAULT_SIZE;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Resizable.prototype, "size", {
get: function () {
var width = 0;
var height = 0;
if (this.resizable && this.window) {
var orgWidth = this.resizable.offsetWidth;
var orgHeight = this.resizable.offsetHeight;
// HACK: Set position `relative` to get parent size.
// This is because when re-resizable set `absolute`, I can not get base width correctly.
var orgPosition = this.resizable.style.position;
if (orgPosition !== 'relative') {
this.resizable.style.position = 'relative';
}
// INFO: Use original width or height if set auto.
width = this.resizable.style.width !== 'auto' ? this.resizable.offsetWidth : orgWidth;
height = this.resizable.style.height !== 'auto' ? this.resizable.offsetHeight : orgHeight;
// Restore original position
this.resizable.style.position = orgPosition;
}
return { width: width, height: height };
},
enumerable: false,
configurable: true
});
Object.defineProperty(Resizable.prototype, "sizeStyle", {
get: function () {
var _this = this;
var size = this.props.size;
var getSize = function (key) {
var _a;
if (typeof _this.state[key] === 'undefined' || _this.state[key] === 'auto') {
return 'auto';
}
if (_this.propsSize && _this.propsSize[key] && ((_a = _this.propsSize[key]) === null || _a === void 0 ? void 0 : _a.toString().endsWith('%'))) {
if (_this.state[key].toString().endsWith('%')) {
return _this.state[key].toString();
}
var parentSize = _this.getParentSize();
var value = Number(_this.state[key].toString().replace('px', ''));
var percent = (value / parentSize[key]) * 100;
return percent + "%";
}
return getStringSize(_this.state[key]);
};
var width = size && typeof size.width !== 'undefined' && !this.state.isResizing
? getStringSize(size.width)
: getSize('width');
var height = size && typeof size.height !== 'undefined' && !this.state.isResizing
? getStringSize(size.height)
: getSize('height');
return { width: width, height: height };
},
enumerable: false,
configurable: true
});
Resizable.prototype.getParentSize = function () {
if (!this.parentNode) {
if (!this.window) {
return { width: 0, height: 0 };
}
return { width: this.window.innerWidth, height: this.window.innerHeight };
}
var base = this.appendBase();
if (!base) {
return { width: 0, height: 0 };
}
// INFO: To calculate parent width with flex layout
var wrapChanged = false;
var wrap = this.parentNode.style.flexWrap;
if (wrap !== 'wrap') {
wrapChanged = true;
this.parentNode.style.flexWrap = 'wrap';
// HACK: Use relative to get parent padding size
}
base.style.position = 'relative';
base.style.minWidth = '100%';
base.style.minHeight = '100%';
var size = {
width: base.offsetWidth,
height: base.offsetHeight,
};
if (wrapChanged) {
this.parentNode.style.flexWrap = wrap;
}
this.removeBase(base);
return size;
};
Resizable.prototype.bindEvents = function () {
if (this.window) {
this.window.addEventListener('mouseup', this.onMouseUp);
this.window.addEventListener('mousemove', this.onMouseMove);
this.window.addEventListener('mouseleave', this.onMouseUp);
this.window.addEventListener('touchmove', this.onMouseMove, {
capture: true,
passive: false,
});
this.window.addEventListener('touchend', this.onMouseUp);
}
};
Resizable.prototype.unbindEvents = function () {
if (this.window) {
this.window.removeEventListener('mouseup', this.onMouseUp);
this.window.removeEventListener('mousemove', this.onMouseMove);
this.window.removeEventListener('mouseleave', this.onMouseUp);
this.window.removeEventListener('touchmove', this.onMouseMove, true);
this.window.removeEventListener('touchend', this.onMouseUp);
}
};
Resizable.prototype.componentDidMount = function () {
if (!this.resizable || !this.window) {
return;
}
var computedStyle = this.window.getComputedStyle(this.resizable);
this.setState({
width: this.state.width || this.size.width,
height: this.state.height || this.size.height,
flexBasis: computedStyle.flexBasis !== 'auto' ? computedStyle.flexBasis : undefined,
});
};
Resizable.prototype.componentWillUnmount = function () {
if (this.window) {
this.unbindEvents();
}
};
Resizable.prototype.createSizeForCssProperty = function (newSize, kind) {
var propsSize = this.propsSize && this.propsSize[kind];
return this.state[kind] === 'auto' &&
this.state.original[kind] === newSize &&
(typeof propsSize === 'undefined' || propsSize === 'auto')
? 'auto'
: newSize;
};
Resizable.prototype.calculateNewMaxFromBoundary = function (maxWidth, maxHeight) {
var boundsByDirection = this.props.boundsByDirection;
var direction = this.state.direction;
var widthByDirection = boundsByDirection && hasDirection('left', direction);
var heightByDirection = boundsByDirection && hasDirection('top', direction);
var boundWidth;
var boundHeight;
if (this.props.bounds === 'parent') {
var parent_1 = this.parentNode;
if (parent_1) {
boundWidth = widthByDirection
? this.resizableRight - this.parentLeft
: parent_1.offsetWidth + (this.parentLeft - this.resizableLeft);
boundHeight = heightByDirection
? this.resizableBottom - this.parentTop
: parent_1.offsetHeight + (this.parentTop - this.resizableTop);
}
}
else if (this.props.bounds === 'window') {
if (this.window) {
boundWidth = widthByDirection ? this.resizableRight : this.window.innerWidth - this.resizableLeft;
boundHeight = heightByDirection ? this.resizableBottom : this.window.innerHeight - this.resizableTop;
}
}
else if (this.props.bounds) {
boundWidth = widthByDirection
? this.resizableRight - this.targetLeft
: this.props.bounds.offsetWidth + (this.targetLeft - this.resizableLeft);
boundHeight = heightByDirection
? this.resizableBottom - this.targetTop
: this.props.bounds.offsetHeight + (this.targetTop - this.resizableTop);
}
if (boundWidth && Number.isFinite(boundWidth)) {
maxWidth = maxWidth && maxWidth < boundWidth ? maxWidth : boundWidth;
}
if (boundHeight && Number.isFinite(boundHeight)) {
maxHeight = maxHeight && maxHeight < boundHeight ? maxHeight : boundHeight;
}
return { maxWidth: maxWidth, maxHeight: maxHeight };
};
Resizable.prototype.calculateNewSizeFromDirection = function (clientX, clientY) {
var scale = this.props.scale || 1;
var _a = normalizeToPair(this.props.resizeRatio || 1), resizeRatioX = _a[0], resizeRatioY = _a[1];
var _b = this.state, direction = _b.direction, original = _b.original;
var _c = this.props, lockAspectRatio = _c.lockAspectRatio, lockAspectRatioExtraHeight = _c.lockAspectRatioExtraHeight, lockAspectRatioExtraWidth = _c.lockAspectRatioExtraWidth;
var newWidth = original.width;
var newHeight = original.height;
var extraHeight = lockAspectRatioExtraHeight || 0;
var extraWidth = lockAspectRatioExtraWidth || 0;
if (hasDirection('right', direction)) {
newWidth = original.width + ((clientX - original.x) * resizeRatioX) / scale;
if (lockAspectRatio) {
newHeight = (newWidth - extraWidth) / this.ratio + extraHeight;
}
}
if (hasDirection('left', direction)) {
newWidth = original.width - ((clientX - original.x) * resizeRatioX) / scale;
if (lockAspectRatio) {
newHeight = (newWidth - extraWidth) / this.ratio + extraHeight;
}
}
if (hasDirection('bottom', direction)) {
newHeight = original.height + ((clientY - original.y) * resizeRatioY) / scale;
if (lockAspectRatio) {
newWidth = (newHeight - extraHeight) * this.ratio + extraWidth;
}
}
if (hasDirection('top', direction)) {
newHeight = original.height - ((clientY - original.y) * resizeRatioY) / scale;
if (lockAspectRatio) {
newWidth = (newHeight - extraHeight) * this.ratio + extraWidth;
}
}
return { newWidth: newWidth, newHeight: newHeight };
};
Resizable.prototype.calculateNewSizeFromAspectRatio = function (newWidth, newHeight, max, min) {
var _a = this.props, lockAspectRatio = _a.lockAspectRatio, lockAspectRatioExtraHeight = _a.lockAspectRatioExtraHeight, lockAspectRatioExtraWidth = _a.lockAspectRatioExtraWidth;
var computedMinWidth = typeof min.width === 'undefined' ? 10 : min.width;
var computedMaxWidth = typeof max.width === 'undefined' || max.width < 0 ? newWidth : max.width;
var computedMinHeight = typeof min.height === 'undefined' ? 10 : min.height;
var computedMaxHeight = typeof max.height === 'undefined' || max.height < 0 ? newHeight : max.height;
var extraHeight = lockAspectRatioExtraHeight || 0;
var extraWidth = lockAspectRatioExtraWidth || 0;
if (lockAspectRatio) {
var extraMinWidth = (computedMinHeight - extraHeight) * this.ratio + extraWidth;
var extraMaxWidth = (computedMaxHeight - extraHeight) * this.ratio + extraWidth;
var extraMinHeight = (computedMinWidth - extraWidth) / this.ratio + extraHeight;
var extraMaxHeight = (computedMaxWidth - extraWidth) / this.ratio + extraHeight;
var lockedMinWidth = Math.max(computedMinWidth, extraMinWidth);
var lockedMaxWidth = Math.min(computedMaxWidth, extraMaxWidth);
var lockedMinHeight = Math.max(computedMinHeight, extraMinHeight);
var lockedMaxHeight = Math.min(computedMaxHeight, extraMaxHeight);
newWidth = lib_clamp(newWidth, lockedMinWidth, lockedMaxWidth);
newHeight = lib_clamp(newHeight, lockedMinHeight, lockedMaxHeight);
}
else {
newWidth = lib_clamp(newWidth, computedMinWidth, computedMaxWidth);
newHeight = lib_clamp(newHeight, computedMinHeight, computedMaxHeight);
}
return { newWidth: newWidth, newHeight: newHeight };
};
Resizable.prototype.setBoundingClientRect = function () {
// For parent boundary
if (this.props.bounds === 'parent') {
var parent_2 = this.parentNode;
if (parent_2) {
var parentRect = parent_2.getBoundingClientRect();
this.parentLeft = parentRect.left;
this.parentTop = parentRect.top;
}
}
// For target(html element) boundary
if (this.props.bounds && typeof this.props.bounds !== 'string') {
var targetRect = this.props.bounds.getBoundingClientRect();
this.targetLeft = targetRect.left;
this.targetTop = targetRect.top;
}
// For boundary
if (this.resizable) {
var _a = this.resizable.getBoundingClientRect(), left = _a.left, top_1 = _a.top, right = _a.right, bottom = _a.bottom;
this.resizableLeft = left;
this.resizableRight = right;
this.resizableTop = top_1;
this.resizableBottom = bottom;
}
};
Resizable.prototype.onResizeStart = function (event, direction) {
if (!this.resizable || !this.window) {
return;
}
var clientX = 0;
var clientY = 0;
if (event.nativeEvent && lib_isMouseEvent(event.nativeEvent)) {
clientX = event.nativeEvent.clientX;
clientY = event.nativeEvent.clientY;
}
else if (event.nativeEvent && lib_isTouchEvent(event.nativeEvent)) {
clientX = event.nativeEvent.touches[0].clientX;
clientY = event.nativeEvent.touches[0].clientY;
}
if (this.props.onResizeStart) {
if (this.resizable) {
var startResize = this.props.onResizeStart(event, direction, this.resizable);
if (startResize === false) {
return;
}
}
}
// Fix #168
if (this.props.size) {
if (typeof this.props.size.height !== 'undefined' && this.props.size.height !== this.state.height) {
this.setState({ height: this.props.size.height });
}
if (typeof this.props.size.width !== 'undefined' && this.props.size.width !== this.state.width) {
this.setState({ width: this.props.size.width });
}
}
// For lockAspectRatio case
this.ratio =
typeof this.props.lockAspectRatio === 'number' ? this.props.lockAspectRatio : this.size.width / this.size.height;
var flexBasis;
var computedStyle = this.window.getComputedStyle(this.resizable);
if (computedStyle.flexBasis !== 'auto') {
var parent_3 = this.parentNode;
if (parent_3) {
var dir = this.window.getComputedStyle(parent_3).flexDirection;
this.flexDir = dir.startsWith('row') ? 'row' : 'column';
flexBasis = computedStyle.flexBasis;
}
}
// For boundary
this.setBoundingClientRect();
this.bindEvents();
var state = {
original: {
x: clientX,
y: clientY,
width: this.size.width,
height: this.size.height,
},
isResizing: true,
backgroundStyle: lib_assign(lib_assign({}, this.state.backgroundStyle), { cursor: this.window.getComputedStyle(event.target).cursor || 'auto' }),
direction: direction,
flexBasis: flexBasis,
};
this.setState(state);
};
Resizable.prototype.onMouseMove = function (event) {
var _this = this;
if (!this.state.isResizing || !this.resizable || !this.window) {
return;
}
if (this.window.TouchEvent && lib_isTouchEvent(event)) {
try {
event.preventDefault();
event.stopPropagation();
}
catch (e) {
// Ignore on fail
}
}
var _a = this.props, maxWidth = _a.maxWidth, maxHeight = _a.maxHeight, minWidth = _a.minWidth, minHeight = _a.minHeight;
var clientX = lib_isTouchEvent(event) ? event.touches[0].clientX : event.clientX;
var clientY = lib_isTouchEvent(event) ? event.touches[0].clientY : event.clientY;
var _b = this.state, direction = _b.direction, original = _b.original, width = _b.width, height = _b.height;
var parentSize = this.getParentSize();
var max = calculateNewMax(parentSize, this.window.innerWidth, this.window.innerHeight, maxWidth, maxHeight, minWidth, minHeight);
maxWidth = max.maxWidth;
maxHeight = max.maxHeight;
minWidth = max.minWidth;
minHeight = max.minHeight;
// Calculate new size
var _c = this.calculateNewSizeFromDirection(clientX, clientY), newHeight = _c.newHeight, newWidth = _c.newWidth;
// Calculate max size from boundary settings
var boundaryMax = this.calculateNewMaxFromBoundary(maxWidth, maxHeight);
if (this.props.snap && this.props.snap.x) {
newWidth = findClosestSnap(newWidth, this.props.snap.x, this.props.snapGap);
}
if (this.props.snap && this.props.snap.y) {
newHeight = findClosestSnap(newHeight, this.props.snap.y, this.props.snapGap);
}
// Calculate new size from aspect ratio
var newSize = this.calculateNewSizeFromAspectRatio(newWidth, newHeight, { width: boundaryMax.maxWidth, height: boundaryMax.maxHeight }, { width: minWidth, height: minHeight });
newWidth = newSize.newWidth;
newHeight = newSize.newHeight;
if (this.props.grid) {
var newGridWidth = snap(newWidth, this.props.grid[0]);
var newGridHeight = snap(newHeight, this.props.grid[1]);
var gap = this.props.snapGap || 0;
var w = gap === 0 || Math.abs(newGridWidth - newWidth) <= gap ? newGridWidth : newWidth;
var h = gap === 0 || Math.abs(newGridHeight - newHeight) <= gap ? newGridHeight : newHeight;
newWidth = w;
newHeight = h;
}
var delta = {
width: newWidth - original.width,
height: newHeight - original.height,
};
if (width && typeof width === 'string') {
if (width.endsWith('%')) {
var percent = (newWidth / parentSize.width) * 100;
newWidth = percent + "%";
}
else if (width.endsWith('vw')) {
var vw = (newWidth / this.window.innerWidth) * 100;
newWidth = vw + "vw";
}
else if (width.endsWith('vh')) {
var vh = (newWidth / this.window.innerHeight) * 100;
newWidth = vh + "vh";
}
}
if (height && typeof height === 'string') {
if (height.endsWith('%')) {
var percent = (newHeight / parentSize.height) * 100;
newHeight = percent + "%";
}
else if (height.endsWith('vw')) {
var vw = (newHeight / this.window.innerWidth) * 100;
newHeight = vw + "vw";
}
else if (height.endsWith('vh')) {
var vh = (newHeight / this.window.innerHeight) * 100;
newHeight = vh + "vh";
}
}
var newState = {
width: this.createSizeForCssProperty(newWidth, 'width'),
height: this.createSizeForCssProperty(newHeight, 'height'),
};
if (this.flexDir === 'row') {
newState.flexBasis = newState.width;
}
else if (this.flexDir === 'column') {
newState.flexBasis = newState.height;
}
var widthChanged = this.state.width !== newState.width;
var heightChanged = this.state.height !== newState.height;
var flexBaseChanged = this.state.flexBasis !== newState.flexBasis;
var changed = widthChanged || heightChanged || flexBaseChanged;
if (changed) {
// For v18, update state sync
(0,external_ReactDOM_namespaceObject.flushSync)(function () {
_this.setState(newState);
});
}
if (this.props.onResize) {
if (changed) {
this.props.onResize(event, direction, this.resizable, delta);
}
}
};
Resizable.prototype.onMouseUp = function (event) {
var _a, _b;
var _c = this.state, isResizing = _c.isResizing, direction = _c.direction, original = _c.original;
if (!isResizing || !this.resizable) {
return;
}
var delta = {
width: this.size.width - original.width,
height: this.size.height - original.height,
};
if (this.props.onResizeStop) {
this.props.onResizeStop(event, direction, this.resizable, delta);
}
if (this.props.size) {
this.setState({ width: (_a = this.props.size.width) !== null && _a !== void 0 ? _a : 'auto', height: (_b = this.props.size.height) !== null && _b !== void 0 ? _b : 'auto' });
}
this.unbindEvents();
this.setState({
isResizing: false,
backgroundStyle: lib_assign(lib_assign({}, this.state.backgroundStyle), { cursor: 'auto' }),
});
};
Resizable.prototype.updateSize = function (size) {
var _a, _b;
this.setState({ width: (_a = size.width) !== null && _a !== void 0 ? _a : 'auto', height: (_b = size.height) !== null && _b !== void 0 ? _b : 'auto' });
};
Resizable.prototype.renderResizer = function () {
var _this = this;
var _a = this.props, enable = _a.enable, handleStyles = _a.handleStyles, handleClasses = _a.handleClasses, handleWrapperStyle = _a.handleWrapperStyle, handleWrapperClass = _a.handleWrapperClass, handleComponent = _a.handleComponent;
if (!enable) {
return null;
}
var resizers = Object.keys(enable).map(function (dir) {
if (enable[dir] !== false) {
return (external_React_.createElement(Resizer, { key: dir, direction: dir, onResizeStart: _this.onResizeStart, replaceStyles: handleStyles && handleStyles[dir], className: handleClasses && handleClasses[dir] }, handleComponent && handleComponent[dir] ? handleComponent[dir] : null));
}
return null;
});
// #93 Wrap the resize box in span (will not break 100% width/height)
return (external_React_.createElement("div", { className: handleWrapperClass, style: handleWrapperStyle }, resizers));
};
Resizable.prototype.render = function () {
var _this = this;
var extendsProps = Object.keys(this.props).reduce(function (acc, key) {
if (definedProps.indexOf(key) !== -1) {
return acc;
}
acc[key] = _this.props[key];
return acc;
}, {});
var style = lib_assign(lib_assign(lib_assign({ position: 'relative', userSelect: this.state.isResizing ? 'none' : 'auto' }, this.props.style), this.sizeStyle), { maxWidth: this.props.maxWidth, maxHeight: this.props.maxHeight, minWidth: this.props.minWidth, minHeight: this.props.minHeight, boxSizing: 'border-box', flexShrink: 0 });
if (this.state.flexBasis) {
style.flexBasis = this.state.flexBasis;
}
var Wrapper = this.props.as || 'div';
return (external_React_.createElement(Wrapper, lib_assign({ style: style, className: this.props.className }, extendsProps, {
// `ref` is after `extendsProps` to ensure this one wins over a version
// passed in
ref: function (c) {
if (c) {
_this.resizable = c;
}
} }),
this.state.isResizing && external_React_.createElement("div", { style: this.state.backgroundStyle }),
this.props.children,
this.renderResizer()));
};
Resizable.defaultProps = {
as: 'div',
onResizeStart: function () { },
onResize: function () { },
onResizeStop: function () { },
enable: {
top: true,
right: true,
bottom: true,
left: true,
topRight: true,
bottomRight: true,
bottomLeft: true,
topLeft: true,
},
style: {},
grid: [1, 1],
lockAspectRatio: false,
lockAspectRatioExtraWidth: 0,
lockAspectRatioExtraHeight: 0,
scale: 1,
resizeRatio: 1,
snapGap: 0,
};
return Resizable;
}(external_React_.PureComponent));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/resizable-box/resize-tooltip/utils.js
/**
* WordPress dependencies
*/
const utils_noop = () => {};
const POSITIONS = {
bottom: 'bottom',
corner: 'corner'
};
/**
* Custom hook that manages resize listener events. It also provides a label
* based on current resize width x height values.
*
* @param props
* @param props.axis Only shows the label corresponding to the axis.
* @param props.fadeTimeout Duration (ms) before deactivating the resize label.
* @param props.onResize Callback when a resize occurs. Provides { width, height } callback.
* @param props.position Adjusts label value.
* @param props.showPx Whether to add `PX` to the label.
*
* @return Properties for hook.
*/
function useResizeLabel(_ref) {
let {
axis,
fadeTimeout = 180,
onResize = utils_noop,
position = POSITIONS.bottom,
showPx = false
} = _ref;
/*
* The width/height values derive from this special useResizeObserver hook.
* This custom hook uses the ResizeObserver API to listen for resize events.
*/
const [resizeListener, sizes] = (0,external_wp_compose_namespaceObject.useResizeObserver)();
/*
* Indicates if the x/y axis is preferred.
* If set, we will avoid resetting the moveX and moveY values.
* This will allow for the preferred axis values to persist in the label.
*/
const isAxisControlled = !!axis;
/*
* The moveX and moveY values are used to track whether the label should
* display width, height, or width x height.
*/
const [moveX, setMoveX] = (0,external_wp_element_namespaceObject.useState)(false);
const [moveY, setMoveY] = (0,external_wp_element_namespaceObject.useState)(false);
/*
* Cached dimension values to check for width/height updates from the
* sizes property from useResizeAware()
*/
const {
width,
height
} = sizes;
const heightRef = (0,external_wp_element_namespaceObject.useRef)(height);
const widthRef = (0,external_wp_element_namespaceObject.useRef)(width);
/*
* This timeout is used with setMoveX and setMoveY to determine of
* both width and height values have changed at (roughly) the same time.
*/
const moveTimeoutRef = (0,external_wp_element_namespaceObject.useRef)();
const debounceUnsetMoveXY = (0,external_wp_element_namespaceObject.useCallback)(() => {
const unsetMoveXY = () => {
/*
* If axis is controlled, we will avoid resetting the moveX and moveY values.
* This will allow for the preferred axis values to persist in the label.
*/
if (isAxisControlled) return;
setMoveX(false);
setMoveY(false);
};
if (moveTimeoutRef.current) {
window.clearTimeout(moveTimeoutRef.current);
}
moveTimeoutRef.current = window.setTimeout(unsetMoveXY, fadeTimeout);
}, [fadeTimeout, isAxisControlled]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
/*
* On the initial render of useResizeAware, the height and width values are
* null. They are calculated then set using via an internal useEffect hook.
*/
const isRendered = width !== null || height !== null;
if (!isRendered) return;
const didWidthChange = width !== widthRef.current;
const didHeightChange = height !== heightRef.current;
if (!didWidthChange && !didHeightChange) return;
/*
* After the initial render, the useResizeAware will set the first
* width and height values. We'll sync those values with our
* width and height refs. However, we shouldn't render our Tooltip
* label on this first cycle.
*/
if (width && !widthRef.current && height && !heightRef.current) {
widthRef.current = width;
heightRef.current = height;
return;
}
/*
* After the first cycle, we can track width and height changes.
*/
if (didWidthChange) {
setMoveX(true);
widthRef.current = width;
}
if (didHeightChange) {
setMoveY(true);
heightRef.current = height;
}
onResize({
width,
height
});
debounceUnsetMoveXY();
}, [width, height, onResize, debounceUnsetMoveXY]);
const label = getSizeLabel({
axis,
height,
moveX,
moveY,
position,
showPx,
width
});
return {
label,
resizeListener
};
}
/**
* Gets the resize label based on width and height values (as well as recent changes).
*
* @param props
* @param props.axis Only shows the label corresponding to the axis.
* @param props.height Height value.
* @param props.moveX Recent width (x axis) changes.
* @param props.moveY Recent width (y axis) changes.
* @param props.position Adjusts label value.
* @param props.showPx Whether to add `PX` to the label.
* @param props.width Width value.
*
* @return The rendered label.
*/
function getSizeLabel(_ref2) {
let {
axis,
height,
moveX = false,
moveY = false,
position = POSITIONS.bottom,
showPx = false,
width
} = _ref2;
if (!moveX && !moveY) return undefined;
/*
* Corner position...
* We want the label to appear like width x height.
*/
if (position === POSITIONS.corner) {
return `${width} x ${height}`;
}
/*
* Other POSITIONS...
* The label will combine both width x height values if both
* values have recently been changed.
*
* Otherwise, only width or height will be displayed.
* The `PX` unit will be added, if specified by the `showPx` prop.
*/
const labelUnit = showPx ? ' px' : '';
if (axis) {
if (axis === 'x' && moveX) {
return `${width}${labelUnit}`;
}
if (axis === 'y' && moveY) {
return `${height}${labelUnit}`;
}
}
if (moveX && moveY) {
return `${width} x ${height}`;
}
if (moveX) {
return `${width}${labelUnit}`;
}
if (moveY) {
return `${height}${labelUnit}`;
}
return undefined;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/resizable-box/resize-tooltip/styles/resize-tooltip.styles.js
function resize_tooltip_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const resize_tooltip_styles_Root = createStyled("div", true ? {
target: "ekdag503"
} : 0)( true ? {
name: "1cd7zoc",
styles: "bottom:0;box-sizing:border-box;left:0;pointer-events:none;position:absolute;right:0;top:0"
} : 0);
const TooltipWrapper = createStyled("div", true ? {
target: "ekdag502"
} : 0)( true ? {
name: "ajymcs",
styles: "align-items:center;box-sizing:border-box;display:inline-flex;justify-content:center;opacity:0;pointer-events:none;transition:opacity 120ms linear"
} : 0);
const resize_tooltip_styles_Tooltip = createStyled("div", true ? {
target: "ekdag501"
} : 0)("background:", COLORS.gray[900], ";border-radius:2px;box-sizing:border-box;font-size:12px;color:", COLORS.ui.textDark, ";padding:4px 8px;position:relative;" + ( true ? "" : 0)); // TODO: Resolve need to use &&& to increase specificity
// https://github.com/WordPress/gutenberg/issues/18483
const LabelText = /*#__PURE__*/createStyled(text_component, true ? {
target: "ekdag500"
} : 0)("&&&{color:", COLORS.ui.textDark, ";display:block;font-size:13px;line-height:1.4;white-space:nowrap;}" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/resizable-box/resize-tooltip/label.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const CORNER_OFFSET = 4;
const CURSOR_OFFSET_TOP = CORNER_OFFSET * 2.5;
function resize_tooltip_label_Label(_ref, ref) {
let {
label,
position = POSITIONS.corner,
zIndex = 1000,
...props
} = _ref;
const showLabel = !!label;
const isBottom = position === POSITIONS.bottom;
const isCorner = position === POSITIONS.corner;
if (!showLabel) return null;
let style = {
opacity: showLabel ? 1 : undefined,
zIndex
};
let labelStyle = {};
if (isBottom) {
style = { ...style,
position: 'absolute',
bottom: CURSOR_OFFSET_TOP * -1,
left: '50%',
transform: 'translate(-50%, 0)'
};
labelStyle = {
transform: `translate(0, 100%)`
};
}
if (isCorner) {
style = { ...style,
position: 'absolute',
top: CORNER_OFFSET,
right: (0,external_wp_i18n_namespaceObject.isRTL)() ? undefined : CORNER_OFFSET,
left: (0,external_wp_i18n_namespaceObject.isRTL)() ? CORNER_OFFSET : undefined
};
}
return (0,external_wp_element_namespaceObject.createElement)(TooltipWrapper, extends_extends({
"aria-hidden": "true",
className: "components-resizable-tooltip__tooltip-wrapper",
ref: ref,
style: style
}, props), (0,external_wp_element_namespaceObject.createElement)(resize_tooltip_styles_Tooltip, {
className: "components-resizable-tooltip__tooltip",
style: labelStyle
}, (0,external_wp_element_namespaceObject.createElement)(LabelText, {
as: "span"
}, label)));
}
const label_ForwardedComponent = (0,external_wp_element_namespaceObject.forwardRef)(resize_tooltip_label_Label);
/* harmony default export */ var resize_tooltip_label = (label_ForwardedComponent);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/resizable-box/resize-tooltip/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const resize_tooltip_noop = () => {};
function ResizeTooltip(_ref, ref) {
let {
axis,
className,
fadeTimeout = 180,
isVisible = true,
labelRef,
onResize = resize_tooltip_noop,
position = POSITIONS.bottom,
showPx = true,
zIndex = 1000,
...props
} = _ref;
const {
label,
resizeListener
} = useResizeLabel({
axis,
fadeTimeout,
onResize,
showPx,
position
});
if (!isVisible) return null;
const classes = classnames_default()('components-resize-tooltip', className);
return (0,external_wp_element_namespaceObject.createElement)(resize_tooltip_styles_Root, extends_extends({
"aria-hidden": "true",
className: classes,
ref: ref
}, props), resizeListener, (0,external_wp_element_namespaceObject.createElement)(resize_tooltip_label, {
"aria-hidden": props['aria-hidden'],
label: label,
position: position,
ref: labelRef,
zIndex: zIndex
}));
}
const resize_tooltip_ForwardedComponent = (0,external_wp_element_namespaceObject.forwardRef)(ResizeTooltip);
/* harmony default export */ var resize_tooltip = (resize_tooltip_ForwardedComponent);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/resizable-box/index.js
/**
* WordPress dependencies
*/
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const HANDLE_CLASS_NAME = 'components-resizable-box__handle';
const SIDE_HANDLE_CLASS_NAME = 'components-resizable-box__side-handle';
const CORNER_HANDLE_CLASS_NAME = 'components-resizable-box__corner-handle';
const HANDLE_CLASSES = {
top: classnames_default()(HANDLE_CLASS_NAME, SIDE_HANDLE_CLASS_NAME, 'components-resizable-box__handle-top'),
right: classnames_default()(HANDLE_CLASS_NAME, SIDE_HANDLE_CLASS_NAME, 'components-resizable-box__handle-right'),
bottom: classnames_default()(HANDLE_CLASS_NAME, SIDE_HANDLE_CLASS_NAME, 'components-resizable-box__handle-bottom'),
left: classnames_default()(HANDLE_CLASS_NAME, SIDE_HANDLE_CLASS_NAME, 'components-resizable-box__handle-left'),
topLeft: classnames_default()(HANDLE_CLASS_NAME, CORNER_HANDLE_CLASS_NAME, 'components-resizable-box__handle-top', 'components-resizable-box__handle-left'),
topRight: classnames_default()(HANDLE_CLASS_NAME, CORNER_HANDLE_CLASS_NAME, 'components-resizable-box__handle-top', 'components-resizable-box__handle-right'),
bottomRight: classnames_default()(HANDLE_CLASS_NAME, CORNER_HANDLE_CLASS_NAME, 'components-resizable-box__handle-bottom', 'components-resizable-box__handle-right'),
bottomLeft: classnames_default()(HANDLE_CLASS_NAME, CORNER_HANDLE_CLASS_NAME, 'components-resizable-box__handle-bottom', 'components-resizable-box__handle-left')
}; // Removes the inline styles in the drag handles.
const HANDLE_STYLES_OVERRIDES = {
width: undefined,
height: undefined,
top: undefined,
right: undefined,
bottom: undefined,
left: undefined
};
const HANDLE_STYLES = {
top: HANDLE_STYLES_OVERRIDES,
right: HANDLE_STYLES_OVERRIDES,
bottom: HANDLE_STYLES_OVERRIDES,
left: HANDLE_STYLES_OVERRIDES,
topLeft: HANDLE_STYLES_OVERRIDES,
topRight: HANDLE_STYLES_OVERRIDES,
bottomRight: HANDLE_STYLES_OVERRIDES,
bottomLeft: HANDLE_STYLES_OVERRIDES
};
function UnforwardedResizableBox(_ref, ref) {
let {
className,
children,
showHandle = true,
__experimentalShowTooltip: showTooltip = false,
__experimentalTooltipProps: tooltipProps = {},
...props
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(Resizable, extends_extends({
className: classnames_default()('components-resizable-box__container', showHandle && 'has-show-handle', className),
handleClasses: HANDLE_CLASSES,
handleStyles: HANDLE_STYLES,
ref: ref
}, props), children, showTooltip && (0,external_wp_element_namespaceObject.createElement)(resize_tooltip, tooltipProps));
}
const ResizableBox = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedResizableBox);
/* harmony default export */ var resizable_box = (ResizableBox);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/responsive-wrapper/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* A wrapper component that maintains its aspect ratio when resized.
*
* ```jsx
* import { ResponsiveWrapper } from '@wordpress/components';
*
* const MyResponsiveWrapper = () => (
* <ResponsiveWrapper naturalWidth={ 2000 } naturalHeight={ 680 }>
* <img
* src="https://s.w.org/style/images/about/WordPress-logotype-standard.png"
* alt="WordPress"
* />
* </ResponsiveWrapper>
* );
* ```
*/
function ResponsiveWrapper(_ref) {
let {
naturalWidth,
naturalHeight,
children,
isInline = false
} = _ref;
const [containerResizeListener, {
width: containerWidth
}] = (0,external_wp_compose_namespaceObject.useResizeObserver)();
if (external_wp_element_namespaceObject.Children.count(children) !== 1) {
return null;
}
const imageStyle = {
paddingBottom: naturalWidth < (containerWidth !== null && containerWidth !== void 0 ? containerWidth : 0) ? naturalHeight : naturalHeight / naturalWidth * 100 + '%'
};
const TagName = isInline ? 'span' : 'div';
return (0,external_wp_element_namespaceObject.createElement)(TagName, {
className: "components-responsive-wrapper"
}, containerResizeListener, (0,external_wp_element_namespaceObject.createElement)(TagName, {
style: imageStyle
}), (0,external_wp_element_namespaceObject.cloneElement)(children, {
className: classnames_default()('components-responsive-wrapper__content', children.props.className)
}));
}
/* harmony default export */ var responsive_wrapper = (ResponsiveWrapper);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/sandbox/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const observeAndResizeJS = function () {
const {
MutationObserver
} = window;
if (!MutationObserver || !document.body || !window.parent) {
return;
}
function sendResize() {
const clientBoundingRect = document.body.getBoundingClientRect();
window.parent.postMessage({
action: 'resize',
width: clientBoundingRect.width,
height: clientBoundingRect.height
}, '*');
}
const observer = new MutationObserver(sendResize);
observer.observe(document.body, {
attributes: true,
attributeOldValue: false,
characterData: true,
characterDataOldValue: false,
childList: true,
subtree: true
});
window.addEventListener('load', sendResize, true); // Hack: Remove viewport unit styles, as these are relative
// the iframe root and interfere with our mechanism for
// determining the unconstrained page bounds.
function removeViewportStyles(ruleOrNode) {
if (ruleOrNode.style) {
['width', 'height', 'minHeight', 'maxHeight'].forEach(function (style) {
if (/^\\d+(vmin|vmax|vh|vw)$/.test(ruleOrNode.style[style])) {
ruleOrNode.style[style] = '';
}
});
}
}
Array.prototype.forEach.call(document.querySelectorAll('[style]'), removeViewportStyles);
Array.prototype.forEach.call(document.styleSheets, function (stylesheet) {
Array.prototype.forEach.call(stylesheet.cssRules || stylesheet.rules, removeViewportStyles);
});
document.body.style.position = 'absolute';
document.body.style.width = '100%';
document.body.setAttribute('data-resizable-iframe-connected', '');
sendResize(); // Resize events can change the width of elements with 100% width, but we don't
// get an DOM mutations for that, so do the resize when the window is resized, too.
window.addEventListener('resize', sendResize, true);
}; // TODO: These styles shouldn't be coupled with WordPress.
const style = `
body {
margin: 0;
}
html,
body,
body > div {
width: 100%;
}
html.wp-has-aspect-ratio,
body.wp-has-aspect-ratio,
body.wp-has-aspect-ratio > div,
body.wp-has-aspect-ratio > div iframe {
width: 100%;
height: 100%;
overflow: hidden; /* If it has an aspect ratio, it shouldn't scroll. */
}
body > div > * {
margin-top: 0 !important; /* Has to have !important to override inline styles. */
margin-bottom: 0 !important;
}
`;
/**
* This component provides an isolated environment for arbitrary HTML via iframes.
*
* ```jsx
* import { SandBox } from '@wordpress/components';
*
* const MySandBox = () => (
* <SandBox html="<p>Content</p>" title="SandBox" type="embed" />
* );
* ```
*/
function SandBox(_ref) {
let {
html = '',
title = '',
type,
styles = [],
scripts = [],
onFocus
} = _ref;
const ref = (0,external_wp_element_namespaceObject.useRef)();
const [width, setWidth] = (0,external_wp_element_namespaceObject.useState)(0);
const [height, setHeight] = (0,external_wp_element_namespaceObject.useState)(0);
function isFrameAccessible() {
try {
var _ref$current, _ref$current$contentD;
return !!((_ref$current = ref.current) !== null && _ref$current !== void 0 && (_ref$current$contentD = _ref$current.contentDocument) !== null && _ref$current$contentD !== void 0 && _ref$current$contentD.body);
} catch (e) {
return false;
}
}
function trySandBox() {
let forceRerender = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
if (!isFrameAccessible()) {
return;
}
const {
contentDocument,
ownerDocument
} = ref.current;
if (!forceRerender && null !== (contentDocument === null || contentDocument === void 0 ? void 0 : contentDocument.body.getAttribute('data-resizable-iframe-connected'))) {
return;
} // Put the html snippet into a html document, and then write it to the iframe's document
// we can use this in the future to inject custom styles or scripts.
// Scripts go into the body rather than the head, to support embedded content such as Instagram
// that expect the scripts to be part of the body.
const htmlDoc = (0,external_wp_element_namespaceObject.createElement)("html", {
lang: ownerDocument.documentElement.lang,
className: type
}, (0,external_wp_element_namespaceObject.createElement)("head", null, (0,external_wp_element_namespaceObject.createElement)("title", null, title), (0,external_wp_element_namespaceObject.createElement)("style", {
dangerouslySetInnerHTML: {
__html: style
}
}), styles.map((rules, i) => (0,external_wp_element_namespaceObject.createElement)("style", {
key: i,
dangerouslySetInnerHTML: {
__html: rules
}
}))), (0,external_wp_element_namespaceObject.createElement)("body", {
"data-resizable-iframe-connected": "data-resizable-iframe-connected",
className: type
}, (0,external_wp_element_namespaceObject.createElement)("div", {
dangerouslySetInnerHTML: {
__html: html
}
}), (0,external_wp_element_namespaceObject.createElement)("script", {
type: "text/javascript",
dangerouslySetInnerHTML: {
__html: `(${observeAndResizeJS.toString()})();`
}
}), scripts.map(src => (0,external_wp_element_namespaceObject.createElement)("script", {
key: src,
src: src
})))); // Writing the document like this makes it act in the same way as if it was
// loaded over the network, so DOM creation and mutation, script execution, etc.
// all work as expected.
contentDocument.open();
contentDocument.write('<!DOCTYPE html>' + (0,external_wp_element_namespaceObject.renderToString)(htmlDoc));
contentDocument.close();
}
(0,external_wp_element_namespaceObject.useEffect)(() => {
var _iframe$ownerDocument;
trySandBox();
function tryNoForceSandBox() {
trySandBox(false);
}
function checkMessageForResize(event) {
const iframe = ref.current; // Verify that the mounted element is the source of the message.
if (!iframe || iframe.contentWindow !== event.source) {
return;
} // Attempt to parse the message data as JSON if passed as string.
let data = event.data || {};
if ('string' === typeof data) {
try {
data = JSON.parse(data);
} catch (e) {}
} // Update the state only if the message is formatted as we expect,
// i.e. as an object with a 'resize' action.
if ('resize' !== data.action) {
return;
}
setWidth(data.width);
setHeight(data.height);
}
const iframe = ref.current;
const defaultView = iframe === null || iframe === void 0 ? void 0 : (_iframe$ownerDocument = iframe.ownerDocument) === null || _iframe$ownerDocument === void 0 ? void 0 : _iframe$ownerDocument.defaultView; // This used to be registered using <iframe onLoad={} />, but it made the iframe blank
// after reordering the containing block. See these two issues for more details:
// https://github.com/WordPress/gutenberg/issues/6146
// https://github.com/facebook/react/issues/18752
iframe === null || iframe === void 0 ? void 0 : iframe.addEventListener('load', tryNoForceSandBox, false);
defaultView === null || defaultView === void 0 ? void 0 : defaultView.addEventListener('message', checkMessageForResize);
return () => {
iframe === null || iframe === void 0 ? void 0 : iframe.removeEventListener('load', tryNoForceSandBox, false);
defaultView === null || defaultView === void 0 ? void 0 : defaultView.addEventListener('message', checkMessageForResize);
}; // Ignore reason: passing `exhaustive-deps` will likely involve a more detailed refactor.
// See https://github.com/WordPress/gutenberg/pull/44378
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
(0,external_wp_element_namespaceObject.useEffect)(() => {
trySandBox(); // Ignore reason: passing `exhaustive-deps` will likely involve a more detailed refactor.
// See https://github.com/WordPress/gutenberg/pull/44378
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [title, styles, scripts]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
trySandBox(true); // Ignore reason: passing `exhaustive-deps` will likely involve a more detailed refactor.
// See https://github.com/WordPress/gutenberg/pull/44378
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [html, type]);
return (0,external_wp_element_namespaceObject.createElement)("iframe", {
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([ref, (0,external_wp_compose_namespaceObject.useFocusableIframe)()]),
title: title,
className: "components-sandbox",
sandbox: "allow-scripts allow-same-origin allow-presentation",
onFocus: onFocus,
width: Math.ceil(width),
height: Math.ceil(height)
});
}
/* harmony default export */ var sandbox = (SandBox);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/snackbar/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const NOTICE_TIMEOUT = 10000;
/**
* Custom hook which announces the message with the given politeness, if a
* valid message is provided.
*
* @param message Message to announce.
* @param politeness Politeness to announce.
*/
function snackbar_useSpokenMessage(message, politeness) {
const spokenMessage = typeof message === 'string' ? message : (0,external_wp_element_namespaceObject.renderToString)(message);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (spokenMessage) {
(0,external_wp_a11y_namespaceObject.speak)(spokenMessage, politeness);
}
}, [spokenMessage, politeness]);
}
function UnforwardedSnackbar(_ref, ref) {
let {
className,
children,
spokenMessage = children,
politeness = 'polite',
actions = [],
onRemove,
icon = null,
explicitDismiss = false,
// onDismiss is a callback executed when the snackbar is dismissed.
// It is distinct from onRemove, which _looks_ like a callback but is
// actually the function to call to remove the snackbar from the UI.
onDismiss,
listRef
} = _ref;
function dismissMe(event) {
var _listRef$current;
if (event && event.preventDefault) {
event.preventDefault();
} // Prevent focus loss by moving it to the list element.
listRef === null || listRef === void 0 ? void 0 : (_listRef$current = listRef.current) === null || _listRef$current === void 0 ? void 0 : _listRef$current.focus();
onDismiss === null || onDismiss === void 0 ? void 0 : onDismiss();
onRemove === null || onRemove === void 0 ? void 0 : onRemove();
}
function onActionClick(event, onClick) {
event.stopPropagation();
onRemove === null || onRemove === void 0 ? void 0 : onRemove();
if (onClick) {
onClick(event);
}
}
snackbar_useSpokenMessage(spokenMessage, politeness); // Only set up the timeout dismiss if we're not explicitly dismissing.
(0,external_wp_element_namespaceObject.useEffect)(() => {
const timeoutHandle = setTimeout(() => {
if (!explicitDismiss) {
onDismiss === null || onDismiss === void 0 ? void 0 : onDismiss();
onRemove === null || onRemove === void 0 ? void 0 : onRemove();
}
}, NOTICE_TIMEOUT);
return () => clearTimeout(timeoutHandle);
}, [onDismiss, onRemove, explicitDismiss]);
const classes = classnames_default()(className, 'components-snackbar', {
'components-snackbar-explicit-dismiss': !!explicitDismiss
});
if (actions && actions.length > 1) {
// We need to inform developers that snackbar only accepts 1 action.
typeof process !== "undefined" && process.env && "production" !== "production" ? 0 : void 0; // return first element only while keeping it inside an array
actions = [actions[0]];
}
const snackbarContentClassnames = classnames_default()('components-snackbar__content', {
'components-snackbar__content-with-icon': !!icon
});
return (0,external_wp_element_namespaceObject.createElement)("div", {
ref: ref,
className: classes,
onClick: !explicitDismiss ? dismissMe : undefined,
tabIndex: 0,
role: !explicitDismiss ? 'button' : '',
onKeyPress: !explicitDismiss ? dismissMe : undefined,
"aria-label": !explicitDismiss ? (0,external_wp_i18n_namespaceObject.__)('Dismiss this notice') : ''
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: snackbarContentClassnames
}, icon && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-snackbar__icon"
}, icon), children, actions.map((_ref2, index) => {
let {
label,
onClick,
url
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(build_module_button, {
key: index,
href: url,
variant: "tertiary",
onClick: event => onActionClick(event, onClick),
className: "components-snackbar__action"
}, label);
}), explicitDismiss && (0,external_wp_element_namespaceObject.createElement)("span", {
role: "button",
"aria-label": "Dismiss this notice",
tabIndex: 0,
className: "components-snackbar__dismiss-button",
onClick: dismissMe,
onKeyPress: dismissMe
}, "\u2715")));
}
/**
* A Snackbar displays a succinct message that is cleared out after a small delay.
*
* It can also offer the user options, like viewing a published post.
* But these options should also be available elsewhere in the UI.
*
* ```jsx
* const MySnackbarNotice = () => (
* <Snackbar>Post published successfully.</Snackbar>
* );
* ```
*/
const Snackbar = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedSnackbar);
/* harmony default export */ var snackbar = (Snackbar);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/snackbar/list.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const SNACKBAR_VARIANTS = {
init: {
height: 0,
opacity: 0
},
open: {
height: 'auto',
opacity: 1,
transition: {
height: {
stiffness: 1000,
velocity: -100
}
}
},
exit: {
opacity: 0,
transition: {
duration: 0.5
}
}
};
/**
* Renders a list of notices.
*
* ```jsx
* const MySnackbarListNotice = () => (
* <SnackbarList
* notices={ notices }
* onRemove={ removeNotice }
* />
* );
* ```
*/
function SnackbarList(_ref) {
let {
notices,
className,
children,
onRemove
} = _ref;
const listRef = (0,external_wp_element_namespaceObject.useRef)(null);
const isReducedMotion = (0,external_wp_compose_namespaceObject.useReducedMotion)();
className = classnames_default()('components-snackbar-list', className);
const removeNotice = notice => () => onRemove === null || onRemove === void 0 ? void 0 : onRemove(notice.id);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: className,
tabIndex: -1,
ref: listRef
}, children, (0,external_wp_element_namespaceObject.createElement)(AnimatePresence, null, notices.map(notice => {
const {
content,
...restNotice
} = notice;
return (0,external_wp_element_namespaceObject.createElement)(motion.div, {
layout: !isReducedMotion // See https://www.framer.com/docs/animation/#layout-animations
,
initial: 'init',
animate: 'open',
exit: 'exit',
key: notice.id,
variants: isReducedMotion ? undefined : SNACKBAR_VARIANTS
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-snackbar-list__notice-container"
}, (0,external_wp_element_namespaceObject.createElement)(snackbar, extends_extends({}, restNotice, {
onRemove: removeNotice(notice),
listRef: listRef
}), notice.content)));
})));
}
/* harmony default export */ var snackbar_list = (SnackbarList);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/spinner/styles.js
function spinner_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const spinAnimation = emotion_react_browser_esm_keyframes`
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
`;
const StyledSpinner = createStyled("svg", true ? {
target: "ea4tfvq2"
} : 0)("width:", config_values.spinnerSize, "px;height:", config_values.spinnerSize, "px;display:inline-block;margin:5px 11px 0;position:relative;color:", COLORS.ui.theme, ";overflow:visible;" + ( true ? "" : 0));
const commonPathProps = true ? {
name: "9s4963",
styles: "fill:transparent;stroke-width:1.5px"
} : 0;
const SpinnerTrack = createStyled("circle", true ? {
target: "ea4tfvq1"
} : 0)(commonPathProps, ";stroke:", COLORS.gray[300], ";" + ( true ? "" : 0));
const SpinnerIndicator = createStyled("path", true ? {
target: "ea4tfvq0"
} : 0)(commonPathProps, ";stroke:currentColor;stroke-linecap:round;transform-origin:50% 50%;animation:1.4s linear infinite both ", spinAnimation, ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/spinner/index.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
/**
* WordPress dependencies
*/
function UnforwardedSpinner(_ref, forwardedRef) {
let {
className,
...props
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(StyledSpinner, extends_extends({
className: classnames_default()('components-spinner', className),
viewBox: "0 0 100 100",
width: "16",
height: "16",
xmlns: "http://www.w3.org/2000/svg",
role: "presentation",
focusable: "false"
}, props, {
ref: forwardedRef
}), (0,external_wp_element_namespaceObject.createElement)(SpinnerTrack, {
cx: "50",
cy: "50",
r: "50",
vectorEffect: "non-scaling-stroke"
}), (0,external_wp_element_namespaceObject.createElement)(SpinnerIndicator, {
d: "m 50 0 a 50 50 0 0 1 50 50",
vectorEffect: "non-scaling-stroke"
}));
}
/**
* `Spinner` is a component used to notify users that their action is being processed.
*
* @example
* ```js
* import { Spinner } from '@wordpress/components';
*
* function Example() {
* return <Spinner />;
* }
* ```
*/
const Spinner = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedSpinner);
/* harmony default export */ var spinner = (Spinner);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/surface/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedSurface(props, forwardedRef) {
const surfaceProps = useSurface(props);
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({}, surfaceProps, {
ref: forwardedRef
}));
}
/**
* `Surface` is a core component that renders a primary background color.
*
* In the example below, notice how the `Surface` renders in white (or dark gray if in dark mode).
*
* ```jsx
* import {
* __experimentalSurface as Surface,
* __experimentalText as Text,
* } from '@wordpress/components';
*
* function Example() {
* return (
* <Surface>
* <Text>Code is Poetry</Text>
* </Surface>
* );
* }
* ```
*/
const component_Surface = contextConnect(UnconnectedSurface, 'Surface');
/* harmony default export */ var surface_component = (component_Surface);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tab-panel/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const TabButton = _ref => {
let {
tabId,
children,
selected,
...rest
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(build_module_button, extends_extends({
role: "tab",
tabIndex: selected ? undefined : -1,
"aria-selected": selected,
id: tabId,
__experimentalIsFocusable: true
}, rest), children);
};
/**
* TabPanel is an ARIA-compliant tabpanel.
*
* TabPanels organize content across different screens, data sets, and interactions.
* It has two sections: a list of tabs, and the view to show when tabs are chosen.
*
* ```jsx
* import { TabPanel } from '@wordpress/components';
*
* const onSelect = ( tabName ) => {
* console.log( 'Selecting tab', tabName );
* };
*
* const MyTabPanel = () => (
* <TabPanel
* className="my-tab-panel"
* activeClass="active-tab"
* onSelect={ onSelect }
* tabs={ [
* {
* name: 'tab1',
* title: 'Tab 1',
* className: 'tab-one',
* },
* {
* name: 'tab2',
* title: 'Tab 2',
* className: 'tab-two',
* },
* ] }
* >
* { ( tab ) => <p>{ tab.title }</p> }
* </TabPanel>
* );
* ```
*/
function TabPanel(_ref2) {
var _selectedTab$name;
let {
className,
children,
tabs,
selectOnMove = true,
initialTabName,
orientation = 'horizontal',
activeClass = 'is-active',
onSelect
} = _ref2;
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(TabPanel, 'tab-panel');
const [selected, setSelected] = (0,external_wp_element_namespaceObject.useState)();
const handleTabSelection = (0,external_wp_element_namespaceObject.useCallback)(tabKey => {
setSelected(tabKey);
onSelect === null || onSelect === void 0 ? void 0 : onSelect(tabKey);
}, [onSelect]); // Simulate a click on the newly focused tab, which causes the component
// to show the `tab-panel` associated with the clicked tab.
const activateTabAutomatically = (_childIndex, child) => {
child.click();
};
const selectedTab = tabs.find(_ref3 => {
let {
name
} = _ref3;
return name === selected;
});
const selectedId = `${instanceId}-${(_selectedTab$name = selectedTab === null || selectedTab === void 0 ? void 0 : selectedTab.name) !== null && _selectedTab$name !== void 0 ? _selectedTab$name : 'none'}`; // Handle selecting the initial tab.
(0,external_wp_element_namespaceObject.useEffect)(() => {
// If there's a selected tab, don't override it.
if (selectedTab) {
return;
}
const initialTab = tabs.find(tab => tab.name === initialTabName); // Wait for the denoted initial tab to be declared before making a
// selection. This ensures that if a tab is declared lazily it can
// still receive initial selection.
if (initialTabName && !initialTab) {
return;
}
if (initialTab && !initialTab.disabled) {
// Select the initial tab if it's not disabled.
handleTabSelection(initialTab.name);
} else {
// Fallback to the first enabled tab when the initial is disabled.
const firstEnabledTab = tabs.find(tab => !tab.disabled);
if (firstEnabledTab) handleTabSelection(firstEnabledTab.name);
}
}, [tabs, selectedTab, initialTabName, handleTabSelection]); // Handle the currently selected tab becoming disabled.
(0,external_wp_element_namespaceObject.useEffect)(() => {
// This effect only runs when the selected tab is defined and becomes disabled.
if (!(selectedTab !== null && selectedTab !== void 0 && selectedTab.disabled)) {
return;
}
const firstEnabledTab = tabs.find(tab => !tab.disabled); // If the currently selected tab becomes disabled, select the first enabled tab.
// (if there is one).
if (firstEnabledTab) {
handleTabSelection(firstEnabledTab.name);
}
}, [tabs, selectedTab === null || selectedTab === void 0 ? void 0 : selectedTab.disabled, handleTabSelection]);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: className
}, (0,external_wp_element_namespaceObject.createElement)(navigable_container_menu, {
role: "tablist",
orientation: orientation,
onNavigate: selectOnMove ? activateTabAutomatically : undefined,
className: "components-tab-panel__tabs"
}, tabs.map(tab => (0,external_wp_element_namespaceObject.createElement)(TabButton, {
className: classnames_default()('components-tab-panel__tabs-item', tab.className, {
[activeClass]: tab.name === selected
}),
tabId: `${instanceId}-${tab.name}`,
"aria-controls": `${instanceId}-${tab.name}-view`,
selected: tab.name === selected,
key: tab.name,
onClick: () => handleTabSelection(tab.name),
disabled: tab.disabled,
label: tab.icon && tab.title,
icon: tab.icon,
showTooltip: !!tab.icon
}, !tab.icon && tab.title))), selectedTab && (0,external_wp_element_namespaceObject.createElement)("div", {
key: selectedId,
"aria-labelledby": selectedId,
role: "tabpanel",
id: `${selectedId}-view`,
className: "components-tab-panel__tab-content"
}, children(selectedTab)));
}
/* harmony default export */ var tab_panel = (TabPanel);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/text-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedTextControl(props, ref) {
const {
__nextHasNoMarginBottom,
label,
hideLabelFromVision,
value,
help,
className,
onChange,
type = 'text',
...additionalProps
} = props;
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(TextControl);
const id = `inspector-text-control-${instanceId}`;
const onChangeValue = event => onChange(event.target.value);
return (0,external_wp_element_namespaceObject.createElement)(base_control, {
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
label: label,
hideLabelFromVision: hideLabelFromVision,
id: id,
help: help,
className: className
}, (0,external_wp_element_namespaceObject.createElement)("input", extends_extends({
className: "components-text-control__input",
type: type,
id: id,
value: value,
onChange: onChangeValue,
"aria-describedby": !!help ? id + '__help' : undefined,
ref: ref
}, additionalProps)));
}
/**
* TextControl components let users enter and edit text.
*
* ```jsx
* import { TextControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyTextControl = () => {
* const [ className, setClassName ] = useState( '' );
*
* return (
* <TextControl
* label="Additional CSS Class"
* value={ className }
* onChange={ ( value ) => setClassName( value ) }
* />
* );
* };
* ```
*/
const TextControl = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedTextControl);
/* harmony default export */ var text_control = (TextControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/input/base.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const inputStyleNeutral = /*#__PURE__*/emotion_react_browser_esm_css("box-shadow:0 0 0 transparent;transition:box-shadow 0.1s linear;border-radius:", config_values.radiusBlockUi, ";border:", config_values.borderWidth, " solid ", COLORS.ui.border, ";" + ( true ? "" : 0), true ? "" : 0);
const inputStyleFocus = /*#__PURE__*/emotion_react_browser_esm_css("border-color:", COLORS.ui.theme, ";box-shadow:0 0 0 calc( ", config_values.borderWidthFocus, " - ", config_values.borderWidth, " ) ", COLORS.ui.theme, ";outline:2px solid transparent;" + ( true ? "" : 0), true ? "" : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/breakpoint-values.js
/* harmony default export */ var breakpoint_values = ({
huge: '1440px',
wide: '1280px',
'x-large': '1080px',
large: '960px',
// admin sidebar auto folds
medium: '782px',
// Adminbar goes big.
small: '600px',
mobile: '480px',
'zoomed-in': '280px'
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/breakpoint.js
/**
* Internal dependencies
*/
/**
* @param {keyof breakpoints} point
* @return {string} Media query declaration.
*/
const breakpoint = point => `@media (min-width: ${breakpoint_values[point]})`;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/utils/input/input-control.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const inputControl = /*#__PURE__*/emotion_react_browser_esm_css("font-family:", font('default.fontFamily'), ";padding:6px 8px;", inputStyleNeutral, ";font-size:", font('mobileTextMinFontSize'), ";line-height:normal;", breakpoint('small'), "{font-size:", font('default.fontSize'), ";line-height:normal;}&:focus{", inputStyleFocus, ";}&::-webkit-input-placeholder{color:", COLORS.ui.darkGrayPlaceholder, ";}&::-moz-placeholder{opacity:1;color:", COLORS.ui.darkGrayPlaceholder, ";}&:-ms-input-placeholder{color:", COLORS.ui.darkGrayPlaceholder, ";}.is-dark-theme &{&::-webkit-input-placeholder{color:", COLORS.ui.lightGrayPlaceholder, ";}&::-moz-placeholder{opacity:1;color:", COLORS.ui.lightGrayPlaceholder, ";}&:-ms-input-placeholder{color:", COLORS.ui.lightGrayPlaceholder, ";}}" + ( true ? "" : 0), true ? "" : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/textarea-control/styles/textarea-control-styles.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const StyledTextarea = createStyled("textarea", true ? {
target: "e1w5nnrk0"
} : 0)("width:100%;", inputControl, ";" + ( true ? "" : 0));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/textarea-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* TextareaControls are TextControls that allow for multiple lines of text, and
* wrap overflow text onto a new line. They are a fixed height and scroll
* vertically when the cursor reaches the bottom of the field.
*
* ```jsx
* import { TextareaControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyTextareaControl = () => {
* const [ text, setText ] = useState( '' );
*
* return (
* <TextareaControl
* label="Text"
* help="Enter some text"
* value={ text }
* onChange={ ( value ) => setText( value ) }
* />
* );
* };
* ```
*/
function TextareaControl(props) {
const {
__nextHasNoMarginBottom,
label,
hideLabelFromVision,
value,
help,
onChange,
rows = 4,
className,
...additionalProps
} = props;
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(TextareaControl);
const id = `inspector-textarea-control-${instanceId}`;
const onChangeValue = event => onChange(event.target.value);
return (0,external_wp_element_namespaceObject.createElement)(base_control, {
__nextHasNoMarginBottom: __nextHasNoMarginBottom,
label: label,
hideLabelFromVision: hideLabelFromVision,
id: id,
help: help,
className: className
}, (0,external_wp_element_namespaceObject.createElement)(StyledTextarea, extends_extends({
className: "components-textarea-control__input",
id: id,
rows: rows,
onChange: onChangeValue,
"aria-describedby": !!help ? id + '__help' : undefined,
value: value
}, additionalProps)));
}
/* harmony default export */ var textarea_control = (TextareaControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/text-highlight/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Highlights occurrences of a given string within another string of text. Wraps
* each match with a `<mark>` tag which provides browser default styling.
*
* ```jsx
* import { TextHighlight } from '@wordpress/components';
*
* const MyTextHighlight = () => (
* <TextHighlight
* text="Why do we like Gutenberg? Because Gutenberg is the best!"
* highlight="Gutenberg"
* />
* );
* ```
*/
const TextHighlight = props => {
const {
text = '',
highlight = ''
} = props;
const trimmedHighlightText = highlight.trim();
if (!trimmedHighlightText) {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, text);
}
const regex = new RegExp(`(${escapeRegExp(trimmedHighlightText)})`, 'gi');
return (0,external_wp_element_namespaceObject.createInterpolateElement)(text.replace(regex, '<mark>$&</mark>'), {
mark: (0,external_wp_element_namespaceObject.createElement)("mark", null)
});
};
/* harmony default export */ var text_highlight = (TextHighlight);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/tip.js
/**
* WordPress dependencies
*/
const tip = (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: "M12 15.8c-3.7 0-6.8-3-6.8-6.8s3-6.8 6.8-6.8c3.7 0 6.8 3 6.8 6.8s-3.1 6.8-6.8 6.8zm0-12C9.1 3.8 6.8 6.1 6.8 9s2.4 5.2 5.2 5.2c2.9 0 5.2-2.4 5.2-5.2S14.9 3.8 12 3.8zM8 17.5h8V19H8zM10 20.5h4V22h-4z"
}));
/* harmony default export */ var library_tip = (tip);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tip/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function Tip(props) {
const {
children
} = props;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-tip"
}, (0,external_wp_element_namespaceObject.createElement)(icons_build_module_icon, {
icon: library_tip
}), (0,external_wp_element_namespaceObject.createElement)("p", null, children));
}
/* harmony default export */ var build_module_tip = (Tip);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toggle-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* ToggleControl is used to generate a toggle user interface.
*
* ```jsx
* import { ToggleControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyToggleControl = () => {
* const [ value, setValue ] = useState( false );
*
* return (
* <ToggleControl
* label="Fixed Background"
* checked={ value }
* onChange={ () => setValue( ( state ) => ! state ) }
* />
* );
* };
* ```
*/
function ToggleControl(_ref) {
let {
__nextHasNoMarginBottom,
label,
checked,
help,
className,
onChange,
disabled
} = _ref;
function onChangeToggle(event) {
onChange(event.target.checked);
}
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(ToggleControl);
const id = `inspector-toggle-control-${instanceId}`;
const cx = useCx();
const classes = cx('components-toggle-control', className, !__nextHasNoMarginBottom && /*#__PURE__*/emotion_react_browser_esm_css({
marginBottom: space(3)
}, true ? "" : 0, true ? "" : 0));
let describedBy, helpLabel;
if (help) {
if (typeof help === 'function') {
// `help` as a function works only for controlled components where
// `checked` is passed down from parent component. Uncontrolled
// component can show only a static help label.
if (checked !== undefined) {
helpLabel = help(checked);
}
} else {
helpLabel = help;
}
if (helpLabel) {
describedBy = id + '__help';
}
}
return (0,external_wp_element_namespaceObject.createElement)(base_control, {
id: id,
help: helpLabel,
className: classes,
__nextHasNoMarginBottom: true
}, (0,external_wp_element_namespaceObject.createElement)(h_stack_component, {
justify: "flex-start",
spacing: 3
}, (0,external_wp_element_namespaceObject.createElement)(form_toggle, {
id: id,
checked: checked,
onChange: onChangeToggle,
"aria-describedby": describedBy,
disabled: disabled
}), (0,external_wp_element_namespaceObject.createElement)(flex_block_component, {
as: "label",
htmlFor: id,
className: "components-toggle-control__label"
}, label)));
}
/* harmony default export */ var toggle_control = (ToggleControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toggle-group-control/toggle-group-control-option-icon/component.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnforwardedToggleGroupControlOptionIcon(props, ref) {
const {
icon,
label,
...restProps
} = props;
return (0,external_wp_element_namespaceObject.createElement)(toggle_group_control_option_base_component, extends_extends({}, restProps, {
isIcon: true,
"aria-label": label,
showTooltip: true,
ref: ref
}), (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: icon
}));
}
/**
* `ToggleGroupControlOptionIcon` is a form component which is meant to be used as a
* child of `ToggleGroupControl` and displays an icon.
*
* ```jsx
*
* import {
* __experimentalToggleGroupControl as ToggleGroupControl,
* __experimentalToggleGroupControlOptionIcon as ToggleGroupControlOptionIcon,
* from '@wordpress/components';
* import { formatLowercase, formatUppercase } from '@wordpress/icons';
*
* function Example() {
* return (
* <ToggleGroupControl>
* <ToggleGroupControlOptionIcon
* value="uppercase"
* label="Uppercase"
* icon={ formatUppercase }
* />
* <ToggleGroupControlOptionIcon
* value="lowercase"
* label="Lowercase"
* icon={ formatLowercase }
* />
* </ToggleGroupControl>
* );
* }
* ```
*/
const ToggleGroupControlOptionIcon = (0,external_wp_element_namespaceObject.forwardRef)(UnforwardedToggleGroupControlOptionIcon);
/* harmony default export */ var toggle_group_control_option_icon_component = (ToggleGroupControlOptionIcon);
;// CONCATENATED MODULE: ./node_modules/reakit/es/__keys-ae468c11.js
// Automatically generated
var TOOLBAR_STATE_KEYS = ["baseId", "unstable_idCountRef", "unstable_virtual", "rtl", "orientation", "items", "groups", "currentId", "loop", "wrap", "shift", "unstable_moves", "unstable_hasActiveWidget", "unstable_includesBaseElement", "setBaseId", "registerItem", "unregisterItem", "registerGroup", "unregisterGroup", "move", "next", "previous", "up", "down", "first", "last", "sort", "unstable_setVirtual", "setRTL", "setOrientation", "setCurrentId", "setLoop", "setWrap", "setShift", "reset", "unstable_setIncludesBaseElement", "unstable_setHasActiveWidget"];
var TOOLBAR_KEYS = TOOLBAR_STATE_KEYS;
var TOOLBAR_ITEM_KEYS = TOOLBAR_KEYS;
var TOOLBAR_SEPARATOR_KEYS = (/* unused pure expression or super */ null && (TOOLBAR_ITEM_KEYS));
;// CONCATENATED MODULE: ./node_modules/reakit/es/Toolbar/ToolbarItem.js
var useToolbarItem = createHook({
name: "ToolbarItem",
compose: useCompositeItem,
keys: TOOLBAR_ITEM_KEYS
});
var ToolbarItem = createComponent({
as: "button",
memo: true,
useHook: useToolbarItem
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toolbar/toolbar-context/index.js
/**
* WordPress dependencies
*/
const ToolbarContext = (0,external_wp_element_namespaceObject.createContext)();
/* harmony default export */ var toolbar_context = (ToolbarContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toolbar/toolbar-item/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function toolbar_item_ToolbarItem(_ref, ref) {
let {
children,
as: Component,
...props
} = _ref;
const accessibleToolbarState = (0,external_wp_element_namespaceObject.useContext)(toolbar_context);
if (typeof children !== 'function' && !Component) {
typeof process !== "undefined" && process.env && "production" !== "production" ? 0 : void 0;
return null;
}
const allProps = { ...props,
ref,
'data-toolbar-item': true
};
if (!accessibleToolbarState) {
if (Component) {
return (0,external_wp_element_namespaceObject.createElement)(Component, allProps, children);
}
return children(allProps);
}
return (0,external_wp_element_namespaceObject.createElement)(ToolbarItem, extends_extends({}, accessibleToolbarState, allProps, {
as: Component
}), children);
}
/* harmony default export */ var toolbar_item = ((0,external_wp_element_namespaceObject.forwardRef)(toolbar_item_ToolbarItem));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toolbar/toolbar-button/toolbar-button-container.js
const ToolbarButtonContainer = props => (0,external_wp_element_namespaceObject.createElement)("div", {
className: props.className
}, props.children);
/* harmony default export */ var toolbar_button_container = (ToolbarButtonContainer);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toolbar/toolbar-button/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ToolbarButton(_ref, ref) {
let {
containerClassName,
className,
extraProps,
children,
title,
isActive,
isDisabled,
...props
} = _ref;
const accessibleToolbarState = (0,external_wp_element_namespaceObject.useContext)(toolbar_context);
if (!accessibleToolbarState) {
return (0,external_wp_element_namespaceObject.createElement)(toolbar_button_container, {
className: containerClassName
}, (0,external_wp_element_namespaceObject.createElement)(build_module_button, extends_extends({
ref: ref,
icon: props.icon,
label: title,
shortcut: props.shortcut,
"data-subscript": props.subscript,
onClick: event => {
event.stopPropagation();
if (props.onClick) {
props.onClick(event);
}
},
className: classnames_default()('components-toolbar__control', className),
isPressed: isActive,
disabled: isDisabled,
"data-toolbar-item": true
}, extraProps, props), children));
} // ToobarItem will pass all props to the render prop child, which will pass
// all props to Button. This means that ToolbarButton has the same API as
// Button.
return (0,external_wp_element_namespaceObject.createElement)(toolbar_item, extends_extends({
className: classnames_default()('components-toolbar-button', className)
}, extraProps, props, {
ref: ref
}), toolbarItemProps => (0,external_wp_element_namespaceObject.createElement)(build_module_button, extends_extends({
label: title,
isPressed: isActive,
disabled: isDisabled
}, toolbarItemProps), children));
}
/* harmony default export */ var toolbar_button = ((0,external_wp_element_namespaceObject.forwardRef)(ToolbarButton));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toolbar/toolbar-group/toolbar-group-container.js
const ToolbarGroupContainer = _ref => {
let {
className,
children,
...props
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("div", extends_extends({
className: className
}, props), children);
};
/* harmony default export */ var toolbar_group_container = (ToolbarGroupContainer);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toolbar/toolbar-group/toolbar-group-collapsed.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ToolbarGroupCollapsed(_ref) {
let {
controls = [],
toggleProps,
...props
} = _ref;
// It'll contain state if `ToolbarGroup` is being used within
// `<Toolbar label="label" />`
const accessibleToolbarState = (0,external_wp_element_namespaceObject.useContext)(toolbar_context);
const renderDropdownMenu = internalToggleProps => (0,external_wp_element_namespaceObject.createElement)(dropdown_menu, extends_extends({
controls: controls,
toggleProps: { ...internalToggleProps,
'data-toolbar-item': true
}
}, props));
if (accessibleToolbarState) {
return (0,external_wp_element_namespaceObject.createElement)(toolbar_item, toggleProps, renderDropdownMenu);
}
return renderDropdownMenu(toggleProps);
}
/* harmony default export */ var toolbar_group_collapsed = (ToolbarGroupCollapsed);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toolbar/toolbar-group/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Renders a collapsible group of controls
*
* The `controls` prop accepts an array of sets. A set is an array of controls.
* Controls have the following shape:
*
* ```
* {
* icon: string,
* title: string,
* subscript: string,
* onClick: Function,
* isActive: boolean,
* isDisabled: boolean
* }
* ```
*
* For convenience it is also possible to pass only an array of controls. It is
* then assumed this is the only set.
*
* Either `controls` or `children` is required, otherwise this components
* renders nothing.
*
* @param {Object} props Component props.
* @param {Array} [props.controls] The controls to render in this toolbar.
* @param {WPElement} [props.children] Any other things to render inside the toolbar besides the controls.
* @param {string} [props.className] Class to set on the container div.
* @param {boolean} [props.isCollapsed] Turns ToolbarGroup into a dropdown menu.
* @param {string} [props.title] ARIA label for dropdown menu if is collapsed.
*/
function ToolbarGroup(_ref) {
var _controlSets;
let {
controls = [],
children,
className,
isCollapsed,
title,
...props
} = _ref;
// It'll contain state if `ToolbarGroup` is being used within
// `<Toolbar label="label" />`
const accessibleToolbarState = (0,external_wp_element_namespaceObject.useContext)(toolbar_context);
if ((!controls || !controls.length) && !children) {
return null;
}
const finalClassName = classnames_default()( // Unfortunately, there's legacy code referencing to `.components-toolbar`
// So we can't get rid of it
accessibleToolbarState ? 'components-toolbar-group' : 'components-toolbar', className); // Normalize controls to nested array of objects (sets of controls)
let controlSets = controls;
if (!Array.isArray(controlSets[0])) {
controlSets = [controlSets];
}
if (isCollapsed) {
return (0,external_wp_element_namespaceObject.createElement)(toolbar_group_collapsed, extends_extends({
label: title,
controls: controlSets,
className: finalClassName,
children: children
}, props));
}
return (0,external_wp_element_namespaceObject.createElement)(toolbar_group_container, extends_extends({
className: finalClassName
}, props), (_controlSets = controlSets) === null || _controlSets === void 0 ? void 0 : _controlSets.flatMap((controlSet, indexOfSet) => controlSet.map((control, indexOfControl) => (0,external_wp_element_namespaceObject.createElement)(toolbar_button, extends_extends({
key: [indexOfSet, indexOfControl].join(),
containerClassName: indexOfSet > 0 && indexOfControl === 0 ? 'has-left-divider' : null
}, control)))), children);
}
/* harmony default export */ var toolbar_group = (ToolbarGroup);
;// CONCATENATED MODULE: ./node_modules/reakit/es/Toolbar/ToolbarState.js
function useToolbarState(initialState) {
if (initialState === void 0) {
initialState = {};
}
var _useSealedState = useSealedState(initialState),
_useSealedState$orien = _useSealedState.orientation,
orientation = _useSealedState$orien === void 0 ? "horizontal" : _useSealedState$orien,
sealed = _objectWithoutPropertiesLoose(_useSealedState, ["orientation"]);
return useCompositeState(_objectSpread2({
orientation: orientation
}, sealed));
}
;// CONCATENATED MODULE: ./node_modules/reakit/es/Toolbar/Toolbar.js
var useToolbar = createHook({
name: "Toolbar",
compose: useComposite,
keys: TOOLBAR_KEYS,
useProps: function useProps(options, htmlProps) {
return _objectSpread2({
role: "toolbar",
"aria-orientation": options.orientation
}, htmlProps);
}
});
var Toolbar = createComponent({
as: "div",
useHook: useToolbar,
useCreateElement: function useCreateElement$1(type, props, children) {
false ? 0 : void 0;
return useCreateElement(type, props, children);
}
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toolbar/toolbar/toolbar-container.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ToolbarContainer(_ref, ref) {
let {
label,
...props
} = _ref;
// https://reakit.io/docs/basic-concepts/#state-hooks
// Passing baseId for server side rendering (which includes snapshots)
// If an id prop is passed to Toolbar, toolbar items will use it as a base for their ids
const toolbarState = useToolbarState({
loop: true,
baseId: props.id,
rtl: (0,external_wp_i18n_namespaceObject.isRTL)()
});
return (// This will provide state for `ToolbarButton`'s
(0,external_wp_element_namespaceObject.createElement)(toolbar_context.Provider, {
value: toolbarState
}, (0,external_wp_element_namespaceObject.createElement)(Toolbar, extends_extends({
ref: ref,
"aria-label": label
}, toolbarState, props)))
);
}
/* harmony default export */ var toolbar_container = ((0,external_wp_element_namespaceObject.forwardRef)(ToolbarContainer));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toolbar/toolbar/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Renders a toolbar.
*
* To add controls, simply pass `ToolbarButton` components as children.
*
* @param {Object} props Component props.
* @param {string} [props.className] Class to set on the container div.
* @param {string} [props.label] ARIA label for toolbar container.
* @param {Object} ref React Element ref.
*/
function toolbar_Toolbar(_ref, ref) {
let {
className,
label,
...props
} = _ref;
if (!label) {
external_wp_deprecated_default()('Using Toolbar without label prop', {
since: '5.6',
alternative: 'ToolbarGroup component',
link: 'https://developer.wordpress.org/block-editor/components/toolbar/'
});
return (0,external_wp_element_namespaceObject.createElement)(toolbar_group, extends_extends({}, props, {
className: className
}));
} // `ToolbarGroup` already uses components-toolbar for compatibility reasons.
const finalClassName = classnames_default()('components-accessible-toolbar', className);
return (0,external_wp_element_namespaceObject.createElement)(toolbar_container, extends_extends({
className: finalClassName,
label: label,
ref: ref
}, props));
}
/* harmony default export */ var toolbar = ((0,external_wp_element_namespaceObject.forwardRef)(toolbar_Toolbar));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/toolbar/toolbar-dropdown-menu/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ToolbarDropdownMenu(props, ref) {
const accessibleToolbarState = (0,external_wp_element_namespaceObject.useContext)(toolbar_context);
if (!accessibleToolbarState) {
return (0,external_wp_element_namespaceObject.createElement)(dropdown_menu, props);
} // ToobarItem will pass all props to the render prop child, which will pass
// all props to the toggle of DropdownMenu. This means that ToolbarDropdownMenu
// has the same API as DropdownMenu.
return (0,external_wp_element_namespaceObject.createElement)(toolbar_item, extends_extends({
ref: ref
}, props.toggleProps), toolbarItemProps => (0,external_wp_element_namespaceObject.createElement)(dropdown_menu, extends_extends({}, props, {
popoverProps: {
variant: 'toolbar',
...props.popoverProps
},
toggleProps: toolbarItemProps
})));
}
/* harmony default export */ var toolbar_dropdown_menu = ((0,external_wp_element_namespaceObject.forwardRef)(ToolbarDropdownMenu));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tools-panel/styles.js
function tools_panel_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const toolsPanelGrid = {
columns: columns => /*#__PURE__*/emotion_react_browser_esm_css("grid-template-columns:", `repeat( ${columns}, minmax(0, 1fr) )`, ";" + ( true ? "" : 0), true ? "" : 0),
spacing: /*#__PURE__*/emotion_react_browser_esm_css("column-gap:", space(2), ";row-gap:", space(4), ";" + ( true ? "" : 0), true ? "" : 0),
item: {
fullWidth: true ? {
name: "18iuzk9",
styles: "grid-column:1/-1"
} : 0
}
};
const ToolsPanel = columns => /*#__PURE__*/emotion_react_browser_esm_css(toolsPanelGrid.columns(columns), " ", toolsPanelGrid.spacing, " border-top:", config_values.borderWidth, " solid ", COLORS.gray[300], ";margin-top:-1px;padding:", space(4), ";" + ( true ? "" : 0), true ? "" : 0);
/**
* Items injected into a ToolsPanel via a virtual bubbling slot will require
* an inner dom element to be injected. The following rule allows for the
* CSS grid display to be re-established.
*/
const ToolsPanelWithInnerWrapper = columns => {
return /*#__PURE__*/emotion_react_browser_esm_css(">div:not( :first-of-type ){display:grid;", toolsPanelGrid.columns(columns), " ", toolsPanelGrid.spacing, " ", toolsPanelGrid.item.fullWidth, ";}" + ( true ? "" : 0), true ? "" : 0);
};
const ToolsPanelHiddenInnerWrapper = true ? {
name: "huufmu",
styles: ">div:not( :first-of-type ){display:none;}"
} : 0;
const ToolsPanelHeader = /*#__PURE__*/emotion_react_browser_esm_css(toolsPanelGrid.item.fullWidth, " gap:", space(2), ";.components-dropdown-menu{margin:", space(-1), " 0;line-height:0;}&&&& .components-dropdown-menu__toggle{padding:0;min-width:", space(6), ";}" + ( true ? "" : 0), true ? "" : 0);
const ToolsPanelHeading = true ? {
name: "1pmxm02",
styles: "font-size:inherit;font-weight:500;line-height:normal;&&{margin:0;}"
} : 0;
const ToolsPanelItem = /*#__PURE__*/emotion_react_browser_esm_css(toolsPanelGrid.item.fullWidth, "&>div,&>fieldset{padding-bottom:0;margin-bottom:0;max-width:100%;}&& ", base_control_styles_Wrapper, "{margin-bottom:0;", StyledField, ":last-child{margin-bottom:0;}}", StyledHelp, "{margin-bottom:0;}&& ", LabelWrapper, "{label{line-height:1.4em;}}" + ( true ? "" : 0), true ? "" : 0);
const ToolsPanelItemPlaceholder = true ? {
name: "eivff4",
styles: "display:none"
} : 0;
const styles_DropdownMenu = true ? {
name: "16gsvie",
styles: "min-width:200px"
} : 0;
const ResetLabel = createStyled("span", true ? {
target: "ews648u0"
} : 0)("color:", COLORS.ui.themeDark10, ";font-size:11px;font-weight:500;line-height:1.4;", rtl({
marginLeft: space(3)
}), " text-transform:uppercase;" + ( true ? "" : 0));
const DefaultControlsItem = /*#__PURE__*/emotion_react_browser_esm_css("color:", COLORS.gray[900], ";&&[aria-disabled='true']{color:", COLORS.gray[700], ";opacity:1;&:hover{color:", COLORS.gray[700], ";}", ResetLabel, "{opacity:0.3;}}" + ( true ? "" : 0), true ? "" : 0);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tools-panel/context.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const tools_panel_context_noop = () => undefined;
const ToolsPanelContext = (0,external_wp_element_namespaceObject.createContext)({
menuItems: {
default: {},
optional: {}
},
hasMenuItems: false,
isResetting: false,
shouldRenderPlaceholderItems: false,
registerPanelItem: tools_panel_context_noop,
deregisterPanelItem: tools_panel_context_noop,
flagItemCustomization: tools_panel_context_noop,
areAllOptionalControlsHidden: true
});
const useToolsPanelContext = () => (0,external_wp_element_namespaceObject.useContext)(ToolsPanelContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tools-panel/tools-panel-header/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useToolsPanelHeader(props) {
const {
className,
...otherProps
} = useContextSystem(props, 'ToolsPanelHeader');
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(ToolsPanelHeader, className);
}, [className, cx]);
const dropdownMenuClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(styles_DropdownMenu);
}, [cx]);
const headingClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(ToolsPanelHeading);
}, [cx]);
const defaultControlsItemClassName = (0,external_wp_element_namespaceObject.useMemo)(() => {
return cx(DefaultControlsItem);
}, [cx]);
const {
menuItems,
hasMenuItems,
areAllOptionalControlsHidden
} = useToolsPanelContext();
return { ...otherProps,
areAllOptionalControlsHidden,
defaultControlsItemClassName,
dropdownMenuClassName,
hasMenuItems,
headingClassName,
menuItems,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tools-panel/tools-panel-header/component.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const DefaultControlsGroup = _ref => {
let {
itemClassName,
items,
toggleItem
} = _ref;
if (!items.length) {
return null;
}
const resetSuffix = (0,external_wp_element_namespaceObject.createElement)(ResetLabel, {
"aria-hidden": true
}, (0,external_wp_i18n_namespaceObject.__)('Reset'));
return (0,external_wp_element_namespaceObject.createElement)(menu_group, {
label: (0,external_wp_i18n_namespaceObject.__)('Defaults')
}, items.map(_ref2 => {
let [label, hasValue] = _ref2;
if (hasValue) {
return (0,external_wp_element_namespaceObject.createElement)(menu_item, {
key: label,
className: itemClassName,
role: "menuitem",
label: (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The name of the control being reset e.g. "Padding".
(0,external_wp_i18n_namespaceObject.__)('Reset %s'), label),
onClick: () => {
toggleItem(label);
(0,external_wp_a11y_namespaceObject.speak)((0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The name of the control being reset e.g. "Padding".
(0,external_wp_i18n_namespaceObject.__)('%s reset to default'), label), 'assertive');
},
suffix: resetSuffix
}, label);
}
return (0,external_wp_element_namespaceObject.createElement)(menu_item, {
key: label,
className: itemClassName,
role: "menuitemcheckbox",
isSelected: true,
"aria-disabled": true
}, label);
}));
};
const OptionalControlsGroup = _ref3 => {
let {
items,
toggleItem
} = _ref3;
if (!items.length) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(menu_group, {
label: (0,external_wp_i18n_namespaceObject.__)('Tools')
}, items.map(_ref4 => {
let [label, isSelected] = _ref4;
const itemLabel = isSelected ? (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The name of the control being hidden and reset e.g. "Padding".
(0,external_wp_i18n_namespaceObject.__)('Hide and reset %s'), label) : (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The name of the control to display e.g. "Padding".
(0,external_wp_i18n_namespaceObject.__)('Show %s'), label);
return (0,external_wp_element_namespaceObject.createElement)(menu_item, {
key: label,
icon: isSelected && library_check,
isSelected: isSelected,
label: itemLabel,
onClick: () => {
if (isSelected) {
(0,external_wp_a11y_namespaceObject.speak)((0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The name of the control being reset e.g. "Padding".
(0,external_wp_i18n_namespaceObject.__)('%s hidden and reset to default'), label), 'assertive');
} else {
(0,external_wp_a11y_namespaceObject.speak)((0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The name of the control being reset e.g. "Padding".
(0,external_wp_i18n_namespaceObject.__)('%s is now visible'), label), 'assertive');
}
toggleItem(label);
},
role: "menuitemcheckbox"
}, label);
}));
};
const component_ToolsPanelHeader = (props, forwardedRef) => {
const {
areAllOptionalControlsHidden,
defaultControlsItemClassName,
dropdownMenuClassName,
hasMenuItems,
headingClassName,
label: labelText,
menuItems,
resetAll,
toggleItem,
...headerProps
} = useToolsPanelHeader(props);
if (!labelText) {
return null;
}
const defaultItems = Object.entries((menuItems === null || menuItems === void 0 ? void 0 : menuItems.default) || {});
const optionalItems = Object.entries((menuItems === null || menuItems === void 0 ? void 0 : menuItems.optional) || {});
const dropDownMenuIcon = areAllOptionalControlsHidden ? library_plus : more_vertical;
const dropDownMenuLabelText = (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The name of the tool e.g. "Color" or "Typography".
(0,external_wp_i18n_namespaceObject._x)('%s options', 'Button label to reveal tool panel options'), labelText);
const dropdownMenuDescriptionText = areAllOptionalControlsHidden ? (0,external_wp_i18n_namespaceObject.__)('All options are currently hidden') : undefined;
const canResetAll = [...defaultItems, ...optionalItems].some(_ref5 => {
let [, isSelected] = _ref5;
return isSelected;
});
return (0,external_wp_element_namespaceObject.createElement)(h_stack_component, extends_extends({}, headerProps, {
ref: forwardedRef
}), (0,external_wp_element_namespaceObject.createElement)(heading_component, {
level: 2,
className: headingClassName
}, labelText), hasMenuItems && (0,external_wp_element_namespaceObject.createElement)(dropdown_menu, {
icon: dropDownMenuIcon,
label: dropDownMenuLabelText,
menuProps: {
className: dropdownMenuClassName
},
toggleProps: {
isSmall: true,
describedBy: dropdownMenuDescriptionText
}
}, () => (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(DefaultControlsGroup, {
items: defaultItems,
toggleItem: toggleItem,
itemClassName: defaultControlsItemClassName
}), (0,external_wp_element_namespaceObject.createElement)(OptionalControlsGroup, {
items: optionalItems,
toggleItem: toggleItem
}), (0,external_wp_element_namespaceObject.createElement)(menu_group, null, (0,external_wp_element_namespaceObject.createElement)(menu_item, {
"aria-disabled": !canResetAll,
variant: 'tertiary',
onClick: () => {
if (canResetAll) {
resetAll();
(0,external_wp_a11y_namespaceObject.speak)((0,external_wp_i18n_namespaceObject.__)('All options reset'), 'assertive');
}
}
}, (0,external_wp_i18n_namespaceObject.__)('Reset all'))))));
};
const ConnectedToolsPanelHeader = contextConnect(component_ToolsPanelHeader, 'ToolsPanelHeader');
/* harmony default export */ var tools_panel_header_component = (ConnectedToolsPanelHeader);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tools-panel/tools-panel/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const DEFAULT_COLUMNS = 2;
const generateMenuItems = _ref => {
let {
panelItems,
shouldReset,
currentMenuItems
} = _ref;
const menuItems = {
default: {},
optional: {}
};
panelItems.forEach(_ref2 => {
var _currentMenuItems$gro;
let {
hasValue,
isShownByDefault,
label
} = _ref2;
const group = isShownByDefault ? 'default' : 'optional'; // If a menu item for this label has already been flagged as customized
// (for default controls), or toggled on (for optional controls), do not
// overwrite its value as those controls would lose that state.
const existingItemValue = currentMenuItems === null || currentMenuItems === void 0 ? void 0 : (_currentMenuItems$gro = currentMenuItems[group]) === null || _currentMenuItems$gro === void 0 ? void 0 : _currentMenuItems$gro[label];
const value = existingItemValue ? existingItemValue : hasValue();
menuItems[group][label] = shouldReset ? false : value;
});
return menuItems;
};
const isMenuItemTypeEmpty = obj => obj && Object.keys(obj).length === 0;
function useToolsPanel(props) {
const {
className,
resetAll,
panelId,
hasInnerWrapper,
shouldRenderPlaceholderItems,
__experimentalFirstVisibleItemClass,
__experimentalLastVisibleItemClass,
...otherProps
} = useContextSystem(props, 'ToolsPanel');
const isResetting = (0,external_wp_element_namespaceObject.useRef)(false);
const wasResetting = isResetting.current; // `isResetting` is cleared via this hook to effectively batch together
// the resetAll task. Without this, the flag is cleared after the first
// control updates and forces a rerender with subsequent controls then
// believing they need to reset, unfortunately using stale data.
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (wasResetting) {
isResetting.current = false;
}
}, [wasResetting]); // Allow panel items to register themselves.
const [panelItems, setPanelItems] = (0,external_wp_element_namespaceObject.useState)([]);
const registerPanelItem = (0,external_wp_element_namespaceObject.useCallback)(item => {
setPanelItems(items => {
const newItems = [...items]; // If an item with this label has already been registered, remove it
// first. This can happen when an item is moved between the default
// and optional groups.
const existingIndex = newItems.findIndex(oldItem => oldItem.label === item.label);
if (existingIndex !== -1) {
newItems.splice(existingIndex, 1);
}
return [...newItems, item];
});
}, [setPanelItems]); // Panels need to deregister on unmount to avoid orphans in menu state.
// This is an issue when panel items are being injected via SlotFills.
const deregisterPanelItem = (0,external_wp_element_namespaceObject.useCallback)(label => {
// When switching selections between components injecting matching
// controls, e.g. both panels have a "padding" control, the
// deregistration of the first panel doesn't occur until after the
// registration of the next.
setPanelItems(items => {
const newItems = [...items];
const index = newItems.findIndex(item => item.label === label);
if (index !== -1) {
newItems.splice(index, 1);
}
return newItems;
});
}, [setPanelItems]); // Manage and share display state of menu items representing child controls.
const [menuItems, setMenuItems] = (0,external_wp_element_namespaceObject.useState)({
default: {},
optional: {}
}); // Setup menuItems state as panel items register themselves.
(0,external_wp_element_namespaceObject.useEffect)(() => {
setMenuItems(prevState => {
const items = generateMenuItems({
panelItems,
shouldReset: false,
currentMenuItems: prevState
});
return items;
});
}, [panelItems, setMenuItems]); // Force a menu item to be checked.
// This is intended for use with default panel items. They are displayed
// separately to optional items and have different display states,
// we need to update that when their value is customized.
const flagItemCustomization = (0,external_wp_element_namespaceObject.useCallback)(function (label) {
let group = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'default';
setMenuItems(items => {
const newState = { ...items,
[group]: { ...items[group],
[label]: true
}
};
return newState;
});
}, [setMenuItems]); // Whether all optional menu items are hidden or not must be tracked
// in order to later determine if the panel display is empty and handle
// conditional display of a plus icon to indicate the presence of further
// menu items.
const [areAllOptionalControlsHidden, setAreAllOptionalControlsHidden] = (0,external_wp_element_namespaceObject.useState)(false);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (isMenuItemTypeEmpty(menuItems === null || menuItems === void 0 ? void 0 : menuItems.default) && !isMenuItemTypeEmpty(menuItems === null || menuItems === void 0 ? void 0 : menuItems.optional)) {
const allControlsHidden = !Object.entries(menuItems.optional).some(_ref3 => {
let [, isSelected] = _ref3;
return isSelected;
});
setAreAllOptionalControlsHidden(allControlsHidden);
}
}, [menuItems, setAreAllOptionalControlsHidden]);
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
const wrapperStyle = hasInnerWrapper && ToolsPanelWithInnerWrapper(DEFAULT_COLUMNS);
const emptyStyle = isMenuItemTypeEmpty(menuItems === null || menuItems === void 0 ? void 0 : menuItems.default) && areAllOptionalControlsHidden && ToolsPanelHiddenInnerWrapper;
return cx(ToolsPanel(DEFAULT_COLUMNS), wrapperStyle, emptyStyle, className);
}, [areAllOptionalControlsHidden, className, cx, hasInnerWrapper, menuItems]); // Toggle the checked state of a menu item which is then used to determine
// display of the item within the panel.
const toggleItem = (0,external_wp_element_namespaceObject.useCallback)(label => {
const currentItem = panelItems.find(item => item.label === label);
if (!currentItem) {
return;
}
const menuGroup = currentItem.isShownByDefault ? 'default' : 'optional';
const newMenuItems = { ...menuItems,
[menuGroup]: { ...menuItems[menuGroup],
[label]: !menuItems[menuGroup][label]
}
};
setMenuItems(newMenuItems);
}, [menuItems, panelItems, setMenuItems]); // Resets display of children and executes resetAll callback if available.
const resetAllItems = (0,external_wp_element_namespaceObject.useCallback)(() => {
if (typeof resetAll === 'function') {
isResetting.current = true; // Collect available reset filters from panel items.
const filters = [];
panelItems.forEach(item => {
if (item.resetAllFilter) {
filters.push(item.resetAllFilter);
}
});
resetAll(filters);
} // Turn off display of all non-default items.
const resetMenuItems = generateMenuItems({
panelItems,
shouldReset: true
});
setMenuItems(resetMenuItems);
}, [panelItems, resetAll, setMenuItems]); // Assist ItemGroup styling when there are potentially hidden placeholder
// items by identifying first & last items that are toggled on for display.
const getFirstVisibleItemLabel = items => {
const optionalItems = menuItems.optional || {};
const firstItem = items.find(item => item.isShownByDefault || !!optionalItems[item.label]);
return firstItem === null || firstItem === void 0 ? void 0 : firstItem.label;
};
const firstDisplayedItem = getFirstVisibleItemLabel(panelItems);
const lastDisplayedItem = getFirstVisibleItemLabel([...panelItems].reverse());
const panelContext = (0,external_wp_element_namespaceObject.useMemo)(() => ({
areAllOptionalControlsHidden,
deregisterPanelItem,
firstDisplayedItem,
flagItemCustomization,
hasMenuItems: !!panelItems.length,
isResetting: isResetting.current,
lastDisplayedItem,
menuItems,
panelId,
registerPanelItem,
shouldRenderPlaceholderItems,
__experimentalFirstVisibleItemClass,
__experimentalLastVisibleItemClass
}), [areAllOptionalControlsHidden, deregisterPanelItem, firstDisplayedItem, flagItemCustomization, lastDisplayedItem, menuItems, panelId, panelItems, registerPanelItem, shouldRenderPlaceholderItems, __experimentalFirstVisibleItemClass, __experimentalLastVisibleItemClass]);
return { ...otherProps,
panelContext,
resetAllItems,
toggleItem,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tools-panel/tools-panel/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const component_ToolsPanel = (props, forwardedRef) => {
const {
children,
label,
panelContext,
resetAllItems,
toggleItem,
...toolsPanelProps
} = useToolsPanel(props);
return (0,external_wp_element_namespaceObject.createElement)(grid_component, extends_extends({}, toolsPanelProps, {
columns: 2,
ref: forwardedRef
}), (0,external_wp_element_namespaceObject.createElement)(ToolsPanelContext.Provider, {
value: panelContext
}, (0,external_wp_element_namespaceObject.createElement)(tools_panel_header_component, {
label: label,
resetAll: resetAllItems,
toggleItem: toggleItem
}), children));
};
const ConnectedToolsPanel = contextConnect(component_ToolsPanel, 'ToolsPanel');
/* harmony default export */ var tools_panel_component = (ConnectedToolsPanel);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tools-panel/tools-panel-item/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useToolsPanelItem(props) {
var _menuItems$menuGroup, _menuItems$menuGroup2, _menuItems$menuGroup3;
const {
className,
hasValue,
isShownByDefault,
label,
panelId,
resetAllFilter,
onDeselect,
onSelect,
...otherProps
} = useContextSystem(props, 'ToolsPanelItem');
const {
panelId: currentPanelId,
menuItems,
registerPanelItem,
deregisterPanelItem,
flagItemCustomization,
isResetting,
shouldRenderPlaceholderItems: shouldRenderPlaceholder,
firstDisplayedItem,
lastDisplayedItem,
__experimentalFirstVisibleItemClass,
__experimentalLastVisibleItemClass
} = useToolsPanelContext();
const hasValueCallback = (0,external_wp_element_namespaceObject.useCallback)(hasValue, [panelId, hasValue]);
const resetAllFilterCallback = (0,external_wp_element_namespaceObject.useCallback)(resetAllFilter, [panelId, resetAllFilter]);
const previousPanelId = (0,external_wp_compose_namespaceObject.usePrevious)(currentPanelId);
const hasMatchingPanel = currentPanelId === panelId || currentPanelId === null; // Registering the panel item allows the panel to include it in its
// automatically generated menu and determine its initial checked status.
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (hasMatchingPanel && previousPanelId !== null) {
registerPanelItem({
hasValue: hasValueCallback,
isShownByDefault,
label,
resetAllFilter: resetAllFilterCallback,
panelId
});
}
return () => {
if (previousPanelId === null && !!currentPanelId || currentPanelId === panelId) {
deregisterPanelItem(label);
}
};
}, [currentPanelId, hasMatchingPanel, isShownByDefault, label, hasValueCallback, panelId, previousPanelId, resetAllFilterCallback, registerPanelItem, deregisterPanelItem]); // Note: `label` is used as a key when building menu item state in
// `ToolsPanel`.
const menuGroup = isShownByDefault ? 'default' : 'optional';
const isMenuItemChecked = menuItems === null || menuItems === void 0 ? void 0 : (_menuItems$menuGroup = menuItems[menuGroup]) === null || _menuItems$menuGroup === void 0 ? void 0 : _menuItems$menuGroup[label];
const wasMenuItemChecked = (0,external_wp_compose_namespaceObject.usePrevious)(isMenuItemChecked);
const isRegistered = (menuItems === null || menuItems === void 0 ? void 0 : (_menuItems$menuGroup2 = menuItems[menuGroup]) === null || _menuItems$menuGroup2 === void 0 ? void 0 : _menuItems$menuGroup2[label]) !== undefined;
const isValueSet = hasValue();
const wasValueSet = (0,external_wp_compose_namespaceObject.usePrevious)(isValueSet);
const newValueSet = isValueSet && !wasValueSet; // Notify the panel when an item's value has been set.
//
// 1. For default controls, this is so "reset" appears beside its menu item.
// 2. For optional controls, when the panel ID is `null`, it allows the
// panel to ensure the item is toggled on for display in the menu, given the
// value has been set external to the control.
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (!newValueSet) {
return;
}
if (isShownByDefault || currentPanelId === null) {
flagItemCustomization(label, menuGroup);
}
}, [currentPanelId, newValueSet, isShownByDefault, menuGroup, label, flagItemCustomization]); // Determine if the panel item's corresponding menu is being toggled and
// trigger appropriate callback if it is.
(0,external_wp_element_namespaceObject.useEffect)(() => {
// We check whether this item is currently registered as items rendered
// via fills can persist through the parent panel being remounted.
// See: https://github.com/WordPress/gutenberg/pull/45673
if (!isRegistered || isResetting || !hasMatchingPanel) {
return;
}
if (isMenuItemChecked && !isValueSet && !wasMenuItemChecked) {
onSelect === null || onSelect === void 0 ? void 0 : onSelect();
}
if (!isMenuItemChecked && wasMenuItemChecked) {
onDeselect === null || onDeselect === void 0 ? void 0 : onDeselect();
}
}, [hasMatchingPanel, isMenuItemChecked, isRegistered, isResetting, isValueSet, wasMenuItemChecked, onSelect, onDeselect]); // The item is shown if it is a default control regardless of whether it
// has a value. Optional items are shown when they are checked or have
// a value.
const isShown = isShownByDefault ? (menuItems === null || menuItems === void 0 ? void 0 : (_menuItems$menuGroup3 = menuItems[menuGroup]) === null || _menuItems$menuGroup3 === void 0 ? void 0 : _menuItems$menuGroup3[label]) !== undefined : isMenuItemChecked;
const cx = useCx();
const classes = (0,external_wp_element_namespaceObject.useMemo)(() => {
const placeholderStyle = shouldRenderPlaceholder && !isShown && ToolsPanelItemPlaceholder;
const firstItemStyle = firstDisplayedItem === label && __experimentalFirstVisibleItemClass;
const lastItemStyle = lastDisplayedItem === label && __experimentalLastVisibleItemClass;
return cx(ToolsPanelItem, placeholderStyle, className, firstItemStyle, lastItemStyle);
}, [isShown, shouldRenderPlaceholder, className, cx, firstDisplayedItem, lastDisplayedItem, __experimentalFirstVisibleItemClass, __experimentalLastVisibleItemClass, label]);
return { ...otherProps,
isShown,
shouldRenderPlaceholder,
className: classes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tools-panel/tools-panel-item/component.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
// This wraps controls to be conditionally displayed within a tools panel. It
// prevents props being applied to HTML elements that would make them invalid.
const component_ToolsPanelItem = (props, forwardedRef) => {
const {
children,
isShown,
shouldRenderPlaceholder,
...toolsPanelItemProps
} = useToolsPanelItem(props);
if (!isShown) {
return shouldRenderPlaceholder ? (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({}, toolsPanelItemProps, {
ref: forwardedRef
})) : null;
}
return (0,external_wp_element_namespaceObject.createElement)(component, extends_extends({}, toolsPanelItemProps, {
ref: forwardedRef
}), children);
};
const ConnectedToolsPanelItem = contextConnect(component_ToolsPanelItem, 'ToolsPanelItem');
/* harmony default export */ var tools_panel_item_component = (ConnectedToolsPanelItem);
;// CONCATENATED MODULE: external ["wp","keycodes"]
var external_wp_keycodes_namespaceObject = window["wp"]["keycodes"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tree-grid/roving-tab-index-context.js
/**
* WordPress dependencies
*/
const RovingTabIndexContext = (0,external_wp_element_namespaceObject.createContext)();
const useRovingTabIndexContext = () => (0,external_wp_element_namespaceObject.useContext)(RovingTabIndexContext);
const RovingTabIndexProvider = RovingTabIndexContext.Provider;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tree-grid/roving-tab-index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Provider for adding roving tab index behaviors to tree grid structures.
*
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/components/src/tree-grid/README.md
*
* @param {Object} props Component props.
* @param {WPElement} props.children Children to be rendered
*/
function RovingTabIndex(_ref) {
let {
children
} = _ref;
const [lastFocusedElement, setLastFocusedElement] = (0,external_wp_element_namespaceObject.useState)(); // Use `useMemo` to avoid creation of a new object for the providerValue
// on every render. Only create a new object when the `lastFocusedElement`
// value changes.
const providerValue = (0,external_wp_element_namespaceObject.useMemo)(() => ({
lastFocusedElement,
setLastFocusedElement
}), [lastFocusedElement]);
return (0,external_wp_element_namespaceObject.createElement)(RovingTabIndexProvider, {
value: providerValue
}, children);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tree-grid/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Return focusables in a row element, excluding those from other branches
* nested within the row.
*
* @param {Element} rowElement The DOM element representing the row.
*
* @return {Array | undefined} The array of focusables in the row.
*/
function getRowFocusables(rowElement) {
const focusablesInRow = external_wp_dom_namespaceObject.focus.focusable.find(rowElement, {
sequential: true
});
if (!focusablesInRow || !focusablesInRow.length) {
return;
}
return focusablesInRow.filter(focusable => {
return focusable.closest('[role="row"]') === rowElement;
});
}
/**
* Renders both a table and tbody element, used to create a tree hierarchy.
*
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/components/src/tree-grid/README.md
* @param {Object} props Component props.
* @param {WPElement} props.children Children to be rendered.
* @param {Function} props.onExpandRow Callback to fire when row is expanded.
* @param {Function} props.onCollapseRow Callback to fire when row is collapsed.
* @param {Function} props.onFocusRow Callback to fire when moving focus to a different row.
* @param {string} props.applicationAriaLabel Label to use for the application role.
* @param {Object} ref A ref to the underlying DOM table element.
*/
function TreeGrid(_ref, ref) {
let {
children,
onExpandRow = () => {},
onCollapseRow = () => {},
onFocusRow = () => {},
applicationAriaLabel,
...props
} = _ref;
const onKeyDown = (0,external_wp_element_namespaceObject.useCallback)(event => {
const {
keyCode,
metaKey,
ctrlKey,
altKey
} = event; // The shift key is intentionally absent from the following list,
// to enable shift + up/down to select items from the list.
const hasModifierKeyPressed = metaKey || ctrlKey || altKey;
if (hasModifierKeyPressed || ![external_wp_keycodes_namespaceObject.UP, external_wp_keycodes_namespaceObject.DOWN, external_wp_keycodes_namespaceObject.LEFT, external_wp_keycodes_namespaceObject.RIGHT, external_wp_keycodes_namespaceObject.HOME, external_wp_keycodes_namespaceObject.END].includes(keyCode)) {
return;
} // The event will be handled, stop propagation.
event.stopPropagation();
const {
activeElement
} = document;
const {
currentTarget: treeGridElement
} = event;
if (!treeGridElement.contains(activeElement)) {
return;
} // Calculate the columnIndex of the active element.
const activeRow = activeElement.closest('[role="row"]');
const focusablesInRow = getRowFocusables(activeRow);
const currentColumnIndex = focusablesInRow.indexOf(activeElement);
const canExpandCollapse = 0 === currentColumnIndex;
const cannotFocusNextColumn = canExpandCollapse && activeRow.getAttribute('aria-expanded') === 'false' && keyCode === external_wp_keycodes_namespaceObject.RIGHT;
if ([external_wp_keycodes_namespaceObject.LEFT, external_wp_keycodes_namespaceObject.RIGHT].includes(keyCode)) {
// Calculate to the next element.
let nextIndex;
if (keyCode === external_wp_keycodes_namespaceObject.LEFT) {
nextIndex = Math.max(0, currentColumnIndex - 1);
} else {
nextIndex = Math.min(currentColumnIndex + 1, focusablesInRow.length - 1);
} // Focus is at the left most column.
if (canExpandCollapse) {
if (keyCode === external_wp_keycodes_namespaceObject.LEFT) {
var _activeRow$getAttribu, _getRowFocusables, _getRowFocusables$;
// Left:
// If a row is focused, and it is expanded, collapses the current row.
if (activeRow.getAttribute('aria-expanded') === 'true') {
onCollapseRow(activeRow);
event.preventDefault();
return;
} // If a row is focused, and it is collapsed, moves to the parent row (if there is one).
const level = Math.max(parseInt((_activeRow$getAttribu = activeRow === null || activeRow === void 0 ? void 0 : activeRow.getAttribute('aria-level')) !== null && _activeRow$getAttribu !== void 0 ? _activeRow$getAttribu : 1, 10) - 1, 1);
const rows = Array.from(treeGridElement.querySelectorAll('[role="row"]'));
let parentRow = activeRow;
const currentRowIndex = rows.indexOf(activeRow);
for (let i = currentRowIndex; i >= 0; i--) {
if (parseInt(rows[i].getAttribute('aria-level'), 10) === level) {
parentRow = rows[i];
break;
}
}
(_getRowFocusables = getRowFocusables(parentRow)) === null || _getRowFocusables === void 0 ? void 0 : (_getRowFocusables$ = _getRowFocusables[0]) === null || _getRowFocusables$ === void 0 ? void 0 : _getRowFocusables$.focus();
}
if (keyCode === external_wp_keycodes_namespaceObject.RIGHT) {
// Right:
// If a row is focused, and it is collapsed, expands the current row.
if (activeRow.getAttribute('aria-expanded') === 'false') {
onExpandRow(activeRow);
event.preventDefault();
return;
} // If a row is focused, and it is expanded, focuses the next cell in the row.
const focusableItems = getRowFocusables(activeRow);
if (focusableItems.length > 0) {
var _focusableItems$nextI;
(_focusableItems$nextI = focusableItems[nextIndex]) === null || _focusableItems$nextI === void 0 ? void 0 : _focusableItems$nextI.focus();
}
} // Prevent key use for anything else. For example, Voiceover
// will start reading text on continued use of left/right arrow
// keys.
event.preventDefault();
return;
} // Focus the next element. If at most left column and row is collapsed, moving right is not allowed as this will expand. However, if row is collapsed, moving left is allowed.
if (cannotFocusNextColumn) {
return;
}
focusablesInRow[nextIndex].focus(); // Prevent key use for anything else. This ensures Voiceover
// doesn't try to handle key navigation.
event.preventDefault();
} else if ([external_wp_keycodes_namespaceObject.UP, external_wp_keycodes_namespaceObject.DOWN].includes(keyCode)) {
// Calculate the rowIndex of the next row.
const rows = Array.from(treeGridElement.querySelectorAll('[role="row"]'));
const currentRowIndex = rows.indexOf(activeRow);
let nextRowIndex;
if (keyCode === external_wp_keycodes_namespaceObject.UP) {
nextRowIndex = Math.max(0, currentRowIndex - 1);
} else {
nextRowIndex = Math.min(currentRowIndex + 1, rows.length - 1);
} // Focus is either at the top or bottom edge of the grid. Do nothing.
if (nextRowIndex === currentRowIndex) {
// Prevent key use for anything else. For example, Voiceover
// will start navigating horizontally when reaching the vertical
// bounds of a table.
event.preventDefault();
return;
} // Get the focusables in the next row.
const focusablesInNextRow = getRowFocusables(rows[nextRowIndex]); // If for some reason there are no focusables in the next row, do nothing.
if (!focusablesInNextRow || !focusablesInNextRow.length) {
// Prevent key use for anything else. For example, Voiceover
// will still focus text when using arrow keys, while this
// component should limit navigation to focusables.
event.preventDefault();
return;
} // Try to focus the element in the next row that's at a similar column to the activeElement.
const nextIndex = Math.min(currentColumnIndex, focusablesInNextRow.length - 1);
focusablesInNextRow[nextIndex].focus(); // Let consumers know the row that was originally focused,
// and the row that is now in focus.
onFocusRow(event, activeRow, rows[nextRowIndex]); // Prevent key use for anything else. This ensures Voiceover
// doesn't try to handle key navigation.
event.preventDefault();
} else if ([external_wp_keycodes_namespaceObject.HOME, external_wp_keycodes_namespaceObject.END].includes(keyCode)) {
// Calculate the rowIndex of the next row.
const rows = Array.from(treeGridElement.querySelectorAll('[role="row"]'));
const currentRowIndex = rows.indexOf(activeRow);
let nextRowIndex;
if (keyCode === external_wp_keycodes_namespaceObject.HOME) {
nextRowIndex = 0;
} else {
nextRowIndex = rows.length - 1;
} // Focus is either at the top or bottom edge of the grid. Do nothing.
if (nextRowIndex === currentRowIndex) {
// Prevent key use for anything else. For example, Voiceover
// will start navigating horizontally when reaching the vertical
// bounds of a table.
event.preventDefault();
return;
} // Get the focusables in the next row.
const focusablesInNextRow = getRowFocusables(rows[nextRowIndex]); // If for some reason there are no focusables in the next row, do nothing.
if (!focusablesInNextRow || !focusablesInNextRow.length) {
// Prevent key use for anything else. For example, Voiceover
// will still focus text when using arrow keys, while this
// component should limit navigation to focusables.
event.preventDefault();
return;
} // Try to focus the element in the next row that's at a similar column to the activeElement.
const nextIndex = Math.min(currentColumnIndex, focusablesInNextRow.length - 1);
focusablesInNextRow[nextIndex].focus(); // Let consumers know the row that was originally focused,
// and the row that is now in focus.
onFocusRow(event, activeRow, rows[nextRowIndex]); // Prevent key use for anything else. This ensures Voiceover
// doesn't try to handle key navigation.
event.preventDefault();
}
}, [onExpandRow, onCollapseRow, onFocusRow]);
/* Disable reason: A treegrid is implemented using a table element. */
/* eslint-disable jsx-a11y/no-noninteractive-element-to-interactive-role */
return (0,external_wp_element_namespaceObject.createElement)(RovingTabIndex, null, (0,external_wp_element_namespaceObject.createElement)("div", {
role: "application",
"aria-label": applicationAriaLabel
}, (0,external_wp_element_namespaceObject.createElement)("table", extends_extends({}, props, {
role: "treegrid",
onKeyDown: onKeyDown,
ref: ref
}), (0,external_wp_element_namespaceObject.createElement)("tbody", null, children))));
/* eslint-enable jsx-a11y/no-noninteractive-element-to-interactive-role */
}
/* harmony default export */ var tree_grid = ((0,external_wp_element_namespaceObject.forwardRef)(TreeGrid));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tree-grid/row.js
/**
* WordPress dependencies
*/
function TreeGridRow(_ref, ref) {
let {
children,
level,
positionInSet,
setSize,
isExpanded,
...props
} = _ref;
return (// Disable reason: Due to an error in the ARIA 1.1 specification, the
// aria-posinset and aria-setsize properties are not supported on row
// elements. This is being corrected in ARIA 1.2. Consequently, the
// linting rule fails when validating this markup.
//
// eslint-disable-next-line jsx-a11y/role-supports-aria-props
(0,external_wp_element_namespaceObject.createElement)("tr", extends_extends({}, props, {
ref: ref,
role: "row",
"aria-level": level,
"aria-posinset": positionInSet,
"aria-setsize": setSize,
"aria-expanded": isExpanded
}), children)
);
}
/* harmony default export */ var tree_grid_row = ((0,external_wp_element_namespaceObject.forwardRef)(TreeGridRow));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tree-grid/roving-tab-index-item.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/* harmony default export */ var roving_tab_index_item = ((0,external_wp_element_namespaceObject.forwardRef)(function RovingTabIndexItem(_ref, forwardedRef) {
let {
children,
as: Component,
...props
} = _ref;
const localRef = (0,external_wp_element_namespaceObject.useRef)();
const ref = forwardedRef || localRef;
const {
lastFocusedElement,
setLastFocusedElement
} = useRovingTabIndexContext();
let tabIndex;
if (lastFocusedElement) {
tabIndex = lastFocusedElement === ref.current ? 0 : -1;
}
const onFocus = event => setLastFocusedElement(event.target);
const allProps = {
ref,
tabIndex,
onFocus,
...props
};
if (typeof children === 'function') {
return children(allProps);
}
return (0,external_wp_element_namespaceObject.createElement)(Component, allProps, children);
}));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tree-grid/item.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/* harmony default export */ var tree_grid_item = ((0,external_wp_element_namespaceObject.forwardRef)(function TreeGridItem(_ref, ref) {
let {
children,
...props
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(roving_tab_index_item, extends_extends({
ref: ref
}, props), children);
}));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/tree-grid/cell.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/* harmony default export */ var cell = ((0,external_wp_element_namespaceObject.forwardRef)(function TreeGridCell(_ref, ref) {
let {
children,
withoutGridItem = false,
...props
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("td", extends_extends({}, props, {
role: "gridcell"
}), withoutGridItem ? children : (0,external_wp_element_namespaceObject.createElement)(tree_grid_item, {
ref: ref
}, children));
}));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/isolated-event-container/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
function stopPropagation(event) {
event.stopPropagation();
}
const IsolatedEventContainer = (0,external_wp_element_namespaceObject.forwardRef)((props, ref) => {
external_wp_deprecated_default()('wp.components.IsolatedEventContainer', {
since: '5.7'
}); // Disable reason: this stops certain events from propagating outside of the component.
// - onMouseDown is disabled as this can cause interactions with other DOM elements.
/* eslint-disable jsx-a11y/no-static-element-interactions */
return (0,external_wp_element_namespaceObject.createElement)("div", extends_extends({}, props, {
ref: ref,
onMouseDown: stopPropagation
}));
/* eslint-enable jsx-a11y/no-static-element-interactions */
});
/* harmony default export */ var isolated_event_container = (IsolatedEventContainer);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/slot-fill/bubbles-virtually/use-slot-fills.js
// @ts-nocheck
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useSlotFills(name) {
const registry = (0,external_wp_element_namespaceObject.useContext)(slot_fill_context);
const fills = useSnapshot(registry.fills, {
sync: true
}); // The important bit here is that this call ensures that the hook
// only causes a re-render if the "fills" of a given slot name
// change change, not any fills.
return fills.get(name);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/z-stack/styles.js
function z_stack_styles_EMOTION_STRINGIFIED_CSS_ERROR_() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const ZStackView = createStyled("div", true ? {
target: "ebn2ljm1"
} : 0)( true ? {
name: "5ob2ly",
styles: "display:flex;position:relative"
} : 0);
const ZStackChildView = createStyled("div", true ? {
target: "ebn2ljm0"
} : 0)(_ref => {
let {
isLayered,
offsetAmount
} = _ref;
return isLayered ? /*#__PURE__*/emotion_react_browser_esm_css(rtl({
marginLeft: offsetAmount
})(), true ? "" : 0, true ? "" : 0) : /*#__PURE__*/emotion_react_browser_esm_css(rtl({
right: offsetAmount * -1
})(), true ? "" : 0, true ? "" : 0);
}, " ", _ref2 => {
let {
isLayered
} = _ref2;
return isLayered ? positionAbsolute : positionRelative;
}, " ", _ref3 => {
let {
zIndex
} = _ref3;
return /*#__PURE__*/emotion_react_browser_esm_css({
zIndex
}, true ? "" : 0, true ? "" : 0);
}, ";" + ( true ? "" : 0));
const positionAbsolute = true ? {
name: "a4hmbt",
styles: "position:absolute"
} : 0;
const positionRelative = true ? {
name: "bjn8wh",
styles: "position:relative"
} : 0;
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/z-stack/component.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnconnectedZStack(props, forwardedRef) {
const {
children,
className,
isLayered = true,
isReversed = false,
offset = 0,
...otherProps
} = useContextSystem(props, 'ZStack');
const validChildren = getValidChildren(children);
const childrenLastIndex = validChildren.length - 1;
const clonedChildren = validChildren.map((child, index) => {
const zIndex = isReversed ? childrenLastIndex - index : index;
const offsetAmount = offset * index;
const key = (0,external_wp_element_namespaceObject.isValidElement)(child) ? child.key : index;
return (0,external_wp_element_namespaceObject.createElement)(ZStackChildView, {
isLayered: isLayered,
offsetAmount: offsetAmount,
zIndex: zIndex,
key: key
}, child);
});
return (0,external_wp_element_namespaceObject.createElement)(ZStackView, extends_extends({}, otherProps, {
className: className,
ref: forwardedRef
}), clonedChildren);
}
/**
* `ZStack` allows you to stack things along the Z-axis.
*
* ```jsx
* import { __experimentalZStack as ZStack } from '@wordpress/components';
*
* function Example() {
* return (
* <ZStack offset={ 20 } isLayered>
* <ExampleImage />
* <ExampleImage />
* <ExampleImage />
* </ZStack>
* );
* }
* ```
*/
const ZStack = contextConnect(UnconnectedZStack, 'ZStack');
/* harmony default export */ var z_stack_component = (ZStack);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/higher-order/navigate-regions/index.js
/**
* WordPress dependencies
*/
const defaultShortcuts = {
previous: [{
modifier: 'ctrlShift',
character: '`'
}, {
modifier: 'ctrlShift',
character: '~'
}, {
modifier: 'access',
character: 'p'
}],
next: [{
modifier: 'ctrl',
character: '`'
}, {
modifier: 'access',
character: 'n'
}]
};
function useNavigateRegions() {
let shortcuts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultShortcuts;
const ref = (0,external_wp_element_namespaceObject.useRef)();
const [isFocusingRegions, setIsFocusingRegions] = (0,external_wp_element_namespaceObject.useState)(false);
function focusRegion(offset) {
const regions = Array.from(ref.current.querySelectorAll('[role="region"][tabindex="-1"]'));
if (!regions.length) {
return;
}
let nextRegion = regions[0]; // Based off the current element, use closest to determine the wrapping region since this operates up the DOM. Also, match tabindex to avoid edge cases with regions we do not want.
const selectedIndex = regions.indexOf(ref.current.ownerDocument.activeElement.closest('[role="region"][tabindex="-1"]'));
if (selectedIndex !== -1) {
let nextIndex = selectedIndex + offset;
nextIndex = nextIndex === -1 ? regions.length - 1 : nextIndex;
nextIndex = nextIndex === regions.length ? 0 : nextIndex;
nextRegion = regions[nextIndex];
}
nextRegion.focus();
setIsFocusingRegions(true);
}
const clickRef = (0,external_wp_compose_namespaceObject.useRefEffect)(element => {
function onClick() {
setIsFocusingRegions(false);
}
element.addEventListener('click', onClick);
return () => {
element.removeEventListener('click', onClick);
};
}, [setIsFocusingRegions]);
return {
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([ref, clickRef]),
className: isFocusingRegions ? 'is-focusing-regions' : '',
onKeyDown(event) {
if (shortcuts.previous.some(_ref => {
let {
modifier,
character
} = _ref;
return external_wp_keycodes_namespaceObject.isKeyboardEvent[modifier](event, character);
})) {
focusRegion(-1);
} else if (shortcuts.next.some(_ref2 => {
let {
modifier,
character
} = _ref2;
return external_wp_keycodes_namespaceObject.isKeyboardEvent[modifier](event, character);
})) {
focusRegion(1);
}
}
};
}
/* harmony default export */ var navigate_regions = ((0,external_wp_compose_namespaceObject.createHigherOrderComponent)(Component => _ref3 => {
let {
shortcuts,
...props
} = _ref3;
return (0,external_wp_element_namespaceObject.createElement)("div", useNavigateRegions(shortcuts), (0,external_wp_element_namespaceObject.createElement)(Component, props));
}, 'navigateRegions'));
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/higher-order/with-constrained-tabbing/index.js
/**
* WordPress dependencies
*/
const withConstrainedTabbing = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(WrappedComponent => function ComponentWithConstrainedTabbing(props) {
const ref = (0,external_wp_compose_namespaceObject.useConstrainedTabbing)();
return (0,external_wp_element_namespaceObject.createElement)("div", {
ref: ref,
tabIndex: -1
}, (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, props));
}, 'withConstrainedTabbing');
/* harmony default export */ var with_constrained_tabbing = (withConstrainedTabbing);
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/higher-order/with-fallback-styles/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/* harmony default export */ var with_fallback_styles = (mapNodeToProps => (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(WrappedComponent => {
return class extends external_wp_element_namespaceObject.Component {
constructor() {
super(...arguments);
this.nodeRef = this.props.node;
this.state = {
fallbackStyles: undefined,
grabStylesCompleted: false
};
this.bindRef = this.bindRef.bind(this);
}
bindRef(node) {
if (!node) {
return;
}
this.nodeRef = node;
}
componentDidMount() {
this.grabFallbackStyles();
}
componentDidUpdate() {
this.grabFallbackStyles();
}
grabFallbackStyles() {
const {
grabStylesCompleted,
fallbackStyles
} = this.state;
if (this.nodeRef && !grabStylesCompleted) {
const newFallbackStyles = mapNodeToProps(this.nodeRef, this.props);
if (!es6_default()(newFallbackStyles, fallbackStyles)) {
this.setState({
fallbackStyles: newFallbackStyles,
grabStylesCompleted: Object.values(newFallbackStyles).every(Boolean)
});
}
}
}
render() {
const wrappedComponent = (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, extends_extends({}, this.props, this.state.fallbackStyles));
return this.props.node ? wrappedComponent : (0,external_wp_element_namespaceObject.createElement)("div", {
ref: this.bindRef
}, " ", wrappedComponent, " ");
}
};
}, 'withFallbackStyles'));
;// CONCATENATED MODULE: external ["wp","hooks"]
var external_wp_hooks_namespaceObject = window["wp"]["hooks"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/higher-order/with-filters/index.js
/**
* WordPress dependencies
*/
const ANIMATION_FRAME_PERIOD = 16;
/**
* Creates a higher-order component which adds filtering capability to the
* wrapped component. Filters get applied when the original component is about
* to be mounted. When a filter is added or removed that matches the hook name,
* the wrapped component re-renders.
*
* @param {string} hookName Hook name exposed to be used by filters.
*
* @return {Function} Higher-order component factory.
*/
function withFilters(hookName) {
return (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(OriginalComponent => {
const namespace = 'core/with-filters/' + hookName;
/**
* The component definition with current filters applied. Each instance
* reuse this shared reference as an optimization to avoid excessive
* calls to `applyFilters` when many instances exist.
*
* @type {?Component}
*/
let FilteredComponent;
/**
* Initializes the FilteredComponent variable once, if not already
* assigned. Subsequent calls are effectively a noop.
*/
function ensureFilteredComponent() {
if (FilteredComponent === undefined) {
FilteredComponent = (0,external_wp_hooks_namespaceObject.applyFilters)(hookName, OriginalComponent);
}
}
class FilteredComponentRenderer extends external_wp_element_namespaceObject.Component {
constructor() {
super(...arguments);
ensureFilteredComponent();
}
componentDidMount() {
FilteredComponentRenderer.instances.push(this); // If there were previously no mounted instances for components
// filtered on this hook, add the hook handler.
if (FilteredComponentRenderer.instances.length === 1) {
(0,external_wp_hooks_namespaceObject.addAction)('hookRemoved', namespace, onHooksUpdated);
(0,external_wp_hooks_namespaceObject.addAction)('hookAdded', namespace, onHooksUpdated);
}
}
componentWillUnmount() {
FilteredComponentRenderer.instances = FilteredComponentRenderer.instances.filter(instance => instance !== this); // If this was the last of the mounted components filtered on
// this hook, remove the hook handler.
if (FilteredComponentRenderer.instances.length === 0) {
(0,external_wp_hooks_namespaceObject.removeAction)('hookRemoved', namespace);
(0,external_wp_hooks_namespaceObject.removeAction)('hookAdded', namespace);
}
}
render() {
return (0,external_wp_element_namespaceObject.createElement)(FilteredComponent, this.props);
}
}
FilteredComponentRenderer.instances = [];
/**
* Updates the FilteredComponent definition, forcing a render for each
* mounted instance. This occurs a maximum of once per animation frame.
*/
const throttledForceUpdate = (0,external_wp_compose_namespaceObject.debounce)(() => {
// Recreate the filtered component, only after delay so that it's
// computed once, even if many filters added.
FilteredComponent = (0,external_wp_hooks_namespaceObject.applyFilters)(hookName, OriginalComponent); // Force each instance to render.
FilteredComponentRenderer.instances.forEach(instance => {
instance.forceUpdate();
});
}, ANIMATION_FRAME_PERIOD);
/**
* When a filter is added or removed for the matching hook name, each
* mounted instance should re-render with the new filters having been
* applied to the original component.
*
* @param {string} updatedHookName Name of the hook that was updated.
*/
function onHooksUpdated(updatedHookName) {
if (updatedHookName === hookName) {
throttledForceUpdate();
}
}
return FilteredComponentRenderer;
}, 'withFilters');
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/higher-order/with-focus-return/index.js
/**
* WordPress dependencies
*/
/**
* Returns true if the given object is component-like. An object is component-
* like if it is an instance of wp.element.Component, or is a function.
*
* @param {*} object Object to test.
*
* @return {boolean} Whether object is component-like.
*/
function isComponentLike(object) {
return object instanceof external_wp_element_namespaceObject.Component || typeof object === 'function';
}
/**
* Higher Order Component used to be used to wrap disposable elements like
* sidebars, modals, dropdowns. When mounting the wrapped component, we track a
* reference to the current active element so we know where to restore focus
* when the component is unmounted.
*
* @param {(WPComponent|Object)} options The component to be enhanced with
* focus return behavior, or an object
* describing the component and the
* focus return characteristics.
*
* @return {Function} Higher Order Component with the focus restauration behaviour.
*/
/* harmony default export */ var with_focus_return = ((0,external_wp_compose_namespaceObject.createHigherOrderComponent)(options => {
const HoC = function () {
let {
onFocusReturn
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return WrappedComponent => {
const WithFocusReturn = props => {
const ref = (0,external_wp_compose_namespaceObject.useFocusReturn)(onFocusReturn);
return (0,external_wp_element_namespaceObject.createElement)("div", {
ref: ref
}, (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, props));
};
return WithFocusReturn;
};
};
if (isComponentLike(options)) {
const WrappedComponent = options;
return HoC()(WrappedComponent);
}
return HoC(options);
}, 'withFocusReturn'));
const with_focus_return_Provider = _ref => {
let {
children
} = _ref;
external_wp_deprecated_default()('wp.components.FocusReturnProvider component', {
since: '5.7',
hint: 'This provider is not used anymore. You can just remove it from your codebase'
});
return children;
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/higher-order/with-notices/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Override the default edit UI to include notices if supported.
*
* @param {WPComponent} OriginalComponent Original component.
*
* @return {WPComponent} Wrapped component.
*/
/* harmony default export */ var with_notices = ((0,external_wp_compose_namespaceObject.createHigherOrderComponent)(OriginalComponent => {
function Component(props, ref) {
const [noticeList, setNoticeList] = (0,external_wp_element_namespaceObject.useState)([]);
const noticeOperations = (0,external_wp_element_namespaceObject.useMemo)(() => {
/**
* Function passed down as a prop that adds a new notice.
*
* @param {Object} notice Notice to add.
*/
const createNotice = notice => {
const noticeToAdd = notice.id ? notice : { ...notice,
id: esm_browser_v4()
};
setNoticeList(current => [...current, noticeToAdd]);
};
return {
createNotice,
/**
* Function passed as a prop that adds a new error notice.
*
* @param {string} msg Error message of the notice.
*/
createErrorNotice: msg => {
createNotice({
status: 'error',
content: msg
});
},
/**
* Removes a notice by id.
*
* @param {string} id Id of the notice to remove.
*/
removeNotice: id => {
setNoticeList(current => current.filter(notice => notice.id !== id));
},
/**
* Removes all notices
*/
removeAllNotices: () => {
setNoticeList([]);
}
};
}, []);
const propsOut = { ...props,
noticeList,
noticeOperations,
noticeUI: noticeList.length > 0 && (0,external_wp_element_namespaceObject.createElement)(list, {
className: "components-with-notices-ui",
notices: noticeList,
onRemove: noticeOperations.removeNotice
})
};
return isForwardRef ? (0,external_wp_element_namespaceObject.createElement)(OriginalComponent, extends_extends({}, propsOut, {
ref: ref
})) : (0,external_wp_element_namespaceObject.createElement)(OriginalComponent, propsOut);
}
let isForwardRef;
const {
render
} = OriginalComponent; // Returns a forwardRef if OriginalComponent appears to be a forwardRef.
if (typeof render === 'function') {
isForwardRef = true;
return (0,external_wp_element_namespaceObject.forwardRef)(Component);
}
return Component;
}));
;// CONCATENATED MODULE: external ["wp","privateApis"]
var external_wp_privateApis_namespaceObject = window["wp"]["privateApis"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/private-apis.js
/**
* WordPress dependencies
*/
/**
* Internal 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/components');
const privateApis = {};
lock(privateApis, {
CustomSelectControl: CustomSelectControl,
__experimentalPopoverLegacyPositionToPlacement: positionToPlacement
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/components/build-module/index.js
// Primitives.
// Components.
// Higher-Order Components.
// Private APIs.
}();
(window.wp = window.wp || {}).components = __webpack_exports__;
/******/ })()
; data-controls.js 0000666 00000015470 15123355174 0007675 0 ustar 00 /******/ (function() { // webpackBootstrap
/******/ "use strict";
/******/ // The require scope
/******/ var __webpack_require__ = {};
/******/
/************************************************************************/
/******/ /* 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__ = {};
// ESM COMPAT FLAG
__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; }
});
;// CONCATENATED MODULE: external ["wp","apiFetch"]
var external_wp_apiFetch_namespaceObject = window["wp"]["apiFetch"];
var external_wp_apiFetch_default = /*#__PURE__*/__webpack_require__.n(external_wp_apiFetch_namespaceObject);
;// CONCATENATED MODULE: external ["wp","data"]
var external_wp_data_namespaceObject = window["wp"]["data"];
;// CONCATENATED MODULE: external ["wp","deprecated"]
var external_wp_deprecated_namespaceObject = window["wp"]["deprecated"];
var external_wp_deprecated_default = /*#__PURE__*/__webpack_require__.n(external_wp_deprecated_namespaceObject);
;// CONCATENATED MODULE: ./node_modules/@wordpress/data-controls/build-module/index.js
/**
* WordPress dependencies
*/
/**
* Dispatches a control action for triggering an api fetch call.
*
* @param {Object} request Arguments for the fetch request.
*
* @example
* ```js
* import { apiFetch } from '@wordpress/data-controls';
*
* // Action generator using apiFetch
* export function* myAction() {
* const path = '/v2/my-api/items';
* const items = yield apiFetch( { path } );
* // do something with the items.
* }
* ```
*
* @return {Object} The control descriptor.
*/
function apiFetch(request) {
return {
type: 'API_FETCH',
request
};
}
/**
* Control for resolving a selector in a registered data store.
* Alias for the `resolveSelect` built-in control in the `@wordpress/data` package.
*
* @param {Array} args Arguments passed without change to the `@wordpress/data` control.
*/
function build_module_select() {
external_wp_deprecated_default()('`select` control in `@wordpress/data-controls`', {
since: '5.7',
alternative: 'built-in `resolveSelect` control in `@wordpress/data`'
});
return external_wp_data_namespaceObject.controls.resolveSelect(...arguments);
}
/**
* Control for calling a selector in a registered data store.
* Alias for the `select` built-in control in the `@wordpress/data` package.
*
* @param {Array} args Arguments passed without change to the `@wordpress/data` control.
*/
function syncSelect() {
external_wp_deprecated_default()('`syncSelect` control in `@wordpress/data-controls`', {
since: '5.7',
alternative: 'built-in `select` control in `@wordpress/data`'
});
return external_wp_data_namespaceObject.controls.select(...arguments);
}
/**
* Control for dispatching an action in a registered data store.
* Alias for the `dispatch` control in the `@wordpress/data` package.
*
* @param {Array} args Arguments passed without change to the `@wordpress/data` control.
*/
function dispatch() {
external_wp_deprecated_default()('`dispatch` control in `@wordpress/data-controls`', {
since: '5.7',
alternative: 'built-in `dispatch` control in `@wordpress/data`'
});
return external_wp_data_namespaceObject.controls.dispatch(...arguments);
}
/**
* Dispatches a control action for awaiting on a promise to be resolved.
*
* @param {Object} promise Promise to wait for.
*
* @example
* ```js
* import { __unstableAwaitPromise } from '@wordpress/data-controls';
*
* // Action generator using apiFetch
* export function* myAction() {
* const promise = getItemsAsync();
* const items = yield __unstableAwaitPromise( promise );
* // do something with the items.
* }
* ```
*
* @return {Object} The control descriptor.
*/
const __unstableAwaitPromise = function (promise) {
return {
type: 'AWAIT_PROMISE',
promise
};
};
/**
* The default export is what you use to register the controls with your custom
* store.
*
* @example
* ```js
* // WordPress dependencies
* import { controls } from '@wordpress/data-controls';
* import { registerStore } from '@wordpress/data';
*
* // Internal dependencies
* import reducer from './reducer';
* import * as selectors from './selectors';
* import * as actions from './actions';
* import * as resolvers from './resolvers';
*
* registerStore( 'my-custom-store', {
* reducer,
* controls,
* actions,
* selectors,
* resolvers,
* } );
* ```
* @return {Object} An object for registering the default controls with the
* store.
*/
const controls = {
AWAIT_PROMISE: _ref => {
let {
promise
} = _ref;
return promise;
},
API_FETCH(_ref2) {
let {
request
} = _ref2;
return external_wp_apiFetch_default()(request);
}
};
(window.wp = window.wp || {}).dataControls = __webpack_exports__;
/******/ })()
; plugins.js 0000666 00000047342 15123355174 0006607 0 ustar 00 /******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 9756:
/***/ (function(module) {
/**
* Memize options object.
*
* @typedef MemizeOptions
*
* @property {number} [maxSize] Maximum size of the cache.
*/
/**
* Internal cache entry.
*
* @typedef MemizeCacheNode
*
* @property {?MemizeCacheNode|undefined} [prev] Previous node.
* @property {?MemizeCacheNode|undefined} [next] Next node.
* @property {Array<*>} args Function arguments for cache
* entry.
* @property {*} val Function result.
*/
/**
* Properties of the enhanced function for controlling cache.
*
* @typedef MemizeMemoizedFunction
*
* @property {()=>void} clear Clear the cache.
*/
/**
* Accepts a function to be memoized, and returns a new memoized function, with
* optional options.
*
* @template {Function} F
*
* @param {F} fn Function to memoize.
* @param {MemizeOptions} [options] Options object.
*
* @return {F & MemizeMemoizedFunction} Memoized function.
*/
function memize( fn, options ) {
var size = 0;
/** @type {?MemizeCacheNode|undefined} */
var head;
/** @type {?MemizeCacheNode|undefined} */
var tail;
options = options || {};
function memoized( /* ...args */ ) {
var node = head,
len = arguments.length,
args, i;
searchCache: while ( node ) {
// Perform a shallow equality test to confirm that whether the node
// under test is a candidate for the arguments passed. Two arrays
// are shallowly equal if their length matches and each entry is
// strictly equal between the two sets. Avoid abstracting to a
// function which could incur an arguments leaking deoptimization.
// Check whether node arguments match arguments length
if ( node.args.length !== arguments.length ) {
node = node.next;
continue;
}
// Check whether node arguments match arguments values
for ( i = 0; i < len; i++ ) {
if ( node.args[ i ] !== arguments[ i ] ) {
node = node.next;
continue searchCache;
}
}
// At this point we can assume we've found a match
// Surface matched node to head if not already
if ( node !== head ) {
// As tail, shift to previous. Must only shift if not also
// head, since if both head and tail, there is no previous.
if ( node === tail ) {
tail = node.prev;
}
// Adjust siblings to point to each other. If node was tail,
// this also handles new tail's empty `next` assignment.
/** @type {MemizeCacheNode} */ ( node.prev ).next = node.next;
if ( node.next ) {
node.next.prev = node.prev;
}
node.next = head;
node.prev = null;
/** @type {MemizeCacheNode} */ ( head ).prev = node;
head = node;
}
// Return immediately
return node.val;
}
// No cached value found. Continue to insertion phase:
// Create a copy of arguments (avoid leaking deoptimization)
args = new Array( len );
for ( i = 0; i < len; i++ ) {
args[ i ] = arguments[ i ];
}
node = {
args: args,
// Generate the result from original function
val: fn.apply( null, args ),
};
// Don't need to check whether node is already head, since it would
// have been returned above already if it was
// Shift existing head down list
if ( head ) {
head.prev = node;
node.next = head;
} else {
// If no head, follows that there's no tail (at initial or reset)
tail = node;
}
// Trim tail if we're reached max size and are pending cache insertion
if ( size === /** @type {MemizeOptions} */ ( options ).maxSize ) {
tail = /** @type {MemizeCacheNode} */ ( tail ).prev;
/** @type {MemizeCacheNode} */ ( tail ).next = null;
} else {
size++;
}
head = node;
return node.val;
}
memoized.clear = function() {
head = null;
tail = null;
size = 0;
};
if ( false ) {}
// Ignore reason: There's not a clear solution to create an intersection of
// the function with additional properties, where the goal is to retain the
// function signature of the incoming argument and add control properties
// on the return value.
// @ts-ignore
return memoized;
}
module.exports = memize;
/***/ })
/******/ });
/************************************************************************/
/******/ // 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 in strict mode.
!function() {
"use strict";
// ESM COMPAT FLAG
__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; }
});
;// CONCATENATED MODULE: external ["wp","element"]
var external_wp_element_namespaceObject = window["wp"]["element"];
// EXTERNAL MODULE: ./node_modules/memize/index.js
var memize = __webpack_require__(9756);
var memize_default = /*#__PURE__*/__webpack_require__.n(memize);
;// CONCATENATED MODULE: external ["wp","hooks"]
var external_wp_hooks_namespaceObject = window["wp"]["hooks"];
;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/extends.js
function _extends() {
return _extends = Object.assign ? Object.assign.bind() : function (n) {
for (var e = 1; e < arguments.length; e++) {
var t = arguments[e];
for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
}
return n;
}, _extends.apply(null, arguments);
}
;// CONCATENATED MODULE: external ["wp","compose"]
var external_wp_compose_namespaceObject = window["wp"]["compose"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/plugins/build-module/components/plugin-context/index.js
/**
* WordPress dependencies
*/
const {
Consumer,
Provider
} = (0,external_wp_element_namespaceObject.createContext)({
name: null,
icon: null
});
/**
* A Higher Order Component used to inject Plugin context to the
* wrapped component.
*
* @param {Function} mapContextToProps Function called on every context change,
* expected to return object of props to
* merge with the component's own props.
*
* @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, _extends({}, props, mapContextToProps(context, props))));
}, 'withPluginContext');
;// CONCATENATED MODULE: ./node_modules/@wordpress/plugins/build-module/components/plugin-error-boundary/index.js
/**
* WordPress dependencies
*/
class PluginErrorBoundary extends external_wp_element_namespaceObject.Component {
constructor(props) {
super(props);
this.state = {
hasError: false
};
}
static getDerivedStateFromError() {
return {
hasError: true
};
}
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
*/
const plugins = (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: "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"
}));
/* harmony default export */ var library_plugins = (plugins);
;// CONCATENATED MODULE: ./node_modules/@wordpress/plugins/build-module/api/index.js
/* eslint no-console: [ 'error', { allow: [ 'error' ] } ] */
/**
* WordPress dependencies
*/
/**
* Defined behavior of a plugin type.
*
* @typedef {Object} WPPlugin
*
* @property {string} name A string identifying the plugin. Must be
* unique across all registered plugins.
* @property {string|WPElement|Function} [icon] An icon to be shown in the UI. It can
* be a slug of the Dashicon, or an element
* (or function returning an element) if you
* choose to render your own SVG.
* @property {Function} render A component containing the UI elements
* to be rendered.
* @property {string} [scope] The optional scope to be used when rendering inside
* a plugin area. No scope by default.
*/
/**
* Plugin definitions keyed by plugin name.
*
* @type {Object.<string,WPPlugin>}
*/
const api_plugins = {};
/**
* Registers a plugin to the editor.
*
* @param {string} name A string identifying the plugin.Must be
* unique across all registered plugins.
* @param {Omit<WPPlugin, 'name'>} settings The settings for this plugin.
*
* @example
* ```js
* // Using ES5 syntax
* var el = wp.element.createElement;
* var Fragment = wp.element.Fragment;
* var PluginSidebar = wp.editPost.PluginSidebar;
* var PluginSidebarMoreMenuItem = wp.editPost.PluginSidebarMoreMenuItem;
* var registerPlugin = wp.plugins.registerPlugin;
* var moreIcon = wp.element.createElement( 'svg' ); //... svg element.
*
* function Component() {
* return el(
* Fragment,
* {},
* el(
* PluginSidebarMoreMenuItem,
* {
* target: 'sidebar-name',
* },
* 'My Sidebar'
* ),
* el(
* PluginSidebar,
* {
* name: 'sidebar-name',
* title: 'My Sidebar',
* },
* 'Content of the sidebar'
* )
* );
* }
* registerPlugin( 'plugin-name', {
* icon: moreIcon,
* render: Component,
* scope: 'my-page',
* } );
* ```
*
* @example
* ```js
* // Using ESNext syntax
* import { PluginSidebar, PluginSidebarMoreMenuItem } from '@wordpress/edit-post';
* import { registerPlugin } from '@wordpress/plugins';
* import { more } from '@wordpress/icons';
*
* const Component = () => (
* <>
* <PluginSidebarMoreMenuItem
* target="sidebar-name"
* >
* My Sidebar
* </PluginSidebarMoreMenuItem>
* <PluginSidebar
* name="sidebar-name"
* title="My Sidebar"
* >
* Content of the sidebar
* </PluginSidebar>
* </>
* );
*
* registerPlugin( 'plugin-name', {
* icon: more,
* render: Component,
* scope: 'my-page',
* } );
* ```
*
* @return {WPPlugin} 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,
...settings
};
(0,external_wp_hooks_namespaceObject.doAction)('plugins.pluginRegistered', settings, name);
return settings;
}
/**
* Unregisters a plugin by name.
*
* @param {string} name Plugin name.
*
* @example
* ```js
* // Using ES5 syntax
* var unregisterPlugin = wp.plugins.unregisterPlugin;
*
* unregisterPlugin( 'plugin-name' );
* ```
*
* @example
* ```js
* // Using ESNext syntax
* import { unregisterPlugin } from '@wordpress/plugins';
*
* unregisterPlugin( 'plugin-name' );
* ```
*
* @return {WPPlugin | undefined} 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.
*
* @param {string} name Plugin name.
*
* @return {?WPPlugin} Plugin setting.
*/
function getPlugin(name) {
return api_plugins[name];
}
/**
* Returns all registered plugins without a scope or for a given scope.
*
* @param {string} [scope] The scope to be used when rendering inside
* a plugin area. No scope by default.
*
* @return {WPPlugin[]} 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
*/
/**
* Internal dependencies
*/
/**
* A component that renders all plugin fills in a hidden div.
*
* @example
* ```js
* // Using ES5 syntax
* var el = wp.element.createElement;
* var PluginArea = wp.plugins.PluginArea;
*
* function Layout() {
* return el(
* 'div',
* { scope: 'my-page' },
* 'Content of the page',
* PluginArea
* );
* }
* ```
*
* @example
* ```js
* // Using ESNext syntax
* import { PluginArea } from '@wordpress/plugins';
*
* const Layout = () => (
* <div>
* Content of the page
* <PluginArea scope="my-page" />
* </div>
* );
* ```
*
* @return {WPComponent} The component to be rendered.
*/
class PluginArea extends external_wp_element_namespaceObject.Component {
constructor() {
super(...arguments);
this.setPlugins = this.setPlugins.bind(this);
this.memoizedContext = memize_default()((name, icon) => {
return {
name,
icon
};
});
this.state = this.getCurrentPluginsState();
}
getCurrentPluginsState() {
return {
plugins: getPlugins(this.props.scope).map(_ref => {
let {
icon,
name,
render
} = _ref;
return {
Plugin: render,
context: this.memoizedContext(name, icon)
};
})
};
}
componentDidMount() {
(0,external_wp_hooks_namespaceObject.addAction)('plugins.pluginRegistered', 'core/plugins/plugin-area/plugins-registered', this.setPlugins);
(0,external_wp_hooks_namespaceObject.addAction)('plugins.pluginUnregistered', 'core/plugins/plugin-area/plugins-unregistered', this.setPlugins);
}
componentWillUnmount() {
(0,external_wp_hooks_namespaceObject.removeAction)('plugins.pluginRegistered', 'core/plugins/plugin-area/plugins-registered');
(0,external_wp_hooks_namespaceObject.removeAction)('plugins.pluginUnregistered', 'core/plugins/plugin-area/plugins-unregistered');
}
setPlugins() {
this.setState(this.getCurrentPluginsState);
}
render() {
return (0,external_wp_element_namespaceObject.createElement)("div", {
style: {
display: 'none'
}
}, this.state.plugins.map(_ref2 => {
let {
context,
Plugin
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(Provider, {
key: context.name,
value: context
}, (0,external_wp_element_namespaceObject.createElement)(PluginErrorBoundary, {
name: context.name,
onError: this.props.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
;// CONCATENATED MODULE: ./node_modules/@wordpress/plugins/build-module/index.js
}();
(window.wp = window.wp || {}).plugins = __webpack_exports__;
/******/ })()
; notices.min.js 0000666 00000004571 15123355174 0007351 0 ustar 00 /*! This file is auto-generated */
!function(){"use strict";var t={d:function(e,n){for(var r in n)t.o(n,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:n[r]})},o:function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r:function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{store:function(){return w}});var n={};t.r(n),t.d(n,{createErrorNotice:function(){return v},createInfoNotice:function(){return g},createNotice:function(){return d},createSuccessNotice:function(){return f},createWarningNotice:function(){return p},removeNotice:function(){return y}});var r={};t.r(r),t.d(r,{getNotices:function(){return E}});var i=window.wp.data;var o=t=>e=>function(){let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0;const i=r[t];if(void 0===i)return n;const o=e(n[i],r);return o===n[i]?n:{...n,[i]:o}};const c=o("context")((function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],e=arguments.length>1?arguments[1]:void 0;switch(e.type){case"CREATE_NOTICE":return[...t.filter((t=>{let{id:n}=t;return n!==e.notice.id})),e.notice];case"REMOVE_NOTICE":return t.filter((t=>{let{id:n}=t;return n!==e.id}))}return t}));var u=c;const s="global",l="info";let a=0;function d(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:l,e=arguments.length>1?arguments[1]:void 0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{speak:r=!0,isDismissible:i=!0,context:o=s,id:c=`${o}${++a}`,actions:u=[],type:d="default",__unstableHTML:f,icon:g=null,explicitDismiss:v=!1,onDismiss:p}=n;return e=String(e),{type:"CREATE_NOTICE",context:o,notice:{id:c,status:t,content:e,spokenMessage:r?e:null,__unstableHTML:f,isDismissible:i,actions:u,type:d,icon:g,explicitDismiss:v,onDismiss:p}}}function f(t,e){return d("success",t,e)}function g(t,e){return d("info",t,e)}function v(t,e){return d("error",t,e)}function p(t,e){return d("warning",t,e)}function y(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:s;return{type:"REMOVE_NOTICE",id:t,context:e}}const b=[];function E(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:s;return t[e]||b}const w=(0,i.createReduxStore)("core/notices",{reducer:u,actions:n,selectors:r});(0,i.register)(w),(window.wp=window.wp||{}).notices=e}(); edit-widgets.js 0000666 00000506124 15123355174 0007515 0 ustar 00 /******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 7153:
/***/ (function(module, exports) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2018 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
'use strict';
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = '';
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
classes = appendClass(classes, parseValue(arg));
}
}
return classes;
}
function parseValue (arg) {
if (typeof arg === 'string' || typeof arg === 'number') {
return arg;
}
if (typeof arg !== 'object') {
return '';
}
if (Array.isArray(arg)) {
return classNames.apply(null, arg);
}
if (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes('[native code]')) {
return arg.toString();
}
var classes = '';
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes = appendClass(classes, key);
}
}
return classes;
}
function appendClass (value, newClass) {
if (!newClass) {
return value;
}
if (value) {
return value + ' ' + newClass;
}
return value + newClass;
}
if ( true && module.exports) {
classNames.default = classNames;
module.exports = classNames;
} else if (true) {
// register as 'classnames', consistent with npm package name
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () {
return classNames;
}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
}());
/***/ })
/******/ });
/************************************************************************/
/******/ // 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 in strict mode.
!function() {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"initialize": function() { return /* binding */ initialize; },
"initializeEditor": function() { return /* binding */ initializeEditor; },
"reinitializeEditor": function() { return /* binding */ reinitializeEditor; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/interface/build-module/store/actions.js
var actions_namespaceObject = {};
__webpack_require__.r(actions_namespaceObject);
__webpack_require__.d(actions_namespaceObject, {
"disableComplementaryArea": function() { return disableComplementaryArea; },
"enableComplementaryArea": function() { return enableComplementaryArea; },
"pinItem": function() { return pinItem; },
"setDefaultComplementaryArea": function() { return setDefaultComplementaryArea; },
"setFeatureDefaults": function() { return setFeatureDefaults; },
"setFeatureValue": function() { return setFeatureValue; },
"toggleFeature": function() { return toggleFeature; },
"unpinItem": function() { return unpinItem; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/interface/build-module/store/selectors.js
var selectors_namespaceObject = {};
__webpack_require__.r(selectors_namespaceObject);
__webpack_require__.d(selectors_namespaceObject, {
"getActiveComplementaryArea": function() { return getActiveComplementaryArea; },
"isFeatureActive": function() { return isFeatureActive; },
"isItemPinned": function() { return isItemPinned; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/edit-widgets/build-module/store/actions.js
var store_actions_namespaceObject = {};
__webpack_require__.r(store_actions_namespaceObject);
__webpack_require__.d(store_actions_namespaceObject, {
"closeGeneralSidebar": function() { return closeGeneralSidebar; },
"moveBlockToWidgetArea": function() { return moveBlockToWidgetArea; },
"persistStubPost": function() { return persistStubPost; },
"saveEditedWidgetAreas": function() { return saveEditedWidgetAreas; },
"saveWidgetArea": function() { return saveWidgetArea; },
"saveWidgetAreas": function() { return saveWidgetAreas; },
"setIsInserterOpened": function() { return setIsInserterOpened; },
"setIsListViewOpened": function() { return setIsListViewOpened; },
"setIsWidgetAreaOpen": function() { return setIsWidgetAreaOpen; },
"setWidgetAreasOpenState": function() { return setWidgetAreasOpenState; },
"setWidgetIdForClientId": function() { return setWidgetIdForClientId; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/edit-widgets/build-module/store/resolvers.js
var resolvers_namespaceObject = {};
__webpack_require__.r(resolvers_namespaceObject);
__webpack_require__.d(resolvers_namespaceObject, {
"getWidgetAreas": function() { return getWidgetAreas; },
"getWidgets": function() { return getWidgets; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/edit-widgets/build-module/store/selectors.js
var store_selectors_namespaceObject = {};
__webpack_require__.r(store_selectors_namespaceObject);
__webpack_require__.d(store_selectors_namespaceObject, {
"__experimentalGetInsertionPoint": function() { return __experimentalGetInsertionPoint; },
"canInsertBlockInWidgetArea": function() { return canInsertBlockInWidgetArea; },
"getEditedWidgetAreas": function() { return getEditedWidgetAreas; },
"getIsWidgetAreaOpen": function() { return getIsWidgetAreaOpen; },
"getParentWidgetAreaBlock": function() { return getParentWidgetAreaBlock; },
"getReferenceWidgetBlocks": function() { return getReferenceWidgetBlocks; },
"getWidget": function() { return getWidget; },
"getWidgetAreaForWidgetId": function() { return getWidgetAreaForWidgetId; },
"getWidgetAreas": function() { return selectors_getWidgetAreas; },
"getWidgets": function() { return selectors_getWidgets; },
"isInserterOpened": function() { return isInserterOpened; },
"isListViewOpened": function() { return isListViewOpened; },
"isSavingWidgetAreas": function() { return isSavingWidgetAreas; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/edit-widgets/build-module/blocks/widget-area/index.js
var widget_area_namespaceObject = {};
__webpack_require__.r(widget_area_namespaceObject);
__webpack_require__.d(widget_area_namespaceObject, {
"metadata": function() { return metadata; },
"name": function() { return widget_area_name; },
"settings": function() { return settings; }
});
;// CONCATENATED MODULE: external ["wp","element"]
var external_wp_element_namespaceObject = window["wp"]["element"];
;// CONCATENATED MODULE: external ["wp","blocks"]
var external_wp_blocks_namespaceObject = window["wp"]["blocks"];
;// CONCATENATED MODULE: external ["wp","data"]
var external_wp_data_namespaceObject = window["wp"]["data"];
;// CONCATENATED MODULE: external ["wp","deprecated"]
var external_wp_deprecated_namespaceObject = window["wp"]["deprecated"];
var external_wp_deprecated_default = /*#__PURE__*/__webpack_require__.n(external_wp_deprecated_namespaceObject);
;// CONCATENATED MODULE: external ["wp","blockLibrary"]
var external_wp_blockLibrary_namespaceObject = window["wp"]["blockLibrary"];
;// CONCATENATED MODULE: external ["wp","coreData"]
var external_wp_coreData_namespaceObject = window["wp"]["coreData"];
;// CONCATENATED MODULE: external ["wp","widgets"]
var external_wp_widgets_namespaceObject = window["wp"]["widgets"];
;// CONCATENATED MODULE: external ["wp","preferences"]
var external_wp_preferences_namespaceObject = window["wp"]["preferences"];
;// CONCATENATED MODULE: external ["wp","apiFetch"]
var external_wp_apiFetch_namespaceObject = window["wp"]["apiFetch"];
var external_wp_apiFetch_default = /*#__PURE__*/__webpack_require__.n(external_wp_apiFetch_namespaceObject);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/store/reducer.js
/**
* WordPress dependencies
*/
/**
* Controls the open state of the widget areas.
*
* @param {Object} state Redux state.
* @param {Object} action Redux action.
*
* @return {Array} Updated state.
*/
function widgetAreasOpenState() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
const {
type
} = action;
switch (type) {
case 'SET_WIDGET_AREAS_OPEN_STATE':
{
return action.widgetAreasOpenState;
}
case 'SET_IS_WIDGET_AREA_OPEN':
{
const {
clientId,
isOpen
} = action;
return { ...state,
[clientId]: isOpen
};
}
default:
{
return state;
}
}
}
/**
* Reducer to set the block inserter panel open or closed.
*
* Note: this reducer interacts with the list view panel reducer
* to make sure that only one of the two panels is open at the same time.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*/
function blockInserterPanel() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'SET_IS_LIST_VIEW_OPENED':
return action.isOpen ? false : state;
case 'SET_IS_INSERTER_OPENED':
return action.value;
}
return state;
}
/**
* Reducer to set the list view panel open or closed.
*
* Note: this reducer interacts with the inserter panel reducer
* to make sure that only one of the two panels is open at the same time.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*/
function listViewPanel() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'SET_IS_INSERTER_OPENED':
return action.value ? false : state;
case 'SET_IS_LIST_VIEW_OPENED':
return action.isOpen;
}
return state;
}
/* harmony default export */ var reducer = ((0,external_wp_data_namespaceObject.combineReducers)({
blockInserterPanel,
listViewPanel,
widgetAreasOpenState
}));
;// 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: ./node_modules/@babel/runtime/helpers/esm/extends.js
function _extends() {
return _extends = Object.assign ? Object.assign.bind() : function (n) {
for (var e = 1; e < arguments.length; e++) {
var t = arguments[e];
for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
}
return n;
}, _extends.apply(null, arguments);
}
// EXTERNAL MODULE: ./node_modules/classnames/index.js
var classnames = __webpack_require__(7153);
var classnames_default = /*#__PURE__*/__webpack_require__.n(classnames);
;// CONCATENATED MODULE: external ["wp","components"]
var external_wp_components_namespaceObject = window["wp"]["components"];
;// CONCATENATED MODULE: external ["wp","primitives"]
var external_wp_primitives_namespaceObject = window["wp"]["primitives"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/check.js
/**
* WordPress dependencies
*/
const check = (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: "M16.7 7.1l-6.3 8.5-3.3-2.5-.9 1.2 4.5 3.4L17.9 8z"
}));
/* harmony default export */ var library_check = (check);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/star-filled.js
/**
* WordPress dependencies
*/
const starFilled = (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: "M11.776 4.454a.25.25 0 01.448 0l2.069 4.192a.25.25 0 00.188.137l4.626.672a.25.25 0 01.139.426l-3.348 3.263a.25.25 0 00-.072.222l.79 4.607a.25.25 0 01-.362.263l-4.138-2.175a.25.25 0 00-.232 0l-4.138 2.175a.25.25 0 01-.363-.263l.79-4.607a.25.25 0 00-.071-.222L4.754 9.881a.25.25 0 01.139-.426l4.626-.672a.25.25 0 00.188-.137l2.069-4.192z"
}));
/* harmony default export */ var star_filled = (starFilled);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/star-empty.js
/**
* WordPress dependencies
*/
const starEmpty = (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, {
fillRule: "evenodd",
d: "M9.706 8.646a.25.25 0 01-.188.137l-4.626.672a.25.25 0 00-.139.427l3.348 3.262a.25.25 0 01.072.222l-.79 4.607a.25.25 0 00.362.264l4.138-2.176a.25.25 0 01.233 0l4.137 2.175a.25.25 0 00.363-.263l-.79-4.607a.25.25 0 01.072-.222l3.347-3.262a.25.25 0 00-.139-.427l-4.626-.672a.25.25 0 01-.188-.137l-2.069-4.192a.25.25 0 00-.448 0L9.706 8.646zM12 7.39l-.948 1.921a1.75 1.75 0 01-1.317.957l-2.12.308 1.534 1.495c.412.402.6.982.503 1.55l-.362 2.11 1.896-.997a1.75 1.75 0 011.629 0l1.895.997-.362-2.11a1.75 1.75 0 01.504-1.55l1.533-1.495-2.12-.308a1.75 1.75 0 01-1.317-.957L12 7.39z",
clipRule: "evenodd"
}));
/* harmony default export */ var star_empty = (starEmpty);
;// CONCATENATED MODULE: external ["wp","viewport"]
var external_wp_viewport_namespaceObject = window["wp"]["viewport"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/close-small.js
/**
* WordPress dependencies
*/
const closeSmall = (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: "M12 13.06l3.712 3.713 1.061-1.06L13.061 12l3.712-3.712-1.06-1.06L12 10.938 8.288 7.227l-1.061 1.06L10.939 12l-3.712 3.712 1.06 1.061L12 13.061z"
}));
/* harmony default export */ var close_small = (closeSmall);
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/store/actions.js
/**
* WordPress dependencies
*/
/**
* Set a default complementary area.
*
* @param {string} scope Complementary area scope.
* @param {string} area Area identifier.
*
* @return {Object} Action object.
*/
const setDefaultComplementaryArea = (scope, area) => ({
type: 'SET_DEFAULT_COMPLEMENTARY_AREA',
scope,
area
});
/**
* Enable the complementary area.
*
* @param {string} scope Complementary area scope.
* @param {string} area Area identifier.
*/
const enableComplementaryArea = (scope, area) => _ref => {
let {
registry,
dispatch
} = _ref;
// Return early if there's no area.
if (!area) {
return;
}
const isComplementaryAreaVisible = registry.select(external_wp_preferences_namespaceObject.store).get(scope, 'isComplementaryAreaVisible');
if (!isComplementaryAreaVisible) {
registry.dispatch(external_wp_preferences_namespaceObject.store).set(scope, 'isComplementaryAreaVisible', true);
}
dispatch({
type: 'ENABLE_COMPLEMENTARY_AREA',
scope,
area
});
};
/**
* Disable the complementary area.
*
* @param {string} scope Complementary area scope.
*/
const disableComplementaryArea = scope => _ref2 => {
let {
registry
} = _ref2;
const isComplementaryAreaVisible = registry.select(external_wp_preferences_namespaceObject.store).get(scope, 'isComplementaryAreaVisible');
if (isComplementaryAreaVisible) {
registry.dispatch(external_wp_preferences_namespaceObject.store).set(scope, 'isComplementaryAreaVisible', false);
}
};
/**
* Pins an item.
*
* @param {string} scope Item scope.
* @param {string} item Item identifier.
*
* @return {Object} Action object.
*/
const pinItem = (scope, item) => _ref3 => {
let {
registry
} = _ref3;
// Return early if there's no item.
if (!item) {
return;
}
const pinnedItems = registry.select(external_wp_preferences_namespaceObject.store).get(scope, 'pinnedItems'); // The item is already pinned, there's nothing to do.
if ((pinnedItems === null || pinnedItems === void 0 ? void 0 : pinnedItems[item]) === true) {
return;
}
registry.dispatch(external_wp_preferences_namespaceObject.store).set(scope, 'pinnedItems', { ...pinnedItems,
[item]: true
});
};
/**
* Unpins an item.
*
* @param {string} scope Item scope.
* @param {string} item Item identifier.
*/
const unpinItem = (scope, item) => _ref4 => {
let {
registry
} = _ref4;
// Return early if there's no item.
if (!item) {
return;
}
const pinnedItems = registry.select(external_wp_preferences_namespaceObject.store).get(scope, 'pinnedItems');
registry.dispatch(external_wp_preferences_namespaceObject.store).set(scope, 'pinnedItems', { ...pinnedItems,
[item]: false
});
};
/**
* Returns an action object used in signalling that a feature should be toggled.
*
* @param {string} scope The feature scope (e.g. core/edit-post).
* @param {string} featureName The feature name.
*/
function toggleFeature(scope, featureName) {
return function (_ref5) {
let {
registry
} = _ref5;
external_wp_deprecated_default()(`dispatch( 'core/interface' ).toggleFeature`, {
since: '6.0',
alternative: `dispatch( 'core/preferences' ).toggle`
});
registry.dispatch(external_wp_preferences_namespaceObject.store).toggle(scope, featureName);
};
}
/**
* Returns an action object used in signalling that a feature should be set to
* a true or false value
*
* @param {string} scope The feature scope (e.g. core/edit-post).
* @param {string} featureName The feature name.
* @param {boolean} value The value to set.
*
* @return {Object} Action object.
*/
function setFeatureValue(scope, featureName, value) {
return function (_ref6) {
let {
registry
} = _ref6;
external_wp_deprecated_default()(`dispatch( 'core/interface' ).setFeatureValue`, {
since: '6.0',
alternative: `dispatch( 'core/preferences' ).set`
});
registry.dispatch(external_wp_preferences_namespaceObject.store).set(scope, featureName, !!value);
};
}
/**
* Returns an action object used in signalling that defaults should be set for features.
*
* @param {string} scope The feature scope (e.g. core/edit-post).
* @param {Object<string, boolean>} defaults A key/value map of feature names to values.
*
* @return {Object} Action object.
*/
function setFeatureDefaults(scope, defaults) {
return function (_ref7) {
let {
registry
} = _ref7;
external_wp_deprecated_default()(`dispatch( 'core/interface' ).setFeatureDefaults`, {
since: '6.0',
alternative: `dispatch( 'core/preferences' ).setDefaults`
});
registry.dispatch(external_wp_preferences_namespaceObject.store).setDefaults(scope, defaults);
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/store/selectors.js
/**
* WordPress dependencies
*/
/**
* Returns the complementary area that is active in a given scope.
*
* @param {Object} state Global application state.
* @param {string} scope Item scope.
*
* @return {string | null | undefined} The complementary area that is active in the given scope.
*/
const getActiveComplementaryArea = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (state, scope) => {
var _state$complementaryA;
const isComplementaryAreaVisible = select(external_wp_preferences_namespaceObject.store).get(scope, 'isComplementaryAreaVisible'); // Return `undefined` to indicate that the user has never toggled
// visibility, this is the vanilla default. Other code relies on this
// nuance in the return value.
if (isComplementaryAreaVisible === undefined) {
return undefined;
} // Return `null` to indicate the user hid the complementary area.
if (!isComplementaryAreaVisible) {
return null;
}
return state === null || state === void 0 ? void 0 : (_state$complementaryA = state.complementaryAreas) === null || _state$complementaryA === void 0 ? void 0 : _state$complementaryA[scope];
});
/**
* Returns a boolean indicating if an item is pinned or not.
*
* @param {Object} state Global application state.
* @param {string} scope Scope.
* @param {string} item Item to check.
*
* @return {boolean} True if the item is pinned and false otherwise.
*/
const isItemPinned = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (state, scope, item) => {
var _pinnedItems$item;
const pinnedItems = select(external_wp_preferences_namespaceObject.store).get(scope, 'pinnedItems');
return (_pinnedItems$item = pinnedItems === null || pinnedItems === void 0 ? void 0 : pinnedItems[item]) !== null && _pinnedItems$item !== void 0 ? _pinnedItems$item : true;
});
/**
* Returns a boolean indicating whether a feature is active for a particular
* scope.
*
* @param {Object} state The store state.
* @param {string} scope The scope of the feature (e.g. core/edit-post).
* @param {string} featureName The name of the feature.
*
* @return {boolean} Is the feature enabled?
*/
const isFeatureActive = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (state, scope, featureName) => {
external_wp_deprecated_default()(`select( 'core/interface' ).isFeatureActive( scope, featureName )`, {
since: '6.0',
alternative: `select( 'core/preferences' ).get( scope, featureName )`
});
return !!select(external_wp_preferences_namespaceObject.store).get(scope, featureName);
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/store/reducer.js
/**
* WordPress dependencies
*/
function complementaryAreas() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'SET_DEFAULT_COMPLEMENTARY_AREA':
{
const {
scope,
area
} = action; // If there's already an area, don't overwrite it.
if (state[scope]) {
return state;
}
return { ...state,
[scope]: area
};
}
case 'ENABLE_COMPLEMENTARY_AREA':
{
const {
scope,
area
} = action;
return { ...state,
[scope]: area
};
}
}
return state;
}
/* harmony default export */ var store_reducer = ((0,external_wp_data_namespaceObject.combineReducers)({
complementaryAreas
}));
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/store/constants.js
/**
* The identifier for the data store.
*
* @type {string}
*/
const STORE_NAME = 'core/interface';
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/store/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Store definition for the interface 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, {
reducer: store_reducer,
actions: actions_namespaceObject,
selectors: selectors_namespaceObject
}); // 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.register)(store);
;// CONCATENATED MODULE: external ["wp","plugins"]
var external_wp_plugins_namespaceObject = window["wp"]["plugins"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/complementary-area-context/index.js
/**
* WordPress dependencies
*/
/* harmony default export */ var complementary_area_context = ((0,external_wp_plugins_namespaceObject.withPluginContext)((context, ownProps) => {
return {
icon: ownProps.icon || context.icon,
identifier: ownProps.identifier || `${context.name}/${ownProps.name}`
};
}));
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/complementary-area-toggle/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ComplementaryAreaToggle(_ref) {
let {
as = external_wp_components_namespaceObject.Button,
scope,
identifier,
icon,
selectedIcon,
name,
...props
} = _ref;
const ComponentToUse = as;
const isSelected = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).getActiveComplementaryArea(scope) === identifier, [identifier]);
const {
enableComplementaryArea,
disableComplementaryArea
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
return (0,external_wp_element_namespaceObject.createElement)(ComponentToUse, _extends({
icon: selectedIcon && isSelected ? selectedIcon : icon,
onClick: () => {
if (isSelected) {
disableComplementaryArea(scope);
} else {
enableComplementaryArea(scope, identifier);
}
}
}, props));
}
/* harmony default export */ var complementary_area_toggle = (complementary_area_context(ComplementaryAreaToggle));
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/complementary-area-header/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const ComplementaryAreaHeader = _ref => {
let {
smallScreenTitle,
children,
className,
toggleButtonProps
} = _ref;
const toggleButton = (0,external_wp_element_namespaceObject.createElement)(complementary_area_toggle, _extends({
icon: close_small
}, toggleButtonProps));
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-panel__header interface-complementary-area-header__small"
}, smallScreenTitle && (0,external_wp_element_namespaceObject.createElement)("span", {
className: "interface-complementary-area-header__small-title"
}, smallScreenTitle), toggleButton), (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('components-panel__header', 'interface-complementary-area-header', className),
tabIndex: -1
}, children, toggleButton));
};
/* harmony default export */ var complementary_area_header = (ComplementaryAreaHeader);
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/action-item/index.js
/**
* WordPress dependencies
*/
const noop = () => {};
function ActionItemSlot(_ref) {
let {
name,
as: Component = external_wp_components_namespaceObject.ButtonGroup,
fillProps = {},
bubblesVirtually,
...props
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Slot, {
name: name,
bubblesVirtually: bubblesVirtually,
fillProps: fillProps
}, fills => {
if (!external_wp_element_namespaceObject.Children.toArray(fills).length) {
return null;
} // Special handling exists for backward compatibility.
// It ensures that menu items created by plugin authors aren't
// duplicated with automatically injected menu items coming
// from pinnable plugin sidebars.
// @see https://github.com/WordPress/gutenberg/issues/14457
const initializedByPlugins = [];
external_wp_element_namespaceObject.Children.forEach(fills, _ref2 => {
let {
props: {
__unstableExplicitMenuItem,
__unstableTarget
}
} = _ref2;
if (__unstableTarget && __unstableExplicitMenuItem) {
initializedByPlugins.push(__unstableTarget);
}
});
const children = external_wp_element_namespaceObject.Children.map(fills, child => {
if (!child.props.__unstableExplicitMenuItem && initializedByPlugins.includes(child.props.__unstableTarget)) {
return null;
}
return child;
});
return (0,external_wp_element_namespaceObject.createElement)(Component, props, children);
});
}
function ActionItem(_ref3) {
let {
name,
as: Component = external_wp_components_namespaceObject.Button,
onClick,
...props
} = _ref3;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Fill, {
name: name
}, _ref4 => {
let {
onClick: fpOnClick
} = _ref4;
return (0,external_wp_element_namespaceObject.createElement)(Component, _extends({
onClick: onClick || fpOnClick ? function () {
(onClick || noop)(...arguments);
(fpOnClick || noop)(...arguments);
} : undefined
}, props));
});
}
ActionItem.Slot = ActionItemSlot;
/* harmony default export */ var action_item = (ActionItem);
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/complementary-area-more-menu-item/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const PluginsMenuItem = _ref => {
let {
// Menu item is marked with unstable prop for backward compatibility.
// They are removed so they don't leak to DOM elements.
// @see https://github.com/WordPress/gutenberg/issues/14457
__unstableExplicitMenuItem,
__unstableTarget,
...restProps
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, restProps);
};
function ComplementaryAreaMoreMenuItem(_ref2) {
let {
scope,
target,
__unstableExplicitMenuItem,
...props
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(complementary_area_toggle, _extends({
as: toggleProps => {
return (0,external_wp_element_namespaceObject.createElement)(action_item, _extends({
__unstableExplicitMenuItem: __unstableExplicitMenuItem,
__unstableTarget: `${scope}/${target}`,
as: PluginsMenuItem,
name: `${scope}/plugin-more-menu`
}, toggleProps));
},
role: "menuitemcheckbox",
selectedIcon: library_check,
name: target,
scope: scope
}, props));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/pinned-items/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
function PinnedItems(_ref) {
let {
scope,
...props
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Fill, _extends({
name: `PinnedItems/${scope}`
}, props));
}
function PinnedItemsSlot(_ref2) {
let {
scope,
className,
...props
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Slot, _extends({
name: `PinnedItems/${scope}`
}, props), fills => (fills === null || fills === void 0 ? void 0 : fills.length) > 0 && (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()(className, 'interface-pinned-items')
}, fills));
}
PinnedItems.Slot = PinnedItemsSlot;
/* harmony default export */ var pinned_items = (PinnedItems);
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/complementary-area/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ComplementaryAreaSlot(_ref) {
let {
scope,
...props
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Slot, _extends({
name: `ComplementaryArea/${scope}`
}, props));
}
function ComplementaryAreaFill(_ref2) {
let {
scope,
children,
className
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Fill, {
name: `ComplementaryArea/${scope}`
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: className
}, children));
}
function useAdjustComplementaryListener(scope, identifier, activeArea, isActive, isSmall) {
const previousIsSmall = (0,external_wp_element_namespaceObject.useRef)(false);
const shouldOpenWhenNotSmall = (0,external_wp_element_namespaceObject.useRef)(false);
const {
enableComplementaryArea,
disableComplementaryArea
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
(0,external_wp_element_namespaceObject.useEffect)(() => {
// If the complementary area is active and the editor is switching from a big to a small window size.
if (isActive && isSmall && !previousIsSmall.current) {
// Disable the complementary area.
disableComplementaryArea(scope); // Flag the complementary area to be reopened when the window size goes from small to big.
shouldOpenWhenNotSmall.current = true;
} else if ( // If there is a flag indicating the complementary area should be enabled when we go from small to big window size
// and we are going from a small to big window size.
shouldOpenWhenNotSmall.current && !isSmall && previousIsSmall.current) {
// Remove the flag indicating the complementary area should be enabled.
shouldOpenWhenNotSmall.current = false; // Enable the complementary area.
enableComplementaryArea(scope, identifier);
} else if ( // If the flag is indicating the current complementary should be reopened but another complementary area becomes active,
// remove the flag.
shouldOpenWhenNotSmall.current && activeArea && activeArea !== identifier) {
shouldOpenWhenNotSmall.current = false;
}
if (isSmall !== previousIsSmall.current) {
previousIsSmall.current = isSmall;
}
}, [isActive, isSmall, scope, identifier, activeArea]);
}
function ComplementaryArea(_ref3) {
let {
children,
className,
closeLabel = (0,external_wp_i18n_namespaceObject.__)('Close plugin'),
identifier,
header,
headerClassName,
icon,
isPinnable = true,
panelClassName,
scope,
name,
smallScreenTitle,
title,
toggleShortcut,
isActiveByDefault,
showIconLabels = false
} = _ref3;
const {
isActive,
isPinned,
activeArea,
isSmall,
isLarge
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getActiveComplementaryArea,
isItemPinned
} = select(store);
const _activeArea = getActiveComplementaryArea(scope);
return {
isActive: _activeArea === identifier,
isPinned: isItemPinned(scope, identifier),
activeArea: _activeArea,
isSmall: select(external_wp_viewport_namespaceObject.store).isViewportMatch('< medium'),
isLarge: select(external_wp_viewport_namespaceObject.store).isViewportMatch('large')
};
}, [identifier, scope]);
useAdjustComplementaryListener(scope, identifier, activeArea, isActive, isSmall);
const {
enableComplementaryArea,
disableComplementaryArea,
pinItem,
unpinItem
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (isActiveByDefault && activeArea === undefined && !isSmall) {
enableComplementaryArea(scope, identifier);
}
}, [activeArea, isActiveByDefault, scope, identifier, isSmall]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, isPinnable && (0,external_wp_element_namespaceObject.createElement)(pinned_items, {
scope: scope
}, isPinned && (0,external_wp_element_namespaceObject.createElement)(complementary_area_toggle, {
scope: scope,
identifier: identifier,
isPressed: isActive && (!showIconLabels || isLarge),
"aria-expanded": isActive,
label: title,
icon: showIconLabels ? library_check : icon,
showTooltip: !showIconLabels,
variant: showIconLabels ? 'tertiary' : undefined
})), name && isPinnable && (0,external_wp_element_namespaceObject.createElement)(ComplementaryAreaMoreMenuItem, {
target: name,
scope: scope,
icon: icon
}, title), isActive && (0,external_wp_element_namespaceObject.createElement)(ComplementaryAreaFill, {
className: classnames_default()('interface-complementary-area', className),
scope: scope
}, (0,external_wp_element_namespaceObject.createElement)(complementary_area_header, {
className: headerClassName,
closeLabel: closeLabel,
onClose: () => disableComplementaryArea(scope),
smallScreenTitle: smallScreenTitle,
toggleButtonProps: {
label: closeLabel,
shortcut: toggleShortcut,
scope,
identifier
}
}, header || (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("strong", null, title), isPinnable && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "interface-complementary-area__pin-unpin-item",
icon: isPinned ? star_filled : star_empty,
label: isPinned ? (0,external_wp_i18n_namespaceObject.__)('Unpin from toolbar') : (0,external_wp_i18n_namespaceObject.__)('Pin to toolbar'),
onClick: () => (isPinned ? unpinItem : pinItem)(scope, identifier),
isPressed: isPinned,
"aria-expanded": isPinned
}))), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Panel, {
className: panelClassName
}, children)));
}
const ComplementaryAreaWrapped = complementary_area_context(ComplementaryArea);
ComplementaryAreaWrapped.Slot = ComplementaryAreaSlot;
/* harmony default export */ var complementary_area = (ComplementaryAreaWrapped);
;// CONCATENATED MODULE: external ["wp","compose"]
var external_wp_compose_namespaceObject = window["wp"]["compose"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/navigable-region/index.js
/**
* External dependencies
*/
function NavigableRegion(_ref) {
let {
children,
className,
ariaLabel,
as: Tag = 'div',
...props
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(Tag, _extends({
className: classnames_default()('interface-navigable-region', className),
"aria-label": ariaLabel,
role: "region",
tabIndex: "-1"
}, props), children);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/interface-skeleton/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useHTMLClass(className) {
(0,external_wp_element_namespaceObject.useEffect)(() => {
const element = document && document.querySelector(`html:not(.${className})`);
if (!element) {
return;
}
element.classList.toggle(className);
return () => {
element.classList.toggle(className);
};
}, [className]);
}
function InterfaceSkeleton(_ref, ref) {
let {
isDistractionFree,
footer,
header,
editorNotices,
sidebar,
secondarySidebar,
notices,
content,
actions,
labels,
className,
enableRegionNavigation = true,
// Todo: does this need to be a prop.
// Can we use a dependency to keyboard-shortcuts directly?
shortcuts
} = _ref;
const navigateRegionsProps = (0,external_wp_components_namespaceObject.__unstableUseNavigateRegions)(shortcuts);
useHTMLClass('interface-interface-skeleton__html-container');
const defaultLabels = {
/* translators: accessibility text for the top bar landmark region. */
header: (0,external_wp_i18n_namespaceObject.__)('Header'),
/* translators: accessibility text for the content landmark region. */
body: (0,external_wp_i18n_namespaceObject.__)('Content'),
/* translators: accessibility text for the secondary sidebar landmark region. */
secondarySidebar: (0,external_wp_i18n_namespaceObject.__)('Block Library'),
/* translators: accessibility text for the settings landmark region. */
sidebar: (0,external_wp_i18n_namespaceObject.__)('Settings'),
/* translators: accessibility text for the publish landmark region. */
actions: (0,external_wp_i18n_namespaceObject.__)('Publish'),
/* translators: accessibility text for the footer landmark region. */
footer: (0,external_wp_i18n_namespaceObject.__)('Footer')
};
const mergedLabels = { ...defaultLabels,
...labels
};
const headerVariants = {
hidden: isDistractionFree ? {
opacity: 0
} : {
opacity: 1
},
hover: {
opacity: 1,
transition: {
type: 'tween',
delay: 0.2,
delayChildren: 0.2
}
}
};
return (0,external_wp_element_namespaceObject.createElement)("div", _extends({}, enableRegionNavigation ? navigateRegionsProps : {}, {
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([ref, enableRegionNavigation ? navigateRegionsProps.ref : undefined]),
className: classnames_default()(className, 'interface-interface-skeleton', navigateRegionsProps.className, !!footer && 'has-footer')
}), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "interface-interface-skeleton__editor"
}, !!header && isDistractionFree && (0,external_wp_element_namespaceObject.createElement)(NavigableRegion, {
as: external_wp_components_namespaceObject.__unstableMotion.div,
className: "interface-interface-skeleton__header",
"aria-label": mergedLabels.header,
initial: isDistractionFree ? 'hidden' : 'hover',
whileHover: "hover",
variants: headerVariants,
transition: {
type: 'tween',
delay: 0.8
}
}, header), !!header && !isDistractionFree && (0,external_wp_element_namespaceObject.createElement)(NavigableRegion, {
className: "interface-interface-skeleton__header",
ariaLabel: mergedLabels.header
}, header), isDistractionFree && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "interface-interface-skeleton__header"
}, editorNotices), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "interface-interface-skeleton__body"
}, !!secondarySidebar && (0,external_wp_element_namespaceObject.createElement)(NavigableRegion, {
className: "interface-interface-skeleton__secondary-sidebar",
ariaLabel: mergedLabels.secondarySidebar
}, secondarySidebar), !!notices && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "interface-interface-skeleton__notices"
}, notices), (0,external_wp_element_namespaceObject.createElement)(NavigableRegion, {
className: "interface-interface-skeleton__content",
ariaLabel: mergedLabels.body
}, content), !!sidebar && (0,external_wp_element_namespaceObject.createElement)(NavigableRegion, {
className: "interface-interface-skeleton__sidebar",
ariaLabel: mergedLabels.sidebar
}, sidebar), !!actions && (0,external_wp_element_namespaceObject.createElement)(NavigableRegion, {
className: "interface-interface-skeleton__actions",
ariaLabel: mergedLabels.actions
}, actions))), !!footer && (0,external_wp_element_namespaceObject.createElement)(NavigableRegion, {
className: "interface-interface-skeleton__footer",
ariaLabel: mergedLabels.footer
}, footer));
}
/* harmony default export */ var interface_skeleton = ((0,external_wp_element_namespaceObject.forwardRef)(InterfaceSkeleton));
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/more-vertical.js
/**
* WordPress dependencies
*/
const moreVertical = (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: "M13 19h-2v-2h2v2zm0-6h-2v-2h2v2zm0-6h-2V5h2v2z"
}));
/* harmony default export */ var more_vertical = (moreVertical);
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/more-menu-dropdown/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
function MoreMenuDropdown(_ref) {
let {
as: DropdownComponent = external_wp_components_namespaceObject.DropdownMenu,
className,
/* translators: button label text should, if possible, be under 16 characters. */
label = (0,external_wp_i18n_namespaceObject.__)('Options'),
popoverProps,
toggleProps,
children
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(DropdownComponent, {
className: classnames_default()('interface-more-menu-dropdown', className),
icon: more_vertical,
label: label,
popoverProps: {
placement: 'bottom-end',
...popoverProps,
className: classnames_default()('interface-more-menu-dropdown__content', popoverProps === null || popoverProps === void 0 ? void 0 : popoverProps.className)
},
toggleProps: {
tooltipPosition: 'bottom',
...toggleProps
}
}, onClose => children(onClose));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/index.js
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/index.js
;// CONCATENATED MODULE: external ["wp","blockEditor"]
var external_wp_blockEditor_namespaceObject = window["wp"]["blockEditor"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/store/transformers.js
/**
* WordPress dependencies
*/
/**
* Converts a widget entity record into a block.
*
* @param {Object} widget The widget entity record.
* @return {Object} a block (converted from the entity record).
*/
function transformWidgetToBlock(widget) {
if (widget.id_base === 'block') {
const parsedBlocks = (0,external_wp_blocks_namespaceObject.parse)(widget.instance.raw.content, {
__unstableSkipAutop: true
});
if (!parsedBlocks.length) {
return (0,external_wp_widgets_namespaceObject.addWidgetIdToBlock)((0,external_wp_blocks_namespaceObject.createBlock)('core/paragraph', {}, []), widget.id);
}
return (0,external_wp_widgets_namespaceObject.addWidgetIdToBlock)(parsedBlocks[0], widget.id);
}
let attributes;
if (widget._embedded.about[0].is_multi) {
attributes = {
idBase: widget.id_base,
instance: widget.instance
};
} else {
attributes = {
id: widget.id
};
}
return (0,external_wp_widgets_namespaceObject.addWidgetIdToBlock)((0,external_wp_blocks_namespaceObject.createBlock)('core/legacy-widget', attributes, []), widget.id);
}
/**
* Converts a block to a widget entity record.
*
* @param {Object} block The block.
* @param {Object?} relatedWidget A related widget entity record from the API (optional).
* @return {Object} the widget object (converted from block).
*/
function transformBlockToWidget(block) {
let relatedWidget = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
let widget;
const isValidLegacyWidgetBlock = block.name === 'core/legacy-widget' && (block.attributes.id || block.attributes.instance);
if (isValidLegacyWidgetBlock) {
var _block$attributes$id, _block$attributes$idB, _block$attributes$ins;
widget = { ...relatedWidget,
id: (_block$attributes$id = block.attributes.id) !== null && _block$attributes$id !== void 0 ? _block$attributes$id : relatedWidget.id,
id_base: (_block$attributes$idB = block.attributes.idBase) !== null && _block$attributes$idB !== void 0 ? _block$attributes$idB : relatedWidget.id_base,
instance: (_block$attributes$ins = block.attributes.instance) !== null && _block$attributes$ins !== void 0 ? _block$attributes$ins : relatedWidget.instance
};
} else {
widget = { ...relatedWidget,
id_base: 'block',
instance: {
raw: {
content: (0,external_wp_blocks_namespaceObject.serialize)(block)
}
}
};
} // Delete read-only properties.
delete widget.rendered;
delete widget.rendered_form;
return widget;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/store/utils.js
/**
* "Kind" of the navigation post.
*
* @type {string}
*/
const KIND = 'root';
/**
* "post type" of the navigation post.
*
* @type {string}
*/
const WIDGET_AREA_ENTITY_TYPE = 'sidebar';
/**
* "post type" of the widget area post.
*
* @type {string}
*/
const POST_TYPE = 'postType';
/**
* Builds an ID for a new widget area post.
*
* @param {number} widgetAreaId Widget area id.
* @return {string} An ID.
*/
const buildWidgetAreaPostId = widgetAreaId => `widget-area-${widgetAreaId}`;
/**
* Builds an ID for a global widget areas post.
*
* @return {string} An ID.
*/
const buildWidgetAreasPostId = () => `widget-areas`;
/**
* Builds a query to resolve sidebars.
*
* @return {Object} Query.
*/
function buildWidgetAreasQuery() {
return {
per_page: -1
};
}
/**
* Builds a query to resolve widgets.
*
* @return {Object} Query.
*/
function buildWidgetsQuery() {
return {
per_page: -1,
_embed: 'about'
};
}
/**
* Creates a stub post with given id and set of blocks. Used as a governing entity records
* for all widget areas.
*
* @param {string} id Post ID.
* @param {Array} blocks The list of blocks.
* @return {Object} A stub post object formatted in compliance with the data layer.
*/
const createStubPost = (id, blocks) => ({
id,
slug: id,
status: 'draft',
type: 'page',
blocks,
meta: {
widgetAreaId: id
}
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/store/constants.js
/**
* Module Constants
*/
const constants_STORE_NAME = 'core/edit-widgets';
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/store/actions.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Persists a stub post with given ID to core data store. The post is meant to be in-memory only and
* shouldn't be saved via the API.
*
* @param {string} id Post ID.
* @param {Array} blocks Blocks the post should consist of.
* @return {Object} The post object.
*/
const persistStubPost = (id, blocks) => _ref => {
let {
registry
} = _ref;
const stubPost = createStubPost(id, blocks);
registry.dispatch(external_wp_coreData_namespaceObject.store).receiveEntityRecords(KIND, POST_TYPE, stubPost, {
id: stubPost.id
}, false);
return stubPost;
};
/**
* Converts all the blocks from edited widget areas into widgets,
* and submits a batch request to save everything at once.
*
* Creates a snackbar notice on either success or error.
*
* @return {Function} An action creator.
*/
const saveEditedWidgetAreas = () => async _ref2 => {
let {
select,
dispatch,
registry
} = _ref2;
const editedWidgetAreas = select.getEditedWidgetAreas();
if (!(editedWidgetAreas !== null && editedWidgetAreas !== void 0 && editedWidgetAreas.length)) {
return;
}
try {
await dispatch.saveWidgetAreas(editedWidgetAreas);
registry.dispatch(external_wp_notices_namespaceObject.store).createSuccessNotice((0,external_wp_i18n_namespaceObject.__)('Widgets saved.'), {
type: 'snackbar'
});
} catch (e) {
registry.dispatch(external_wp_notices_namespaceObject.store).createErrorNotice(
/* translators: %s: The error message. */
(0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('There was an error. %s'), e.message), {
type: 'snackbar'
});
}
};
/**
* Converts all the blocks from specified widget areas into widgets,
* and submits a batch request to save everything at once.
*
* @param {Object[]} widgetAreas Widget areas to save.
* @return {Function} An action creator.
*/
const saveWidgetAreas = widgetAreas => async _ref3 => {
let {
dispatch,
registry
} = _ref3;
try {
for (const widgetArea of widgetAreas) {
await dispatch.saveWidgetArea(widgetArea.id);
}
} finally {
// saveEditedEntityRecord resets the resolution status, let's fix it manually.
await registry.dispatch(external_wp_coreData_namespaceObject.store).finishResolution('getEntityRecord', KIND, WIDGET_AREA_ENTITY_TYPE, buildWidgetAreasQuery());
}
};
/**
* Converts all the blocks from a widget area specified by ID into widgets,
* and submits a batch request to save everything at once.
*
* @param {string} widgetAreaId ID of the widget area to process.
* @return {Function} An action creator.
*/
const saveWidgetArea = widgetAreaId => async _ref4 => {
let {
dispatch,
select,
registry
} = _ref4;
const widgets = select.getWidgets();
const post = registry.select(external_wp_coreData_namespaceObject.store).getEditedEntityRecord(KIND, POST_TYPE, buildWidgetAreaPostId(widgetAreaId)); // Get all widgets from this area
const areaWidgets = Object.values(widgets).filter(_ref5 => {
let {
sidebar
} = _ref5;
return sidebar === widgetAreaId;
}); // Remove all duplicate reference widget instances for legacy widgets.
// Why? We filter out the widgets with duplicate IDs to prevent adding more than one instance of a widget
// implemented using a function. WordPress doesn't support having more than one instance of these, if you try to
// save multiple instances of these in different sidebars you will run into undefined behaviors.
const usedReferenceWidgets = [];
const widgetsBlocks = post.blocks.filter(block => {
const {
id
} = block.attributes;
if (block.name === 'core/legacy-widget' && id) {
if (usedReferenceWidgets.includes(id)) {
return false;
}
usedReferenceWidgets.push(id);
}
return true;
}); // Determine which widgets have been deleted. We can tell if a widget is
// deleted and not just moved to a different area by looking to see if
// getWidgetAreaForWidgetId() finds something.
const deletedWidgets = [];
for (const widget of areaWidgets) {
const widgetsNewArea = select.getWidgetAreaForWidgetId(widget.id);
if (!widgetsNewArea) {
deletedWidgets.push(widget);
}
}
const batchMeta = [];
const batchTasks = [];
const sidebarWidgetsIds = [];
for (let i = 0; i < widgetsBlocks.length; i++) {
const block = widgetsBlocks[i];
const widgetId = (0,external_wp_widgets_namespaceObject.getWidgetIdFromBlock)(block);
const oldWidget = widgets[widgetId];
const widget = transformBlockToWidget(block, oldWidget); // We'll replace the null widgetId after save, but we track it here
// since order is important.
sidebarWidgetsIds.push(widgetId); // Check oldWidget as widgetId might refer to an ID which has been
// deleted, e.g. if a deleted block is restored via undo after saving.
if (oldWidget) {
// Update an existing widget.
registry.dispatch(external_wp_coreData_namespaceObject.store).editEntityRecord('root', 'widget', widgetId, { ...widget,
sidebar: widgetAreaId
}, {
undoIgnore: true
});
const hasEdits = registry.select(external_wp_coreData_namespaceObject.store).hasEditsForEntityRecord('root', 'widget', widgetId);
if (!hasEdits) {
continue;
}
batchTasks.push(_ref6 => {
let {
saveEditedEntityRecord
} = _ref6;
return saveEditedEntityRecord('root', 'widget', widgetId);
});
} else {
// Create a new widget.
batchTasks.push(_ref7 => {
let {
saveEntityRecord
} = _ref7;
return saveEntityRecord('root', 'widget', { ...widget,
sidebar: widgetAreaId
});
});
}
batchMeta.push({
block,
position: i,
clientId: block.clientId
});
}
for (const widget of deletedWidgets) {
batchTasks.push(_ref8 => {
let {
deleteEntityRecord
} = _ref8;
return deleteEntityRecord('root', 'widget', widget.id, {
force: true
});
});
}
const records = await registry.dispatch(external_wp_coreData_namespaceObject.store).__experimentalBatch(batchTasks);
const preservedRecords = records.filter(record => !record.hasOwnProperty('deleted'));
const failedWidgetNames = [];
for (let i = 0; i < preservedRecords.length; i++) {
const widget = preservedRecords[i];
const {
block,
position
} = batchMeta[i]; // Set __internalWidgetId on the block. This will be persisted to the
// store when we dispatch receiveEntityRecords( post ) below.
post.blocks[position].attributes.__internalWidgetId = widget.id;
const error = registry.select(external_wp_coreData_namespaceObject.store).getLastEntitySaveError('root', 'widget', widget.id);
if (error) {
var _block$attributes;
failedWidgetNames.push(((_block$attributes = block.attributes) === null || _block$attributes === void 0 ? void 0 : _block$attributes.name) || (block === null || block === void 0 ? void 0 : block.name));
}
if (!sidebarWidgetsIds[position]) {
sidebarWidgetsIds[position] = widget.id;
}
}
if (failedWidgetNames.length) {
throw new Error((0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: List of widget names */
(0,external_wp_i18n_namespaceObject.__)('Could not save the following widgets: %s.'), failedWidgetNames.join(', ')));
}
registry.dispatch(external_wp_coreData_namespaceObject.store).editEntityRecord(KIND, WIDGET_AREA_ENTITY_TYPE, widgetAreaId, {
widgets: sidebarWidgetsIds
}, {
undoIgnore: true
});
dispatch(trySaveWidgetArea(widgetAreaId));
registry.dispatch(external_wp_coreData_namespaceObject.store).receiveEntityRecords(KIND, POST_TYPE, post, undefined);
};
const trySaveWidgetArea = widgetAreaId => _ref9 => {
let {
registry
} = _ref9;
registry.dispatch(external_wp_coreData_namespaceObject.store).saveEditedEntityRecord(KIND, WIDGET_AREA_ENTITY_TYPE, widgetAreaId, {
throwOnError: true
});
};
/**
* Sets the clientId stored for a particular widgetId.
*
* @param {number} clientId Client id.
* @param {number} widgetId Widget id.
*
* @return {Object} Action.
*/
function setWidgetIdForClientId(clientId, widgetId) {
return {
type: 'SET_WIDGET_ID_FOR_CLIENT_ID',
clientId,
widgetId
};
}
/**
* Sets the open state of all the widget areas.
*
* @param {Object} widgetAreasOpenState The open states of all the widget areas.
*
* @return {Object} Action.
*/
function setWidgetAreasOpenState(widgetAreasOpenState) {
return {
type: 'SET_WIDGET_AREAS_OPEN_STATE',
widgetAreasOpenState
};
}
/**
* Sets the open state of the widget area.
*
* @param {string} clientId The clientId of the widget area.
* @param {boolean} isOpen Whether the widget area should be opened.
*
* @return {Object} Action.
*/
function setIsWidgetAreaOpen(clientId, isOpen) {
return {
type: 'SET_IS_WIDGET_AREA_OPEN',
clientId,
isOpen
};
}
/**
* Returns an action object used to open/close the inserter.
*
* @param {boolean|Object} value Whether the inserter should be
* opened (true) or closed (false).
* To specify an insertion point,
* use an object.
* @param {string} value.rootClientId The root client ID to insert at.
* @param {number} value.insertionIndex The index to insert at.
*
* @return {Object} Action object.
*/
function setIsInserterOpened(value) {
return {
type: 'SET_IS_INSERTER_OPENED',
value
};
}
/**
* Returns an action object used to open/close the list view.
*
* @param {boolean} isOpen A boolean representing whether the list view should be opened or closed.
* @return {Object} Action object.
*/
function setIsListViewOpened(isOpen) {
return {
type: 'SET_IS_LIST_VIEW_OPENED',
isOpen
};
}
/**
* Returns an action object signalling that the user closed the sidebar.
*
* @return {Object} Action creator.
*/
const closeGeneralSidebar = () => _ref10 => {
let {
registry
} = _ref10;
registry.dispatch(store).disableComplementaryArea(constants_STORE_NAME);
};
/**
* Action that handles moving a block between widget areas
*
* @param {string} clientId The clientId of the block to move.
* @param {string} widgetAreaId The id of the widget area to move the block to.
*/
const moveBlockToWidgetArea = (clientId, widgetAreaId) => async _ref11 => {
let {
dispatch,
select,
registry
} = _ref11;
const sourceRootClientId = registry.select(external_wp_blockEditor_namespaceObject.store).getBlockRootClientId(clientId); // Search the top level blocks (widget areas) for the one with the matching
// id attribute. Makes the assumption that all top-level blocks are widget
// areas.
const widgetAreas = registry.select(external_wp_blockEditor_namespaceObject.store).getBlocks();
const destinationWidgetAreaBlock = widgetAreas.find(_ref12 => {
let {
attributes
} = _ref12;
return attributes.id === widgetAreaId;
});
const destinationRootClientId = destinationWidgetAreaBlock.clientId; // Get the index for moving to the end of the destination widget area.
const destinationInnerBlocksClientIds = registry.select(external_wp_blockEditor_namespaceObject.store).getBlockOrder(destinationRootClientId);
const destinationIndex = destinationInnerBlocksClientIds.length; // Reveal the widget area, if it's not open.
const isDestinationWidgetAreaOpen = select.getIsWidgetAreaOpen(destinationRootClientId);
if (!isDestinationWidgetAreaOpen) {
dispatch.setIsWidgetAreaOpen(destinationRootClientId, true);
} // Move the block.
registry.dispatch(external_wp_blockEditor_namespaceObject.store).moveBlocksToPosition([clientId], sourceRootClientId, destinationRootClientId, destinationIndex);
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/store/resolvers.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Creates a "stub" widgets post reflecting all available widget areas. The
* post is meant as a convenient to only exists in runtime and should never be saved. It
* enables a convenient way of editing the widgets by using a regular post editor.
*
* Fetches all widgets from all widgets aras, converts them into blocks, and hydrates a new post with them.
*
* @return {Function} An action creator.
*/
const getWidgetAreas = () => async _ref => {
let {
dispatch,
registry
} = _ref;
const query = buildWidgetAreasQuery();
const widgetAreas = await registry.resolveSelect(external_wp_coreData_namespaceObject.store).getEntityRecords(KIND, WIDGET_AREA_ENTITY_TYPE, query);
const widgetAreaBlocks = [];
const sortedWidgetAreas = widgetAreas.sort((a, b) => {
if (a.id === 'wp_inactive_widgets') {
return 1;
}
if (b.id === 'wp_inactive_widgets') {
return -1;
}
return 0;
});
for (const widgetArea of sortedWidgetAreas) {
widgetAreaBlocks.push((0,external_wp_blocks_namespaceObject.createBlock)('core/widget-area', {
id: widgetArea.id,
name: widgetArea.name
}));
if (!widgetArea.widgets.length) {
// If this widget area has no widgets, it won't get a post setup by
// the getWidgets resolver.
dispatch(persistStubPost(buildWidgetAreaPostId(widgetArea.id), []));
}
}
const widgetAreasOpenState = {};
widgetAreaBlocks.forEach((widgetAreaBlock, index) => {
// Defaults to open the first widget area.
widgetAreasOpenState[widgetAreaBlock.clientId] = index === 0;
});
dispatch(setWidgetAreasOpenState(widgetAreasOpenState));
dispatch(persistStubPost(buildWidgetAreasPostId(), widgetAreaBlocks));
};
/**
* Fetches all widgets from all widgets ares, and groups them by widget area Id.
*
* @return {Function} An action creator.
*/
const getWidgets = () => async _ref2 => {
let {
dispatch,
registry
} = _ref2;
const query = buildWidgetsQuery();
const widgets = await registry.resolveSelect(external_wp_coreData_namespaceObject.store).getEntityRecords('root', 'widget', query);
const groupedBySidebar = {};
for (const widget of widgets) {
const block = transformWidgetToBlock(widget);
groupedBySidebar[widget.sidebar] = groupedBySidebar[widget.sidebar] || [];
groupedBySidebar[widget.sidebar].push(block);
}
for (const sidebarId in groupedBySidebar) {
if (groupedBySidebar.hasOwnProperty(sidebarId)) {
// Persist the actual post containing the widget block
dispatch(persistStubPost(buildWidgetAreaPostId(sidebarId), groupedBySidebar[sidebarId]));
}
}
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/store/selectors.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Returns all API widgets.
*
* @return {Object[]} API List of widgets.
*/
const selectors_getWidgets = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => () => {
const widgets = select(external_wp_coreData_namespaceObject.store).getEntityRecords('root', 'widget', buildWidgetsQuery());
return (// Key widgets by their ID.
(widgets === null || widgets === void 0 ? void 0 : widgets.reduce((allWidgets, widget) => ({ ...allWidgets,
[widget.id]: widget
}), {})) || {}
);
});
/**
* Returns API widget data for a particular widget ID.
*
* @param {number} id Widget ID.
*
* @return {Object} API widget data for a particular widget ID.
*/
const getWidget = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (state, id) => {
const widgets = select(constants_STORE_NAME).getWidgets();
return widgets[id];
});
/**
* Returns all API widget areas.
*
* @return {Object[]} API List of widget areas.
*/
const selectors_getWidgetAreas = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => () => {
const query = buildWidgetAreasQuery();
return select(external_wp_coreData_namespaceObject.store).getEntityRecords(KIND, WIDGET_AREA_ENTITY_TYPE, query);
});
/**
* Returns widgetArea containing a block identify by given widgetId
*
* @param {string} widgetId The ID of the widget.
* @return {Object} Containing widget area.
*/
const getWidgetAreaForWidgetId = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (state, widgetId) => {
const widgetAreas = select(constants_STORE_NAME).getWidgetAreas();
return widgetAreas.find(widgetArea => {
const post = select(external_wp_coreData_namespaceObject.store).getEditedEntityRecord(KIND, POST_TYPE, buildWidgetAreaPostId(widgetArea.id));
const blockWidgetIds = post.blocks.map(block => (0,external_wp_widgets_namespaceObject.getWidgetIdFromBlock)(block));
return blockWidgetIds.includes(widgetId);
});
});
/**
* Given a child client id, returns the parent widget area block.
*
* @param {string} clientId The client id of a block in a widget area.
*
* @return {WPBlock} The widget area block.
*/
const getParentWidgetAreaBlock = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (state, clientId) => {
const {
getBlock,
getBlockName,
getBlockParents
} = select(external_wp_blockEditor_namespaceObject.store);
const blockParents = getBlockParents(clientId);
const widgetAreaClientId = blockParents.find(parentClientId => getBlockName(parentClientId) === 'core/widget-area');
return getBlock(widgetAreaClientId);
});
/**
* Returns all edited widget area entity records.
*
* @return {Object[]} List of edited widget area entity records.
*/
const getEditedWidgetAreas = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (state, ids) => {
let widgetAreas = select(constants_STORE_NAME).getWidgetAreas();
if (!widgetAreas) {
return [];
}
if (ids) {
widgetAreas = widgetAreas.filter(_ref => {
let {
id
} = _ref;
return ids.includes(id);
});
}
return widgetAreas.filter(_ref2 => {
let {
id
} = _ref2;
return select(external_wp_coreData_namespaceObject.store).hasEditsForEntityRecord(KIND, POST_TYPE, buildWidgetAreaPostId(id));
}).map(_ref3 => {
let {
id
} = _ref3;
return select(external_wp_coreData_namespaceObject.store).getEditedEntityRecord(KIND, WIDGET_AREA_ENTITY_TYPE, id);
});
});
/**
* Returns all blocks representing reference widgets.
*
* @param {string} referenceWidgetName Optional. If given, only reference widgets with this name will be returned.
* @return {Array} List of all blocks representing reference widgets
*/
const getReferenceWidgetBlocks = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => function (state) {
let referenceWidgetName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
const results = [];
const widgetAreas = select(constants_STORE_NAME).getWidgetAreas();
for (const _widgetArea of widgetAreas) {
const post = select(external_wp_coreData_namespaceObject.store).getEditedEntityRecord(KIND, POST_TYPE, buildWidgetAreaPostId(_widgetArea.id));
for (const block of post.blocks) {
var _block$attributes;
if (block.name === 'core/legacy-widget' && (!referenceWidgetName || ((_block$attributes = block.attributes) === null || _block$attributes === void 0 ? void 0 : _block$attributes.referenceWidgetName) === referenceWidgetName)) {
results.push(block);
}
}
}
return results;
});
/**
* Returns true if any widget area is currently being saved.
*
* @return {boolean} True if any widget area is currently being saved. False otherwise.
*/
const isSavingWidgetAreas = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => () => {
var _select$getWidgetArea;
const widgetAreasIds = (_select$getWidgetArea = select(constants_STORE_NAME).getWidgetAreas()) === null || _select$getWidgetArea === void 0 ? void 0 : _select$getWidgetArea.map(_ref4 => {
let {
id
} = _ref4;
return id;
});
if (!widgetAreasIds) {
return false;
}
for (const id of widgetAreasIds) {
const isSaving = select(external_wp_coreData_namespaceObject.store).isSavingEntityRecord(KIND, WIDGET_AREA_ENTITY_TYPE, id);
if (isSaving) {
return true;
}
}
const widgetIds = [...Object.keys(select(constants_STORE_NAME).getWidgets()), undefined // account for new widgets without an ID
];
for (const id of widgetIds) {
const isSaving = select(external_wp_coreData_namespaceObject.store).isSavingEntityRecord('root', 'widget', id);
if (isSaving) {
return true;
}
}
return false;
});
/**
* Gets whether the widget area is opened.
*
* @param {Array} state The open state of the widget areas.
* @param {string} clientId The clientId of the widget area.
*
* @return {boolean} True if the widget area is open.
*/
const getIsWidgetAreaOpen = (state, clientId) => {
const {
widgetAreasOpenState
} = state;
return !!widgetAreasOpenState[clientId];
};
/**
* Returns true if the inserter is opened.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the inserter is opened.
*/
function isInserterOpened(state) {
return !!state.blockInserterPanel;
}
/**
* Get the insertion point for the inserter.
*
* @param {Object} state Global application state.
*
* @return {Object} The root client ID and index to insert at.
*/
function __experimentalGetInsertionPoint(state) {
const {
rootClientId,
insertionIndex
} = state.blockInserterPanel;
return {
rootClientId,
insertionIndex
};
}
/**
* Returns true if a block can be inserted into a widget area.
*
* @param {Array} state The open state of the widget areas.
* @param {string} blockName The name of the block being inserted.
*
* @return {boolean} True if the block can be inserted in a widget area.
*/
const canInsertBlockInWidgetArea = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (state, blockName) => {
// Widget areas are always top-level blocks, which getBlocks will return.
const widgetAreas = select(external_wp_blockEditor_namespaceObject.store).getBlocks(); // Makes an assumption that a block that can be inserted into one
// widget area can be inserted into any widget area. Uses the first
// widget area for testing whether the block can be inserted.
const [firstWidgetArea] = widgetAreas;
return select(external_wp_blockEditor_namespaceObject.store).canInsertBlockType(blockName, firstWidgetArea.clientId);
});
/**
* Returns true if the list view is opened.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the list view is opened.
*/
function isListViewOpened(state) {
return state.listViewPanel;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/store/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Block editor data store configuration.
*
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/data/README.md#register
*
* @type {Object}
*/
const storeConfig = {
reducer: reducer,
selectors: store_selectors_namespaceObject,
resolvers: resolvers_namespaceObject,
actions: store_actions_namespaceObject
};
/**
* Store definition for the edit widgets namespace.
*
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/data/README.md#createReduxStore
*
* @type {Object}
*/
const store_store = (0,external_wp_data_namespaceObject.createReduxStore)(constants_STORE_NAME, storeConfig);
(0,external_wp_data_namespaceObject.register)(store_store); // This package uses a few in-memory post types as wrappers for convenience.
// This middleware prevents any network requests related to these types as they are
// bound to fail anyway.
external_wp_apiFetch_default().use(function (options, next) {
var _options$path;
if (((_options$path = options.path) === null || _options$path === void 0 ? void 0 : _options$path.indexOf('/wp/v2/types/widget-area')) === 0) {
return Promise.resolve({});
}
return next(options);
});
;// CONCATENATED MODULE: external ["wp","hooks"]
var external_wp_hooks_namespaceObject = window["wp"]["hooks"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/filters/move-to-widget-area.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const withMoveToWidgetAreaToolbarItem = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(BlockEdit => props => {
const {
clientId,
name: blockName
} = props;
const {
widgetAreas,
currentWidgetAreaId,
canInsertBlockInWidgetArea
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _widgetAreaBlock$attr;
// Component won't display for a widget area, so don't run selectors.
if (blockName === 'core/widget-area') {
return {};
}
const selectors = select(store_store);
const widgetAreaBlock = selectors.getParentWidgetAreaBlock(clientId);
return {
widgetAreas: selectors.getWidgetAreas(),
currentWidgetAreaId: widgetAreaBlock === null || widgetAreaBlock === void 0 ? void 0 : (_widgetAreaBlock$attr = widgetAreaBlock.attributes) === null || _widgetAreaBlock$attr === void 0 ? void 0 : _widgetAreaBlock$attr.id,
canInsertBlockInWidgetArea: selectors.canInsertBlockInWidgetArea(blockName)
};
}, [clientId, blockName]);
const {
moveBlockToWidgetArea
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const hasMultipleWidgetAreas = (widgetAreas === null || widgetAreas === void 0 ? void 0 : widgetAreas.length) > 1;
const isMoveToWidgetAreaVisible = blockName !== 'core/widget-area' && hasMultipleWidgetAreas && canInsertBlockInWidgetArea;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(BlockEdit, props), isMoveToWidgetAreaVisible && (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockControls, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_widgets_namespaceObject.MoveToWidgetArea, {
widgetAreas: widgetAreas,
currentWidgetAreaId: currentWidgetAreaId,
onSelect: widgetAreaId => {
moveBlockToWidgetArea(props.clientId, widgetAreaId);
}
})));
}, 'withMoveToWidgetAreaToolbarItem');
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockEdit', 'core/edit-widgets/block-edit', withMoveToWidgetAreaToolbarItem);
;// CONCATENATED MODULE: external ["wp","mediaUtils"]
var external_wp_mediaUtils_namespaceObject = window["wp"]["mediaUtils"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/filters/replace-media-upload.js
/**
* WordPress dependencies
*/
const replaceMediaUpload = () => external_wp_mediaUtils_namespaceObject.MediaUpload;
(0,external_wp_hooks_namespaceObject.addFilter)('editor.MediaUpload', 'core/edit-widgets/replace-media-upload', replaceMediaUpload);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/filters/index.js
/**
* Internal dependencies
*/
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/blocks/widget-area/edit/use-is-dragging-within.js
/**
* WordPress dependencies
*/
/** @typedef {import('@wordpress/element').RefObject} RefObject */
/**
* A React hook to determine if it's dragging within the target element.
*
* @param {RefObject<HTMLElement>} elementRef The target elementRef object.
*
* @return {boolean} Is dragging within the target element.
*/
const useIsDraggingWithin = elementRef => {
const [isDraggingWithin, setIsDraggingWithin] = (0,external_wp_element_namespaceObject.useState)(false);
(0,external_wp_element_namespaceObject.useEffect)(() => {
const {
ownerDocument
} = elementRef.current;
function handleDragStart(event) {
// Check the first time when the dragging starts.
handleDragEnter(event);
} // Set to false whenever the user cancel the drag event by either releasing the mouse or press Escape.
function handleDragEnd() {
setIsDraggingWithin(false);
}
function handleDragEnter(event) {
// Check if the current target is inside the item element.
if (elementRef.current.contains(event.target)) {
setIsDraggingWithin(true);
} else {
setIsDraggingWithin(false);
}
} // Bind these events to the document to catch all drag events.
// Ideally, we can also use `event.relatedTarget`, but sadly that doesn't work in Safari.
ownerDocument.addEventListener('dragstart', handleDragStart);
ownerDocument.addEventListener('dragend', handleDragEnd);
ownerDocument.addEventListener('dragenter', handleDragEnter);
return () => {
ownerDocument.removeEventListener('dragstart', handleDragStart);
ownerDocument.removeEventListener('dragend', handleDragEnd);
ownerDocument.removeEventListener('dragenter', handleDragEnter);
};
}, []);
return isDraggingWithin;
};
/* harmony default export */ var use_is_dragging_within = (useIsDraggingWithin);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/blocks/widget-area/edit/inner-blocks.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function WidgetAreaInnerBlocks(_ref) {
let {
id
} = _ref;
const [blocks, onInput, onChange] = (0,external_wp_coreData_namespaceObject.useEntityBlockEditor)('root', 'postType');
const innerBlocksRef = (0,external_wp_element_namespaceObject.useRef)();
const isDraggingWithinInnerBlocks = use_is_dragging_within(innerBlocksRef);
const shouldHighlightDropZone = isDraggingWithinInnerBlocks; // Using the experimental hook so that we can control the className of the element.
const innerBlocksProps = (0,external_wp_blockEditor_namespaceObject.useInnerBlocksProps)({
ref: innerBlocksRef
}, {
value: blocks,
onInput,
onChange,
templateLock: false,
renderAppender: external_wp_blockEditor_namespaceObject.InnerBlocks.ButtonBlockAppender
});
return (0,external_wp_element_namespaceObject.createElement)("div", {
"data-widget-area-id": id,
className: classnames_default()('wp-block-widget-area__inner-blocks block-editor-inner-blocks editor-styles-wrapper', {
'wp-block-widget-area__highlight-drop-zone': shouldHighlightDropZone
})
}, (0,external_wp_element_namespaceObject.createElement)("div", innerBlocksProps));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/blocks/widget-area/edit/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/** @typedef {import('@wordpress/element').RefObject} RefObject */
function WidgetAreaEdit(_ref) {
let {
clientId,
className,
attributes: {
id,
name
}
} = _ref;
const isOpen = (0,external_wp_data_namespaceObject.useSelect)(select => select(store_store).getIsWidgetAreaOpen(clientId), [clientId]);
const {
setIsWidgetAreaOpen
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const wrapper = (0,external_wp_element_namespaceObject.useRef)();
const setOpen = (0,external_wp_element_namespaceObject.useCallback)(openState => setIsWidgetAreaOpen(clientId, openState), [clientId]);
const isDragging = useIsDragging(wrapper);
const isDraggingWithin = use_is_dragging_within(wrapper);
const [openedWhileDragging, setOpenedWhileDragging] = (0,external_wp_element_namespaceObject.useState)(false);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (!isDragging) {
setOpenedWhileDragging(false);
return;
}
if (isDraggingWithin && !isOpen) {
setOpen(true);
setOpenedWhileDragging(true);
} else if (!isDraggingWithin && isOpen && openedWhileDragging) {
setOpen(false);
}
}, [isOpen, isDragging, isDraggingWithin, openedWhileDragging]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Panel, {
className: className,
ref: wrapper
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelBody, {
title: name,
opened: isOpen,
onToggle: () => {
setIsWidgetAreaOpen(clientId, !isOpen);
},
scrollAfterOpen: !isDragging
}, _ref2 => {
let {
opened
} = _ref2;
return (// This is required to ensure LegacyWidget blocks are not
// unmounted when the panel is collapsed. Unmounting legacy
// widgets may have unintended consequences (e.g. TinyMCE
// not being properly reinitialized)
(0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableDisclosureContent, {
className: "wp-block-widget-area__panel-body-content",
visible: opened
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_coreData_namespaceObject.EntityProvider, {
kind: "root",
type: "postType",
id: `widget-area-${id}`
}, (0,external_wp_element_namespaceObject.createElement)(WidgetAreaInnerBlocks, {
id: id
})))
);
}));
}
/**
* A React hook to determine if dragging is active.
*
* @param {RefObject<HTMLElement>} elementRef The target elementRef object.
*
* @return {boolean} Is dragging within the entire document.
*/
const useIsDragging = elementRef => {
const [isDragging, setIsDragging] = (0,external_wp_element_namespaceObject.useState)(false);
(0,external_wp_element_namespaceObject.useEffect)(() => {
const {
ownerDocument
} = elementRef.current;
function handleDragStart() {
setIsDragging(true);
}
function handleDragEnd() {
setIsDragging(false);
}
ownerDocument.addEventListener('dragstart', handleDragStart);
ownerDocument.addEventListener('dragend', handleDragEnd);
return () => {
ownerDocument.removeEventListener('dragstart', handleDragStart);
ownerDocument.removeEventListener('dragend', handleDragEnd);
};
}, []);
return isDragging;
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/blocks/widget-area/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const metadata = {
name: "core/widget-area",
category: "widgets",
attributes: {
id: {
type: "string"
},
name: {
type: "string"
}
},
supports: {
html: false,
inserter: false,
customClassName: false,
reusable: false,
__experimentalToolbar: false,
__experimentalParentSelector: false,
__experimentalDisableBlockOverlay: true
},
editorStyle: "wp-block-widget-area-editor",
style: "wp-block-widget-area"
};
const {
name: widget_area_name
} = metadata;
const settings = {
title: (0,external_wp_i18n_namespaceObject.__)('Widget Area'),
description: (0,external_wp_i18n_namespaceObject.__)('A widget area container.'),
__experimentalLabel: _ref => {
let {
name: label
} = _ref;
return label;
},
edit: WidgetAreaEdit
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/error-boundary/index.js
/**
* WordPress dependencies
*/
function CopyButton(_ref) {
let {
text,
children
} = _ref;
const ref = (0,external_wp_compose_namespaceObject.useCopyToClipboard)(text);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "secondary",
ref: ref
}, children);
}
function ErrorBoundaryWarning(_ref2) {
let {
message,
error
} = _ref2;
const actions = [(0,external_wp_element_namespaceObject.createElement)(CopyButton, {
key: "copy-error",
text: error.stack
}, (0,external_wp_i18n_namespaceObject.__)('Copy Error'))];
return (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.Warning, {
className: "edit-widgets-error-boundary",
actions: actions
}, message);
}
class ErrorBoundary extends external_wp_element_namespaceObject.Component {
constructor() {
super(...arguments);
this.state = {
error: null
};
}
componentDidCatch(error) {
(0,external_wp_hooks_namespaceObject.doAction)('editor.ErrorBoundary.errorLogged', error);
}
static getDerivedStateFromError(error) {
return {
error
};
}
render() {
if (!this.state.error) {
return this.props.children;
}
return (0,external_wp_element_namespaceObject.createElement)(ErrorBoundaryWarning, {
message: (0,external_wp_i18n_namespaceObject.__)('The editor has encountered an unexpected error.'),
error: this.state.error
});
}
}
;// CONCATENATED MODULE: external ["wp","reusableBlocks"]
var external_wp_reusableBlocks_namespaceObject = window["wp"]["reusableBlocks"];
;// CONCATENATED MODULE: external ["wp","keyboardShortcuts"]
var external_wp_keyboardShortcuts_namespaceObject = window["wp"]["keyboardShortcuts"];
;// CONCATENATED MODULE: external ["wp","keycodes"]
var external_wp_keycodes_namespaceObject = window["wp"]["keycodes"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/keyboard-shortcuts/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function KeyboardShortcuts() {
const {
redo,
undo
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_coreData_namespaceObject.store);
const {
saveEditedWidgetAreas
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
(0,external_wp_keyboardShortcuts_namespaceObject.useShortcut)('core/edit-widgets/undo', event => {
undo();
event.preventDefault();
});
(0,external_wp_keyboardShortcuts_namespaceObject.useShortcut)('core/edit-widgets/redo', event => {
redo();
event.preventDefault();
});
(0,external_wp_keyboardShortcuts_namespaceObject.useShortcut)('core/edit-widgets/save', event => {
event.preventDefault();
saveEditedWidgetAreas();
});
return null;
}
function KeyboardShortcutsRegister() {
// Registering the shortcuts.
const {
registerShortcut
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_keyboardShortcuts_namespaceObject.store);
(0,external_wp_element_namespaceObject.useEffect)(() => {
registerShortcut({
name: 'core/edit-widgets/undo',
category: 'global',
description: (0,external_wp_i18n_namespaceObject.__)('Undo your last changes.'),
keyCombination: {
modifier: 'primary',
character: 'z'
}
});
registerShortcut({
name: 'core/edit-widgets/redo',
category: 'global',
description: (0,external_wp_i18n_namespaceObject.__)('Redo your last undo.'),
keyCombination: {
modifier: 'primaryShift',
character: 'z'
},
// Disable on Apple OS because it conflicts with the browser's
// history shortcut. It's a fine alias for both Windows and Linux.
// Since there's no conflict for Ctrl+Shift+Z on both Windows and
// Linux, we keep it as the default for consistency.
aliases: (0,external_wp_keycodes_namespaceObject.isAppleOS)() ? [] : [{
modifier: 'primary',
character: 'y'
}]
});
registerShortcut({
name: 'core/edit-widgets/save',
category: 'global',
description: (0,external_wp_i18n_namespaceObject.__)('Save your changes.'),
keyCombination: {
modifier: 'primary',
character: 's'
}
});
registerShortcut({
name: 'core/edit-widgets/keyboard-shortcuts',
category: 'main',
description: (0,external_wp_i18n_namespaceObject.__)('Display these keyboard shortcuts.'),
keyCombination: {
modifier: 'access',
character: 'h'
}
});
registerShortcut({
name: 'core/edit-widgets/next-region',
category: 'global',
description: (0,external_wp_i18n_namespaceObject.__)('Navigate to the next part of the editor.'),
keyCombination: {
modifier: 'ctrl',
character: '`'
},
aliases: [{
modifier: 'access',
character: 'n'
}]
});
registerShortcut({
name: 'core/edit-widgets/previous-region',
category: 'global',
description: (0,external_wp_i18n_namespaceObject.__)('Navigate to the previous part of the editor.'),
keyCombination: {
modifier: 'ctrlShift',
character: '`'
},
aliases: [{
modifier: 'access',
character: 'p'
}, {
modifier: 'ctrlShift',
character: '~'
}]
});
}, [registerShortcut]);
return null;
}
KeyboardShortcuts.Register = KeyboardShortcutsRegister;
/* harmony default export */ var keyboard_shortcuts = (KeyboardShortcuts);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/hooks/use-last-selected-widget-area.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* A react hook that returns the client id of the last widget area to have
* been selected, or to have a selected block within it.
*
* @return {string} clientId of the widget area last selected.
*/
const useLastSelectedWidgetArea = () => (0,external_wp_data_namespaceObject.useSelect)(select => {
var _widgetAreasPost$bloc;
const {
getBlockSelectionEnd,
getBlockName
} = select(external_wp_blockEditor_namespaceObject.store);
const selectionEndClientId = getBlockSelectionEnd(); // If the selected block is a widget area, return its clientId.
if (getBlockName(selectionEndClientId) === 'core/widget-area') {
return selectionEndClientId;
}
const {
getParentWidgetAreaBlock
} = select(store_store);
const widgetAreaBlock = getParentWidgetAreaBlock(selectionEndClientId);
const widgetAreaBlockClientId = widgetAreaBlock === null || widgetAreaBlock === void 0 ? void 0 : widgetAreaBlock.clientId;
if (widgetAreaBlockClientId) {
return widgetAreaBlockClientId;
} // If no widget area has been selected, return the clientId of the first
// area.
const {
getEntityRecord
} = select(external_wp_coreData_namespaceObject.store);
const widgetAreasPost = getEntityRecord(KIND, POST_TYPE, buildWidgetAreasPostId());
return widgetAreasPost === null || widgetAreasPost === void 0 ? void 0 : (_widgetAreasPost$bloc = widgetAreasPost.blocks[0]) === null || _widgetAreasPost$bloc === void 0 ? void 0 : _widgetAreasPost$bloc.clientId;
}, []);
/* harmony default export */ var use_last_selected_widget_area = (useLastSelectedWidgetArea);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/constants.js
const ALLOW_REUSABLE_BLOCKS = false;
const ENABLE_EXPERIMENTAL_FSE_BLOCKS = false;
;// CONCATENATED MODULE: external ["wp","privateApis"]
var external_wp_privateApis_namespaceObject = window["wp"]["privateApis"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/private-apis.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/edit-widgets');
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/widget-areas-block-editor-provider/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const {
ExperimentalBlockEditorProvider
} = unlock(external_wp_blockEditor_namespaceObject.privateApis);
function WidgetAreasBlockEditorProvider(_ref) {
let {
blockEditorSettings,
children,
...props
} = _ref;
const mediaPermissions = (0,external_wp_coreData_namespaceObject.useResourcePermissions)('media');
const {
reusableBlocks,
isFixedToolbarActive,
keepCaretInsideBlock
} = (0,external_wp_data_namespaceObject.useSelect)(select => ({
widgetAreas: select(store_store).getWidgetAreas(),
widgets: select(store_store).getWidgets(),
reusableBlocks: ALLOW_REUSABLE_BLOCKS ? select(external_wp_coreData_namespaceObject.store).getEntityRecords('postType', 'wp_block') : [],
isFixedToolbarActive: !!select(external_wp_preferences_namespaceObject.store).get('core/edit-widgets', 'fixedToolbar'),
keepCaretInsideBlock: !!select(external_wp_preferences_namespaceObject.store).get('core/edit-widgets', 'keepCaretInsideBlock')
}), []);
const {
setIsInserterOpened
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const settings = (0,external_wp_element_namespaceObject.useMemo)(() => {
let mediaUploadBlockEditor;
if (mediaPermissions.canCreate) {
mediaUploadBlockEditor = _ref2 => {
let {
onError,
...argumentsObject
} = _ref2;
(0,external_wp_mediaUtils_namespaceObject.uploadMedia)({
wpAllowedMimeTypes: blockEditorSettings.allowedMimeTypes,
onError: _ref3 => {
let {
message
} = _ref3;
return onError(message);
},
...argumentsObject
});
};
}
return { ...blockEditorSettings,
__experimentalReusableBlocks: reusableBlocks,
hasFixedToolbar: isFixedToolbarActive,
keepCaretInsideBlock,
mediaUpload: mediaUploadBlockEditor,
templateLock: 'all',
__experimentalSetIsInserterOpened: setIsInserterOpened
};
}, [blockEditorSettings, isFixedToolbarActive, keepCaretInsideBlock, mediaPermissions.canCreate, reusableBlocks, setIsInserterOpened]);
const widgetAreaId = use_last_selected_widget_area();
const [blocks, onInput, onChange] = (0,external_wp_coreData_namespaceObject.useEntityBlockEditor)(KIND, POST_TYPE, {
id: buildWidgetAreasPostId()
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_keyboardShortcuts_namespaceObject.ShortcutProvider, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockEditorKeyboardShortcuts.Register, null), (0,external_wp_element_namespaceObject.createElement)(keyboard_shortcuts.Register, null), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SlotFillProvider, null, (0,external_wp_element_namespaceObject.createElement)(ExperimentalBlockEditorProvider, _extends({
value: blocks,
onInput: onInput,
onChange: onChange,
settings: settings,
useSubRegistry: false
}, props), (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.CopyHandler, null, children), (0,external_wp_element_namespaceObject.createElement)(external_wp_reusableBlocks_namespaceObject.ReusableBlocksMenuItems, {
rootClientId: widgetAreaId
}))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/cog.js
/**
* WordPress dependencies
*/
const cog = (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, {
fillRule: "evenodd",
d: "M10.289 4.836A1 1 0 0111.275 4h1.306a1 1 0 01.987.836l.244 1.466c.787.26 1.503.679 2.108 1.218l1.393-.522a1 1 0 011.216.437l.653 1.13a1 1 0 01-.23 1.273l-1.148.944a6.025 6.025 0 010 2.435l1.149.946a1 1 0 01.23 1.272l-.653 1.13a1 1 0 01-1.216.437l-1.394-.522c-.605.54-1.32.958-2.108 1.218l-.244 1.466a1 1 0 01-.987.836h-1.306a1 1 0 01-.986-.836l-.244-1.466a5.995 5.995 0 01-2.108-1.218l-1.394.522a1 1 0 01-1.217-.436l-.653-1.131a1 1 0 01.23-1.272l1.149-.946a6.026 6.026 0 010-2.435l-1.148-.944a1 1 0 01-.23-1.272l.653-1.131a1 1 0 011.217-.437l1.393.522a5.994 5.994 0 012.108-1.218l.244-1.466zM14.929 12a3 3 0 11-6 0 3 3 0 016 0z",
clipRule: "evenodd"
}));
/* harmony default export */ var library_cog = (cog);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/block-default.js
/**
* WordPress dependencies
*/
const blockDefault = (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 8h-1V6h-5v2h-2V6H6v2H5c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-8c0-1.1-.9-2-2-2zm.5 10c0 .3-.2.5-.5.5H5c-.3 0-.5-.2-.5-.5v-8c0-.3.2-.5.5-.5h14c.3 0 .5.2.5.5v8z"
}));
/* harmony default export */ var block_default = (blockDefault);
;// CONCATENATED MODULE: external ["wp","url"]
var external_wp_url_namespaceObject = window["wp"]["url"];
;// CONCATENATED MODULE: external ["wp","dom"]
var external_wp_dom_namespaceObject = window["wp"]["dom"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/sidebar/widget-areas.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function WidgetAreas(_ref) {
let {
selectedWidgetAreaId
} = _ref;
const widgetAreas = (0,external_wp_data_namespaceObject.useSelect)(select => select(store_store).getWidgetAreas(), []);
const selectedWidgetArea = (0,external_wp_element_namespaceObject.useMemo)(() => selectedWidgetAreaId && (widgetAreas === null || widgetAreas === void 0 ? void 0 : widgetAreas.find(widgetArea => widgetArea.id === selectedWidgetAreaId)), [selectedWidgetAreaId, widgetAreas]);
let description;
if (!selectedWidgetArea) {
description = (0,external_wp_i18n_namespaceObject.__)('Widget Areas are global parts in your site’s layout that can accept blocks. These vary by theme, but are typically parts like your Sidebar or Footer.');
} else if (selectedWidgetAreaId === 'wp_inactive_widgets') {
description = (0,external_wp_i18n_namespaceObject.__)('Blocks in this Widget Area will not be displayed in your site.');
} else {
description = selectedWidgetArea.description;
}
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-widgets-widget-areas"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-widgets-widget-areas__top-container"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockIcon, {
icon: block_default
}), (0,external_wp_element_namespaceObject.createElement)("div", null, (0,external_wp_element_namespaceObject.createElement)("p", {
// Use `dangerouslySetInnerHTML` to keep backwards
// compatibility. Basic markup in the description is an
// established feature of WordPress.
// @see https://github.com/WordPress/gutenberg/issues/33106
dangerouslySetInnerHTML: {
__html: (0,external_wp_dom_namespaceObject.safeHTML)(description)
}
}), (widgetAreas === null || widgetAreas === void 0 ? void 0 : widgetAreas.length) === 0 && (0,external_wp_element_namespaceObject.createElement)("p", null, (0,external_wp_i18n_namespaceObject.__)('Your theme does not contain any Widget Areas.')), !selectedWidgetArea && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
href: (0,external_wp_url_namespaceObject.addQueryArgs)('customize.php', {
'autofocus[panel]': 'widgets',
return: window.location.pathname
}),
variant: "tertiary"
}, (0,external_wp_i18n_namespaceObject.__)('Manage with live preview')))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/sidebar/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
const SIDEBAR_ACTIVE_BY_DEFAULT = external_wp_element_namespaceObject.Platform.select({
web: true,
native: false
});
const BLOCK_INSPECTOR_IDENTIFIER = 'edit-widgets/block-inspector'; // Widget areas were one called block areas, so use 'edit-widgets/block-areas'
// for backwards compatibility.
const WIDGET_AREAS_IDENTIFIER = 'edit-widgets/block-areas';
/**
* Internal dependencies
*/
function ComplementaryAreaTab(_ref) {
let {
identifier,
label,
isActive
} = _ref;
const {
enableComplementaryArea
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
onClick: () => enableComplementaryArea(store_store.name, identifier),
className: classnames_default()('edit-widgets-sidebar__panel-tab', {
'is-active': isActive
}),
"aria-label": isActive ? // translators: %s: sidebar label e.g: "Widget Areas".
(0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('%s (selected)'), label) : label,
"data-label": label
}, label);
}
function Sidebar() {
const {
enableComplementaryArea
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const {
currentArea,
hasSelectedNonAreaBlock,
isGeneralSidebarOpen,
selectedWidgetAreaBlock
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getSelectedBlock,
getBlock,
getBlockParentsByBlockName
} = select(external_wp_blockEditor_namespaceObject.store);
const {
getActiveComplementaryArea
} = select(store);
const selectedBlock = getSelectedBlock();
const activeArea = getActiveComplementaryArea(store_store.name);
let currentSelection = activeArea;
if (!currentSelection) {
if (selectedBlock) {
currentSelection = BLOCK_INSPECTOR_IDENTIFIER;
} else {
currentSelection = WIDGET_AREAS_IDENTIFIER;
}
}
let widgetAreaBlock;
if (selectedBlock) {
if (selectedBlock.name === 'core/widget-area') {
widgetAreaBlock = selectedBlock;
} else {
widgetAreaBlock = getBlock(getBlockParentsByBlockName(selectedBlock.clientId, 'core/widget-area')[0]);
}
}
return {
currentArea: currentSelection,
hasSelectedNonAreaBlock: !!(selectedBlock && selectedBlock.name !== 'core/widget-area'),
isGeneralSidebarOpen: !!activeArea,
selectedWidgetAreaBlock: widgetAreaBlock
};
}, []); // currentArea, and isGeneralSidebarOpen are intentionally left out from the dependencies,
// because we want to run the effect when a block is selected/unselected and not when the sidebar state changes.
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (hasSelectedNonAreaBlock && currentArea === WIDGET_AREAS_IDENTIFIER && isGeneralSidebarOpen) {
enableComplementaryArea('core/edit-widgets', BLOCK_INSPECTOR_IDENTIFIER);
}
if (!hasSelectedNonAreaBlock && currentArea === BLOCK_INSPECTOR_IDENTIFIER && isGeneralSidebarOpen) {
enableComplementaryArea('core/edit-widgets', WIDGET_AREAS_IDENTIFIER);
}
}, [hasSelectedNonAreaBlock, enableComplementaryArea]);
return (0,external_wp_element_namespaceObject.createElement)(complementary_area, {
className: "edit-widgets-sidebar",
header: (0,external_wp_element_namespaceObject.createElement)("ul", null, (0,external_wp_element_namespaceObject.createElement)("li", null, (0,external_wp_element_namespaceObject.createElement)(ComplementaryAreaTab, {
identifier: WIDGET_AREAS_IDENTIFIER,
label: selectedWidgetAreaBlock ? selectedWidgetAreaBlock.attributes.name : (0,external_wp_i18n_namespaceObject.__)('Widget Areas'),
isActive: currentArea === WIDGET_AREAS_IDENTIFIER
})), (0,external_wp_element_namespaceObject.createElement)("li", null, (0,external_wp_element_namespaceObject.createElement)(ComplementaryAreaTab, {
identifier: BLOCK_INSPECTOR_IDENTIFIER,
label: (0,external_wp_i18n_namespaceObject.__)('Block'),
isActive: currentArea === BLOCK_INSPECTOR_IDENTIFIER
}))),
headerClassName: "edit-widgets-sidebar__panel-tabs"
/* translators: button label text should, if possible, be under 16 characters. */
,
title: (0,external_wp_i18n_namespaceObject.__)('Settings'),
closeLabel: (0,external_wp_i18n_namespaceObject.__)('Close settings'),
scope: "core/edit-widgets",
identifier: currentArea,
icon: library_cog,
isActiveByDefault: SIDEBAR_ACTIVE_BY_DEFAULT
}, currentArea === WIDGET_AREAS_IDENTIFIER && (0,external_wp_element_namespaceObject.createElement)(WidgetAreas, {
selectedWidgetAreaId: selectedWidgetAreaBlock === null || selectedWidgetAreaBlock === void 0 ? void 0 : selectedWidgetAreaBlock.attributes.id
}), currentArea === BLOCK_INSPECTOR_IDENTIFIER && (hasSelectedNonAreaBlock ? (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockInspector, null) : // Pretend that Widget Areas are part of the UI by not
// showing the Block Inspector when one is selected.
(0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-block-inspector__no-blocks"
}, (0,external_wp_i18n_namespaceObject.__)('No block selected.'))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/plus.js
/**
* WordPress dependencies
*/
const plus = (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: "M18 11.2h-5.2V6h-1.6v5.2H6v1.6h5.2V18h1.6v-5.2H18z"
}));
/* harmony default export */ var library_plus = (plus);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/list-view.js
/**
* WordPress dependencies
*/
const listView = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M13.8 5.2H3v1.5h10.8V5.2zm-3.6 12v1.5H21v-1.5H10.2zm7.2-6H6.6v1.5h10.8v-1.5z"
}));
/* harmony default export */ var list_view = (listView);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/save-button/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function SaveButton() {
const {
hasEditedWidgetAreaIds,
isSaving
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _getEditedWidgetAreas;
const {
getEditedWidgetAreas,
isSavingWidgetAreas
} = select(store_store);
return {
hasEditedWidgetAreaIds: ((_getEditedWidgetAreas = getEditedWidgetAreas()) === null || _getEditedWidgetAreas === void 0 ? void 0 : _getEditedWidgetAreas.length) > 0,
isSaving: isSavingWidgetAreas()
};
}, []);
const {
saveEditedWidgetAreas
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "primary",
isBusy: isSaving,
"aria-disabled": isSaving,
onClick: isSaving ? undefined : saveEditedWidgetAreas,
disabled: !hasEditedWidgetAreaIds
}, isSaving ? (0,external_wp_i18n_namespaceObject.__)('Saving…') : (0,external_wp_i18n_namespaceObject.__)('Update'));
}
/* harmony default export */ var save_button = (SaveButton);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/undo.js
/**
* WordPress dependencies
*/
const undo = (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: "M18.3 11.7c-.6-.6-1.4-.9-2.3-.9H6.7l2.9-3.3-1.1-1-4.5 5L8.5 16l1-1-2.7-2.7H16c.5 0 .9.2 1.3.5 1 1 1 3.4 1 4.5v.3h1.5v-.2c0-1.5 0-4.3-1.5-5.7z"
}));
/* harmony default export */ var library_undo = (undo);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/redo.js
/**
* WordPress dependencies
*/
const redo = (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: "M15.6 6.5l-1.1 1 2.9 3.3H8c-.9 0-1.7.3-2.3.9-1.4 1.5-1.4 4.2-1.4 5.6v.2h1.5v-.3c0-1.1 0-3.5 1-4.5.3-.3.7-.5 1.3-.5h9.2L14.5 15l1.1 1.1 4.6-4.6-4.6-5z"
}));
/* harmony default export */ var library_redo = (redo);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/header/undo-redo/undo.js
/**
* WordPress dependencies
*/
function UndoButton() {
const hasUndo = (0,external_wp_data_namespaceObject.useSelect)(select => select(external_wp_coreData_namespaceObject.store).hasUndo(), []);
const {
undo
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_coreData_namespaceObject.store);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
icon: !(0,external_wp_i18n_namespaceObject.isRTL)() ? library_undo : library_redo,
label: (0,external_wp_i18n_namespaceObject.__)('Undo'),
shortcut: external_wp_keycodes_namespaceObject.displayShortcut.primary('z') // If there are no undo levels we don't want to actually disable this
// button, because it will remove focus for keyboard users.
// See: https://github.com/WordPress/gutenberg/issues/3486
,
"aria-disabled": !hasUndo,
onClick: hasUndo ? undo : undefined
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/header/undo-redo/redo.js
/**
* WordPress dependencies
*/
function RedoButton() {
const shortcut = (0,external_wp_keycodes_namespaceObject.isAppleOS)() ? external_wp_keycodes_namespaceObject.displayShortcut.primaryShift('z') : external_wp_keycodes_namespaceObject.displayShortcut.primary('y');
const hasRedo = (0,external_wp_data_namespaceObject.useSelect)(select => select(external_wp_coreData_namespaceObject.store).hasRedo(), []);
const {
redo
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_coreData_namespaceObject.store);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
icon: !(0,external_wp_i18n_namespaceObject.isRTL)() ? library_redo : library_undo,
label: (0,external_wp_i18n_namespaceObject.__)('Redo'),
shortcut: shortcut // If there are no undo levels we don't want to actually disable this
// button, because it will remove focus for keyboard users.
// See: https://github.com/WordPress/gutenberg/issues/3486
,
"aria-disabled": !hasRedo,
onClick: hasRedo ? redo : undefined
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/external.js
/**
* WordPress dependencies
*/
const external = (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: "M18.2 17c0 .7-.6 1.2-1.2 1.2H7c-.7 0-1.2-.6-1.2-1.2V7c0-.7.6-1.2 1.2-1.2h3.2V4.2H7C5.5 4.2 4.2 5.5 4.2 7v10c0 1.5 1.2 2.8 2.8 2.8h10c1.5 0 2.8-1.2 2.8-2.8v-3.6h-1.5V17zM14.9 3v1.5h3.7l-6.4 6.4 1.1 1.1 6.4-6.4v3.7h1.5V3h-6.3z"
}));
/* harmony default export */ var library_external = (external);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/keyboard-shortcut-help-modal/config.js
/**
* WordPress dependencies
*/
const textFormattingShortcuts = [{
keyCombination: {
modifier: 'primary',
character: 'b'
},
description: (0,external_wp_i18n_namespaceObject.__)('Make the selected text bold.')
}, {
keyCombination: {
modifier: 'primary',
character: 'i'
},
description: (0,external_wp_i18n_namespaceObject.__)('Make the selected text italic.')
}, {
keyCombination: {
modifier: 'primary',
character: 'k'
},
description: (0,external_wp_i18n_namespaceObject.__)('Convert the selected text into a link.')
}, {
keyCombination: {
modifier: 'primaryShift',
character: 'k'
},
description: (0,external_wp_i18n_namespaceObject.__)('Remove a link.')
}, {
keyCombination: {
character: '[['
},
description: (0,external_wp_i18n_namespaceObject.__)('Insert a link to a post or page.')
}, {
keyCombination: {
modifier: 'primary',
character: 'u'
},
description: (0,external_wp_i18n_namespaceObject.__)('Underline the selected text.')
}, {
keyCombination: {
modifier: 'access',
character: 'd'
},
description: (0,external_wp_i18n_namespaceObject.__)('Strikethrough the selected text.')
}, {
keyCombination: {
modifier: 'access',
character: 'x'
},
description: (0,external_wp_i18n_namespaceObject.__)('Make the selected text inline code.')
}];
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/keyboard-shortcut-help-modal/shortcut.js
/**
* WordPress dependencies
*/
function KeyCombination(_ref) {
let {
keyCombination,
forceAriaLabel
} = _ref;
const shortcut = keyCombination.modifier ? external_wp_keycodes_namespaceObject.displayShortcutList[keyCombination.modifier](keyCombination.character) : keyCombination.character;
const ariaLabel = keyCombination.modifier ? external_wp_keycodes_namespaceObject.shortcutAriaLabel[keyCombination.modifier](keyCombination.character) : keyCombination.character;
const shortcuts = Array.isArray(shortcut) ? shortcut : [shortcut];
return (0,external_wp_element_namespaceObject.createElement)("kbd", {
className: "edit-widgets-keyboard-shortcut-help-modal__shortcut-key-combination",
"aria-label": forceAriaLabel || ariaLabel
}, shortcuts.map((character, index) => {
if (character === '+') {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, {
key: index
}, character);
}
return (0,external_wp_element_namespaceObject.createElement)("kbd", {
key: index,
className: "edit-widgets-keyboard-shortcut-help-modal__shortcut-key"
}, character);
}));
}
function Shortcut(_ref2) {
let {
description,
keyCombination,
aliases = [],
ariaLabel
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-widgets-keyboard-shortcut-help-modal__shortcut-description"
}, description), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-widgets-keyboard-shortcut-help-modal__shortcut-term"
}, (0,external_wp_element_namespaceObject.createElement)(KeyCombination, {
keyCombination: keyCombination,
forceAriaLabel: ariaLabel
}), aliases.map((alias, index) => (0,external_wp_element_namespaceObject.createElement)(KeyCombination, {
keyCombination: alias,
forceAriaLabel: ariaLabel,
key: index
}))));
}
/* harmony default export */ var keyboard_shortcut_help_modal_shortcut = (Shortcut);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/keyboard-shortcut-help-modal/dynamic-shortcut.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function DynamicShortcut(_ref) {
let {
name
} = _ref;
const {
keyCombination,
description,
aliases
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getShortcutKeyCombination,
getShortcutDescription,
getShortcutAliases
} = select(external_wp_keyboardShortcuts_namespaceObject.store);
return {
keyCombination: getShortcutKeyCombination(name),
aliases: getShortcutAliases(name),
description: getShortcutDescription(name)
};
}, [name]);
if (!keyCombination) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(keyboard_shortcut_help_modal_shortcut, {
keyCombination: keyCombination,
description: description,
aliases: aliases
});
}
/* harmony default export */ var dynamic_shortcut = (DynamicShortcut);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/keyboard-shortcut-help-modal/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const ShortcutList = _ref => {
let {
shortcuts
} = _ref;
return (
/*
* Disable reason: The `list` ARIA role is redundant but
* Safari+VoiceOver won't announce the list otherwise.
*/
/* eslint-disable jsx-a11y/no-redundant-roles */
(0,external_wp_element_namespaceObject.createElement)("ul", {
className: "edit-widgets-keyboard-shortcut-help-modal__shortcut-list",
role: "list"
}, shortcuts.map((shortcut, index) => (0,external_wp_element_namespaceObject.createElement)("li", {
className: "edit-widgets-keyboard-shortcut-help-modal__shortcut",
key: index
}, typeof shortcut === 'string' ? (0,external_wp_element_namespaceObject.createElement)(dynamic_shortcut, {
name: shortcut
}) : (0,external_wp_element_namespaceObject.createElement)(keyboard_shortcut_help_modal_shortcut, shortcut))))
/* eslint-enable jsx-a11y/no-redundant-roles */
);
};
const ShortcutSection = _ref2 => {
let {
title,
shortcuts,
className
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)("section", {
className: classnames_default()('edit-widgets-keyboard-shortcut-help-modal__section', className)
}, !!title && (0,external_wp_element_namespaceObject.createElement)("h2", {
className: "edit-widgets-keyboard-shortcut-help-modal__section-title"
}, title), (0,external_wp_element_namespaceObject.createElement)(ShortcutList, {
shortcuts: shortcuts
}));
};
const ShortcutCategorySection = _ref3 => {
let {
title,
categoryName,
additionalShortcuts = []
} = _ref3;
const categoryShortcuts = (0,external_wp_data_namespaceObject.useSelect)(select => {
return select(external_wp_keyboardShortcuts_namespaceObject.store).getCategoryShortcuts(categoryName);
}, [categoryName]);
return (0,external_wp_element_namespaceObject.createElement)(ShortcutSection, {
title: title,
shortcuts: categoryShortcuts.concat(additionalShortcuts)
});
};
function KeyboardShortcutHelpModal(_ref4) {
let {
isModalActive,
toggleModal
} = _ref4;
(0,external_wp_keyboardShortcuts_namespaceObject.useShortcut)('core/edit-widgets/keyboard-shortcuts', toggleModal, {
bindGlobal: true
});
if (!isModalActive) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Modal, {
className: "edit-widgets-keyboard-shortcut-help-modal",
title: (0,external_wp_i18n_namespaceObject.__)('Keyboard shortcuts'),
onRequestClose: toggleModal
}, (0,external_wp_element_namespaceObject.createElement)(ShortcutSection, {
className: "edit-widgets-keyboard-shortcut-help-modal__main-shortcuts",
shortcuts: ['core/edit-widgets/keyboard-shortcuts']
}), (0,external_wp_element_namespaceObject.createElement)(ShortcutCategorySection, {
title: (0,external_wp_i18n_namespaceObject.__)('Global shortcuts'),
categoryName: "global"
}), (0,external_wp_element_namespaceObject.createElement)(ShortcutCategorySection, {
title: (0,external_wp_i18n_namespaceObject.__)('Selection shortcuts'),
categoryName: "selection"
}), (0,external_wp_element_namespaceObject.createElement)(ShortcutCategorySection, {
title: (0,external_wp_i18n_namespaceObject.__)('Block shortcuts'),
categoryName: "block",
additionalShortcuts: [{
keyCombination: {
character: '/'
},
description: (0,external_wp_i18n_namespaceObject.__)('Change the block type after adding a new paragraph.'),
/* translators: The forward-slash character. e.g. '/'. */
ariaLabel: (0,external_wp_i18n_namespaceObject.__)('Forward-slash')
}]
}), (0,external_wp_element_namespaceObject.createElement)(ShortcutSection, {
title: (0,external_wp_i18n_namespaceObject.__)('Text formatting'),
shortcuts: textFormattingShortcuts
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/more-menu/tools-more-menu-group.js
/**
* WordPress dependencies
*/
const {
Fill: ToolsMoreMenuGroup,
Slot
} = (0,external_wp_components_namespaceObject.createSlotFill)('EditWidgetsToolsMoreMenuGroup');
ToolsMoreMenuGroup.Slot = _ref => {
let {
fillProps
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(Slot, {
fillProps: fillProps
}, fills => fills.length > 0 && fills);
};
/* harmony default export */ var tools_more_menu_group = (ToolsMoreMenuGroup);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/more-menu/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function MoreMenu() {
const [isKeyboardShortcutsModalActive, setIsKeyboardShortcutsModalVisible] = (0,external_wp_element_namespaceObject.useState)(false);
const toggleKeyboardShortcutsModal = () => setIsKeyboardShortcutsModalVisible(!isKeyboardShortcutsModalActive);
(0,external_wp_keyboardShortcuts_namespaceObject.useShortcut)('core/edit-widgets/keyboard-shortcuts', toggleKeyboardShortcutsModal);
const isLargeViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('medium');
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(MoreMenuDropdown, null, onClose => (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, isLargeViewport && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, {
label: (0,external_wp_i18n_namespaceObject._x)('View', 'noun')
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_preferences_namespaceObject.PreferenceToggleMenuItem, {
scope: "core/edit-widgets",
name: "fixedToolbar",
label: (0,external_wp_i18n_namespaceObject.__)('Top toolbar'),
info: (0,external_wp_i18n_namespaceObject.__)('Access all block and document tools in a single place'),
messageActivated: (0,external_wp_i18n_namespaceObject.__)('Top toolbar activated'),
messageDeactivated: (0,external_wp_i18n_namespaceObject.__)('Top toolbar deactivated')
})), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, {
label: (0,external_wp_i18n_namespaceObject.__)('Tools')
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
onClick: () => {
setIsKeyboardShortcutsModalVisible(true);
},
shortcut: external_wp_keycodes_namespaceObject.displayShortcut.access('h')
}, (0,external_wp_i18n_namespaceObject.__)('Keyboard shortcuts')), (0,external_wp_element_namespaceObject.createElement)(external_wp_preferences_namespaceObject.PreferenceToggleMenuItem, {
scope: "core/edit-widgets",
name: "welcomeGuide",
label: (0,external_wp_i18n_namespaceObject.__)('Welcome Guide')
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
role: "menuitem",
icon: library_external,
href: (0,external_wp_i18n_namespaceObject.__)('https://wordpress.org/support/article/block-based-widgets-editor/'),
target: "_blank",
rel: "noopener noreferrer"
}, (0,external_wp_i18n_namespaceObject.__)('Help'), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.VisuallyHidden, {
as: "span"
},
/* translators: accessibility text */
(0,external_wp_i18n_namespaceObject.__)('(opens in a new tab)'))), (0,external_wp_element_namespaceObject.createElement)(tools_more_menu_group.Slot, {
fillProps: {
onClose
}
})), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, {
label: (0,external_wp_i18n_namespaceObject.__)('Preferences')
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_preferences_namespaceObject.PreferenceToggleMenuItem, {
scope: "core/edit-widgets",
name: "keepCaretInsideBlock",
label: (0,external_wp_i18n_namespaceObject.__)('Contain text cursor inside block'),
info: (0,external_wp_i18n_namespaceObject.__)('Aids screen readers by stopping text caret from leaving blocks.'),
messageActivated: (0,external_wp_i18n_namespaceObject.__)('Contain text cursor inside block activated'),
messageDeactivated: (0,external_wp_i18n_namespaceObject.__)('Contain text cursor inside block deactivated')
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_preferences_namespaceObject.PreferenceToggleMenuItem, {
scope: "core/edit-widgets",
name: "themeStyles",
info: (0,external_wp_i18n_namespaceObject.__)('Make the editor look like your theme.'),
label: (0,external_wp_i18n_namespaceObject.__)('Use theme styles')
}), isLargeViewport && (0,external_wp_element_namespaceObject.createElement)(external_wp_preferences_namespaceObject.PreferenceToggleMenuItem, {
scope: "core/edit-widgets",
name: "showBlockBreadcrumbs",
label: (0,external_wp_i18n_namespaceObject.__)('Display block breadcrumbs'),
info: (0,external_wp_i18n_namespaceObject.__)('Shows block breadcrumbs at the bottom of the editor.'),
messageActivated: (0,external_wp_i18n_namespaceObject.__)('Display block breadcrumbs activated'),
messageDeactivated: (0,external_wp_i18n_namespaceObject.__)('Display block breadcrumbs deactivated')
})))), (0,external_wp_element_namespaceObject.createElement)(KeyboardShortcutHelpModal, {
isModalActive: isKeyboardShortcutsModalActive,
toggleModal: toggleKeyboardShortcutsModal
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/header/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function Header() {
const isMediumViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('medium');
const inserterButton = (0,external_wp_element_namespaceObject.useRef)();
const widgetAreaClientId = use_last_selected_widget_area();
const isLastSelectedWidgetAreaOpen = (0,external_wp_data_namespaceObject.useSelect)(select => select(store_store).getIsWidgetAreaOpen(widgetAreaClientId), [widgetAreaClientId]);
const {
isInserterOpen,
isListViewOpen
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
isInserterOpened,
isListViewOpened
} = select(store_store);
return {
isInserterOpen: isInserterOpened(),
isListViewOpen: isListViewOpened()
};
}, []);
const {
setIsWidgetAreaOpen,
setIsInserterOpened,
setIsListViewOpened
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const {
selectBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_blockEditor_namespaceObject.store);
const handleClick = () => {
if (isInserterOpen) {
// Focusing the inserter button closes the inserter popover.
setIsInserterOpened(false);
} else {
if (!isLastSelectedWidgetAreaOpen) {
// Select the last selected block if hasn't already.
selectBlock(widgetAreaClientId); // Open the last selected widget area when opening the inserter.
setIsWidgetAreaOpen(widgetAreaClientId, true);
} // The DOM updates resulting from selectBlock() and setIsInserterOpened() calls are applied the
// same tick and pretty much in a random order. The inserter is closed if any other part of the
// app receives focus. If selectBlock() happens to take effect after setIsInserterOpened() then
// the inserter is visible for a brief moment and then gets auto-closed due to focus moving to
// the selected block.
window.requestAnimationFrame(() => setIsInserterOpened(true));
}
};
const toggleListView = (0,external_wp_element_namespaceObject.useCallback)(() => setIsListViewOpened(!isListViewOpen), [setIsListViewOpened, isListViewOpen]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-widgets-header"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-widgets-header__navigable-toolbar-wrapper"
}, isMediumViewport && (0,external_wp_element_namespaceObject.createElement)("h1", {
className: "edit-widgets-header__title"
}, (0,external_wp_i18n_namespaceObject.__)('Widgets')), !isMediumViewport && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.VisuallyHidden, {
as: "h1",
className: "edit-widgets-header__title"
}, (0,external_wp_i18n_namespaceObject.__)('Widgets')), (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.NavigableToolbar, {
className: "edit-widgets-header-toolbar",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Document tools')
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarItem, {
ref: inserterButton,
as: external_wp_components_namespaceObject.Button,
className: "edit-widgets-header-toolbar__inserter-toggle",
variant: "primary",
isPressed: isInserterOpen,
onMouseDown: event => {
event.preventDefault();
},
onClick: handleClick,
icon: library_plus
/* translators: button label text should, if possible, be under 16
characters. */
,
label: (0,external_wp_i18n_namespaceObject._x)('Toggle block inserter', 'Generic label for block inserter button')
}), isMediumViewport && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(UndoButton, null), (0,external_wp_element_namespaceObject.createElement)(RedoButton, null), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarItem, {
as: external_wp_components_namespaceObject.Button,
className: "edit-widgets-header-toolbar__list-view-toggle",
icon: list_view,
isPressed: isListViewOpen
/* translators: button label text should, if possible, be under 16 characters. */
,
label: (0,external_wp_i18n_namespaceObject.__)('List View'),
onClick: toggleListView
})))), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-widgets-header__actions"
}, (0,external_wp_element_namespaceObject.createElement)(save_button, null), (0,external_wp_element_namespaceObject.createElement)(pinned_items.Slot, {
scope: "core/edit-widgets"
}), (0,external_wp_element_namespaceObject.createElement)(MoreMenu, null))));
}
/* harmony default export */ var header = (Header);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/notices/index.js
/**
* WordPress dependencies
*/
function Notices() {
const {
removeNotice
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_notices_namespaceObject.store);
const {
notices
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
return {
notices: select(external_wp_notices_namespaceObject.store).getNotices()
};
}, []);
const dismissibleNotices = notices.filter(_ref => {
let {
isDismissible,
type
} = _ref;
return isDismissible && type === 'default';
});
const nonDismissibleNotices = notices.filter(_ref2 => {
let {
isDismissible,
type
} = _ref2;
return !isDismissible && type === 'default';
});
const snackbarNotices = notices.filter(_ref3 => {
let {
type
} = _ref3;
return type === 'snackbar';
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.NoticeList, {
notices: nonDismissibleNotices,
className: "edit-widgets-notices__pinned"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.NoticeList, {
notices: dismissibleNotices,
className: "edit-widgets-notices__dismissible",
onRemove: removeNotice
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SnackbarList, {
notices: snackbarNotices,
className: "edit-widgets-notices__snackbar",
onRemove: removeNotice
}));
}
/* harmony default export */ var notices = (Notices);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/widget-areas-block-editor-content/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function WidgetAreasBlockEditorContent(_ref) {
let {
blockEditorSettings
} = _ref;
const hasThemeStyles = (0,external_wp_data_namespaceObject.useSelect)(select => !!select(external_wp_preferences_namespaceObject.store).get('core/edit-widgets', 'themeStyles'), []);
const styles = (0,external_wp_element_namespaceObject.useMemo)(() => {
return hasThemeStyles ? blockEditorSettings.styles : [];
}, [blockEditorSettings, hasThemeStyles]);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-widgets-block-editor"
}, (0,external_wp_element_namespaceObject.createElement)(notices, null), (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockTools, null, (0,external_wp_element_namespaceObject.createElement)(keyboard_shortcuts, null), (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.__unstableEditorStyles, {
styles: styles
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockSelectionClearer, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.WritingFlow, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.ObserveTyping, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockList, {
className: "edit-widgets-main-block-list"
}))))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/close.js
/**
* WordPress dependencies
*/
const close_close = (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: "M13 11.8l6.1-6.3-1-1-6.1 6.2-6.1-6.2-1 1 6.1 6.3-6.5 6.7 1 1 6.5-6.6 6.5 6.6 1-1z"
}));
/* harmony default export */ var library_close = (close_close);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/hooks/use-widget-library-insertion-point.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const useWidgetLibraryInsertionPoint = () => {
const firstRootId = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _widgetAreasPost$bloc;
// Default to the first widget area
const {
getEntityRecord
} = select(external_wp_coreData_namespaceObject.store);
const widgetAreasPost = getEntityRecord(KIND, POST_TYPE, buildWidgetAreasPostId());
return widgetAreasPost === null || widgetAreasPost === void 0 ? void 0 : (_widgetAreasPost$bloc = widgetAreasPost.blocks[0]) === null || _widgetAreasPost$bloc === void 0 ? void 0 : _widgetAreasPost$bloc.clientId;
}, []);
return (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlockRootClientId,
getBlockSelectionEnd,
getBlockOrder,
getBlockIndex
} = select(external_wp_blockEditor_namespaceObject.store);
const insertionPoint = select(store_store).__experimentalGetInsertionPoint(); // "Browse all" in the quick inserter will set the rootClientId to the current block.
// Otherwise, it will just be undefined, and we'll have to handle it differently below.
if (insertionPoint.rootClientId) {
return insertionPoint;
}
const clientId = getBlockSelectionEnd() || firstRootId;
const rootClientId = getBlockRootClientId(clientId); // If the selected block is at the root level, it's a widget area and
// blocks can't be inserted here. Return this block as the root and the
// last child clientId indicating insertion at the end.
if (clientId && rootClientId === '') {
return {
rootClientId: clientId,
insertionIndex: getBlockOrder(clientId).length
};
}
return {
rootClientId,
insertionIndex: getBlockIndex(clientId) + 1
};
}, [firstRootId]);
};
/* harmony default export */ var use_widget_library_insertion_point = (useWidgetLibraryInsertionPoint);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/secondary-sidebar/inserter-sidebar.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function InserterSidebar() {
const isMobileViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('medium', '<');
const {
rootClientId,
insertionIndex
} = use_widget_library_insertion_point();
const {
setIsInserterOpened
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const closeInserter = (0,external_wp_element_namespaceObject.useCallback)(() => {
return setIsInserterOpened(false);
}, [setIsInserterOpened]);
const TagName = !isMobileViewport ? external_wp_components_namespaceObject.VisuallyHidden : 'div';
const [inserterDialogRef, inserterDialogProps] = (0,external_wp_compose_namespaceObject.__experimentalUseDialog)({
onClose: closeInserter,
focusOnMount: null
});
const libraryRef = (0,external_wp_element_namespaceObject.useRef)();
(0,external_wp_element_namespaceObject.useEffect)(() => {
libraryRef.current.focusSearch();
}, []);
return (0,external_wp_element_namespaceObject.createElement)("div", _extends({
ref: inserterDialogRef
}, inserterDialogProps, {
className: "edit-widgets-layout__inserter-panel"
}), (0,external_wp_element_namespaceObject.createElement)(TagName, {
className: "edit-widgets-layout__inserter-panel-header"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
icon: library_close,
onClick: closeInserter,
label: (0,external_wp_i18n_namespaceObject.__)('Close block inserter')
})), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-widgets-layout__inserter-panel-content"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.__experimentalLibrary, {
showInserterHelpPanel: true,
shouldFocusBlock: isMobileViewport,
rootClientId: rootClientId,
__experimentalInsertionIndex: insertionIndex,
ref: libraryRef
})));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/secondary-sidebar/list-view-sidebar.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ListViewSidebar() {
const {
setIsListViewOpened
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const focusOnMountRef = (0,external_wp_compose_namespaceObject.useFocusOnMount)('firstElement');
const headerFocusReturnRef = (0,external_wp_compose_namespaceObject.useFocusReturn)();
const contentFocusReturnRef = (0,external_wp_compose_namespaceObject.useFocusReturn)();
function closeOnEscape(event) {
if (event.keyCode === external_wp_keycodes_namespaceObject.ESCAPE && !event.defaultPrevented) {
event.preventDefault();
setIsListViewOpened(false);
}
}
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(ListViewSidebar);
const labelId = `edit-widgets-editor__list-view-panel-label-${instanceId}`;
return (// eslint-disable-next-line jsx-a11y/no-static-element-interactions
(0,external_wp_element_namespaceObject.createElement)("div", {
"aria-labelledby": labelId,
className: "edit-widgets-editor__list-view-panel",
onKeyDown: closeOnEscape
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-widgets-editor__list-view-panel-header",
ref: headerFocusReturnRef
}, (0,external_wp_element_namespaceObject.createElement)("strong", {
id: labelId
}, (0,external_wp_i18n_namespaceObject.__)('List View')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
icon: close_small,
label: (0,external_wp_i18n_namespaceObject.__)('Close List View Sidebar'),
onClick: () => setIsListViewOpened(false)
})), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-widgets-editor__list-view-panel-content",
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([contentFocusReturnRef, focusOnMountRef])
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.__experimentalListView, null)))
);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/secondary-sidebar/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Internal dependencies
*/
function SecondarySidebar() {
const {
isInserterOpen,
isListViewOpen
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
isInserterOpened,
isListViewOpened
} = select(store_store);
return {
isInserterOpen: isInserterOpened(),
isListViewOpen: isListViewOpened()
};
}, []);
if (isInserterOpen) {
return (0,external_wp_element_namespaceObject.createElement)(InserterSidebar, null);
}
if (isListViewOpen) {
return (0,external_wp_element_namespaceObject.createElement)(ListViewSidebar, null);
}
return null;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/layout/interface.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const interfaceLabels = {
/* translators: accessibility text for the widgets screen top bar landmark region. */
header: (0,external_wp_i18n_namespaceObject.__)('Widgets top bar'),
/* translators: accessibility text for the widgets screen content landmark region. */
body: (0,external_wp_i18n_namespaceObject.__)('Widgets and blocks'),
/* translators: accessibility text for the widgets screen settings landmark region. */
sidebar: (0,external_wp_i18n_namespaceObject.__)('Widgets settings'),
/* translators: accessibility text for the widgets screen footer landmark region. */
footer: (0,external_wp_i18n_namespaceObject.__)('Widgets footer')
};
function Interface(_ref) {
let {
blockEditorSettings
} = _ref;
const isMobileViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('medium', '<');
const isHugeViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('huge', '>=');
const {
setIsInserterOpened,
setIsListViewOpened,
closeGeneralSidebar
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const {
hasBlockBreadCrumbsEnabled,
hasSidebarEnabled,
isInserterOpened,
isListViewOpened,
previousShortcut,
nextShortcut
} = (0,external_wp_data_namespaceObject.useSelect)(select => ({
hasSidebarEnabled: !!select(store).getActiveComplementaryArea(store_store.name),
isInserterOpened: !!select(store_store).isInserterOpened(),
isListViewOpened: !!select(store_store).isListViewOpened(),
hasBlockBreadCrumbsEnabled: !!select(external_wp_preferences_namespaceObject.store).get('core/edit-widgets', 'showBlockBreadcrumbs'),
previousShortcut: select(external_wp_keyboardShortcuts_namespaceObject.store).getAllShortcutKeyCombinations('core/edit-widgets/previous-region'),
nextShortcut: select(external_wp_keyboardShortcuts_namespaceObject.store).getAllShortcutKeyCombinations('core/edit-widgets/next-region')
}), []); // Inserter and Sidebars are mutually exclusive
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (hasSidebarEnabled && !isHugeViewport) {
setIsInserterOpened(false);
setIsListViewOpened(false);
}
}, [hasSidebarEnabled, isHugeViewport]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if ((isInserterOpened || isListViewOpened) && !isHugeViewport) {
closeGeneralSidebar();
}
}, [isInserterOpened, isListViewOpened, isHugeViewport]);
const secondarySidebarLabel = isListViewOpened ? (0,external_wp_i18n_namespaceObject.__)('List View') : (0,external_wp_i18n_namespaceObject.__)('Block Library');
const hasSecondarySidebar = isListViewOpened || isInserterOpened;
return (0,external_wp_element_namespaceObject.createElement)(interface_skeleton, {
labels: { ...interfaceLabels,
secondarySidebar: secondarySidebarLabel
},
header: (0,external_wp_element_namespaceObject.createElement)(header, null),
secondarySidebar: hasSecondarySidebar && (0,external_wp_element_namespaceObject.createElement)(SecondarySidebar, null),
sidebar: hasSidebarEnabled && (0,external_wp_element_namespaceObject.createElement)(complementary_area.Slot, {
scope: "core/edit-widgets"
}),
content: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(WidgetAreasBlockEditorContent, {
blockEditorSettings: blockEditorSettings
})),
footer: hasBlockBreadCrumbsEnabled && !isMobileViewport && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-widgets-layout__footer"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockBreadcrumb, {
rootLabelText: (0,external_wp_i18n_namespaceObject.__)('Widgets')
})),
shortcuts: {
previous: previousShortcut,
next: nextShortcut
}
});
}
/* harmony default export */ var layout_interface = (Interface);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/layout/unsaved-changes-warning.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Warns the user if there are unsaved changes before leaving the editor.
*
* This is a duplicate of the component implemented in the editor package.
* Duplicated here as edit-widgets doesn't depend on editor.
*
* @return {WPComponent} The component.
*/
function UnsavedChangesWarning() {
const isDirty = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getEditedWidgetAreas
} = select(store_store);
const editedWidgetAreas = getEditedWidgetAreas();
return (editedWidgetAreas === null || editedWidgetAreas === void 0 ? void 0 : editedWidgetAreas.length) > 0;
}, []);
(0,external_wp_element_namespaceObject.useEffect)(() => {
/**
* Warns the user if there are unsaved changes before leaving the editor.
*
* @param {Event} event `beforeunload` event.
*
* @return {string | undefined} Warning prompt message, if unsaved changes exist.
*/
const warnIfUnsavedChanges = event => {
if (isDirty) {
event.returnValue = (0,external_wp_i18n_namespaceObject.__)('You have unsaved changes. If you proceed, they will be lost.');
return event.returnValue;
}
};
window.addEventListener('beforeunload', warnIfUnsavedChanges);
return () => {
window.removeEventListener('beforeunload', warnIfUnsavedChanges);
};
}, [isDirty]);
return null;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/welcome-guide/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function WelcomeGuide() {
var _widgetAreas$filter$l;
const isActive = (0,external_wp_data_namespaceObject.useSelect)(select => !!select(external_wp_preferences_namespaceObject.store).get('core/edit-widgets', 'welcomeGuide'), []);
const {
toggle
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_preferences_namespaceObject.store);
const widgetAreas = (0,external_wp_data_namespaceObject.useSelect)(select => select(store_store).getWidgetAreas({
per_page: -1
}), []);
if (!isActive) {
return null;
}
const isEntirelyBlockWidgets = widgetAreas === null || widgetAreas === void 0 ? void 0 : widgetAreas.every(widgetArea => widgetArea.id === 'wp_inactive_widgets' || widgetArea.widgets.every(widgetId => widgetId.startsWith('block-')));
const numWidgetAreas = (_widgetAreas$filter$l = widgetAreas === null || widgetAreas === void 0 ? void 0 : widgetAreas.filter(widgetArea => widgetArea.id !== 'wp_inactive_widgets').length) !== null && _widgetAreas$filter$l !== void 0 ? _widgetAreas$filter$l : 0;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Guide, {
className: "edit-widgets-welcome-guide",
contentLabel: (0,external_wp_i18n_namespaceObject.__)('Welcome to block Widgets'),
finishButtonText: (0,external_wp_i18n_namespaceObject.__)('Get started'),
onFinish: () => toggle('core/edit-widgets', 'welcomeGuide'),
pages: [{
image: (0,external_wp_element_namespaceObject.createElement)(WelcomeGuideImage, {
nonAnimatedSrc: "https://s.w.org/images/block-editor/welcome-canvas.svg",
animatedSrc: "https://s.w.org/images/block-editor/welcome-canvas.gif"
}),
content: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("h1", {
className: "edit-widgets-welcome-guide__heading"
}, (0,external_wp_i18n_namespaceObject.__)('Welcome to block Widgets')), isEntirelyBlockWidgets ? (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("p", {
className: "edit-widgets-welcome-guide__text"
}, (0,external_wp_i18n_namespaceObject.sprintf)( // Translators: %s: Number of block areas in the current theme.
(0,external_wp_i18n_namespaceObject._n)('Your theme provides %s “block” area for you to add and edit content. Try adding a search bar, social icons, or other types of blocks here and see how they’ll look on your site.', 'Your theme provides %s different “block” areas for you to add and edit content. Try adding a search bar, social icons, or other types of blocks here and see how they’ll look on your site.', numWidgetAreas), numWidgetAreas))) : (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("p", {
className: "edit-widgets-welcome-guide__text"
}, (0,external_wp_i18n_namespaceObject.__)('You can now add any block to your site’s widget areas. Don’t worry, all of your favorite widgets still work flawlessly.')), (0,external_wp_element_namespaceObject.createElement)("p", {
className: "edit-widgets-welcome-guide__text"
}, (0,external_wp_element_namespaceObject.createElement)("strong", null, (0,external_wp_i18n_namespaceObject.__)('Want to stick with the old widgets?')), ' ', (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ExternalLink, {
href: (0,external_wp_i18n_namespaceObject.__)('https://wordpress.org/plugins/classic-widgets/')
}, (0,external_wp_i18n_namespaceObject.__)('Get the Classic Widgets plugin.')))))
}, {
image: (0,external_wp_element_namespaceObject.createElement)(WelcomeGuideImage, {
nonAnimatedSrc: "https://s.w.org/images/block-editor/welcome-editor.svg",
animatedSrc: "https://s.w.org/images/block-editor/welcome-editor.gif"
}),
content: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("h1", {
className: "edit-widgets-welcome-guide__heading"
}, (0,external_wp_i18n_namespaceObject.__)('Make each block your own')), (0,external_wp_element_namespaceObject.createElement)("p", {
className: "edit-widgets-welcome-guide__text"
}, (0,external_wp_i18n_namespaceObject.__)('Each block comes with its own set of controls for changing things like color, width, and alignment. These will show and hide automatically when you have a block selected.')))
}, {
image: (0,external_wp_element_namespaceObject.createElement)(WelcomeGuideImage, {
nonAnimatedSrc: "https://s.w.org/images/block-editor/welcome-library.svg",
animatedSrc: "https://s.w.org/images/block-editor/welcome-library.gif"
}),
content: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("h1", {
className: "edit-widgets-welcome-guide__heading"
}, (0,external_wp_i18n_namespaceObject.__)('Get to know the block library')), (0,external_wp_element_namespaceObject.createElement)("p", {
className: "edit-widgets-welcome-guide__text"
}, (0,external_wp_element_namespaceObject.createInterpolateElement)((0,external_wp_i18n_namespaceObject.__)('All of the blocks available to you live in the block library. You’ll find it wherever you see the <InserterIconImage /> icon.'), {
InserterIconImage: (0,external_wp_element_namespaceObject.createElement)("img", {
className: "edit-widgets-welcome-guide__inserter-icon",
alt: (0,external_wp_i18n_namespaceObject.__)('inserter'),
src: "data:image/svg+xml,%3Csvg width='18' height='18' viewBox='0 0 18 18' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='18' height='18' rx='2' fill='%231E1E1E'/%3E%3Cpath d='M9.22727 4V14M4 8.77273H14' stroke='white' stroke-width='1.5'/%3E%3C/svg%3E%0A"
})
})))
}, {
image: (0,external_wp_element_namespaceObject.createElement)(WelcomeGuideImage, {
nonAnimatedSrc: "https://s.w.org/images/block-editor/welcome-documentation.svg",
animatedSrc: "https://s.w.org/images/block-editor/welcome-documentation.gif"
}),
content: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("h1", {
className: "edit-widgets-welcome-guide__heading"
}, (0,external_wp_i18n_namespaceObject.__)('Learn how to use the block editor')), (0,external_wp_element_namespaceObject.createElement)("p", {
className: "edit-widgets-welcome-guide__text"
}, (0,external_wp_i18n_namespaceObject.__)('New to the block editor? Want to learn more about using it? '), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ExternalLink, {
href: (0,external_wp_i18n_namespaceObject.__)('https://wordpress.org/support/article/wordpress-editor/')
}, (0,external_wp_i18n_namespaceObject.__)("Here's a detailed guide."))))
}]
});
}
function WelcomeGuideImage(_ref) {
let {
nonAnimatedSrc,
animatedSrc
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("picture", {
className: "edit-widgets-welcome-guide__image"
}, (0,external_wp_element_namespaceObject.createElement)("source", {
srcSet: nonAnimatedSrc,
media: "(prefers-reduced-motion: reduce)"
}), (0,external_wp_element_namespaceObject.createElement)("img", {
src: animatedSrc,
width: "312",
height: "240",
alt: ""
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/components/layout/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function Layout(_ref) {
let {
blockEditorSettings
} = _ref;
const {
createErrorNotice
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_notices_namespaceObject.store);
function onPluginAreaError(name) {
createErrorNotice((0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: plugin name */
(0,external_wp_i18n_namespaceObject.__)('The "%s" plugin has encountered an error and cannot be rendered.'), name));
}
return (0,external_wp_element_namespaceObject.createElement)(ErrorBoundary, null, (0,external_wp_element_namespaceObject.createElement)(WidgetAreasBlockEditorProvider, {
blockEditorSettings: blockEditorSettings
}, (0,external_wp_element_namespaceObject.createElement)(layout_interface, {
blockEditorSettings: blockEditorSettings
}), (0,external_wp_element_namespaceObject.createElement)(Sidebar, null), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Popover.Slot, null), (0,external_wp_element_namespaceObject.createElement)(external_wp_plugins_namespaceObject.PluginArea, {
onError: onPluginAreaError
}), (0,external_wp_element_namespaceObject.createElement)(UnsavedChangesWarning, null), (0,external_wp_element_namespaceObject.createElement)(WelcomeGuide, null)));
}
/* harmony default export */ var layout = (Layout);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-widgets/build-module/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const disabledBlocks = ['core/more', 'core/freeform', 'core/template-part', ...(ALLOW_REUSABLE_BLOCKS ? [] : ['core/block'])];
/**
* Initializes the block editor in the widgets screen.
*
* @param {string} id ID of the root element to render the screen in.
* @param {Object} settings Block editor settings.
*/
function initializeEditor(id, settings) {
const target = document.getElementById(id);
const root = (0,external_wp_element_namespaceObject.createRoot)(target);
const coreBlocks = (0,external_wp_blockLibrary_namespaceObject.__experimentalGetCoreBlocks)().filter(block => {
return !(disabledBlocks.includes(block.name) || block.name.startsWith('core/post') || block.name.startsWith('core/query') || block.name.startsWith('core/site') || block.name.startsWith('core/navigation'));
});
(0,external_wp_data_namespaceObject.dispatch)(external_wp_preferences_namespaceObject.store).setDefaults('core/edit-widgets', {
fixedToolbar: false,
welcomeGuide: true,
showBlockBreadcrumbs: true,
themeStyles: true
});
(0,external_wp_data_namespaceObject.dispatch)(external_wp_blocks_namespaceObject.store).__experimentalReapplyBlockTypeFilters();
(0,external_wp_blockLibrary_namespaceObject.registerCoreBlocks)(coreBlocks);
(0,external_wp_widgets_namespaceObject.registerLegacyWidgetBlock)();
if (false) {}
(0,external_wp_widgets_namespaceObject.registerLegacyWidgetVariations)(settings);
registerBlock(widget_area_namespaceObject);
(0,external_wp_widgets_namespaceObject.registerWidgetGroupBlock)();
settings.__experimentalFetchLinkSuggestions = (search, searchOptions) => (0,external_wp_coreData_namespaceObject.__experimentalFetchLinkSuggestions)(search, searchOptions, settings); // As we are unregistering `core/freeform` to avoid the Classic block, we must
// replace it with something as the default freeform content handler. Failure to
// do this will result in errors in the default block parser.
// see: https://github.com/WordPress/gutenberg/issues/33097
(0,external_wp_blocks_namespaceObject.setFreeformContentHandlerName)('core/html');
root.render((0,external_wp_element_namespaceObject.createElement)(layout, {
blockEditorSettings: settings
}));
return root;
}
/**
* Compatibility export under the old `initialize` name.
*/
const initialize = initializeEditor;
function reinitializeEditor() {
external_wp_deprecated_default()('wp.editWidgets.reinitializeEditor', {
since: '6.2',
version: '6.3'
});
}
/**
* Function to register an individual block.
*
* @param {Object} block The block to be registered.
*
*/
const registerBlock = block => {
if (!block) {
return;
}
const {
metadata,
settings,
name
} = block;
if (metadata) {
(0,external_wp_blocks_namespaceObject.unstable__bootstrapServerSideBlockDefinitions)({
[name]: metadata
});
}
(0,external_wp_blocks_namespaceObject.registerBlockType)(name, settings);
};
}();
(window.wp = window.wp || {}).editWidgets = __webpack_exports__;
/******/ })()
; i18n.js 0000666 00000145206 15123355174 0005703 0 ustar 00 /******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 9756:
/***/ (function(module) {
/**
* Memize options object.
*
* @typedef MemizeOptions
*
* @property {number} [maxSize] Maximum size of the cache.
*/
/**
* Internal cache entry.
*
* @typedef MemizeCacheNode
*
* @property {?MemizeCacheNode|undefined} [prev] Previous node.
* @property {?MemizeCacheNode|undefined} [next] Next node.
* @property {Array<*>} args Function arguments for cache
* entry.
* @property {*} val Function result.
*/
/**
* Properties of the enhanced function for controlling cache.
*
* @typedef MemizeMemoizedFunction
*
* @property {()=>void} clear Clear the cache.
*/
/**
* Accepts a function to be memoized, and returns a new memoized function, with
* optional options.
*
* @template {Function} F
*
* @param {F} fn Function to memoize.
* @param {MemizeOptions} [options] Options object.
*
* @return {F & MemizeMemoizedFunction} Memoized function.
*/
function memize( fn, options ) {
var size = 0;
/** @type {?MemizeCacheNode|undefined} */
var head;
/** @type {?MemizeCacheNode|undefined} */
var tail;
options = options || {};
function memoized( /* ...args */ ) {
var node = head,
len = arguments.length,
args, i;
searchCache: while ( node ) {
// Perform a shallow equality test to confirm that whether the node
// under test is a candidate for the arguments passed. Two arrays
// are shallowly equal if their length matches and each entry is
// strictly equal between the two sets. Avoid abstracting to a
// function which could incur an arguments leaking deoptimization.
// Check whether node arguments match arguments length
if ( node.args.length !== arguments.length ) {
node = node.next;
continue;
}
// Check whether node arguments match arguments values
for ( i = 0; i < len; i++ ) {
if ( node.args[ i ] !== arguments[ i ] ) {
node = node.next;
continue searchCache;
}
}
// At this point we can assume we've found a match
// Surface matched node to head if not already
if ( node !== head ) {
// As tail, shift to previous. Must only shift if not also
// head, since if both head and tail, there is no previous.
if ( node === tail ) {
tail = node.prev;
}
// Adjust siblings to point to each other. If node was tail,
// this also handles new tail's empty `next` assignment.
/** @type {MemizeCacheNode} */ ( node.prev ).next = node.next;
if ( node.next ) {
node.next.prev = node.prev;
}
node.next = head;
node.prev = null;
/** @type {MemizeCacheNode} */ ( head ).prev = node;
head = node;
}
// Return immediately
return node.val;
}
// No cached value found. Continue to insertion phase:
// Create a copy of arguments (avoid leaking deoptimization)
args = new Array( len );
for ( i = 0; i < len; i++ ) {
args[ i ] = arguments[ i ];
}
node = {
args: args,
// Generate the result from original function
val: fn.apply( null, args ),
};
// Don't need to check whether node is already head, since it would
// have been returned above already if it was
// Shift existing head down list
if ( head ) {
head.prev = node;
node.next = head;
} else {
// If no head, follows that there's no tail (at initial or reset)
tail = node;
}
// Trim tail if we're reached max size and are pending cache insertion
if ( size === /** @type {MemizeOptions} */ ( options ).maxSize ) {
tail = /** @type {MemizeCacheNode} */ ( tail ).prev;
/** @type {MemizeCacheNode} */ ( tail ).next = null;
} else {
size++;
}
head = node;
return node.val;
}
memoized.clear = function() {
head = null;
tail = null;
size = 0;
};
if ( false ) {}
// Ignore reason: There's not a clear solution to create an intersection of
// the function with additional properties, where the goal is to retain the
// function signature of the incoming argument and add control properties
// on the return value.
// @ts-ignore
return memoized;
}
module.exports = memize;
/***/ }),
/***/ 124:
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;/* global window, exports, define */
!function() {
'use strict'
var re = {
not_string: /[^s]/,
not_bool: /[^t]/,
not_type: /[^T]/,
not_primitive: /[^v]/,
number: /[diefg]/,
numeric_arg: /[bcdiefguxX]/,
json: /[j]/,
not_json: /[^j]/,
text: /^[^\x25]+/,
modulo: /^\x25{2}/,
placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
key: /^([a-z_][a-z_\d]*)/i,
key_access: /^\.([a-z_][a-z_\d]*)/i,
index_access: /^\[(\d+)\]/,
sign: /^[+-]/
}
function sprintf(key) {
// `arguments` is not an array, but should be fine for this call
return sprintf_format(sprintf_parse(key), arguments)
}
function vsprintf(fmt, argv) {
return sprintf.apply(null, [fmt].concat(argv || []))
}
function sprintf_format(parse_tree, argv) {
var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign
for (i = 0; i < tree_length; i++) {
if (typeof parse_tree[i] === 'string') {
output += parse_tree[i]
}
else if (typeof parse_tree[i] === 'object') {
ph = parse_tree[i] // convenience purposes only
if (ph.keys) { // keyword argument
arg = argv[cursor]
for (k = 0; k < ph.keys.length; k++) {
if (arg == undefined) {
throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k-1]))
}
arg = arg[ph.keys[k]]
}
}
else if (ph.param_no) { // positional argument (explicit)
arg = argv[ph.param_no]
}
else { // positional argument (implicit)
arg = argv[cursor++]
}
if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
arg = arg()
}
if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {
throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg))
}
if (re.number.test(ph.type)) {
is_positive = arg >= 0
}
switch (ph.type) {
case 'b':
arg = parseInt(arg, 10).toString(2)
break
case 'c':
arg = String.fromCharCode(parseInt(arg, 10))
break
case 'd':
case 'i':
arg = parseInt(arg, 10)
break
case 'j':
arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0)
break
case 'e':
arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential()
break
case 'f':
arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg)
break
case 'g':
arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg)
break
case 'o':
arg = (parseInt(arg, 10) >>> 0).toString(8)
break
case 's':
arg = String(arg)
arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
break
case 't':
arg = String(!!arg)
arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
break
case 'T':
arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase()
arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
break
case 'u':
arg = parseInt(arg, 10) >>> 0
break
case 'v':
arg = arg.valueOf()
arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
break
case 'x':
arg = (parseInt(arg, 10) >>> 0).toString(16)
break
case 'X':
arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase()
break
}
if (re.json.test(ph.type)) {
output += arg
}
else {
if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
sign = is_positive ? '+' : '-'
arg = arg.toString().replace(re.sign, '')
}
else {
sign = ''
}
pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' '
pad_length = ph.width - (sign + arg).length
pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : ''
output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg)
}
}
}
return output
}
var sprintf_cache = Object.create(null)
function sprintf_parse(fmt) {
if (sprintf_cache[fmt]) {
return sprintf_cache[fmt]
}
var _fmt = fmt, match, parse_tree = [], arg_names = 0
while (_fmt) {
if ((match = re.text.exec(_fmt)) !== null) {
parse_tree.push(match[0])
}
else if ((match = re.modulo.exec(_fmt)) !== null) {
parse_tree.push('%')
}
else if ((match = re.placeholder.exec(_fmt)) !== null) {
if (match[2]) {
arg_names |= 1
var field_list = [], replacement_field = match[2], field_match = []
if ((field_match = re.key.exec(replacement_field)) !== null) {
field_list.push(field_match[1])
while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
if ((field_match = re.key_access.exec(replacement_field)) !== null) {
field_list.push(field_match[1])
}
else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
field_list.push(field_match[1])
}
else {
throw new SyntaxError('[sprintf] failed to parse named argument key')
}
}
}
else {
throw new SyntaxError('[sprintf] failed to parse named argument key')
}
match[2] = field_list
}
else {
arg_names |= 2
}
if (arg_names === 3) {
throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported')
}
parse_tree.push(
{
placeholder: match[0],
param_no: match[1],
keys: match[2],
sign: match[3],
pad_char: match[4],
align: match[5],
width: match[6],
precision: match[7],
type: match[8]
}
)
}
else {
throw new SyntaxError('[sprintf] unexpected placeholder')
}
_fmt = _fmt.substring(match[0].length)
}
return sprintf_cache[fmt] = parse_tree
}
/**
* export to either browser or node.js
*/
/* eslint-disable quote-props */
if (true) {
exports.sprintf = sprintf
exports.vsprintf = vsprintf
}
if (typeof window !== 'undefined') {
window['sprintf'] = sprintf
window['vsprintf'] = vsprintf
if (true) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function() {
return {
'sprintf': sprintf,
'vsprintf': vsprintf
}
}).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))
}
}
/* eslint-enable quote-props */
}(); // eslint-disable-line
/***/ })
/******/ });
/************************************************************************/
/******/ // 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 in strict mode.
!function() {
"use strict";
// ESM COMPAT FLAG
__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; }
});
// EXTERNAL MODULE: ./node_modules/memize/index.js
var memize = __webpack_require__(9756);
var memize_default = /*#__PURE__*/__webpack_require__.n(memize);
// EXTERNAL MODULE: ./node_modules/sprintf-js/src/sprintf.js
var sprintf = __webpack_require__(124);
var sprintf_default = /*#__PURE__*/__webpack_require__.n(sprintf);
;// CONCATENATED MODULE: ./node_modules/@wordpress/i18n/build-module/sprintf.js
/**
* External dependencies
*/
/**
* 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
* to avoid crashing the application.
*
* @param {...*} args Arguments to pass to `console.error`
*/
const logErrorOnce = memize_default()(console.error); // eslint-disable-line no-console
/**
* Returns a formatted string. If an error occurs in applying the format, the
* original format string is returned.
*
* @param {string} format The format of the string to generate.
* @param {...*} args Arguments to apply to the format.
*
* @see https://www.npmjs.com/package/sprintf-js
*
* @return {string} The formatted string.
*/
function sprintf_sprintf(format) {
try {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return sprintf_default().sprintf(format, ...args);
} catch (error) {
if (error instanceof Error) {
logErrorOnce('sprintf error: \n\n' + error.toString());
}
return format;
}
}
;// CONCATENATED MODULE: ./node_modules/@tannin/postfix/index.js
var PRECEDENCE, OPENERS, TERMINATORS, PATTERN;
/**
* Operator precedence mapping.
*
* @type {Object}
*/
PRECEDENCE = {
'(': 9,
'!': 8,
'*': 7,
'/': 7,
'%': 7,
'+': 6,
'-': 6,
'<': 5,
'<=': 5,
'>': 5,
'>=': 5,
'==': 4,
'!=': 4,
'&&': 3,
'||': 2,
'?': 1,
'?:': 1,
};
/**
* Characters which signal pair opening, to be terminated by terminators.
*
* @type {string[]}
*/
OPENERS = [ '(', '?' ];
/**
* Characters which signal pair termination, the value an array with the
* opener as its first member. The second member is an optional operator
* replacement to push to the stack.
*
* @type {string[]}
*/
TERMINATORS = {
')': [ '(' ],
':': [ '?', '?:' ],
};
/**
* Pattern matching operators and openers.
*
* @type {RegExp}
*/
PATTERN = /<=|>=|==|!=|&&|\|\||\?:|\(|!|\*|\/|%|\+|-|<|>|\?|\)|:/;
/**
* Given a C expression, returns the equivalent postfix (Reverse Polish)
* notation terms as an array.
*
* If a postfix string is desired, simply `.join( ' ' )` the result.
*
* @example
*
* ```js
* import postfix from '@tannin/postfix';
*
* postfix( 'n > 1' );
* // ⇒ [ 'n', '1', '>' ]
* ```
*
* @param {string} expression C expression.
*
* @return {string[]} Postfix terms.
*/
function postfix( expression ) {
var terms = [],
stack = [],
match, operator, term, element;
while ( ( match = expression.match( PATTERN ) ) ) {
operator = match[ 0 ];
// Term is the string preceding the operator match. It may contain
// whitespace, and may be empty (if operator is at beginning).
term = expression.substr( 0, match.index ).trim();
if ( term ) {
terms.push( term );
}
while ( ( element = stack.pop() ) ) {
if ( TERMINATORS[ operator ] ) {
if ( TERMINATORS[ operator ][ 0 ] === element ) {
// Substitution works here under assumption that because
// the assigned operator will no longer be a terminator, it
// will be pushed to the stack during the condition below.
operator = TERMINATORS[ operator ][ 1 ] || operator;
break;
}
} else if ( OPENERS.indexOf( element ) >= 0 || PRECEDENCE[ element ] < PRECEDENCE[ operator ] ) {
// Push to stack if either an opener or when pop reveals an
// element of lower precedence.
stack.push( element );
break;
}
// For each popped from stack, push to terms.
terms.push( element );
}
if ( ! TERMINATORS[ operator ] ) {
stack.push( operator );
}
// Slice matched fragment from expression to continue match.
expression = expression.substr( match.index + operator.length );
}
// Push remainder of operand, if exists, to terms.
expression = expression.trim();
if ( expression ) {
terms.push( expression );
}
// Pop remaining items from stack into terms.
return terms.concat( stack.reverse() );
}
;// CONCATENATED MODULE: ./node_modules/@tannin/evaluate/index.js
/**
* Operator callback functions.
*
* @type {Object}
*/
var OPERATORS = {
'!': function( a ) {
return ! a;
},
'*': function( a, b ) {
return a * b;
},
'/': function( a, b ) {
return a / b;
},
'%': function( a, b ) {
return a % b;
},
'+': function( a, b ) {
return a + b;
},
'-': function( a, b ) {
return a - b;
},
'<': function( a, b ) {
return a < b;
},
'<=': function( a, b ) {
return a <= b;
},
'>': function( a, b ) {
return a > b;
},
'>=': function( a, b ) {
return a >= b;
},
'==': function( a, b ) {
return a === b;
},
'!=': function( a, b ) {
return a !== b;
},
'&&': function( a, b ) {
return a && b;
},
'||': function( a, b ) {
return a || b;
},
'?:': function( a, b, c ) {
if ( a ) {
throw b;
}
return c;
},
};
/**
* Given an array of postfix terms and operand variables, returns the result of
* the postfix evaluation.
*
* @example
*
* ```js
* import evaluate from '@tannin/evaluate';
*
* // 3 + 4 * 5 / 6 ⇒ '3 4 5 * 6 / +'
* const terms = [ '3', '4', '5', '*', '6', '/', '+' ];
*
* evaluate( terms, {} );
* // ⇒ 6.333333333333334
* ```
*
* @param {string[]} postfix Postfix terms.
* @param {Object} variables Operand variables.
*
* @return {*} Result of evaluation.
*/
function evaluate( postfix, variables ) {
var stack = [],
i, j, args, getOperatorResult, term, value;
for ( i = 0; i < postfix.length; i++ ) {
term = postfix[ i ];
getOperatorResult = OPERATORS[ term ];
if ( getOperatorResult ) {
// Pop from stack by number of function arguments.
j = getOperatorResult.length;
args = Array( j );
while ( j-- ) {
args[ j ] = stack.pop();
}
try {
value = getOperatorResult.apply( null, args );
} catch ( earlyReturn ) {
return earlyReturn;
}
} else if ( variables.hasOwnProperty( term ) ) {
value = variables[ term ];
} else {
value = +term;
}
stack.push( value );
}
return stack[ 0 ];
}
;// CONCATENATED MODULE: ./node_modules/@tannin/compile/index.js
/**
* Given a C expression, returns a function which can be called to evaluate its
* result.
*
* @example
*
* ```js
* import compile from '@tannin/compile';
*
* const evaluate = compile( 'n > 1' );
*
* evaluate( { n: 2 } );
* // ⇒ true
* ```
*
* @param {string} expression C expression.
*
* @return {(variables?:{[variable:string]:*})=>*} Compiled evaluator.
*/
function compile( expression ) {
var terms = postfix( expression );
return function( variables ) {
return evaluate( terms, variables );
};
}
;// CONCATENATED MODULE: ./node_modules/@tannin/plural-forms/index.js
/**
* Given a C expression, returns a function which, when called with a value,
* evaluates the result with the value assumed to be the "n" variable of the
* expression. The result will be coerced to its numeric equivalent.
*
* @param {string} expression C expression.
*
* @return {Function} Evaluator function.
*/
function pluralForms( expression ) {
var evaluate = compile( expression );
return function( n ) {
return +evaluate( { n: n } );
};
}
;// CONCATENATED MODULE: ./node_modules/tannin/index.js
/**
* Tannin constructor options.
*
* @typedef {Object} TanninOptions
*
* @property {string} [contextDelimiter] Joiner in string lookup with context.
* @property {Function} [onMissingKey] Callback to invoke when key missing.
*/
/**
* Domain metadata.
*
* @typedef {Object} TanninDomainMetadata
*
* @property {string} [domain] Domain name.
* @property {string} [lang] Language code.
* @property {(string|Function)} [plural_forms] Plural forms expression or
* function evaluator.
*/
/**
* Domain translation pair respectively representing the singular and plural
* translation.
*
* @typedef {[string,string]} TanninTranslation
*/
/**
* Locale data domain. The key is used as reference for lookup, the value an
* array of two string entries respectively representing the singular and plural
* translation.
*
* @typedef {{[key:string]:TanninDomainMetadata|TanninTranslation,'':TanninDomainMetadata|TanninTranslation}} TanninLocaleDomain
*/
/**
* Jed-formatted locale data.
*
* @see http://messageformat.github.io/Jed/
*
* @typedef {{[domain:string]:TanninLocaleDomain}} TanninLocaleData
*/
/**
* Default Tannin constructor options.
*
* @type {TanninOptions}
*/
var DEFAULT_OPTIONS = {
contextDelimiter: '\u0004',
onMissingKey: null,
};
/**
* Given a specific locale data's config `plural_forms` value, returns the
* expression.
*
* @example
*
* ```
* getPluralExpression( 'nplurals=2; plural=(n != 1);' ) === '(n != 1)'
* ```
*
* @param {string} pf Locale data plural forms.
*
* @return {string} Plural forms expression.
*/
function getPluralExpression( pf ) {
var parts, i, part;
parts = pf.split( ';' );
for ( i = 0; i < parts.length; i++ ) {
part = parts[ i ].trim();
if ( part.indexOf( 'plural=' ) === 0 ) {
return part.substr( 7 );
}
}
}
/**
* Tannin constructor.
*
* @class
*
* @param {TanninLocaleData} data Jed-formatted locale data.
* @param {TanninOptions} [options] Tannin options.
*/
function Tannin( data, options ) {
var key;
/**
* Jed-formatted locale data.
*
* @name Tannin#data
* @type {TanninLocaleData}
*/
this.data = data;
/**
* Plural forms function cache, keyed by plural forms string.
*
* @name Tannin#pluralForms
* @type {Object<string,Function>}
*/
this.pluralForms = {};
/**
* Effective options for instance, including defaults.
*
* @name Tannin#options
* @type {TanninOptions}
*/
this.options = {};
for ( key in DEFAULT_OPTIONS ) {
this.options[ key ] = options !== undefined && key in options
? options[ key ]
: DEFAULT_OPTIONS[ key ];
}
}
/**
* Returns the plural form index for the given domain and value.
*
* @param {string} domain Domain on which to calculate plural form.
* @param {number} n Value for which plural form is to be calculated.
*
* @return {number} Plural form index.
*/
Tannin.prototype.getPluralForm = function( domain, n ) {
var getPluralForm = this.pluralForms[ domain ],
config, plural, pf;
if ( ! getPluralForm ) {
config = this.data[ domain ][ '' ];
pf = (
config[ 'Plural-Forms' ] ||
config[ 'plural-forms' ] ||
// Ignore reason: As known, there's no way to document the empty
// string property on a key to guarantee this as metadata.
// @ts-ignore
config.plural_forms
);
if ( typeof pf !== 'function' ) {
plural = getPluralExpression(
config[ 'Plural-Forms' ] ||
config[ 'plural-forms' ] ||
// Ignore reason: As known, there's no way to document the empty
// string property on a key to guarantee this as metadata.
// @ts-ignore
config.plural_forms
);
pf = pluralForms( plural );
}
getPluralForm = this.pluralForms[ domain ] = pf;
}
return getPluralForm( n );
};
/**
* Translate a string.
*
* @param {string} domain Translation domain.
* @param {string|void} context Context distinguishing terms of the same name.
* @param {string} singular Primary key for translation lookup.
* @param {string=} plural Fallback value used for non-zero plural
* form index.
* @param {number=} n Value to use in calculating plural form.
*
* @return {string} Translated string.
*/
Tannin.prototype.dcnpgettext = function( domain, context, singular, plural, n ) {
var index, key, entry;
if ( n === undefined ) {
// Default to singular.
index = 0;
} else {
// Find index by evaluating plural form for value.
index = this.getPluralForm( domain, n );
}
key = singular;
// If provided, context is prepended to key with delimiter.
if ( context ) {
key = context + this.options.contextDelimiter + singular;
}
entry = this.data[ domain ][ key ];
// Verify not only that entry exists, but that the intended index is within
// range and non-empty.
if ( entry && entry[ index ] ) {
return entry[ index ];
}
if ( this.options.onMissingKey ) {
this.options.onMissingKey( singular, domain );
}
// If entry not found, fall back to singular vs. plural with zero index
// representing the singular value.
return index === 0 ? singular : plural;
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/i18n/build-module/create-i18n.js
/**
* External dependencies
*/
/**
* @typedef {Record<string,any>} LocaleData
*/
/**
* Default locale data to use for Tannin domain when not otherwise provided.
* Assumes an English plural forms expression.
*
* @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
*
* Returns locale data by domain in a
* Jed-formatted JSON object shape.
*
* @see http://messageformat.github.io/Jed/
*/
/**
* @typedef {(data?: LocaleData, domain?: string) => void} SetLocaleData
*
* Merges locale data into the Tannin instance by domain. Note that this
* function will overwrite the domain configuration. Accepts data in a
* Jed-formatted JSON object shape.
*
* @see http://messageformat.github.io/Jed/
*/
/**
* @typedef {(data?: LocaleData, domain?: string) => void} AddLocaleData
*
* Merges locale data into the Tannin instance by domain. Note that this
* function will also merge the domain configuration. Accepts data in a
* Jed-formatted JSON object shape.
*
* @see http://messageformat.github.io/Jed/
*/
/**
* @typedef {(data?: LocaleData, domain?: string) => void} ResetLocaleData
*
* 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.
*
* @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} __
*
* Retrieve the translation of text.
*
* @see https://developer.wordpress.org/reference/functions/__/
*/
/**
* @typedef {(text: string, context: string, domain?: string) => string} _x
*
* Retrieve translated string with gettext context.
*
* @see https://developer.wordpress.org/reference/functions/_x/
*/
/**
* @typedef {(single: string, plural: string, number: number, domain?: string) => string} _n
*
* Translates and retrieves the singular or plural form based on the supplied
* number.
*
* @see https://developer.wordpress.org/reference/functions/_n/
*/
/**
* @typedef {(single: string, plural: string, number: number, context: string, domain?: string) => string} _nx
*
* Translates and retrieves the singular or plural form based on the supplied
* number, with gettext context.
*
* @see https://developer.wordpress.org/reference/functions/_nx/
*/
/**
* @typedef {() => boolean} IsRtl
*
* Check if current locale is RTL.
*
* **RTL (Right To Left)** is a locale property indicating that text is written from right to left.
* For example, the `he` locale (for Hebrew) specifies right-to-left. Arabic (ar) is another common
* 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 */
/**
* An i18n instance
*
* @typedef I18n
* @property {GetLocaleData} getLocaleData Returns locale data by domain in a Jed-formatted JSON object shape.
* @property {SetLocaleData} setLocaleData Merges locale data into the Tannin instance by domain. Note that this
* function will overwrite the domain configuration. Accepts data in a
* Jed-formatted JSON object shape.
* @property {AddLocaleData} addLocaleData Merges locale data into the Tannin instance by domain. Note that this
* function will also merge the domain configuration. Accepts data in a
* Jed-formatted JSON object shape.
* @property {ResetLocaleData} resetLocaleData 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.
* @property {Subscribe} subscribe Subscribes to changes of Tannin locale data.
* @property {__} __ Retrieve the translation of text.
* @property {_x} _x Retrieve translated string with gettext context.
* @property {_n} _n Translates and retrieves the singular or plural form based on the supplied
* number.
* @property {_nx} _nx Translates and retrieves the singular or plural form based on the supplied
* number, with gettext context.
* @property {IsRtl} isRTL Check if current locale is RTL.
* @property {HasTranslation} hasTranslation Check if there is a translation for a given string.
*/
/**
* Create an i18n instance
*
* @param {LocaleData} [initialData] Locale data configuration.
* @param {string} [initialDomain] Domain for which configuration applies.
* @param {Hooks} [hooks] Hooks implementation.
*
* @return {I18n} I18n instance.
*/
const createI18n = (initialData, initialDomain, hooks) => {
/**
* The underlying instance of Tannin to which exported functions interface.
*
* @type {Tannin}
*/
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 = function () {
let domain = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'default';
return tannin.data[domain];
};
/**
* @param {LocaleData} [data]
* @param {string} [domain]
*/
const doSetLocaleData = function (data) {
var _tannin$data$domain;
let domain = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'default';
tannin.data[domain] = { ...tannin.data[domain],
...data
}; // Populate default domain configuration (supported locale date which omits
// a plural forms expression).
tannin.data[domain][''] = { ...DEFAULT_LOCALE_DATA[''],
...((_tannin$data$domain = tannin.data[domain]) === null || _tannin$data$domain === void 0 ? void 0 : _tannin$data$domain[''])
}; // 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 = function (data) {
var _tannin$data$domain2;
let domain = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'default';
tannin.data[domain] = { ...tannin.data[domain],
...data,
// Populate default domain configuration (supported locale date which omits
// a plural forms expression).
'': { ...DEFAULT_LOCALE_DATA[''],
...((_tannin$data$domain2 = tannin.data[domain]) === null || _tannin$data$domain2 === void 0 ? void 0 : _tannin$data$domain2['']),
...(data === null || data === void 0 ? void 0 : data[''])
}
}; // 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.pluralForms = {};
setLocaleData(data, domain);
};
/**
* Wrapper for Tannin's `dcnpgettext`. Populates default locale data if not
* otherwise previously assigned.
*
* @param {string|undefined} domain Domain to retrieve the translated text.
* @param {string|undefined} context Context information for the translators.
* @param {string} single Text to translate if non-plural. Used as
* fallback return value on a caught error.
* @param {string} [plural] The text to be used if the number is
* plural.
* @param {number} [number] The number to compare against to use
* either the singular or plural form.
*
* @return {string} The translated string.
*/
const dcnpgettext = function () {
let domain = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'default';
let context = arguments.length > 1 ? arguments[1] : undefined;
let single = arguments.length > 2 ? arguments[2] : undefined;
let plural = arguments.length > 3 ? arguments[3] : undefined;
let number = arguments.length > 4 ? arguments[4] : undefined;
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 = function () {
let domain = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'default';
return domain;
};
/** @type {__} */
const __ = (text, domain) => {
let translation = dcnpgettext(domain, undefined, text);
if (!hooks) {
return translation;
}
/**
* Filters text with its translation.
*
* @param {string} translation Translated text.
* @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)
);
};
/** @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.
*
* @param {string} translation Translated text.
* @param {string} text Text to translate.
* @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)
);
};
/** @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.
*
* @param {string} translation Translated text.
* @param {string} single The text to be used if the number is singular.
* @param {string} plural The text to be used if the number is plural.
* @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)
);
};
/** @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.
*
* @param {string} translation Translated text.
* @param {string} single The text to be used if the number is singular.
* @param {string} plural The text to be used if the number is plural.
* @param {string} number The number to compare against to use either the singular or plural form.
* @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)
);
};
/** @type {IsRtl} */
const isRTL = () => {
return 'rtl' === _x('ltr', 'text direction');
};
/** @type {HasTranslation} */
const hasTranslation = (single, context, domain) => {
var _tannin$data, _tannin$data2;
const key = context ? context + '\u0004' + single : single;
let result = !!((_tannin$data = tannin.data) !== null && _tannin$data !== void 0 && (_tannin$data2 = _tannin$data[domain !== null && domain !== void 0 ? domain : 'default']) !== null && _tannin$data2 !== void 0 && _tannin$data2[key]);
if (hooks) {
/**
* Filters the presence of a translation in the locale data.
*
* @param {boolean} hasTranslation Whether the translation is present or not..
* @param {string} single The singular form of the translated text (used as key in locale data)
* @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);
}
return result;
};
if (initialData) {
setLocaleData(initialData, initialDomain);
}
if (hooks) {
/**
* @param {string} hookName
*/
const onHookAddedOrRemoved = hookName => {
if (I18N_HOOK_REGEXP.test(hookName)) {
notifyListeners();
}
};
hooks.addAction('hookAdded', 'core/i18n', onHookAddedOrRemoved);
hooks.addAction('hookRemoved', 'core/i18n', onHookAddedOrRemoved);
}
return {
getLocaleData,
setLocaleData,
addLocaleData,
resetLocaleData,
subscribe,
__,
_x,
_n,
_nx,
isRTL,
hasTranslation
};
};
;// CONCATENATED MODULE: external ["wp","hooks"]
var external_wp_hooks_namespaceObject = window["wp"]["hooks"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/i18n/build-module/default-i18n.js
/**
* 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
*/
/**
* @typedef {import('./create-i18n').LocaleData} LocaleData
* @typedef {import('./create-i18n').SubscribeCallback} SubscribeCallback
* @typedef {import('./create-i18n').UnsubscribeCallback} UnsubscribeCallback
*/
/**
* Returns locale data by domain in a Jed-formatted JSON object shape.
*
* @see http://messageformat.github.io/Jed/
*
* @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.
*
* @see http://messageformat.github.io/Jed/
*
* @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.
*
* @see http://messageformat.github.io/Jed/
*
* @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.
*
* @see https://developer.wordpress.org/reference/functions/__/
*
* @param {string} text Text to translate.
* @param {string} [domain] Domain to retrieve the translated text.
*
* @return {string} Translated text.
*/
const __ = i18n.__.bind(i18n);
/**
* Retrieve translated string with gettext context.
*
* @see https://developer.wordpress.org/reference/functions/_x/
*
* @param {string} text Text to translate.
* @param {string} context Context information for the translators.
* @param {string} [domain] Domain to retrieve the translated text.
*
* @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.
*
* @see https://developer.wordpress.org/reference/functions/_n/
*
* @param {string} single The text to be used if the number is singular.
* @param {string} plural The text to be used if the number is plural.
* @param {number} number The number to compare against to use either the
* singular or plural form.
* @param {string} [domain] Domain to retrieve the translated text.
*
* @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.
*
* @see https://developer.wordpress.org/reference/functions/_nx/
*
* @param {string} single The text to be used if the number is singular.
* @param {string} plural The text to be used if the number is plural.
* @param {number} number The number to compare against to use either the
* singular or plural form.
* @param {string} context Context information for the translators.
* @param {string} [domain] Domain to retrieve the translated text.
*
* @return {string} The translated singular or plural form.
*/
const _nx = i18n._nx.bind(i18n);
/**
* Check if current locale is RTL.
*
* **RTL (Right To Left)** is a locale property indicating that text is written from right to left.
* For example, the `he` locale (for Hebrew) specifies right-to-left. Arabic (ar) is another common
* 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`).
*
* @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).
*
* @param {string} single Singular form of the string to look up.
* @param {string} [context] Context information for the translators.
* @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
}();
(window.wp = window.wp || {}).i18n = __webpack_exports__;
/******/ })()
; private-apis.min.js 0000666 00000005074 15123355174 0010310 0 ustar 00 /*! 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 i}});const r=["@wordpress/block-editor","@wordpress/block-library","@wordpress/blocks","@wordpress/components","@wordpress/customize-widgets","@wordpress/data","@wordpress/edit-post","@wordpress/edit-site","@wordpress/edit-widgets","@wordpress/editor"],t=[];let n;try{var s;n=null!==(s=process.env.ALLOW_EXPERIMENT_REREGISTRATION)&&void 0!==s&&s}catch(e){n=!1}const i=(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:a,unlock:d}};function a(e,o){if(!e)throw new Error("Cannot lock an undefined object.");l in e||(e[l]={}),u.set(e[l],o)}function d(e){if(!e)throw new Error("Cannot unlock an undefined object.");if(!(l in e))throw new Error("Cannot unlock an object that was not locked before. ");return u.get(e[l])}const u=new WeakMap,l=Symbol("Private API ID");(window.wp=window.wp||{}).privateApis=o}(); blob.js 0000666 00000007346 15123355174 0006044 0 ustar 00 /******/ (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__ = {};
__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 */ });
/**
* @type {Record<string, File|undefined>}
*/
const cache = {};
/**
* Create a blob URL from a file.
*
* @param {File} file The file to create a blob URL for.
*
* @return {string} The blob URL.
*/
function createBlobURL(file) {
const url = 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
* `undefined`.
*
* @param {string} url The blob URL.
*
* @return {File|undefined} The file for the blob URL.
*/
function getBlobByURL(url) {
return cache[url];
}
/**
* Retrieve a blob type based on URL. The file must have been created by
* `createBlobURL` and not removed by `revokeBlobURL`, otherwise it will return
* `undefined`.
*
* @param {string} url The blob URL.
*
* @return {string|undefined} The blob type.
*/
function getBlobTypeByURL(url) {
var _getBlobByURL;
return (_getBlobByURL = getBlobByURL(url)) === null || _getBlobByURL === void 0 ? void 0 : _getBlobByURL.type.split('/')[0]; // 0: media type , 1: file extension eg ( type: 'image/jpeg' ).
}
/**
* Remove the resource and file cache from memory.
*
* @param {string} url The blob URL.
*/
function revokeBlobURL(url) {
if (cache[url]) {
window.URL.revokeObjectURL(url);
}
delete cache[url];
}
/**
* Check whether a url is a blob url.
*
* @param {string} url The URL.
*
* @return {boolean} Is the url a blob url?
*/
function isBlobURL(url) {
if (!url || !url.indexOf) {
return false;
}
return url.indexOf('blob:') === 0;
}
(window.wp = window.wp || {}).blob = __webpack_exports__;
/******/ })()
; url.min.js 0000666 00000021757 15123355174 0006514 0 ustar 00 /*! This file is auto-generated */
!function(){var t={4793:function(t){var n={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","Ấ":"A","Ắ":"A","Ẳ":"A","Ẵ":"A","Ặ":"A","Æ":"AE","Ầ":"A","Ằ":"A","Ȃ":"A","Ç":"C","Ḉ":"C","È":"E","É":"E","Ê":"E","Ë":"E","Ế":"E","Ḗ":"E","Ề":"E","Ḕ":"E","Ḝ":"E","Ȇ":"E","Ì":"I","Í":"I","Î":"I","Ï":"I","Ḯ":"I","Ȋ":"I","Ð":"D","Ñ":"N","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","Ố":"O","Ṍ":"O","Ṓ":"O","Ȏ":"O","Ù":"U","Ú":"U","Û":"U","Ü":"U","Ý":"Y","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","ấ":"a","ắ":"a","ẳ":"a","ẵ":"a","ặ":"a","æ":"ae","ầ":"a","ằ":"a","ȃ":"a","ç":"c","ḉ":"c","è":"e","é":"e","ê":"e","ë":"e","ế":"e","ḗ":"e","ề":"e","ḕ":"e","ḝ":"e","ȇ":"e","ì":"i","í":"i","î":"i","ï":"i","ḯ":"i","ȋ":"i","ð":"d","ñ":"n","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","ố":"o","ṍ":"o","ṓ":"o","ȏ":"o","ù":"u","ú":"u","û":"u","ü":"u","ý":"y","ÿ":"y","Ā":"A","ā":"a","Ă":"A","ă":"a","Ą":"A","ą":"a","Ć":"C","ć":"c","Ĉ":"C","ĉ":"c","Ċ":"C","ċ":"c","Č":"C","č":"c","C̆":"C","c̆":"c","Ď":"D","ď":"d","Đ":"D","đ":"d","Ē":"E","ē":"e","Ĕ":"E","ĕ":"e","Ė":"E","ė":"e","Ę":"E","ę":"e","Ě":"E","ě":"e","Ĝ":"G","Ǵ":"G","ĝ":"g","ǵ":"g","Ğ":"G","ğ":"g","Ġ":"G","ġ":"g","Ģ":"G","ģ":"g","Ĥ":"H","ĥ":"h","Ħ":"H","ħ":"h","Ḫ":"H","ḫ":"h","Ĩ":"I","ĩ":"i","Ī":"I","ī":"i","Ĭ":"I","ĭ":"i","Į":"I","į":"i","İ":"I","ı":"i","IJ":"IJ","ij":"ij","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","Ḱ":"K","ḱ":"k","K̆":"K","k̆":"k","Ĺ":"L","ĺ":"l","Ļ":"L","ļ":"l","Ľ":"L","ľ":"l","Ŀ":"L","ŀ":"l","Ł":"l","ł":"l","Ḿ":"M","ḿ":"m","M̆":"M","m̆":"m","Ń":"N","ń":"n","Ņ":"N","ņ":"n","Ň":"N","ň":"n","ʼn":"n","N̆":"N","n̆":"n","Ō":"O","ō":"o","Ŏ":"O","ŏ":"o","Ő":"O","ő":"o","Œ":"OE","œ":"oe","P̆":"P","p̆":"p","Ŕ":"R","ŕ":"r","Ŗ":"R","ŗ":"r","Ř":"R","ř":"r","R̆":"R","r̆":"r","Ȓ":"R","ȓ":"r","Ś":"S","ś":"s","Ŝ":"S","ŝ":"s","Ş":"S","Ș":"S","ș":"s","ş":"s","Š":"S","š":"s","ß":"ss","Ţ":"T","ţ":"t","ț":"t","Ț":"T","Ť":"T","ť":"t","Ŧ":"T","ŧ":"t","T̆":"T","t̆":"t","Ũ":"U","ũ":"u","Ū":"U","ū":"u","Ŭ":"U","ŭ":"u","Ů":"U","ů":"u","Ű":"U","ű":"u","Ų":"U","ų":"u","Ȗ":"U","ȗ":"u","V̆":"V","v̆":"v","Ŵ":"W","ŵ":"w","Ẃ":"W","ẃ":"w","X̆":"X","x̆":"x","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Y̆":"Y","y̆":"y","Ź":"Z","ź":"z","Ż":"Z","ż":"z","Ž":"Z","ž":"z","ſ":"s","ƒ":"f","Ơ":"O","ơ":"o","Ư":"U","ư":"u","Ǎ":"A","ǎ":"a","Ǐ":"I","ǐ":"i","Ǒ":"O","ǒ":"o","Ǔ":"U","ǔ":"u","Ǖ":"U","ǖ":"u","Ǘ":"U","ǘ":"u","Ǚ":"U","ǚ":"u","Ǜ":"U","ǜ":"u","Ứ":"U","ứ":"u","Ṹ":"U","ṹ":"u","Ǻ":"A","ǻ":"a","Ǽ":"AE","ǽ":"ae","Ǿ":"O","ǿ":"o","Þ":"TH","þ":"th","Ṕ":"P","ṕ":"p","Ṥ":"S","ṥ":"s","X́":"X","x́":"x","Ѓ":"Г","ѓ":"г","Ќ":"К","ќ":"к","A̋":"A","a̋":"a","E̋":"E","e̋":"e","I̋":"I","i̋":"i","Ǹ":"N","ǹ":"n","Ồ":"O","ồ":"o","Ṑ":"O","ṑ":"o","Ừ":"U","ừ":"u","Ẁ":"W","ẁ":"w","Ỳ":"Y","ỳ":"y","Ȁ":"A","ȁ":"a","Ȅ":"E","ȅ":"e","Ȉ":"I","ȉ":"i","Ȍ":"O","ȍ":"o","Ȑ":"R","ȑ":"r","Ȕ":"U","ȕ":"u","B̌":"B","b̌":"b","Č̣":"C","č̣":"c","Ê̌":"E","ê̌":"e","F̌":"F","f̌":"f","Ǧ":"G","ǧ":"g","Ȟ":"H","ȟ":"h","J̌":"J","ǰ":"j","Ǩ":"K","ǩ":"k","M̌":"M","m̌":"m","P̌":"P","p̌":"p","Q̌":"Q","q̌":"q","Ř̩":"R","ř̩":"r","Ṧ":"S","ṧ":"s","V̌":"V","v̌":"v","W̌":"W","w̌":"w","X̌":"X","x̌":"x","Y̌":"Y","y̌":"y","A̧":"A","a̧":"a","B̧":"B","b̧":"b","Ḑ":"D","ḑ":"d","Ȩ":"E","ȩ":"e","Ɛ̧":"E","ɛ̧":"e","Ḩ":"H","ḩ":"h","I̧":"I","i̧":"i","Ɨ̧":"I","ɨ̧":"i","M̧":"M","m̧":"m","O̧":"O","o̧":"o","Q̧":"Q","q̧":"q","U̧":"U","u̧":"u","X̧":"X","x̧":"x","Z̧":"Z","z̧":"z","й":"и","Й":"И","ё":"е","Ё":"Е"},e=Object.keys(n).join("|"),r=new RegExp(e,"g"),o=new RegExp(e,"");function u(t){return n[t]}var i=function(t){return t.replace(r,u)};t.exports=i,t.exports.has=function(t){return!!t.match(o)},t.exports.remove=i}},n={};function e(r){var o=n[r];if(void 0!==o)return o.exports;var u=n[r]={exports:{}};return t[r](u,u.exports,e),u.exports}e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,{a:n}),n},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]})},e.o=function(t,n){return Object.prototype.hasOwnProperty.call(t,n)},e.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var r={};!function(){"use strict";function t(t){try{return new URL(t),!0}catch{return!1}}e.r(r),e.d(r,{addQueryArgs:function(){return O},buildQueryString:function(){return p},cleanForSlug:function(){return j},filterURLForDisplay:function(){return w},getAuthority:function(){return c},getFilename:function(){return C},getFragment:function(){return y},getPath:function(){return a},getPathAndQueryString:function(){return d},getProtocol:function(){return u},getQueryArg:function(){return U},getQueryArgs:function(){return A},getQueryString:function(){return l},hasQueryArg:function(){return E},isEmail:function(){return o},isURL:function(){return t},isValidAuthority:function(){return s},isValidFragment:function(){return h},isValidPath:function(){return f},isValidProtocol:function(){return i},isValidQueryString:function(){return g},normalizePath:function(){return P},prependHTTP:function(){return x},removeQueryArgs:function(){return I},safeDecodeURI:function(){return b},safeDecodeURIComponent:function(){return m}});const n=/^(mailto:)?[a-z0-9._%+-]+@[a-z0-9][a-z0-9.-]*\.[a-z]{2,63}$/i;function o(t){return n.test(t)}function u(t){const n=/^([^\s:]+:)/.exec(t);if(n)return n[1]}function i(t){return!!t&&/^[a-z\-.\+]+[0-9]*:$/i.test(t)}function c(t){const n=/^[^\/\s:]+:(?:\/\/)?\/?([^\/\s#?]+)[\/#?]{0,1}\S*$/.exec(t);if(n)return n[1]}function s(t){return!!t&&/^[^\s#?]+$/.test(t)}function a(t){const n=/^[^\/\s:]+:(?:\/\/)?[^\/\s#?]+[\/]([^\s#?]+)[#?]{0,1}\S*$/.exec(t);if(n)return n[1]}function f(t){return!!t&&/^[^\s#?]+$/.test(t)}function l(t){let n;try{n=new URL(t,"http://example.com").search.substring(1)}catch(t){}if(n)return n}function p(t){let n="";const e=Object.entries(t);let r;for(;r=e.shift();){let[t,o]=r;if(Array.isArray(o)||o&&o.constructor===Object){const n=Object.entries(o).reverse();for(const[r,o]of n)e.unshift([`${t}[${r}]`,o])}else void 0!==o&&(null===o&&(o=""),n+="&"+[t,o].map(encodeURIComponent).join("="))}return n.substr(1)}function g(t){return!!t&&/^[^\s#?\/]+$/.test(t)}function d(t){const n=a(t),e=l(t);let r="/";return n&&(r+=n),e&&(r+=`?${e}`),r}function y(t){const n=/^\S+?(#[^\s\?]*)/.exec(t);if(n)return n[1]}function h(t){return!!t&&/^#[^\s#?\/]*$/.test(t)}function m(t){try{return decodeURIComponent(t)}catch(n){return t}}function A(t){return(l(t)||"").replace(/\+/g,"%20").split("&").reduce(((t,n)=>{const[e,r=""]=n.split("=").filter(Boolean).map(m);if(e){!function(t,n,e){const r=n.length,o=r-1;for(let u=0;u<r;u++){let r=n[u];!r&&Array.isArray(t)&&(r=t.length.toString()),r=["__proto__","constructor","prototype"].includes(r)?r.toUpperCase():r;const i=!isNaN(Number(n[u+1]));t[r]=u===o?e:t[r]||(i?[]:{}),Array.isArray(t[r])&&!i&&(t[r]={...t[r]}),t=t[r]}}(t,e.replace(/\]/g,"").split("["),r)}return t}),Object.create(null))}function O(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",n=arguments.length>1?arguments[1]:void 0;if(!n||!Object.keys(n).length)return t;let e=t;const r=t.indexOf("?");return-1!==r&&(n=Object.assign(A(t),n),e=e.substr(0,r)),e+"?"+p(n)}function U(t,n){return A(t)[n]}function E(t,n){return void 0!==U(t,n)}function I(t){const n=t.indexOf("?");if(-1===n)return t;const e=A(t),r=t.substr(0,n);for(var o=arguments.length,u=new Array(o>1?o-1:0),i=1;i<o;i++)u[i-1]=arguments[i];u.forEach((t=>delete e[t]));const c=p(e);return c?r+"?"+c:r}const v=/^(?:[a-z]+:|#|\?|\.|\/)/i;function x(t){return t?(t=t.trim(),v.test(t)||o(t)?t:"http://"+t):t}function b(t){try{return decodeURI(t)}catch(n){return t}}function w(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,e=t.replace(/^(?:https?:)\/\/(?:www\.)?/,"");e.match(/^[^\/]+\/$/)&&(e=e.replace("/",""));const r=/([\w|:])*\.(?:jpg|jpeg|gif|png|svg)/;if(!n||e.length<=n||!e.match(r))return e;e=e.split("?")[0];const o=e.split("/"),u=o[o.length-1];if(u.length<=n)return"…"+e.slice(-n);const i=u.lastIndexOf("."),[c,s]=[u.slice(0,i),u.slice(i+1)],a=c.slice(-3)+"."+s;return u.slice(0,n-a.length-1)+"…"+a}var R=e(4793),S=e.n(R);function j(t){return t?S()(t).replace(/[\s\./]+/g,"-").replace(/[^\p{L}\p{N}_-]+/gu,"").toLowerCase().replace(/-+/g,"-").replace(/(^-+)|(-+$)/g,""):""}function C(t){let n;try{n=new URL(t,"http://example.com").pathname.split("/").pop()}catch(t){}if(n)return n}function P(t){const n=t.split("?"),e=n[1],r=n[0];return e?r+"?"+e.split("&").map((t=>t.split("="))).map((t=>t.map(decodeURIComponent))).sort(((t,n)=>t[0].localeCompare(n[0]))).map((t=>t.map(encodeURIComponent))).map((t=>t.join("="))).join("&"):r}}(),(window.wp=window.wp||{}).url=r}(); wordcount.min.js 0000666 00000005104 15123355174 0007722 0 ustar 00 /*! This file is auto-generated */
!function(){"use strict";var e={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,{count:function(){return g}});const r={HTMLRegExp:/<\/?[a-z][^>]*?>/gi,HTMLcommentRegExp:/<!--[\s\S]*?-->/g,spaceRegExp:/ | /gi,HTMLEntityRegExp:/&\S+?;/g,connectorRegExp:/--|\u2014/g,removeRegExp:new RegExp(["[","!-/:-@[-`{-~","-¿×÷"," -⯿","⸀-","]"].join(""),"g"),astralRegExp:/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,wordsRegExp:/\S\s+/g,characters_excluding_spacesRegExp:/\S/g,characters_including_spacesRegExp:/[^\f\n\r\t\v\u00AD\u2028\u2029]/g,l10n:{type:"words"}};function t(e,n){return n.replace(e.HTMLRegExp,"\n")}function c(e,n){return n.replace(e.astralRegExp,"a")}function o(e,n){return n.replace(e.HTMLEntityRegExp,"")}function u(e,n){return n.replace(e.connectorRegExp," ")}function l(e,n){return n.replace(e.removeRegExp,"")}function i(e,n){return n.replace(e.HTMLcommentRegExp,"")}function s(e,n){return e.shortcodesRegExp?n.replace(e.shortcodesRegExp,"\n"):n}function a(e,n){return n.replace(e.spaceRegExp," ")}function p(e,n){return n.replace(e.HTMLEntityRegExp,"a")}function d(e,n,r){var o,u;return e=[t.bind(null,r),i.bind(null,r),s.bind(null,r),c.bind(null,r),a.bind(null,r),p.bind(null,r)].reduce(((e,n)=>n(e)),e),null!==(o=null===(u=(e+="\n").match(n))||void 0===u?void 0:u.length)&&void 0!==o?o:0}function g(e,n,c){const p=function(e,n){var t,c;const o=Object.assign({},r,n);return o.shortcodes=null!==(t=null===(c=o.l10n)||void 0===c?void 0:c.shortcodes)&&void 0!==t?t:[],o.shortcodes&&o.shortcodes.length&&(o.shortcodesRegExp=new RegExp("\\[\\/?(?:"+o.shortcodes.join("|")+")[^\\]]*?\\]","g")),o.type=e,"characters_excluding_spaces"!==o.type&&"characters_including_spaces"!==o.type&&(o.type="words"),o}(n,c);let g;switch(p.type){case"words":return g=p.wordsRegExp,function(e,n,r){var c,p;return e=[t.bind(null,r),i.bind(null,r),s.bind(null,r),a.bind(null,r),o.bind(null,r),u.bind(null,r),l.bind(null,r)].reduce(((e,n)=>n(e)),e),null!==(c=null===(p=(e+="\n").match(n))||void 0===p?void 0:p.length)&&void 0!==c?c:0}(e,g,p);case"characters_including_spaces":return g=p.characters_including_spacesRegExp,d(e,g,p);case"characters_excluding_spaces":return g=p.characters_excluding_spacesRegExp,d(e,g,p);default:return 0}}(window.wp=window.wp||{}).wordcount=n}(); reusable-blocks.min.js 0000666 00000013211 15123355174 0010751 0 ustar 00 /*! This file is auto-generated */
!function(){"use strict";var e={d:function(t,n){for(var o in n)e.o(n,o)&&!e.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:n[o]})},o: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,{ReusableBlocksMenuItems:function(){return C},store:function(){return k}});var n={};e.r(n),e.d(n,{__experimentalConvertBlockToStatic:function(){return s},__experimentalConvertBlocksToReusable:function(){return a},__experimentalDeleteReusableBlock:function(){return u},__experimentalSetEditingReusableBlock:function(){return d}});var o={};e.r(o),e.d(o,{__experimentalIsEditingReusableBlock:function(){return b}});var l=window.wp.data,r=window.wp.blockEditor,c=window.wp.blocks,i=window.wp.i18n;const s=e=>t=>{let{registry:n}=t;const o=n.select(r.store).getBlock(e),l=n.select("core").getEditedEntityRecord("postType","wp_block",o.attributes.ref),i=(0,c.parse)("function"==typeof l.content?l.content(l):l.content);n.dispatch(r.store).replaceBlocks(o.clientId,i)},a=(e,t)=>async n=>{let{registry:o,dispatch:l}=n;const s={title:t||(0,i.__)("Untitled Reusable block"),content:(0,c.serialize)(o.select(r.store).getBlocksByClientId(e)),status:"publish"},a=await o.dispatch("core").saveEntityRecord("postType","wp_block",s),u=(0,c.createBlock)("core/block",{ref:a.id});o.dispatch(r.store).replaceBlocks(e,u),l.__experimentalSetEditingReusableBlock(u.clientId,!0)},u=e=>async t=>{let{registry:n}=t;if(!n.select("core").getEditedEntityRecord("postType","wp_block",e))return;const o=n.select(r.store).getBlocks().filter((t=>(0,c.isReusableBlock)(t)&&t.attributes.ref===e)).map((e=>e.clientId));o.length&&n.dispatch(r.store).removeBlocks(o),await n.dispatch("core").deleteEntityRecord("postType","wp_block",e)};function d(e,t){return{type:"SET_EDITING_REUSABLE_BLOCK",clientId:e,isEditing:t}}var p=(0,l.combineReducers)({isEditingReusableBlock:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;return"SET_EDITING_REUSABLE_BLOCK"===(null==t?void 0:t.type)?{...e,[t.clientId]:t.isEditing}:e}});function b(e,t){return e.isEditingReusableBlock[t]}const k=(0,l.createReduxStore)("core/reusable-blocks",{actions:n,reducer:p,selectors:o});(0,l.register)(k);var m=window.wp.element,_=window.wp.components,w=window.wp.primitives;var g=(0,m.createElement)(w.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,m.createElement)(w.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"})),B=window.wp.notices,y=window.wp.coreData;function E(e){let{clientIds:t,rootClientId:n}=e;const[o,s]=(0,m.useState)(!1),[a,u]=(0,m.useState)(""),d=(0,l.useSelect)((e=>{var o;const{canUser:l}=e(y.store),{getBlocksByClientId:i,canInsertBlockType:s}=e(r.store),a=null!==(o=i(t))&&void 0!==o?o:[];return!(1===a.length&&a[0]&&(0,c.isReusableBlock)(a[0])&&!!e(y.store).getEntityRecord("postType","wp_block",a[0].attributes.ref))&&s("core/block",n)&&a.every((e=>!!e&&e.isValid&&(0,c.hasBlockSupport)(e.name,"reusable",!0)))&&!!l("create","blocks")}),[t]),{__experimentalConvertBlocksToReusable:p}=(0,l.useDispatch)(k),{createSuccessNotice:b,createErrorNotice:w}=(0,l.useDispatch)(B.store),E=(0,m.useCallback)((async function(e){try{await p(t,e),b((0,i.__)("Reusable block created."),{type:"snackbar"})}catch(e){w(e.message,{type:"snackbar"})}}),[t]);return d?(0,m.createElement)(r.BlockSettingsMenuControls,null,(e=>{let{onClose:t}=e;return(0,m.createElement)(m.Fragment,null,(0,m.createElement)(_.MenuItem,{icon:g,onClick:()=>{s(!0)}},(0,i.__)("Create Reusable block")),o&&(0,m.createElement)(_.Modal,{title:(0,i.__)("Create Reusable block"),onRequestClose:()=>{s(!1),u("")},overlayClassName:"reusable-blocks-menu-items__convert-modal"},(0,m.createElement)("form",{onSubmit:e=>{e.preventDefault(),E(a),s(!1),u(""),t()}},(0,m.createElement)(_.__experimentalVStack,{spacing:"5"},(0,m.createElement)(_.TextControl,{__nextHasNoMarginBottom:!0,label:(0,i.__)("Name"),value:a,onChange:u}),(0,m.createElement)(_.__experimentalHStack,{justify:"right"},(0,m.createElement)(_.Button,{variant:"tertiary",onClick:()=>{s(!1),u("")}},(0,i.__)("Cancel")),(0,m.createElement)(_.Button,{variant:"primary",type:"submit"},(0,i.__)("Save")))))))})):null}var v=window.wp.url;var f=function(e){let{clientId:t}=e;const{canRemove:n,isVisible:o,innerBlockCount:s}=(0,l.useSelect)((e=>{const{getBlock:n,canRemoveBlock:o,getBlockCount:l}=e(r.store),{canUser:i}=e(y.store),s=n(t);return{canRemove:o(t),isVisible:!!s&&(0,c.isReusableBlock)(s)&&!!i("update","blocks",s.attributes.ref),innerBlockCount:l(t)}}),[t]),{__experimentalConvertBlockToStatic:a}=(0,l.useDispatch)(k);return o?(0,m.createElement)(r.BlockSettingsMenuControls,null,(0,m.createElement)(_.MenuItem,{href:(0,v.addQueryArgs)("edit.php",{post_type:"wp_block"})},(0,i.__)("Manage Reusable blocks")),n&&(0,m.createElement)(_.MenuItem,{onClick:()=>a(t)},s>1?(0,i.__)("Convert to regular blocks"):(0,i.__)("Convert to regular block"))):null};var C=(0,l.withSelect)((e=>{const{getSelectedBlockClientIds:t}=e(r.store);return{clientIds:t()}}))((function(e){let{clientIds:t,rootClientId:n}=e;return(0,m.createElement)(m.Fragment,null,(0,m.createElement)(E,{clientIds:t,rootClientId:n}),1===t.length&&(0,m.createElement)(f,{clientId:t[0]}))}));(window.wp=window.wp||{}).reusableBlocks=t}(); blocks.min.js 0000666 00000514354 15123355174 0007167 0 ustar 00 /*! This file is auto-generated */
!function(){var e={5619:function(e){"use strict";e.exports=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var n,o,a;if(Array.isArray(t)){if((n=t.length)!=r.length)return!1;for(o=n;0!=o--;)if(!e(t[o],r[o]))return!1;return!0}if(t instanceof Map&&r instanceof Map){if(t.size!==r.size)return!1;for(o of t.entries())if(!r.has(o[0]))return!1;for(o of t.entries())if(!e(o[1],r.get(o[0])))return!1;return!0}if(t instanceof Set&&r instanceof Set){if(t.size!==r.size)return!1;for(o of t.entries())if(!r.has(o[0]))return!1;return!0}if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(r)){if((n=t.length)!=r.length)return!1;for(o=n;0!=o--;)if(t[o]!==r[o])return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if((n=(a=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(o=n;0!=o--;)if(!Object.prototype.hasOwnProperty.call(r,a[o]))return!1;for(o=n;0!=o--;){var i=a[o];if(!e(t[i],r[i]))return!1}return!0}return t!=t&&r!=r}},9756:function(e){e.exports=function(e,t){var r,n,o=0;function a(){var a,i,s=r,l=arguments.length;e:for(;s;){if(s.args.length===arguments.length){for(i=0;i<l;i++)if(s.args[i]!==arguments[i]){s=s.next;continue e}return s!==r&&(s===n&&(n=s.prev),s.prev.next=s.next,s.next&&(s.next.prev=s.prev),s.next=r,s.prev=null,r.prev=s,r=s),s.val}s=s.next}for(a=new Array(l),i=0;i<l;i++)a[i]=arguments[i];return s={args:a,val:e.apply(null,a)},r?(r.prev=s,s.next=r):n=s,o===t.maxSize?(n=n.prev).next=null:o++,r=s,s.val}return t=t||{},a.clear=function(){r=null,n=null,o=0},a}},4793:function(e){var t={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","Ấ":"A","Ắ":"A","Ẳ":"A","Ẵ":"A","Ặ":"A","Æ":"AE","Ầ":"A","Ằ":"A","Ȃ":"A","Ç":"C","Ḉ":"C","È":"E","É":"E","Ê":"E","Ë":"E","Ế":"E","Ḗ":"E","Ề":"E","Ḕ":"E","Ḝ":"E","Ȇ":"E","Ì":"I","Í":"I","Î":"I","Ï":"I","Ḯ":"I","Ȋ":"I","Ð":"D","Ñ":"N","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","Ố":"O","Ṍ":"O","Ṓ":"O","Ȏ":"O","Ù":"U","Ú":"U","Û":"U","Ü":"U","Ý":"Y","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","ấ":"a","ắ":"a","ẳ":"a","ẵ":"a","ặ":"a","æ":"ae","ầ":"a","ằ":"a","ȃ":"a","ç":"c","ḉ":"c","è":"e","é":"e","ê":"e","ë":"e","ế":"e","ḗ":"e","ề":"e","ḕ":"e","ḝ":"e","ȇ":"e","ì":"i","í":"i","î":"i","ï":"i","ḯ":"i","ȋ":"i","ð":"d","ñ":"n","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","ố":"o","ṍ":"o","ṓ":"o","ȏ":"o","ù":"u","ú":"u","û":"u","ü":"u","ý":"y","ÿ":"y","Ā":"A","ā":"a","Ă":"A","ă":"a","Ą":"A","ą":"a","Ć":"C","ć":"c","Ĉ":"C","ĉ":"c","Ċ":"C","ċ":"c","Č":"C","č":"c","C̆":"C","c̆":"c","Ď":"D","ď":"d","Đ":"D","đ":"d","Ē":"E","ē":"e","Ĕ":"E","ĕ":"e","Ė":"E","ė":"e","Ę":"E","ę":"e","Ě":"E","ě":"e","Ĝ":"G","Ǵ":"G","ĝ":"g","ǵ":"g","Ğ":"G","ğ":"g","Ġ":"G","ġ":"g","Ģ":"G","ģ":"g","Ĥ":"H","ĥ":"h","Ħ":"H","ħ":"h","Ḫ":"H","ḫ":"h","Ĩ":"I","ĩ":"i","Ī":"I","ī":"i","Ĭ":"I","ĭ":"i","Į":"I","į":"i","İ":"I","ı":"i","IJ":"IJ","ij":"ij","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","Ḱ":"K","ḱ":"k","K̆":"K","k̆":"k","Ĺ":"L","ĺ":"l","Ļ":"L","ļ":"l","Ľ":"L","ľ":"l","Ŀ":"L","ŀ":"l","Ł":"l","ł":"l","Ḿ":"M","ḿ":"m","M̆":"M","m̆":"m","Ń":"N","ń":"n","Ņ":"N","ņ":"n","Ň":"N","ň":"n","ʼn":"n","N̆":"N","n̆":"n","Ō":"O","ō":"o","Ŏ":"O","ŏ":"o","Ő":"O","ő":"o","Œ":"OE","œ":"oe","P̆":"P","p̆":"p","Ŕ":"R","ŕ":"r","Ŗ":"R","ŗ":"r","Ř":"R","ř":"r","R̆":"R","r̆":"r","Ȓ":"R","ȓ":"r","Ś":"S","ś":"s","Ŝ":"S","ŝ":"s","Ş":"S","Ș":"S","ș":"s","ş":"s","Š":"S","š":"s","ß":"ss","Ţ":"T","ţ":"t","ț":"t","Ț":"T","Ť":"T","ť":"t","Ŧ":"T","ŧ":"t","T̆":"T","t̆":"t","Ũ":"U","ũ":"u","Ū":"U","ū":"u","Ŭ":"U","ŭ":"u","Ů":"U","ů":"u","Ű":"U","ű":"u","Ų":"U","ų":"u","Ȗ":"U","ȗ":"u","V̆":"V","v̆":"v","Ŵ":"W","ŵ":"w","Ẃ":"W","ẃ":"w","X̆":"X","x̆":"x","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Y̆":"Y","y̆":"y","Ź":"Z","ź":"z","Ż":"Z","ż":"z","Ž":"Z","ž":"z","ſ":"s","ƒ":"f","Ơ":"O","ơ":"o","Ư":"U","ư":"u","Ǎ":"A","ǎ":"a","Ǐ":"I","ǐ":"i","Ǒ":"O","ǒ":"o","Ǔ":"U","ǔ":"u","Ǖ":"U","ǖ":"u","Ǘ":"U","ǘ":"u","Ǚ":"U","ǚ":"u","Ǜ":"U","ǜ":"u","Ứ":"U","ứ":"u","Ṹ":"U","ṹ":"u","Ǻ":"A","ǻ":"a","Ǽ":"AE","ǽ":"ae","Ǿ":"O","ǿ":"o","Þ":"TH","þ":"th","Ṕ":"P","ṕ":"p","Ṥ":"S","ṥ":"s","X́":"X","x́":"x","Ѓ":"Г","ѓ":"г","Ќ":"К","ќ":"к","A̋":"A","a̋":"a","E̋":"E","e̋":"e","I̋":"I","i̋":"i","Ǹ":"N","ǹ":"n","Ồ":"O","ồ":"o","Ṑ":"O","ṑ":"o","Ừ":"U","ừ":"u","Ẁ":"W","ẁ":"w","Ỳ":"Y","ỳ":"y","Ȁ":"A","ȁ":"a","Ȅ":"E","ȅ":"e","Ȉ":"I","ȉ":"i","Ȍ":"O","ȍ":"o","Ȑ":"R","ȑ":"r","Ȕ":"U","ȕ":"u","B̌":"B","b̌":"b","Č̣":"C","č̣":"c","Ê̌":"E","ê̌":"e","F̌":"F","f̌":"f","Ǧ":"G","ǧ":"g","Ȟ":"H","ȟ":"h","J̌":"J","ǰ":"j","Ǩ":"K","ǩ":"k","M̌":"M","m̌":"m","P̌":"P","p̌":"p","Q̌":"Q","q̌":"q","Ř̩":"R","ř̩":"r","Ṧ":"S","ṧ":"s","V̌":"V","v̌":"v","W̌":"W","w̌":"w","X̌":"X","x̌":"x","Y̌":"Y","y̌":"y","A̧":"A","a̧":"a","B̧":"B","b̧":"b","Ḑ":"D","ḑ":"d","Ȩ":"E","ȩ":"e","Ɛ̧":"E","ɛ̧":"e","Ḩ":"H","ḩ":"h","I̧":"I","i̧":"i","Ɨ̧":"I","ɨ̧":"i","M̧":"M","m̧":"m","O̧":"O","o̧":"o","Q̧":"Q","q̧":"q","U̧":"U","u̧":"u","X̧":"X","x̧":"x","Z̧":"Z","z̧":"z","й":"и","Й":"И","ё":"е","Ё":"Е"},r=Object.keys(t).join("|"),n=new RegExp(r,"g"),o=new RegExp(r,"");function a(e){return t[e]}var i=function(e){return e.replace(n,a)};e.exports=i,e.exports.has=function(e){return!!e.match(o)},e.exports.remove=i},7308:function(e,t,r){var n;/*! showdown v 1.9.1 - 02-11-2019 */
(function(){function o(e){"use strict";var t={omitExtraWLInCodeBlocks:{defaultValue:!1,describe:"Omit the default extra whiteline added to code blocks",type:"boolean"},noHeaderId:{defaultValue:!1,describe:"Turn on/off generated header id",type:"boolean"},prefixHeaderId:{defaultValue:!1,describe:"Add a prefix to the generated header ids. Passing a string will prefix that string to the header id. Setting to true will add a generic 'section-' prefix",type:"string"},rawPrefixHeaderId:{defaultValue:!1,describe:'Setting this option to true will prevent showdown from modifying the prefix. This might result in malformed IDs (if, for instance, the " char is used in the prefix)',type:"boolean"},ghCompatibleHeaderId:{defaultValue:!1,describe:"Generate header ids compatible with github style (spaces are replaced with dashes, a bunch of non alphanumeric chars are removed)",type:"boolean"},rawHeaderId:{defaultValue:!1,describe:"Remove only spaces, ' and \" from generated header ids (including prefixes), replacing them with dashes (-). WARNING: This might result in malformed ids",type:"boolean"},headerLevelStart:{defaultValue:!1,describe:"The header blocks level start",type:"integer"},parseImgDimensions:{defaultValue:!1,describe:"Turn on/off image dimension parsing",type:"boolean"},simplifiedAutoLink:{defaultValue:!1,describe:"Turn on/off GFM autolink style",type:"boolean"},excludeTrailingPunctuationFromURLs:{defaultValue:!1,describe:"Excludes trailing punctuation from links generated with autoLinking",type:"boolean"},literalMidWordUnderscores:{defaultValue:!1,describe:"Parse midword underscores as literal underscores",type:"boolean"},literalMidWordAsterisks:{defaultValue:!1,describe:"Parse midword asterisks as literal asterisks",type:"boolean"},strikethrough:{defaultValue:!1,describe:"Turn on/off strikethrough support",type:"boolean"},tables:{defaultValue:!1,describe:"Turn on/off tables support",type:"boolean"},tablesHeaderId:{defaultValue:!1,describe:"Add an id to table headers",type:"boolean"},ghCodeBlocks:{defaultValue:!0,describe:"Turn on/off GFM fenced code blocks support",type:"boolean"},tasklists:{defaultValue:!1,describe:"Turn on/off GFM tasklist support",type:"boolean"},smoothLivePreview:{defaultValue:!1,describe:"Prevents weird effects in live previews due to incomplete input",type:"boolean"},smartIndentationFix:{defaultValue:!1,description:"Tries to smartly fix indentation in es6 strings",type:"boolean"},disableForced4SpacesIndentedSublists:{defaultValue:!1,description:"Disables the requirement of indenting nested sublists by 4 spaces",type:"boolean"},simpleLineBreaks:{defaultValue:!1,description:"Parses simple line breaks as <br> (GFM Style)",type:"boolean"},requireSpaceBeforeHeadingText:{defaultValue:!1,description:"Makes adding a space between `#` and the header text mandatory (GFM Style)",type:"boolean"},ghMentions:{defaultValue:!1,description:"Enables github @mentions",type:"boolean"},ghMentionsLink:{defaultValue:"https://github.com/{u}",description:"Changes the link generated by @mentions. Only applies if ghMentions option is enabled.",type:"string"},encodeEmails:{defaultValue:!0,description:"Encode e-mail addresses through the use of Character Entities, transforming ASCII e-mail addresses into its equivalent decimal entities",type:"boolean"},openLinksInNewWindow:{defaultValue:!1,description:"Open all links in new windows",type:"boolean"},backslashEscapesHTMLTags:{defaultValue:!1,description:"Support for HTML Tag escaping. ex: <div>foo</div>",type:"boolean"},emoji:{defaultValue:!1,description:"Enable emoji support. Ex: `this is a :smile: emoji`",type:"boolean"},underline:{defaultValue:!1,description:"Enable support for underline. Syntax is double or triple underscores: `__underline word__`. With this option enabled, underscores no longer parses into `<em>` and `<strong>`",type:"boolean"},completeHTMLDocument:{defaultValue:!1,description:"Outputs a complete html document, including `<html>`, `<head>` and `<body>` tags",type:"boolean"},metadata:{defaultValue:!1,description:"Enable support for document metadata (defined at the top of the document between `«««` and `»»»` or between `---` and `---`).",type:"boolean"},splitAdjacentBlockquotes:{defaultValue:!1,description:"Split adjacent blockquote blocks",type:"boolean"}};if(!1===e)return JSON.parse(JSON.stringify(t));var r={};for(var n in t)t.hasOwnProperty(n)&&(r[n]=t[n].defaultValue);return r}var a={},i={},s={},l=o(!0),c="vanilla",u={github:{omitExtraWLInCodeBlocks:!0,simplifiedAutoLink:!0,excludeTrailingPunctuationFromURLs:!0,literalMidWordUnderscores:!0,strikethrough:!0,tables:!0,tablesHeaderId:!0,ghCodeBlocks:!0,tasklists:!0,disableForced4SpacesIndentedSublists:!0,simpleLineBreaks:!0,requireSpaceBeforeHeadingText:!0,ghCompatibleHeaderId:!0,ghMentions:!0,backslashEscapesHTMLTags:!0,emoji:!0,splitAdjacentBlockquotes:!0},original:{noHeaderId:!0,ghCodeBlocks:!1},ghost:{omitExtraWLInCodeBlocks:!0,parseImgDimensions:!0,simplifiedAutoLink:!0,excludeTrailingPunctuationFromURLs:!0,literalMidWordUnderscores:!0,strikethrough:!0,tables:!0,tablesHeaderId:!0,ghCodeBlocks:!0,tasklists:!0,smoothLivePreview:!0,simpleLineBreaks:!0,requireSpaceBeforeHeadingText:!0,ghMentions:!1,encodeEmails:!0},vanilla:o(!0),allOn:function(){"use strict";var e=o(!0),t={};for(var r in e)e.hasOwnProperty(r)&&(t[r]=!0);return t}()};function d(e,t){"use strict";var r=t?"Error in "+t+" extension->":"Error in unnamed extension",n={valid:!0,error:""};a.helper.isArray(e)||(e=[e]);for(var o=0;o<e.length;++o){var i=r+" sub-extension "+o+": ",s=e[o];if("object"!=typeof s)return n.valid=!1,n.error=i+"must be an object, but "+typeof s+" given",n;if(!a.helper.isString(s.type))return n.valid=!1,n.error=i+'property "type" must be a string, but '+typeof s.type+" given",n;var l=s.type=s.type.toLowerCase();if("language"===l&&(l=s.type="lang"),"html"===l&&(l=s.type="output"),"lang"!==l&&"output"!==l&&"listener"!==l)return n.valid=!1,n.error=i+"type "+l+' is not recognized. Valid values: "lang/language", "output/html" or "listener"',n;if("listener"===l){if(a.helper.isUndefined(s.listeners))return n.valid=!1,n.error=i+'. Extensions of type "listener" must have a property called "listeners"',n}else if(a.helper.isUndefined(s.filter)&&a.helper.isUndefined(s.regex))return n.valid=!1,n.error=i+l+' extensions must define either a "regex" property or a "filter" method',n;if(s.listeners){if("object"!=typeof s.listeners)return n.valid=!1,n.error=i+'"listeners" property must be an object but '+typeof s.listeners+" given",n;for(var c in s.listeners)if(s.listeners.hasOwnProperty(c)&&"function"!=typeof s.listeners[c])return n.valid=!1,n.error=i+'"listeners" property must be an hash of [event name]: [callback]. listeners.'+c+" must be a function but "+typeof s.listeners[c]+" given",n}if(s.filter){if("function"!=typeof s.filter)return n.valid=!1,n.error=i+'"filter" must be a function, but '+typeof s.filter+" given",n}else if(s.regex){if(a.helper.isString(s.regex)&&(s.regex=new RegExp(s.regex,"g")),!(s.regex instanceof RegExp))return n.valid=!1,n.error=i+'"regex" property must either be a string or a RegExp object, but '+typeof s.regex+" given",n;if(a.helper.isUndefined(s.replace))return n.valid=!1,n.error=i+'"regex" extensions must implement a replace string or function',n}}return n}function p(e,t){"use strict";return"¨E"+t.charCodeAt(0)+"E"}a.helper={},a.extensions={},a.setOption=function(e,t){"use strict";return l[e]=t,this},a.getOption=function(e){"use strict";return l[e]},a.getOptions=function(){"use strict";return l},a.resetOptions=function(){"use strict";l=o(!0)},a.setFlavor=function(e){"use strict";if(!u.hasOwnProperty(e))throw Error(e+" flavor was not found");a.resetOptions();var t=u[e];for(var r in c=e,t)t.hasOwnProperty(r)&&(l[r]=t[r])},a.getFlavor=function(){"use strict";return c},a.getFlavorOptions=function(e){"use strict";if(u.hasOwnProperty(e))return u[e]},a.getDefaultOptions=function(e){"use strict";return o(e)},a.subParser=function(e,t){"use strict";if(a.helper.isString(e)){if(void 0===t){if(i.hasOwnProperty(e))return i[e];throw Error("SubParser named "+e+" not registered!")}i[e]=t}},a.extension=function(e,t){"use strict";if(!a.helper.isString(e))throw Error("Extension 'name' must be a string");if(e=a.helper.stdExtName(e),a.helper.isUndefined(t)){if(!s.hasOwnProperty(e))throw Error("Extension named "+e+" is not registered!");return s[e]}"function"==typeof t&&(t=t()),a.helper.isArray(t)||(t=[t]);var r=d(t,e);if(!r.valid)throw Error(r.error);s[e]=t},a.getAllExtensions=function(){"use strict";return s},a.removeExtension=function(e){"use strict";delete s[e]},a.resetExtensions=function(){"use strict";s={}},a.validateExtension=function(e){"use strict";var t=d(e,null);return!!t.valid||(console.warn(t.error),!1)},a.hasOwnProperty("helper")||(a.helper={}),a.helper.isString=function(e){"use strict";return"string"==typeof e||e instanceof String},a.helper.isFunction=function(e){"use strict";return e&&"[object Function]"==={}.toString.call(e)},a.helper.isArray=function(e){"use strict";return Array.isArray(e)},a.helper.isUndefined=function(e){"use strict";return void 0===e},a.helper.forEach=function(e,t){"use strict";if(a.helper.isUndefined(e))throw new Error("obj param is required");if(a.helper.isUndefined(t))throw new Error("callback param is required");if(!a.helper.isFunction(t))throw new Error("callback param must be a function/closure");if("function"==typeof e.forEach)e.forEach(t);else if(a.helper.isArray(e))for(var r=0;r<e.length;r++)t(e[r],r,e);else{if("object"!=typeof e)throw new Error("obj does not seem to be an array or an iterable object");for(var n in e)e.hasOwnProperty(n)&&t(e[n],n,e)}},a.helper.stdExtName=function(e){"use strict";return e.replace(/[_?*+\/\\.^-]/g,"").replace(/\s/g,"").toLowerCase()},a.helper.escapeCharactersCallback=p,a.helper.escapeCharacters=function(e,t,r){"use strict";var n="(["+t.replace(/([\[\]\\])/g,"\\$1")+"])";r&&(n="\\\\"+n);var o=new RegExp(n,"g");return e=e.replace(o,p)},a.helper.unescapeHTMLEntities=function(e){"use strict";return e.replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")};var f=function(e,t,r,n){"use strict";var o,a,i,s,l,c=n||"",u=c.indexOf("g")>-1,d=new RegExp(t+"|"+r,"g"+c.replace(/g/g,"")),p=new RegExp(t,c.replace(/g/g,"")),f=[];do{for(o=0;i=d.exec(e);)if(p.test(i[0]))o++||(s=(a=d.lastIndex)-i[0].length);else if(o&&!--o){l=i.index+i[0].length;var h={left:{start:s,end:a},match:{start:a,end:i.index},right:{start:i.index,end:l},wholeMatch:{start:s,end:l}};if(f.push(h),!u)return f}}while(o&&(d.lastIndex=a));return f};a.helper.matchRecursiveRegExp=function(e,t,r,n){"use strict";for(var o=f(e,t,r,n),a=[],i=0;i<o.length;++i)a.push([e.slice(o[i].wholeMatch.start,o[i].wholeMatch.end),e.slice(o[i].match.start,o[i].match.end),e.slice(o[i].left.start,o[i].left.end),e.slice(o[i].right.start,o[i].right.end)]);return a},a.helper.replaceRecursiveRegExp=function(e,t,r,n,o){"use strict";if(!a.helper.isFunction(t)){var i=t;t=function(){return i}}var s=f(e,r,n,o),l=e,c=s.length;if(c>0){var u=[];0!==s[0].wholeMatch.start&&u.push(e.slice(0,s[0].wholeMatch.start));for(var d=0;d<c;++d)u.push(t(e.slice(s[d].wholeMatch.start,s[d].wholeMatch.end),e.slice(s[d].match.start,s[d].match.end),e.slice(s[d].left.start,s[d].left.end),e.slice(s[d].right.start,s[d].right.end))),d<c-1&&u.push(e.slice(s[d].wholeMatch.end,s[d+1].wholeMatch.start));s[c-1].wholeMatch.end<e.length&&u.push(e.slice(s[c-1].wholeMatch.end)),l=u.join("")}return l},a.helper.regexIndexOf=function(e,t,r){"use strict";if(!a.helper.isString(e))throw"InvalidArgumentError: first parameter of showdown.helper.regexIndexOf function must be a string";if(t instanceof RegExp==!1)throw"InvalidArgumentError: second parameter of showdown.helper.regexIndexOf function must be an instance of RegExp";var n=e.substring(r||0).search(t);return n>=0?n+(r||0):n},a.helper.splitAtIndex=function(e,t){"use strict";if(!a.helper.isString(e))throw"InvalidArgumentError: first parameter of showdown.helper.regexIndexOf function must be a string";return[e.substring(0,t),e.substring(t)]},a.helper.encodeEmailAddress=function(e){"use strict";var t=[function(e){return"&#"+e.charCodeAt(0)+";"},function(e){return"&#x"+e.charCodeAt(0).toString(16)+";"},function(e){return e}];return e=e.replace(/./g,(function(e){if("@"===e)e=t[Math.floor(2*Math.random())](e);else{var r=Math.random();e=r>.9?t[2](e):r>.45?t[1](e):t[0](e)}return e}))},a.helper.padEnd=function(e,t,r){"use strict";return t>>=0,r=String(r||" "),e.length>t?String(e):((t-=e.length)>r.length&&(r+=r.repeat(t/r.length)),String(e)+r.slice(0,t))},"undefined"==typeof console&&(console={warn:function(e){"use strict";alert(e)},log:function(e){"use strict";alert(e)},error:function(e){"use strict";throw e}}),a.helper.regexes={asteriskDashAndColon:/([*_:~])/g},a.helper.emojis={"+1":"👍","-1":"👎",100:"💯",1234:"🔢","1st_place_medal":"🥇","2nd_place_medal":"🥈","3rd_place_medal":"🥉","8ball":"🎱",a:"🅰️",ab:"🆎",abc:"🔤",abcd:"🔡",accept:"🉑",aerial_tramway:"🚡",airplane:"✈️",alarm_clock:"⏰",alembic:"⚗️",alien:"👽",ambulance:"🚑",amphora:"🏺",anchor:"⚓️",angel:"👼",anger:"💢",angry:"😠",anguished:"😧",ant:"🐜",apple:"🍎",aquarius:"♒️",aries:"♈️",arrow_backward:"◀️",arrow_double_down:"⏬",arrow_double_up:"⏫",arrow_down:"⬇️",arrow_down_small:"🔽",arrow_forward:"▶️",arrow_heading_down:"⤵️",arrow_heading_up:"⤴️",arrow_left:"⬅️",arrow_lower_left:"↙️",arrow_lower_right:"↘️",arrow_right:"➡️",arrow_right_hook:"↪️",arrow_up:"⬆️",arrow_up_down:"↕️",arrow_up_small:"🔼",arrow_upper_left:"↖️",arrow_upper_right:"↗️",arrows_clockwise:"🔃",arrows_counterclockwise:"🔄",art:"🎨",articulated_lorry:"🚛",artificial_satellite:"🛰",astonished:"😲",athletic_shoe:"👟",atm:"🏧",atom_symbol:"⚛️",avocado:"🥑",b:"🅱️",baby:"👶",baby_bottle:"🍼",baby_chick:"🐤",baby_symbol:"🚼",back:"🔙",bacon:"🥓",badminton:"🏸",baggage_claim:"🛄",baguette_bread:"🥖",balance_scale:"⚖️",balloon:"🎈",ballot_box:"🗳",ballot_box_with_check:"☑️",bamboo:"🎍",banana:"🍌",bangbang:"‼️",bank:"🏦",bar_chart:"📊",barber:"💈",baseball:"⚾️",basketball:"🏀",basketball_man:"⛹️",basketball_woman:"⛹️‍♀️",bat:"🦇",bath:"🛀",bathtub:"🛁",battery:"🔋",beach_umbrella:"🏖",bear:"🐻",bed:"🛏",bee:"🐝",beer:"🍺",beers:"🍻",beetle:"🐞",beginner:"🔰",bell:"🔔",bellhop_bell:"🛎",bento:"🍱",biking_man:"🚴",bike:"🚲",biking_woman:"🚴‍♀️",bikini:"👙",biohazard:"☣️",bird:"🐦",birthday:"🎂",black_circle:"⚫️",black_flag:"🏴",black_heart:"🖤",black_joker:"🃏",black_large_square:"⬛️",black_medium_small_square:"◾️",black_medium_square:"◼️",black_nib:"✒️",black_small_square:"▪️",black_square_button:"🔲",blonde_man:"👱",blonde_woman:"👱‍♀️",blossom:"🌼",blowfish:"🐡",blue_book:"📘",blue_car:"🚙",blue_heart:"💙",blush:"😊",boar:"🐗",boat:"⛵️",bomb:"💣",book:"📖",bookmark:"🔖",bookmark_tabs:"📑",books:"📚",boom:"💥",boot:"👢",bouquet:"💐",bowing_man:"🙇",bow_and_arrow:"🏹",bowing_woman:"🙇‍♀️",bowling:"🎳",boxing_glove:"🥊",boy:"👦",bread:"🍞",bride_with_veil:"👰",bridge_at_night:"🌉",briefcase:"💼",broken_heart:"💔",bug:"🐛",building_construction:"🏗",bulb:"💡",bullettrain_front:"🚅",bullettrain_side:"🚄",burrito:"🌯",bus:"🚌",business_suit_levitating:"🕴",busstop:"🚏",bust_in_silhouette:"👤",busts_in_silhouette:"👥",butterfly:"🦋",cactus:"🌵",cake:"🍰",calendar:"📆",call_me_hand:"🤙",calling:"📲",camel:"🐫",camera:"📷",camera_flash:"📸",camping:"🏕",cancer:"♋️",candle:"🕯",candy:"🍬",canoe:"🛶",capital_abcd:"🔠",capricorn:"♑️",car:"🚗",card_file_box:"🗃",card_index:"📇",card_index_dividers:"🗂",carousel_horse:"🎠",carrot:"🥕",cat:"🐱",cat2:"🐈",cd:"💿",chains:"⛓",champagne:"🍾",chart:"💹",chart_with_downwards_trend:"📉",chart_with_upwards_trend:"📈",checkered_flag:"🏁",cheese:"🧀",cherries:"🍒",cherry_blossom:"🌸",chestnut:"🌰",chicken:"🐔",children_crossing:"🚸",chipmunk:"🐿",chocolate_bar:"🍫",christmas_tree:"🎄",church:"⛪️",cinema:"🎦",circus_tent:"🎪",city_sunrise:"🌇",city_sunset:"🌆",cityscape:"🏙",cl:"🆑",clamp:"🗜",clap:"👏",clapper:"🎬",classical_building:"🏛",clinking_glasses:"🥂",clipboard:"📋",clock1:"🕐",clock10:"🕙",clock1030:"🕥",clock11:"🕚",clock1130:"🕦",clock12:"🕛",clock1230:"🕧",clock130:"🕜",clock2:"🕑",clock230:"🕝",clock3:"🕒",clock330:"🕞",clock4:"🕓",clock430:"🕟",clock5:"🕔",clock530:"🕠",clock6:"🕕",clock630:"🕡",clock7:"🕖",clock730:"🕢",clock8:"🕗",clock830:"🕣",clock9:"🕘",clock930:"🕤",closed_book:"📕",closed_lock_with_key:"🔐",closed_umbrella:"🌂",cloud:"☁️",cloud_with_lightning:"🌩",cloud_with_lightning_and_rain:"⛈",cloud_with_rain:"🌧",cloud_with_snow:"🌨",clown_face:"🤡",clubs:"♣️",cocktail:"🍸",coffee:"☕️",coffin:"⚰️",cold_sweat:"😰",comet:"☄️",computer:"💻",computer_mouse:"🖱",confetti_ball:"🎊",confounded:"😖",confused:"😕",congratulations:"㊗️",construction:"🚧",construction_worker_man:"👷",construction_worker_woman:"👷‍♀️",control_knobs:"🎛",convenience_store:"🏪",cookie:"🍪",cool:"🆒",policeman:"👮",copyright:"©️",corn:"🌽",couch_and_lamp:"🛋",couple:"👫",couple_with_heart_woman_man:"💑",couple_with_heart_man_man:"👨‍❤️‍👨",couple_with_heart_woman_woman:"👩‍❤️‍👩",couplekiss_man_man:"👨‍❤️‍💋‍👨",couplekiss_man_woman:"💏",couplekiss_woman_woman:"👩‍❤️‍💋‍👩",cow:"🐮",cow2:"🐄",cowboy_hat_face:"🤠",crab:"🦀",crayon:"🖍",credit_card:"💳",crescent_moon:"🌙",cricket:"🏏",crocodile:"🐊",croissant:"🥐",crossed_fingers:"🤞",crossed_flags:"🎌",crossed_swords:"⚔️",crown:"👑",cry:"😢",crying_cat_face:"😿",crystal_ball:"🔮",cucumber:"🥒",cupid:"💘",curly_loop:"➰",currency_exchange:"💱",curry:"🍛",custard:"🍮",customs:"🛃",cyclone:"🌀",dagger:"🗡",dancer:"💃",dancing_women:"👯",dancing_men:"👯‍♂️",dango:"🍡",dark_sunglasses:"🕶",dart:"🎯",dash:"💨",date:"📅",deciduous_tree:"🌳",deer:"🦌",department_store:"🏬",derelict_house:"🏚",desert:"🏜",desert_island:"🏝",desktop_computer:"🖥",male_detective:"🕵️",diamond_shape_with_a_dot_inside:"💠",diamonds:"♦️",disappointed:"😞",disappointed_relieved:"😥",dizzy:"💫",dizzy_face:"😵",do_not_litter:"🚯",dog:"🐶",dog2:"🐕",dollar:"💵",dolls:"🎎",dolphin:"🐬",door:"🚪",doughnut:"🍩",dove:"🕊",dragon:"🐉",dragon_face:"🐲",dress:"👗",dromedary_camel:"🐪",drooling_face:"🤤",droplet:"💧",drum:"🥁",duck:"🦆",dvd:"📀","e-mail":"📧",eagle:"🦅",ear:"👂",ear_of_rice:"🌾",earth_africa:"🌍",earth_americas:"🌎",earth_asia:"🌏",egg:"🥚",eggplant:"🍆",eight_pointed_black_star:"✴️",eight_spoked_asterisk:"✳️",electric_plug:"🔌",elephant:"🐘",email:"✉️",end:"🔚",envelope_with_arrow:"📩",euro:"💶",european_castle:"🏰",european_post_office:"🏤",evergreen_tree:"🌲",exclamation:"❗️",expressionless:"😑",eye:"👁",eye_speech_bubble:"👁‍🗨",eyeglasses:"👓",eyes:"👀",face_with_head_bandage:"🤕",face_with_thermometer:"🤒",fist_oncoming:"👊",factory:"🏭",fallen_leaf:"🍂",family_man_woman_boy:"👪",family_man_boy:"👨‍👦",family_man_boy_boy:"👨‍👦‍👦",family_man_girl:"👨‍👧",family_man_girl_boy:"👨‍👧‍👦",family_man_girl_girl:"👨‍👧‍👧",family_man_man_boy:"👨‍👨‍👦",family_man_man_boy_boy:"👨‍👨‍👦‍👦",family_man_man_girl:"👨‍👨‍👧",family_man_man_girl_boy:"👨‍👨‍👧‍👦",family_man_man_girl_girl:"👨‍👨‍👧‍👧",family_man_woman_boy_boy:"👨‍👩‍👦‍👦",family_man_woman_girl:"👨‍👩‍👧",family_man_woman_girl_boy:"👨‍👩‍👧‍👦",family_man_woman_girl_girl:"👨‍👩‍👧‍👧",family_woman_boy:"👩‍👦",family_woman_boy_boy:"👩‍👦‍👦",family_woman_girl:"👩‍👧",family_woman_girl_boy:"👩‍👧‍👦",family_woman_girl_girl:"👩‍👧‍👧",family_woman_woman_boy:"👩‍👩‍👦",family_woman_woman_boy_boy:"👩‍👩‍👦‍👦",family_woman_woman_girl:"👩‍👩‍👧",family_woman_woman_girl_boy:"👩‍👩‍👧‍👦",family_woman_woman_girl_girl:"👩‍👩‍👧‍👧",fast_forward:"⏩",fax:"📠",fearful:"😨",feet:"🐾",female_detective:"🕵️‍♀️",ferris_wheel:"🎡",ferry:"⛴",field_hockey:"🏑",file_cabinet:"🗄",file_folder:"📁",film_projector:"📽",film_strip:"🎞",fire:"🔥",fire_engine:"🚒",fireworks:"🎆",first_quarter_moon:"🌓",first_quarter_moon_with_face:"🌛",fish:"🐟",fish_cake:"🍥",fishing_pole_and_fish:"🎣",fist_raised:"✊",fist_left:"🤛",fist_right:"🤜",flags:"🎏",flashlight:"🔦",fleur_de_lis:"⚜️",flight_arrival:"🛬",flight_departure:"🛫",floppy_disk:"💾",flower_playing_cards:"🎴",flushed:"😳",fog:"🌫",foggy:"🌁",football:"🏈",footprints:"👣",fork_and_knife:"🍴",fountain:"⛲️",fountain_pen:"🖋",four_leaf_clover:"🍀",fox_face:"🦊",framed_picture:"🖼",free:"🆓",fried_egg:"🍳",fried_shrimp:"🍤",fries:"🍟",frog:"🐸",frowning:"😦",frowning_face:"☹️",frowning_man:"🙍‍♂️",frowning_woman:"🙍",middle_finger:"🖕",fuelpump:"⛽️",full_moon:"🌕",full_moon_with_face:"🌝",funeral_urn:"⚱️",game_die:"🎲",gear:"⚙️",gem:"💎",gemini:"♊️",ghost:"👻",gift:"🎁",gift_heart:"💝",girl:"👧",globe_with_meridians:"🌐",goal_net:"🥅",goat:"🐐",golf:"⛳️",golfing_man:"🏌️",golfing_woman:"🏌️‍♀️",gorilla:"🦍",grapes:"🍇",green_apple:"🍏",green_book:"📗",green_heart:"💚",green_salad:"🥗",grey_exclamation:"❕",grey_question:"❔",grimacing:"😬",grin:"😁",grinning:"😀",guardsman:"💂",guardswoman:"💂‍♀️",guitar:"🎸",gun:"🔫",haircut_woman:"💇",haircut_man:"💇‍♂️",hamburger:"🍔",hammer:"🔨",hammer_and_pick:"⚒",hammer_and_wrench:"🛠",hamster:"🐹",hand:"✋",handbag:"👜",handshake:"🤝",hankey:"💩",hatched_chick:"🐥",hatching_chick:"🐣",headphones:"🎧",hear_no_evil:"🙉",heart:"❤️",heart_decoration:"💟",heart_eyes:"😍",heart_eyes_cat:"😻",heartbeat:"💓",heartpulse:"💗",hearts:"♥️",heavy_check_mark:"✔️",heavy_division_sign:"➗",heavy_dollar_sign:"💲",heavy_heart_exclamation:"❣️",heavy_minus_sign:"➖",heavy_multiplication_x:"✖️",heavy_plus_sign:"➕",helicopter:"🚁",herb:"🌿",hibiscus:"🌺",high_brightness:"🔆",high_heel:"👠",hocho:"🔪",hole:"🕳",honey_pot:"🍯",horse:"🐴",horse_racing:"🏇",hospital:"🏥",hot_pepper:"🌶",hotdog:"🌭",hotel:"🏨",hotsprings:"♨️",hourglass:"⌛️",hourglass_flowing_sand:"⏳",house:"🏠",house_with_garden:"🏡",houses:"🏘",hugs:"🤗",hushed:"😯",ice_cream:"🍨",ice_hockey:"🏒",ice_skate:"⛸",icecream:"🍦",id:"🆔",ideograph_advantage:"🉐",imp:"👿",inbox_tray:"📥",incoming_envelope:"📨",tipping_hand_woman:"💁",information_source:"ℹ️",innocent:"😇",interrobang:"⁉️",iphone:"📱",izakaya_lantern:"🏮",jack_o_lantern:"🎃",japan:"🗾",japanese_castle:"🏯",japanese_goblin:"👺",japanese_ogre:"👹",jeans:"👖",joy:"😂",joy_cat:"😹",joystick:"🕹",kaaba:"🕋",key:"🔑",keyboard:"⌨️",keycap_ten:"🔟",kick_scooter:"🛴",kimono:"👘",kiss:"💋",kissing:"😗",kissing_cat:"😽",kissing_closed_eyes:"😚",kissing_heart:"😘",kissing_smiling_eyes:"😙",kiwi_fruit:"🥝",koala:"🐨",koko:"🈁",label:"🏷",large_blue_circle:"🔵",large_blue_diamond:"🔷",large_orange_diamond:"🔶",last_quarter_moon:"🌗",last_quarter_moon_with_face:"🌜",latin_cross:"✝️",laughing:"😆",leaves:"🍃",ledger:"📒",left_luggage:"🛅",left_right_arrow:"↔️",leftwards_arrow_with_hook:"↩️",lemon:"🍋",leo:"♌️",leopard:"🐆",level_slider:"🎚",libra:"♎️",light_rail:"🚈",link:"🔗",lion:"🦁",lips:"👄",lipstick:"💄",lizard:"🦎",lock:"🔒",lock_with_ink_pen:"🔏",lollipop:"🍭",loop:"➿",loud_sound:"🔊",loudspeaker:"📢",love_hotel:"🏩",love_letter:"💌",low_brightness:"🔅",lying_face:"🤥",m:"Ⓜ️",mag:"🔍",mag_right:"🔎",mahjong:"🀄️",mailbox:"📫",mailbox_closed:"📪",mailbox_with_mail:"📬",mailbox_with_no_mail:"📭",man:"👨",man_artist:"👨‍🎨",man_astronaut:"👨‍🚀",man_cartwheeling:"🤸‍♂️",man_cook:"👨‍🍳",man_dancing:"🕺",man_facepalming:"🤦‍♂️",man_factory_worker:"👨‍🏭",man_farmer:"👨‍🌾",man_firefighter:"👨‍🚒",man_health_worker:"👨‍⚕️",man_in_tuxedo:"🤵",man_judge:"👨‍⚖️",man_juggling:"🤹‍♂️",man_mechanic:"👨‍🔧",man_office_worker:"👨‍💼",man_pilot:"👨‍✈️",man_playing_handball:"🤾‍♂️",man_playing_water_polo:"🤽‍♂️",man_scientist:"👨‍🔬",man_shrugging:"🤷‍♂️",man_singer:"👨‍🎤",man_student:"👨‍🎓",man_teacher:"👨‍🏫",man_technologist:"👨‍💻",man_with_gua_pi_mao:"👲",man_with_turban:"👳",tangerine:"🍊",mans_shoe:"👞",mantelpiece_clock:"🕰",maple_leaf:"🍁",martial_arts_uniform:"🥋",mask:"😷",massage_woman:"💆",massage_man:"💆‍♂️",meat_on_bone:"🍖",medal_military:"🎖",medal_sports:"🏅",mega:"📣",melon:"🍈",memo:"📝",men_wrestling:"🤼‍♂️",menorah:"🕎",mens:"🚹",metal:"🤘",metro:"🚇",microphone:"🎤",microscope:"🔬",milk_glass:"🥛",milky_way:"🌌",minibus:"🚐",minidisc:"💽",mobile_phone_off:"📴",money_mouth_face:"🤑",money_with_wings:"💸",moneybag:"💰",monkey:"🐒",monkey_face:"🐵",monorail:"🚝",moon:"🌔",mortar_board:"🎓",mosque:"🕌",motor_boat:"🛥",motor_scooter:"🛵",motorcycle:"🏍",motorway:"🛣",mount_fuji:"🗻",mountain:"⛰",mountain_biking_man:"🚵",mountain_biking_woman:"🚵‍♀️",mountain_cableway:"🚠",mountain_railway:"🚞",mountain_snow:"🏔",mouse:"🐭",mouse2:"🐁",movie_camera:"🎥",moyai:"🗿",mrs_claus:"🤶",muscle:"💪",mushroom:"🍄",musical_keyboard:"🎹",musical_note:"🎵",musical_score:"🎼",mute:"🔇",nail_care:"💅",name_badge:"📛",national_park:"🏞",nauseated_face:"🤢",necktie:"👔",negative_squared_cross_mark:"❎",nerd_face:"🤓",neutral_face:"😐",new:"🆕",new_moon:"🌑",new_moon_with_face:"🌚",newspaper:"📰",newspaper_roll:"🗞",next_track_button:"⏭",ng:"🆖",no_good_man:"🙅‍♂️",no_good_woman:"🙅",night_with_stars:"🌃",no_bell:"🔕",no_bicycles:"🚳",no_entry:"⛔️",no_entry_sign:"🚫",no_mobile_phones:"📵",no_mouth:"😶",no_pedestrians:"🚷",no_smoking:"🚭","non-potable_water":"🚱",nose:"👃",notebook:"📓",notebook_with_decorative_cover:"📔",notes:"🎶",nut_and_bolt:"🔩",o:"⭕️",o2:"🅾️",ocean:"🌊",octopus:"🐙",oden:"🍢",office:"🏢",oil_drum:"🛢",ok:"🆗",ok_hand:"👌",ok_man:"🙆‍♂️",ok_woman:"🙆",old_key:"🗝",older_man:"👴",older_woman:"👵",om:"🕉",on:"🔛",oncoming_automobile:"🚘",oncoming_bus:"🚍",oncoming_police_car:"🚔",oncoming_taxi:"🚖",open_file_folder:"📂",open_hands:"👐",open_mouth:"😮",open_umbrella:"☂️",ophiuchus:"⛎",orange_book:"📙",orthodox_cross:"☦️",outbox_tray:"📤",owl:"🦉",ox:"🐂",package:"📦",page_facing_up:"📄",page_with_curl:"📃",pager:"📟",paintbrush:"🖌",palm_tree:"🌴",pancakes:"🥞",panda_face:"🐼",paperclip:"📎",paperclips:"🖇",parasol_on_ground:"⛱",parking:"🅿️",part_alternation_mark:"〽️",partly_sunny:"⛅️",passenger_ship:"🛳",passport_control:"🛂",pause_button:"⏸",peace_symbol:"☮️",peach:"🍑",peanuts:"🥜",pear:"🍐",pen:"🖊",pencil2:"✏️",penguin:"🐧",pensive:"😔",performing_arts:"🎭",persevere:"😣",person_fencing:"🤺",pouting_woman:"🙎",phone:"☎️",pick:"⛏",pig:"🐷",pig2:"🐖",pig_nose:"🐽",pill:"💊",pineapple:"🍍",ping_pong:"🏓",pisces:"♓️",pizza:"🍕",place_of_worship:"🛐",plate_with_cutlery:"🍽",play_or_pause_button:"⏯",point_down:"👇",point_left:"👈",point_right:"👉",point_up:"☝️",point_up_2:"👆",police_car:"🚓",policewoman:"👮‍♀️",poodle:"🐩",popcorn:"🍿",post_office:"🏣",postal_horn:"📯",postbox:"📮",potable_water:"🚰",potato:"🥔",pouch:"👝",poultry_leg:"🍗",pound:"💷",rage:"😡",pouting_cat:"😾",pouting_man:"🙎‍♂️",pray:"🙏",prayer_beads:"📿",pregnant_woman:"🤰",previous_track_button:"⏮",prince:"🤴",princess:"👸",printer:"🖨",purple_heart:"💜",purse:"👛",pushpin:"📌",put_litter_in_its_place:"🚮",question:"❓",rabbit:"🐰",rabbit2:"🐇",racehorse:"🐎",racing_car:"🏎",radio:"📻",radio_button:"🔘",radioactive:"☢️",railway_car:"🚃",railway_track:"🛤",rainbow:"🌈",rainbow_flag:"🏳️‍🌈",raised_back_of_hand:"🤚",raised_hand_with_fingers_splayed:"🖐",raised_hands:"🙌",raising_hand_woman:"🙋",raising_hand_man:"🙋‍♂️",ram:"🐏",ramen:"🍜",rat:"🐀",record_button:"⏺",recycle:"♻️",red_circle:"🔴",registered:"®️",relaxed:"☺️",relieved:"😌",reminder_ribbon:"🎗",repeat:"🔁",repeat_one:"🔂",rescue_worker_helmet:"⛑",restroom:"🚻",revolving_hearts:"💞",rewind:"⏪",rhinoceros:"🦏",ribbon:"🎀",rice:"🍚",rice_ball:"🍙",rice_cracker:"🍘",rice_scene:"🎑",right_anger_bubble:"🗯",ring:"💍",robot:"🤖",rocket:"🚀",rofl:"🤣",roll_eyes:"🙄",roller_coaster:"🎢",rooster:"🐓",rose:"🌹",rosette:"🏵",rotating_light:"🚨",round_pushpin:"📍",rowing_man:"🚣",rowing_woman:"🚣‍♀️",rugby_football:"🏉",running_man:"🏃",running_shirt_with_sash:"🎽",running_woman:"🏃‍♀️",sa:"🈂️",sagittarius:"♐️",sake:"🍶",sandal:"👡",santa:"🎅",satellite:"📡",saxophone:"🎷",school:"🏫",school_satchel:"🎒",scissors:"✂️",scorpion:"🦂",scorpius:"♏️",scream:"😱",scream_cat:"🙀",scroll:"📜",seat:"💺",secret:"㊙️",see_no_evil:"🙈",seedling:"🌱",selfie:"🤳",shallow_pan_of_food:"🥘",shamrock:"☘️",shark:"🦈",shaved_ice:"🍧",sheep:"🐑",shell:"🐚",shield:"🛡",shinto_shrine:"⛩",ship:"🚢",shirt:"👕",shopping:"🛍",shopping_cart:"🛒",shower:"🚿",shrimp:"🦐",signal_strength:"📶",six_pointed_star:"🔯",ski:"🎿",skier:"⛷",skull:"💀",skull_and_crossbones:"☠️",sleeping:"😴",sleeping_bed:"🛌",sleepy:"😪",slightly_frowning_face:"🙁",slightly_smiling_face:"🙂",slot_machine:"🎰",small_airplane:"🛩",small_blue_diamond:"🔹",small_orange_diamond:"🔸",small_red_triangle:"🔺",small_red_triangle_down:"🔻",smile:"😄",smile_cat:"😸",smiley:"😃",smiley_cat:"😺",smiling_imp:"😈",smirk:"😏",smirk_cat:"😼",smoking:"🚬",snail:"🐌",snake:"🐍",sneezing_face:"🤧",snowboarder:"🏂",snowflake:"❄️",snowman:"⛄️",snowman_with_snow:"☃️",sob:"😭",soccer:"⚽️",soon:"🔜",sos:"🆘",sound:"🔉",space_invader:"👾",spades:"♠️",spaghetti:"🍝",sparkle:"❇️",sparkler:"🎇",sparkles:"✨",sparkling_heart:"💖",speak_no_evil:"🙊",speaker:"🔈",speaking_head:"🗣",speech_balloon:"💬",speedboat:"🚤",spider:"🕷",spider_web:"🕸",spiral_calendar:"🗓",spiral_notepad:"🗒",spoon:"🥄",squid:"🦑",stadium:"🏟",star:"⭐️",star2:"🌟",star_and_crescent:"☪️",star_of_david:"✡️",stars:"🌠",station:"🚉",statue_of_liberty:"🗽",steam_locomotive:"🚂",stew:"🍲",stop_button:"⏹",stop_sign:"🛑",stopwatch:"⏱",straight_ruler:"📏",strawberry:"🍓",stuck_out_tongue:"😛",stuck_out_tongue_closed_eyes:"😝",stuck_out_tongue_winking_eye:"😜",studio_microphone:"🎙",stuffed_flatbread:"🥙",sun_behind_large_cloud:"🌥",sun_behind_rain_cloud:"🌦",sun_behind_small_cloud:"🌤",sun_with_face:"🌞",sunflower:"🌻",sunglasses:"😎",sunny:"☀️",sunrise:"🌅",sunrise_over_mountains:"🌄",surfing_man:"🏄",surfing_woman:"🏄‍♀️",sushi:"🍣",suspension_railway:"🚟",sweat:"😓",sweat_drops:"💦",sweat_smile:"😅",sweet_potato:"🍠",swimming_man:"🏊",swimming_woman:"🏊‍♀️",symbols:"🔣",synagogue:"🕍",syringe:"💉",taco:"🌮",tada:"🎉",tanabata_tree:"🎋",taurus:"♉️",taxi:"🚕",tea:"🍵",telephone_receiver:"📞",telescope:"🔭",tennis:"🎾",tent:"⛺️",thermometer:"🌡",thinking:"🤔",thought_balloon:"💭",ticket:"🎫",tickets:"🎟",tiger:"🐯",tiger2:"🐅",timer_clock:"⏲",tipping_hand_man:"💁‍♂️",tired_face:"😫",tm:"™️",toilet:"🚽",tokyo_tower:"🗼",tomato:"🍅",tongue:"👅",top:"🔝",tophat:"🎩",tornado:"🌪",trackball:"🖲",tractor:"🚜",traffic_light:"🚥",train:"🚋",train2:"🚆",tram:"🚊",triangular_flag_on_post:"🚩",triangular_ruler:"📐",trident:"🔱",triumph:"😤",trolleybus:"🚎",trophy:"🏆",tropical_drink:"🍹",tropical_fish:"🐠",truck:"🚚",trumpet:"🎺",tulip:"🌷",tumbler_glass:"🥃",turkey:"🦃",turtle:"🐢",tv:"📺",twisted_rightwards_arrows:"🔀",two_hearts:"💕",two_men_holding_hands:"👬",two_women_holding_hands:"👭",u5272:"🈹",u5408:"🈴",u55b6:"🈺",u6307:"🈯️",u6708:"🈷️",u6709:"🈶",u6e80:"🈵",u7121:"🈚️",u7533:"🈸",u7981:"🈲",u7a7a:"🈳",umbrella:"☔️",unamused:"😒",underage:"🔞",unicorn:"🦄",unlock:"🔓",up:"🆙",upside_down_face:"🙃",v:"✌️",vertical_traffic_light:"🚦",vhs:"📼",vibration_mode:"📳",video_camera:"📹",video_game:"🎮",violin:"🎻",virgo:"♍️",volcano:"🌋",volleyball:"🏐",vs:"🆚",vulcan_salute:"🖖",walking_man:"🚶",walking_woman:"🚶‍♀️",waning_crescent_moon:"🌘",waning_gibbous_moon:"🌖",warning:"⚠️",wastebasket:"🗑",watch:"⌚️",water_buffalo:"🐃",watermelon:"🍉",wave:"👋",wavy_dash:"〰️",waxing_crescent_moon:"🌒",wc:"🚾",weary:"😩",wedding:"💒",weight_lifting_man:"🏋️",weight_lifting_woman:"🏋️‍♀️",whale:"🐳",whale2:"🐋",wheel_of_dharma:"☸️",wheelchair:"♿️",white_check_mark:"✅",white_circle:"⚪️",white_flag:"🏳️",white_flower:"💮",white_large_square:"⬜️",white_medium_small_square:"◽️",white_medium_square:"◻️",white_small_square:"▫️",white_square_button:"🔳",wilted_flower:"🥀",wind_chime:"🎐",wind_face:"🌬",wine_glass:"🍷",wink:"😉",wolf:"🐺",woman:"👩",woman_artist:"👩‍🎨",woman_astronaut:"👩‍🚀",woman_cartwheeling:"🤸‍♀️",woman_cook:"👩‍🍳",woman_facepalming:"🤦‍♀️",woman_factory_worker:"👩‍🏭",woman_farmer:"👩‍🌾",woman_firefighter:"👩‍🚒",woman_health_worker:"👩‍⚕️",woman_judge:"👩‍⚖️",woman_juggling:"🤹‍♀️",woman_mechanic:"👩‍🔧",woman_office_worker:"👩‍💼",woman_pilot:"👩‍✈️",woman_playing_handball:"🤾‍♀️",woman_playing_water_polo:"🤽‍♀️",woman_scientist:"👩‍🔬",woman_shrugging:"🤷‍♀️",woman_singer:"👩‍🎤",woman_student:"👩‍🎓",woman_teacher:"👩‍🏫",woman_technologist:"👩‍💻",woman_with_turban:"👳‍♀️",womans_clothes:"👚",womans_hat:"👒",women_wrestling:"🤼‍♀️",womens:"🚺",world_map:"🗺",worried:"😟",wrench:"🔧",writing_hand:"✍️",x:"❌",yellow_heart:"💛",yen:"💴",yin_yang:"☯️",yum:"😋",zap:"⚡️",zipper_mouth_face:"🤐",zzz:"💤",octocat:'<img alt=":octocat:" height="20" width="20" align="absmiddle" src="https://assets-cdn.github.com/images/icons/emoji/octocat.png">',showdown:"<span style=\"font-family: 'Anonymous Pro', monospace; text-decoration: underline; text-decoration-style: dashed; text-decoration-color: #3e8b8a;text-underline-position: under;\">S</span>"},a.Converter=function(e){"use strict";var t={},r=[],n=[],o={},i=c,p={parsed:{},raw:"",format:""};function f(e,t){if(t=t||null,a.helper.isString(e)){if(t=e=a.helper.stdExtName(e),a.extensions[e])return console.warn("DEPRECATION WARNING: "+e+" is an old extension that uses a deprecated loading method.Please inform the developer that the extension should be updated!"),void function(e,t){"function"==typeof e&&(e=e(new a.Converter));a.helper.isArray(e)||(e=[e]);var o=d(e,t);if(!o.valid)throw Error(o.error);for(var i=0;i<e.length;++i)switch(e[i].type){case"lang":r.push(e[i]);break;case"output":n.push(e[i]);break;default:throw Error("Extension loader error: Type unrecognized!!!")}}(a.extensions[e],e);if(a.helper.isUndefined(s[e]))throw Error('Extension "'+e+'" could not be loaded. It was either not found or is not a valid extension.');e=s[e]}"function"==typeof e&&(e=e()),a.helper.isArray(e)||(e=[e]);var o=d(e,t);if(!o.valid)throw Error(o.error);for(var i=0;i<e.length;++i){switch(e[i].type){case"lang":r.push(e[i]);break;case"output":n.push(e[i])}if(e[i].hasOwnProperty("listeners"))for(var l in e[i].listeners)e[i].listeners.hasOwnProperty(l)&&h(l,e[i].listeners[l])}}function h(e,t){if(!a.helper.isString(e))throw Error("Invalid argument in converter.listen() method: name must be a string, but "+typeof e+" given");if("function"!=typeof t)throw Error("Invalid argument in converter.listen() method: callback must be a function, but "+typeof t+" given");o.hasOwnProperty(e)||(o[e]=[]),o[e].push(t)}!function(){for(var r in e=e||{},l)l.hasOwnProperty(r)&&(t[r]=l[r]);if("object"!=typeof e)throw Error("Converter expects the passed parameter to be an object, but "+typeof e+" was passed instead.");for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);t.extensions&&a.helper.forEach(t.extensions,f)}(),this._dispatch=function(e,t,r,n){if(o.hasOwnProperty(e))for(var a=0;a<o[e].length;++a){var i=o[e][a](e,t,this,r,n);i&&void 0!==i&&(t=i)}return t},this.listen=function(e,t){return h(e,t),this},this.makeHtml=function(e){if(!e)return e;var o={gHtmlBlocks:[],gHtmlMdBlocks:[],gHtmlSpans:[],gUrls:{},gTitles:{},gDimensions:{},gListLevel:0,hashLinkCounts:{},langExtensions:r,outputModifiers:n,converter:this,ghCodeBlocks:[],metadata:{parsed:{},raw:"",format:""}};return e=(e=(e=(e=(e=e.replace(/¨/g,"¨T")).replace(/\$/g,"¨D")).replace(/\r\n/g,"\n")).replace(/\r/g,"\n")).replace(/\u00A0/g," "),t.smartIndentationFix&&(e=function(e){var t=e.match(/^\s*/)[0].length,r=new RegExp("^\\s{0,"+t+"}","gm");return e.replace(r,"")}(e)),e="\n\n"+e+"\n\n",e=(e=a.subParser("detab")(e,t,o)).replace(/^[ \t]+$/gm,""),a.helper.forEach(r,(function(r){e=a.subParser("runExtension")(r,e,t,o)})),e=a.subParser("metadata")(e,t,o),e=a.subParser("hashPreCodeTags")(e,t,o),e=a.subParser("githubCodeBlocks")(e,t,o),e=a.subParser("hashHTMLBlocks")(e,t,o),e=a.subParser("hashCodeTags")(e,t,o),e=a.subParser("stripLinkDefinitions")(e,t,o),e=a.subParser("blockGamut")(e,t,o),e=a.subParser("unhashHTMLSpans")(e,t,o),e=(e=(e=a.subParser("unescapeSpecialChars")(e,t,o)).replace(/¨D/g,"$$")).replace(/¨T/g,"¨"),e=a.subParser("completeHTMLDocument")(e,t,o),a.helper.forEach(n,(function(r){e=a.subParser("runExtension")(r,e,t,o)})),p=o.metadata,e},this.makeMarkdown=this.makeMd=function(e,t){if(e=(e=(e=e.replace(/\r\n/g,"\n")).replace(/\r/g,"\n")).replace(/>[ \t]+</,">¨NBSP;<"),!t){if(!window||!window.document)throw new Error("HTMLParser is undefined. If in a webworker or nodejs environment, you need to provide a WHATWG DOM and HTML such as JSDOM");t=window.document}var r=t.createElement("div");r.innerHTML=e;var n={preList:function(e){for(var t=e.querySelectorAll("pre"),r=[],n=0;n<t.length;++n)if(1===t[n].childElementCount&&"code"===t[n].firstChild.tagName.toLowerCase()){var o=t[n].firstChild.innerHTML.trim(),i=t[n].firstChild.getAttribute("data-language")||"";if(""===i)for(var s=t[n].firstChild.className.split(" "),l=0;l<s.length;++l){var c=s[l].match(/^language-(.+)$/);if(null!==c){i=c[1];break}}o=a.helper.unescapeHTMLEntities(o),r.push(o),t[n].outerHTML='<precode language="'+i+'" precodenum="'+n.toString()+'"></precode>'}else r.push(t[n].innerHTML),t[n].innerHTML="",t[n].setAttribute("prenum",n.toString());return r}(r)};!function e(t){for(var r=0;r<t.childNodes.length;++r){var n=t.childNodes[r];3===n.nodeType?/\S/.test(n.nodeValue)?(n.nodeValue=n.nodeValue.split("\n").join(" "),n.nodeValue=n.nodeValue.replace(/(\s)+/g,"$1")):(t.removeChild(n),--r):1===n.nodeType&&e(n)}}(r);for(var o=r.childNodes,i="",s=0;s<o.length;s++)i+=a.subParser("makeMarkdown.node")(o[s],n);return i},this.setOption=function(e,r){t[e]=r},this.getOption=function(e){return t[e]},this.getOptions=function(){return t},this.addExtension=function(e,t){f(e,t=t||null)},this.useExtension=function(e){f(e)},this.setFlavor=function(e){if(!u.hasOwnProperty(e))throw Error(e+" flavor was not found");var r=u[e];for(var n in i=e,r)r.hasOwnProperty(n)&&(t[n]=r[n])},this.getFlavor=function(){return i},this.removeExtension=function(e){a.helper.isArray(e)||(e=[e]);for(var t=0;t<e.length;++t){for(var o=e[t],i=0;i<r.length;++i)r[i]===o&&r[i].splice(i,1);for(;0<n.length;++i)n[0]===o&&n[0].splice(i,1)}},this.getAllExtensions=function(){return{language:r,output:n}},this.getMetadata=function(e){return e?p.raw:p.parsed},this.getMetadataFormat=function(){return p.format},this._setMetadataPair=function(e,t){p.parsed[e]=t},this._setMetadataFormat=function(e){p.format=e},this._setMetadataRaw=function(e){p.raw=e}},a.subParser("anchors",(function(e,t,r){"use strict";var n=function(e,n,o,i,s,l,c){if(a.helper.isUndefined(c)&&(c=""),o=o.toLowerCase(),e.search(/\(<?\s*>? ?(['"].*['"])?\)$/m)>-1)i="";else if(!i){if(o||(o=n.toLowerCase().replace(/ ?\n/g," ")),i="#"+o,a.helper.isUndefined(r.gUrls[o]))return e;i=r.gUrls[o],a.helper.isUndefined(r.gTitles[o])||(c=r.gTitles[o])}var u='<a href="'+(i=i.replace(a.helper.regexes.asteriskDashAndColon,a.helper.escapeCharactersCallback))+'"';return""!==c&&null!==c&&(u+=' title="'+(c=(c=c.replace(/"/g,""")).replace(a.helper.regexes.asteriskDashAndColon,a.helper.escapeCharactersCallback))+'"'),t.openLinksInNewWindow&&!/^#/.test(i)&&(u+=' rel="noopener noreferrer" target="¨E95Eblank"'),u+=">"+n+"</a>"};return e=(e=(e=(e=(e=r.converter._dispatch("anchors.before",e,t,r)).replace(/\[((?:\[[^\]]*]|[^\[\]])*)] ?(?:\n *)?\[(.*?)]()()()()/g,n)).replace(/\[((?:\[[^\]]*]|[^\[\]])*)]()[ \t]*\([ \t]?<([^>]*)>(?:[ \t]*((["'])([^"]*?)\5))?[ \t]?\)/g,n)).replace(/\[((?:\[[^\]]*]|[^\[\]])*)]()[ \t]*\([ \t]?<?([\S]+?(?:\([\S]*?\)[\S]*?)?)>?(?:[ \t]*((["'])([^"]*?)\5))?[ \t]?\)/g,n)).replace(/\[([^\[\]]+)]()()()()()/g,n),t.ghMentions&&(e=e.replace(/(^|\s)(\\)?(@([a-z\d]+(?:[a-z\d.-]+?[a-z\d]+)*))/gim,(function(e,r,n,o,i){if("\\"===n)return r+o;if(!a.helper.isString(t.ghMentionsLink))throw new Error("ghMentionsLink option must be a string");var s=t.ghMentionsLink.replace(/\{u}/g,i),l="";return t.openLinksInNewWindow&&(l=' rel="noopener noreferrer" target="¨E95Eblank"'),r+'<a href="'+s+'"'+l+">"+o+"</a>"}))),e=r.converter._dispatch("anchors.after",e,t,r)}));var h=/([*~_]+|\b)(((https?|ftp|dict):\/\/|www\.)[^'">\s]+?\.[^'">\s]+?)()(\1)?(?=\s|$)(?!["<>])/gi,g=/([*~_]+|\b)(((https?|ftp|dict):\/\/|www\.)[^'">\s]+\.[^'">\s]+?)([.!?,()\[\]])?(\1)?(?=\s|$)(?!["<>])/gi,m=/()<(((https?|ftp|dict):\/\/|www\.)[^'">\s]+)()>()/gi,b=/(^|\s)(?:mailto:)?([A-Za-z0-9!#$%&'*+-/=?^_`{|}~.]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)(?=$|\s)/gim,_=/<()(?:mailto:)?([-.\w]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,k=function(e){"use strict";return function(t,r,n,o,i,s,l){var c=n=n.replace(a.helper.regexes.asteriskDashAndColon,a.helper.escapeCharactersCallback),u="",d="",p=r||"",f=l||"";return/^www\./i.test(n)&&(n=n.replace(/^www\./i,"http://www.")),e.excludeTrailingPunctuationFromURLs&&s&&(u=s),e.openLinksInNewWindow&&(d=' rel="noopener noreferrer" target="¨E95Eblank"'),p+'<a href="'+n+'"'+d+">"+c+"</a>"+u+f}},y=function(e,t){"use strict";return function(r,n,o){var i="mailto:";return n=n||"",o=a.subParser("unescapeSpecialChars")(o,e,t),e.encodeEmails?(i=a.helper.encodeEmailAddress(i+o),o=a.helper.encodeEmailAddress(o)):i+=o,n+'<a href="'+i+'">'+o+"</a>"}};a.subParser("autoLinks",(function(e,t,r){"use strict";return e=(e=(e=r.converter._dispatch("autoLinks.before",e,t,r)).replace(m,k(t))).replace(_,y(t,r)),e=r.converter._dispatch("autoLinks.after",e,t,r)})),a.subParser("simplifiedAutoLinks",(function(e,t,r){"use strict";return t.simplifiedAutoLink?(e=r.converter._dispatch("simplifiedAutoLinks.before",e,t,r),e=(e=t.excludeTrailingPunctuationFromURLs?e.replace(g,k(t)):e.replace(h,k(t))).replace(b,y(t,r)),e=r.converter._dispatch("simplifiedAutoLinks.after",e,t,r)):e})),a.subParser("blockGamut",(function(e,t,r){"use strict";return e=r.converter._dispatch("blockGamut.before",e,t,r),e=a.subParser("blockQuotes")(e,t,r),e=a.subParser("headers")(e,t,r),e=a.subParser("horizontalRule")(e,t,r),e=a.subParser("lists")(e,t,r),e=a.subParser("codeBlocks")(e,t,r),e=a.subParser("tables")(e,t,r),e=a.subParser("hashHTMLBlocks")(e,t,r),e=a.subParser("paragraphs")(e,t,r),e=r.converter._dispatch("blockGamut.after",e,t,r)})),a.subParser("blockQuotes",(function(e,t,r){"use strict";e=r.converter._dispatch("blockQuotes.before",e,t,r),e+="\n\n";var n=/(^ {0,3}>[ \t]?.+\n(.+\n)*\n*)+/gm;return t.splitAdjacentBlockquotes&&(n=/^ {0,3}>[\s\S]*?(?:\n\n)/gm),e=e.replace(n,(function(e){return e=(e=(e=e.replace(/^[ \t]*>[ \t]?/gm,"")).replace(/¨0/g,"")).replace(/^[ \t]+$/gm,""),e=a.subParser("githubCodeBlocks")(e,t,r),e=(e=(e=a.subParser("blockGamut")(e,t,r)).replace(/(^|\n)/g,"$1 ")).replace(/(\s*<pre>[^\r]+?<\/pre>)/gm,(function(e,t){var r=t;return r=(r=r.replace(/^ /gm,"¨0")).replace(/¨0/g,"")})),a.subParser("hashBlock")("<blockquote>\n"+e+"\n</blockquote>",t,r)})),e=r.converter._dispatch("blockQuotes.after",e,t,r)})),a.subParser("codeBlocks",(function(e,t,r){"use strict";e=r.converter._dispatch("codeBlocks.before",e,t,r);return e=(e=(e+="¨0").replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=¨0))/g,(function(e,n,o){var i=n,s=o,l="\n";return i=a.subParser("outdent")(i,t,r),i=a.subParser("encodeCode")(i,t,r),i=(i=(i=a.subParser("detab")(i,t,r)).replace(/^\n+/g,"")).replace(/\n+$/g,""),t.omitExtraWLInCodeBlocks&&(l=""),i="<pre><code>"+i+l+"</code></pre>",a.subParser("hashBlock")(i,t,r)+s}))).replace(/¨0/,""),e=r.converter._dispatch("codeBlocks.after",e,t,r)})),a.subParser("codeSpans",(function(e,t,r){"use strict";return void 0===(e=r.converter._dispatch("codeSpans.before",e,t,r))&&(e=""),e=e.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,(function(e,n,o,i){var s=i;return s=(s=s.replace(/^([ \t]*)/g,"")).replace(/[ \t]*$/g,""),s=n+"<code>"+(s=a.subParser("encodeCode")(s,t,r))+"</code>",s=a.subParser("hashHTMLSpans")(s,t,r)})),e=r.converter._dispatch("codeSpans.after",e,t,r)})),a.subParser("completeHTMLDocument",(function(e,t,r){"use strict";if(!t.completeHTMLDocument)return e;e=r.converter._dispatch("completeHTMLDocument.before",e,t,r);var n="html",o="<!DOCTYPE HTML>\n",a="",i='<meta charset="utf-8">\n',s="",l="";for(var c in void 0!==r.metadata.parsed.doctype&&(o="<!DOCTYPE "+r.metadata.parsed.doctype+">\n","html"!==(n=r.metadata.parsed.doctype.toString().toLowerCase())&&"html5"!==n||(i='<meta charset="utf-8">')),r.metadata.parsed)if(r.metadata.parsed.hasOwnProperty(c))switch(c.toLowerCase()){case"doctype":break;case"title":a="<title>"+r.metadata.parsed.title+"</title>\n";break;case"charset":i="html"===n||"html5"===n?'<meta charset="'+r.metadata.parsed.charset+'">\n':'<meta name="charset" content="'+r.metadata.parsed.charset+'">\n';break;case"language":case"lang":s=' lang="'+r.metadata.parsed[c]+'"',l+='<meta name="'+c+'" content="'+r.metadata.parsed[c]+'">\n';break;default:l+='<meta name="'+c+'" content="'+r.metadata.parsed[c]+'">\n'}return e=o+"<html"+s+">\n<head>\n"+a+i+l+"</head>\n<body>\n"+e.trim()+"\n</body>\n</html>",e=r.converter._dispatch("completeHTMLDocument.after",e,t,r)})),a.subParser("detab",(function(e,t,r){"use strict";return e=(e=(e=(e=(e=(e=r.converter._dispatch("detab.before",e,t,r)).replace(/\t(?=\t)/g," ")).replace(/\t/g,"¨A¨B")).replace(/¨B(.+?)¨A/g,(function(e,t){for(var r=t,n=4-r.length%4,o=0;o<n;o++)r+=" ";return r}))).replace(/¨A/g," ")).replace(/¨B/g,""),e=r.converter._dispatch("detab.after",e,t,r)})),a.subParser("ellipsis",(function(e,t,r){"use strict";return e=(e=r.converter._dispatch("ellipsis.before",e,t,r)).replace(/\.\.\./g,"…"),e=r.converter._dispatch("ellipsis.after",e,t,r)})),a.subParser("emoji",(function(e,t,r){"use strict";if(!t.emoji)return e;return e=(e=r.converter._dispatch("emoji.before",e,t,r)).replace(/:([\S]+?):/g,(function(e,t){return a.helper.emojis.hasOwnProperty(t)?a.helper.emojis[t]:e})),e=r.converter._dispatch("emoji.after",e,t,r)})),a.subParser("encodeAmpsAndAngles",(function(e,t,r){"use strict";return e=(e=(e=(e=(e=r.converter._dispatch("encodeAmpsAndAngles.before",e,t,r)).replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g,"&")).replace(/<(?![a-z\/?$!])/gi,"<")).replace(/</g,"<")).replace(/>/g,">"),e=r.converter._dispatch("encodeAmpsAndAngles.after",e,t,r)})),a.subParser("encodeBackslashEscapes",(function(e,t,r){"use strict";return e=(e=(e=r.converter._dispatch("encodeBackslashEscapes.before",e,t,r)).replace(/\\(\\)/g,a.helper.escapeCharactersCallback)).replace(/\\([`*_{}\[\]()>#+.!~=|-])/g,a.helper.escapeCharactersCallback),e=r.converter._dispatch("encodeBackslashEscapes.after",e,t,r)})),a.subParser("encodeCode",(function(e,t,r){"use strict";return e=(e=r.converter._dispatch("encodeCode.before",e,t,r)).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/([*_{}\[\]\\=~-])/g,a.helper.escapeCharactersCallback),e=r.converter._dispatch("encodeCode.after",e,t,r)})),a.subParser("escapeSpecialCharsWithinTagAttributes",(function(e,t,r){"use strict";return e=(e=(e=r.converter._dispatch("escapeSpecialCharsWithinTagAttributes.before",e,t,r)).replace(/<\/?[a-z\d_:-]+(?:[\s]+[\s\S]+?)?>/gi,(function(e){return e.replace(/(.)<\/?code>(?=.)/g,"$1`").replace(/([\\`*_~=|])/g,a.helper.escapeCharactersCallback)}))).replace(/<!(--(?:(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--)>/gi,(function(e){return e.replace(/([\\`*_~=|])/g,a.helper.escapeCharactersCallback)})),e=r.converter._dispatch("escapeSpecialCharsWithinTagAttributes.after",e,t,r)})),a.subParser("githubCodeBlocks",(function(e,t,r){"use strict";return t.ghCodeBlocks?(e=r.converter._dispatch("githubCodeBlocks.before",e,t,r),e=(e=(e+="¨0").replace(/(?:^|\n)(?: {0,3})(```+|~~~+)(?: *)([^\s`~]*)\n([\s\S]*?)\n(?: {0,3})\1/g,(function(e,n,o,i){var s=t.omitExtraWLInCodeBlocks?"":"\n";return i=a.subParser("encodeCode")(i,t,r),i="<pre><code"+(o?' class="'+o+" language-"+o+'"':"")+">"+(i=(i=(i=a.subParser("detab")(i,t,r)).replace(/^\n+/g,"")).replace(/\n+$/g,""))+s+"</code></pre>",i=a.subParser("hashBlock")(i,t,r),"\n\n¨G"+(r.ghCodeBlocks.push({text:e,codeblock:i})-1)+"G\n\n"}))).replace(/¨0/,""),r.converter._dispatch("githubCodeBlocks.after",e,t,r)):e})),a.subParser("hashBlock",(function(e,t,r){"use strict";return e=(e=r.converter._dispatch("hashBlock.before",e,t,r)).replace(/(^\n+|\n+$)/g,""),e="\n\n¨K"+(r.gHtmlBlocks.push(e)-1)+"K\n\n",e=r.converter._dispatch("hashBlock.after",e,t,r)})),a.subParser("hashCodeTags",(function(e,t,r){"use strict";e=r.converter._dispatch("hashCodeTags.before",e,t,r);return e=a.helper.replaceRecursiveRegExp(e,(function(e,n,o,i){var s=o+a.subParser("encodeCode")(n,t,r)+i;return"¨C"+(r.gHtmlSpans.push(s)-1)+"C"}),"<code\\b[^>]*>","</code>","gim"),e=r.converter._dispatch("hashCodeTags.after",e,t,r)})),a.subParser("hashElement",(function(e,t,r){"use strict";return function(e,t){var n=t;return n=(n=(n=n.replace(/\n\n/g,"\n")).replace(/^\n/,"")).replace(/\n+$/g,""),n="\n\n¨K"+(r.gHtmlBlocks.push(n)-1)+"K\n\n"}})),a.subParser("hashHTMLBlocks",(function(e,t,r){"use strict";e=r.converter._dispatch("hashHTMLBlocks.before",e,t,r);var n=["pre","div","h1","h2","h3","h4","h5","h6","blockquote","table","dl","ol","ul","script","noscript","form","fieldset","iframe","math","style","section","header","footer","nav","article","aside","address","audio","canvas","figure","hgroup","output","video","p"],o=function(e,t,n,o){var a=e;return-1!==n.search(/\bmarkdown\b/)&&(a=n+r.converter.makeHtml(t)+o),"\n\n¨K"+(r.gHtmlBlocks.push(a)-1)+"K\n\n"};t.backslashEscapesHTMLTags&&(e=e.replace(/\\<(\/?[^>]+?)>/g,(function(e,t){return"<"+t+">"})));for(var i=0;i<n.length;++i)for(var s,l=new RegExp("^ {0,3}(<"+n[i]+"\\b[^>]*>)","im"),c="<"+n[i]+"\\b[^>]*>",u="</"+n[i]+">";-1!==(s=a.helper.regexIndexOf(e,l));){var d=a.helper.splitAtIndex(e,s),p=a.helper.replaceRecursiveRegExp(d[1],o,c,u,"im");if(p===d[1])break;e=d[0].concat(p)}return e=e.replace(/(\n {0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,a.subParser("hashElement")(e,t,r)),e=(e=a.helper.replaceRecursiveRegExp(e,(function(e){return"\n\n¨K"+(r.gHtmlBlocks.push(e)-1)+"K\n\n"}),"^ {0,3}\x3c!--","--\x3e","gm")).replace(/(?:\n\n)( {0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,a.subParser("hashElement")(e,t,r)),e=r.converter._dispatch("hashHTMLBlocks.after",e,t,r)})),a.subParser("hashHTMLSpans",(function(e,t,r){"use strict";function n(e){return"¨C"+(r.gHtmlSpans.push(e)-1)+"C"}return e=(e=(e=(e=(e=r.converter._dispatch("hashHTMLSpans.before",e,t,r)).replace(/<[^>]+?\/>/gi,(function(e){return n(e)}))).replace(/<([^>]+?)>[\s\S]*?<\/\1>/g,(function(e){return n(e)}))).replace(/<([^>]+?)\s[^>]+?>[\s\S]*?<\/\1>/g,(function(e){return n(e)}))).replace(/<[^>]+?>/gi,(function(e){return n(e)})),e=r.converter._dispatch("hashHTMLSpans.after",e,t,r)})),a.subParser("unhashHTMLSpans",(function(e,t,r){"use strict";e=r.converter._dispatch("unhashHTMLSpans.before",e,t,r);for(var n=0;n<r.gHtmlSpans.length;++n){for(var o=r.gHtmlSpans[n],a=0;/¨C(\d+)C/.test(o);){var i=RegExp.$1;if(o=o.replace("¨C"+i+"C",r.gHtmlSpans[i]),10===a){console.error("maximum nesting of 10 spans reached!!!");break}++a}e=e.replace("¨C"+n+"C",o)}return e=r.converter._dispatch("unhashHTMLSpans.after",e,t,r)})),a.subParser("hashPreCodeTags",(function(e,t,r){"use strict";e=r.converter._dispatch("hashPreCodeTags.before",e,t,r);return e=a.helper.replaceRecursiveRegExp(e,(function(e,n,o,i){var s=o+a.subParser("encodeCode")(n,t,r)+i;return"\n\n¨G"+(r.ghCodeBlocks.push({text:e,codeblock:s})-1)+"G\n\n"}),"^ {0,3}<pre\\b[^>]*>\\s*<code\\b[^>]*>","^ {0,3}</code>\\s*</pre>","gim"),e=r.converter._dispatch("hashPreCodeTags.after",e,t,r)})),a.subParser("headers",(function(e,t,r){"use strict";e=r.converter._dispatch("headers.before",e,t,r);var n=isNaN(parseInt(t.headerLevelStart))?1:parseInt(t.headerLevelStart),o=t.smoothLivePreview?/^(.+)[ \t]*\n={2,}[ \t]*\n+/gm:/^(.+)[ \t]*\n=+[ \t]*\n+/gm,i=t.smoothLivePreview?/^(.+)[ \t]*\n-{2,}[ \t]*\n+/gm:/^(.+)[ \t]*\n-+[ \t]*\n+/gm;e=(e=e.replace(o,(function(e,o){var i=a.subParser("spanGamut")(o,t,r),s=t.noHeaderId?"":' id="'+l(o)+'"',c="<h"+n+s+">"+i+"</h"+n+">";return a.subParser("hashBlock")(c,t,r)}))).replace(i,(function(e,o){var i=a.subParser("spanGamut")(o,t,r),s=t.noHeaderId?"":' id="'+l(o)+'"',c=n+1,u="<h"+c+s+">"+i+"</h"+c+">";return a.subParser("hashBlock")(u,t,r)}));var s=t.requireSpaceBeforeHeadingText?/^(#{1,6})[ \t]+(.+?)[ \t]*#*\n+/gm:/^(#{1,6})[ \t]*(.+?)[ \t]*#*\n+/gm;function l(e){var n,o;if(t.customizedHeaderId){var i=e.match(/\{([^{]+?)}\s*$/);i&&i[1]&&(e=i[1])}return n=e,o=a.helper.isString(t.prefixHeaderId)?t.prefixHeaderId:!0===t.prefixHeaderId?"section-":"",t.rawPrefixHeaderId||(n=o+n),n=t.ghCompatibleHeaderId?n.replace(/ /g,"-").replace(/&/g,"").replace(/¨T/g,"").replace(/¨D/g,"").replace(/[&+$,\/:;=?@"#{}|^¨~\[\]`\\*)(%.!'<>]/g,"").toLowerCase():t.rawHeaderId?n.replace(/ /g,"-").replace(/&/g,"&").replace(/¨T/g,"¨").replace(/¨D/g,"$").replace(/["']/g,"-").toLowerCase():n.replace(/[^\w]/g,"").toLowerCase(),t.rawPrefixHeaderId&&(n=o+n),r.hashLinkCounts[n]?n=n+"-"+r.hashLinkCounts[n]++:r.hashLinkCounts[n]=1,n}return e=e.replace(s,(function(e,o,i){var s=i;t.customizedHeaderId&&(s=i.replace(/\s?\{([^{]+?)}\s*$/,""));var c=a.subParser("spanGamut")(s,t,r),u=t.noHeaderId?"":' id="'+l(i)+'"',d=n-1+o.length,p="<h"+d+u+">"+c+"</h"+d+">";return a.subParser("hashBlock")(p,t,r)})),e=r.converter._dispatch("headers.after",e,t,r)})),a.subParser("horizontalRule",(function(e,t,r){"use strict";e=r.converter._dispatch("horizontalRule.before",e,t,r);var n=a.subParser("hashBlock")("<hr />",t,r);return e=(e=(e=e.replace(/^ {0,2}( ?-){3,}[ \t]*$/gm,n)).replace(/^ {0,2}( ?\*){3,}[ \t]*$/gm,n)).replace(/^ {0,2}( ?_){3,}[ \t]*$/gm,n),e=r.converter._dispatch("horizontalRule.after",e,t,r)})),a.subParser("images",(function(e,t,r){"use strict";function n(e,t,n,o,i,s,l,c){var u=r.gUrls,d=r.gTitles,p=r.gDimensions;if(n=n.toLowerCase(),c||(c=""),e.search(/\(<?\s*>? ?(['"].*['"])?\)$/m)>-1)o="";else if(""===o||null===o){if(""!==n&&null!==n||(n=t.toLowerCase().replace(/ ?\n/g," ")),o="#"+n,a.helper.isUndefined(u[n]))return e;o=u[n],a.helper.isUndefined(d[n])||(c=d[n]),a.helper.isUndefined(p[n])||(i=p[n].width,s=p[n].height)}t=t.replace(/"/g,""").replace(a.helper.regexes.asteriskDashAndColon,a.helper.escapeCharactersCallback);var f='<img src="'+(o=o.replace(a.helper.regexes.asteriskDashAndColon,a.helper.escapeCharactersCallback))+'" alt="'+t+'"';return c&&a.helper.isString(c)&&(f+=' title="'+(c=c.replace(/"/g,""").replace(a.helper.regexes.asteriskDashAndColon,a.helper.escapeCharactersCallback))+'"'),i&&s&&(f+=' width="'+(i="*"===i?"auto":i)+'"',f+=' height="'+(s="*"===s?"auto":s)+'"'),f+=" />"}return e=(e=(e=(e=(e=(e=r.converter._dispatch("images.before",e,t,r)).replace(/!\[([^\]]*?)] ?(?:\n *)?\[([\s\S]*?)]()()()()()/g,n)).replace(/!\[([^\]]*?)][ \t]*()\([ \t]?<?(data:.+?\/.+?;base64,[A-Za-z0-9+/=\n]+?)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(["'])([^"]*?)\6)?[ \t]?\)/g,(function(e,t,r,o,a,i,s,l){return n(e,t,r,o=o.replace(/\s/g,""),a,i,s,l)}))).replace(/!\[([^\]]*?)][ \t]*()\([ \t]?<([^>]*)>(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(?:(["'])([^"]*?)\6))?[ \t]?\)/g,n)).replace(/!\[([^\]]*?)][ \t]*()\([ \t]?<?([\S]+?(?:\([\S]*?\)[\S]*?)?)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(["'])([^"]*?)\6)?[ \t]?\)/g,n)).replace(/!\[([^\[\]]+)]()()()()()/g,n),e=r.converter._dispatch("images.after",e,t,r)})),a.subParser("italicsAndBold",(function(e,t,r){"use strict";function n(e,t,r){return t+e+r}return e=r.converter._dispatch("italicsAndBold.before",e,t,r),e=t.literalMidWordUnderscores?(e=(e=e.replace(/\b___(\S[\s\S]*?)___\b/g,(function(e,t){return n(t,"<strong><em>","</em></strong>")}))).replace(/\b__(\S[\s\S]*?)__\b/g,(function(e,t){return n(t,"<strong>","</strong>")}))).replace(/\b_(\S[\s\S]*?)_\b/g,(function(e,t){return n(t,"<em>","</em>")})):(e=(e=e.replace(/___(\S[\s\S]*?)___/g,(function(e,t){return/\S$/.test(t)?n(t,"<strong><em>","</em></strong>"):e}))).replace(/__(\S[\s\S]*?)__/g,(function(e,t){return/\S$/.test(t)?n(t,"<strong>","</strong>"):e}))).replace(/_([^\s_][\s\S]*?)_/g,(function(e,t){return/\S$/.test(t)?n(t,"<em>","</em>"):e})),e=t.literalMidWordAsterisks?(e=(e=e.replace(/([^*]|^)\B\*\*\*(\S[\s\S]*?)\*\*\*\B(?!\*)/g,(function(e,t,r){return n(r,t+"<strong><em>","</em></strong>")}))).replace(/([^*]|^)\B\*\*(\S[\s\S]*?)\*\*\B(?!\*)/g,(function(e,t,r){return n(r,t+"<strong>","</strong>")}))).replace(/([^*]|^)\B\*(\S[\s\S]*?)\*\B(?!\*)/g,(function(e,t,r){return n(r,t+"<em>","</em>")})):(e=(e=e.replace(/\*\*\*(\S[\s\S]*?)\*\*\*/g,(function(e,t){return/\S$/.test(t)?n(t,"<strong><em>","</em></strong>"):e}))).replace(/\*\*(\S[\s\S]*?)\*\*/g,(function(e,t){return/\S$/.test(t)?n(t,"<strong>","</strong>"):e}))).replace(/\*([^\s*][\s\S]*?)\*/g,(function(e,t){return/\S$/.test(t)?n(t,"<em>","</em>"):e})),e=r.converter._dispatch("italicsAndBold.after",e,t,r)})),a.subParser("lists",(function(e,t,r){"use strict";function n(e,n){r.gListLevel++,e=e.replace(/\n{2,}$/,"\n");var o=/(\n)?(^ {0,3})([*+-]|\d+[.])[ \t]+((\[(x|X| )?])?[ \t]*[^\r]+?(\n{1,2}))(?=\n*(¨0| {0,3}([*+-]|\d+[.])[ \t]+))/gm,i=/\n[ \t]*\n(?!¨0)/.test(e+="¨0");return t.disableForced4SpacesIndentedSublists&&(o=/(\n)?(^ {0,3})([*+-]|\d+[.])[ \t]+((\[(x|X| )?])?[ \t]*[^\r]+?(\n{1,2}))(?=\n*(¨0|\2([*+-]|\d+[.])[ \t]+))/gm),e=(e=e.replace(o,(function(e,n,o,s,l,c,u){u=u&&""!==u.trim();var d=a.subParser("outdent")(l,t,r),p="";return c&&t.tasklists&&(p=' class="task-list-item" style="list-style-type: none;"',d=d.replace(/^[ \t]*\[(x|X| )?]/m,(function(){var e='<input type="checkbox" disabled style="margin: 0px 0.35em 0.25em -1.6em; vertical-align: middle;"';return u&&(e+=" checked"),e+=">"}))),d=d.replace(/^([-*+]|\d\.)[ \t]+[\S\n ]*/g,(function(e){return"¨A"+e})),n||d.search(/\n{2,}/)>-1?(d=a.subParser("githubCodeBlocks")(d,t,r),d=a.subParser("blockGamut")(d,t,r)):(d=(d=a.subParser("lists")(d,t,r)).replace(/\n$/,""),d=(d=a.subParser("hashHTMLBlocks")(d,t,r)).replace(/\n\n+/g,"\n\n"),d=i?a.subParser("paragraphs")(d,t,r):a.subParser("spanGamut")(d,t,r)),d="<li"+p+">"+(d=d.replace("¨A",""))+"</li>\n"}))).replace(/¨0/g,""),r.gListLevel--,n&&(e=e.replace(/\s+$/,"")),e}function o(e,t){if("ol"===t){var r=e.match(/^ *(\d+)\./);if(r&&"1"!==r[1])return' start="'+r[1]+'"'}return""}function i(e,r,a){var i=t.disableForced4SpacesIndentedSublists?/^ ?\d+\.[ \t]/gm:/^ {0,3}\d+\.[ \t]/gm,s=t.disableForced4SpacesIndentedSublists?/^ ?[*+-][ \t]/gm:/^ {0,3}[*+-][ \t]/gm,l="ul"===r?i:s,c="";if(-1!==e.search(l))!function t(u){var d=u.search(l),p=o(e,r);-1!==d?(c+="\n\n<"+r+p+">\n"+n(u.slice(0,d),!!a)+"</"+r+">\n",l="ul"===(r="ul"===r?"ol":"ul")?i:s,t(u.slice(d))):c+="\n\n<"+r+p+">\n"+n(u,!!a)+"</"+r+">\n"}(e);else{var u=o(e,r);c="\n\n<"+r+u+">\n"+n(e,!!a)+"</"+r+">\n"}return c}return e=r.converter._dispatch("lists.before",e,t,r),e+="¨0",e=(e=r.gListLevel?e.replace(/^(( {0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(¨0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm,(function(e,t,r){return i(t,r.search(/[*+-]/g)>-1?"ul":"ol",!0)})):e.replace(/(\n\n|^\n?)(( {0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(¨0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm,(function(e,t,r,n){return i(r,n.search(/[*+-]/g)>-1?"ul":"ol",!1)}))).replace(/¨0/,""),e=r.converter._dispatch("lists.after",e,t,r)})),a.subParser("metadata",(function(e,t,r){"use strict";if(!t.metadata)return e;function n(e){r.metadata.raw=e,(e=(e=e.replace(/&/g,"&").replace(/"/g,""")).replace(/\n {4}/g," ")).replace(/^([\S ]+): +([\s\S]+?)$/gm,(function(e,t,n){return r.metadata.parsed[t]=n,""}))}return e=(e=(e=(e=r.converter._dispatch("metadata.before",e,t,r)).replace(/^\s*«««+(\S*?)\n([\s\S]+?)\n»»»+\n/,(function(e,t,r){return n(r),"¨M"}))).replace(/^\s*---+(\S*?)\n([\s\S]+?)\n---+\n/,(function(e,t,o){return t&&(r.metadata.format=t),n(o),"¨M"}))).replace(/¨M/g,""),e=r.converter._dispatch("metadata.after",e,t,r)})),a.subParser("outdent",(function(e,t,r){"use strict";return e=(e=(e=r.converter._dispatch("outdent.before",e,t,r)).replace(/^(\t|[ ]{1,4})/gm,"¨0")).replace(/¨0/g,""),e=r.converter._dispatch("outdent.after",e,t,r)})),a.subParser("paragraphs",(function(e,t,r){"use strict";for(var n=(e=(e=(e=r.converter._dispatch("paragraphs.before",e,t,r)).replace(/^\n+/g,"")).replace(/\n+$/g,"")).split(/\n{2,}/g),o=[],i=n.length,s=0;s<i;s++){var l=n[s];l.search(/¨(K|G)(\d+)\1/g)>=0?o.push(l):l.search(/\S/)>=0&&(l=(l=a.subParser("spanGamut")(l,t,r)).replace(/^([ \t]*)/g,"<p>"),l+="</p>",o.push(l))}for(i=o.length,s=0;s<i;s++){for(var c="",u=o[s],d=!1;/¨(K|G)(\d+)\1/.test(u);){var p=RegExp.$1,f=RegExp.$2;c=(c="K"===p?r.gHtmlBlocks[f]:d?a.subParser("encodeCode")(r.ghCodeBlocks[f].text,t,r):r.ghCodeBlocks[f].codeblock).replace(/\$/g,"$$$$"),u=u.replace(/(\n\n)?¨(K|G)\d+\2(\n\n)?/,c),/^<pre\b[^>]*>\s*<code\b[^>]*>/.test(u)&&(d=!0)}o[s]=u}return e=(e=(e=o.join("\n")).replace(/^\n+/g,"")).replace(/\n+$/g,""),r.converter._dispatch("paragraphs.after",e,t,r)})),a.subParser("runExtension",(function(e,t,r,n){"use strict";if(e.filter)t=e.filter(t,n.converter,r);else if(e.regex){var o=e.regex;o instanceof RegExp||(o=new RegExp(o,"g")),t=t.replace(o,e.replace)}return t})),a.subParser("spanGamut",(function(e,t,r){"use strict";return e=r.converter._dispatch("spanGamut.before",e,t,r),e=a.subParser("codeSpans")(e,t,r),e=a.subParser("escapeSpecialCharsWithinTagAttributes")(e,t,r),e=a.subParser("encodeBackslashEscapes")(e,t,r),e=a.subParser("images")(e,t,r),e=a.subParser("anchors")(e,t,r),e=a.subParser("autoLinks")(e,t,r),e=a.subParser("simplifiedAutoLinks")(e,t,r),e=a.subParser("emoji")(e,t,r),e=a.subParser("underline")(e,t,r),e=a.subParser("italicsAndBold")(e,t,r),e=a.subParser("strikethrough")(e,t,r),e=a.subParser("ellipsis")(e,t,r),e=a.subParser("hashHTMLSpans")(e,t,r),e=a.subParser("encodeAmpsAndAngles")(e,t,r),t.simpleLineBreaks?/\n\n¨K/.test(e)||(e=e.replace(/\n+/g,"<br />\n")):e=e.replace(/ +\n/g,"<br />\n"),e=r.converter._dispatch("spanGamut.after",e,t,r)})),a.subParser("strikethrough",(function(e,t,r){"use strict";return t.strikethrough&&(e=(e=r.converter._dispatch("strikethrough.before",e,t,r)).replace(/(?:~){2}([\s\S]+?)(?:~){2}/g,(function(e,n){return function(e){return t.simplifiedAutoLink&&(e=a.subParser("simplifiedAutoLinks")(e,t,r)),"<del>"+e+"</del>"}(n)})),e=r.converter._dispatch("strikethrough.after",e,t,r)),e})),a.subParser("stripLinkDefinitions",(function(e,t,r){"use strict";var n=function(e,n,o,i,s,l,c){return n=n.toLowerCase(),o.match(/^data:.+?\/.+?;base64,/)?r.gUrls[n]=o.replace(/\s/g,""):r.gUrls[n]=a.subParser("encodeAmpsAndAngles")(o,t,r),l?l+c:(c&&(r.gTitles[n]=c.replace(/"|'/g,""")),t.parseImgDimensions&&i&&s&&(r.gDimensions[n]={width:i,height:s}),"")};return e=(e=(e=(e+="¨0").replace(/^ {0,3}\[(.+)]:[ \t]*\n?[ \t]*<?(data:.+?\/.+?;base64,[A-Za-z0-9+/=\n]+?)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*\n?[ \t]*(?:(\n*)["|'(](.+?)["|')][ \t]*)?(?:\n\n|(?=¨0)|(?=\n\[))/gm,n)).replace(/^ {0,3}\[(.+)]:[ \t]*\n?[ \t]*<?([^>\s]+)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*\n?[ \t]*(?:(\n*)["|'(](.+?)["|')][ \t]*)?(?:\n+|(?=¨0))/gm,n)).replace(/¨0/,"")})),a.subParser("tables",(function(e,t,r){"use strict";if(!t.tables)return e;function n(e,n){return"<td"+n+">"+a.subParser("spanGamut")(e,t,r)+"</td>\n"}function o(e){var o,i=e.split("\n");for(o=0;o<i.length;++o)/^ {0,3}\|/.test(i[o])&&(i[o]=i[o].replace(/^ {0,3}\|/,"")),/\|[ \t]*$/.test(i[o])&&(i[o]=i[o].replace(/\|[ \t]*$/,"")),i[o]=a.subParser("codeSpans")(i[o],t,r);var s,l,c,u,d=i[0].split("|").map((function(e){return e.trim()})),p=i[1].split("|").map((function(e){return e.trim()})),f=[],h=[],g=[],m=[];for(i.shift(),i.shift(),o=0;o<i.length;++o)""!==i[o].trim()&&f.push(i[o].split("|").map((function(e){return e.trim()})));if(d.length<p.length)return e;for(o=0;o<p.length;++o)g.push((s=p[o],/^:[ \t]*--*$/.test(s)?' style="text-align:left;"':/^--*[ \t]*:[ \t]*$/.test(s)?' style="text-align:right;"':/^:[ \t]*--*[ \t]*:$/.test(s)?' style="text-align:center;"':""));for(o=0;o<d.length;++o)a.helper.isUndefined(g[o])&&(g[o]=""),h.push((l=d[o],c=g[o],u=void 0,u="",l=l.trim(),(t.tablesHeaderId||t.tableHeaderId)&&(u=' id="'+l.replace(/ /g,"_").toLowerCase()+'"'),"<th"+u+c+">"+(l=a.subParser("spanGamut")(l,t,r))+"</th>\n"));for(o=0;o<f.length;++o){for(var b=[],_=0;_<h.length;++_)a.helper.isUndefined(f[o][_]),b.push(n(f[o][_],g[_]));m.push(b)}return function(e,t){for(var r="<table>\n<thead>\n<tr>\n",n=e.length,o=0;o<n;++o)r+=e[o];for(r+="</tr>\n</thead>\n<tbody>\n",o=0;o<t.length;++o){r+="<tr>\n";for(var a=0;a<n;++a)r+=t[o][a];r+="</tr>\n"}return r+"</tbody>\n</table>\n"}(h,m)}return e=(e=(e=(e=r.converter._dispatch("tables.before",e,t,r)).replace(/\\(\|)/g,a.helper.escapeCharactersCallback)).replace(/^ {0,3}\|?.+\|.+\n {0,3}\|?[ \t]*:?[ \t]*(?:[-=]){2,}[ \t]*:?[ \t]*\|[ \t]*:?[ \t]*(?:[-=]){2,}[\s\S]+?(?:\n\n|¨0)/gm,o)).replace(/^ {0,3}\|.+\|[ \t]*\n {0,3}\|[ \t]*:?[ \t]*(?:[-=]){2,}[ \t]*:?[ \t]*\|[ \t]*\n( {0,3}\|.+\|[ \t]*\n)*(?:\n|¨0)/gm,o),e=r.converter._dispatch("tables.after",e,t,r)})),a.subParser("underline",(function(e,t,r){"use strict";return t.underline?(e=r.converter._dispatch("underline.before",e,t,r),e=(e=t.literalMidWordUnderscores?(e=e.replace(/\b___(\S[\s\S]*?)___\b/g,(function(e,t){return"<u>"+t+"</u>"}))).replace(/\b__(\S[\s\S]*?)__\b/g,(function(e,t){return"<u>"+t+"</u>"})):(e=e.replace(/___(\S[\s\S]*?)___/g,(function(e,t){return/\S$/.test(t)?"<u>"+t+"</u>":e}))).replace(/__(\S[\s\S]*?)__/g,(function(e,t){return/\S$/.test(t)?"<u>"+t+"</u>":e}))).replace(/(_)/g,a.helper.escapeCharactersCallback),e=r.converter._dispatch("underline.after",e,t,r)):e})),a.subParser("unescapeSpecialChars",(function(e,t,r){"use strict";return e=(e=r.converter._dispatch("unescapeSpecialChars.before",e,t,r)).replace(/¨E(\d+)E/g,(function(e,t){var r=parseInt(t);return String.fromCharCode(r)})),e=r.converter._dispatch("unescapeSpecialChars.after",e,t,r)})),a.subParser("makeMarkdown.blockquote",(function(e,t){"use strict";var r="";if(e.hasChildNodes())for(var n=e.childNodes,o=n.length,i=0;i<o;++i){var s=a.subParser("makeMarkdown.node")(n[i],t);""!==s&&(r+=s)}return r="> "+(r=r.trim()).split("\n").join("\n> ")})),a.subParser("makeMarkdown.codeBlock",(function(e,t){"use strict";var r=e.getAttribute("language"),n=e.getAttribute("precodenum");return"```"+r+"\n"+t.preList[n]+"\n```"})),a.subParser("makeMarkdown.codeSpan",(function(e){"use strict";return"`"+e.innerHTML+"`"})),a.subParser("makeMarkdown.emphasis",(function(e,t){"use strict";var r="";if(e.hasChildNodes()){r+="*";for(var n=e.childNodes,o=n.length,i=0;i<o;++i)r+=a.subParser("makeMarkdown.node")(n[i],t);r+="*"}return r})),a.subParser("makeMarkdown.header",(function(e,t,r){"use strict";var n=new Array(r+1).join("#"),o="";if(e.hasChildNodes()){o=n+" ";for(var i=e.childNodes,s=i.length,l=0;l<s;++l)o+=a.subParser("makeMarkdown.node")(i[l],t)}return o})),a.subParser("makeMarkdown.hr",(function(){"use strict";return"---"})),a.subParser("makeMarkdown.image",(function(e){"use strict";var t="";return e.hasAttribute("src")&&(t+="+">",e.hasAttribute("width")&&e.hasAttribute("height")&&(t+=" ="+e.getAttribute("width")+"x"+e.getAttribute("height")),e.hasAttribute("title")&&(t+=' "'+e.getAttribute("title")+'"'),t+=")"),t})),a.subParser("makeMarkdown.links",(function(e,t){"use strict";var r="";if(e.hasChildNodes()&&e.hasAttribute("href")){var n=e.childNodes,o=n.length;r="[";for(var i=0;i<o;++i)r+=a.subParser("makeMarkdown.node")(n[i],t);r+="](",r+="<"+e.getAttribute("href")+">",e.hasAttribute("title")&&(r+=' "'+e.getAttribute("title")+'"'),r+=")"}return r})),a.subParser("makeMarkdown.list",(function(e,t,r){"use strict";var n="";if(!e.hasChildNodes())return"";for(var o=e.childNodes,i=o.length,s=e.getAttribute("start")||1,l=0;l<i;++l)if(void 0!==o[l].tagName&&"li"===o[l].tagName.toLowerCase()){n+=("ol"===r?s.toString()+". ":"- ")+a.subParser("makeMarkdown.listItem")(o[l],t),++s}return(n+="\n\x3c!-- --\x3e\n").trim()})),a.subParser("makeMarkdown.listItem",(function(e,t){"use strict";for(var r="",n=e.childNodes,o=n.length,i=0;i<o;++i)r+=a.subParser("makeMarkdown.node")(n[i],t);return/\n$/.test(r)?r=r.split("\n").join("\n ").replace(/^ {4}$/gm,"").replace(/\n\n+/g,"\n\n"):r+="\n",r})),a.subParser("makeMarkdown.node",(function(e,t,r){"use strict";r=r||!1;var n="";if(3===e.nodeType)return a.subParser("makeMarkdown.txt")(e,t);if(8===e.nodeType)return"\x3c!--"+e.data+"--\x3e\n\n";if(1!==e.nodeType)return"";switch(e.tagName.toLowerCase()){case"h1":r||(n=a.subParser("makeMarkdown.header")(e,t,1)+"\n\n");break;case"h2":r||(n=a.subParser("makeMarkdown.header")(e,t,2)+"\n\n");break;case"h3":r||(n=a.subParser("makeMarkdown.header")(e,t,3)+"\n\n");break;case"h4":r||(n=a.subParser("makeMarkdown.header")(e,t,4)+"\n\n");break;case"h5":r||(n=a.subParser("makeMarkdown.header")(e,t,5)+"\n\n");break;case"h6":r||(n=a.subParser("makeMarkdown.header")(e,t,6)+"\n\n");break;case"p":r||(n=a.subParser("makeMarkdown.paragraph")(e,t)+"\n\n");break;case"blockquote":r||(n=a.subParser("makeMarkdown.blockquote")(e,t)+"\n\n");break;case"hr":r||(n=a.subParser("makeMarkdown.hr")(e,t)+"\n\n");break;case"ol":r||(n=a.subParser("makeMarkdown.list")(e,t,"ol")+"\n\n");break;case"ul":r||(n=a.subParser("makeMarkdown.list")(e,t,"ul")+"\n\n");break;case"precode":r||(n=a.subParser("makeMarkdown.codeBlock")(e,t)+"\n\n");break;case"pre":r||(n=a.subParser("makeMarkdown.pre")(e,t)+"\n\n");break;case"table":r||(n=a.subParser("makeMarkdown.table")(e,t)+"\n\n");break;case"code":n=a.subParser("makeMarkdown.codeSpan")(e,t);break;case"em":case"i":n=a.subParser("makeMarkdown.emphasis")(e,t);break;case"strong":case"b":n=a.subParser("makeMarkdown.strong")(e,t);break;case"del":n=a.subParser("makeMarkdown.strikethrough")(e,t);break;case"a":n=a.subParser("makeMarkdown.links")(e,t);break;case"img":n=a.subParser("makeMarkdown.image")(e,t);break;default:n=e.outerHTML+"\n\n"}return n})),a.subParser("makeMarkdown.paragraph",(function(e,t){"use strict";var r="";if(e.hasChildNodes())for(var n=e.childNodes,o=n.length,i=0;i<o;++i)r+=a.subParser("makeMarkdown.node")(n[i],t);return r=r.trim()})),a.subParser("makeMarkdown.pre",(function(e,t){"use strict";var r=e.getAttribute("prenum");return"<pre>"+t.preList[r]+"</pre>"})),a.subParser("makeMarkdown.strikethrough",(function(e,t){"use strict";var r="";if(e.hasChildNodes()){r+="~~";for(var n=e.childNodes,o=n.length,i=0;i<o;++i)r+=a.subParser("makeMarkdown.node")(n[i],t);r+="~~"}return r})),a.subParser("makeMarkdown.strong",(function(e,t){"use strict";var r="";if(e.hasChildNodes()){r+="**";for(var n=e.childNodes,o=n.length,i=0;i<o;++i)r+=a.subParser("makeMarkdown.node")(n[i],t);r+="**"}return r})),a.subParser("makeMarkdown.table",(function(e,t){"use strict";var r,n,o="",i=[[],[]],s=e.querySelectorAll("thead>tr>th"),l=e.querySelectorAll("tbody>tr");for(r=0;r<s.length;++r){var c=a.subParser("makeMarkdown.tableCell")(s[r],t),u="---";if(s[r].hasAttribute("style"))switch(s[r].getAttribute("style").toLowerCase().replace(/\s/g,"")){case"text-align:left;":u=":---";break;case"text-align:right;":u="---:";break;case"text-align:center;":u=":---:"}i[0][r]=c.trim(),i[1][r]=u}for(r=0;r<l.length;++r){var d=i.push([])-1,p=l[r].getElementsByTagName("td");for(n=0;n<s.length;++n){var f=" ";void 0!==p[n]&&(f=a.subParser("makeMarkdown.tableCell")(p[n],t)),i[d].push(f)}}var h=3;for(r=0;r<i.length;++r)for(n=0;n<i[r].length;++n){var g=i[r][n].length;g>h&&(h=g)}for(r=0;r<i.length;++r){for(n=0;n<i[r].length;++n)1===r?":"===i[r][n].slice(-1)?i[r][n]=a.helper.padEnd(i[r][n].slice(-1),h-1,"-")+":":i[r][n]=a.helper.padEnd(i[r][n],h,"-"):i[r][n]=a.helper.padEnd(i[r][n],h);o+="| "+i[r].join(" | ")+" |\n"}return o.trim()})),a.subParser("makeMarkdown.tableCell",(function(e,t){"use strict";var r="";if(!e.hasChildNodes())return"";for(var n=e.childNodes,o=n.length,i=0;i<o;++i)r+=a.subParser("makeMarkdown.node")(n[i],t,!0);return r.trim()})),a.subParser("makeMarkdown.txt",(function(e){"use strict";var t=e.nodeValue;return t=(t=t.replace(/ +/g," ")).replace(/¨NBSP;/g," "),t=(t=(t=(t=(t=(t=(t=(t=(t=a.helper.unescapeHTMLEntities(t)).replace(/([*_~|`])/g,"\\$1")).replace(/^(\s*)>/g,"\\$1>")).replace(/^#/gm,"\\#")).replace(/^(\s*)([-=]{3,})(\s*)$/,"$1\\$2$3")).replace(/^( {0,3}\d+)\./gm,"$1\\.")).replace(/^( {0,3})([+-])/gm,"$1\\$2")).replace(/]([\s]*)\(/g,"\\]$1\\(")).replace(/^ {0,3}\[([\S \t]*?)]:/gm,"\\[$1]:")}));void 0===(n=function(){"use strict";return a}.call(t,r,t,e))||(e.exports=n)}).call(this)}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var a=t[n]={exports:{}};return e[n].call(a.exports,a,a.exports,r),a.exports}r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,{a:t}),t},r.d=function(e,t){for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};!function(){"use strict";r.r(n),r.d(n,{__EXPERIMENTAL_ELEMENTS:function(){return $},__EXPERIMENTAL_PATHS_WITH_MERGE:function(){return U},__EXPERIMENTAL_STYLE_PROPERTY:function(){return R},__experimentalCloneSanitizedBlock:function(){return Re},__experimentalGetAccessibleBlockLabel:function(){return at},__experimentalGetBlockAttributesNamesByRole:function(){return st},__experimentalGetBlockLabel:function(){return ot},__experimentalSanitizeBlockAttributes:function(){return it},__unstableGetBlockProps:function(){return Er},__unstableGetInnerBlocksProps:function(){return Ar},__unstableSerializeAndClean:function(){return Mr},children:function(){return Dn},cloneBlock:function(){return $e},createBlock:function(){return He},createBlocksFromInnerBlocksTemplate:function(){return Ve},doBlocksMatchTemplate:function(){return Ro},findTransform:function(){return Ke},getBlockAttributes:function(){return $n},getBlockContent:function(){return Pr},getBlockDefaultClassName:function(){return vr},getBlockFromExample:function(){return Ze},getBlockMenuDefaultClassName:function(){return Tr},getBlockSupport:function(){return be},getBlockTransforms:function(){return We},getBlockType:function(){return ge},getBlockTypes:function(){return me},getBlockVariations:function(){return Ee},getCategories:function(){return Io},getChildBlockNames:function(){return we},getDefaultBlockName:function(){return he},getFreeformContentHandlerName:function(){return le},getGroupingBlockName:function(){return ce},getPhrasingContentSchema:function(){return po},getPossibleBlockTransformations:function(){return Ge},getSaveContent:function(){return Br},getSaveElement:function(){return Sr},getUnregisteredTypeHandlerName:function(){return de},hasBlockSupport:function(){return _e},hasChildBlocks:function(){return ve},hasChildBlocksWithInserterSupport:function(){return Te},isReusableBlock:function(){return ke},isTemplatePart:function(){return ye},isUnmodifiedBlock:function(){return Je},isUnmodifiedDefaultBlock:function(){return et},isValidBlockContent:function(){return wn},isValidIcon:function(){return tt},node:function(){return Ln},normalizeIconObject:function(){return rt},parse:function(){return Wn},parseWithAttributeSchema:function(){return Rn},pasteHandler:function(){return zo},rawHandler:function(){return fo},registerBlockCollection:function(){return ae},registerBlockStyle:function(){return Ce},registerBlockType:function(){return ne},registerBlockVariation:function(){return Ae},serialize:function(){return Or},serializeRawBlock:function(){return wr},setCategories:function(){return Ho},setDefaultBlockName:function(){return pe},setFreeformContentHandlerName:function(){return se},setGroupingBlockName:function(){return fe},setUnregisteredTypeHandlerName:function(){return ue},store:function(){return mr},switchToBlockType:function(){return Qe},synchronizeBlocksWithTemplate:function(){return $o},unregisterBlockStyle:function(){return xe},unregisterBlockType:function(){return ie},unregisterBlockVariation:function(){return Se},unstable__bootstrapServerSideBlockDefinitions:function(){return te},updateCategory:function(){return Vo},validateBlock:function(){return yn},withBlockContentContext:function(){return Uo}});var e={};r.r(e),r.d(e,{__experimentalGetUnprocessedBlockTypes:function(){return Et},__experimentalHasContentRoleAttribute:function(){return qt},getActiveBlockVariation:function(){return Pt},getBlockStyles:function(){return Bt},getBlockSupport:function(){return Vt},getBlockType:function(){return St},getBlockTypes:function(){return At},getBlockVariations:function(){return Nt},getCategories:function(){return Mt},getChildBlockNames:function(){return Ht},getCollections:function(){return Ot},getDefaultBlockName:function(){return jt},getDefaultBlockVariation:function(){return Lt},getFreeformFallbackBlockName:function(){return Dt},getGroupingBlockName:function(){return It},getUnregisteredFallbackBlockName:function(){return zt},hasBlockSupport:function(){return Rt},hasChildBlocks:function(){return Ut},hasChildBlocksWithInserterSupport:function(){return Ft},isMatchingSearchTerm:function(){return $t}});var t={};r.r(t),r.d(t,{__experimentalReapplyBlockTypeFilters:function(){return rr},__experimentalRegisterBlockType:function(){return tr},addBlockCollection:function(){return hr},addBlockStyles:function(){return or},addBlockTypes:function(){return er},addBlockVariations:function(){return ir},removeBlockCollection:function(){return gr},removeBlockStyles:function(){return ar},removeBlockTypes:function(){return nr},removeBlockVariations:function(){return sr},setCategories:function(){return pr},setDefaultBlockName:function(){return lr},setFreeformFallbackBlockName:function(){return cr},setGroupingBlockName:function(){return dr},setUnregisteredFallbackBlockName:function(){return ur},updateCategory:function(){return fr}});var o=window.wp.data,a=window.lodash,i=window.wp.i18n,s={grad:.9,turn:360,rad:360/(2*Math.PI)},l=function(e){return"string"==typeof e?e.length>0:"number"==typeof e},c=function(e,t,r){return void 0===t&&(t=0),void 0===r&&(r=Math.pow(10,t)),Math.round(r*e)/r+0},u=function(e,t,r){return void 0===t&&(t=0),void 0===r&&(r=1),e>r?r:e>t?e:t},d=function(e){return(e=isFinite(e)?e%360:0)>0?e:e+360},p=function(e){return{r:u(e.r,0,255),g:u(e.g,0,255),b:u(e.b,0,255),a:u(e.a)}},f=function(e){return{r:c(e.r),g:c(e.g),b:c(e.b),a:c(e.a,3)}},h=/^#([0-9a-f]{3,8})$/i,g=function(e){var t=e.toString(16);return t.length<2?"0"+t:t},m=function(e){var t=e.r,r=e.g,n=e.b,o=e.a,a=Math.max(t,r,n),i=a-Math.min(t,r,n),s=i?a===t?(r-n)/i:a===r?2+(n-t)/i:4+(t-r)/i:0;return{h:60*(s<0?s+6:s),s:a?i/a*100:0,v:a/255*100,a:o}},b=function(e){var t=e.h,r=e.s,n=e.v,o=e.a;t=t/360*6,r/=100,n/=100;var a=Math.floor(t),i=n*(1-r),s=n*(1-(t-a)*r),l=n*(1-(1-t+a)*r),c=a%6;return{r:255*[n,s,i,i,l,n][c],g:255*[l,n,n,s,i,i][c],b:255*[i,i,l,n,n,s][c],a:o}},_=function(e){return{h:d(e.h),s:u(e.s,0,100),l:u(e.l,0,100),a:u(e.a)}},k=function(e){return{h:c(e.h),s:c(e.s),l:c(e.l),a:c(e.a,3)}},y=function(e){return b((r=(t=e).s,{h:t.h,s:(r*=((n=t.l)<50?n:100-n)/100)>0?2*r/(n+r)*100:0,v:n+r,a:t.a}));var t,r,n},w=function(e){return{h:(t=m(e)).h,s:(o=(200-(r=t.s))*(n=t.v)/100)>0&&o<200?r*n/100/(o<=100?o:200-o)*100:0,l:o/2,a:t.a};var t,r,n,o},v=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,T=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,C=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,x=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,E={string:[[function(e){var t=h.exec(e);return t?(e=t[1]).length<=4?{r:parseInt(e[0]+e[0],16),g:parseInt(e[1]+e[1],16),b:parseInt(e[2]+e[2],16),a:4===e.length?c(parseInt(e[3]+e[3],16)/255,2):1}:6===e.length||8===e.length?{r:parseInt(e.substr(0,2),16),g:parseInt(e.substr(2,2),16),b:parseInt(e.substr(4,2),16),a:8===e.length?c(parseInt(e.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(e){var t=C.exec(e)||x.exec(e);return t?t[2]!==t[4]||t[4]!==t[6]?null:p({r:Number(t[1])/(t[2]?100/255:1),g:Number(t[3])/(t[4]?100/255:1),b:Number(t[5])/(t[6]?100/255:1),a:void 0===t[7]?1:Number(t[7])/(t[8]?100:1)}):null},"rgb"],[function(e){var t=v.exec(e)||T.exec(e);if(!t)return null;var r,n,o=_({h:(r=t[1],n=t[2],void 0===n&&(n="deg"),Number(r)*(s[n]||1)),s:Number(t[3]),l:Number(t[4]),a:void 0===t[5]?1:Number(t[5])/(t[6]?100:1)});return y(o)},"hsl"]],object:[[function(e){var t=e.r,r=e.g,n=e.b,o=e.a,a=void 0===o?1:o;return l(t)&&l(r)&&l(n)?p({r:Number(t),g:Number(r),b:Number(n),a:Number(a)}):null},"rgb"],[function(e){var t=e.h,r=e.s,n=e.l,o=e.a,a=void 0===o?1:o;if(!l(t)||!l(r)||!l(n))return null;var i=_({h:Number(t),s:Number(r),l:Number(n),a:Number(a)});return y(i)},"hsl"],[function(e){var t=e.h,r=e.s,n=e.v,o=e.a,a=void 0===o?1:o;if(!l(t)||!l(r)||!l(n))return null;var i=function(e){return{h:d(e.h),s:u(e.s,0,100),v:u(e.v,0,100),a:u(e.a)}}({h:Number(t),s:Number(r),v:Number(n),a:Number(a)});return b(i)},"hsv"]]},A=function(e,t){for(var r=0;r<t.length;r++){var n=t[r][0](e);if(n)return[n,t[r][1]]}return[null,void 0]},S=function(e){return"string"==typeof e?A(e.trim(),E.string):"object"==typeof e&&null!==e?A(e,E.object):[null,void 0]},B=function(e,t){var r=w(e);return{h:r.h,s:u(r.s+100*t,0,100),l:r.l,a:r.a}},N=function(e){return(299*e.r+587*e.g+114*e.b)/1e3/255},P=function(e,t){var r=w(e);return{h:r.h,s:r.s,l:u(r.l+100*t,0,100),a:r.a}},L=function(){function e(e){this.parsed=S(e)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return e.prototype.isValid=function(){return null!==this.parsed},e.prototype.brightness=function(){return c(N(this.rgba),2)},e.prototype.isDark=function(){return N(this.rgba)<.5},e.prototype.isLight=function(){return N(this.rgba)>=.5},e.prototype.toHex=function(){return t=(e=f(this.rgba)).r,r=e.g,n=e.b,a=(o=e.a)<1?g(c(255*o)):"","#"+g(t)+g(r)+g(n)+a;var e,t,r,n,o,a},e.prototype.toRgb=function(){return f(this.rgba)},e.prototype.toRgbString=function(){return t=(e=f(this.rgba)).r,r=e.g,n=e.b,(o=e.a)<1?"rgba("+t+", "+r+", "+n+", "+o+")":"rgb("+t+", "+r+", "+n+")";var e,t,r,n,o},e.prototype.toHsl=function(){return k(w(this.rgba))},e.prototype.toHslString=function(){return t=(e=k(w(this.rgba))).h,r=e.s,n=e.l,(o=e.a)<1?"hsla("+t+", "+r+"%, "+n+"%, "+o+")":"hsl("+t+", "+r+"%, "+n+"%)";var e,t,r,n,o},e.prototype.toHsv=function(){return e=m(this.rgba),{h:c(e.h),s:c(e.s),v:c(e.v),a:c(e.a,3)};var e},e.prototype.invert=function(){return M({r:255-(e=this.rgba).r,g:255-e.g,b:255-e.b,a:e.a});var e},e.prototype.saturate=function(e){return void 0===e&&(e=.1),M(B(this.rgba,e))},e.prototype.desaturate=function(e){return void 0===e&&(e=.1),M(B(this.rgba,-e))},e.prototype.grayscale=function(){return M(B(this.rgba,-1))},e.prototype.lighten=function(e){return void 0===e&&(e=.1),M(P(this.rgba,e))},e.prototype.darken=function(e){return void 0===e&&(e=.1),M(P(this.rgba,-e))},e.prototype.rotate=function(e){return void 0===e&&(e=15),this.hue(this.hue()+e)},e.prototype.alpha=function(e){return"number"==typeof e?M({r:(t=this.rgba).r,g:t.g,b:t.b,a:e}):c(this.rgba.a,3);var t},e.prototype.hue=function(e){var t=w(this.rgba);return"number"==typeof e?M({h:e,s:t.s,l:t.l,a:t.a}):c(t.h)},e.prototype.isEqual=function(e){return this.toHex()===M(e).toHex()},e}(),M=function(e){return e instanceof L?e:new L(e)},O=[];var j=function(e){var t=e/255;return t<.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)},D=function(e){return.2126*j(e.r)+.7152*j(e.g)+.0722*j(e.b)};var z=window.wp.element,I=window.wp.dom;const H="block-default",V=["attributes","supports","save","migrate","isEligible","apiVersion"],R={"--wp--style--color--link":{value:["color","link"],support:["color","link"]},background:{value:["color","gradient"],support:["color","gradients"],useEngine:!0},backgroundColor:{value:["color","background"],support:["color","background"],requiresOptOut:!0,useEngine:!0},borderColor:{value:["border","color"],support:["__experimentalBorder","color"],useEngine:!0},borderRadius:{value:["border","radius"],support:["__experimentalBorder","radius"],properties:{borderTopLeftRadius:"topLeft",borderTopRightRadius:"topRight",borderBottomLeftRadius:"bottomLeft",borderBottomRightRadius:"bottomRight"},useEngine:!0},borderStyle:{value:["border","style"],support:["__experimentalBorder","style"],useEngine:!0},borderWidth:{value:["border","width"],support:["__experimentalBorder","width"],useEngine:!0},borderTopColor:{value:["border","top","color"],support:["__experimentalBorder","color"],useEngine:!0},borderTopStyle:{value:["border","top","style"],support:["__experimentalBorder","style"],useEngine:!0},borderTopWidth:{value:["border","top","width"],support:["__experimentalBorder","width"],useEngine:!0},borderRightColor:{value:["border","right","color"],support:["__experimentalBorder","color"],useEngine:!0},borderRightStyle:{value:["border","right","style"],support:["__experimentalBorder","style"],useEngine:!0},borderRightWidth:{value:["border","right","width"],support:["__experimentalBorder","width"],useEngine:!0},borderBottomColor:{value:["border","bottom","color"],support:["__experimentalBorder","color"],useEngine:!0},borderBottomStyle:{value:["border","bottom","style"],support:["__experimentalBorder","style"],useEngine:!0},borderBottomWidth:{value:["border","bottom","width"],support:["__experimentalBorder","width"],useEngine:!0},borderLeftColor:{value:["border","left","color"],support:["__experimentalBorder","color"],useEngine:!0},borderLeftStyle:{value:["border","left","style"],support:["__experimentalBorder","style"],useEngine:!0},borderLeftWidth:{value:["border","left","width"],support:["__experimentalBorder","width"],useEngine:!0},color:{value:["color","text"],support:["color","text"],requiresOptOut:!0,useEngine:!0},filter:{value:["filter","duotone"],support:["color","__experimentalDuotone"]},linkColor:{value:["elements","link","color","text"],support:["color","link"]},buttonColor:{value:["elements","button","color","text"],support:["color","button"]},buttonBackgroundColor:{value:["elements","button","color","background"],support:["color","button"]},fontFamily:{value:["typography","fontFamily"],support:["typography","__experimentalFontFamily"],useEngine:!0},fontSize:{value:["typography","fontSize"],support:["typography","fontSize"],useEngine:!0},fontStyle:{value:["typography","fontStyle"],support:["typography","__experimentalFontStyle"],useEngine:!0},fontWeight:{value:["typography","fontWeight"],support:["typography","__experimentalFontWeight"],useEngine:!0},lineHeight:{value:["typography","lineHeight"],support:["typography","lineHeight"],useEngine:!0},margin:{value:["spacing","margin"],support:["spacing","margin"],properties:{marginTop:"top",marginRight:"right",marginBottom:"bottom",marginLeft:"left"},useEngine:!0},minHeight:{value:["dimensions","minHeight"],support:["dimensions","minHeight"],useEngine:!0},padding:{value:["spacing","padding"],support:["spacing","padding"],properties:{paddingTop:"top",paddingRight:"right",paddingBottom:"bottom",paddingLeft:"left"},useEngine:!0},textDecoration:{value:["typography","textDecoration"],support:["typography","__experimentalTextDecoration"],useEngine:!0},textTransform:{value:["typography","textTransform"],support:["typography","__experimentalTextTransform"],useEngine:!0},letterSpacing:{value:["typography","letterSpacing"],support:["typography","__experimentalLetterSpacing"],useEngine:!0},"--wp--style--root--padding":{value:["spacing","padding"],support:["spacing","padding"],properties:{"--wp--style--root--padding-top":"top","--wp--style--root--padding-right":"right","--wp--style--root--padding-bottom":"bottom","--wp--style--root--padding-left":"left"},rootOnly:!0}},$={link:"a",heading:"h1, h2, h3, h4, h5, h6",h1:"h1",h2:"h2",h3:"h3",h4:"h4",h5:"h5",h6:"h6",button:".wp-element-button, .wp-block-button__link",caption:".wp-element-caption, .wp-block-audio figcaption, .wp-block-embed figcaption, .wp-block-gallery figcaption, .wp-block-image figcaption, .wp-block-table figcaption, .wp-block-video figcaption",cite:"cite"},U={"color.duotone":!0,"color.gradients":!0,"color.palette":!0,"typography.fontFamilies":!0,"typography.fontSizes":!0,"spacing.spacingSizes":!0};var F=function(){return F=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},F.apply(this,arguments)};Object.create;Object.create;function q(e){return e.toLowerCase()}var G=[/([a-z0-9])([A-Z])/g,/([A-Z])([A-Z][a-z])/g],K=/[^A-Z0-9]+/gi;function W(e,t,r){return t instanceof RegExp?e.replace(t,r):t.reduce((function(e,t){return e.replace(t,r)}),e)}function Y(e,t){var r=e.charAt(0),n=e.substr(1).toLowerCase();return t>0&&r>="0"&&r<="9"?"_"+r+n:""+r.toUpperCase()+n}function Q(e,t){return void 0===t&&(t={}),function(e,t){void 0===t&&(t={});for(var r=t.splitRegexp,n=void 0===r?G:r,o=t.stripRegexp,a=void 0===o?K:o,i=t.transform,s=void 0===i?q:i,l=t.delimiter,c=void 0===l?" ":l,u=W(W(e,n,"$1\0$2"),a,"\0"),d=0,p=u.length;"\0"===u.charAt(d);)d++;for(;"\0"===u.charAt(p-1);)p--;return u.slice(d,p).split("\0").map(s).join(c)}(e,F({delimiter:"",transform:Y},t))}function Z(e,t){return 0===t?e.toLowerCase():Y(e,t)}const X={title:"block title",description:"block description",keywords:["block keyword"],styles:[{label:"block style label"}],variations:[{title:"block variation title",description:"block variation description",keywords:["block variation keyword"]}]},J={};function ee(e){return null!==e&&"object"==typeof e}function te(e){for(const t of Object.keys(e))J[t]?(void 0===J[t].apiVersion&&e[t].apiVersion&&(J[t].apiVersion=e[t].apiVersion),void 0===J[t].ancestor&&e[t].ancestor&&(J[t].ancestor=e[t].ancestor)):J[t]=Object.fromEntries(Object.entries(e[t]).filter((e=>{let[,t]=e;return null!=t})).map((e=>{let[t,r]=e;return[(n=t,void 0===o&&(o={}),Q(n,F({transform:Z},o))),r];var n,o})))}function re(e){let{textdomain:t,...r}=e;const n=["apiVersion","title","category","parent","ancestor","icon","description","keywords","attributes","providesContext","usesContext","supports","styles","example","variations"],o=Object.fromEntries(Object.entries(r).filter((e=>{let[t]=e;return n.includes(t)})));return t&&Object.keys(X).forEach((e=>{o[e]&&(o[e]=oe(X[e],o[e],t))})),o}function ne(e,t){const r=ee(e)?e.name:e;if("string"!=typeof r)return void console.error("Block names must be strings.");if(!/^[a-z][a-z0-9-]*\/[a-z][a-z0-9-]*$/.test(r))return void console.error("Block names must contain a namespace prefix, include only lowercase alphanumeric characters or dashes, and start with a letter. Example: my-plugin/my-custom-block");if((0,o.select)(mr).getBlockType(r))return void console.error('Block "'+r+'" is already registered.');ee(e)&&te({[r]:re(e)});const n={name:r,icon:H,keywords:[],attributes:{},providesContext:{},usesContext:[],supports:{},styles:[],variations:[],save:()=>null,...null==J?void 0:J[r],...t};return(0,o.dispatch)(mr).__experimentalRegisterBlockType(n),(0,o.select)(mr).getBlockType(r)}function oe(e,t,r){return"string"==typeof e&&"string"==typeof t?(0,i._x)(t,e,r):Array.isArray(e)&&e.length&&Array.isArray(t)?t.map((t=>oe(e[0],t,r))):ee(e)&&Object.entries(e).length&&ee(t)?Object.keys(t).reduce(((n,o)=>e[o]?(n[o]=oe(e[o],t[o],r),n):(n[o]=t[o],n)),{}):t}function ae(e,t){let{title:r,icon:n}=t;(0,o.dispatch)(mr).addBlockCollection(e,r,n)}function ie(e){const t=(0,o.select)(mr).getBlockType(e);if(t)return(0,o.dispatch)(mr).removeBlockTypes(e),t;console.error('Block "'+e+'" is not registered.')}function se(e){(0,o.dispatch)(mr).setFreeformFallbackBlockName(e)}function le(){return(0,o.select)(mr).getFreeformFallbackBlockName()}function ce(){return(0,o.select)(mr).getGroupingBlockName()}function ue(e){(0,o.dispatch)(mr).setUnregisteredFallbackBlockName(e)}function de(){return(0,o.select)(mr).getUnregisteredFallbackBlockName()}function pe(e){(0,o.dispatch)(mr).setDefaultBlockName(e)}function fe(e){(0,o.dispatch)(mr).setGroupingBlockName(e)}function he(){return(0,o.select)(mr).getDefaultBlockName()}function ge(e){var t;return null===(t=(0,o.select)(mr))||void 0===t?void 0:t.getBlockType(e)}function me(){return(0,o.select)(mr).getBlockTypes()}function be(e,t,r){return(0,o.select)(mr).getBlockSupport(e,t,r)}function _e(e,t,r){return(0,o.select)(mr).hasBlockSupport(e,t,r)}function ke(e){return"core/block"===(null==e?void 0:e.name)}function ye(e){return"core/template-part"===(null==e?void 0:e.name)}const we=e=>(0,o.select)(mr).getChildBlockNames(e),ve=e=>(0,o.select)(mr).hasChildBlocks(e),Te=e=>(0,o.select)(mr).hasChildBlocksWithInserterSupport(e),Ce=(e,t)=>{(0,o.dispatch)(mr).addBlockStyles(e,t)},xe=(e,t)=>{(0,o.dispatch)(mr).removeBlockStyles(e,t)},Ee=(e,t)=>(0,o.select)(mr).getBlockVariations(e,t),Ae=(e,t)=>{(0,o.dispatch)(mr).addBlockVariations(e,t)},Se=(e,t)=>{(0,o.dispatch)(mr).removeBlockVariations(e,t)};var Be,Ne=new Uint8Array(16);function Pe(){if(!Be&&!(Be="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Be(Ne)}var Le=/^(?:[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;for(var Me=function(e){return"string"==typeof e&&Le.test(e)},Oe=[],je=0;je<256;++je)Oe.push((je+256).toString(16).substr(1));var De=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=(Oe[e[t+0]]+Oe[e[t+1]]+Oe[e[t+2]]+Oe[e[t+3]]+"-"+Oe[e[t+4]]+Oe[e[t+5]]+"-"+Oe[e[t+6]]+Oe[e[t+7]]+"-"+Oe[e[t+8]]+Oe[e[t+9]]+"-"+Oe[e[t+10]]+Oe[e[t+11]]+Oe[e[t+12]]+Oe[e[t+13]]+Oe[e[t+14]]+Oe[e[t+15]]).toLowerCase();if(!Me(r))throw TypeError("Stringified UUID is invalid");return r};var ze=function(e,t,r){var n=(e=e||{}).random||(e.rng||Pe)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){r=r||0;for(var o=0;o<16;++o)t[r+o]=n[o];return t}return De(n)},Ie=window.wp.hooks;function He(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];const n=it(e,t),o=ze();return{clientId:o,name:e,isValid:!0,attributes:n,innerBlocks:r}}function Ve(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return e.map((e=>{const t=Array.isArray(e)?e:[e.name,e.attributes,e.innerBlocks],[r,n,o=[]]=t;return He(r,n,Ve(o))}))}function Re(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;const n=ze(),o=it(e.name,{...e.attributes,...t});return{...e,clientId:n,attributes:o,innerBlocks:r||e.innerBlocks.map((e=>Re(e)))}}function $e(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;const n=ze();return{...e,clientId:n,attributes:{...e.attributes,...t},innerBlocks:r||e.innerBlocks.map((e=>$e(e)))}}const Ue=(e,t,r)=>{if(!r.length)return!1;const n=r.length>1,o=r[0].name;if(!(Fe(e)||!n||e.isMultiBlock))return!1;if(!Fe(e)&&!r.every((e=>e.name===o)))return!1;if(!("block"===e.type))return!1;const a=r[0];return!("from"===t&&-1===e.blocks.indexOf(a.name)&&!Fe(e))&&(!(!n&&"from"===t&&qe(a.name)&&qe(e.blockName))&&(!!Ye(e,r)&&!(e.usingMobileTransformations&&Fe(e)&&!qe(a.name))))},Fe=e=>e&&"block"===e.type&&Array.isArray(e.blocks)&&e.blocks.includes("*"),qe=e=>e===ce();function Ge(e){if(!e.length)return[];const t=(e=>e.length?me().filter((t=>!!Ke(We("from",t.name),(t=>Ue(t,"from",e))))):[])(e),r=(e=>{if(!e.length)return[];const t=ge(e[0].name);return(t?We("to",t.name):[]).filter((t=>t&&Ue(t,"to",e))).map((e=>e.blocks)).flat().map((e=>"*"===e?e:ge(e)))})(e);return[...new Set([...t,...r])]}function Ke(e,t){const r=(0,Ie.createHooks)();for(let n=0;n<e.length;n++){const o=e[n];t(o)&&r.addFilter("transform","transform/"+n.toString(),(e=>e||o),o.priority)}return r.applyFilters("transform",null)}function We(e,t){if(void 0===t)return me().map((t=>{let{name:r}=t;return We(e,r)})).flat();const r=nt(t),{name:n,transforms:o}=r||{};if(!o||!Array.isArray(o[e]))return[];const a=o.supportedMobileTransforms&&Array.isArray(o.supportedMobileTransforms),i=a?o[e].filter((e=>"raw"===e.type||!(!e.blocks||!e.blocks.length)&&(!!Fe(e)||e.blocks.every((e=>o.supportedMobileTransforms.includes(e)))))):o[e];return i.map((e=>({...e,blockName:n,usingMobileTransformations:a})))}function Ye(e,t){if("function"!=typeof e.isMatch)return!0;const r=t[0],n=e.isMultiBlock?t.map((e=>e.attributes)):r.attributes,o=e.isMultiBlock?t:r;return e.isMatch(n,o)}function Qe(e,t){const r=Array.isArray(e)?e:[e],n=r.length>1,o=r[0],a=o.name,i=We("from",t),s=Ke(We("to",a),(e=>"block"===e.type&&-1!==e.blocks.indexOf(t)&&(!n||e.isMultiBlock)&&Ye(e,r)))||Ke(i,(e=>"block"===e.type&&(Fe(e)||-1!==e.blocks.indexOf(a))&&(!n||e.isMultiBlock)&&Ye(e,r)));if(!s)return null;let l;if(l=s.isMultiBlock?"__experimentalConvert"in s?s.__experimentalConvert(r):s.transform(r.map((e=>e.attributes)),r.map((e=>e.innerBlocks))):"__experimentalConvert"in s?s.__experimentalConvert(o):s.transform(o.attributes,o.innerBlocks),null===l||"object"!=typeof l)return null;if(l=Array.isArray(l)?l:[l],l.some((e=>!ge(e.name))))return null;if("*"===t)return l;if(!l.some((e=>e.name===t)))return null;return l.map(((t,r,n)=>(0,Ie.applyFilters)("blocks.switchToBlockType.transformedBlock",t,e,r,n)))}const Ze=(e,t)=>{var r;return He(e,t.attributes,(null!==(r=t.innerBlocks)&&void 0!==r?r:[]).map((e=>Ze(e.name,e))))};!function(e){e.forEach((function(e){O.indexOf(e)<0&&(e(L,E),O.push(e))}))}([function(e,t){var r={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},n={};for(var o in r)n[r[o]]=o;var a={};e.prototype.toName=function(t){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var o,i,s=n[this.toHex()];if(s)return s;if(null==t?void 0:t.closest){var l=this.toRgb(),c=1/0,u="black";if(!a.length)for(var d in r)a[d]=new e(r[d]).toRgb();for(var p in r){var f=(o=l,i=a[p],Math.pow(o.r-i.r,2)+Math.pow(o.g-i.g,2)+Math.pow(o.b-i.b,2));f<c&&(c=f,u=p)}return u}},t.string.push([function(t){var n=t.toLowerCase(),o="transparent"===n?"#0000":r[n];return o?new e(o).toRgb():null},"name"])},function(e){e.prototype.luminance=function(){return e=D(this.rgba),void 0===(t=2)&&(t=0),void 0===r&&(r=Math.pow(10,t)),Math.round(r*e)/r+0;var e,t,r},e.prototype.contrast=function(t){void 0===t&&(t="#FFF");var r,n,o,a,i,s,l,c=t instanceof e?t:new e(t);return a=this.rgba,i=c.toRgb(),r=(s=D(a))>(l=D(i))?(s+.05)/(l+.05):(l+.05)/(s+.05),void 0===(n=2)&&(n=0),void 0===o&&(o=Math.pow(10,n)),Math.floor(o*r)/o+0},e.prototype.isReadable=function(e,t){return void 0===e&&(e="#FFF"),void 0===t&&(t={}),this.contrast(e)>=(i=void 0===(a=(r=t).size)?"normal":a,"AAA"===(o=void 0===(n=r.level)?"AA":n)&&"normal"===i?7:"AA"===o&&"large"===i?3:4.5);var r,n,o,a,i}}]);const Xe=["#191e23","#f8f9f9"];function Je(e){var t;Je[e.name]||(Je[e.name]=He(e.name));const r=Je[e.name],n=ge(e.name);return Object.keys(null!==(t=null==n?void 0:n.attributes)&&void 0!==t?t:{}).every((t=>r.attributes[t]===e.attributes[t]))}function et(e){return e.name===he()&&Je(e)}function tt(e){return!!e&&("string"==typeof e||(0,z.isValidElement)(e)||"function"==typeof e||e instanceof z.Component)}function rt(e){if(tt(e=e||H))return{src:e};if("background"in e){const t=M(e.background),r=e=>t.contrast(e),n=Math.max(...Xe.map(r));return{...e,foreground:e.foreground?e.foreground:Xe.find((e=>r(e)===n)),shadowColor:t.alpha(.3).toRgbString()}}return e}function nt(e){return"string"==typeof e?ge(e):e}function ot(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"visual";const{__experimentalLabel:n,title:o}=e,a=n&&n(t,{context:r});return a?(0,I.__unstableStripHTML)(a):o}function at(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"vertical";const o=null==e?void 0:e.title,a=e?ot(e,t,"accessibility"):"",s=void 0!==r,l=a&&a!==o;return s&&"vertical"===n?l?(0,i.sprintf)((0,i.__)("%1$s Block. Row %2$d. %3$s"),o,r,a):(0,i.sprintf)((0,i.__)("%1$s Block. Row %2$d"),o,r):s&&"horizontal"===n?l?(0,i.sprintf)((0,i.__)("%1$s Block. Column %2$d. %3$s"),o,r,a):(0,i.sprintf)((0,i.__)("%1$s Block. Column %2$d"),o,r):l?(0,i.sprintf)((0,i.__)("%1$s Block. %2$s"),o,a):(0,i.sprintf)((0,i.__)("%s Block"),o)}function it(e,t){const r=ge(e);if(void 0===r)throw new Error(`Block type '${e}' is not registered.`);return Object.entries(r.attributes).reduce(((e,r)=>{let[n,o]=r;const a=t[n];return void 0!==a?e[n]=a:o.hasOwnProperty("default")&&(e[n]=o.default),-1!==["node","children"].indexOf(o.source)&&("string"==typeof e[n]?e[n]=[e[n]]:Array.isArray(e[n])||(e[n]=[])),e}),{})}function st(e,t){var r;const n=null===(r=ge(e))||void 0===r?void 0:r.attributes;if(!n)return[];const o=Object.keys(n);return t?o.filter((e=>{var r;return(null===(r=n[e])||void 0===r?void 0:r.__experimentalRole)===t})):o}function lt(e,t){return Object.fromEntries(Object.entries(e).filter((e=>{let[r]=e;return!t.includes(r)})))}const ct=[{slug:"text",title:(0,i.__)("Text")},{slug:"media",title:(0,i.__)("Media")},{slug:"design",title:(0,i.__)("Design")},{slug:"widgets",title:(0,i.__)("Widgets")},{slug:"theme",title:(0,i.__)("Theme")},{slug:"embed",title:(0,i.__)("Embeds")},{slug:"reusable",title:(0,i.__)("Reusable blocks")}];function ut(e){return e.reduce(((e,t)=>({...e,[t.name]:t})),{})}function dt(e){return e.reduce(((e,t)=>(e.some((e=>e.name===t.name))||e.push(t),e)),[])}function pt(e){return function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,r=arguments.length>1?arguments[1]:void 0;switch(r.type){case"REMOVE_BLOCK_TYPES":return-1!==r.names.indexOf(t)?null:t;case e:return r.name||null}return t}}const ft=pt("SET_DEFAULT_BLOCK_NAME"),ht=pt("SET_FREEFORM_FALLBACK_BLOCK_NAME"),gt=pt("SET_UNREGISTERED_FALLBACK_BLOCK_NAME"),mt=pt("SET_GROUPING_BLOCK_NAME");var bt=(0,o.combineReducers)({unprocessedBlockTypes:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;switch(t.type){case"ADD_UNPROCESSED_BLOCK_TYPE":return{...e,[t.blockType.name]:t.blockType};case"REMOVE_BLOCK_TYPES":return lt(e,t.names)}return e},blockTypes:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;switch(t.type){case"ADD_BLOCK_TYPES":return{...e,...ut(t.blockTypes)};case"REMOVE_BLOCK_TYPES":return lt(e,t.names)}return e},blockStyles:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;switch(t.type){case"ADD_BLOCK_TYPES":return{...e,...(0,a.mapValues)(ut(t.blockTypes),(t=>dt([...(0,a.get)(t,["styles"],[]).map((e=>({...e,source:"block"}))),...(0,a.get)(e,[t.name],[]).filter((e=>{let{source:t}=e;return"block"!==t}))])))};case"ADD_BLOCK_STYLES":return{...e,[t.blockName]:dt([...(0,a.get)(e,[t.blockName],[]),...t.styles])};case"REMOVE_BLOCK_STYLES":return{...e,[t.blockName]:(0,a.get)(e,[t.blockName],[]).filter((e=>-1===t.styleNames.indexOf(e.name)))}}return e},blockVariations:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;switch(t.type){case"ADD_BLOCK_TYPES":return{...e,...(0,a.mapValues)(ut(t.blockTypes),(t=>dt([...(0,a.get)(t,["variations"],[]).map((e=>({...e,source:"block"}))),...(0,a.get)(e,[t.name],[]).filter((e=>{let{source:t}=e;return"block"!==t}))])))};case"ADD_BLOCK_VARIATIONS":return{...e,[t.blockName]:dt([...(0,a.get)(e,[t.blockName],[]),...t.variations])};case"REMOVE_BLOCK_VARIATIONS":return{...e,[t.blockName]:(0,a.get)(e,[t.blockName],[]).filter((e=>-1===t.variationNames.indexOf(e.name)))}}return e},defaultBlockName:ft,freeformFallbackBlockName:ht,unregisteredFallbackBlockName:gt,groupingBlockName:mt,categories:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ct,t=arguments.length>1?arguments[1]:void 0;switch(t.type){case"SET_CATEGORIES":return t.categories||[];case"UPDATE_CATEGORY":if(!t.category||(0,a.isEmpty)(t.category))return e;if(e.find((e=>{let{slug:r}=e;return r===t.slug})))return e.map((e=>e.slug===t.slug?{...e,...t.category}:e))}return e},collections:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;switch(t.type){case"ADD_BLOCK_COLLECTION":return{...e,[t.namespace]:{title:t.title,icon:t.icon}};case"REMOVE_BLOCK_COLLECTION":return lt(e,t.namespace)}return e}}),_t={};function kt(e){return[e]}function yt(e,t,r){var n;if(e.length!==t.length)return!1;for(n=r;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function wt(e,t){var r,n=t||kt;function o(e){var t,n,o,a,i,s=r,l=!0;for(t=0;t<e.length;t++){if(n=e[t],!(i=n)||"object"!=typeof i){l=!1;break}s.has(n)?s=s.get(n):(o=new WeakMap,s.set(n,o),s=o)}return s.has(_t)||((a=function(){var e={clear:function(){e.head=null}};return e}()).isUniqueByDependants=l,s.set(_t,a)),s.get(_t)}function a(){r=new WeakMap}function i(){var t,r,a,i,s,l=arguments.length;for(i=new Array(l),a=0;a<l;a++)i[a]=arguments[a];for((t=o(s=n.apply(null,i))).isUniqueByDependants||(t.lastDependants&&!yt(s,t.lastDependants,0)&&t.clear(),t.lastDependants=s),r=t.head;r;){if(yt(r.args,i,1))return r!==t.head&&(r.prev.next=r.next,r.next&&(r.next.prev=r.prev),r.next=t.head,r.prev=null,t.head.prev=r,t.head=r),r.val;r=r.next}return r={val:e.apply(null,i)},i[0]=null,r.args=i,t.head&&(t.head.prev=r,r.next=t.head),t.head=r,r.val}return i.getDependants=n,i.clear=a,a(),i}var vt=r(4793),Tt=r.n(vt),Ct=window.wp.compose;const xt=(e,t)=>"string"==typeof t?St(e,t):t;function Et(e){return e.unprocessedBlockTypes}const At=wt((e=>Object.values(e.blockTypes)),(e=>[e.blockTypes]));function St(e,t){return e.blockTypes[t]}function Bt(e,t){return e.blockStyles[t]}const Nt=wt(((e,t,r)=>{const n=e.blockVariations[t];return n&&r?n.filter((e=>(e.scope||["block","inserter"]).includes(r))):n}),((e,t)=>[e.blockVariations[t]]));function Pt(e,t,r,n){const o=Nt(e,t,n);return null==o?void 0:o.find((n=>{var o;if(Array.isArray(n.isActive)){const o=St(e,t),a=Object.keys((null==o?void 0:o.attributes)||{}),i=n.isActive.filter((e=>a.includes(e)));return 0!==i.length&&i.every((e=>r[e]===n.attributes[e]))}return null===(o=n.isActive)||void 0===o?void 0:o.call(n,r,n.attributes)}))}function Lt(e,t,r){const n=Nt(e,t,r);return[...n].reverse().find((e=>{let{isDefault:t}=e;return!!t}))||n[0]}function Mt(e){return e.categories}function Ot(e){return e.collections}function jt(e){return e.defaultBlockName}function Dt(e){return e.freeformFallbackBlockName}function zt(e){return e.unregisteredFallbackBlockName}function It(e){return e.groupingBlockName}const Ht=wt(((e,t)=>At(e).filter((e=>{var r;return null===(r=e.parent)||void 0===r?void 0:r.includes(t)})).map((e=>{let{name:t}=e;return t}))),(e=>[e.blockTypes])),Vt=(e,t,r,n)=>{const o=xt(e,t);return null!=o&&o.supports?(0,a.get)(o.supports,r,n):n};function Rt(e,t,r,n){return!!Vt(e,t,r,n)}function $t(e,t,r){var n;const o=xt(e,t),a=(0,Ct.pipe)([e=>Tt()(null!=e?e:""),e=>e.toLowerCase(),e=>e.trim()]),i=a(r),s=(0,Ct.pipe)([a,e=>e.includes(i)]);return s(o.title)||(null===(n=o.keywords)||void 0===n?void 0:n.some(s))||s(o.category)||"string"==typeof o.description&&s(o.description)}const Ut=(e,t)=>Ht(e,t).length>0,Ft=(e,t)=>Ht(e,t).some((t=>Rt(e,t,"inserter",!0))),qt=wt(((e,t)=>{const r=St(e,t);return!!r&&Object.entries(r.attributes).some((e=>{let[,{__experimentalRole:t}]=e;return"content"===t}))}),((e,t)=>{var r;return[null===(r=e.blockTypes[t])||void 0===r?void 0:r.attributes]}));
/*!
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*/
function Gt(e){return"[object Object]"===Object.prototype.toString.call(e)}var Kt=window.wp.deprecated,Wt=r.n(Kt);const{error:Yt,warn:Qt}=window.console,Zt={common:"text",formatting:"text",layout:"design"};function Xt(e){return"function"==typeof e}const Jt=(e,t)=>{let{select:r}=t;const{name:n}=e,o=(0,Ie.applyFilters)("blocks.registerBlockType",{...e},n,null);if(o.description&&"string"!=typeof o.description&&Wt()("Declaring non-string block descriptions",{since:"6.2"}),o.deprecated&&(o.deprecated=o.deprecated.map((t=>Object.fromEntries(Object.entries((0,Ie.applyFilters)("blocks.registerBlockType",{...lt(e,V),...t},n,t)).filter((e=>{let[t]=e;return V.includes(t)})))))),function(e){var t,r;return!1!==Gt(e)&&(void 0===(t=e.constructor)||!1!==Gt(r=t.prototype)&&!1!==r.hasOwnProperty("isPrototypeOf"))}(o))if(Xt(o.save))if(!("edit"in o)||Xt(o.edit))if(Zt.hasOwnProperty(o.category)&&(o.category=Zt[o.category]),"category"in o&&!r.getCategories().some((e=>{let{slug:t}=e;return t===o.category}))&&(Qt('The block "'+n+'" is registered with an invalid category "'+o.category+'".'),delete o.category),"title"in o&&""!==o.title)if("string"==typeof o.title){if(o.icon=rt(o.icon),tt(o.icon.src))return o;Yt("The icon passed is invalid. The icon should be a string, an element, a function, or an object following the specifications documented in https://developer.wordpress.org/block-editor/developers/block-api/block-registration/#icon-optional")}else Yt("Block titles must be strings.");else Yt('The block "'+n+'" must have a title.');else Yt('The "edit" property must be a valid function.');else Yt('The "save" property must be a valid function.');else Yt("Block settings must be a valid object.")};function er(e){return{type:"ADD_BLOCK_TYPES",blockTypes:Array.isArray(e)?e:[e]}}const tr=e=>t=>{let{dispatch:r,select:n}=t;r({type:"ADD_UNPROCESSED_BLOCK_TYPE",blockType:e});const o=Jt(e,{select:n});o&&r.addBlockTypes(o)},rr=()=>e=>{let{dispatch:t,select:r}=e;const n=r.__experimentalGetUnprocessedBlockTypes(),o=Object.keys(n).reduce(((e,t)=>{const o=Jt(n[t],{select:r});return o&&e.push(o),e}),[]);o.length&&t.addBlockTypes(o)};function nr(e){return{type:"REMOVE_BLOCK_TYPES",names:Array.isArray(e)?e:[e]}}function or(e,t){return{type:"ADD_BLOCK_STYLES",styles:Array.isArray(t)?t:[t],blockName:e}}function ar(e,t){return{type:"REMOVE_BLOCK_STYLES",styleNames:Array.isArray(t)?t:[t],blockName:e}}function ir(e,t){return{type:"ADD_BLOCK_VARIATIONS",variations:Array.isArray(t)?t:[t],blockName:e}}function sr(e,t){return{type:"REMOVE_BLOCK_VARIATIONS",variationNames:Array.isArray(t)?t:[t],blockName:e}}function lr(e){return{type:"SET_DEFAULT_BLOCK_NAME",name:e}}function cr(e){return{type:"SET_FREEFORM_FALLBACK_BLOCK_NAME",name:e}}function ur(e){return{type:"SET_UNREGISTERED_FALLBACK_BLOCK_NAME",name:e}}function dr(e){return{type:"SET_GROUPING_BLOCK_NAME",name:e}}function pr(e){return{type:"SET_CATEGORIES",categories:e}}function fr(e,t){return{type:"UPDATE_CATEGORY",slug:e,category:t}}function hr(e,t,r){return{type:"ADD_BLOCK_COLLECTION",namespace:e,title:t,icon:r}}function gr(e){return{type:"REMOVE_BLOCK_COLLECTION",namespace:e}}const mr=(0,o.createReduxStore)("core/blocks",{reducer:bt,selectors:e,actions:t});(0,o.register)(mr);var br=window.wp.blockSerializationDefaultParser,_r=window.wp.autop,kr=window.wp.isShallowEqual,yr=r.n(kr);function wr(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{isCommentDelimited:r=!0}=t,{blockName:n,attrs:o={},innerBlocks:a=[],innerContent:i=[]}=e;let s=0;const l=i.map((e=>null!==e?e:wr(a[s++],t))).join("\n").replace(/\n+/g,"\n").trim();return r?Lr(n,o,l):l}function vr(e){const t="wp-block-"+e.replace(/\//,"-").replace(/^core-/,"");return(0,Ie.applyFilters)("blocks.getBlockDefaultClassName",t,e)}function Tr(e){const t="editor-block-list-item-"+e.replace(/\//,"-").replace(/^core-/,"");return(0,Ie.applyFilters)("blocks.getBlockMenuDefaultClassName",t,e)}const Cr={},xr={};function Er(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{blockType:t,attributes:r}=Cr;return(0,Ie.applyFilters)("blocks.getSaveContent.extraProps",{...e},t,r)}function Ar(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{innerBlocks:t}=xr,r=Or(t,{isInnerBlocks:!0}),n=(0,z.createElement)(z.RawHTML,null,r);return{...e,children:n}}function Sr(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];const n=nt(e);let{save:o}=n;if(o.prototype instanceof z.Component){const e=new o({attributes:t});o=e.render.bind(e)}Cr.blockType=n,Cr.attributes=t,xr.innerBlocks=r;let a=o({attributes:t,innerBlocks:r});if(null!==a&&"object"==typeof a&&(0,Ie.hasFilter)("blocks.getSaveContent.extraProps")&&!(n.apiVersion>1)){const e=(0,Ie.applyFilters)("blocks.getSaveContent.extraProps",{...a.props},n,t);yr()(e,a.props)||(a=(0,z.cloneElement)(a,e))}return(0,Ie.applyFilters)("blocks.getSaveElement",a,n,t)}function Br(e,t,r){const n=nt(e);return(0,z.renderToString)(Sr(n,t,r))}function Nr(e,t){var r;return Object.entries(null!==(r=e.attributes)&&void 0!==r?r:{}).reduce(((e,r)=>{let[n,o]=r;const a=t[n];return void 0===a||void 0!==o.source||"default"in o&&o.default===a||(e[n]=a),e}),{})}function Pr(e){let t=e.originalContent;if(e.isValid||e.innerBlocks.length)try{t=Br(e.name,e.attributes,e.innerBlocks)}catch(e){}return t}function Lr(e,t,r){const n=t&&Object.entries(t).length?function(e){return JSON.stringify(e).replace(/--/g,"\\u002d\\u002d").replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\\"/g,"\\u0022")}(t)+" ":"",o=null!=e&&e.startsWith("core/")?e.slice(5):e;return r?`\x3c!-- wp:${o} ${n}--\x3e\n`+r+`\n\x3c!-- /wp:${o} --\x3e`:`\x3c!-- wp:${o} ${n}/--\x3e`}function Mr(e){1===e.length&&et(e[0])&&(e=[]);let t=Or(e);return 1===e.length&&e[0].name===le()&&(t=(0,_r.removep)(t)),t}function Or(e,t){return(Array.isArray(e)?e:[e]).map((e=>function(e){let{isInnerBlocks:t=!1}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e.isValid&&e.__unstableBlockSource)return wr(e.__unstableBlockSource);const r=e.name,n=Pr(e);if(r===de()||!t&&r===le())return n;const o=ge(r);if(!o)return n;const a=Nr(o,e.attributes);return Lr(r,a,n)}(e,t))).join("\n\n")}var jr=/^#[xX]([A-Fa-f0-9]+)$/,Dr=/^#([0-9]+)$/,zr=/^([A-Za-z0-9]+)$/,Ir=(function(){function e(e){this.named=e}e.prototype.parse=function(e){if(e){var t=e.match(jr);return t?String.fromCharCode(parseInt(t[1],16)):(t=e.match(Dr))?String.fromCharCode(parseInt(t[1],10)):(t=e.match(zr))?this.named[t[1]]:void 0}}}(),/[\t\n\f ]/),Hr=/[A-Za-z]/,Vr=/\r\n?/g;function Rr(e){return Ir.test(e)}function $r(e){return Hr.test(e)}var Ur=function(){function e(e,t,r){void 0===r&&(r="precompile"),this.delegate=e,this.entityParser=t,this.mode=r,this.state="beforeData",this.line=-1,this.column=-1,this.input="",this.index=-1,this.tagNameBuffer="",this.states={beforeData:function(){var e=this.peek();if("<"!==e||this.isIgnoredEndTag()){if("precompile"===this.mode&&"\n"===e){var t=this.tagNameBuffer.toLowerCase();"pre"!==t&&"textarea"!==t||this.consume()}this.transitionTo("data"),this.delegate.beginData()}else this.transitionTo("tagOpen"),this.markTagStart(),this.consume()},data:function(){var e=this.peek(),t=this.tagNameBuffer;"<"!==e||this.isIgnoredEndTag()?"&"===e&&"script"!==t&&"style"!==t?(this.consume(),this.delegate.appendToData(this.consumeCharRef()||"&")):(this.consume(),this.delegate.appendToData(e)):(this.delegate.finishData(),this.transitionTo("tagOpen"),this.markTagStart(),this.consume())},tagOpen:function(){var e=this.consume();"!"===e?this.transitionTo("markupDeclarationOpen"):"/"===e?this.transitionTo("endTagOpen"):("@"===e||":"===e||$r(e))&&(this.transitionTo("tagName"),this.tagNameBuffer="",this.delegate.beginStartTag(),this.appendToTagName(e))},markupDeclarationOpen:function(){var e=this.consume();"-"===e&&"-"===this.peek()?(this.consume(),this.transitionTo("commentStart"),this.delegate.beginComment()):"DOCTYPE"===e.toUpperCase()+this.input.substring(this.index,this.index+6).toUpperCase()&&(this.consume(),this.consume(),this.consume(),this.consume(),this.consume(),this.consume(),this.transitionTo("doctype"),this.delegate.beginDoctype&&this.delegate.beginDoctype())},doctype:function(){Rr(this.consume())&&this.transitionTo("beforeDoctypeName")},beforeDoctypeName:function(){var e=this.consume();Rr(e)||(this.transitionTo("doctypeName"),this.delegate.appendToDoctypeName&&this.delegate.appendToDoctypeName(e.toLowerCase()))},doctypeName:function(){var e=this.consume();Rr(e)?this.transitionTo("afterDoctypeName"):">"===e?(this.delegate.endDoctype&&this.delegate.endDoctype(),this.transitionTo("beforeData")):this.delegate.appendToDoctypeName&&this.delegate.appendToDoctypeName(e.toLowerCase())},afterDoctypeName:function(){var e=this.consume();if(!Rr(e))if(">"===e)this.delegate.endDoctype&&this.delegate.endDoctype(),this.transitionTo("beforeData");else{var t=e.toUpperCase()+this.input.substring(this.index,this.index+5).toUpperCase(),r="PUBLIC"===t.toUpperCase(),n="SYSTEM"===t.toUpperCase();(r||n)&&(this.consume(),this.consume(),this.consume(),this.consume(),this.consume(),this.consume()),r?this.transitionTo("afterDoctypePublicKeyword"):n&&this.transitionTo("afterDoctypeSystemKeyword")}},afterDoctypePublicKeyword:function(){var e=this.peek();Rr(e)?(this.transitionTo("beforeDoctypePublicIdentifier"),this.consume()):'"'===e?(this.transitionTo("doctypePublicIdentifierDoubleQuoted"),this.consume()):"'"===e?(this.transitionTo("doctypePublicIdentifierSingleQuoted"),this.consume()):">"===e&&(this.consume(),this.delegate.endDoctype&&this.delegate.endDoctype(),this.transitionTo("beforeData"))},doctypePublicIdentifierDoubleQuoted:function(){var e=this.consume();'"'===e?this.transitionTo("afterDoctypePublicIdentifier"):">"===e?(this.delegate.endDoctype&&this.delegate.endDoctype(),this.transitionTo("beforeData")):this.delegate.appendToDoctypePublicIdentifier&&this.delegate.appendToDoctypePublicIdentifier(e)},doctypePublicIdentifierSingleQuoted:function(){var e=this.consume();"'"===e?this.transitionTo("afterDoctypePublicIdentifier"):">"===e?(this.delegate.endDoctype&&this.delegate.endDoctype(),this.transitionTo("beforeData")):this.delegate.appendToDoctypePublicIdentifier&&this.delegate.appendToDoctypePublicIdentifier(e)},afterDoctypePublicIdentifier:function(){var e=this.consume();Rr(e)?this.transitionTo("betweenDoctypePublicAndSystemIdentifiers"):">"===e?(this.delegate.endDoctype&&this.delegate.endDoctype(),this.transitionTo("beforeData")):'"'===e?this.transitionTo("doctypeSystemIdentifierDoubleQuoted"):"'"===e&&this.transitionTo("doctypeSystemIdentifierSingleQuoted")},betweenDoctypePublicAndSystemIdentifiers:function(){var e=this.consume();Rr(e)||(">"===e?(this.delegate.endDoctype&&this.delegate.endDoctype(),this.transitionTo("beforeData")):'"'===e?this.transitionTo("doctypeSystemIdentifierDoubleQuoted"):"'"===e&&this.transitionTo("doctypeSystemIdentifierSingleQuoted"))},doctypeSystemIdentifierDoubleQuoted:function(){var e=this.consume();'"'===e?this.transitionTo("afterDoctypeSystemIdentifier"):">"===e?(this.delegate.endDoctype&&this.delegate.endDoctype(),this.transitionTo("beforeData")):this.delegate.appendToDoctypeSystemIdentifier&&this.delegate.appendToDoctypeSystemIdentifier(e)},doctypeSystemIdentifierSingleQuoted:function(){var e=this.consume();"'"===e?this.transitionTo("afterDoctypeSystemIdentifier"):">"===e?(this.delegate.endDoctype&&this.delegate.endDoctype(),this.transitionTo("beforeData")):this.delegate.appendToDoctypeSystemIdentifier&&this.delegate.appendToDoctypeSystemIdentifier(e)},afterDoctypeSystemIdentifier:function(){var e=this.consume();Rr(e)||">"===e&&(this.delegate.endDoctype&&this.delegate.endDoctype(),this.transitionTo("beforeData"))},commentStart:function(){var e=this.consume();"-"===e?this.transitionTo("commentStartDash"):">"===e?(this.delegate.finishComment(),this.transitionTo("beforeData")):(this.delegate.appendToCommentData(e),this.transitionTo("comment"))},commentStartDash:function(){var e=this.consume();"-"===e?this.transitionTo("commentEnd"):">"===e?(this.delegate.finishComment(),this.transitionTo("beforeData")):(this.delegate.appendToCommentData("-"),this.transitionTo("comment"))},comment:function(){var e=this.consume();"-"===e?this.transitionTo("commentEndDash"):this.delegate.appendToCommentData(e)},commentEndDash:function(){var e=this.consume();"-"===e?this.transitionTo("commentEnd"):(this.delegate.appendToCommentData("-"+e),this.transitionTo("comment"))},commentEnd:function(){var e=this.consume();">"===e?(this.delegate.finishComment(),this.transitionTo("beforeData")):(this.delegate.appendToCommentData("--"+e),this.transitionTo("comment"))},tagName:function(){var e=this.consume();Rr(e)?this.transitionTo("beforeAttributeName"):"/"===e?this.transitionTo("selfClosingStartTag"):">"===e?(this.delegate.finishTag(),this.transitionTo("beforeData")):this.appendToTagName(e)},endTagName:function(){var e=this.consume();Rr(e)?(this.transitionTo("beforeAttributeName"),this.tagNameBuffer=""):"/"===e?(this.transitionTo("selfClosingStartTag"),this.tagNameBuffer=""):">"===e?(this.delegate.finishTag(),this.transitionTo("beforeData"),this.tagNameBuffer=""):this.appendToTagName(e)},beforeAttributeName:function(){var e=this.peek();Rr(e)?this.consume():"/"===e?(this.transitionTo("selfClosingStartTag"),this.consume()):">"===e?(this.consume(),this.delegate.finishTag(),this.transitionTo("beforeData")):"="===e?(this.delegate.reportSyntaxError("attribute name cannot start with equals sign"),this.transitionTo("attributeName"),this.delegate.beginAttribute(),this.consume(),this.delegate.appendToAttributeName(e)):(this.transitionTo("attributeName"),this.delegate.beginAttribute())},attributeName:function(){var e=this.peek();Rr(e)?(this.transitionTo("afterAttributeName"),this.consume()):"/"===e?(this.delegate.beginAttributeValue(!1),this.delegate.finishAttributeValue(),this.consume(),this.transitionTo("selfClosingStartTag")):"="===e?(this.transitionTo("beforeAttributeValue"),this.consume()):">"===e?(this.delegate.beginAttributeValue(!1),this.delegate.finishAttributeValue(),this.consume(),this.delegate.finishTag(),this.transitionTo("beforeData")):'"'===e||"'"===e||"<"===e?(this.delegate.reportSyntaxError(e+" is not a valid character within attribute names"),this.consume(),this.delegate.appendToAttributeName(e)):(this.consume(),this.delegate.appendToAttributeName(e))},afterAttributeName:function(){var e=this.peek();Rr(e)?this.consume():"/"===e?(this.delegate.beginAttributeValue(!1),this.delegate.finishAttributeValue(),this.consume(),this.transitionTo("selfClosingStartTag")):"="===e?(this.consume(),this.transitionTo("beforeAttributeValue")):">"===e?(this.delegate.beginAttributeValue(!1),this.delegate.finishAttributeValue(),this.consume(),this.delegate.finishTag(),this.transitionTo("beforeData")):(this.delegate.beginAttributeValue(!1),this.delegate.finishAttributeValue(),this.transitionTo("attributeName"),this.delegate.beginAttribute(),this.consume(),this.delegate.appendToAttributeName(e))},beforeAttributeValue:function(){var e=this.peek();Rr(e)?this.consume():'"'===e?(this.transitionTo("attributeValueDoubleQuoted"),this.delegate.beginAttributeValue(!0),this.consume()):"'"===e?(this.transitionTo("attributeValueSingleQuoted"),this.delegate.beginAttributeValue(!0),this.consume()):">"===e?(this.delegate.beginAttributeValue(!1),this.delegate.finishAttributeValue(),this.consume(),this.delegate.finishTag(),this.transitionTo("beforeData")):(this.transitionTo("attributeValueUnquoted"),this.delegate.beginAttributeValue(!1),this.consume(),this.delegate.appendToAttributeValue(e))},attributeValueDoubleQuoted:function(){var e=this.consume();'"'===e?(this.delegate.finishAttributeValue(),this.transitionTo("afterAttributeValueQuoted")):"&"===e?this.delegate.appendToAttributeValue(this.consumeCharRef()||"&"):this.delegate.appendToAttributeValue(e)},attributeValueSingleQuoted:function(){var e=this.consume();"'"===e?(this.delegate.finishAttributeValue(),this.transitionTo("afterAttributeValueQuoted")):"&"===e?this.delegate.appendToAttributeValue(this.consumeCharRef()||"&"):this.delegate.appendToAttributeValue(e)},attributeValueUnquoted:function(){var e=this.peek();Rr(e)?(this.delegate.finishAttributeValue(),this.consume(),this.transitionTo("beforeAttributeName")):"/"===e?(this.delegate.finishAttributeValue(),this.consume(),this.transitionTo("selfClosingStartTag")):"&"===e?(this.consume(),this.delegate.appendToAttributeValue(this.consumeCharRef()||"&")):">"===e?(this.delegate.finishAttributeValue(),this.consume(),this.delegate.finishTag(),this.transitionTo("beforeData")):(this.consume(),this.delegate.appendToAttributeValue(e))},afterAttributeValueQuoted:function(){var e=this.peek();Rr(e)?(this.consume(),this.transitionTo("beforeAttributeName")):"/"===e?(this.consume(),this.transitionTo("selfClosingStartTag")):">"===e?(this.consume(),this.delegate.finishTag(),this.transitionTo("beforeData")):this.transitionTo("beforeAttributeName")},selfClosingStartTag:function(){">"===this.peek()?(this.consume(),this.delegate.markTagAsSelfClosing(),this.delegate.finishTag(),this.transitionTo("beforeData")):this.transitionTo("beforeAttributeName")},endTagOpen:function(){var e=this.consume();("@"===e||":"===e||$r(e))&&(this.transitionTo("endTagName"),this.tagNameBuffer="",this.delegate.beginEndTag(),this.appendToTagName(e))}},this.reset()}return e.prototype.reset=function(){this.transitionTo("beforeData"),this.input="",this.tagNameBuffer="",this.index=0,this.line=1,this.column=0,this.delegate.reset()},e.prototype.transitionTo=function(e){this.state=e},e.prototype.tokenize=function(e){this.reset(),this.tokenizePart(e),this.tokenizeEOF()},e.prototype.tokenizePart=function(e){for(this.input+=function(e){return e.replace(Vr,"\n")}(e);this.index<this.input.length;){var t=this.states[this.state];if(void 0===t)throw new Error("unhandled state "+this.state);t.call(this)}},e.prototype.tokenizeEOF=function(){this.flushData()},e.prototype.flushData=function(){"data"===this.state&&(this.delegate.finishData(),this.transitionTo("beforeData"))},e.prototype.peek=function(){return this.input.charAt(this.index)},e.prototype.consume=function(){var e=this.peek();return this.index++,"\n"===e?(this.line++,this.column=0):this.column++,e},e.prototype.consumeCharRef=function(){var e=this.input.indexOf(";",this.index);if(-1!==e){var t=this.input.slice(this.index,e),r=this.entityParser.parse(t);if(r){for(var n=t.length;n;)this.consume(),n--;return this.consume(),r}}},e.prototype.markTagStart=function(){this.delegate.tagOpen()},e.prototype.appendToTagName=function(e){this.tagNameBuffer+=e,this.delegate.appendToTagName(e)},e.prototype.isIgnoredEndTag=function(){var e=this.tagNameBuffer;return"title"===e&&"</title>"!==this.input.substring(this.index,this.index+8)||"style"===e&&"</style>"!==this.input.substring(this.index,this.index+8)||"script"===e&&"<\/script>"!==this.input.substring(this.index,this.index+9)},e}(),Fr=function(){function e(e,t){void 0===t&&(t={}),this.options=t,this.token=null,this.startLine=1,this.startColumn=0,this.tokens=[],this.tokenizer=new Ur(this,e,t.mode),this._currentAttribute=void 0}return e.prototype.tokenize=function(e){return this.tokens=[],this.tokenizer.tokenize(e),this.tokens},e.prototype.tokenizePart=function(e){return this.tokens=[],this.tokenizer.tokenizePart(e),this.tokens},e.prototype.tokenizeEOF=function(){return this.tokens=[],this.tokenizer.tokenizeEOF(),this.tokens[0]},e.prototype.reset=function(){this.token=null,this.startLine=1,this.startColumn=0},e.prototype.current=function(){var e=this.token;if(null===e)throw new Error("token was unexpectedly null");if(0===arguments.length)return e;for(var t=0;t<arguments.length;t++)if(e.type===arguments[t])return e;throw new Error("token type was unexpectedly "+e.type)},e.prototype.push=function(e){this.token=e,this.tokens.push(e)},e.prototype.currentAttribute=function(){return this._currentAttribute},e.prototype.addLocInfo=function(){this.options.loc&&(this.current().loc={start:{line:this.startLine,column:this.startColumn},end:{line:this.tokenizer.line,column:this.tokenizer.column}}),this.startLine=this.tokenizer.line,this.startColumn=this.tokenizer.column},e.prototype.beginDoctype=function(){this.push({type:"Doctype",name:""})},e.prototype.appendToDoctypeName=function(e){this.current("Doctype").name+=e},e.prototype.appendToDoctypePublicIdentifier=function(e){var t=this.current("Doctype");void 0===t.publicIdentifier?t.publicIdentifier=e:t.publicIdentifier+=e},e.prototype.appendToDoctypeSystemIdentifier=function(e){var t=this.current("Doctype");void 0===t.systemIdentifier?t.systemIdentifier=e:t.systemIdentifier+=e},e.prototype.endDoctype=function(){this.addLocInfo()},e.prototype.beginData=function(){this.push({type:"Chars",chars:""})},e.prototype.appendToData=function(e){this.current("Chars").chars+=e},e.prototype.finishData=function(){this.addLocInfo()},e.prototype.beginComment=function(){this.push({type:"Comment",chars:""})},e.prototype.appendToCommentData=function(e){this.current("Comment").chars+=e},e.prototype.finishComment=function(){this.addLocInfo()},e.prototype.tagOpen=function(){},e.prototype.beginStartTag=function(){this.push({type:"StartTag",tagName:"",attributes:[],selfClosing:!1})},e.prototype.beginEndTag=function(){this.push({type:"EndTag",tagName:""})},e.prototype.finishTag=function(){this.addLocInfo()},e.prototype.markTagAsSelfClosing=function(){this.current("StartTag").selfClosing=!0},e.prototype.appendToTagName=function(e){this.current("StartTag","EndTag").tagName+=e},e.prototype.beginAttribute=function(){this._currentAttribute=["","",!1]},e.prototype.appendToAttributeName=function(e){this.currentAttribute()[0]+=e},e.prototype.beginAttributeValue=function(e){this.currentAttribute()[2]=e},e.prototype.appendToAttributeValue=function(e){this.currentAttribute()[1]+=e},e.prototype.finishAttributeValue=function(){this.current("StartTag").attributes.push(this._currentAttribute)},e.prototype.reportSyntaxError=function(e){this.current().syntaxError=e},e}();var qr=r(5619),Gr=r.n(qr),Kr=window.wp.htmlEntities;function Wr(){function e(e){return function(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return e("Block validation: "+t,...n)}}return{error:e(console.error),warning:e(console.warn),getItems(){return[]}}}function Yr(){const e=[],t=Wr();return{error(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];e.push({log:t.error,args:n})},warning(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];e.push({log:t.warning,args:n})},getItems(){return e}}}const Qr=/[\t\n\r\v\f ]+/g,Zr=/^[\t\n\r\v\f ]*$/,Xr=/^url\s*\(['"\s]*(.*?)['"\s]*\)$/,Jr=["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"],en=[...Jr,"autocapitalize","autocomplete","charset","contenteditable","crossorigin","decoding","dir","draggable","enctype","formenctype","formmethod","http-equiv","inputmode","kind","method","preload","scope","shape","spellcheck","translate","type","wrap"],tn=[e=>e,function(e){return sn(e).join(" ")}],rn=/^[\da-z]+$/i,nn=/^#\d+$/,on=/^#x[\da-f]+$/i;class an{parse(e){if(t=e,rn.test(t)||nn.test(t)||on.test(t))return(0,Kr.decodeEntities)("&"+e+";");var t}}function sn(e){return e.trim().split(Qr)}function ln(e){return e.attributes.filter((e=>{const[t,r]=e;return r||0===t.indexOf("data-")||en.includes(t)}))}function cn(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Wr(),n=e.chars,o=t.chars;for(let e=0;e<tn.length;e++){const t=tn[e];if(n=t(n),o=t(o),n===o)return!0}return r.warning("Expected text `%s`, saw `%s`.",t.chars,e.chars),!1}function un(e){return 0===parseFloat(e)?"0":0===e.indexOf(".")?"0"+e:e}function dn(e){return sn(e).map(un).join(" ").replace(Xr,"url($1)")}function pn(e){const t=e.replace(/;?\s*$/,"").split(";").map((e=>{const[t,...r]=e.split(":"),n=r.join(":");return[t.trim(),dn(n.trim())]}));return Object.fromEntries(t)}const fn={class:(e,t)=>{const[r,n]=[e,t].map(sn),o=r.filter((e=>!n.includes(e))),a=n.filter((e=>!r.includes(e)));return 0===o.length&&0===a.length},style:(e,t)=>Gr()(...[e,t].map(pn)),...Object.fromEntries(Jr.map((e=>[e,()=>!0])))};function hn(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Wr();if(e.length!==t.length)return r.warning("Expected attributes %o, instead saw %o.",t,e),!1;const n={};for(let e=0;e<t.length;e++)n[t[e][0].toLowerCase()]=t[e][1];for(let t=0;t<e.length;t++){const[o,a]=e[t],i=o.toLowerCase();if(!n.hasOwnProperty(i))return r.warning("Encountered unexpected attribute `%s`.",o),!1;const s=n[i],l=fn[i];if(l){if(!l(a,s))return r.warning("Expected attribute `%s` of value `%s`, saw `%s`.",o,s,a),!1}else if(a!==s)return r.warning("Expected attribute `%s` of value `%s`, saw `%s`.",o,s,a),!1}return!0}const gn={StartTag:function(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Wr();return e.tagName!==t.tagName&&e.tagName.toLowerCase()!==t.tagName.toLowerCase()?(r.warning("Expected tag name `%s`, instead saw `%s`.",t.tagName,e.tagName),!1):hn(...[e,t].map(ln),r)},Chars:cn,Comment:cn};function mn(e){let t;for(;t=e.shift();){if("Chars"!==t.type)return t;if(!Zr.test(t.chars))return t}}function bn(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Wr();try{return new Fr(new an).tokenize(e)}catch(r){t.warning("Malformed HTML detected: %s",e)}return null}function _n(e,t){return!!e.selfClosing&&!(!t||t.tagName!==e.tagName||"EndTag"!==t.type)}function kn(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Wr();if(e===t)return!0;const[n,o]=[e,t].map((e=>bn(e,r)));if(!n||!o)return!1;let a,i;for(;a=mn(n);){if(i=mn(o),!i)return r.warning("Expected end of content, instead saw %o.",a),!1;if(a.type!==i.type)return r.warning("Expected token of type `%s` (%o), instead saw `%s` (%o).",i.type,i,a.type,a),!1;const e=gn[a.type];if(e&&!e(a,i,r))return!1;_n(a,o[0])?mn(o):_n(i,n[0])&&mn(n)}return!(i=mn(o))||(r.warning("Expected %o, instead saw end of content.",i),!1)}function yn(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.name;const r=e.name===le()||e.name===de();if(r)return[!0,[]];const n=Yr(),o=nt(t);let a;try{a=Br(o,e.attributes)}catch(e){return n.error("Block validation failed because an error occurred while generating block content:\n\n%s",e.toString()),[!1,n.getItems()]}const i=kn(e.originalContent,a,n);return i||n.error("Block validation failed for `%s` (%o).\n\nContent generated by `save` function:\n\n%s\n\nContent retrieved from post body:\n\n%s",o.name,o,a,e.originalContent),[i,n.getItems()]}function wn(e,t,r){Wt()("isValidBlockContent introduces opportunity for data loss",{since:"12.6",plugin:"Gutenberg",alternative:"validateBlock"});const n=nt(e),o={name:n.name,attributes:t,innerBlocks:[],originalContent:r},[a]=yn(o,n);return a}function vn(e,t){const r={...t};if("core/cover-image"===e&&(e="core/cover"),"core/text"!==e&&"core/cover-text"!==e||(e="core/paragraph"),e&&0===e.indexOf("core/social-link-")&&(r.service=e.substring(17),e="core/social-link"),e&&0===e.indexOf("core-embed/")){const t=e.substring(11),n={speaker:"speaker-deck",polldaddy:"crowdsignal"};r.providerNameSlug=t in n?n[t]:t,["amazon-kindle","wordpress"].includes(t)||(r.responsive=!0),e="core/embed"}if("core/post-comment-author"===e&&(e="core/comment-author-name"),"core/post-comment-content"===e&&(e="core/comment-content"),"core/post-comment-date"===e&&(e="core/comment-date"),"core/comments-query-loop"===e){e="core/comments";const{className:t=""}=r;t.includes("wp-block-comments-query-loop")||(r.className=["wp-block-comments-query-loop",t].join(" "))}return"core/post-comments"===e&&(e="core/comments",r.legacy=!0),[e,r]}function Tn(e,t){for(var r,n=t.split(".");r=n.shift();){if(!(r in e))return;e=e[r]}return e}var Cn,xn=function(){return Cn||(Cn=document.implementation.createHTMLDocument("")),Cn};function En(e,t){if(t){if("string"==typeof e){var r=xn();r.body.innerHTML=e,e=r.body}if("function"==typeof t)return t(e);if(Object===t.constructor)return Object.keys(t).reduce((function(r,n){var o=t[n];return r[n]=En(e,o),r}),{})}}function An(e,t){var r,n;return 1===arguments.length?(r=e,n=void 0):(r=t,n=e),function(e){var t=e;if(n&&(t=e.querySelector(n)),t)return Tn(t,r)}}var Sn=r(9756);function Bn(e){const t={};for(let r=0;r<e.length;r++){const{name:n,value:o}=e[r];t[n]=o}return t}function Nn(e){if(Wt()("wp.blocks.node.fromDOM",{since:"6.1",version:"6.3",alternative:"wp.richText.create",link:"https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/introducing-attributes-and-editable-fields/"}),e.nodeType===e.TEXT_NODE)return e.nodeValue;if(e.nodeType!==e.ELEMENT_NODE)throw new TypeError("A block node can only be created from a node of type text or element.");return{type:e.nodeName.toLowerCase(),props:{...Bn(e.attributes),children:Mn(e.childNodes)}}}function Pn(e){return Wt()("wp.blocks.node.matcher",{since:"6.1",version:"6.3",alternative:"html source",link:"https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/introducing-attributes-and-editable-fields/"}),t=>{let r=t;e&&(r=t.querySelector(e));try{return Nn(r)}catch(e){return null}}}var Ln={isNodeOfType:function(e,t){return Wt()("wp.blocks.node.isNodeOfType",{since:"6.1",version:"6.3",link:"https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/introducing-attributes-and-editable-fields/"}),e&&e.type===t},fromDOM:Nn,toHTML:function(e){return Wt()("wp.blocks.node.toHTML",{since:"6.1",version:"6.3",alternative:"wp.richText.toHTMLString",link:"https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/introducing-attributes-and-editable-fields/"}),On([e])},matcher:Pn};function Mn(e){Wt()("wp.blocks.children.fromDOM",{since:"6.1",version:"6.3",alternative:"wp.richText.create",link:"https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/introducing-attributes-and-editable-fields/"});const t=[];for(let r=0;r<e.length;r++)try{t.push(Nn(e[r]))}catch(e){}return t}function On(e){Wt()("wp.blocks.children.toHTML",{since:"6.1",version:"6.3",alternative:"wp.richText.toHTMLString",link:"https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/introducing-attributes-and-editable-fields/"});const t=e;return(0,z.renderToString)(t)}function jn(e){return Wt()("wp.blocks.children.matcher",{since:"6.1",version:"6.3",alternative:"html source",link:"https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/introducing-attributes-and-editable-fields/"}),t=>{let r=t;return e&&(r=t.querySelector(e)),r?Mn(r.childNodes):[]}}var Dn={concat:function(){Wt()("wp.blocks.children.concat",{since:"6.1",version:"6.3",alternative:"wp.richText.concat",link:"https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/introducing-attributes-and-editable-fields/"});const e=[];for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];for(let t=0;t<r.length;t++){const n=Array.isArray(r[t])?r[t]:[r[t]];for(let t=0;t<n.length;t++){const r=n[t];"string"==typeof r&&"string"==typeof e[e.length-1]?e[e.length-1]+=r:e.push(r)}}return e},getChildrenArray:function(e){return Wt()("wp.blocks.children.getChildrenArray",{since:"6.1",version:"6.3",link:"https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/introducing-attributes-and-editable-fields/"}),e},fromDOM:Mn,toHTML:On,matcher:jn};function zn(e,t){return t.some((t=>function(e,t){switch(t){case"string":return"string"==typeof e;case"boolean":return"boolean"==typeof e;case"object":return!!e&&e.constructor===Object;case"null":return null===e;case"array":return Array.isArray(e);case"integer":case"number":return"number"==typeof e}return!0}(e,t)))}function In(e,t,r,n,o){let a;switch(t.source){case void 0:a=n?n[e]:void 0;break;case"raw":a=o;break;case"attribute":case"property":case"html":case"text":case"children":case"node":case"query":case"tag":a=Rn(r,t)}return function(e,t){return void 0===t||zn(e,Array.isArray(t)?t:[t])}(a,t.type)&&function(e,t){return!Array.isArray(t)||t.includes(e)}(a,t.enum)||(a=void 0),void 0===a&&(a=t.default),a}const Hn=r.n(Sn)()((e=>{switch(e.source){case"attribute":let n=function(e,t){var r,n;return 1===arguments.length?(r=e,n=void 0):(r=t,n=e),function(e){var t=An(n,"attributes")(e);if(t&&Object.prototype.hasOwnProperty.call(t,r))return t[r].value}}(e.selector,e.attribute);return"boolean"===e.type&&(n=(e=>(0,Ct.pipe)([e,e=>void 0!==e]))(n)),n;case"html":return t=e.selector,r=e.multiline,e=>{let n=e;if(t&&(n=e.querySelector(t)),!n)return"";if(r){let e="";const t=n.children.length;for(let o=0;o<t;o++){const t=n.children[o];t.nodeName.toLowerCase()===r&&(e+=t.outerHTML)}return e}return n.innerHTML};case"text":return function(e){return An(e,"textContent")}(e.selector);case"children":return jn(e.selector);case"node":return Pn(e.selector);case"query":const o=(0,a.mapValues)(e.query,Hn);return function(e,t){return function(r){var n=r.querySelectorAll(e);return[].map.call(n,(function(e){return En(e,t)}))}}(e.selector,o);case"tag":return(0,Ct.pipe)([An(e.selector,"nodeName"),e=>e?e.toLowerCase():void 0]);default:console.error(`Unknown source type "${e.source}"`)}var t,r}));function Vn(e){return En(e,(e=>e))}function Rn(e,t){return Hn(t)(Vn(e))}function $n(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const n=Vn(t),o=nt(e),i=(0,a.mapValues)(o.attributes,((e,o)=>In(o,e,n,r,t)));return(0,Ie.applyFilters)("blocks.getBlockAttributes",i,o,t,r)}const Un={type:"string",source:"attribute",selector:"[data-custom-class-name] > *",attribute:"class"};function Fn(e){const t=Rn(`<div data-custom-class-name>${e}</div>`,Un);return t?t.trim().split(/\s+/):[]}function qn(e,t){const r=function(e,t,r){if(_e(t,"customClassName",!0)){const{className:n,...o}=e,a=Br(t,o),i=Fn(a),s=Fn(r).filter((e=>!i.includes(e)));s.length?e.className=s.join(" "):a&&delete e.className}return e}(e.attributes,t,e.originalContent);return{...e,attributes:r}}function Gn(){return!1}function Kn(e,t){let r=function(e,t){const r=le(),n=e.blockName||le(),o=e.attrs||{},a=e.innerBlocks||[];let i=e.innerHTML.trim();return n!==r||null!=t&&t.__unstableSkipAutop||(i=(0,_r.autop)(i).trim()),{...e,blockName:n,attrs:o,innerHTML:i,innerBlocks:a}}(e,t);r=function(e){const[t,r]=vn(e.blockName,e.attrs);return{...e,blockName:t,attrs:r}}(r);let n=ge(r.blockName);n||(r=function(e){const t=de()||le(),r=wr(e,{isCommentDelimited:!1}),n=wr(e,{isCommentDelimited:!0});return{blockName:t,attrs:{originalName:e.blockName,originalContent:n,originalUndelimitedContent:r},innerHTML:e.blockName?n:e.innerHTML,innerBlocks:e.innerBlocks,innerContent:e.innerContent}}(r),n=ge(r.blockName));const o=r.blockName===le()||r.blockName===de();if(!n||!r.innerHTML&&o)return;const a=r.innerBlocks.map((e=>Kn(e,t))).filter((e=>!!e)),i=He(r.blockName,$n(n,r.innerHTML,r.attrs),a);i.originalContent=r.innerHTML;const s=function(e,t){const[r]=yn(e,t);if(r)return{...e,isValid:r,validationIssues:[]};const n=qn(e,t),[o,a]=yn(e,t);return{...n,isValid:o,validationIssues:a}}(i,n),{validationIssues:l}=s,c=function(e,t,r){const n=t.attrs,{deprecated:o}=r;if(!o||!o.length)return e;for(let t=0;t<o.length;t++){const{isEligible:a=Gn}=o[t];if(e.isValid&&!a(n,e.innerBlocks))continue;const i=Object.assign(lt(r,V),o[t]);let s={...e,attributes:$n(i,e.originalContent,n)},[l]=yn(s,i);if(l||(s=qn(s,i),[l]=yn(s,i)),!l)continue;let c=s.innerBlocks,u=s.attributes;const{migrate:d}=i;if(d){let t=d(u,e.innerBlocks);Array.isArray(t)||(t=[t]),[u=n,c=e.innerBlocks]=t}e={...e,attributes:u,innerBlocks:c,isValid:!0,validationIssues:[]}}return e}(s,r,n);return c.isValid||(c.__unstableBlockSource=e),s.isValid||!c.isValid||null!=t&&t.__unstableSkipMigrationLogs?s.isValid||c.isValid||l.forEach((e=>{let{log:t,args:r}=e;return t(...r)})):(console.groupCollapsed("Updated Block: %s",n.name),console.info("Block successfully updated for `%s` (%o).\n\nNew content generated by `save` function:\n\n%s\n\nContent retrieved from post body:\n\n%s",n.name,n,Br(n,c.attributes),c.originalContent),console.groupEnd()),c}function Wn(e,t){return(0,br.parse)(e).reduce(((e,r)=>{const n=Kn(r,t);return n&&e.push(n),e}),[])}function Yn(){return We("from").filter((e=>{let{type:t}=e;return"raw"===t})).map((e=>e.isMatch?e:{...e,isMatch:t=>e.selector&&t.matches(e.selector)}))}function Qn(e,t){const r=document.implementation.createHTMLDocument("");return r.body.innerHTML=e,Array.from(r.body.children).flatMap((e=>{const r=Ke(Yn(),(t=>{let{isMatch:r}=t;return r(e)}));if(!r)return He("core/html",$n("core/html",e.outerHTML));const{transform:n,blockName:o}=r;return n?n(e,t):He(o,$n(o,e.outerHTML))}))}function Zn(e){const t=document.implementation.createHTMLDocument(""),r=document.implementation.createHTMLDocument(""),n=t.body,o=r.body;for(n.innerHTML=e;n.firstChild;){const e=n.firstChild;e.nodeType===e.TEXT_NODE?(0,I.isEmpty)(e)?n.removeChild(e):(o.lastChild&&"P"===o.lastChild.nodeName||o.appendChild(r.createElement("P")),o.lastChild.appendChild(e)):e.nodeType===e.ELEMENT_NODE?"BR"===e.nodeName?(e.nextSibling&&"BR"===e.nextSibling.nodeName&&(o.appendChild(r.createElement("P")),n.removeChild(e.nextSibling)),o.lastChild&&"P"===o.lastChild.nodeName&&o.lastChild.hasChildNodes()?o.lastChild.appendChild(e):n.removeChild(e)):"P"===e.nodeName?(0,I.isEmpty)(e)?n.removeChild(e):o.appendChild(e):(0,I.isPhrasingContent)(e)?(o.lastChild&&"P"===o.lastChild.nodeName||o.appendChild(r.createElement("P")),o.lastChild.appendChild(e)):o.appendChild(e):n.removeChild(e)}return o.innerHTML}function Xn(e,t){e.nodeType===e.COMMENT_NODE&&("nextpage"!==e.nodeValue?0===e.nodeValue.indexOf("more")&&function(e,t){const r=e.nodeValue.slice(4).trim();let n=e,o=!1;for(;n=n.nextSibling;)if(n.nodeType===n.COMMENT_NODE&&"noteaser"===n.nodeValue){o=!0,(0,I.remove)(n);break}const a=function(e,t,r){const n=r.createElement("wp-block");n.dataset.block="core/more",e&&(n.dataset.customText=e);t&&(n.dataset.noTeaser="");return n}(r,o,t);if(e.parentNode&&"P"===e.parentNode.nodeName&&1!==e.parentNode.childNodes.length){const r=Array.from(e.parentNode.childNodes),n=r.indexOf(e),o=e.parentNode.parentNode||t.body,i=(e,r)=>(e||(e=t.createElement("p")),e.appendChild(r),e);[r.slice(0,n).reduce(i,null),a,r.slice(n+1).reduce(i,null)].forEach((t=>t&&o.insertBefore(t,e.parentNode))),(0,I.remove)(e.parentNode)}else(0,I.replace)(e,a)}(e,t):(0,I.replace)(e,function(e){const t=e.createElement("wp-block");return t.dataset.block="core/nextpage",t}(t)))}function Jn(e){return"OL"===e.nodeName||"UL"===e.nodeName}function eo(e){if(!Jn(e))return;const t=e,r=e.previousElementSibling;if(r&&r.nodeName===e.nodeName&&1===t.children.length){for(;t.firstChild;)r.appendChild(t.firstChild);t.parentNode.removeChild(t)}const n=e.parentNode;if(n&&"LI"===n.nodeName&&1===n.children.length&&!/\S/.test((o=n,Array.from(o.childNodes).map((e=>{let{nodeValue:t=""}=e;return t})).join("")))){const e=n,r=e.previousElementSibling,o=e.parentNode;r?(r.appendChild(t),o.removeChild(e)):(o.parentNode.insertBefore(t,o),o.parentNode.removeChild(o))}var o;if(n&&Jn(n)){const t=e.previousElementSibling;t?t.appendChild(e):(0,I.unwrap)(e)}}function to(e){"BLOCKQUOTE"===e.nodeName&&(e.innerHTML=Zn(e.innerHTML))}function ro(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e;const r=e.ownerDocument.createElement("figure");t.parentNode.insertBefore(r,t),r.appendChild(e)}function no(e,t,r){if(!function(e,t){var r,n;const o=e.nodeName.toLowerCase();return"figcaption"!==o&&!(0,I.isTextContent)(e)&&o in(null!==(r=null==t||null===(n=t.figure)||void 0===n?void 0:n.children)&&void 0!==r?r:{})}(e,r))return;let n=e;const o=e.parentNode;(function(e,t){var r,n,o,a;return e.nodeName.toLowerCase()in(null!==(r=null==t||null===(n=t.figure)||void 0===n||null===(o=n.children)||void 0===o||null===(a=o.a)||void 0===a?void 0:a.children)&&void 0!==r?r:{})})(e,r)&&"A"===o.nodeName&&1===o.childNodes.length&&(n=e.parentNode);const a=n.closest("p,div");a?e.classList?(e.classList.contains("alignright")||e.classList.contains("alignleft")||e.classList.contains("aligncenter")||!a.textContent.trim())&&ro(n,a):ro(n,a):"BODY"===n.parentNode.nodeName&&ro(n)}var oo=window.wp.shortcode;const ao=e=>Array.isArray(e)?e:[e];var io=function e(t){let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];const o=We("from"),a=Ke(o,(e=>-1===n.indexOf(e.blockName)&&"shortcode"===e.type&&ao(e.tag).some((e=>(0,oo.regexp)(e).test(t)))));if(!a)return[t];const i=ao(a.tag),s=i.find((e=>(0,oo.regexp)(e).test(t)));let l;const c=r;if(l=(0,oo.next)(s,t,r)){var u;r=l.index+l.content.length;const o=t.substr(0,l.index),i=t.substr(r);if(!(null!==(u=l.shortcode.content)&&void 0!==u&&u.includes("<")||/(\n|<p>)\s*$/.test(o)&&/^\s*(\n|<\/p>)/.test(i)))return e(t,r);if(a.isMatch&&!a.isMatch(l.shortcode.attrs))return e(t,c,[...n,a.blockName]);let s=[];if("function"==typeof a.transform)s=[].concat(a.transform(l.shortcode.attrs,l)),s=s.map((e=>(e.originalContent=l.shortcode.content,qn(e,ge(e.name)))));else{const e=Object.fromEntries(Object.entries(a.attributes).filter((e=>{let[,t]=e;return t.shortcode})).map((e=>{let[t,r]=e;return[t,r.shortcode(l.shortcode.attrs,l)]}))),r=ge(a.blockName);if(!r)return[t];const n={...r,attributes:a.attributes};let o=He(a.blockName,$n(n,l.shortcode.content,e));o.originalContent=l.shortcode.content,o=qn(o,n),s=[o]}return[...e(o),...s,...e(i)]}return[t]};function so(e){return function(e,t){const r={phrasingContentSchema:(0,I.getPhrasingContentSchema)(t),isPaste:"paste"===t},n=e.map((e=>{let{isMatch:t,blockName:n,schema:o}=e;const i=_e(n,"anchor");return o="function"==typeof o?o(r):o,i||t?(0,a.mapValues)(o,(e=>{let r=e.attributes||[];return i&&(r=[...r,"id"]),{...e,attributes:r,isMatch:t||void 0}})):o}));return(0,a.mergeWith)({},...n,((e,t,r)=>{switch(r){case"children":return"*"===e||"*"===t?"*":{...e,...t};case"attributes":case"require":return[...e||[],...t||[]];case"isMatch":if(!e||!t)return;return function(){return e(...arguments)||t(...arguments)}}}))}(Yn(),e)}function lo(e,t,r,n){Array.from(e).forEach((e=>{lo(e.childNodes,t,r,n),t.forEach((t=>{r.contains(e)&&t(e,r,n)}))}))}function co(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=arguments.length>2?arguments[2]:void 0;const n=document.implementation.createHTMLDocument("");return n.body.innerHTML=e,lo(n.body.childNodes,t,n,r),n.body.innerHTML}function uo(e,t){const r=e[`${t}Sibling`];if(r&&(0,I.isPhrasingContent)(r))return r;const{parentNode:n}=e;return n&&(0,I.isPhrasingContent)(n)?uo(n,t):void 0}function po(e){return Wt()("wp.blocks.getPhrasingContentSchema",{since:"5.6",alternative:"wp.dom.getPhrasingContentSchema"}),(0,I.getPhrasingContentSchema)(e)}function fo(e){let{HTML:t=""}=e;if(-1!==t.indexOf("\x3c!-- wp:"))return Wn(t);const r=io(t),n=so();return r.map((e=>{if("string"!=typeof e)return e;return Qn(e=Zn(e=co(e,[eo,Xn,no,to],n)),fo)})).flat().filter(Boolean)}function ho(e){e.nodeType===e.COMMENT_NODE&&(0,I.remove)(e)}function go(e,t){return e.every((e=>function(e,t){if((0,I.isTextContent)(e))return!0;if(!t)return!1;const r=e.nodeName.toLowerCase();return[["ul","li","ol"],["h1","h2","h3","h4","h5","h6"]].some((e=>0===[r,t].filter((t=>!e.includes(t))).length))}(e,t)&&go(Array.from(e.children),t)))}function mo(e){return"BR"===e.nodeName&&e.previousSibling&&"BR"===e.previousSibling.nodeName}function bo(e,t){if("SPAN"===e.nodeName&&e.style){const{fontWeight:r,fontStyle:n,textDecorationLine:o,textDecoration:a,verticalAlign:i}=e.style;"bold"!==r&&"700"!==r||(0,I.wrap)(t.createElement("strong"),e),"italic"===n&&(0,I.wrap)(t.createElement("em"),e),("line-through"===o||a.includes("line-through"))&&(0,I.wrap)(t.createElement("s"),e),"super"===i?(0,I.wrap)(t.createElement("sup"),e):"sub"===i&&(0,I.wrap)(t.createElement("sub"),e)}else"B"===e.nodeName?e=(0,I.replaceTag)(e,"strong"):"I"===e.nodeName?e=(0,I.replaceTag)(e,"em"):"A"===e.nodeName&&(e.target&&"_blank"===e.target.toLowerCase()?e.rel="noreferrer noopener":(e.removeAttribute("target"),e.removeAttribute("rel")),e.name&&!e.id&&(e.id=e.name),e.id&&!e.ownerDocument.querySelector(`[href="#${e.id}"]`)&&e.removeAttribute("id"))}function _o(e){"SCRIPT"!==e.nodeName&&"NOSCRIPT"!==e.nodeName&&"TEMPLATE"!==e.nodeName&&"STYLE"!==e.nodeName||e.parentNode.removeChild(e)}const{parseInt:ko}=window;function yo(e){return"OL"===e.nodeName||"UL"===e.nodeName}function wo(e,t){if("P"!==e.nodeName)return;const r=e.getAttribute("style");if(!r)return;if(-1===r.indexOf("mso-list"))return;const n=/mso-list\s*:[^;]+level([0-9]+)/i.exec(r);if(!n)return;let o=ko(n[1],10)-1||0;const a=e.previousElementSibling;if(!a||!yo(a)){const r=e.textContent.trim().slice(0,1),n=/[1iIaA]/.test(r),o=t.createElement(n?"ol":"ul");n&&o.setAttribute("type",r),e.parentNode.insertBefore(o,e)}const i=e.previousElementSibling,s=i.nodeName,l=t.createElement("li");let c=i;for(e.removeChild(e.firstChild);e.firstChild;)l.appendChild(e.firstChild);for(;o--;)c=c.lastChild||c,yo(c)&&(c=c.lastChild||c);yo(c)||(c=c.appendChild(t.createElement(s))),c.appendChild(l),e.parentNode.removeChild(e)}var vo=window.wp.blob;const{atob:To,File:Co}=window;function xo(e){if("IMG"===e.nodeName){if(0===e.src.indexOf("file:")&&(e.src=""),0===e.src.indexOf("data:")){const[t,r]=e.src.split(","),[n]=t.slice(5).split(";");if(!r||!n)return void(e.src="");let o;try{o=To(r)}catch(t){return void(e.src="")}const a=new Uint8Array(o.length);for(let e=0;e<a.length;e++)a[e]=o.charCodeAt(e);const i=n.replace("/","."),s=new Co([a],i,{type:n});e.src=(0,vo.createBlobURL)(s)}1!==e.height&&1!==e.width||e.parentNode.removeChild(e)}}function Eo(e){"DIV"===e.nodeName&&(e.innerHTML=Zn(e.innerHTML))}var Ao=r(7308);const So=new(r.n(Ao)().Converter)({noHeaderId:!0,tables:!0,literalMidWordUnderscores:!0,omitExtraWLInCodeBlocks:!0,simpleLineBreaks:!0,strikethrough:!0});function Bo(e){if("IFRAME"===e.nodeName){const t=e.ownerDocument.createTextNode(e.src);e.parentNode.replaceChild(t,e)}}function No(e){e.id&&0===e.id.indexOf("docs-internal-guid-")&&("B"===e.tagName?(0,I.unwrap)(e):e.removeAttribute("id"))}function Po(e){if(e.nodeType!==e.TEXT_NODE)return;let t=e;for(;t=t.parentNode;)if(t.nodeType===t.ELEMENT_NODE&&"PRE"===t.nodeName)return;let r=e.data.replace(/[ \r\n\t]+/g," ");if(" "===r[0]){const t=uo(e,"previous");t&&"BR"!==t.nodeName&&" "!==t.textContent.slice(-1)||(r=r.slice(1))}if(" "===r[r.length-1]){const t=uo(e,"next");(!t||"BR"===t.nodeName||t.nodeType===t.TEXT_NODE&&(" "===(n=t.textContent[0])||"\r"===n||"\n"===n||"\t"===n))&&(r=r.slice(0,-1))}var n;r?e.data=r:e.parentNode.removeChild(e)}function Lo(e){"BR"===e.nodeName&&(uo(e,"next")||e.parentNode.removeChild(e))}function Mo(e){"P"===e.nodeName&&(e.hasChildNodes()||e.parentNode.removeChild(e))}function Oo(e){if("SPAN"!==e.nodeName)return;if("paragraph-break"!==e.getAttribute("data-stringify-type"))return;const{parentNode:t}=e;t.insertBefore(e.ownerDocument.createElement("br"),e),t.insertBefore(e.ownerDocument.createElement("br"),e),t.removeChild(e)}const{console:jo}=window;function Do(e,t){return e=co(e,[_o,No,bo,ho]),e=(0,I.removeInvalidHTML)(e,(0,I.getPhrasingContentSchema)("paste"),{inline:!0}),t||(e=co(e,[Po,Lo])),jo.log("Processed inline HTML:\n\n",e),e}function zo(e){let{HTML:t="",plainText:r="",mode:n="AUTO",tagName:o,preserveWhiteSpace:a}=e;if(t=t.replace(/<meta[^>]+>/g,""),t=t.replace(/^\s*<html[^>]*>\s*<body[^>]*>(?:\s*<!--\s*StartFragment\s*-->)?/i,""),t=t.replace(/(?:<!--\s*EndFragment\s*-->\s*)?<\/body>\s*<\/html>\s*$/i,""),"INLINE"!==n){const e=t||r;if(-1!==e.indexOf("\x3c!-- wp:"))return Wn(e)}var i;if(String.prototype.normalize&&(t=t.normalize()),!r||t&&!function(e){return!/<(?!br[ />])/i.test(e)}(t)||(t=r,/^\s+$/.test(r)||(i=t,t=So.makeHtml(function(e){return e.replace(/((?:^|\n)```)([^\n`]+)(```(?:$|\n))/,((e,t,r,n)=>`${t}\n${r}\n${n}`))}(function(e){return e.replace(/(^|\n)•( +)/g,"$1*$2")}(i)))),"AUTO"===n&&-1===r.indexOf("\n")&&0!==r.indexOf("<p>")&&0===t.indexOf("<p>")&&(n="INLINE")),"INLINE"===n)return Do(t,a);t=co(t,[Oo]);const s=io(t),l=s.length>1;if("AUTO"===n&&!l&&function(e,t){const r=document.implementation.createHTMLDocument("");r.body.innerHTML=e;const n=Array.from(r.body.children);return!n.some(mo)&&go(n,t)}(t,o))return Do(t,a);const c=(0,I.getPhrasingContentSchema)("paste"),u=so("paste"),d=s.map((e=>{if("string"!=typeof e)return e;const t=[No,wo,_o,eo,xo,bo,Xn,ho,Bo,no,to,Eo],r={...u,...c};return e=co(e,t,u),e=co(e=Zn(e=(0,I.removeInvalidHTML)(e,r)),[Po,Lo,Mo],u),jo.log("Processed HTML piece:\n\n",e),Qn(e,zo)})).flat().filter(Boolean);if("AUTO"===n&&1===d.length&&_e(d[0].name,"__unstablePasteTextInline",!1)){const e=/^[\n]+|[\n]+$/g,t=r.replace(e,"");if(""!==t&&-1===t.indexOf("\n"))return(0,I.removeInvalidHTML)(Pr(d[0]),c).replace(e,"")}return d}function Io(){return(0,o.select)(mr).getCategories()}function Ho(e){(0,o.dispatch)(mr).setCategories(e)}function Vo(e,t){(0,o.dispatch)(mr).updateCategory(e,t)}function Ro(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return e.length===t.length&&t.every(((t,r)=>{let[n,,o]=t;const a=e[r];return n===a.name&&Ro(a.innerBlocks,o)}))}function $o(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1?arguments[1]:void 0;return t?t.map(((t,r)=>{var n;let[o,a,i]=t;const s=e[r];if(s&&s.name===o){const e=$o(s.innerBlocks,i);return{...s,innerBlocks:e}}const l=ge(o),c=(e,t)=>t?Object.fromEntries(Object.entries(t).map((t=>{let[r,n]=t;return[r,u(e[r],n)]}))):{},u=(e,t)=>{return"html"===(null==(r=e)?void 0:r.source)&&Array.isArray(t)?(0,z.renderToString)(t):(e=>"query"===(null==e?void 0:e.source))(e)&&t?t.map((t=>c(e.query,t))):t;var r},d=c(null!==(n=null==l?void 0:l.attributes)&&void 0!==n?n:{},a);let[p,f]=vn(o,d);return void 0===ge(p)&&(f={originalName:o,originalContent:"",originalUndelimitedContent:""},p="core/missing"),He(p,f,$o([],i))})):e}function Uo(e){return Wt()("wp.blocks.withBlockContentContext",{since:"6.1"}),e}}(),(window.wp=window.wp||{}).blocks=n}(); redux-routine.min.js 0000666 00000022034 15123355174 0010511 0 ustar 00 /*! This file is auto-generated */
!function(){"use strict";var t={9025:function(t,r,e){Object.defineProperty(r,"__esModule",{value:!0}),r.race=r.join=r.fork=r.promise=void 0;var n=c(e(9681)),u=e(7783),o=c(e(2451));function c(t){return t&&t.__esModule?t:{default:t}}var f=r.promise=function(t,r,e,u,o){return!!n.default.promise(t)&&(t.then(r,o),!0)},a=new Map,i=r.fork=function(t,r,e){if(!n.default.fork(t))return!1;var c=Symbol("fork"),f=(0,o.default)();a.set(c,f),e(t.iterator.apply(null,t.args),(function(t){return f.dispatch(t)}),(function(t){return f.dispatch((0,u.error)(t))}));var i=f.subscribe((function(){i(),a.delete(c)}));return r(c),!0},l=r.join=function(t,r,e,u,o){if(!n.default.join(t))return!1;var c,f=a.get(t.task);return f?c=f.subscribe((function(t){c(),r(t)})):o("join error : task not found"),!0},s=r.race=function(t,r,e,u,o){if(!n.default.race(t))return!1;var c,f=!1,a=function(t,e,n){f||(f=!0,t[e]=n,r(t))},i=function(t){f||o(t)};return n.default.array(t.competitors)?(c=t.competitors.map((function(){return!1})),t.competitors.forEach((function(t,r){e(t,(function(t){return a(c,r,t)}),i)}))):function(){var r=Object.keys(t.competitors).reduce((function(t,r){return t[r]=!1,t}),{});Object.keys(t.competitors).forEach((function(n){e(t.competitors[n],(function(t){return a(r,n,t)}),i)}))}(),!0};r.default=[f,i,l,s,function(t,r){if(!n.default.subscribe(t))return!1;if(!n.default.channel(t.channel))throw new Error('the first argument of "subscribe" must be a valid channel');var e=t.channel.subscribe((function(t){e&&e(),r(t)}));return!0}]},1575:function(t,r,e){Object.defineProperty(r,"__esModule",{value:!0}),r.iterator=r.array=r.object=r.error=r.any=void 0;var n,u=e(9681),o=(n=u)&&n.__esModule?n:{default:n};var c=r.any=function(t,r,e,n){return n(t),!0},f=r.error=function(t,r,e,n,u){return!!o.default.error(t)&&(u(t.error),!0)},a=r.object=function(t,r,e,n,u){if(!o.default.all(t)||!o.default.obj(t.value))return!1;var c={},f=Object.keys(t.value),a=0,i=!1;return f.map((function(r){e(t.value[r],(function(t){return function(t,r){i||(c[t]=r,++a===f.length&&n(c))}(r,t)}),(function(t){return function(t,r){i||(i=!0,u(r))}(0,t)}))})),!0},i=r.array=function(t,r,e,n,u){if(!o.default.all(t)||!o.default.array(t.value))return!1;var c=[],f=0,a=!1;return t.value.map((function(r,o){e(r,(function(r){return function(r,e){a||(c[r]=e,++f===t.value.length&&n(c))}(o,r)}),(function(t){return function(t,r){a||(a=!0,u(r))}(0,t)}))})),!0},l=r.iterator=function(t,r,e,n,u){return!!o.default.iterator(t)&&(e(t,r,u),!0)};r.default=[f,l,i,a,c]},2165:function(t,r,e){Object.defineProperty(r,"__esModule",{value:!0}),r.cps=r.call=void 0;var n,u=e(9681),o=(n=u)&&n.__esModule?n:{default:n};var c=r.call=function(t,r,e,n,u){if(!o.default.call(t))return!1;try{r(t.func.apply(t.context,t.args))}catch(t){u(t)}return!0},f=r.cps=function(t,r,e,n,u){var c;return!!o.default.cps(t)&&((c=t.func).call.apply(c,[null].concat(function(t){if(Array.isArray(t)){for(var r=0,e=Array(t.length);r<t.length;r++)e[r]=t[r];return e}return Array.from(t)}(t.args),[function(t,e){t?u(t):r(e)}])),!0)};r.default=[c,f]},6288:function(t,r,e){Object.defineProperty(r,"__esModule",{value:!0});var n=o(e(1575)),u=o(e(9681));function o(t){return t&&t.__esModule?t:{default:t}}function c(t){if(Array.isArray(t)){for(var r=0,e=Array(t.length);r<t.length;r++)e[r]=t[r];return e}return Array.from(t)}r.default=function(){var t=arguments.length<=0||void 0===arguments[0]?[]:arguments[0],r=[].concat(c(t),c(n.default)),e=function t(e){var n=arguments.length<=1||void 0===arguments[1]?function(){}:arguments[1],o=arguments.length<=2||void 0===arguments[2]?function(){}:arguments[2],c=function(e){var u=function(t){return function(r){try{var u=t?e.throw(r):e.next(r),f=u.value;if(u.done)return n(f);c(f)}catch(t){return o(t)}}},c=function e(n){r.some((function(r){return r(n,e,t,u(!1),u(!0))}))};u(!1)()},f=u.default.iterator(e)?e:regeneratorRuntime.mark((function t(){return regeneratorRuntime.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,e;case 2:return t.abrupt("return",t.sent);case 3:case"end":return t.stop()}}),t,this)}))();c(f,n,o)};return e}},2290:function(t,r,e){Object.defineProperty(r,"__esModule",{value:!0}),r.wrapControls=r.asyncControls=r.create=void 0;var n=e(7783);Object.keys(n).forEach((function(t){"default"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return n[t]}})}));var u=f(e(6288)),o=f(e(9025)),c=f(e(2165));function f(t){return t&&t.__esModule?t:{default:t}}r.create=u.default,r.asyncControls=o.default,r.wrapControls=c.default},2451:function(t,r){Object.defineProperty(r,"__esModule",{value:!0});r.default=function(){var t=[];return{subscribe:function(r){return t.push(r),function(){t=t.filter((function(t){return t!==r}))}},dispatch:function(r){t.slice().forEach((function(t){return t(r)}))}}}},7783:function(t,r,e){Object.defineProperty(r,"__esModule",{value:!0}),r.createChannel=r.subscribe=r.cps=r.apply=r.call=r.invoke=r.delay=r.race=r.join=r.fork=r.error=r.all=void 0;var n,u=e(9851),o=(n=u)&&n.__esModule?n:{default:n};r.all=function(t){return{type:o.default.all,value:t}},r.error=function(t){return{type:o.default.error,error:t}},r.fork=function(t){for(var r=arguments.length,e=Array(r>1?r-1:0),n=1;n<r;n++)e[n-1]=arguments[n];return{type:o.default.fork,iterator:t,args:e}},r.join=function(t){return{type:o.default.join,task:t}},r.race=function(t){return{type:o.default.race,competitors:t}},r.delay=function(t){return new Promise((function(r){setTimeout((function(){return r(!0)}),t)}))},r.invoke=function(t){for(var r=arguments.length,e=Array(r>1?r-1:0),n=1;n<r;n++)e[n-1]=arguments[n];return{type:o.default.call,func:t,context:null,args:e}},r.call=function(t,r){for(var e=arguments.length,n=Array(e>2?e-2:0),u=2;u<e;u++)n[u-2]=arguments[u];return{type:o.default.call,func:t,context:r,args:n}},r.apply=function(t,r,e){return{type:o.default.call,func:t,context:r,args:e}},r.cps=function(t){for(var r=arguments.length,e=Array(r>1?r-1:0),n=1;n<r;n++)e[n-1]=arguments[n];return{type:o.default.cps,func:t,args:e}},r.subscribe=function(t){return{type:o.default.subscribe,channel:t}},r.createChannel=function(t){var r=[];return t((function(t){return r.forEach((function(r){return r(t)}))})),{subscribe:function(t){return r.push(t),function(){return r.splice(r.indexOf(t),1)}}}}},9681:function(t,r,e){Object.defineProperty(r,"__esModule",{value:!0});var n,u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol?"symbol":typeof t},o=e(9851),c=(n=o)&&n.__esModule?n:{default:n};var f={obj:function(t){return"object"===(void 0===t?"undefined":u(t))&&!!t},all:function(t){return f.obj(t)&&t.type===c.default.all},error:function(t){return f.obj(t)&&t.type===c.default.error},array:Array.isArray,func:function(t){return"function"==typeof t},promise:function(t){return t&&f.func(t.then)},iterator:function(t){return t&&f.func(t.next)&&f.func(t.throw)},fork:function(t){return f.obj(t)&&t.type===c.default.fork},join:function(t){return f.obj(t)&&t.type===c.default.join},race:function(t){return f.obj(t)&&t.type===c.default.race},call:function(t){return f.obj(t)&&t.type===c.default.call},cps:function(t){return f.obj(t)&&t.type===c.default.cps},subscribe:function(t){return f.obj(t)&&t.type===c.default.subscribe},channel:function(t){return f.obj(t)&&f.func(t.subscribe)}};r.default=f},9851:function(t,r){Object.defineProperty(r,"__esModule",{value:!0});var e={all:Symbol("all"),error:Symbol("error"),fork:Symbol("fork"),join:Symbol("join"),race:Symbol("race"),call:Symbol("call"),cps:Symbol("cps"),subscribe:Symbol("subscribe")};r.default=e}},r={};function e(n){var u=r[n];if(void 0!==u)return u.exports;var o=r[n]={exports:{}};return t[n](o,o.exports,e),o.exports}e.d=function(t,r){for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},e.o=function(t,r){return Object.prototype.hasOwnProperty.call(t,r)};var n={};!function(){function t(t){return!!t&&"function"==typeof t[Symbol.iterator]&&"function"==typeof t.next}e.d(n,{default:function(){return i}});var r=e(2290);function u(t){return!!t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then}
/*!
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*/
function o(t){return"[object Object]"===Object.prototype.toString.call(t)}function c(t){return!1!==o(r=t)&&(void 0===(e=r.constructor)||!1!==o(n=e.prototype)&&!1!==n.hasOwnProperty("isPrototypeOf"))&&"string"==typeof t.type;var r,e,n}function f(t,r){return c(t)&&t.type===r}function a(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0;const n=Object.entries(t).map((t=>{let[r,e]=t;return(t,n,o,c,a)=>{if(!f(t,r))return!1;const i=e(t);return u(i)?i.then(c,a):c(i),!0}})),o=(t,r)=>!!c(t)&&(e(t),r(),!0);n.push(o);const a=(0,r.create)(n);return t=>new Promise(((r,n)=>a(t,(t=>{c(t)&&e(t),r(t)}),n)))}function i(){let r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return e=>{const n=a(r,e.dispatch);return r=>e=>t(e)?n(e):r(e)}}}(),(window.wp=window.wp||{}).reduxRoutine=n.default}(); customize-widgets.js 0000666 00000327416 15123355174 0010617 0 ustar 00 /******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 5619:
/***/ (function(module) {
"use strict";
// do not edit .js files directly - edit src/index.jst
var envHasBigInt64Array = typeof BigInt64Array !== 'undefined';
module.exports = function equal(a, b) {
if (a === b) return true;
if (a && b && typeof a == 'object' && typeof b == 'object') {
if (a.constructor !== b.constructor) return false;
var length, i, keys;
if (Array.isArray(a)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (!equal(a[i], b[i])) return false;
return true;
}
if ((a instanceof Map) && (b instanceof Map)) {
if (a.size !== b.size) return false;
for (i of a.entries())
if (!b.has(i[0])) return false;
for (i of a.entries())
if (!equal(i[1], b.get(i[0]))) return false;
return true;
}
if ((a instanceof Set) && (b instanceof Set)) {
if (a.size !== b.size) return false;
for (i of a.entries())
if (!b.has(i[0])) return false;
return true;
}
if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (a[i] !== b[i]) return false;
return true;
}
if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) return false;
for (i = length; i-- !== 0;)
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
for (i = length; i-- !== 0;) {
var key = keys[i];
if (!equal(a[key], b[key])) return false;
}
return true;
}
// true if both NaN, false otherwise
return a!==a && b!==b;
};
/***/ }),
/***/ 7153:
/***/ (function(module, exports) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2018 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
'use strict';
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = '';
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
classes = appendClass(classes, parseValue(arg));
}
}
return classes;
}
function parseValue (arg) {
if (typeof arg === 'string' || typeof arg === 'number') {
return arg;
}
if (typeof arg !== 'object') {
return '';
}
if (Array.isArray(arg)) {
return classNames.apply(null, arg);
}
if (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes('[native code]')) {
return arg.toString();
}
var classes = '';
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes = appendClass(classes, key);
}
}
return classes;
}
function appendClass (value, newClass) {
if (!newClass) {
return value;
}
if (value) {
return value + ' ' + newClass;
}
return value + newClass;
}
if ( true && module.exports) {
classNames.default = classNames;
module.exports = classNames;
} else if (true) {
// register as 'classnames', consistent with npm package name
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () {
return classNames;
}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
}());
/***/ })
/******/ });
/************************************************************************/
/******/ // 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 in strict mode.
!function() {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"initialize": function() { return /* binding */ initialize; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/customize-widgets/build-module/store/selectors.js
var selectors_namespaceObject = {};
__webpack_require__.r(selectors_namespaceObject);
__webpack_require__.d(selectors_namespaceObject, {
"__experimentalGetInsertionPoint": function() { return __experimentalGetInsertionPoint; },
"isInserterOpened": function() { return isInserterOpened; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/customize-widgets/build-module/store/actions.js
var actions_namespaceObject = {};
__webpack_require__.r(actions_namespaceObject);
__webpack_require__.d(actions_namespaceObject, {
"setIsInserterOpened": function() { return setIsInserterOpened; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/interface/build-module/store/actions.js
var store_actions_namespaceObject = {};
__webpack_require__.r(store_actions_namespaceObject);
__webpack_require__.d(store_actions_namespaceObject, {
"disableComplementaryArea": function() { return disableComplementaryArea; },
"enableComplementaryArea": function() { return enableComplementaryArea; },
"pinItem": function() { return pinItem; },
"setDefaultComplementaryArea": function() { return setDefaultComplementaryArea; },
"setFeatureDefaults": function() { return setFeatureDefaults; },
"setFeatureValue": function() { return setFeatureValue; },
"toggleFeature": function() { return toggleFeature; },
"unpinItem": function() { return unpinItem; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/interface/build-module/store/selectors.js
var store_selectors_namespaceObject = {};
__webpack_require__.r(store_selectors_namespaceObject);
__webpack_require__.d(store_selectors_namespaceObject, {
"getActiveComplementaryArea": function() { return getActiveComplementaryArea; },
"isFeatureActive": function() { return isFeatureActive; },
"isItemPinned": function() { return isItemPinned; }
});
;// CONCATENATED MODULE: external ["wp","element"]
var external_wp_element_namespaceObject = window["wp"]["element"];
;// CONCATENATED MODULE: external ["wp","blockLibrary"]
var external_wp_blockLibrary_namespaceObject = window["wp"]["blockLibrary"];
;// CONCATENATED MODULE: external ["wp","widgets"]
var external_wp_widgets_namespaceObject = window["wp"]["widgets"];
;// CONCATENATED MODULE: external ["wp","blocks"]
var external_wp_blocks_namespaceObject = window["wp"]["blocks"];
;// CONCATENATED MODULE: external ["wp","data"]
var external_wp_data_namespaceObject = window["wp"]["data"];
;// CONCATENATED MODULE: external ["wp","preferences"]
var external_wp_preferences_namespaceObject = window["wp"]["preferences"];
;// CONCATENATED MODULE: external ["wp","components"]
var external_wp_components_namespaceObject = window["wp"]["components"];
;// CONCATENATED MODULE: external ["wp","keyboardShortcuts"]
var external_wp_keyboardShortcuts_namespaceObject = window["wp"]["keyboardShortcuts"];
;// CONCATENATED MODULE: external ["wp","i18n"]
var external_wp_i18n_namespaceObject = window["wp"]["i18n"];
;// CONCATENATED MODULE: external ["wp","blockEditor"]
var external_wp_blockEditor_namespaceObject = window["wp"]["blockEditor"];
;// CONCATENATED MODULE: external ["wp","compose"]
var external_wp_compose_namespaceObject = window["wp"]["compose"];
;// CONCATENATED MODULE: external ["wp","hooks"]
var external_wp_hooks_namespaceObject = window["wp"]["hooks"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/components/error-boundary/index.js
/**
* WordPress dependencies
*/
function CopyButton(_ref) {
let {
text,
children
} = _ref;
const ref = (0,external_wp_compose_namespaceObject.useCopyToClipboard)(text);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "secondary",
ref: ref
}, children);
}
class ErrorBoundary extends external_wp_element_namespaceObject.Component {
constructor() {
super(...arguments);
this.state = {
error: null
};
}
componentDidCatch(error) {
this.setState({
error
});
(0,external_wp_hooks_namespaceObject.doAction)('editor.ErrorBoundary.errorLogged', error);
}
render() {
const {
error
} = this.state;
if (!error) {
return this.props.children;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.Warning, {
className: "customize-widgets-error-boundary",
actions: [(0,external_wp_element_namespaceObject.createElement)(CopyButton, {
key: "copy-error",
text: error.stack
}, (0,external_wp_i18n_namespaceObject.__)('Copy Error'))]
}, (0,external_wp_i18n_namespaceObject.__)('The editor has encountered an unexpected error.'));
}
}
;// CONCATENATED MODULE: external ["wp","coreData"]
var external_wp_coreData_namespaceObject = window["wp"]["coreData"];
;// CONCATENATED MODULE: external ["wp","mediaUtils"]
var external_wp_mediaUtils_namespaceObject = window["wp"]["mediaUtils"];
;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/extends.js
function _extends() {
return _extends = Object.assign ? Object.assign.bind() : function (n) {
for (var e = 1; e < arguments.length; e++) {
var t = arguments[e];
for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
}
return n;
}, _extends.apply(null, arguments);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/components/block-inspector-button/index.js
/**
* WordPress dependencies
*/
function BlockInspectorButton(_ref) {
let {
inspector,
closeMenu,
...props
} = _ref;
const selectedBlockClientId = (0,external_wp_data_namespaceObject.useSelect)(select => select(external_wp_blockEditor_namespaceObject.store).getSelectedBlockClientId(), []);
const selectedBlock = (0,external_wp_element_namespaceObject.useMemo)(() => document.getElementById(`block-${selectedBlockClientId}`), [selectedBlockClientId]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, _extends({
onClick: () => {
// Open the inspector.
inspector.open({
returnFocusWhenClose: selectedBlock
}); // Then close the dropdown menu.
closeMenu();
}
}, props), (0,external_wp_i18n_namespaceObject.__)('Show more settings'));
}
/* harmony default export */ var block_inspector_button = (BlockInspectorButton);
// EXTERNAL MODULE: ./node_modules/classnames/index.js
var classnames = __webpack_require__(7153);
var classnames_default = /*#__PURE__*/__webpack_require__.n(classnames);
;// CONCATENATED MODULE: external ["wp","keycodes"]
var external_wp_keycodes_namespaceObject = window["wp"]["keycodes"];
;// CONCATENATED MODULE: external ["wp","primitives"]
var external_wp_primitives_namespaceObject = window["wp"]["primitives"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/undo.js
/**
* WordPress dependencies
*/
const undo = (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: "M18.3 11.7c-.6-.6-1.4-.9-2.3-.9H6.7l2.9-3.3-1.1-1-4.5 5L8.5 16l1-1-2.7-2.7H16c.5 0 .9.2 1.3.5 1 1 1 3.4 1 4.5v.3h1.5v-.2c0-1.5 0-4.3-1.5-5.7z"
}));
/* harmony default export */ var library_undo = (undo);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/redo.js
/**
* WordPress dependencies
*/
const redo = (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: "M15.6 6.5l-1.1 1 2.9 3.3H8c-.9 0-1.7.3-2.3.9-1.4 1.5-1.4 4.2-1.4 5.6v.2h1.5v-.3c0-1.1 0-3.5 1-4.5.3-.3.7-.5 1.3-.5h9.2L14.5 15l1.1 1.1 4.6-4.6-4.6-5z"
}));
/* harmony default export */ var library_redo = (redo);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/plus.js
/**
* WordPress dependencies
*/
const plus = (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: "M18 11.2h-5.2V6h-1.6v5.2H6v1.6h5.2V18h1.6v-5.2H18z"
}));
/* harmony default export */ var library_plus = (plus);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/close-small.js
/**
* WordPress dependencies
*/
const closeSmall = (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: "M12 13.06l3.712 3.713 1.061-1.06L13.061 12l3.712-3.712-1.06-1.06L12 10.938 8.288 7.227l-1.061 1.06L10.939 12l-3.712 3.712 1.06 1.061L12 13.061z"
}));
/* harmony default export */ var close_small = (closeSmall);
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/store/reducer.js
/**
* WordPress dependencies
*/
/**
* Reducer tracking whether the inserter is open.
*
* @param {boolean|Object} state
* @param {Object} action
*/
function blockInserterPanel() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'SET_IS_INSERTER_OPENED':
return action.value;
}
return state;
}
/* harmony default export */ var reducer = ((0,external_wp_data_namespaceObject.combineReducers)({
blockInserterPanel
}));
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/store/selectors.js
/**
* Returns true if the inserter is opened.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the inserter is opened.
*/
function isInserterOpened(state) {
return !!state.blockInserterPanel;
}
/**
* Get the insertion point for the inserter.
*
* @param {Object} state Global application state.
*
* @return {Object} The root client ID and index to insert at.
*/
function __experimentalGetInsertionPoint(state) {
const {
rootClientId,
insertionIndex
} = state.blockInserterPanel;
return {
rootClientId,
insertionIndex
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/store/actions.js
/**
* Returns an action object used to open/close the inserter.
*
* @param {boolean|Object} value Whether the inserter should be
* opened (true) or closed (false).
* To specify an insertion point,
* use an object.
* @param {string} value.rootClientId The root client ID to insert at.
* @param {number} value.insertionIndex The index to insert at.
*
* @return {Object} Action object.
*/
function setIsInserterOpened(value) {
return {
type: 'SET_IS_INSERTER_OPENED',
value
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/store/constants.js
/**
* Module Constants
*/
const STORE_NAME = 'core/customize-widgets';
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/store/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Block editor data store configuration.
*
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/data/README.md#registering-a-store
*
* @type {Object}
*/
const storeConfig = {
reducer: reducer,
selectors: selectors_namespaceObject,
actions: actions_namespaceObject
};
/**
* Store definition for the edit widgets 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);
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/components/inserter/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function Inserter(_ref) {
let {
setIsOpened
} = _ref;
const inserterTitleId = (0,external_wp_compose_namespaceObject.useInstanceId)(Inserter, 'customize-widget-layout__inserter-panel-title');
const insertionPoint = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).__experimentalGetInsertionPoint(), []);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "customize-widgets-layout__inserter-panel",
"aria-labelledby": inserterTitleId
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "customize-widgets-layout__inserter-panel-header"
}, (0,external_wp_element_namespaceObject.createElement)("h2", {
id: inserterTitleId,
className: "customize-widgets-layout__inserter-panel-header-title"
}, (0,external_wp_i18n_namespaceObject.__)('Add a block')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "customize-widgets-layout__inserter-panel-header-close-button",
icon: close_small,
onClick: () => setIsOpened(false),
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Close inserter')
})), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "customize-widgets-layout__inserter-panel-content"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.__experimentalLibrary, {
rootClientId: insertionPoint.rootClientId,
__experimentalInsertionIndex: insertionPoint.insertionIndex,
showInserterHelpPanel: true,
onSelect: () => setIsOpened(false)
})));
}
/* harmony default export */ var components_inserter = (Inserter);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/external.js
/**
* WordPress dependencies
*/
const external = (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: "M18.2 17c0 .7-.6 1.2-1.2 1.2H7c-.7 0-1.2-.6-1.2-1.2V7c0-.7.6-1.2 1.2-1.2h3.2V4.2H7C5.5 4.2 4.2 5.5 4.2 7v10c0 1.5 1.2 2.8 2.8 2.8h10c1.5 0 2.8-1.2 2.8-2.8v-3.6h-1.5V17zM14.9 3v1.5h3.7l-6.4 6.4 1.1 1.1 6.4-6.4v3.7h1.5V3h-6.3z"
}));
/* harmony default export */ var library_external = (external);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/more-vertical.js
/**
* WordPress dependencies
*/
const moreVertical = (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: "M13 19h-2v-2h2v2zm0-6h-2v-2h2v2zm0-6h-2V5h2v2z"
}));
/* harmony default export */ var more_vertical = (moreVertical);
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/more-menu-dropdown/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
function MoreMenuDropdown(_ref) {
let {
as: DropdownComponent = external_wp_components_namespaceObject.DropdownMenu,
className,
/* translators: button label text should, if possible, be under 16 characters. */
label = (0,external_wp_i18n_namespaceObject.__)('Options'),
popoverProps,
toggleProps,
children
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(DropdownComponent, {
className: classnames_default()('interface-more-menu-dropdown', className),
icon: more_vertical,
label: label,
popoverProps: {
placement: 'bottom-end',
...popoverProps,
className: classnames_default()('interface-more-menu-dropdown__content', popoverProps === null || popoverProps === void 0 ? void 0 : popoverProps.className)
},
toggleProps: {
tooltipPosition: 'bottom',
...toggleProps
}
}, onClose => children(onClose));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/index.js
;// CONCATENATED MODULE: external ["wp","deprecated"]
var external_wp_deprecated_namespaceObject = window["wp"]["deprecated"];
var external_wp_deprecated_default = /*#__PURE__*/__webpack_require__.n(external_wp_deprecated_namespaceObject);
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/store/actions.js
/**
* WordPress dependencies
*/
/**
* Set a default complementary area.
*
* @param {string} scope Complementary area scope.
* @param {string} area Area identifier.
*
* @return {Object} Action object.
*/
const setDefaultComplementaryArea = (scope, area) => ({
type: 'SET_DEFAULT_COMPLEMENTARY_AREA',
scope,
area
});
/**
* Enable the complementary area.
*
* @param {string} scope Complementary area scope.
* @param {string} area Area identifier.
*/
const enableComplementaryArea = (scope, area) => _ref => {
let {
registry,
dispatch
} = _ref;
// Return early if there's no area.
if (!area) {
return;
}
const isComplementaryAreaVisible = registry.select(external_wp_preferences_namespaceObject.store).get(scope, 'isComplementaryAreaVisible');
if (!isComplementaryAreaVisible) {
registry.dispatch(external_wp_preferences_namespaceObject.store).set(scope, 'isComplementaryAreaVisible', true);
}
dispatch({
type: 'ENABLE_COMPLEMENTARY_AREA',
scope,
area
});
};
/**
* Disable the complementary area.
*
* @param {string} scope Complementary area scope.
*/
const disableComplementaryArea = scope => _ref2 => {
let {
registry
} = _ref2;
const isComplementaryAreaVisible = registry.select(external_wp_preferences_namespaceObject.store).get(scope, 'isComplementaryAreaVisible');
if (isComplementaryAreaVisible) {
registry.dispatch(external_wp_preferences_namespaceObject.store).set(scope, 'isComplementaryAreaVisible', false);
}
};
/**
* Pins an item.
*
* @param {string} scope Item scope.
* @param {string} item Item identifier.
*
* @return {Object} Action object.
*/
const pinItem = (scope, item) => _ref3 => {
let {
registry
} = _ref3;
// Return early if there's no item.
if (!item) {
return;
}
const pinnedItems = registry.select(external_wp_preferences_namespaceObject.store).get(scope, 'pinnedItems'); // The item is already pinned, there's nothing to do.
if ((pinnedItems === null || pinnedItems === void 0 ? void 0 : pinnedItems[item]) === true) {
return;
}
registry.dispatch(external_wp_preferences_namespaceObject.store).set(scope, 'pinnedItems', { ...pinnedItems,
[item]: true
});
};
/**
* Unpins an item.
*
* @param {string} scope Item scope.
* @param {string} item Item identifier.
*/
const unpinItem = (scope, item) => _ref4 => {
let {
registry
} = _ref4;
// Return early if there's no item.
if (!item) {
return;
}
const pinnedItems = registry.select(external_wp_preferences_namespaceObject.store).get(scope, 'pinnedItems');
registry.dispatch(external_wp_preferences_namespaceObject.store).set(scope, 'pinnedItems', { ...pinnedItems,
[item]: false
});
};
/**
* Returns an action object used in signalling that a feature should be toggled.
*
* @param {string} scope The feature scope (e.g. core/edit-post).
* @param {string} featureName The feature name.
*/
function toggleFeature(scope, featureName) {
return function (_ref5) {
let {
registry
} = _ref5;
external_wp_deprecated_default()(`dispatch( 'core/interface' ).toggleFeature`, {
since: '6.0',
alternative: `dispatch( 'core/preferences' ).toggle`
});
registry.dispatch(external_wp_preferences_namespaceObject.store).toggle(scope, featureName);
};
}
/**
* Returns an action object used in signalling that a feature should be set to
* a true or false value
*
* @param {string} scope The feature scope (e.g. core/edit-post).
* @param {string} featureName The feature name.
* @param {boolean} value The value to set.
*
* @return {Object} Action object.
*/
function setFeatureValue(scope, featureName, value) {
return function (_ref6) {
let {
registry
} = _ref6;
external_wp_deprecated_default()(`dispatch( 'core/interface' ).setFeatureValue`, {
since: '6.0',
alternative: `dispatch( 'core/preferences' ).set`
});
registry.dispatch(external_wp_preferences_namespaceObject.store).set(scope, featureName, !!value);
};
}
/**
* Returns an action object used in signalling that defaults should be set for features.
*
* @param {string} scope The feature scope (e.g. core/edit-post).
* @param {Object<string, boolean>} defaults A key/value map of feature names to values.
*
* @return {Object} Action object.
*/
function setFeatureDefaults(scope, defaults) {
return function (_ref7) {
let {
registry
} = _ref7;
external_wp_deprecated_default()(`dispatch( 'core/interface' ).setFeatureDefaults`, {
since: '6.0',
alternative: `dispatch( 'core/preferences' ).setDefaults`
});
registry.dispatch(external_wp_preferences_namespaceObject.store).setDefaults(scope, defaults);
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/store/selectors.js
/**
* WordPress dependencies
*/
/**
* Returns the complementary area that is active in a given scope.
*
* @param {Object} state Global application state.
* @param {string} scope Item scope.
*
* @return {string | null | undefined} The complementary area that is active in the given scope.
*/
const getActiveComplementaryArea = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (state, scope) => {
var _state$complementaryA;
const isComplementaryAreaVisible = select(external_wp_preferences_namespaceObject.store).get(scope, 'isComplementaryAreaVisible'); // Return `undefined` to indicate that the user has never toggled
// visibility, this is the vanilla default. Other code relies on this
// nuance in the return value.
if (isComplementaryAreaVisible === undefined) {
return undefined;
} // Return `null` to indicate the user hid the complementary area.
if (!isComplementaryAreaVisible) {
return null;
}
return state === null || state === void 0 ? void 0 : (_state$complementaryA = state.complementaryAreas) === null || _state$complementaryA === void 0 ? void 0 : _state$complementaryA[scope];
});
/**
* Returns a boolean indicating if an item is pinned or not.
*
* @param {Object} state Global application state.
* @param {string} scope Scope.
* @param {string} item Item to check.
*
* @return {boolean} True if the item is pinned and false otherwise.
*/
const isItemPinned = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (state, scope, item) => {
var _pinnedItems$item;
const pinnedItems = select(external_wp_preferences_namespaceObject.store).get(scope, 'pinnedItems');
return (_pinnedItems$item = pinnedItems === null || pinnedItems === void 0 ? void 0 : pinnedItems[item]) !== null && _pinnedItems$item !== void 0 ? _pinnedItems$item : true;
});
/**
* Returns a boolean indicating whether a feature is active for a particular
* scope.
*
* @param {Object} state The store state.
* @param {string} scope The scope of the feature (e.g. core/edit-post).
* @param {string} featureName The name of the feature.
*
* @return {boolean} Is the feature enabled?
*/
const isFeatureActive = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (state, scope, featureName) => {
external_wp_deprecated_default()(`select( 'core/interface' ).isFeatureActive( scope, featureName )`, {
since: '6.0',
alternative: `select( 'core/preferences' ).get( scope, featureName )`
});
return !!select(external_wp_preferences_namespaceObject.store).get(scope, featureName);
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/store/reducer.js
/**
* WordPress dependencies
*/
function complementaryAreas() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'SET_DEFAULT_COMPLEMENTARY_AREA':
{
const {
scope,
area
} = action; // If there's already an area, don't overwrite it.
if (state[scope]) {
return state;
}
return { ...state,
[scope]: area
};
}
case 'ENABLE_COMPLEMENTARY_AREA':
{
const {
scope,
area
} = action;
return { ...state,
[scope]: area
};
}
}
return state;
}
/* harmony default export */ var store_reducer = ((0,external_wp_data_namespaceObject.combineReducers)({
complementaryAreas
}));
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/store/constants.js
/**
* The identifier for the data store.
*
* @type {string}
*/
const constants_STORE_NAME = 'core/interface';
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/store/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Store definition for the interface namespace.
*
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/data/README.md#createReduxStore
*
* @type {Object}
*/
const store_store = (0,external_wp_data_namespaceObject.createReduxStore)(constants_STORE_NAME, {
reducer: store_reducer,
actions: store_actions_namespaceObject,
selectors: store_selectors_namespaceObject
}); // 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.register)(store_store);
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/index.js
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/components/keyboard-shortcut-help-modal/config.js
/**
* WordPress dependencies
*/
const textFormattingShortcuts = [{
keyCombination: {
modifier: 'primary',
character: 'b'
},
description: (0,external_wp_i18n_namespaceObject.__)('Make the selected text bold.')
}, {
keyCombination: {
modifier: 'primary',
character: 'i'
},
description: (0,external_wp_i18n_namespaceObject.__)('Make the selected text italic.')
}, {
keyCombination: {
modifier: 'primary',
character: 'k'
},
description: (0,external_wp_i18n_namespaceObject.__)('Convert the selected text into a link.')
}, {
keyCombination: {
modifier: 'primaryShift',
character: 'k'
},
description: (0,external_wp_i18n_namespaceObject.__)('Remove a link.')
}, {
keyCombination: {
character: '[['
},
description: (0,external_wp_i18n_namespaceObject.__)('Insert a link to a post or page.')
}, {
keyCombination: {
modifier: 'primary',
character: 'u'
},
description: (0,external_wp_i18n_namespaceObject.__)('Underline the selected text.')
}, {
keyCombination: {
modifier: 'access',
character: 'd'
},
description: (0,external_wp_i18n_namespaceObject.__)('Strikethrough the selected text.')
}, {
keyCombination: {
modifier: 'access',
character: 'x'
},
description: (0,external_wp_i18n_namespaceObject.__)('Make the selected text inline code.')
}];
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/components/keyboard-shortcut-help-modal/shortcut.js
/**
* WordPress dependencies
*/
function KeyCombination(_ref) {
let {
keyCombination,
forceAriaLabel
} = _ref;
const shortcut = keyCombination.modifier ? external_wp_keycodes_namespaceObject.displayShortcutList[keyCombination.modifier](keyCombination.character) : keyCombination.character;
const ariaLabel = keyCombination.modifier ? external_wp_keycodes_namespaceObject.shortcutAriaLabel[keyCombination.modifier](keyCombination.character) : keyCombination.character;
return (0,external_wp_element_namespaceObject.createElement)("kbd", {
className: "customize-widgets-keyboard-shortcut-help-modal__shortcut-key-combination",
"aria-label": forceAriaLabel || ariaLabel
}, (Array.isArray(shortcut) ? shortcut : [shortcut]).map((character, index) => {
if (character === '+') {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, {
key: index
}, character);
}
return (0,external_wp_element_namespaceObject.createElement)("kbd", {
key: index,
className: "customize-widgets-keyboard-shortcut-help-modal__shortcut-key"
}, character);
}));
}
function Shortcut(_ref2) {
let {
description,
keyCombination,
aliases = [],
ariaLabel
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "customize-widgets-keyboard-shortcut-help-modal__shortcut-description"
}, description), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "customize-widgets-keyboard-shortcut-help-modal__shortcut-term"
}, (0,external_wp_element_namespaceObject.createElement)(KeyCombination, {
keyCombination: keyCombination,
forceAriaLabel: ariaLabel
}), aliases.map((alias, index) => (0,external_wp_element_namespaceObject.createElement)(KeyCombination, {
keyCombination: alias,
forceAriaLabel: ariaLabel,
key: index
}))));
}
/* harmony default export */ var keyboard_shortcut_help_modal_shortcut = (Shortcut);
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/components/keyboard-shortcut-help-modal/dynamic-shortcut.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function DynamicShortcut(_ref) {
let {
name
} = _ref;
const {
keyCombination,
description,
aliases
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getShortcutKeyCombination,
getShortcutDescription,
getShortcutAliases
} = select(external_wp_keyboardShortcuts_namespaceObject.store);
return {
keyCombination: getShortcutKeyCombination(name),
aliases: getShortcutAliases(name),
description: getShortcutDescription(name)
};
}, [name]);
if (!keyCombination) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(keyboard_shortcut_help_modal_shortcut, {
keyCombination: keyCombination,
description: description,
aliases: aliases
});
}
/* harmony default export */ var dynamic_shortcut = (DynamicShortcut);
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/components/keyboard-shortcut-help-modal/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const ShortcutList = _ref => {
let {
shortcuts
} = _ref;
return (
/*
* Disable reason: The `list` ARIA role is redundant but
* Safari+VoiceOver won't announce the list otherwise.
*/
/* eslint-disable jsx-a11y/no-redundant-roles */
(0,external_wp_element_namespaceObject.createElement)("ul", {
className: "customize-widgets-keyboard-shortcut-help-modal__shortcut-list",
role: "list"
}, shortcuts.map((shortcut, index) => (0,external_wp_element_namespaceObject.createElement)("li", {
className: "customize-widgets-keyboard-shortcut-help-modal__shortcut",
key: index
}, typeof shortcut === 'string' ? (0,external_wp_element_namespaceObject.createElement)(dynamic_shortcut, {
name: shortcut
}) : (0,external_wp_element_namespaceObject.createElement)(keyboard_shortcut_help_modal_shortcut, shortcut))))
/* eslint-enable jsx-a11y/no-redundant-roles */
);
};
const ShortcutSection = _ref2 => {
let {
title,
shortcuts,
className
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)("section", {
className: classnames_default()('customize-widgets-keyboard-shortcut-help-modal__section', className)
}, !!title && (0,external_wp_element_namespaceObject.createElement)("h2", {
className: "customize-widgets-keyboard-shortcut-help-modal__section-title"
}, title), (0,external_wp_element_namespaceObject.createElement)(ShortcutList, {
shortcuts: shortcuts
}));
};
const ShortcutCategorySection = _ref3 => {
let {
title,
categoryName,
additionalShortcuts = []
} = _ref3;
const categoryShortcuts = (0,external_wp_data_namespaceObject.useSelect)(select => {
return select(external_wp_keyboardShortcuts_namespaceObject.store).getCategoryShortcuts(categoryName);
}, [categoryName]);
return (0,external_wp_element_namespaceObject.createElement)(ShortcutSection, {
title: title,
shortcuts: categoryShortcuts.concat(additionalShortcuts)
});
};
function KeyboardShortcutHelpModal(_ref4) {
let {
isModalActive,
toggleModal
} = _ref4;
const {
registerShortcut
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_keyboardShortcuts_namespaceObject.store);
registerShortcut({
name: 'core/customize-widgets/keyboard-shortcuts',
category: 'main',
description: (0,external_wp_i18n_namespaceObject.__)('Display these keyboard shortcuts.'),
keyCombination: {
modifier: 'access',
character: 'h'
}
});
(0,external_wp_keyboardShortcuts_namespaceObject.useShortcut)('core/customize-widgets/keyboard-shortcuts', toggleModal);
if (!isModalActive) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Modal, {
className: "customize-widgets-keyboard-shortcut-help-modal",
title: (0,external_wp_i18n_namespaceObject.__)('Keyboard shortcuts'),
onRequestClose: toggleModal
}, (0,external_wp_element_namespaceObject.createElement)(ShortcutSection, {
className: "customize-widgets-keyboard-shortcut-help-modal__main-shortcuts",
shortcuts: ['core/customize-widgets/keyboard-shortcuts']
}), (0,external_wp_element_namespaceObject.createElement)(ShortcutCategorySection, {
title: (0,external_wp_i18n_namespaceObject.__)('Global shortcuts'),
categoryName: "global"
}), (0,external_wp_element_namespaceObject.createElement)(ShortcutCategorySection, {
title: (0,external_wp_i18n_namespaceObject.__)('Selection shortcuts'),
categoryName: "selection"
}), (0,external_wp_element_namespaceObject.createElement)(ShortcutCategorySection, {
title: (0,external_wp_i18n_namespaceObject.__)('Block shortcuts'),
categoryName: "block",
additionalShortcuts: [{
keyCombination: {
character: '/'
},
description: (0,external_wp_i18n_namespaceObject.__)('Change the block type after adding a new paragraph.'),
/* translators: The forward-slash character. e.g. '/'. */
ariaLabel: (0,external_wp_i18n_namespaceObject.__)('Forward-slash')
}]
}), (0,external_wp_element_namespaceObject.createElement)(ShortcutSection, {
title: (0,external_wp_i18n_namespaceObject.__)('Text formatting'),
shortcuts: textFormattingShortcuts
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/components/more-menu/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function MoreMenu() {
const [isKeyboardShortcutsModalActive, setIsKeyboardShortcutsModalVisible] = (0,external_wp_element_namespaceObject.useState)(false);
const toggleKeyboardShortcutsModal = () => setIsKeyboardShortcutsModalVisible(!isKeyboardShortcutsModalActive);
(0,external_wp_keyboardShortcuts_namespaceObject.useShortcut)('core/customize-widgets/keyboard-shortcuts', toggleKeyboardShortcutsModal);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(MoreMenuDropdown, {
as: external_wp_components_namespaceObject.ToolbarDropdownMenu
}, () => (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, {
label: (0,external_wp_i18n_namespaceObject._x)('View', 'noun')
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_preferences_namespaceObject.PreferenceToggleMenuItem, {
scope: "core/customize-widgets",
name: "fixedToolbar",
label: (0,external_wp_i18n_namespaceObject.__)('Top toolbar'),
info: (0,external_wp_i18n_namespaceObject.__)('Access all block and document tools in a single place'),
messageActivated: (0,external_wp_i18n_namespaceObject.__)('Top toolbar activated'),
messageDeactivated: (0,external_wp_i18n_namespaceObject.__)('Top toolbar deactivated')
})), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, {
label: (0,external_wp_i18n_namespaceObject.__)('Tools')
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
onClick: () => {
setIsKeyboardShortcutsModalVisible(true);
},
shortcut: external_wp_keycodes_namespaceObject.displayShortcut.access('h')
}, (0,external_wp_i18n_namespaceObject.__)('Keyboard shortcuts')), (0,external_wp_element_namespaceObject.createElement)(external_wp_preferences_namespaceObject.PreferenceToggleMenuItem, {
scope: "core/customize-widgets",
name: "welcomeGuide",
label: (0,external_wp_i18n_namespaceObject.__)('Welcome Guide')
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
role: "menuitem",
icon: library_external,
href: (0,external_wp_i18n_namespaceObject.__)('https://wordpress.org/support/article/block-based-widgets-editor/'),
target: "_blank",
rel: "noopener noreferrer"
}, (0,external_wp_i18n_namespaceObject.__)('Help'), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.VisuallyHidden, {
as: "span"
},
/* translators: accessibility text */
(0,external_wp_i18n_namespaceObject.__)('(opens in a new tab)')))), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, {
label: (0,external_wp_i18n_namespaceObject.__)('Preferences')
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_preferences_namespaceObject.PreferenceToggleMenuItem, {
scope: "core/customize-widgets",
name: "keepCaretInsideBlock",
label: (0,external_wp_i18n_namespaceObject.__)('Contain text cursor inside block'),
info: (0,external_wp_i18n_namespaceObject.__)('Aids screen readers by stopping text caret from leaving blocks.'),
messageActivated: (0,external_wp_i18n_namespaceObject.__)('Contain text cursor inside block activated'),
messageDeactivated: (0,external_wp_i18n_namespaceObject.__)('Contain text cursor inside block deactivated')
})))), (0,external_wp_element_namespaceObject.createElement)(KeyboardShortcutHelpModal, {
isModalActive: isKeyboardShortcutsModalActive,
toggleModal: toggleKeyboardShortcutsModal
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/components/header/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function Header(_ref) {
let {
sidebar,
inserter,
isInserterOpened,
setIsInserterOpened,
isFixedToolbarActive
} = _ref;
const [[hasUndo, hasRedo], setUndoRedo] = (0,external_wp_element_namespaceObject.useState)([sidebar.hasUndo(), sidebar.hasRedo()]);
const shortcut = (0,external_wp_keycodes_namespaceObject.isAppleOS)() ? external_wp_keycodes_namespaceObject.displayShortcut.primaryShift('z') : external_wp_keycodes_namespaceObject.displayShortcut.primary('y');
(0,external_wp_element_namespaceObject.useEffect)(() => {
return sidebar.subscribeHistory(() => {
setUndoRedo([sidebar.hasUndo(), sidebar.hasRedo()]);
});
}, [sidebar]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('customize-widgets-header', {
'is-fixed-toolbar-active': isFixedToolbarActive
})
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.NavigableToolbar, {
className: "customize-widgets-header-toolbar",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Document tools')
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
icon: !(0,external_wp_i18n_namespaceObject.isRTL)() ? library_undo : library_redo
/* translators: button label text should, if possible, be under 16 characters. */
,
label: (0,external_wp_i18n_namespaceObject.__)('Undo'),
shortcut: external_wp_keycodes_namespaceObject.displayShortcut.primary('z') // If there are no undo levels we don't want to actually disable this
// button, because it will remove focus for keyboard users.
// See: https://github.com/WordPress/gutenberg/issues/3486
,
"aria-disabled": !hasUndo,
onClick: sidebar.undo,
className: "customize-widgets-editor-history-button undo-button"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
icon: !(0,external_wp_i18n_namespaceObject.isRTL)() ? library_redo : library_undo
/* translators: button label text should, if possible, be under 16 characters. */
,
label: (0,external_wp_i18n_namespaceObject.__)('Redo'),
shortcut: shortcut // If there are no undo levels we don't want to actually disable this
// button, because it will remove focus for keyboard users.
// See: https://github.com/WordPress/gutenberg/issues/3486
,
"aria-disabled": !hasRedo,
onClick: sidebar.redo,
className: "customize-widgets-editor-history-button redo-button"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
className: "customize-widgets-header-toolbar__inserter-toggle",
isPressed: isInserterOpened,
variant: "primary",
icon: library_plus,
label: (0,external_wp_i18n_namespaceObject._x)('Add block', 'Generic label for block inserter button'),
onClick: () => {
setIsInserterOpened(isOpen => !isOpen);
}
}), (0,external_wp_element_namespaceObject.createElement)(MoreMenu, null))), (0,external_wp_element_namespaceObject.createPortal)((0,external_wp_element_namespaceObject.createElement)(components_inserter, {
setIsOpened: setIsInserterOpened
}), inserter.contentContainer[0]));
}
/* harmony default export */ var header = (Header);
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/components/inserter/use-inserter.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useInserter(inserter) {
const isInserterOpened = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).isInserterOpened(), []);
const {
setIsInserterOpened
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (isInserterOpened) {
inserter.open();
} else {
inserter.close();
}
}, [inserter, isInserterOpened]);
return [isInserterOpened, (0,external_wp_element_namespaceObject.useCallback)(updater => {
let isOpen = updater;
if (typeof updater === 'function') {
isOpen = updater((0,external_wp_data_namespaceObject.select)(store).isInserterOpened());
}
setIsInserterOpened(isOpen);
}, [setIsInserterOpened])];
}
// EXTERNAL MODULE: ./node_modules/fast-deep-equal/es6/index.js
var es6 = __webpack_require__(5619);
var es6_default = /*#__PURE__*/__webpack_require__.n(es6);
;// CONCATENATED MODULE: external ["wp","isShallowEqual"]
var external_wp_isShallowEqual_namespaceObject = window["wp"]["isShallowEqual"];
var external_wp_isShallowEqual_default = /*#__PURE__*/__webpack_require__.n(external_wp_isShallowEqual_namespaceObject);
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/utils.js
// @ts-check
/**
* WordPress dependencies
*/
/**
* Convert settingId to widgetId.
*
* @param {string} settingId The setting id.
* @return {string} The widget id.
*/
function settingIdToWidgetId(settingId) {
const matches = settingId.match(/^widget_(.+)(?:\[(\d+)\])$/);
if (matches) {
const idBase = matches[1];
const number = parseInt(matches[2], 10);
return `${idBase}-${number}`;
}
return settingId;
}
/**
* Transform a block to a customizable widget.
*
* @param {WPBlock} block The block to be transformed from.
* @param {Object} existingWidget The widget to be extended from.
* @return {Object} The transformed widget.
*/
function blockToWidget(block) {
let existingWidget = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
let widget;
const isValidLegacyWidgetBlock = block.name === 'core/legacy-widget' && (block.attributes.id || block.attributes.instance);
if (isValidLegacyWidgetBlock) {
if (block.attributes.id) {
// Widget that does not extend WP_Widget.
widget = {
id: block.attributes.id
};
} else {
const {
encoded,
hash,
raw,
...rest
} = block.attributes.instance; // Widget that extends WP_Widget.
widget = {
idBase: block.attributes.idBase,
instance: { ...(existingWidget === null || existingWidget === void 0 ? void 0 : existingWidget.instance),
// Required only for the customizer.
is_widget_customizer_js_value: true,
encoded_serialized_instance: encoded,
instance_hash_key: hash,
raw_instance: raw,
...rest
}
};
}
} else {
const instance = {
content: (0,external_wp_blocks_namespaceObject.serialize)(block)
};
widget = {
idBase: 'block',
widgetClass: 'WP_Widget_Block',
instance: {
raw_instance: instance
}
};
}
const {
form,
rendered,
...restExistingWidget
} = existingWidget || {};
return { ...restExistingWidget,
...widget
};
}
/**
* Transform a widget to a block.
*
* @param {Object} widget The widget to be transformed from.
* @param {string} widget.id The widget id.
* @param {string} widget.idBase The id base of the widget.
* @param {number} widget.number The number/index of the widget.
* @param {Object} widget.instance The instance of the widget.
* @return {WPBlock} The transformed block.
*/
function widgetToBlock(_ref) {
let {
id,
idBase,
number,
instance
} = _ref;
let block;
const {
encoded_serialized_instance: encoded,
instance_hash_key: hash,
raw_instance: raw,
...rest
} = instance;
if (idBase === 'block') {
var _raw$content;
const parsedBlocks = (0,external_wp_blocks_namespaceObject.parse)((_raw$content = raw.content) !== null && _raw$content !== void 0 ? _raw$content : '', {
__unstableSkipAutop: true
});
block = parsedBlocks.length ? parsedBlocks[0] : (0,external_wp_blocks_namespaceObject.createBlock)('core/paragraph', {});
} else if (number) {
// Widget that extends WP_Widget.
block = (0,external_wp_blocks_namespaceObject.createBlock)('core/legacy-widget', {
idBase,
instance: {
encoded,
hash,
raw,
...rest
}
});
} else {
// Widget that does not extend WP_Widget.
block = (0,external_wp_blocks_namespaceObject.createBlock)('core/legacy-widget', {
id
});
}
return (0,external_wp_widgets_namespaceObject.addWidgetIdToBlock)(block, id);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/components/sidebar-block-editor/use-sidebar-block-editor.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function widgetsToBlocks(widgets) {
return widgets.map(widget => widgetToBlock(widget));
}
function useSidebarBlockEditor(sidebar) {
const [blocks, setBlocks] = (0,external_wp_element_namespaceObject.useState)(() => widgetsToBlocks(sidebar.getWidgets()));
(0,external_wp_element_namespaceObject.useEffect)(() => {
return sidebar.subscribe((prevWidgets, nextWidgets) => {
setBlocks(prevBlocks => {
const prevWidgetsMap = new Map(prevWidgets.map(widget => [widget.id, widget]));
const prevBlocksMap = new Map(prevBlocks.map(block => [(0,external_wp_widgets_namespaceObject.getWidgetIdFromBlock)(block), block]));
const nextBlocks = nextWidgets.map(nextWidget => {
const prevWidget = prevWidgetsMap.get(nextWidget.id); // Bail out updates.
if (prevWidget && prevWidget === nextWidget) {
return prevBlocksMap.get(nextWidget.id);
}
return widgetToBlock(nextWidget);
}); // Bail out updates.
if (external_wp_isShallowEqual_default()(prevBlocks, nextBlocks)) {
return prevBlocks;
}
return nextBlocks;
});
});
}, [sidebar]);
const onChangeBlocks = (0,external_wp_element_namespaceObject.useCallback)(nextBlocks => {
setBlocks(prevBlocks => {
if (external_wp_isShallowEqual_default()(prevBlocks, nextBlocks)) {
return prevBlocks;
}
const prevBlocksMap = new Map(prevBlocks.map(block => [(0,external_wp_widgets_namespaceObject.getWidgetIdFromBlock)(block), block]));
const nextWidgets = nextBlocks.map(nextBlock => {
const widgetId = (0,external_wp_widgets_namespaceObject.getWidgetIdFromBlock)(nextBlock); // Update existing widgets.
if (widgetId && prevBlocksMap.has(widgetId)) {
const prevBlock = prevBlocksMap.get(widgetId);
const prevWidget = sidebar.getWidget(widgetId); // Bail out updates by returning the previous widgets.
// Deep equality is necessary until the block editor's internals changes.
if (es6_default()(nextBlock, prevBlock) && prevWidget) {
return prevWidget;
}
return blockToWidget(nextBlock, prevWidget);
} // Add a new widget.
return blockToWidget(nextBlock);
}); // Bail out updates if the updated widgets are the same.
if (external_wp_isShallowEqual_default()(sidebar.getWidgets(), nextWidgets)) {
return prevBlocks;
}
const addedWidgetIds = sidebar.setWidgets(nextWidgets);
return nextBlocks.reduce((updatedNextBlocks, nextBlock, index) => {
const addedWidgetId = addedWidgetIds[index];
if (addedWidgetId !== null) {
// Only create a new instance if necessary to prevent
// the whole editor from re-rendering on every edit.
if (updatedNextBlocks === nextBlocks) {
updatedNextBlocks = nextBlocks.slice();
}
updatedNextBlocks[index] = (0,external_wp_widgets_namespaceObject.addWidgetIdToBlock)(nextBlock, addedWidgetId);
}
return updatedNextBlocks;
}, nextBlocks);
});
}, [sidebar]);
return [blocks, onChangeBlocks, onChangeBlocks];
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/components/focus-control/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const FocusControlContext = (0,external_wp_element_namespaceObject.createContext)();
function FocusControl(_ref) {
let {
api,
sidebarControls,
children
} = _ref;
const [focusedWidgetIdRef, setFocusedWidgetIdRef] = (0,external_wp_element_namespaceObject.useState)({
current: null
});
const focusWidget = (0,external_wp_element_namespaceObject.useCallback)(widgetId => {
for (const sidebarControl of sidebarControls) {
const widgets = sidebarControl.setting.get();
if (widgets.includes(widgetId)) {
sidebarControl.sectionInstance.expand({
// Schedule it after the complete callback so that
// it won't be overridden by the "Back" button focus.
completeCallback() {
// Create a "ref-like" object every time to ensure
// the same widget id can also triggers the focus control.
setFocusedWidgetIdRef({
current: widgetId
});
}
});
break;
}
}
}, [sidebarControls]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
function handleFocus(settingId) {
const widgetId = settingIdToWidgetId(settingId);
focusWidget(widgetId);
}
function handleReady() {
api.previewer.preview.bind('focus-control-for-setting', handleFocus);
}
api.previewer.bind('ready', handleReady);
return () => {
api.previewer.unbind('ready', handleReady);
api.previewer.preview.unbind('focus-control-for-setting', handleFocus);
};
}, [api, focusWidget]);
const context = (0,external_wp_element_namespaceObject.useMemo)(() => [focusedWidgetIdRef, focusWidget], [focusedWidgetIdRef, focusWidget]);
return (0,external_wp_element_namespaceObject.createElement)(FocusControlContext.Provider, {
value: context
}, children);
}
const useFocusControl = () => (0,external_wp_element_namespaceObject.useContext)(FocusControlContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/components/focus-control/use-blocks-focus-control.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useBlocksFocusControl(blocks) {
const {
selectBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_blockEditor_namespaceObject.store);
const [focusedWidgetIdRef] = useFocusControl();
const blocksRef = (0,external_wp_element_namespaceObject.useRef)(blocks);
(0,external_wp_element_namespaceObject.useEffect)(() => {
blocksRef.current = blocks;
}, [blocks]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (focusedWidgetIdRef.current) {
const focusedBlock = blocksRef.current.find(block => (0,external_wp_widgets_namespaceObject.getWidgetIdFromBlock)(block) === focusedWidgetIdRef.current);
if (focusedBlock) {
selectBlock(focusedBlock.clientId); // If the block is already being selected, the DOM node won't
// get focused again automatically.
// We select the DOM and focus it manually here.
const blockNode = document.querySelector(`[data-block="${focusedBlock.clientId}"]`);
blockNode === null || blockNode === void 0 ? void 0 : blockNode.focus();
}
}
}, [focusedWidgetIdRef, selectBlock]);
}
;// CONCATENATED MODULE: external ["wp","privateApis"]
var external_wp_privateApis_namespaceObject = window["wp"]["privateApis"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/private-apis.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/customize-widgets');
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/components/sidebar-block-editor/sidebar-editor-provider.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const {
ExperimentalBlockEditorProvider
} = unlock(external_wp_blockEditor_namespaceObject.privateApis);
function SidebarEditorProvider(_ref) {
let {
sidebar,
settings,
children
} = _ref;
const [blocks, onInput, onChange] = useSidebarBlockEditor(sidebar);
useBlocksFocusControl(blocks);
return (0,external_wp_element_namespaceObject.createElement)(ExperimentalBlockEditorProvider, {
value: blocks,
onInput: onInput,
onChange: onChange,
settings: settings,
useSubRegistry: false
}, children);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/components/welcome-guide/index.js
/**
* WordPress dependencies
*/
function WelcomeGuide(_ref) {
let {
sidebar
} = _ref;
const {
toggle
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_preferences_namespaceObject.store);
const isEntirelyBlockWidgets = sidebar.getWidgets().every(widget => widget.id.startsWith('block-'));
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "customize-widgets-welcome-guide"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "customize-widgets-welcome-guide__image__wrapper"
}, (0,external_wp_element_namespaceObject.createElement)("picture", null, (0,external_wp_element_namespaceObject.createElement)("source", {
srcSet: "https://s.w.org/images/block-editor/welcome-editor.svg",
media: "(prefers-reduced-motion: reduce)"
}), (0,external_wp_element_namespaceObject.createElement)("img", {
className: "customize-widgets-welcome-guide__image",
src: "https://s.w.org/images/block-editor/welcome-editor.gif",
width: "312",
height: "240",
alt: ""
}))), (0,external_wp_element_namespaceObject.createElement)("h1", {
className: "customize-widgets-welcome-guide__heading"
}, (0,external_wp_i18n_namespaceObject.__)('Welcome to block Widgets')), (0,external_wp_element_namespaceObject.createElement)("p", {
className: "customize-widgets-welcome-guide__text"
}, isEntirelyBlockWidgets ? (0,external_wp_i18n_namespaceObject.__)('Your theme provides different “block” areas for you to add and edit content. Try adding a search bar, social icons, or other types of blocks here and see how they’ll look on your site.') : (0,external_wp_i18n_namespaceObject.__)('You can now add any block to your site’s widget areas. Don’t worry, all of your favorite widgets still work flawlessly.')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "customize-widgets-welcome-guide__button",
variant: "primary",
onClick: () => toggle('core/customize-widgets', 'welcomeGuide')
}, (0,external_wp_i18n_namespaceObject.__)('Got it')), (0,external_wp_element_namespaceObject.createElement)("hr", {
className: "customize-widgets-welcome-guide__separator"
}), !isEntirelyBlockWidgets && (0,external_wp_element_namespaceObject.createElement)("p", {
className: "customize-widgets-welcome-guide__more-info"
}, (0,external_wp_i18n_namespaceObject.__)('Want to stick with the old widgets?'), (0,external_wp_element_namespaceObject.createElement)("br", null), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ExternalLink, {
href: (0,external_wp_i18n_namespaceObject.__)('https://wordpress.org/plugins/classic-widgets/')
}, (0,external_wp_i18n_namespaceObject.__)('Get the Classic Widgets plugin.'))), (0,external_wp_element_namespaceObject.createElement)("p", {
className: "customize-widgets-welcome-guide__more-info"
}, (0,external_wp_i18n_namespaceObject.__)('New to the block editor?'), (0,external_wp_element_namespaceObject.createElement)("br", null), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ExternalLink, {
href: (0,external_wp_i18n_namespaceObject.__)('https://wordpress.org/support/article/wordpress-editor/')
}, (0,external_wp_i18n_namespaceObject.__)("Here's a detailed guide."))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/components/keyboard-shortcuts/index.js
/**
* WordPress dependencies
*/
function KeyboardShortcuts(_ref) {
let {
undo,
redo,
save
} = _ref;
(0,external_wp_keyboardShortcuts_namespaceObject.useShortcut)('core/customize-widgets/undo', event => {
undo();
event.preventDefault();
});
(0,external_wp_keyboardShortcuts_namespaceObject.useShortcut)('core/customize-widgets/redo', event => {
redo();
event.preventDefault();
});
(0,external_wp_keyboardShortcuts_namespaceObject.useShortcut)('core/customize-widgets/save', event => {
event.preventDefault();
save();
});
return null;
}
function KeyboardShortcutsRegister() {
const {
registerShortcut,
unregisterShortcut
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_keyboardShortcuts_namespaceObject.store);
(0,external_wp_element_namespaceObject.useEffect)(() => {
registerShortcut({
name: 'core/customize-widgets/undo',
category: 'global',
description: (0,external_wp_i18n_namespaceObject.__)('Undo your last changes.'),
keyCombination: {
modifier: 'primary',
character: 'z'
}
});
registerShortcut({
name: 'core/customize-widgets/redo',
category: 'global',
description: (0,external_wp_i18n_namespaceObject.__)('Redo your last undo.'),
keyCombination: {
modifier: 'primaryShift',
character: 'z'
},
// Disable on Apple OS because it conflicts with the browser's
// history shortcut. It's a fine alias for both Windows and Linux.
// Since there's no conflict for Ctrl+Shift+Z on both Windows and
// Linux, we keep it as the default for consistency.
aliases: (0,external_wp_keycodes_namespaceObject.isAppleOS)() ? [] : [{
modifier: 'primary',
character: 'y'
}]
});
registerShortcut({
name: 'core/customize-widgets/save',
category: 'global',
description: (0,external_wp_i18n_namespaceObject.__)('Save your changes.'),
keyCombination: {
modifier: 'primary',
character: 's'
}
});
return () => {
unregisterShortcut('core/customize-widgets/undo');
unregisterShortcut('core/customize-widgets/redo');
unregisterShortcut('core/customize-widgets/save');
};
}, [registerShortcut]);
return null;
}
KeyboardShortcuts.Register = KeyboardShortcutsRegister;
/* harmony default export */ var keyboard_shortcuts = (KeyboardShortcuts);
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/components/block-appender/index.js
/**
* WordPress dependencies
*/
function BlockAppender(props) {
const ref = (0,external_wp_element_namespaceObject.useRef)();
const isBlocksListEmpty = (0,external_wp_data_namespaceObject.useSelect)(select => select(external_wp_blockEditor_namespaceObject.store).getBlockCount() === 0); // Move the focus to the block appender to prevent focus from
// being lost when emptying the widget area.
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (isBlocksListEmpty && ref.current) {
const {
ownerDocument
} = ref.current;
if (!ownerDocument.activeElement || ownerDocument.activeElement === ownerDocument.body) {
ref.current.focus();
}
}
}, [isBlocksListEmpty]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.ButtonBlockAppender, _extends({}, props, {
ref: ref
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/components/sidebar-block-editor/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function SidebarBlockEditor(_ref) {
let {
blockEditorSettings,
sidebar,
inserter,
inspector
} = _ref;
const [isInserterOpened, setIsInserterOpened] = useInserter(inserter);
const {
hasUploadPermissions,
isFixedToolbarActive,
keepCaretInsideBlock,
isWelcomeGuideActive
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _select$canUser;
const {
get
} = select(external_wp_preferences_namespaceObject.store);
return {
hasUploadPermissions: (_select$canUser = select(external_wp_coreData_namespaceObject.store).canUser('create', 'media')) !== null && _select$canUser !== void 0 ? _select$canUser : true,
isFixedToolbarActive: !!get('core/customize-widgets', 'fixedToolbar'),
keepCaretInsideBlock: !!get('core/customize-widgets', 'keepCaretInsideBlock'),
isWelcomeGuideActive: !!get('core/customize-widgets', 'welcomeGuide')
};
}, []);
const settings = (0,external_wp_element_namespaceObject.useMemo)(() => {
let mediaUploadBlockEditor;
if (hasUploadPermissions) {
mediaUploadBlockEditor = _ref2 => {
let {
onError,
...argumentsObject
} = _ref2;
(0,external_wp_mediaUtils_namespaceObject.uploadMedia)({
wpAllowedMimeTypes: blockEditorSettings.allowedMimeTypes,
onError: _ref3 => {
let {
message
} = _ref3;
return onError(message);
},
...argumentsObject
});
};
}
return { ...blockEditorSettings,
__experimentalSetIsInserterOpened: setIsInserterOpened,
mediaUpload: mediaUploadBlockEditor,
hasFixedToolbar: isFixedToolbarActive,
keepCaretInsideBlock,
__unstableHasCustomAppender: true
};
}, [hasUploadPermissions, blockEditorSettings, isFixedToolbarActive, keepCaretInsideBlock, setIsInserterOpened]);
if (isWelcomeGuideActive) {
return (0,external_wp_element_namespaceObject.createElement)(WelcomeGuide, {
sidebar: sidebar
});
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockEditorKeyboardShortcuts.Register, null), (0,external_wp_element_namespaceObject.createElement)(keyboard_shortcuts.Register, null), (0,external_wp_element_namespaceObject.createElement)(SidebarEditorProvider, {
sidebar: sidebar,
settings: settings
}, (0,external_wp_element_namespaceObject.createElement)(keyboard_shortcuts, {
undo: sidebar.undo,
redo: sidebar.redo,
save: sidebar.save
}), (0,external_wp_element_namespaceObject.createElement)(header, {
sidebar: sidebar,
inserter: inserter,
isInserterOpened: isInserterOpened,
setIsInserterOpened: setIsInserterOpened,
isFixedToolbarActive: isFixedToolbarActive
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.CopyHandler, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockTools, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.__unstableEditorStyles, {
styles: settings.defaultEditorStyles
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockSelectionClearer, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.WritingFlow, {
className: "editor-styles-wrapper"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.ObserveTyping, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockList, {
renderAppender: BlockAppender
})))))), (0,external_wp_element_namespaceObject.createPortal)( // This is a temporary hack to prevent button component inside <BlockInspector>
// from submitting form when type="button" is not specified.
(0,external_wp_element_namespaceObject.createElement)("form", {
onSubmit: event => event.preventDefault()
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockInspector, null)), inspector.contentContainer[0])), (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.__unstableBlockSettingsMenuFirstItem, null, _ref4 => {
let {
onClose
} = _ref4;
return (0,external_wp_element_namespaceObject.createElement)(block_inspector_button, {
inspector: inspector,
closeMenu: onClose
});
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/components/sidebar-controls/index.js
/**
* WordPress dependencies
*/
const SidebarControlsContext = (0,external_wp_element_namespaceObject.createContext)();
function SidebarControls(_ref) {
let {
sidebarControls,
activeSidebarControl,
children
} = _ref;
const context = (0,external_wp_element_namespaceObject.useMemo)(() => ({
sidebarControls,
activeSidebarControl
}), [sidebarControls, activeSidebarControl]);
return (0,external_wp_element_namespaceObject.createElement)(SidebarControlsContext.Provider, {
value: context
}, children);
}
function useSidebarControls() {
const {
sidebarControls
} = (0,external_wp_element_namespaceObject.useContext)(SidebarControlsContext);
return sidebarControls;
}
function useActiveSidebarControl() {
const {
activeSidebarControl
} = (0,external_wp_element_namespaceObject.useContext)(SidebarControlsContext);
return activeSidebarControl;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/components/customize-widgets/use-clear-selected-block.js
/**
* WordPress dependencies
*/
/**
* We can't just use <BlockSelectionClearer> because the customizer has
* many root nodes rather than just one in the post editor.
* We need to listen to the focus events in all those roots, and also in
* the preview iframe.
* This hook will clear the selected block when focusing outside the editor,
* with a few exceptions:
* 1. Focusing on popovers.
* 2. Focusing on the inspector.
* 3. Focusing on any modals/dialogs.
* These cases are normally triggered by user interactions from the editor,
* not by explicitly focusing outside the editor, hence no need for clearing.
*
* @param {Object} sidebarControl The sidebar control instance.
* @param {Object} popoverRef The ref object of the popover node container.
*/
function useClearSelectedBlock(sidebarControl, popoverRef) {
const {
hasSelectedBlock,
hasMultiSelection
} = (0,external_wp_data_namespaceObject.useSelect)(external_wp_blockEditor_namespaceObject.store);
const {
clearSelectedBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_blockEditor_namespaceObject.store);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (popoverRef.current && sidebarControl) {
const inspector = sidebarControl.inspector;
const container = sidebarControl.container[0];
const ownerDocument = container.ownerDocument;
const ownerWindow = ownerDocument.defaultView;
function handleClearSelectedBlock(element) {
if ( // 1. Make sure there are blocks being selected.
(hasSelectedBlock() || hasMultiSelection()) && // 2. The element should exist in the DOM (not deleted).
element && ownerDocument.contains(element) && // 3. It should also not exist in the container, the popover, nor the dialog.
!container.contains(element) && !popoverRef.current.contains(element) && !element.closest('[role="dialog"]') && // 4. The inspector should not be opened.
!inspector.expanded()) {
clearSelectedBlock();
}
} // Handle mouse down in the same document.
function handleMouseDown(event) {
handleClearSelectedBlock(event.target);
} // Handle focusing outside the current document, like to iframes.
function handleBlur() {
handleClearSelectedBlock(ownerDocument.activeElement);
}
ownerDocument.addEventListener('mousedown', handleMouseDown);
ownerWindow.addEventListener('blur', handleBlur);
return () => {
ownerDocument.removeEventListener('mousedown', handleMouseDown);
ownerWindow.removeEventListener('blur', handleBlur);
};
}
}, [popoverRef, sidebarControl, hasSelectedBlock, hasMultiSelection, clearSelectedBlock]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/components/customize-widgets/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function CustomizeWidgets(_ref) {
let {
api,
sidebarControls,
blockEditorSettings
} = _ref;
const [activeSidebarControl, setActiveSidebarControl] = (0,external_wp_element_namespaceObject.useState)(null);
const parentContainer = document.getElementById('customize-theme-controls');
const popoverRef = (0,external_wp_element_namespaceObject.useRef)();
useClearSelectedBlock(activeSidebarControl, popoverRef);
(0,external_wp_element_namespaceObject.useEffect)(() => {
const unsubscribers = sidebarControls.map(sidebarControl => sidebarControl.subscribe(expanded => {
if (expanded) {
setActiveSidebarControl(sidebarControl);
}
}));
return () => {
unsubscribers.forEach(unsubscriber => unsubscriber());
};
}, [sidebarControls]);
const activeSidebar = activeSidebarControl && (0,external_wp_element_namespaceObject.createPortal)((0,external_wp_element_namespaceObject.createElement)(ErrorBoundary, null, (0,external_wp_element_namespaceObject.createElement)(SidebarBlockEditor, {
key: activeSidebarControl.id,
blockEditorSettings: blockEditorSettings,
sidebar: activeSidebarControl.sidebarAdapter,
inserter: activeSidebarControl.inserter,
inspector: activeSidebarControl.inspector
})), activeSidebarControl.container[0]); // We have to portal this to the parent of both the editor and the inspector,
// so that the popovers will appear above both of them.
const popover = parentContainer && (0,external_wp_element_namespaceObject.createPortal)((0,external_wp_element_namespaceObject.createElement)("div", {
className: "customize-widgets-popover",
ref: popoverRef
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Popover.Slot, null)), parentContainer);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_keyboardShortcuts_namespaceObject.ShortcutProvider, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SlotFillProvider, null, (0,external_wp_element_namespaceObject.createElement)(SidebarControls, {
sidebarControls: sidebarControls,
activeSidebarControl: activeSidebarControl
}, (0,external_wp_element_namespaceObject.createElement)(FocusControl, {
api: api,
sidebarControls: sidebarControls
}, activeSidebar, popover))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/controls/inspector-section.js
function getInspectorSection() {
const {
wp: {
customize
}
} = window;
return class InspectorSection extends customize.Section {
constructor(id, options) {
super(id, options);
this.parentSection = options.parentSection;
this.returnFocusWhenClose = null;
this._isOpen = false;
}
get isOpen() {
return this._isOpen;
}
set isOpen(value) {
this._isOpen = value;
this.triggerActiveCallbacks();
}
ready() {
this.contentContainer[0].classList.add('customize-widgets-layout__inspector');
}
isContextuallyActive() {
return this.isOpen;
}
onChangeExpanded(expanded, args) {
super.onChangeExpanded(expanded, args);
if (this.parentSection && !args.unchanged) {
if (expanded) {
this.parentSection.collapse({
manualTransition: true
});
} else {
this.parentSection.expand({
manualTransition: true,
completeCallback: () => {
// Return focus after finishing the transition.
if (this.returnFocusWhenClose && !this.contentContainer[0].contains(this.returnFocusWhenClose)) {
this.returnFocusWhenClose.focus();
}
}
});
}
}
}
open() {
let {
returnFocusWhenClose
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
this.isOpen = true;
this.returnFocusWhenClose = returnFocusWhenClose;
this.expand({
allowMultiple: true
});
}
close() {
this.collapse({
allowMultiple: true
});
}
collapse(options) {
// Overridden collapse() function. Mostly call the parent collapse(), but also
// move our .isOpen to false.
// Initially, I tried tracking this with onChangeExpanded(), but it doesn't work
// because the block settings sidebar is a layer "on top of" the G editor sidebar.
//
// For example, when closing the block settings sidebar, the G
// editor sidebar would display, and onChangeExpanded in
// inspector-section would run with expanded=true, but I want
// isOpen to be false when the block settings is closed.
this.isOpen = false;
super.collapse(options);
}
triggerActiveCallbacks() {
// Manually fire the callbacks associated with moving this.active
// from false to true. "active" is always true for this section,
// and "isContextuallyActive" reflects if the block settings
// sidebar is currently visible, that is, it has replaced the main
// Gutenberg view.
// The WP customizer only checks ".isContextuallyActive()" when
// ".active" changes values. But our ".active" never changes value.
// The WP customizer never foresaw a section being used a way we
// fit the block settings sidebar into a section. By manually
// triggering the "this.active" callbacks, we force the WP
// customizer to query our .isContextuallyActive() function and
// update its view of our status.
this.active.callbacks.fireWith(this.active, [false, true]);
}
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/controls/sidebar-section.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const getInspectorSectionId = sidebarId => `widgets-inspector-${sidebarId}`;
function getSidebarSection() {
const {
wp: {
customize
}
} = window;
const reduceMotionMediaQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
let isReducedMotion = reduceMotionMediaQuery.matches;
reduceMotionMediaQuery.addEventListener('change', event => {
isReducedMotion = event.matches;
});
return class SidebarSection extends customize.Section {
ready() {
const InspectorSection = getInspectorSection();
this.inspector = new InspectorSection(getInspectorSectionId(this.id), {
title: (0,external_wp_i18n_namespaceObject.__)('Block Settings'),
parentSection: this,
customizeAction: [(0,external_wp_i18n_namespaceObject.__)('Customizing'), (0,external_wp_i18n_namespaceObject.__)('Widgets'), this.params.title].join(' ▸ ')
});
customize.section.add(this.inspector);
this.contentContainer[0].classList.add('customize-widgets__sidebar-section');
}
hasSubSectionOpened() {
return this.inspector.expanded();
}
onChangeExpanded(expanded, _args) {
const controls = this.controls();
const args = { ..._args,
completeCallback() {
var _args$completeCallbac;
controls.forEach(control => {
var _control$onChangeSect;
(_control$onChangeSect = control.onChangeSectionExpanded) === null || _control$onChangeSect === void 0 ? void 0 : _control$onChangeSect.call(control, expanded, args);
});
(_args$completeCallbac = _args.completeCallback) === null || _args$completeCallbac === void 0 ? void 0 : _args$completeCallbac.call(_args);
}
};
if (args.manualTransition) {
if (expanded) {
this.contentContainer.addClass(['busy', 'open']);
this.contentContainer.removeClass('is-sub-section-open');
this.contentContainer.closest('.wp-full-overlay').addClass('section-open');
} else {
this.contentContainer.addClass(['busy', 'is-sub-section-open']);
this.contentContainer.closest('.wp-full-overlay').addClass('section-open');
this.contentContainer.removeClass('open');
}
const handleTransitionEnd = () => {
this.contentContainer.removeClass('busy');
args.completeCallback();
};
if (isReducedMotion) {
handleTransitionEnd();
} else {
this.contentContainer.one('transitionend', handleTransitionEnd);
}
} else {
super.onChangeExpanded(expanded, args);
}
}
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/components/sidebar-block-editor/sidebar-adapter.js
/**
* Internal dependencies
*/
const {
wp
} = window;
function parseWidgetId(widgetId) {
const matches = widgetId.match(/^(.+)-(\d+)$/);
if (matches) {
return {
idBase: matches[1],
number: parseInt(matches[2], 10)
};
} // Likely an old single widget.
return {
idBase: widgetId
};
}
function widgetIdToSettingId(widgetId) {
const {
idBase,
number
} = parseWidgetId(widgetId);
if (number) {
return `widget_${idBase}[${number}]`;
}
return `widget_${idBase}`;
}
/**
* This is a custom debounce function to call different callbacks depending on
* whether it's the _leading_ call or not.
*
* @param {Function} leading The callback that gets called first.
* @param {Function} callback The callback that gets called after the first time.
* @param {number} timeout The debounced time in milliseconds.
* @return {Function} The debounced function.
*/
function debounce(leading, callback, timeout) {
let isLeading = false;
let timerID;
function debounced() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
const result = (isLeading ? callback : leading).apply(this, args);
isLeading = true;
clearTimeout(timerID);
timerID = setTimeout(() => {
isLeading = false;
}, timeout);
return result;
}
debounced.cancel = () => {
isLeading = false;
clearTimeout(timerID);
};
return debounced;
}
class SidebarAdapter {
constructor(setting, api) {
this.setting = setting;
this.api = api;
this.locked = false;
this.widgetsCache = new WeakMap();
this.subscribers = new Set();
this.history = [this._getWidgetIds().map(widgetId => this.getWidget(widgetId))];
this.historyIndex = 0;
this.historySubscribers = new Set(); // Debounce the input for 1 second.
this._debounceSetHistory = debounce(this._pushHistory, this._replaceHistory, 1000);
this.setting.bind(this._handleSettingChange.bind(this));
this.api.bind('change', this._handleAllSettingsChange.bind(this));
this.undo = this.undo.bind(this);
this.redo = this.redo.bind(this);
this.save = this.save.bind(this);
}
subscribe(callback) {
this.subscribers.add(callback);
return () => {
this.subscribers.delete(callback);
};
}
getWidgets() {
return this.history[this.historyIndex];
}
_emit() {
for (const callback of this.subscribers) {
callback(...arguments);
}
}
_getWidgetIds() {
return this.setting.get();
}
_pushHistory() {
this.history = [...this.history.slice(0, this.historyIndex + 1), this._getWidgetIds().map(widgetId => this.getWidget(widgetId))];
this.historyIndex += 1;
this.historySubscribers.forEach(listener => listener());
}
_replaceHistory() {
this.history[this.historyIndex] = this._getWidgetIds().map(widgetId => this.getWidget(widgetId));
}
_handleSettingChange() {
if (this.locked) {
return;
}
const prevWidgets = this.getWidgets();
this._pushHistory();
this._emit(prevWidgets, this.getWidgets());
}
_handleAllSettingsChange(setting) {
if (this.locked) {
return;
}
if (!setting.id.startsWith('widget_')) {
return;
}
const widgetId = settingIdToWidgetId(setting.id);
if (!this.setting.get().includes(widgetId)) {
return;
}
const prevWidgets = this.getWidgets();
this._pushHistory();
this._emit(prevWidgets, this.getWidgets());
}
_createWidget(widget) {
const widgetModel = wp.customize.Widgets.availableWidgets.findWhere({
id_base: widget.idBase
});
let number = widget.number;
if (widgetModel.get('is_multi') && !number) {
widgetModel.set('multi_number', widgetModel.get('multi_number') + 1);
number = widgetModel.get('multi_number');
}
const settingId = number ? `widget_${widget.idBase}[${number}]` : `widget_${widget.idBase}`;
const settingArgs = {
transport: wp.customize.Widgets.data.selectiveRefreshableWidgets[widgetModel.get('id_base')] ? 'postMessage' : 'refresh',
previewer: this.setting.previewer
};
const setting = this.api.create(settingId, settingId, '', settingArgs);
setting.set(widget.instance);
const widgetId = settingIdToWidgetId(settingId);
return widgetId;
}
_removeWidget(widget) {
const settingId = widgetIdToSettingId(widget.id);
const setting = this.api(settingId);
if (setting) {
const instance = setting.get();
this.widgetsCache.delete(instance);
}
this.api.remove(settingId);
}
_updateWidget(widget) {
const prevWidget = this.getWidget(widget.id); // Bail out update if nothing changed.
if (prevWidget === widget) {
return widget.id;
} // Update existing setting if only the widget's instance changed.
if (prevWidget.idBase && widget.idBase && prevWidget.idBase === widget.idBase) {
const settingId = widgetIdToSettingId(widget.id);
this.api(settingId).set(widget.instance);
return widget.id;
} // Otherwise delete and re-create.
this._removeWidget(widget);
return this._createWidget(widget);
}
getWidget(widgetId) {
if (!widgetId) {
return null;
}
const {
idBase,
number
} = parseWidgetId(widgetId);
const settingId = widgetIdToSettingId(widgetId);
const setting = this.api(settingId);
if (!setting) {
return null;
}
const instance = setting.get();
if (this.widgetsCache.has(instance)) {
return this.widgetsCache.get(instance);
}
const widget = {
id: widgetId,
idBase,
number,
instance
};
this.widgetsCache.set(instance, widget);
return widget;
}
_updateWidgets(nextWidgets) {
this.locked = true;
const addedWidgetIds = [];
const nextWidgetIds = nextWidgets.map(nextWidget => {
if (nextWidget.id && this.getWidget(nextWidget.id)) {
addedWidgetIds.push(null);
return this._updateWidget(nextWidget);
}
const widgetId = this._createWidget(nextWidget);
addedWidgetIds.push(widgetId);
return widgetId;
});
const deletedWidgets = this.getWidgets().filter(widget => !nextWidgetIds.includes(widget.id));
deletedWidgets.forEach(widget => this._removeWidget(widget));
this.setting.set(nextWidgetIds);
this.locked = false;
return addedWidgetIds;
}
setWidgets(nextWidgets) {
const addedWidgetIds = this._updateWidgets(nextWidgets);
this._debounceSetHistory();
return addedWidgetIds;
}
/**
* Undo/Redo related features
*/
hasUndo() {
return this.historyIndex > 0;
}
hasRedo() {
return this.historyIndex < this.history.length - 1;
}
_seek(historyIndex) {
const currentWidgets = this.getWidgets();
this.historyIndex = historyIndex;
const widgets = this.history[this.historyIndex];
this._updateWidgets(widgets);
this._emit(currentWidgets, this.getWidgets());
this.historySubscribers.forEach(listener => listener());
this._debounceSetHistory.cancel();
}
undo() {
if (!this.hasUndo()) {
return;
}
this._seek(this.historyIndex - 1);
}
redo() {
if (!this.hasRedo()) {
return;
}
this._seek(this.historyIndex + 1);
}
subscribeHistory(listener) {
this.historySubscribers.add(listener);
return () => {
this.historySubscribers.delete(listener);
};
}
save() {
this.api.previewer.save();
}
}
;// CONCATENATED MODULE: external ["wp","dom"]
var external_wp_dom_namespaceObject = window["wp"]["dom"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/controls/inserter-outer-section.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function getInserterOuterSection() {
const {
wp: {
customize
}
} = window;
const OuterSection = customize.OuterSection; // Override the OuterSection class to handle multiple outer sections.
// It closes all the other outer sections whenever one is opened.
// The result is that at most one outer section can be opened at the same time.
customize.OuterSection = class extends OuterSection {
onChangeExpanded(expanded, args) {
if (expanded) {
customize.section.each(section => {
if (section.params.type === 'outer' && section.id !== this.id) {
if (section.expanded()) {
section.collapse();
}
}
});
}
return super.onChangeExpanded(expanded, args);
}
}; // Handle constructor so that "params.type" can be correctly pointed to "outer".
customize.sectionConstructor.outer = customize.OuterSection;
return class InserterOuterSection extends customize.OuterSection {
constructor() {
super(...arguments); // This is necessary since we're creating a new class which is not identical to the original OuterSection.
// @See https://github.com/WordPress/wordpress-develop/blob/42b05c397c50d9dc244083eff52991413909d4bd/src/js/_enqueues/wp/customize/controls.js#L1427-L1436
this.params.type = 'outer';
this.activeElementBeforeExpanded = null;
const ownerWindow = this.contentContainer[0].ownerDocument.defaultView; // Handle closing the inserter when pressing the Escape key.
ownerWindow.addEventListener('keydown', event => {
if (this.expanded() && (event.keyCode === external_wp_keycodes_namespaceObject.ESCAPE || event.code === 'Escape') && !event.defaultPrevented) {
event.preventDefault();
event.stopPropagation();
(0,external_wp_data_namespaceObject.dispatch)(store).setIsInserterOpened(false);
}
}, // Use capture mode to make this run before other event listeners.
true);
this.contentContainer.addClass('widgets-inserter'); // Set a flag if the state is being changed from open() or close().
// Don't propagate the event if it's an internal action to prevent infinite loop.
this.isFromInternalAction = false;
this.expanded.bind(() => {
if (!this.isFromInternalAction) {
// Propagate the event to React to sync the state.
(0,external_wp_data_namespaceObject.dispatch)(store).setIsInserterOpened(this.expanded());
}
this.isFromInternalAction = false;
});
}
open() {
if (!this.expanded()) {
const contentContainer = this.contentContainer[0];
this.activeElementBeforeExpanded = contentContainer.ownerDocument.activeElement;
this.isFromInternalAction = true;
this.expand({
completeCallback() {
// We have to do this in a "completeCallback" or else the elements will not yet be visible/tabbable.
// The first one should be the close button,
// we want to skip it and choose the second one instead, which is the search box.
const searchBox = external_wp_dom_namespaceObject.focus.tabbable.find(contentContainer)[1];
if (searchBox) {
searchBox.focus();
}
}
});
}
}
close() {
if (this.expanded()) {
const contentContainer = this.contentContainer[0];
const activeElement = contentContainer.ownerDocument.activeElement;
this.isFromInternalAction = true;
this.collapse({
completeCallback() {
// Return back the focus when closing the inserter.
// Only do this if the active element which triggers the action is inside the inserter,
// (the close button for instance). In that case the focus will be lost.
// Otherwise, we don't hijack the focus when the user is focusing on other elements
// (like the quick inserter).
if (contentContainer.contains(activeElement)) {
// Return back the focus when closing the inserter.
if (this.activeElementBeforeExpanded) {
this.activeElementBeforeExpanded.focus();
}
}
}
});
}
}
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/controls/sidebar-control.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const getInserterId = controlId => `widgets-inserter-${controlId}`;
function getSidebarControl() {
const {
wp: {
customize
}
} = window;
return class SidebarControl extends customize.Control {
constructor() {
super(...arguments);
this.subscribers = new Set();
}
ready() {
const InserterOuterSection = getInserterOuterSection();
this.inserter = new InserterOuterSection(getInserterId(this.id), {});
customize.section.add(this.inserter);
this.sectionInstance = customize.section(this.section());
this.inspector = this.sectionInstance.inspector;
this.sidebarAdapter = new SidebarAdapter(this.setting, customize);
}
subscribe(callback) {
this.subscribers.add(callback);
return () => {
this.subscribers.delete(callback);
};
}
onChangeSectionExpanded(expanded, args) {
if (!args.unchanged) {
// Close the inserter when the section collapses.
if (!expanded) {
(0,external_wp_data_namespaceObject.dispatch)(store).setIsInserterOpened(false);
}
this.subscribers.forEach(subscriber => subscriber(expanded, args));
}
}
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/filters/move-to-sidebar.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const withMoveToSidebarToolbarItem = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(BlockEdit => props => {
let widgetId = (0,external_wp_widgets_namespaceObject.getWidgetIdFromBlock)(props);
const sidebarControls = useSidebarControls();
const activeSidebarControl = useActiveSidebarControl();
const hasMultipleSidebars = (sidebarControls === null || sidebarControls === void 0 ? void 0 : sidebarControls.length) > 1;
const blockName = props.name;
const clientId = props.clientId;
const canInsertBlockInSidebar = (0,external_wp_data_namespaceObject.useSelect)(select => {
// Use an empty string to represent the root block list, which
// in the customizer editor represents a sidebar/widget area.
return select(external_wp_blockEditor_namespaceObject.store).canInsertBlockType(blockName, '');
}, [blockName]);
const block = (0,external_wp_data_namespaceObject.useSelect)(select => select(external_wp_blockEditor_namespaceObject.store).getBlock(clientId), [clientId]);
const {
removeBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_blockEditor_namespaceObject.store);
const [, focusWidget] = useFocusControl();
function moveToSidebar(sidebarControlId) {
const newSidebarControl = sidebarControls.find(sidebarControl => sidebarControl.id === sidebarControlId);
if (widgetId) {
/**
* If there's a widgetId, move it to the other sidebar.
*/
const oldSetting = activeSidebarControl.setting;
const newSetting = newSidebarControl.setting;
oldSetting(oldSetting().filter(id => id !== widgetId));
newSetting([...newSetting(), widgetId]);
} else {
/**
* If there isn't a widgetId, it's most likely a inner block.
* First, remove the block in the original sidebar,
* then, create a new widget in the new sidebar and get back its widgetId.
*/
const sidebarAdapter = newSidebarControl.sidebarAdapter;
removeBlock(clientId);
const addedWidgetIds = sidebarAdapter.setWidgets([...sidebarAdapter.getWidgets(), blockToWidget(block)]); // The last non-null id is the added widget's id.
widgetId = addedWidgetIds.reverse().find(id => !!id);
} // Move focus to the moved widget and expand the sidebar.
focusWidget(widgetId);
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(BlockEdit, props), hasMultipleSidebars && canInsertBlockInSidebar && (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockControls, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_widgets_namespaceObject.MoveToWidgetArea, {
widgetAreas: sidebarControls.map(sidebarControl => ({
id: sidebarControl.id,
name: sidebarControl.params.label,
description: sidebarControl.params.description
})),
currentWidgetAreaId: activeSidebarControl === null || activeSidebarControl === void 0 ? void 0 : activeSidebarControl.id,
onSelect: moveToSidebar
})));
}, 'withMoveToSidebarToolbarItem');
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockEdit', 'core/customize-widgets/block-edit', withMoveToSidebarToolbarItem);
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/filters/replace-media-upload.js
/**
* WordPress dependencies
*/
const replaceMediaUpload = () => external_wp_mediaUtils_namespaceObject.MediaUpload;
(0,external_wp_hooks_namespaceObject.addFilter)('editor.MediaUpload', 'core/edit-widgets/replace-media-upload', replaceMediaUpload);
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/filters/wide-widget-display.js
/**
* WordPress dependencies
*/
const {
wp: wide_widget_display_wp
} = window;
const withWideWidgetDisplay = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(BlockEdit => props => {
var _wp$customize$Widgets, _wp$customize$Widgets2;
const {
idBase
} = props.attributes;
const isWide = (_wp$customize$Widgets = (_wp$customize$Widgets2 = wide_widget_display_wp.customize.Widgets.data.availableWidgets.find(widget => widget.id_base === idBase)) === null || _wp$customize$Widgets2 === void 0 ? void 0 : _wp$customize$Widgets2.is_wide) !== null && _wp$customize$Widgets !== void 0 ? _wp$customize$Widgets : false;
return (0,external_wp_element_namespaceObject.createElement)(BlockEdit, _extends({}, props, {
isWide: isWide
}));
}, 'withWideWidgetDisplay');
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockEdit', 'core/customize-widgets/wide-widget-display', withWideWidgetDisplay);
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/filters/index.js
/**
* Internal dependencies
*/
;// CONCATENATED MODULE: ./node_modules/@wordpress/customize-widgets/build-module/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const {
wp: build_module_wp
} = window;
const DISABLED_BLOCKS = ['core/more', 'core/block', 'core/freeform', 'core/template-part'];
const ENABLE_EXPERIMENTAL_FSE_BLOCKS = false;
/**
* Initializes the widgets block editor in the customizer.
*
* @param {string} editorName The editor name.
* @param {Object} blockEditorSettings Block editor settings.
*/
function initialize(editorName, blockEditorSettings) {
(0,external_wp_data_namespaceObject.dispatch)(external_wp_preferences_namespaceObject.store).setDefaults('core/customize-widgets', {
fixedToolbar: false,
welcomeGuide: true
});
(0,external_wp_data_namespaceObject.dispatch)(external_wp_blocks_namespaceObject.store).__experimentalReapplyBlockTypeFilters();
const coreBlocks = (0,external_wp_blockLibrary_namespaceObject.__experimentalGetCoreBlocks)().filter(block => {
return !(DISABLED_BLOCKS.includes(block.name) || block.name.startsWith('core/post') || block.name.startsWith('core/query') || block.name.startsWith('core/site') || block.name.startsWith('core/navigation'));
});
(0,external_wp_blockLibrary_namespaceObject.registerCoreBlocks)(coreBlocks);
(0,external_wp_widgets_namespaceObject.registerLegacyWidgetBlock)();
if (false) {}
(0,external_wp_widgets_namespaceObject.registerLegacyWidgetVariations)(blockEditorSettings);
(0,external_wp_widgets_namespaceObject.registerWidgetGroupBlock)(); // As we are unregistering `core/freeform` to avoid the Classic block, we must
// replace it with something as the default freeform content handler. Failure to
// do this will result in errors in the default block parser.
// see: https://github.com/WordPress/gutenberg/issues/33097
(0,external_wp_blocks_namespaceObject.setFreeformContentHandlerName)('core/html');
const SidebarControl = getSidebarControl(blockEditorSettings);
build_module_wp.customize.sectionConstructor.sidebar = getSidebarSection();
build_module_wp.customize.controlConstructor.sidebar_block_editor = SidebarControl;
const container = document.createElement('div');
document.body.appendChild(container);
build_module_wp.customize.bind('ready', () => {
const sidebarControls = [];
build_module_wp.customize.control.each(control => {
if (control instanceof SidebarControl) {
sidebarControls.push(control);
}
});
(0,external_wp_element_namespaceObject.render)((0,external_wp_element_namespaceObject.createElement)(CustomizeWidgets, {
api: build_module_wp.customize,
sidebarControls: sidebarControls,
blockEditorSettings: blockEditorSettings
}), container);
});
}
}();
(window.wp = window.wp || {}).customizeWidgets = __webpack_exports__;
/******/ })()
; hooks.min.js 0000666 00000011456 15123355174 0007030 0 ustar 00 /*! This file is auto-generated */
!function(){"use strict";var n={d:function(t,r){for(var e in r)n.o(r,e)&&!n.o(t,e)&&Object.defineProperty(t,e,{enumerable:!0,get:r[e]})},o:function(n,t){return Object.prototype.hasOwnProperty.call(n,t)},r:function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})}},t={};n.r(t),n.d(t,{actions:function(){return S},addAction:function(){return v},addFilter:function(){return m},applyFilters:function(){return k},createHooks:function(){return h},currentAction:function(){return w},currentFilter:function(){return I},defaultHooks:function(){return f},didAction:function(){return O},didFilter:function(){return j},doAction:function(){return b},doingAction:function(){return x},doingFilter:function(){return T},filters:function(){return z},hasAction:function(){return _},hasFilter:function(){return g},removeAction:function(){return p},removeAllActions:function(){return y},removeAllFilters:function(){return F},removeFilter:function(){return A}});var r=function(n){return"string"!=typeof n||""===n?(console.error("The namespace must be a non-empty string."),!1):!!/^[a-zA-Z][a-zA-Z0-9_.\-\/]*$/.test(n)||(console.error("The namespace can only contain numbers, letters, dashes, periods, underscores and slashes."),!1)};var e=function(n){return"string"!=typeof n||""===n?(console.error("The hook name must be a non-empty string."),!1):/^__/.test(n)?(console.error("The hook name cannot begin with `__`."),!1):!!/^[a-zA-Z][a-zA-Z0-9_.-]*$/.test(n)||(console.error("The hook name can only contain numbers, letters, dashes, periods and underscores."),!1)};var o=function(n,t){return function(o,i,c){let s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:10;const u=n[t];if(!e(o))return;if(!r(i))return;if("function"!=typeof c)return void console.error("The hook callback must be a function.");if("number"!=typeof s)return void console.error("If specified, the hook priority must be a number.");const l={callback:c,priority:s,namespace:i};if(u[o]){const n=u[o].handlers;let t;for(t=n.length;t>0&&!(s>=n[t-1].priority);t--);t===n.length?n[t]=l:n.splice(t,0,l),u.__current.forEach((n=>{n.name===o&&n.currentIndex>=t&&n.currentIndex++}))}else u[o]={handlers:[l],runs:0};"hookAdded"!==o&&n.doAction("hookAdded",o,i,c,s)}};var i=function(n,t){let o=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function(i,c){const s=n[t];if(!e(i))return;if(!o&&!r(c))return;if(!s[i])return 0;let u=0;if(o)u=s[i].handlers.length,s[i]={runs:s[i].runs,handlers:[]};else{const n=s[i].handlers;for(let t=n.length-1;t>=0;t--)n[t].namespace===c&&(n.splice(t,1),u++,s.__current.forEach((n=>{n.name===i&&n.currentIndex>=t&&n.currentIndex--})))}return"hookRemoved"!==i&&n.doAction("hookRemoved",i,c),u}};var c=function(n,t){return function(r,e){const o=n[t];return void 0!==e?r in o&&o[r].handlers.some((n=>n.namespace===e)):r in o}};var s=function(n,t){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function(e){const o=n[t];o[e]||(o[e]={handlers:[],runs:0}),o[e].runs++;const i=o[e].handlers;for(var c=arguments.length,s=new Array(c>1?c-1:0),u=1;u<c;u++)s[u-1]=arguments[u];if(!i||!i.length)return r?s[0]:void 0;const l={name:e,currentIndex:0};for(o.__current.push(l);l.currentIndex<i.length;){const n=i[l.currentIndex].callback.apply(null,s);r&&(s[0]=n),l.currentIndex++}return o.__current.pop(),r?s[0]:void 0}};var u=function(n,t){return function(){var r,e;const o=n[t];return null!==(r=null===(e=o.__current[o.__current.length-1])||void 0===e?void 0:e.name)&&void 0!==r?r:null}};var l=function(n,t){return function(r){const e=n[t];return void 0===r?void 0!==e.__current[0]:!!e.__current[0]&&r===e.__current[0].name}};var a=function(n,t){return function(r){const o=n[t];if(e(r))return o[r]&&o[r].runs?o[r].runs:0}};class d{constructor(){this.actions=Object.create(null),this.actions.__current=[],this.filters=Object.create(null),this.filters.__current=[],this.addAction=o(this,"actions"),this.addFilter=o(this,"filters"),this.removeAction=i(this,"actions"),this.removeFilter=i(this,"filters"),this.hasAction=c(this,"actions"),this.hasFilter=c(this,"filters"),this.removeAllActions=i(this,"actions",!0),this.removeAllFilters=i(this,"filters",!0),this.doAction=s(this,"actions"),this.applyFilters=s(this,"filters",!0),this.currentAction=u(this,"actions"),this.currentFilter=u(this,"filters"),this.doingAction=l(this,"actions"),this.doingFilter=l(this,"filters"),this.didAction=a(this,"actions"),this.didFilter=a(this,"filters")}}var h=function(){return new d};const f=h(),{addAction:v,addFilter:m,removeAction:p,removeFilter:A,hasAction:_,hasFilter:g,removeAllActions:y,removeAllFilters:F,doAction:b,applyFilters:k,currentAction:w,currentFilter:I,doingAction:x,doingFilter:T,didAction:O,didFilter:j,actions:S,filters:z}=f;(window.wp=window.wp||{}).hooks=t}(); keyboard-shortcuts.js 0000666 00000054602 15123355174 0010757 0 ustar 00 /******/ (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__, {
"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; }
});
// 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; }
});
;// CONCATENATED MODULE: external ["wp","data"]
var external_wp_data_namespaceObject = window["wp"]["data"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/keyboard-shortcuts/build-module/store/reducer.js
/**
* Reducer returning the registered shortcuts
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
function reducer() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'REGISTER_SHORTCUT':
return { ...state,
[action.name]: {
category: action.category,
keyCombination: action.keyCombination,
aliases: action.aliases,
description: action.description
}
};
case 'UNREGISTER_SHORTCUT':
const {
[action.name]: actionName,
...remainingState
} = state;
return remainingState;
}
return state;
}
/* harmony default export */ var store_reducer = (reducer);
;// CONCATENATED MODULE: ./node_modules/@wordpress/keyboard-shortcuts/build-module/store/actions.js
/** @typedef {import('@wordpress/keycodes').WPKeycodeModifier} WPKeycodeModifier */
/**
* Keyboard key combination.
*
* @typedef {Object} WPShortcutKeyCombination
*
* @property {string} character Character.
* @property {WPKeycodeModifier|undefined} modifier Modifier.
*/
/**
* Configuration of a registered keyboard shortcut.
*
* @typedef {Object} WPShortcutConfig
*
* @property {string} name Shortcut name.
* @property {string} category Shortcut category.
* @property {string} description Shortcut description.
* @property {WPShortcutKeyCombination} keyCombination Shortcut key combination.
* @property {WPShortcutKeyCombination[]} [aliases] Shortcut aliases.
*/
/**
* Returns an action object used to register a new keyboard shortcut.
*
* @param {WPShortcutConfig} config Shortcut config.
*
* @return {Object} action.
*/
function registerShortcut(_ref) {
let {
name,
category,
description,
keyCombination,
aliases
} = _ref;
return {
type: 'REGISTER_SHORTCUT',
name,
category,
keyCombination,
aliases,
description
};
}
/**
* Returns an action object used to unregister a keyboard shortcut.
*
* @param {string} name Shortcut name.
*
* @return {Object} action.
*/
function unregisterShortcut(name) {
return {
type: 'UNREGISTER_SHORTCUT',
name
};
}
;// CONCATENATED MODULE: ./node_modules/rememo/rememo.js
/** @typedef {(...args: any[]) => *[]} GetDependants */
/** @typedef {() => void} Clear */
/**
* @typedef {{
* getDependants: GetDependants,
* clear: Clear
* }} EnhancedSelector
*/
/**
* Internal cache entry.
*
* @typedef CacheNode
*
* @property {?CacheNode|undefined} [prev] Previous node.
* @property {?CacheNode|undefined} [next] Next node.
* @property {*[]} args Function arguments for cache entry.
* @property {*} val Function result.
*/
/**
* @typedef Cache
*
* @property {Clear} clear Function to clear cache.
* @property {boolean} [isUniqueByDependants] Whether dependants are valid in
* considering cache uniqueness. A cache is unique if dependents are all arrays
* or objects.
* @property {CacheNode?} [head] Cache head.
* @property {*[]} [lastDependants] Dependants from previous invocation.
*/
/**
* Arbitrary value used as key for referencing cache object in WeakMap tree.
*
* @type {{}}
*/
var LEAF_KEY = {};
/**
* Returns the first argument as the sole entry in an array.
*
* @template T
*
* @param {T} value Value to return.
*
* @return {[T]} Value returned as entry in array.
*/
function arrayOf(value) {
return [value];
}
/**
* Returns true if the value passed is object-like, or false otherwise. A value
* is object-like if it can support property assignment, e.g. object or array.
*
* @param {*} value Value to test.
*
* @return {boolean} Whether value is object-like.
*/
function isObjectLike(value) {
return !!value && 'object' === typeof value;
}
/**
* Creates and returns a new cache object.
*
* @return {Cache} Cache object.
*/
function createCache() {
/** @type {Cache} */
var cache = {
clear: function () {
cache.head = null;
},
};
return cache;
}
/**
* Returns true if entries within the two arrays are strictly equal by
* reference from a starting index.
*
* @param {*[]} a First array.
* @param {*[]} b Second array.
* @param {number} fromIndex Index from which to start comparison.
*
* @return {boolean} Whether arrays are shallowly equal.
*/
function isShallowEqual(a, b, fromIndex) {
var i;
if (a.length !== b.length) {
return false;
}
for (i = fromIndex; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
/**
* Returns a memoized selector function. The getDependants function argument is
* called before the memoized selector and is expected to return an immutable
* reference or array of references on which the selector depends for computing
* its own return value. The memoize cache is preserved only as long as those
* dependant references remain the same. If getDependants returns a different
* reference(s), the cache is cleared and the selector value regenerated.
*
* @template {(...args: *[]) => *} S
*
* @param {S} selector Selector function.
* @param {GetDependants=} getDependants Dependant getter returning an array of
* references used in cache bust consideration.
*/
/* harmony default export */ function rememo(selector, getDependants) {
/** @type {WeakMap<*,*>} */
var rootCache;
/** @type {GetDependants} */
var normalizedGetDependants = getDependants ? getDependants : arrayOf;
/**
* Returns the cache for a given dependants array. When possible, a WeakMap
* will be used to create a unique cache for each set of dependants. This
* is feasible due to the nature of WeakMap in allowing garbage collection
* to occur on entries where the key object is no longer referenced. Since
* WeakMap requires the key to be an object, this is only possible when the
* dependant is object-like. The root cache is created as a hierarchy where
* each top-level key is the first entry in a dependants set, the value a
* WeakMap where each key is the next dependant, and so on. This continues
* so long as the dependants are object-like. If no dependants are object-
* like, then the cache is shared across all invocations.
*
* @see isObjectLike
*
* @param {*[]} dependants Selector dependants.
*
* @return {Cache} Cache object.
*/
function getCache(dependants) {
var caches = rootCache,
isUniqueByDependants = true,
i,
dependant,
map,
cache;
for (i = 0; i < dependants.length; i++) {
dependant = dependants[i];
// Can only compose WeakMap from object-like key.
if (!isObjectLike(dependant)) {
isUniqueByDependants = false;
break;
}
// Does current segment of cache already have a WeakMap?
if (caches.has(dependant)) {
// Traverse into nested WeakMap.
caches = caches.get(dependant);
} else {
// Create, set, and traverse into a new one.
map = new WeakMap();
caches.set(dependant, map);
caches = map;
}
}
// We use an arbitrary (but consistent) object as key for the last item
// in the WeakMap to serve as our running cache.
if (!caches.has(LEAF_KEY)) {
cache = createCache();
cache.isUniqueByDependants = isUniqueByDependants;
caches.set(LEAF_KEY, cache);
}
return caches.get(LEAF_KEY);
}
/**
* Resets root memoization cache.
*/
function clear() {
rootCache = new WeakMap();
}
/* eslint-disable jsdoc/check-param-names */
/**
* The augmented selector call, considering first whether dependants have
* changed before passing it to underlying memoize function.
*
* @param {*} source Source object for derivation.
* @param {...*} extraArgs Additional arguments to pass to selector.
*
* @return {*} Selector result.
*/
/* eslint-enable jsdoc/check-param-names */
function callSelector(/* source, ...extraArgs */) {
var len = arguments.length,
cache,
node,
i,
args,
dependants;
// Create copy of arguments (avoid leaking deoptimization).
args = new Array(len);
for (i = 0; i < len; i++) {
args[i] = arguments[i];
}
dependants = normalizedGetDependants.apply(null, args);
cache = getCache(dependants);
// If not guaranteed uniqueness by dependants (primitive type), shallow
// compare against last dependants and, if references have changed,
// destroy cache to recalculate result.
if (!cache.isUniqueByDependants) {
if (
cache.lastDependants &&
!isShallowEqual(dependants, cache.lastDependants, 0)
) {
cache.clear();
}
cache.lastDependants = dependants;
}
node = cache.head;
while (node) {
// Check whether node arguments match arguments
if (!isShallowEqual(node.args, args, 1)) {
node = node.next;
continue;
}
// At this point we can assume we've found a match
// Surface matched node to head if not already
if (node !== cache.head) {
// Adjust siblings to point to each other.
/** @type {CacheNode} */ (node.prev).next = node.next;
if (node.next) {
node.next.prev = node.prev;
}
node.next = cache.head;
node.prev = null;
/** @type {CacheNode} */ (cache.head).prev = node;
cache.head = node;
}
// Return immediately
return node.val;
}
// No cached value found. Continue to insertion phase:
node = /** @type {CacheNode} */ ({
// Generate the result from original function
val: selector.apply(null, args),
});
// Avoid including the source object in the cache.
args[0] = null;
node.args = args;
// Don't need to check whether node is already head, since it would
// have been returned above already if it was
// Shift existing head down list
if (cache.head) {
cache.head.prev = node;
node.next = cache.head;
}
cache.head = node;
return node.val;
}
callSelector.getDependants = normalizedGetDependants;
callSelector.clear = clear;
clear();
return /** @type {S & EnhancedSelector} */ (callSelector);
}
;// CONCATENATED MODULE: external ["wp","keycodes"]
var external_wp_keycodes_namespaceObject = window["wp"]["keycodes"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/keyboard-shortcuts/build-module/store/selectors.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/** @typedef {import('./actions').WPShortcutKeyCombination} WPShortcutKeyCombination */
/** @typedef {import('@wordpress/keycodes').WPKeycodeHandlerByModifier} WPKeycodeHandlerByModifier */
/**
* Shared reference to an empty array for cases where it is important to avoid
* returning a new array reference on every invocation.
*
* @type {Array<any>}
*/
const EMPTY_ARRAY = [];
/**
* Shortcut formatting methods.
*
* @property {WPKeycodeHandlerByModifier} display Display formatting.
* @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.
*
* @param {?WPShortcutKeyCombination} shortcut Key combination.
* @param {keyof FORMATTING_METHODS} representation Type of representation
* (display, raw, ariaLabel).
*
* @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.
*
* @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.
*
* @param {Object} state Global state.
* @param {string} name Shortcut name.
* @param {keyof FORMATTING_METHODS} representation Type of representation
* (display, raw, ariaLabel).
*
* @return {string?} Shortcut representation.
*/
function getShortcutRepresentation(state, name) {
let representation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '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.
*
* @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.
*
* @return {WPShortcutKeyCombination[]} Key combinations.
*/
function getShortcutAliases(state, name) {
return state[name] && state[name].aliases ? state[name].aliases : EMPTY_ARRAY;
}
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.
*
* @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.
*
* @return {string[]} Shortcut names.
*/
const getCategoryShortcuts = rememo((state, categoryName) => {
return Object.entries(state).filter(_ref => {
let [, shortcut] = _ref;
return shortcut.category === categoryName;
}).map(_ref2 => {
let [name] = _ref2;
return name;
});
}, state => [state]);
;// CONCATENATED MODULE: ./node_modules/@wordpress/keyboard-shortcuts/build-module/store/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const STORE_NAME = 'core/keyboard-shortcuts';
/**
* Store definition for the keyboard shortcuts 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, {
reducer: store_reducer,
actions: actions_namespaceObject,
selectors: selectors_namespaceObject
});
(0,external_wp_data_namespaceObject.register)(store);
;// CONCATENATED MODULE: external ["wp","element"]
var external_wp_element_namespaceObject = window["wp"]["element"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/keyboard-shortcuts/build-module/hooks/use-shortcut-event-match.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Returns a function to check if a keyboard event matches a shortcut name.
*
* @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.
*
* @param {string} name Shortcut name.
* @param {KeyboardEvent} event Event to check.
*
* @return {boolean} True if the event matches any shortcuts, false if not.
*/
function isMatch(name, event) {
return getAllShortcutKeyCombinations(name).some(_ref => {
let {
modifier,
character
} = _ref;
return external_wp_keycodes_namespaceObject.isKeyboardEvent[modifier](event, character);
});
}
return isMatch;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/keyboard-shortcuts/build-module/context.js
/**
* WordPress dependencies
*/
const context = (0,external_wp_element_namespaceObject.createContext)();
;// CONCATENATED MODULE: ./node_modules/@wordpress/keyboard-shortcuts/build-module/hooks/use-shortcut.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Attach a keyboard shortcut handler.
*
* @param {string} name Shortcut name.
* @param {Function} callback Shortcut callback.
* @param {Object} options Shortcut options.
* @param {boolean} options.isDisabled Whether to disable to shortut.
*/
function useShortcut(name, callback) {
let {
isDisabled
} = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
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)(() => {
if (isDisabled) {
return;
}
function _callback(event) {
if (isMatch(name, event)) {
callbackRef.current(event);
}
}
shortcuts.current.add(_callback);
return () => {
shortcuts.current.delete(_callback);
};
}, [name, isDisabled]);
}
;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/extends.js
function _extends() {
return _extends = Object.assign ? Object.assign.bind() : function (n) {
for (var e = 1; e < arguments.length; e++) {
var t = arguments[e];
for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
}
return n;
}, _extends.apply(null, arguments);
}
;// 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`.
*
* @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());
function onKeyDown(event) {
if (props.onKeyDown) props.onKeyDown(event);
for (const keyboardShortcut of keyboardShortcuts.current) {
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", _extends({}, props, {
onKeyDown: onKeyDown
})));
/* eslint-enable jsx-a11y/no-static-element-interactions */
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/keyboard-shortcuts/build-module/index.js
(window.wp = window.wp || {}).keyboardShortcuts = __webpack_exports__;
/******/ })()
; edit-post.js 0000666 00001275212 15123355174 0007036 0 ustar 00 /******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 7153:
/***/ (function(module, exports) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2018 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
'use strict';
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = '';
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
classes = appendClass(classes, parseValue(arg));
}
}
return classes;
}
function parseValue (arg) {
if (typeof arg === 'string' || typeof arg === 'number') {
return arg;
}
if (typeof arg !== 'object') {
return '';
}
if (Array.isArray(arg)) {
return classNames.apply(null, arg);
}
if (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes('[native code]')) {
return arg.toString();
}
var classes = '';
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes = appendClass(classes, key);
}
}
return classes;
}
function appendClass (value, newClass) {
if (!newClass) {
return value;
}
if (value) {
return value + ' ' + newClass;
}
return value + newClass;
}
if ( true && module.exports) {
classNames.default = classNames;
module.exports = classNames;
} else if (true) {
// register as 'classnames', consistent with npm package name
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () {
return classNames;
}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
}());
/***/ })
/******/ });
/************************************************************************/
/******/ // 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 in strict mode.
!function() {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"PluginBlockSettingsMenuItem": function() { return /* reexport */ plugin_block_settings_menu_item; },
"PluginDocumentSettingPanel": function() { return /* reexport */ plugin_document_setting_panel; },
"PluginMoreMenuItem": function() { return /* reexport */ plugin_more_menu_item; },
"PluginPostPublishPanel": function() { return /* reexport */ plugin_post_publish_panel; },
"PluginPostStatusInfo": function() { return /* reexport */ plugin_post_status_info; },
"PluginPrePublishPanel": function() { return /* reexport */ plugin_pre_publish_panel; },
"PluginSidebar": function() { return /* reexport */ PluginSidebarEditPost; },
"PluginSidebarMoreMenuItem": function() { return /* reexport */ PluginSidebarMoreMenuItem; },
"__experimentalFullscreenModeClose": function() { return /* reexport */ fullscreen_mode_close; },
"__experimentalMainDashboardButton": function() { return /* reexport */ main_dashboard_button; },
"initializeEditor": function() { return /* binding */ initializeEditor; },
"reinitializeEditor": function() { return /* binding */ reinitializeEditor; },
"store": function() { return /* reexport */ store_store; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/interface/build-module/store/actions.js
var actions_namespaceObject = {};
__webpack_require__.r(actions_namespaceObject);
__webpack_require__.d(actions_namespaceObject, {
"disableComplementaryArea": function() { return disableComplementaryArea; },
"enableComplementaryArea": function() { return enableComplementaryArea; },
"pinItem": function() { return pinItem; },
"setDefaultComplementaryArea": function() { return setDefaultComplementaryArea; },
"setFeatureDefaults": function() { return setFeatureDefaults; },
"setFeatureValue": function() { return setFeatureValue; },
"toggleFeature": function() { return toggleFeature; },
"unpinItem": function() { return unpinItem; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/interface/build-module/store/selectors.js
var selectors_namespaceObject = {};
__webpack_require__.r(selectors_namespaceObject);
__webpack_require__.d(selectors_namespaceObject, {
"getActiveComplementaryArea": function() { return getActiveComplementaryArea; },
"isFeatureActive": function() { return isFeatureActive; },
"isItemPinned": function() { return isItemPinned; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/edit-post/build-module/store/actions.js
var store_actions_namespaceObject = {};
__webpack_require__.r(store_actions_namespaceObject);
__webpack_require__.d(store_actions_namespaceObject, {
"__experimentalSetPreviewDeviceType": function() { return __experimentalSetPreviewDeviceType; },
"__unstableCreateTemplate": function() { return __unstableCreateTemplate; },
"__unstableSwitchToTemplateMode": function() { return __unstableSwitchToTemplateMode; },
"closeGeneralSidebar": function() { return closeGeneralSidebar; },
"closeModal": function() { return closeModal; },
"closePublishSidebar": function() { return closePublishSidebar; },
"hideBlockTypes": function() { return hideBlockTypes; },
"initializeMetaBoxes": function() { return initializeMetaBoxes; },
"metaBoxUpdatesFailure": function() { return metaBoxUpdatesFailure; },
"metaBoxUpdatesSuccess": function() { return metaBoxUpdatesSuccess; },
"openGeneralSidebar": function() { return openGeneralSidebar; },
"openModal": function() { return openModal; },
"openPublishSidebar": function() { return openPublishSidebar; },
"removeEditorPanel": function() { return removeEditorPanel; },
"requestMetaBoxUpdates": function() { return requestMetaBoxUpdates; },
"setAvailableMetaBoxesPerLocation": function() { return setAvailableMetaBoxesPerLocation; },
"setIsEditingTemplate": function() { return setIsEditingTemplate; },
"setIsInserterOpened": function() { return setIsInserterOpened; },
"setIsListViewOpened": function() { return setIsListViewOpened; },
"showBlockTypes": function() { return showBlockTypes; },
"switchEditorMode": function() { return switchEditorMode; },
"toggleEditorPanelEnabled": function() { return toggleEditorPanelEnabled; },
"toggleEditorPanelOpened": function() { return toggleEditorPanelOpened; },
"toggleFeature": function() { return actions_toggleFeature; },
"togglePinnedPluginItem": function() { return togglePinnedPluginItem; },
"togglePublishSidebar": function() { return togglePublishSidebar; },
"updatePreferredStyleVariations": function() { return updatePreferredStyleVariations; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/edit-post/build-module/store/selectors.js
var store_selectors_namespaceObject = {};
__webpack_require__.r(store_selectors_namespaceObject);
__webpack_require__.d(store_selectors_namespaceObject, {
"__experimentalGetInsertionPoint": function() { return __experimentalGetInsertionPoint; },
"__experimentalGetPreviewDeviceType": function() { return __experimentalGetPreviewDeviceType; },
"areMetaBoxesInitialized": function() { return areMetaBoxesInitialized; },
"getActiveGeneralSidebarName": function() { return getActiveGeneralSidebarName; },
"getActiveMetaBoxLocations": function() { return getActiveMetaBoxLocations; },
"getAllMetaBoxes": function() { return getAllMetaBoxes; },
"getEditedPostTemplate": function() { return getEditedPostTemplate; },
"getEditorMode": function() { return getEditorMode; },
"getHiddenBlockTypes": function() { return getHiddenBlockTypes; },
"getMetaBoxesPerLocation": function() { return getMetaBoxesPerLocation; },
"getPreference": function() { return getPreference; },
"getPreferences": function() { return getPreferences; },
"hasMetaBoxes": function() { return hasMetaBoxes; },
"isEditingTemplate": function() { return selectors_isEditingTemplate; },
"isEditorPanelEnabled": function() { return isEditorPanelEnabled; },
"isEditorPanelOpened": function() { return isEditorPanelOpened; },
"isEditorPanelRemoved": function() { return isEditorPanelRemoved; },
"isEditorSidebarOpened": function() { return isEditorSidebarOpened; },
"isFeatureActive": function() { return selectors_isFeatureActive; },
"isInserterOpened": function() { return isInserterOpened; },
"isListViewOpened": function() { return isListViewOpened; },
"isMetaBoxLocationActive": function() { return isMetaBoxLocationActive; },
"isMetaBoxLocationVisible": function() { return isMetaBoxLocationVisible; },
"isModalActive": function() { return isModalActive; },
"isPluginItemPinned": function() { return isPluginItemPinned; },
"isPluginSidebarOpened": function() { return isPluginSidebarOpened; },
"isPublishSidebarOpened": function() { return isPublishSidebarOpened; },
"isSavingMetaBoxes": function() { return selectors_isSavingMetaBoxes; }
});
;// CONCATENATED MODULE: external ["wp","element"]
var external_wp_element_namespaceObject = window["wp"]["element"];
;// CONCATENATED MODULE: external ["wp","blocks"]
var external_wp_blocks_namespaceObject = window["wp"]["blocks"];
;// CONCATENATED MODULE: external ["wp","blockLibrary"]
var external_wp_blockLibrary_namespaceObject = window["wp"]["blockLibrary"];
;// CONCATENATED MODULE: external ["wp","deprecated"]
var external_wp_deprecated_namespaceObject = window["wp"]["deprecated"];
var external_wp_deprecated_default = /*#__PURE__*/__webpack_require__.n(external_wp_deprecated_namespaceObject);
;// CONCATENATED MODULE: external ["wp","data"]
var external_wp_data_namespaceObject = window["wp"]["data"];
;// CONCATENATED MODULE: external ["wp","hooks"]
var external_wp_hooks_namespaceObject = window["wp"]["hooks"];
;// CONCATENATED MODULE: external ["wp","preferences"]
var external_wp_preferences_namespaceObject = window["wp"]["preferences"];
;// CONCATENATED MODULE: external ["wp","widgets"]
var external_wp_widgets_namespaceObject = window["wp"]["widgets"];
;// CONCATENATED MODULE: external ["wp","mediaUtils"]
var external_wp_mediaUtils_namespaceObject = window["wp"]["mediaUtils"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/hooks/components/index.js
/**
* WordPress dependencies
*/
const replaceMediaUpload = () => external_wp_mediaUtils_namespaceObject.MediaUpload;
(0,external_wp_hooks_namespaceObject.addFilter)('editor.MediaUpload', 'core/edit-post/replace-media-upload', replaceMediaUpload);
;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/extends.js
function _extends() {
return _extends = Object.assign ? Object.assign.bind() : function (n) {
for (var e = 1; e < arguments.length; e++) {
var t = arguments[e];
for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
}
return n;
}, _extends.apply(null, arguments);
}
;// CONCATENATED MODULE: external ["wp","components"]
var external_wp_components_namespaceObject = window["wp"]["components"];
;// CONCATENATED MODULE: external ["wp","blockEditor"]
var external_wp_blockEditor_namespaceObject = window["wp"]["blockEditor"];
;// CONCATENATED MODULE: external ["wp","i18n"]
var external_wp_i18n_namespaceObject = window["wp"]["i18n"];
;// CONCATENATED MODULE: external ["wp","compose"]
var external_wp_compose_namespaceObject = window["wp"]["compose"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/hooks/validate-multiple-use/index.js
/**
* WordPress dependencies
*/
const enhance = (0,external_wp_compose_namespaceObject.compose)(
/**
* For blocks whose block type doesn't support `multiple`, provides the
* wrapped component with `originalBlockClientId` -- a reference to the
* first block of the same type in the content -- if and only if that
* "original" block is not the current one. Thus, an inexisting
* `originalBlockClientId` prop signals that the block is valid.
*
* @param {WPComponent} WrappedBlockEdit A filtered BlockEdit instance.
*
* @return {WPComponent} Enhanced component with merged state data props.
*/
(0,external_wp_data_namespaceObject.withSelect)((select, block) => {
const multiple = (0,external_wp_blocks_namespaceObject.hasBlockSupport)(block.name, 'multiple', true); // For block types with `multiple` support, there is no "original
// block" to be found in the content, as the block itself is valid.
if (multiple) {
return {};
} // Otherwise, only pass `originalBlockClientId` if it refers to a different
// block from the current one.
const blocks = select(external_wp_blockEditor_namespaceObject.store).getBlocks();
const firstOfSameType = blocks.find(_ref => {
let {
name
} = _ref;
return block.name === name;
});
const isInvalid = firstOfSameType && firstOfSameType.clientId !== block.clientId;
return {
originalBlockClientId: isInvalid && firstOfSameType.clientId
};
}), (0,external_wp_data_namespaceObject.withDispatch)((dispatch, _ref2) => {
let {
originalBlockClientId
} = _ref2;
return {
selectFirst: () => dispatch(external_wp_blockEditor_namespaceObject.store).selectBlock(originalBlockClientId)
};
}));
const withMultipleValidation = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(BlockEdit => {
return enhance(_ref3 => {
let {
originalBlockClientId,
selectFirst,
...props
} = _ref3;
if (!originalBlockClientId) {
return (0,external_wp_element_namespaceObject.createElement)(BlockEdit, props);
}
const blockType = (0,external_wp_blocks_namespaceObject.getBlockType)(props.name);
const outboundType = getOutboundType(props.name);
return [(0,external_wp_element_namespaceObject.createElement)("div", {
key: "invalid-preview",
style: {
minHeight: '60px'
}
}, (0,external_wp_element_namespaceObject.createElement)(BlockEdit, _extends({
key: "block-edit"
}, props))), (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.Warning, {
key: "multiple-use-warning",
actions: [(0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
key: "find-original",
variant: "secondary",
onClick: selectFirst
}, (0,external_wp_i18n_namespaceObject.__)('Find original')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
key: "remove",
variant: "secondary",
onClick: () => props.onReplace([])
}, (0,external_wp_i18n_namespaceObject.__)('Remove')), outboundType && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
key: "transform",
variant: "secondary",
onClick: () => props.onReplace((0,external_wp_blocks_namespaceObject.createBlock)(outboundType.name, props.attributes))
}, (0,external_wp_i18n_namespaceObject.__)('Transform into:'), " ", outboundType.title)]
}, (0,external_wp_element_namespaceObject.createElement)("strong", null, blockType === null || blockType === void 0 ? void 0 : blockType.title, ": "), (0,external_wp_i18n_namespaceObject.__)('This block can only be used once.'))];
});
}, 'withMultipleValidation');
/**
* Given a base block name, returns the default block type to which to offer
* transforms.
*
* @param {string} blockName Base block name.
*
* @return {?Object} The chosen default block type.
*/
function getOutboundType(blockName) {
// Grab the first outbound transform.
const transform = (0,external_wp_blocks_namespaceObject.findTransform)((0,external_wp_blocks_namespaceObject.getBlockTransforms)('to', blockName), _ref4 => {
let {
type,
blocks
} = _ref4;
return type === 'block' && blocks.length === 1;
} // What about when .length > 1?
);
if (!transform) {
return null;
}
return (0,external_wp_blocks_namespaceObject.getBlockType)(transform.blocks[0]);
}
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockEdit', 'core/edit-post/validate-multiple-use/with-multiple-validation', withMultipleValidation);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/hooks/index.js
/**
* Internal dependencies
*/
;// CONCATENATED MODULE: external ["wp","primitives"]
var external_wp_primitives_namespaceObject = window["wp"]["primitives"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/external.js
/**
* WordPress dependencies
*/
const external = (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: "M18.2 17c0 .7-.6 1.2-1.2 1.2H7c-.7 0-1.2-.6-1.2-1.2V7c0-.7.6-1.2 1.2-1.2h3.2V4.2H7C5.5 4.2 4.2 5.5 4.2 7v10c0 1.5 1.2 2.8 2.8 2.8h10c1.5 0 2.8-1.2 2.8-2.8v-3.6h-1.5V17zM14.9 3v1.5h3.7l-6.4 6.4 1.1 1.1 6.4-6.4v3.7h1.5V3h-6.3z"
}));
/* harmony default export */ var library_external = (external);
;// CONCATENATED MODULE: external ["wp","plugins"]
var external_wp_plugins_namespaceObject = window["wp"]["plugins"];
;// CONCATENATED MODULE: external ["wp","url"]
var external_wp_url_namespaceObject = window["wp"]["url"];
;// CONCATENATED MODULE: external ["wp","notices"]
var external_wp_notices_namespaceObject = window["wp"]["notices"];
;// CONCATENATED MODULE: external ["wp","editor"]
var external_wp_editor_namespaceObject = window["wp"]["editor"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/plugins/copy-content-menu-item/index.js
/**
* WordPress dependencies
*/
function CopyContentMenuItem() {
const {
createNotice
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_notices_namespaceObject.store);
const getText = (0,external_wp_data_namespaceObject.useSelect)(select => () => select(external_wp_editor_namespaceObject.store).getEditedPostAttribute('content'), []);
function onSuccess() {
createNotice('info', (0,external_wp_i18n_namespaceObject.__)('All content copied.'), {
isDismissible: true,
type: 'snackbar'
});
}
const ref = (0,external_wp_compose_namespaceObject.useCopyToClipboard)(getText, onSuccess);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
ref: ref
}, (0,external_wp_i18n_namespaceObject.__)('Copy all blocks'));
}
;// CONCATENATED MODULE: external ["wp","keycodes"]
var external_wp_keycodes_namespaceObject = window["wp"]["keycodes"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/store/reducer.js
/**
* WordPress dependencies
*/
/**
* Reducer storing the list of all programmatically removed panels.
*
* @param {Array} state Current state.
* @param {Object} action Action object.
*
* @return {Array} Updated state.
*/
function removedPanels() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'REMOVE_PANEL':
if (!state.includes(action.panelName)) {
return [...state, action.panelName];
}
}
return state;
}
/**
* Reducer for storing the name of the open modal, or null if no modal is open.
*
* @param {Object} state Previous state.
* @param {Object} action Action object containing the `name` of the modal
*
* @return {Object} Updated state
*/
function activeModal() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'OPEN_MODAL':
return action.name;
case 'CLOSE_MODAL':
return null;
}
return state;
}
function publishSidebarActive() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'OPEN_PUBLISH_SIDEBAR':
return true;
case 'CLOSE_PUBLISH_SIDEBAR':
return false;
case 'TOGGLE_PUBLISH_SIDEBAR':
return !state;
}
return state;
}
/**
* Reducer keeping track of the meta boxes isSaving state.
* A "true" value means the meta boxes saving request is in-flight.
*
*
* @param {boolean} state Previous state.
* @param {Object} action Action Object.
*
* @return {Object} Updated state.
*/
function isSavingMetaBoxes() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'REQUEST_META_BOX_UPDATES':
return true;
case 'META_BOX_UPDATES_SUCCESS':
case 'META_BOX_UPDATES_FAILURE':
return false;
default:
return state;
}
}
function mergeMetaboxes() {
let metaboxes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
let newMetaboxes = arguments.length > 1 ? arguments[1] : undefined;
const mergedMetaboxes = [...metaboxes];
for (const metabox of newMetaboxes) {
const existing = mergedMetaboxes.findIndex(box => box.id === metabox.id);
if (existing !== -1) {
mergedMetaboxes[existing] = metabox;
} else {
mergedMetaboxes.push(metabox);
}
}
return mergedMetaboxes;
}
/**
* Reducer keeping track of the meta boxes per location.
*
* @param {boolean} state Previous state.
* @param {Object} action Action Object.
*
* @return {Object} Updated state.
*/
function metaBoxLocations() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'SET_META_BOXES_PER_LOCATIONS':
{
const newState = { ...state
};
for (const [location, metaboxes] of Object.entries(action.metaBoxesPerLocation)) {
newState[location] = mergeMetaboxes(newState[location], metaboxes);
}
return newState;
}
}
return state;
}
/**
* Reducer returning the editing canvas device type.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
function deviceType() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'Desktop';
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'SET_PREVIEW_DEVICE_TYPE':
return action.deviceType;
}
return state;
}
/**
* Reducer to set the block inserter panel open or closed.
*
* Note: this reducer interacts with the list view panel reducer
* to make sure that only one of the two panels is open at the same time.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*/
function blockInserterPanel() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'SET_IS_LIST_VIEW_OPENED':
return action.isOpen ? false : state;
case 'SET_IS_INSERTER_OPENED':
return action.value;
}
return state;
}
/**
* Reducer to set the list view panel open or closed.
*
* Note: this reducer interacts with the inserter panel reducer
* to make sure that only one of the two panels is open at the same time.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*/
function listViewPanel() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'SET_IS_INSERTER_OPENED':
return action.value ? false : state;
case 'SET_IS_LIST_VIEW_OPENED':
return action.isOpen;
}
return state;
}
/**
* Reducer tracking whether template editing is on or off.
*
* @param {boolean} state
* @param {Object} action
*/
function isEditingTemplate() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'SET_IS_EDITING_TEMPLATE':
return action.value;
}
return state;
}
/**
* Reducer tracking whether meta boxes are initialized.
*
* @param {boolean} state
* @param {Object} action
*
* @return {boolean} Updated state.
*/
function metaBoxesInitialized() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'META_BOXES_INITIALIZED':
return true;
}
return state;
}
const metaBoxes = (0,external_wp_data_namespaceObject.combineReducers)({
isSaving: isSavingMetaBoxes,
locations: metaBoxLocations,
initialized: metaBoxesInitialized
});
/* harmony default export */ var reducer = ((0,external_wp_data_namespaceObject.combineReducers)({
activeModal,
metaBoxes,
publishSidebarActive,
removedPanels,
deviceType,
blockInserterPanel,
listViewPanel,
isEditingTemplate
}));
;// CONCATENATED MODULE: external ["wp","apiFetch"]
var external_wp_apiFetch_namespaceObject = window["wp"]["apiFetch"];
var external_wp_apiFetch_default = /*#__PURE__*/__webpack_require__.n(external_wp_apiFetch_namespaceObject);
// EXTERNAL MODULE: ./node_modules/classnames/index.js
var classnames = __webpack_require__(7153);
var classnames_default = /*#__PURE__*/__webpack_require__.n(classnames);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/check.js
/**
* WordPress dependencies
*/
const check = (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: "M16.7 7.1l-6.3 8.5-3.3-2.5-.9 1.2 4.5 3.4L17.9 8z"
}));
/* harmony default export */ var library_check = (check);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/star-filled.js
/**
* WordPress dependencies
*/
const starFilled = (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: "M11.776 4.454a.25.25 0 01.448 0l2.069 4.192a.25.25 0 00.188.137l4.626.672a.25.25 0 01.139.426l-3.348 3.263a.25.25 0 00-.072.222l.79 4.607a.25.25 0 01-.362.263l-4.138-2.175a.25.25 0 00-.232 0l-4.138 2.175a.25.25 0 01-.363-.263l.79-4.607a.25.25 0 00-.071-.222L4.754 9.881a.25.25 0 01.139-.426l4.626-.672a.25.25 0 00.188-.137l2.069-4.192z"
}));
/* harmony default export */ var star_filled = (starFilled);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/star-empty.js
/**
* WordPress dependencies
*/
const starEmpty = (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, {
fillRule: "evenodd",
d: "M9.706 8.646a.25.25 0 01-.188.137l-4.626.672a.25.25 0 00-.139.427l3.348 3.262a.25.25 0 01.072.222l-.79 4.607a.25.25 0 00.362.264l4.138-2.176a.25.25 0 01.233 0l4.137 2.175a.25.25 0 00.363-.263l-.79-4.607a.25.25 0 01.072-.222l3.347-3.262a.25.25 0 00-.139-.427l-4.626-.672a.25.25 0 01-.188-.137l-2.069-4.192a.25.25 0 00-.448 0L9.706 8.646zM12 7.39l-.948 1.921a1.75 1.75 0 01-1.317.957l-2.12.308 1.534 1.495c.412.402.6.982.503 1.55l-.362 2.11 1.896-.997a1.75 1.75 0 011.629 0l1.895.997-.362-2.11a1.75 1.75 0 01.504-1.55l1.533-1.495-2.12-.308a1.75 1.75 0 01-1.317-.957L12 7.39z",
clipRule: "evenodd"
}));
/* harmony default export */ var star_empty = (starEmpty);
;// CONCATENATED MODULE: external ["wp","viewport"]
var external_wp_viewport_namespaceObject = window["wp"]["viewport"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/close-small.js
/**
* WordPress dependencies
*/
const closeSmall = (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: "M12 13.06l3.712 3.713 1.061-1.06L13.061 12l3.712-3.712-1.06-1.06L12 10.938 8.288 7.227l-1.061 1.06L10.939 12l-3.712 3.712 1.06 1.061L12 13.061z"
}));
/* harmony default export */ var close_small = (closeSmall);
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/store/actions.js
/**
* WordPress dependencies
*/
/**
* Set a default complementary area.
*
* @param {string} scope Complementary area scope.
* @param {string} area Area identifier.
*
* @return {Object} Action object.
*/
const setDefaultComplementaryArea = (scope, area) => ({
type: 'SET_DEFAULT_COMPLEMENTARY_AREA',
scope,
area
});
/**
* Enable the complementary area.
*
* @param {string} scope Complementary area scope.
* @param {string} area Area identifier.
*/
const enableComplementaryArea = (scope, area) => _ref => {
let {
registry,
dispatch
} = _ref;
// Return early if there's no area.
if (!area) {
return;
}
const isComplementaryAreaVisible = registry.select(external_wp_preferences_namespaceObject.store).get(scope, 'isComplementaryAreaVisible');
if (!isComplementaryAreaVisible) {
registry.dispatch(external_wp_preferences_namespaceObject.store).set(scope, 'isComplementaryAreaVisible', true);
}
dispatch({
type: 'ENABLE_COMPLEMENTARY_AREA',
scope,
area
});
};
/**
* Disable the complementary area.
*
* @param {string} scope Complementary area scope.
*/
const disableComplementaryArea = scope => _ref2 => {
let {
registry
} = _ref2;
const isComplementaryAreaVisible = registry.select(external_wp_preferences_namespaceObject.store).get(scope, 'isComplementaryAreaVisible');
if (isComplementaryAreaVisible) {
registry.dispatch(external_wp_preferences_namespaceObject.store).set(scope, 'isComplementaryAreaVisible', false);
}
};
/**
* Pins an item.
*
* @param {string} scope Item scope.
* @param {string} item Item identifier.
*
* @return {Object} Action object.
*/
const pinItem = (scope, item) => _ref3 => {
let {
registry
} = _ref3;
// Return early if there's no item.
if (!item) {
return;
}
const pinnedItems = registry.select(external_wp_preferences_namespaceObject.store).get(scope, 'pinnedItems'); // The item is already pinned, there's nothing to do.
if ((pinnedItems === null || pinnedItems === void 0 ? void 0 : pinnedItems[item]) === true) {
return;
}
registry.dispatch(external_wp_preferences_namespaceObject.store).set(scope, 'pinnedItems', { ...pinnedItems,
[item]: true
});
};
/**
* Unpins an item.
*
* @param {string} scope Item scope.
* @param {string} item Item identifier.
*/
const unpinItem = (scope, item) => _ref4 => {
let {
registry
} = _ref4;
// Return early if there's no item.
if (!item) {
return;
}
const pinnedItems = registry.select(external_wp_preferences_namespaceObject.store).get(scope, 'pinnedItems');
registry.dispatch(external_wp_preferences_namespaceObject.store).set(scope, 'pinnedItems', { ...pinnedItems,
[item]: false
});
};
/**
* Returns an action object used in signalling that a feature should be toggled.
*
* @param {string} scope The feature scope (e.g. core/edit-post).
* @param {string} featureName The feature name.
*/
function toggleFeature(scope, featureName) {
return function (_ref5) {
let {
registry
} = _ref5;
external_wp_deprecated_default()(`dispatch( 'core/interface' ).toggleFeature`, {
since: '6.0',
alternative: `dispatch( 'core/preferences' ).toggle`
});
registry.dispatch(external_wp_preferences_namespaceObject.store).toggle(scope, featureName);
};
}
/**
* Returns an action object used in signalling that a feature should be set to
* a true or false value
*
* @param {string} scope The feature scope (e.g. core/edit-post).
* @param {string} featureName The feature name.
* @param {boolean} value The value to set.
*
* @return {Object} Action object.
*/
function setFeatureValue(scope, featureName, value) {
return function (_ref6) {
let {
registry
} = _ref6;
external_wp_deprecated_default()(`dispatch( 'core/interface' ).setFeatureValue`, {
since: '6.0',
alternative: `dispatch( 'core/preferences' ).set`
});
registry.dispatch(external_wp_preferences_namespaceObject.store).set(scope, featureName, !!value);
};
}
/**
* Returns an action object used in signalling that defaults should be set for features.
*
* @param {string} scope The feature scope (e.g. core/edit-post).
* @param {Object<string, boolean>} defaults A key/value map of feature names to values.
*
* @return {Object} Action object.
*/
function setFeatureDefaults(scope, defaults) {
return function (_ref7) {
let {
registry
} = _ref7;
external_wp_deprecated_default()(`dispatch( 'core/interface' ).setFeatureDefaults`, {
since: '6.0',
alternative: `dispatch( 'core/preferences' ).setDefaults`
});
registry.dispatch(external_wp_preferences_namespaceObject.store).setDefaults(scope, defaults);
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/store/selectors.js
/**
* WordPress dependencies
*/
/**
* Returns the complementary area that is active in a given scope.
*
* @param {Object} state Global application state.
* @param {string} scope Item scope.
*
* @return {string | null | undefined} The complementary area that is active in the given scope.
*/
const getActiveComplementaryArea = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (state, scope) => {
var _state$complementaryA;
const isComplementaryAreaVisible = select(external_wp_preferences_namespaceObject.store).get(scope, 'isComplementaryAreaVisible'); // Return `undefined` to indicate that the user has never toggled
// visibility, this is the vanilla default. Other code relies on this
// nuance in the return value.
if (isComplementaryAreaVisible === undefined) {
return undefined;
} // Return `null` to indicate the user hid the complementary area.
if (!isComplementaryAreaVisible) {
return null;
}
return state === null || state === void 0 ? void 0 : (_state$complementaryA = state.complementaryAreas) === null || _state$complementaryA === void 0 ? void 0 : _state$complementaryA[scope];
});
/**
* Returns a boolean indicating if an item is pinned or not.
*
* @param {Object} state Global application state.
* @param {string} scope Scope.
* @param {string} item Item to check.
*
* @return {boolean} True if the item is pinned and false otherwise.
*/
const isItemPinned = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (state, scope, item) => {
var _pinnedItems$item;
const pinnedItems = select(external_wp_preferences_namespaceObject.store).get(scope, 'pinnedItems');
return (_pinnedItems$item = pinnedItems === null || pinnedItems === void 0 ? void 0 : pinnedItems[item]) !== null && _pinnedItems$item !== void 0 ? _pinnedItems$item : true;
});
/**
* Returns a boolean indicating whether a feature is active for a particular
* scope.
*
* @param {Object} state The store state.
* @param {string} scope The scope of the feature (e.g. core/edit-post).
* @param {string} featureName The name of the feature.
*
* @return {boolean} Is the feature enabled?
*/
const isFeatureActive = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (state, scope, featureName) => {
external_wp_deprecated_default()(`select( 'core/interface' ).isFeatureActive( scope, featureName )`, {
since: '6.0',
alternative: `select( 'core/preferences' ).get( scope, featureName )`
});
return !!select(external_wp_preferences_namespaceObject.store).get(scope, featureName);
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/store/reducer.js
/**
* WordPress dependencies
*/
function complementaryAreas() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'SET_DEFAULT_COMPLEMENTARY_AREA':
{
const {
scope,
area
} = action; // If there's already an area, don't overwrite it.
if (state[scope]) {
return state;
}
return { ...state,
[scope]: area
};
}
case 'ENABLE_COMPLEMENTARY_AREA':
{
const {
scope,
area
} = action;
return { ...state,
[scope]: area
};
}
}
return state;
}
/* harmony default export */ var store_reducer = ((0,external_wp_data_namespaceObject.combineReducers)({
complementaryAreas
}));
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/store/constants.js
/**
* The identifier for the data store.
*
* @type {string}
*/
const STORE_NAME = 'core/interface';
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/store/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Store definition for the interface 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, {
reducer: store_reducer,
actions: actions_namespaceObject,
selectors: selectors_namespaceObject
}); // 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.register)(store);
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/complementary-area-context/index.js
/**
* WordPress dependencies
*/
/* harmony default export */ var complementary_area_context = ((0,external_wp_plugins_namespaceObject.withPluginContext)((context, ownProps) => {
return {
icon: ownProps.icon || context.icon,
identifier: ownProps.identifier || `${context.name}/${ownProps.name}`
};
}));
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/complementary-area-toggle/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ComplementaryAreaToggle(_ref) {
let {
as = external_wp_components_namespaceObject.Button,
scope,
identifier,
icon,
selectedIcon,
name,
...props
} = _ref;
const ComponentToUse = as;
const isSelected = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).getActiveComplementaryArea(scope) === identifier, [identifier]);
const {
enableComplementaryArea,
disableComplementaryArea
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
return (0,external_wp_element_namespaceObject.createElement)(ComponentToUse, _extends({
icon: selectedIcon && isSelected ? selectedIcon : icon,
onClick: () => {
if (isSelected) {
disableComplementaryArea(scope);
} else {
enableComplementaryArea(scope, identifier);
}
}
}, props));
}
/* harmony default export */ var complementary_area_toggle = (complementary_area_context(ComplementaryAreaToggle));
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/complementary-area-header/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const ComplementaryAreaHeader = _ref => {
let {
smallScreenTitle,
children,
className,
toggleButtonProps
} = _ref;
const toggleButton = (0,external_wp_element_namespaceObject.createElement)(complementary_area_toggle, _extends({
icon: close_small
}, toggleButtonProps));
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-panel__header interface-complementary-area-header__small"
}, smallScreenTitle && (0,external_wp_element_namespaceObject.createElement)("span", {
className: "interface-complementary-area-header__small-title"
}, smallScreenTitle), toggleButton), (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('components-panel__header', 'interface-complementary-area-header', className),
tabIndex: -1
}, children, toggleButton));
};
/* harmony default export */ var complementary_area_header = (ComplementaryAreaHeader);
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/action-item/index.js
/**
* WordPress dependencies
*/
const noop = () => {};
function ActionItemSlot(_ref) {
let {
name,
as: Component = external_wp_components_namespaceObject.ButtonGroup,
fillProps = {},
bubblesVirtually,
...props
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Slot, {
name: name,
bubblesVirtually: bubblesVirtually,
fillProps: fillProps
}, fills => {
if (!external_wp_element_namespaceObject.Children.toArray(fills).length) {
return null;
} // Special handling exists for backward compatibility.
// It ensures that menu items created by plugin authors aren't
// duplicated with automatically injected menu items coming
// from pinnable plugin sidebars.
// @see https://github.com/WordPress/gutenberg/issues/14457
const initializedByPlugins = [];
external_wp_element_namespaceObject.Children.forEach(fills, _ref2 => {
let {
props: {
__unstableExplicitMenuItem,
__unstableTarget
}
} = _ref2;
if (__unstableTarget && __unstableExplicitMenuItem) {
initializedByPlugins.push(__unstableTarget);
}
});
const children = external_wp_element_namespaceObject.Children.map(fills, child => {
if (!child.props.__unstableExplicitMenuItem && initializedByPlugins.includes(child.props.__unstableTarget)) {
return null;
}
return child;
});
return (0,external_wp_element_namespaceObject.createElement)(Component, props, children);
});
}
function ActionItem(_ref3) {
let {
name,
as: Component = external_wp_components_namespaceObject.Button,
onClick,
...props
} = _ref3;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Fill, {
name: name
}, _ref4 => {
let {
onClick: fpOnClick
} = _ref4;
return (0,external_wp_element_namespaceObject.createElement)(Component, _extends({
onClick: onClick || fpOnClick ? function () {
(onClick || noop)(...arguments);
(fpOnClick || noop)(...arguments);
} : undefined
}, props));
});
}
ActionItem.Slot = ActionItemSlot;
/* harmony default export */ var action_item = (ActionItem);
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/complementary-area-more-menu-item/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const PluginsMenuItem = _ref => {
let {
// Menu item is marked with unstable prop for backward compatibility.
// They are removed so they don't leak to DOM elements.
// @see https://github.com/WordPress/gutenberg/issues/14457
__unstableExplicitMenuItem,
__unstableTarget,
...restProps
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, restProps);
};
function ComplementaryAreaMoreMenuItem(_ref2) {
let {
scope,
target,
__unstableExplicitMenuItem,
...props
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(complementary_area_toggle, _extends({
as: toggleProps => {
return (0,external_wp_element_namespaceObject.createElement)(action_item, _extends({
__unstableExplicitMenuItem: __unstableExplicitMenuItem,
__unstableTarget: `${scope}/${target}`,
as: PluginsMenuItem,
name: `${scope}/plugin-more-menu`
}, toggleProps));
},
role: "menuitemcheckbox",
selectedIcon: library_check,
name: target,
scope: scope
}, props));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/pinned-items/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
function PinnedItems(_ref) {
let {
scope,
...props
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Fill, _extends({
name: `PinnedItems/${scope}`
}, props));
}
function PinnedItemsSlot(_ref2) {
let {
scope,
className,
...props
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Slot, _extends({
name: `PinnedItems/${scope}`
}, props), fills => (fills === null || fills === void 0 ? void 0 : fills.length) > 0 && (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()(className, 'interface-pinned-items')
}, fills));
}
PinnedItems.Slot = PinnedItemsSlot;
/* harmony default export */ var pinned_items = (PinnedItems);
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/complementary-area/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ComplementaryAreaSlot(_ref) {
let {
scope,
...props
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Slot, _extends({
name: `ComplementaryArea/${scope}`
}, props));
}
function ComplementaryAreaFill(_ref2) {
let {
scope,
children,
className
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Fill, {
name: `ComplementaryArea/${scope}`
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: className
}, children));
}
function useAdjustComplementaryListener(scope, identifier, activeArea, isActive, isSmall) {
const previousIsSmall = (0,external_wp_element_namespaceObject.useRef)(false);
const shouldOpenWhenNotSmall = (0,external_wp_element_namespaceObject.useRef)(false);
const {
enableComplementaryArea,
disableComplementaryArea
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
(0,external_wp_element_namespaceObject.useEffect)(() => {
// If the complementary area is active and the editor is switching from a big to a small window size.
if (isActive && isSmall && !previousIsSmall.current) {
// Disable the complementary area.
disableComplementaryArea(scope); // Flag the complementary area to be reopened when the window size goes from small to big.
shouldOpenWhenNotSmall.current = true;
} else if ( // If there is a flag indicating the complementary area should be enabled when we go from small to big window size
// and we are going from a small to big window size.
shouldOpenWhenNotSmall.current && !isSmall && previousIsSmall.current) {
// Remove the flag indicating the complementary area should be enabled.
shouldOpenWhenNotSmall.current = false; // Enable the complementary area.
enableComplementaryArea(scope, identifier);
} else if ( // If the flag is indicating the current complementary should be reopened but another complementary area becomes active,
// remove the flag.
shouldOpenWhenNotSmall.current && activeArea && activeArea !== identifier) {
shouldOpenWhenNotSmall.current = false;
}
if (isSmall !== previousIsSmall.current) {
previousIsSmall.current = isSmall;
}
}, [isActive, isSmall, scope, identifier, activeArea]);
}
function ComplementaryArea(_ref3) {
let {
children,
className,
closeLabel = (0,external_wp_i18n_namespaceObject.__)('Close plugin'),
identifier,
header,
headerClassName,
icon,
isPinnable = true,
panelClassName,
scope,
name,
smallScreenTitle,
title,
toggleShortcut,
isActiveByDefault,
showIconLabels = false
} = _ref3;
const {
isActive,
isPinned,
activeArea,
isSmall,
isLarge
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getActiveComplementaryArea,
isItemPinned
} = select(store);
const _activeArea = getActiveComplementaryArea(scope);
return {
isActive: _activeArea === identifier,
isPinned: isItemPinned(scope, identifier),
activeArea: _activeArea,
isSmall: select(external_wp_viewport_namespaceObject.store).isViewportMatch('< medium'),
isLarge: select(external_wp_viewport_namespaceObject.store).isViewportMatch('large')
};
}, [identifier, scope]);
useAdjustComplementaryListener(scope, identifier, activeArea, isActive, isSmall);
const {
enableComplementaryArea,
disableComplementaryArea,
pinItem,
unpinItem
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (isActiveByDefault && activeArea === undefined && !isSmall) {
enableComplementaryArea(scope, identifier);
}
}, [activeArea, isActiveByDefault, scope, identifier, isSmall]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, isPinnable && (0,external_wp_element_namespaceObject.createElement)(pinned_items, {
scope: scope
}, isPinned && (0,external_wp_element_namespaceObject.createElement)(complementary_area_toggle, {
scope: scope,
identifier: identifier,
isPressed: isActive && (!showIconLabels || isLarge),
"aria-expanded": isActive,
label: title,
icon: showIconLabels ? library_check : icon,
showTooltip: !showIconLabels,
variant: showIconLabels ? 'tertiary' : undefined
})), name && isPinnable && (0,external_wp_element_namespaceObject.createElement)(ComplementaryAreaMoreMenuItem, {
target: name,
scope: scope,
icon: icon
}, title), isActive && (0,external_wp_element_namespaceObject.createElement)(ComplementaryAreaFill, {
className: classnames_default()('interface-complementary-area', className),
scope: scope
}, (0,external_wp_element_namespaceObject.createElement)(complementary_area_header, {
className: headerClassName,
closeLabel: closeLabel,
onClose: () => disableComplementaryArea(scope),
smallScreenTitle: smallScreenTitle,
toggleButtonProps: {
label: closeLabel,
shortcut: toggleShortcut,
scope,
identifier
}
}, header || (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("strong", null, title), isPinnable && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "interface-complementary-area__pin-unpin-item",
icon: isPinned ? star_filled : star_empty,
label: isPinned ? (0,external_wp_i18n_namespaceObject.__)('Unpin from toolbar') : (0,external_wp_i18n_namespaceObject.__)('Pin to toolbar'),
onClick: () => (isPinned ? unpinItem : pinItem)(scope, identifier),
isPressed: isPinned,
"aria-expanded": isPinned
}))), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Panel, {
className: panelClassName
}, children)));
}
const ComplementaryAreaWrapped = complementary_area_context(ComplementaryArea);
ComplementaryAreaWrapped.Slot = ComplementaryAreaSlot;
/* harmony default export */ var complementary_area = (ComplementaryAreaWrapped);
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/fullscreen-mode/index.js
/**
* WordPress dependencies
*/
const FullscreenMode = _ref => {
let {
isActive
} = _ref;
(0,external_wp_element_namespaceObject.useEffect)(() => {
let isSticky = false; // `is-fullscreen-mode` is set in PHP as a body class by Gutenberg, and this causes
// `sticky-menu` to be applied by WordPress and prevents the admin menu being scrolled
// even if `is-fullscreen-mode` is then removed. Let's remove `sticky-menu` here as
// a consequence of the FullscreenMode setup.
if (document.body.classList.contains('sticky-menu')) {
isSticky = true;
document.body.classList.remove('sticky-menu');
}
return () => {
if (isSticky) {
document.body.classList.add('sticky-menu');
}
};
}, []);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (isActive) {
document.body.classList.add('is-fullscreen-mode');
} else {
document.body.classList.remove('is-fullscreen-mode');
}
return () => {
if (isActive) {
document.body.classList.remove('is-fullscreen-mode');
}
};
}, [isActive]);
return null;
};
/* harmony default export */ var fullscreen_mode = (FullscreenMode);
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/navigable-region/index.js
/**
* External dependencies
*/
function NavigableRegion(_ref) {
let {
children,
className,
ariaLabel,
as: Tag = 'div',
...props
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(Tag, _extends({
className: classnames_default()('interface-navigable-region', className),
"aria-label": ariaLabel,
role: "region",
tabIndex: "-1"
}, props), children);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/interface-skeleton/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useHTMLClass(className) {
(0,external_wp_element_namespaceObject.useEffect)(() => {
const element = document && document.querySelector(`html:not(.${className})`);
if (!element) {
return;
}
element.classList.toggle(className);
return () => {
element.classList.toggle(className);
};
}, [className]);
}
function InterfaceSkeleton(_ref, ref) {
let {
isDistractionFree,
footer,
header,
editorNotices,
sidebar,
secondarySidebar,
notices,
content,
actions,
labels,
className,
enableRegionNavigation = true,
// Todo: does this need to be a prop.
// Can we use a dependency to keyboard-shortcuts directly?
shortcuts
} = _ref;
const navigateRegionsProps = (0,external_wp_components_namespaceObject.__unstableUseNavigateRegions)(shortcuts);
useHTMLClass('interface-interface-skeleton__html-container');
const defaultLabels = {
/* translators: accessibility text for the top bar landmark region. */
header: (0,external_wp_i18n_namespaceObject.__)('Header'),
/* translators: accessibility text for the content landmark region. */
body: (0,external_wp_i18n_namespaceObject.__)('Content'),
/* translators: accessibility text for the secondary sidebar landmark region. */
secondarySidebar: (0,external_wp_i18n_namespaceObject.__)('Block Library'),
/* translators: accessibility text for the settings landmark region. */
sidebar: (0,external_wp_i18n_namespaceObject.__)('Settings'),
/* translators: accessibility text for the publish landmark region. */
actions: (0,external_wp_i18n_namespaceObject.__)('Publish'),
/* translators: accessibility text for the footer landmark region. */
footer: (0,external_wp_i18n_namespaceObject.__)('Footer')
};
const mergedLabels = { ...defaultLabels,
...labels
};
const headerVariants = {
hidden: isDistractionFree ? {
opacity: 0
} : {
opacity: 1
},
hover: {
opacity: 1,
transition: {
type: 'tween',
delay: 0.2,
delayChildren: 0.2
}
}
};
return (0,external_wp_element_namespaceObject.createElement)("div", _extends({}, enableRegionNavigation ? navigateRegionsProps : {}, {
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([ref, enableRegionNavigation ? navigateRegionsProps.ref : undefined]),
className: classnames_default()(className, 'interface-interface-skeleton', navigateRegionsProps.className, !!footer && 'has-footer')
}), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "interface-interface-skeleton__editor"
}, !!header && isDistractionFree && (0,external_wp_element_namespaceObject.createElement)(NavigableRegion, {
as: external_wp_components_namespaceObject.__unstableMotion.div,
className: "interface-interface-skeleton__header",
"aria-label": mergedLabels.header,
initial: isDistractionFree ? 'hidden' : 'hover',
whileHover: "hover",
variants: headerVariants,
transition: {
type: 'tween',
delay: 0.8
}
}, header), !!header && !isDistractionFree && (0,external_wp_element_namespaceObject.createElement)(NavigableRegion, {
className: "interface-interface-skeleton__header",
ariaLabel: mergedLabels.header
}, header), isDistractionFree && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "interface-interface-skeleton__header"
}, editorNotices), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "interface-interface-skeleton__body"
}, !!secondarySidebar && (0,external_wp_element_namespaceObject.createElement)(NavigableRegion, {
className: "interface-interface-skeleton__secondary-sidebar",
ariaLabel: mergedLabels.secondarySidebar
}, secondarySidebar), !!notices && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "interface-interface-skeleton__notices"
}, notices), (0,external_wp_element_namespaceObject.createElement)(NavigableRegion, {
className: "interface-interface-skeleton__content",
ariaLabel: mergedLabels.body
}, content), !!sidebar && (0,external_wp_element_namespaceObject.createElement)(NavigableRegion, {
className: "interface-interface-skeleton__sidebar",
ariaLabel: mergedLabels.sidebar
}, sidebar), !!actions && (0,external_wp_element_namespaceObject.createElement)(NavigableRegion, {
className: "interface-interface-skeleton__actions",
ariaLabel: mergedLabels.actions
}, actions))), !!footer && (0,external_wp_element_namespaceObject.createElement)(NavigableRegion, {
className: "interface-interface-skeleton__footer",
ariaLabel: mergedLabels.footer
}, footer));
}
/* harmony default export */ var interface_skeleton = ((0,external_wp_element_namespaceObject.forwardRef)(InterfaceSkeleton));
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/more-vertical.js
/**
* WordPress dependencies
*/
const moreVertical = (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: "M13 19h-2v-2h2v2zm0-6h-2v-2h2v2zm0-6h-2V5h2v2z"
}));
/* harmony default export */ var more_vertical = (moreVertical);
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/more-menu-dropdown/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
function MoreMenuDropdown(_ref) {
let {
as: DropdownComponent = external_wp_components_namespaceObject.DropdownMenu,
className,
/* translators: button label text should, if possible, be under 16 characters. */
label = (0,external_wp_i18n_namespaceObject.__)('Options'),
popoverProps,
toggleProps,
children
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(DropdownComponent, {
className: classnames_default()('interface-more-menu-dropdown', className),
icon: more_vertical,
label: label,
popoverProps: {
placement: 'bottom-end',
...popoverProps,
className: classnames_default()('interface-more-menu-dropdown__content', popoverProps === null || popoverProps === void 0 ? void 0 : popoverProps.className)
},
toggleProps: {
tooltipPosition: 'bottom',
...toggleProps
}
}, onClose => children(onClose));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/preferences-modal/index.js
/**
* WordPress dependencies
*/
function PreferencesModal(_ref) {
let {
closeModal,
children
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Modal, {
className: "interface-preferences-modal",
title: (0,external_wp_i18n_namespaceObject.__)('Preferences'),
onRequestClose: closeModal
}, children);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/icon/index.js
/**
* WordPress dependencies
*/
/** @typedef {{icon: JSX.Element, size?: number} & import('@wordpress/primitives').SVGProps} IconProps */
/**
* Return an SVG icon.
*
* @param {IconProps} props icon is the SVG component to render
* size is a number specifiying the icon size in pixels
* Other props will be passed to wrapped SVG component
*
* @return {JSX.Element} Icon component
*/
function Icon(_ref) {
let {
icon,
size = 24,
...props
} = _ref;
return (0,external_wp_element_namespaceObject.cloneElement)(icon, {
width: size,
height: size,
...props
});
}
/* harmony default export */ var icon = (Icon);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/chevron-left.js
/**
* WordPress dependencies
*/
const chevronLeft = (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: "M14.6 7l-1.2-1L8 12l5.4 6 1.2-1-4.6-5z"
}));
/* harmony default export */ var chevron_left = (chevronLeft);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/chevron-right.js
/**
* WordPress dependencies
*/
const chevronRight = (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: "M10.6 6L9.4 7l4.6 5-4.6 5 1.2 1 5.4-6z"
}));
/* harmony default export */ var chevron_right = (chevronRight);
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/preferences-modal-tabs/index.js
/**
* WordPress dependencies
*/
const PREFERENCES_MENU = 'preferences-menu';
function PreferencesModalTabs(_ref) {
let {
sections
} = _ref;
const isLargeViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('medium'); // This is also used to sync the two different rendered components
// between small and large viewports.
const [activeMenu, setActiveMenu] = (0,external_wp_element_namespaceObject.useState)(PREFERENCES_MENU);
/**
* Create helper objects from `sections` for easier data handling.
* `tabs` is used for creating the `TabPanel` and `sectionsContentMap`
* is used for easier access to active tab's content.
*/
const {
tabs,
sectionsContentMap
} = (0,external_wp_element_namespaceObject.useMemo)(() => {
let mappedTabs = {
tabs: [],
sectionsContentMap: {}
};
if (sections.length) {
mappedTabs = sections.reduce((accumulator, _ref2) => {
let {
name,
tabLabel: title,
content
} = _ref2;
accumulator.tabs.push({
name,
title
});
accumulator.sectionsContentMap[name] = content;
return accumulator;
}, {
tabs: [],
sectionsContentMap: {}
});
}
return mappedTabs;
}, [sections]);
const getCurrentTab = (0,external_wp_element_namespaceObject.useCallback)(tab => sectionsContentMap[tab.name] || null, [sectionsContentMap]);
let modalContent; // We render different components based on the viewport size.
if (isLargeViewport) {
modalContent = (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.TabPanel, {
className: "interface-preferences__tabs",
tabs: tabs,
initialTabName: activeMenu !== PREFERENCES_MENU ? activeMenu : undefined,
onSelect: setActiveMenu,
orientation: "vertical"
}, getCurrentTab);
} else {
modalContent = (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalNavigatorProvider, {
initialPath: "/",
className: "interface-preferences__provider"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalNavigatorScreen, {
path: "/"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Card, {
isBorderless: true,
size: "small"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.CardBody, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalItemGroup, null, tabs.map(tab => {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalNavigatorButton, {
key: tab.name,
path: tab.name,
as: external_wp_components_namespaceObject.__experimentalItem,
isAction: true
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalHStack, {
justify: "space-between"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexItem, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalTruncate, null, tab.title)), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexItem, null, (0,external_wp_element_namespaceObject.createElement)(icon, {
icon: (0,external_wp_i18n_namespaceObject.isRTL)() ? chevron_left : chevron_right
}))));
}))))), sections.length && sections.map(section => {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalNavigatorScreen, {
key: `${section.name}-menu`,
path: section.name
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Card, {
isBorderless: true,
size: "large"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.CardHeader, {
isBorderless: false,
justify: "left",
size: "small",
gap: "6"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalNavigatorBackButton, {
icon: (0,external_wp_i18n_namespaceObject.isRTL)() ? chevron_right : chevron_left,
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Navigate to the previous view')
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalText, {
size: "16"
}, section.tabLabel)), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.CardBody, null, section.content)));
}));
}
return modalContent;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/preferences-modal-section/index.js
const Section = _ref => {
let {
description,
title,
children
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("fieldset", {
className: "interface-preferences-modal__section"
}, (0,external_wp_element_namespaceObject.createElement)("legend", {
className: "interface-preferences-modal__section-legend"
}, (0,external_wp_element_namespaceObject.createElement)("h2", {
className: "interface-preferences-modal__section-title"
}, title), description && (0,external_wp_element_namespaceObject.createElement)("p", {
className: "interface-preferences-modal__section-description"
}, description)), children);
};
/* harmony default export */ var preferences_modal_section = (Section);
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/preferences-modal-base-option/index.js
/**
* WordPress dependencies
*/
function BaseOption(_ref) {
let {
help,
label,
isChecked,
onChange,
children
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "interface-preferences-modal__option"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToggleControl, {
__nextHasNoMarginBottom: true,
help: help,
label: label,
checked: isChecked,
onChange: onChange
}), children);
}
/* harmony default export */ var preferences_modal_base_option = (BaseOption);
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/components/index.js
;// CONCATENATED MODULE: ./node_modules/@wordpress/interface/build-module/index.js
;// CONCATENATED MODULE: external ["wp","a11y"]
var external_wp_a11y_namespaceObject = window["wp"]["a11y"];
;// CONCATENATED MODULE: external ["wp","coreData"]
var external_wp_coreData_namespaceObject = window["wp"]["coreData"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/utils/meta-boxes.js
/**
* Function returning the current Meta Boxes DOM Node in the editor
* whether the meta box area is opened or not.
* If the MetaBox Area is visible returns it, and returns the original container instead.
*
* @param {string} location Meta Box location.
*
* @return {string} HTML content.
*/
const getMetaBoxContainer = location => {
const area = document.querySelector(`.edit-post-meta-boxes-area.is-${location} .metabox-location-${location}`);
if (area) {
return area;
}
return document.querySelector('#metaboxes .metabox-location-' + location);
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/store/actions.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Returns an action object used in signalling that the user opened an editor sidebar.
*
* @param {?string} name Sidebar name to be opened.
*/
const openGeneralSidebar = name => _ref => {
let {
registry
} = _ref;
return registry.dispatch(store).enableComplementaryArea(store_store.name, name);
};
/**
* Returns an action object signalling that the user closed the sidebar.
*/
const closeGeneralSidebar = () => _ref2 => {
let {
registry
} = _ref2;
return registry.dispatch(store).disableComplementaryArea(store_store.name);
};
/**
* Returns an action object used in signalling that the user opened a modal.
*
* @param {string} name A string that uniquely identifies the modal.
*
* @return {Object} Action object.
*/
function openModal(name) {
return {
type: 'OPEN_MODAL',
name
};
}
/**
* Returns an action object signalling that the user closed a modal.
*
* @return {Object} Action object.
*/
function closeModal() {
return {
type: 'CLOSE_MODAL'
};
}
/**
* Returns an action object used in signalling that the user opened the publish
* sidebar.
*
* @return {Object} Action object
*/
function openPublishSidebar() {
return {
type: 'OPEN_PUBLISH_SIDEBAR'
};
}
/**
* Returns an action object used in signalling that the user closed the
* publish sidebar.
*
* @return {Object} Action object.
*/
function closePublishSidebar() {
return {
type: 'CLOSE_PUBLISH_SIDEBAR'
};
}
/**
* Returns an action object used in signalling that the user toggles the publish sidebar.
*
* @return {Object} Action object
*/
function togglePublishSidebar() {
return {
type: 'TOGGLE_PUBLISH_SIDEBAR'
};
}
/**
* Returns an action object used to enable or disable a panel in the editor.
*
* @param {string} panelName A string that identifies the panel to enable or disable.
*
* @return {Object} Action object.
*/
const toggleEditorPanelEnabled = panelName => _ref3 => {
var _registry$select$get;
let {
registry
} = _ref3;
const inactivePanels = (_registry$select$get = registry.select(external_wp_preferences_namespaceObject.store).get('core/edit-post', 'inactivePanels')) !== null && _registry$select$get !== void 0 ? _registry$select$get : [];
const isPanelInactive = !!(inactivePanels !== null && inactivePanels !== void 0 && inactivePanels.includes(panelName)); // If the panel is inactive, remove it to enable it, else add it to
// make it inactive.
let updatedInactivePanels;
if (isPanelInactive) {
updatedInactivePanels = inactivePanels.filter(invactivePanelName => invactivePanelName !== panelName);
} else {
updatedInactivePanels = [...inactivePanels, panelName];
}
registry.dispatch(external_wp_preferences_namespaceObject.store).set('core/edit-post', 'inactivePanels', updatedInactivePanels);
};
/**
* Opens a closed panel and closes an open panel.
*
* @param {string} panelName A string that identifies the panel to open or close.
*/
const toggleEditorPanelOpened = panelName => _ref4 => {
var _registry$select$get2;
let {
registry
} = _ref4;
const openPanels = (_registry$select$get2 = registry.select(external_wp_preferences_namespaceObject.store).get('core/edit-post', 'openPanels')) !== null && _registry$select$get2 !== void 0 ? _registry$select$get2 : [];
const isPanelOpen = !!(openPanels !== null && openPanels !== void 0 && openPanels.includes(panelName)); // If the panel is open, remove it to close it, else add it to
// make it open.
let updatedOpenPanels;
if (isPanelOpen) {
updatedOpenPanels = openPanels.filter(openPanelName => openPanelName !== panelName);
} else {
updatedOpenPanels = [...openPanels, panelName];
}
registry.dispatch(external_wp_preferences_namespaceObject.store).set('core/edit-post', 'openPanels', updatedOpenPanels);
};
/**
* Returns an action object used to remove a panel from the editor.
*
* @param {string} panelName A string that identifies the panel to remove.
*
* @return {Object} Action object.
*/
function removeEditorPanel(panelName) {
return {
type: 'REMOVE_PANEL',
panelName
};
}
/**
* Triggers an action used to toggle a feature flag.
*
* @param {string} feature Feature name.
*/
const actions_toggleFeature = feature => _ref5 => {
let {
registry
} = _ref5;
return registry.dispatch(external_wp_preferences_namespaceObject.store).toggle('core/edit-post', feature);
};
/**
* Triggers an action used to switch editor mode.
*
* @param {string} mode The editor mode.
*/
const switchEditorMode = mode => _ref6 => {
let {
registry
} = _ref6;
registry.dispatch(external_wp_preferences_namespaceObject.store).set('core/edit-post', 'editorMode', mode); // Unselect blocks when we switch to the code editor.
if (mode !== 'visual') {
registry.dispatch(external_wp_blockEditor_namespaceObject.store).clearSelectedBlock();
}
const message = mode === 'visual' ? (0,external_wp_i18n_namespaceObject.__)('Visual editor selected') : (0,external_wp_i18n_namespaceObject.__)('Code editor selected');
(0,external_wp_a11y_namespaceObject.speak)(message, 'assertive');
};
/**
* Triggers an action object used to toggle a plugin name flag.
*
* @param {string} pluginName Plugin name.
*/
const togglePinnedPluginItem = pluginName => _ref7 => {
let {
registry
} = _ref7;
const isPinned = registry.select(store).isItemPinned('core/edit-post', pluginName);
registry.dispatch(store)[isPinned ? 'unpinItem' : 'pinItem']('core/edit-post', pluginName);
};
/**
* Returns an action object used in signaling that a style should be auto-applied when a block is created.
*
* @param {string} blockName Name of the block.
* @param {?string} blockStyle Name of the style that should be auto applied. If undefined, the "auto apply" setting of the block is removed.
*/
const updatePreferredStyleVariations = (blockName, blockStyle) => _ref8 => {
var _registry$select$get3;
let {
registry
} = _ref8;
if (!blockName) {
return;
}
const existingVariations = (_registry$select$get3 = registry.select(external_wp_preferences_namespaceObject.store).get('core/edit-post', 'preferredStyleVariations')) !== null && _registry$select$get3 !== void 0 ? _registry$select$get3 : {}; // When the blockStyle is omitted, remove the block's preferred variation.
if (!blockStyle) {
const updatedVariations = { ...existingVariations
};
delete updatedVariations[blockName];
registry.dispatch(external_wp_preferences_namespaceObject.store).set('core/edit-post', 'preferredStyleVariations', updatedVariations);
} else {
// Else add the variation.
registry.dispatch(external_wp_preferences_namespaceObject.store).set('core/edit-post', 'preferredStyleVariations', { ...existingVariations,
[blockName]: blockStyle
});
}
};
/**
* Update the provided block types to be visible.
*
* @param {string[]} blockNames Names of block types to show.
*/
const showBlockTypes = blockNames => _ref9 => {
var _registry$select$get4;
let {
registry
} = _ref9;
const existingBlockNames = (_registry$select$get4 = registry.select(external_wp_preferences_namespaceObject.store).get('core/edit-post', 'hiddenBlockTypes')) !== null && _registry$select$get4 !== void 0 ? _registry$select$get4 : [];
const newBlockNames = existingBlockNames.filter(type => !(Array.isArray(blockNames) ? blockNames : [blockNames]).includes(type));
registry.dispatch(external_wp_preferences_namespaceObject.store).set('core/edit-post', 'hiddenBlockTypes', newBlockNames);
};
/**
* Update the provided block types to be hidden.
*
* @param {string[]} blockNames Names of block types to hide.
*/
const hideBlockTypes = blockNames => _ref10 => {
var _registry$select$get5;
let {
registry
} = _ref10;
const existingBlockNames = (_registry$select$get5 = registry.select(external_wp_preferences_namespaceObject.store).get('core/edit-post', 'hiddenBlockTypes')) !== null && _registry$select$get5 !== void 0 ? _registry$select$get5 : [];
const mergedBlockNames = new Set([...existingBlockNames, ...(Array.isArray(blockNames) ? blockNames : [blockNames])]);
registry.dispatch(external_wp_preferences_namespaceObject.store).set('core/edit-post', 'hiddenBlockTypes', [...mergedBlockNames]);
};
/**
* Stores info about which Meta boxes are available in which location.
*
* @param {Object} metaBoxesPerLocation Meta boxes per location.
*/
function setAvailableMetaBoxesPerLocation(metaBoxesPerLocation) {
return {
type: 'SET_META_BOXES_PER_LOCATIONS',
metaBoxesPerLocation
};
}
/**
* Update a metabox.
*/
const requestMetaBoxUpdates = () => async _ref11 => {
let {
registry,
select,
dispatch
} = _ref11;
dispatch({
type: 'REQUEST_META_BOX_UPDATES'
}); // Saves the wp_editor fields.
if (window.tinyMCE) {
window.tinyMCE.triggerSave();
} // Additional data needed for backward compatibility.
// If we do not provide this data, the post will be overridden with the default values.
const post = registry.select(external_wp_editor_namespaceObject.store).getCurrentPost();
const additionalData = [post.comment_status ? ['comment_status', post.comment_status] : false, post.ping_status ? ['ping_status', post.ping_status] : false, post.sticky ? ['sticky', post.sticky] : false, post.author ? ['post_author', post.author] : false].filter(Boolean); // We gather all the metaboxes locations data and the base form data.
const baseFormData = new window.FormData(document.querySelector('.metabox-base-form'));
const activeMetaBoxLocations = select.getActiveMetaBoxLocations();
const formDataToMerge = [baseFormData, ...activeMetaBoxLocations.map(location => new window.FormData(getMetaBoxContainer(location)))]; // Merge all form data objects into a single one.
const formData = formDataToMerge.reduce((memo, currentFormData) => {
for (const [key, value] of currentFormData) {
memo.append(key, value);
}
return memo;
}, new window.FormData());
additionalData.forEach(_ref12 => {
let [key, value] = _ref12;
return formData.append(key, value);
});
try {
// Save the metaboxes.
await external_wp_apiFetch_default()({
url: window._wpMetaBoxUrl,
method: 'POST',
body: formData,
parse: false
});
dispatch.metaBoxUpdatesSuccess();
} catch {
dispatch.metaBoxUpdatesFailure();
}
};
/**
* Returns an action object used to signal a successful meta box update.
*
* @return {Object} Action object.
*/
function metaBoxUpdatesSuccess() {
return {
type: 'META_BOX_UPDATES_SUCCESS'
};
}
/**
* Returns an action object used to signal a failed meta box update.
*
* @return {Object} Action object.
*/
function metaBoxUpdatesFailure() {
return {
type: 'META_BOX_UPDATES_FAILURE'
};
}
/**
* Returns an action object used to toggle the width of the editing canvas.
*
* @param {string} deviceType
*
* @return {Object} Action object.
*/
function __experimentalSetPreviewDeviceType(deviceType) {
return {
type: 'SET_PREVIEW_DEVICE_TYPE',
deviceType
};
}
/**
* Returns an action object used to open/close the inserter.
*
* @param {boolean|Object} value Whether the inserter should be
* opened (true) or closed (false).
* To specify an insertion point,
* use an object.
* @param {string} value.rootClientId The root client ID to insert at.
* @param {number} value.insertionIndex The index to insert at.
*
* @return {Object} Action object.
*/
function setIsInserterOpened(value) {
return {
type: 'SET_IS_INSERTER_OPENED',
value
};
}
/**
* Returns an action object used to open/close the list view.
*
* @param {boolean} isOpen A boolean representing whether the list view should be opened or closed.
* @return {Object} Action object.
*/
function setIsListViewOpened(isOpen) {
return {
type: 'SET_IS_LIST_VIEW_OPENED',
isOpen
};
}
/**
* Returns an action object used to switch to template editing.
*
* @param {boolean} value Is editing template.
* @return {Object} Action object.
*/
function setIsEditingTemplate(value) {
return {
type: 'SET_IS_EDITING_TEMPLATE',
value
};
}
/**
* Switches to the template mode.
*
* @param {boolean} newTemplate Is new template.
*/
const __unstableSwitchToTemplateMode = function () {
let newTemplate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
return _ref13 => {
let {
registry,
select,
dispatch
} = _ref13;
dispatch(setIsEditingTemplate(true));
const isWelcomeGuideActive = select.isFeatureActive('welcomeGuideTemplate');
if (!isWelcomeGuideActive) {
const message = newTemplate ? (0,external_wp_i18n_namespaceObject.__)("Custom template created. You're in template mode now.") : (0,external_wp_i18n_namespaceObject.__)('Editing template. Changes made here affect all posts and pages that use the template.');
registry.dispatch(external_wp_notices_namespaceObject.store).createSuccessNotice(message, {
type: 'snackbar'
});
}
};
};
/**
* Create a block based template.
*
* @param {Object?} template Template to create and assign.
*/
const __unstableCreateTemplate = template => async _ref14 => {
let {
registry
} = _ref14;
const savedTemplate = await registry.dispatch(external_wp_coreData_namespaceObject.store).saveEntityRecord('postType', 'wp_template', template);
const post = registry.select(external_wp_editor_namespaceObject.store).getCurrentPost();
registry.dispatch(external_wp_coreData_namespaceObject.store).editEntityRecord('postType', post.type, post.id, {
template: savedTemplate.slug
});
};
let actions_metaBoxesInitialized = false;
/**
* Initializes WordPress `postboxes` script and the logic for saving meta boxes.
*/
const initializeMetaBoxes = () => _ref15 => {
let {
registry,
select,
dispatch
} = _ref15;
const isEditorReady = registry.select(external_wp_editor_namespaceObject.store).__unstableIsEditorReady();
if (!isEditorReady) {
return;
} // Only initialize once.
if (actions_metaBoxesInitialized) {
return;
}
const postType = registry.select(external_wp_editor_namespaceObject.store).getCurrentPostType();
if (window.postboxes.page !== postType) {
window.postboxes.add_postbox_toggles(postType);
}
actions_metaBoxesInitialized = true;
let wasSavingPost = registry.select(external_wp_editor_namespaceObject.store).isSavingPost();
let wasAutosavingPost = registry.select(external_wp_editor_namespaceObject.store).isAutosavingPost(); // Save metaboxes when performing a full save on the post.
registry.subscribe(async () => {
const isSavingPost = registry.select(external_wp_editor_namespaceObject.store).isSavingPost();
const isAutosavingPost = registry.select(external_wp_editor_namespaceObject.store).isAutosavingPost(); // Save metaboxes on save completion, except for autosaves.
const shouldTriggerMetaboxesSave = wasSavingPost && !wasAutosavingPost && !isSavingPost && select.hasMetaBoxes(); // Save current state for next inspection.
wasSavingPost = isSavingPost;
wasAutosavingPost = isAutosavingPost;
if (shouldTriggerMetaboxesSave) {
await dispatch.requestMetaBoxUpdates();
}
});
dispatch({
type: 'META_BOXES_INITIALIZED'
});
};
;// CONCATENATED MODULE: ./node_modules/rememo/rememo.js
/** @typedef {(...args: any[]) => *[]} GetDependants */
/** @typedef {() => void} Clear */
/**
* @typedef {{
* getDependants: GetDependants,
* clear: Clear
* }} EnhancedSelector
*/
/**
* Internal cache entry.
*
* @typedef CacheNode
*
* @property {?CacheNode|undefined} [prev] Previous node.
* @property {?CacheNode|undefined} [next] Next node.
* @property {*[]} args Function arguments for cache entry.
* @property {*} val Function result.
*/
/**
* @typedef Cache
*
* @property {Clear} clear Function to clear cache.
* @property {boolean} [isUniqueByDependants] Whether dependants are valid in
* considering cache uniqueness. A cache is unique if dependents are all arrays
* or objects.
* @property {CacheNode?} [head] Cache head.
* @property {*[]} [lastDependants] Dependants from previous invocation.
*/
/**
* Arbitrary value used as key for referencing cache object in WeakMap tree.
*
* @type {{}}
*/
var LEAF_KEY = {};
/**
* Returns the first argument as the sole entry in an array.
*
* @template T
*
* @param {T} value Value to return.
*
* @return {[T]} Value returned as entry in array.
*/
function arrayOf(value) {
return [value];
}
/**
* Returns true if the value passed is object-like, or false otherwise. A value
* is object-like if it can support property assignment, e.g. object or array.
*
* @param {*} value Value to test.
*
* @return {boolean} Whether value is object-like.
*/
function isObjectLike(value) {
return !!value && 'object' === typeof value;
}
/**
* Creates and returns a new cache object.
*
* @return {Cache} Cache object.
*/
function createCache() {
/** @type {Cache} */
var cache = {
clear: function () {
cache.head = null;
},
};
return cache;
}
/**
* Returns true if entries within the two arrays are strictly equal by
* reference from a starting index.
*
* @param {*[]} a First array.
* @param {*[]} b Second array.
* @param {number} fromIndex Index from which to start comparison.
*
* @return {boolean} Whether arrays are shallowly equal.
*/
function isShallowEqual(a, b, fromIndex) {
var i;
if (a.length !== b.length) {
return false;
}
for (i = fromIndex; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
/**
* Returns a memoized selector function. The getDependants function argument is
* called before the memoized selector and is expected to return an immutable
* reference or array of references on which the selector depends for computing
* its own return value. The memoize cache is preserved only as long as those
* dependant references remain the same. If getDependants returns a different
* reference(s), the cache is cleared and the selector value regenerated.
*
* @template {(...args: *[]) => *} S
*
* @param {S} selector Selector function.
* @param {GetDependants=} getDependants Dependant getter returning an array of
* references used in cache bust consideration.
*/
/* harmony default export */ function rememo(selector, getDependants) {
/** @type {WeakMap<*,*>} */
var rootCache;
/** @type {GetDependants} */
var normalizedGetDependants = getDependants ? getDependants : arrayOf;
/**
* Returns the cache for a given dependants array. When possible, a WeakMap
* will be used to create a unique cache for each set of dependants. This
* is feasible due to the nature of WeakMap in allowing garbage collection
* to occur on entries where the key object is no longer referenced. Since
* WeakMap requires the key to be an object, this is only possible when the
* dependant is object-like. The root cache is created as a hierarchy where
* each top-level key is the first entry in a dependants set, the value a
* WeakMap where each key is the next dependant, and so on. This continues
* so long as the dependants are object-like. If no dependants are object-
* like, then the cache is shared across all invocations.
*
* @see isObjectLike
*
* @param {*[]} dependants Selector dependants.
*
* @return {Cache} Cache object.
*/
function getCache(dependants) {
var caches = rootCache,
isUniqueByDependants = true,
i,
dependant,
map,
cache;
for (i = 0; i < dependants.length; i++) {
dependant = dependants[i];
// Can only compose WeakMap from object-like key.
if (!isObjectLike(dependant)) {
isUniqueByDependants = false;
break;
}
// Does current segment of cache already have a WeakMap?
if (caches.has(dependant)) {
// Traverse into nested WeakMap.
caches = caches.get(dependant);
} else {
// Create, set, and traverse into a new one.
map = new WeakMap();
caches.set(dependant, map);
caches = map;
}
}
// We use an arbitrary (but consistent) object as key for the last item
// in the WeakMap to serve as our running cache.
if (!caches.has(LEAF_KEY)) {
cache = createCache();
cache.isUniqueByDependants = isUniqueByDependants;
caches.set(LEAF_KEY, cache);
}
return caches.get(LEAF_KEY);
}
/**
* Resets root memoization cache.
*/
function clear() {
rootCache = new WeakMap();
}
/* eslint-disable jsdoc/check-param-names */
/**
* The augmented selector call, considering first whether dependants have
* changed before passing it to underlying memoize function.
*
* @param {*} source Source object for derivation.
* @param {...*} extraArgs Additional arguments to pass to selector.
*
* @return {*} Selector result.
*/
/* eslint-enable jsdoc/check-param-names */
function callSelector(/* source, ...extraArgs */) {
var len = arguments.length,
cache,
node,
i,
args,
dependants;
// Create copy of arguments (avoid leaking deoptimization).
args = new Array(len);
for (i = 0; i < len; i++) {
args[i] = arguments[i];
}
dependants = normalizedGetDependants.apply(null, args);
cache = getCache(dependants);
// If not guaranteed uniqueness by dependants (primitive type), shallow
// compare against last dependants and, if references have changed,
// destroy cache to recalculate result.
if (!cache.isUniqueByDependants) {
if (
cache.lastDependants &&
!isShallowEqual(dependants, cache.lastDependants, 0)
) {
cache.clear();
}
cache.lastDependants = dependants;
}
node = cache.head;
while (node) {
// Check whether node arguments match arguments
if (!isShallowEqual(node.args, args, 1)) {
node = node.next;
continue;
}
// At this point we can assume we've found a match
// Surface matched node to head if not already
if (node !== cache.head) {
// Adjust siblings to point to each other.
/** @type {CacheNode} */ (node.prev).next = node.next;
if (node.next) {
node.next.prev = node.prev;
}
node.next = cache.head;
node.prev = null;
/** @type {CacheNode} */ (cache.head).prev = node;
cache.head = node;
}
// Return immediately
return node.val;
}
// No cached value found. Continue to insertion phase:
node = /** @type {CacheNode} */ ({
// Generate the result from original function
val: selector.apply(null, args),
});
// Avoid including the source object in the cache.
args[0] = null;
node.args = args;
// Don't need to check whether node is already head, since it would
// have been returned above already if it was
// Shift existing head down list
if (cache.head) {
cache.head.prev = node;
node.next = cache.head;
}
cache.head = node;
return node.val;
}
callSelector.getDependants = normalizedGetDependants;
callSelector.clear = clear;
clear();
return /** @type {S & EnhancedSelector} */ (callSelector);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/store/selectors.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
const EMPTY_ARRAY = [];
const EMPTY_OBJECT = {};
/**
* Returns the current editing mode.
*
* @param {Object} state Global application state.
*
* @return {string} Editing mode.
*/
const getEditorMode = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => () => {
var _select$get;
return (_select$get = select(external_wp_preferences_namespaceObject.store).get('core/edit-post', 'editorMode')) !== null && _select$get !== void 0 ? _select$get : 'visual';
});
/**
* Returns true if the editor sidebar is opened.
*
* @param {Object} state Global application state
*
* @return {boolean} Whether the editor sidebar is opened.
*/
const isEditorSidebarOpened = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => () => {
const activeGeneralSidebar = select(store).getActiveComplementaryArea('core/edit-post');
return ['edit-post/document', 'edit-post/block'].includes(activeGeneralSidebar);
});
/**
* Returns true if the plugin sidebar is opened.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the plugin sidebar is opened.
*/
const isPluginSidebarOpened = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => () => {
const activeGeneralSidebar = select(store).getActiveComplementaryArea('core/edit-post');
return !!activeGeneralSidebar && !['edit-post/document', 'edit-post/block'].includes(activeGeneralSidebar);
});
/**
* Returns the current active general sidebar name, or null if there is no
* general sidebar active. The active general sidebar is a unique name to
* identify either an editor or plugin sidebar.
*
* Examples:
*
* - `edit-post/document`
* - `my-plugin/insert-image-sidebar`
*
* @param {Object} state Global application state.
*
* @return {?string} Active general sidebar name.
*/
const getActiveGeneralSidebarName = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => () => {
return select(store).getActiveComplementaryArea('core/edit-post');
});
/**
* Converts panels from the new preferences store format to the old format
* that the post editor previously used.
*
* The resultant converted data should look like this:
* {
* panelName: {
* enabled: false,
* opened: true,
* },
* anotherPanelName: {
* opened: true
* },
* }
*
* @param {string[] | undefined} inactivePanels An array of inactive panel names.
* @param {string[] | undefined} openPanels An array of open panel names.
*
* @return {Object} The converted panel data.
*/
function convertPanelsToOldFormat(inactivePanels, openPanels) {
var _ref;
// First reduce the inactive panels.
const panelsWithEnabledState = inactivePanels === null || inactivePanels === void 0 ? void 0 : inactivePanels.reduce((accumulatedPanels, panelName) => ({ ...accumulatedPanels,
[panelName]: {
enabled: false
}
}), {}); // Then reduce the open panels, passing in the result of the previous
// reduction as the initial value so that both open and inactive
// panel state is combined.
const panels = openPanels === null || openPanels === void 0 ? void 0 : openPanels.reduce((accumulatedPanels, panelName) => {
const currentPanelState = accumulatedPanels === null || accumulatedPanels === void 0 ? void 0 : accumulatedPanels[panelName];
return { ...accumulatedPanels,
[panelName]: { ...currentPanelState,
opened: true
}
};
}, panelsWithEnabledState !== null && panelsWithEnabledState !== void 0 ? panelsWithEnabledState : {}); // The panels variable will only be set if openPanels wasn't `undefined`.
// If it isn't set just return `panelsWithEnabledState`, and if that isn't
// set return an empty object.
return (_ref = panels !== null && panels !== void 0 ? panels : panelsWithEnabledState) !== null && _ref !== void 0 ? _ref : EMPTY_OBJECT;
}
/**
* Returns the preferences (these preferences are persisted locally).
*
* @param {Object} state Global application state.
*
* @return {Object} Preferences Object.
*/
const getPreferences = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => () => {
external_wp_deprecated_default()(`select( 'core/edit-post' ).getPreferences`, {
since: '6.0',
alternative: `select( 'core/preferences' ).get`
}); // These preferences now exist in the preferences store.
// Fetch them so that they can be merged into the post
// editor preferences.
const preferences = ['hiddenBlockTypes', 'editorMode', 'preferredStyleVariations'].reduce((accumulatedPrefs, preferenceKey) => {
const value = select(external_wp_preferences_namespaceObject.store).get('core/edit-post', preferenceKey);
return { ...accumulatedPrefs,
[preferenceKey]: value
};
}, {}); // Panels were a preference, but the data structure changed when the state
// was migrated to the preferences store. They need to be converted from
// the new preferences store format to old format to ensure no breaking
// changes for plugins.
const inactivePanels = select(external_wp_preferences_namespaceObject.store).get('core/edit-post', 'inactivePanels');
const openPanels = select(external_wp_preferences_namespaceObject.store).get('core/edit-post', 'openPanels');
const panels = convertPanelsToOldFormat(inactivePanels, openPanels);
return { ...preferences,
panels
};
});
/**
*
* @param {Object} state Global application state.
* @param {string} preferenceKey Preference Key.
* @param {*} defaultValue Default Value.
*
* @return {*} Preference Value.
*/
function getPreference(state, preferenceKey, defaultValue) {
external_wp_deprecated_default()(`select( 'core/edit-post' ).getPreference`, {
since: '6.0',
alternative: `select( 'core/preferences' ).get`
}); // Avoid using the `getPreferences` registry selector where possible.
const preferences = getPreferences(state);
const value = preferences[preferenceKey];
return value === undefined ? defaultValue : value;
}
/**
* Returns an array of blocks that are hidden.
*
* @return {Array} A list of the hidden block types
*/
const getHiddenBlockTypes = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => () => {
var _select$get2;
return (_select$get2 = select(external_wp_preferences_namespaceObject.store).get('core/edit-post', 'hiddenBlockTypes')) !== null && _select$get2 !== void 0 ? _select$get2 : EMPTY_ARRAY;
});
/**
* Returns true if the publish sidebar is opened.
*
* @param {Object} state Global application state
*
* @return {boolean} Whether the publish sidebar is open.
*/
function isPublishSidebarOpened(state) {
return state.publishSidebarActive;
}
/**
* Returns true if the given panel was programmatically removed, or false otherwise.
* All panels are not removed by default.
*
* @param {Object} state Global application state.
* @param {string} panelName A string that identifies the panel.
*
* @return {boolean} Whether or not the panel is removed.
*/
function isEditorPanelRemoved(state, panelName) {
return state.removedPanels.includes(panelName);
}
/**
* Returns true if the given panel is enabled, or false otherwise. Panels are
* enabled by default.
*
* @param {Object} state Global application state.
* @param {string} panelName A string that identifies the panel.
*
* @return {boolean} Whether or not the panel is enabled.
*/
const isEditorPanelEnabled = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (state, panelName) => {
const inactivePanels = select(external_wp_preferences_namespaceObject.store).get('core/edit-post', 'inactivePanels');
return !isEditorPanelRemoved(state, panelName) && !(inactivePanels !== null && inactivePanels !== void 0 && inactivePanels.includes(panelName));
});
/**
* Returns true if the given panel is open, or false otherwise. Panels are
* closed by default.
*
* @param {Object} state Global application state.
* @param {string} panelName A string that identifies the panel.
*
* @return {boolean} Whether or not the panel is open.
*/
const isEditorPanelOpened = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (state, panelName) => {
const openPanels = select(external_wp_preferences_namespaceObject.store).get('core/edit-post', 'openPanels');
return !!(openPanels !== null && openPanels !== void 0 && openPanels.includes(panelName));
});
/**
* Returns true if a modal is active, or false otherwise.
*
* @param {Object} state Global application state.
* @param {string} modalName A string that uniquely identifies the modal.
*
* @return {boolean} Whether the modal is active.
*/
function isModalActive(state, modalName) {
return state.activeModal === modalName;
}
/**
* Returns whether the given feature is enabled or not.
*
* @param {Object} state Global application state.
* @param {string} feature Feature slug.
*
* @return {boolean} Is active.
*/
const selectors_isFeatureActive = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (state, feature) => {
return !!select(external_wp_preferences_namespaceObject.store).get('core/edit-post', feature);
});
/**
* Returns true if the plugin item is pinned to the header.
* When the value is not set it defaults to true.
*
* @param {Object} state Global application state.
* @param {string} pluginName Plugin item name.
*
* @return {boolean} Whether the plugin item is pinned.
*/
const isPluginItemPinned = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (state, pluginName) => {
return select(store).isItemPinned('core/edit-post', pluginName);
});
/**
* Returns an array of active meta box locations.
*
* @param {Object} state Post editor state.
*
* @return {string[]} Active meta box locations.
*/
const getActiveMetaBoxLocations = rememo(state => {
return Object.keys(state.metaBoxes.locations).filter(location => isMetaBoxLocationActive(state, location));
}, state => [state.metaBoxes.locations]);
/**
* Returns true if a metabox location is active and visible
*
* @param {Object} state Post editor state.
* @param {string} location Meta box location to test.
*
* @return {boolean} Whether the meta box location is active and visible.
*/
function isMetaBoxLocationVisible(state, location) {
var _getMetaBoxesPerLocat;
return isMetaBoxLocationActive(state, location) && ((_getMetaBoxesPerLocat = getMetaBoxesPerLocation(state, location)) === null || _getMetaBoxesPerLocat === void 0 ? void 0 : _getMetaBoxesPerLocat.some(_ref2 => {
let {
id
} = _ref2;
return isEditorPanelEnabled(state, `meta-box-${id}`);
}));
}
/**
* Returns true if there is an active meta box in the given location, or false
* otherwise.
*
* @param {Object} state Post editor state.
* @param {string} location Meta box location to test.
*
* @return {boolean} Whether the meta box location is active.
*/
function isMetaBoxLocationActive(state, location) {
const metaBoxes = getMetaBoxesPerLocation(state, location);
return !!metaBoxes && metaBoxes.length !== 0;
}
/**
* Returns the list of all the available meta boxes for a given location.
*
* @param {Object} state Global application state.
* @param {string} location Meta box location to test.
*
* @return {?Array} List of meta boxes.
*/
function getMetaBoxesPerLocation(state, location) {
return state.metaBoxes.locations[location];
}
/**
* Returns the list of all the available meta boxes.
*
* @param {Object} state Global application state.
*
* @return {Array} List of meta boxes.
*/
const getAllMetaBoxes = rememo(state => {
return Object.values(state.metaBoxes.locations).flat();
}, state => [state.metaBoxes.locations]);
/**
* Returns true if the post is using Meta Boxes
*
* @param {Object} state Global application state
*
* @return {boolean} Whether there are metaboxes or not.
*/
function hasMetaBoxes(state) {
return getActiveMetaBoxLocations(state).length > 0;
}
/**
* Returns true if the Meta Boxes are being saved.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the metaboxes are being saved.
*/
function selectors_isSavingMetaBoxes(state) {
return state.metaBoxes.isSaving;
}
/**
* Returns the current editing canvas device type.
*
* @param {Object} state Global application state.
*
* @return {string} Device type.
*/
function __experimentalGetPreviewDeviceType(state) {
return state.deviceType;
}
/**
* Returns true if the inserter is opened.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the inserter is opened.
*/
function isInserterOpened(state) {
return !!state.blockInserterPanel;
}
/**
* Get the insertion point for the inserter.
*
* @param {Object} state Global application state.
*
* @return {Object} The root client ID, index to insert at and starting filter value.
*/
function __experimentalGetInsertionPoint(state) {
const {
rootClientId,
insertionIndex,
filterValue
} = state.blockInserterPanel;
return {
rootClientId,
insertionIndex,
filterValue
};
}
/**
* Returns true if the list view is opened.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the list view is opened.
*/
function isListViewOpened(state) {
return state.listViewPanel;
}
/**
* Returns true if the template editing mode is enabled.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether we're editing the template.
*/
function selectors_isEditingTemplate(state) {
return state.isEditingTemplate;
}
/**
* Returns true if meta boxes are initialized.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether meta boxes are initialized.
*/
function areMetaBoxesInitialized(state) {
return state.metaBoxes.initialized;
}
/**
* Retrieves the template of the currently edited post.
*
* @return {Object?} Post Template.
*/
const getEditedPostTemplate = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => () => {
const currentTemplate = select(external_wp_editor_namespaceObject.store).getEditedPostAttribute('template');
if (currentTemplate) {
var _select$getEntityReco;
const templateWithSameSlug = (_select$getEntityReco = select(external_wp_coreData_namespaceObject.store).getEntityRecords('postType', 'wp_template', {
per_page: -1
})) === null || _select$getEntityReco === void 0 ? void 0 : _select$getEntityReco.find(template => template.slug === currentTemplate);
if (!templateWithSameSlug) {
return templateWithSameSlug;
}
return select(external_wp_coreData_namespaceObject.store).getEditedEntityRecord('postType', 'wp_template', templateWithSameSlug.id);
}
const post = select(external_wp_editor_namespaceObject.store).getCurrentPost();
if (post.link) {
return select(external_wp_coreData_namespaceObject.store).__experimentalGetTemplateForLink(post.link);
}
return null;
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/store/constants.js
/**
* The identifier for the data store.
*
* @type {string}
*/
const constants_STORE_NAME = 'core/edit-post';
/**
* CSS selector string for the admin bar view post link anchor tag.
*
* @type {string}
*/
const VIEW_AS_LINK_SELECTOR = '#wp-admin-bar-view a';
/**
* CSS selector string for the admin bar preview post link anchor tag.
*
* @type {string}
*/
const VIEW_AS_PREVIEW_LINK_SELECTOR = '#wp-admin-bar-preview a';
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/store/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Store definition for the edit post namespace.
*
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/data/README.md#createReduxStore
*
* @type {Object}
*/
const store_store = (0,external_wp_data_namespaceObject.createReduxStore)(constants_STORE_NAME, {
reducer: reducer,
actions: store_actions_namespaceObject,
selectors: store_selectors_namespaceObject
});
(0,external_wp_data_namespaceObject.register)(store_store);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/plugins/keyboard-shortcuts-help-menu-item/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function KeyboardShortcutsHelpMenuItem(_ref) {
let {
openModal
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
onClick: () => {
openModal('edit-post/keyboard-shortcut-help');
},
shortcut: external_wp_keycodes_namespaceObject.displayShortcut.access('h')
}, (0,external_wp_i18n_namespaceObject.__)('Keyboard shortcuts'));
}
/* harmony default export */ var keyboard_shortcuts_help_menu_item = ((0,external_wp_data_namespaceObject.withDispatch)(dispatch => {
const {
openModal
} = dispatch(store_store);
return {
openModal
};
})(KeyboardShortcutsHelpMenuItem));
;// CONCATENATED MODULE: external "lodash"
var external_lodash_namespaceObject = window["lodash"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/header/tools-more-menu-group/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
const {
Fill: ToolsMoreMenuGroup,
Slot
} = (0,external_wp_components_namespaceObject.createSlotFill)('ToolsMoreMenuGroup');
ToolsMoreMenuGroup.Slot = _ref => {
let {
fillProps
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(Slot, {
fillProps: fillProps
}, fills => !(0,external_lodash_namespaceObject.isEmpty)(fills) && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, {
label: (0,external_wp_i18n_namespaceObject.__)('Tools')
}, fills));
};
/* harmony default export */ var tools_more_menu_group = (ToolsMoreMenuGroup);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/plugins/welcome-guide-menu-item/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function WelcomeGuideMenuItem() {
const isTemplateMode = (0,external_wp_data_namespaceObject.useSelect)(select => select(store_store).isEditingTemplate(), []);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_preferences_namespaceObject.PreferenceToggleMenuItem, {
scope: "core/edit-post",
name: isTemplateMode ? 'welcomeGuideTemplate' : 'welcomeGuide',
label: (0,external_wp_i18n_namespaceObject.__)('Welcome Guide')
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/plugins/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
(0,external_wp_plugins_namespaceObject.registerPlugin)('edit-post', {
render() {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(tools_more_menu_group, null, _ref => {
let {
onClose
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
role: "menuitem",
href: (0,external_wp_url_namespaceObject.addQueryArgs)('edit.php', {
post_type: 'wp_block'
})
}, (0,external_wp_i18n_namespaceObject.__)('Manage Reusable blocks')), (0,external_wp_element_namespaceObject.createElement)(keyboard_shortcuts_help_menu_item, {
onSelect: onClose
}), (0,external_wp_element_namespaceObject.createElement)(WelcomeGuideMenuItem, null), (0,external_wp_element_namespaceObject.createElement)(CopyContentMenuItem, null), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
role: "menuitem",
icon: library_external,
href: (0,external_wp_i18n_namespaceObject.__)('https://wordpress.org/support/article/wordpress-editor/'),
target: "_blank",
rel: "noopener noreferrer"
}, (0,external_wp_i18n_namespaceObject.__)('Help'), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.VisuallyHidden, {
as: "span"
},
/* translators: accessibility text */
(0,external_wp_i18n_namespaceObject.__)('(opens in a new tab)'))));
}));
}
});
;// CONCATENATED MODULE: external ["wp","keyboardShortcuts"]
var external_wp_keyboardShortcuts_namespaceObject = window["wp"]["keyboardShortcuts"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/text-editor/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function TextEditor() {
const isRichEditingEnabled = (0,external_wp_data_namespaceObject.useSelect)(select => {
return select(external_wp_editor_namespaceObject.store).getEditorSettings().richEditingEnabled;
}, []);
const {
switchEditorMode
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-text-editor"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.TextEditorGlobalKeyboardShortcuts, null), isRichEditingEnabled && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-text-editor__toolbar"
}, (0,external_wp_element_namespaceObject.createElement)("h2", null, (0,external_wp_i18n_namespaceObject.__)('Editing code')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "tertiary",
onClick: () => switchEditorMode('visual'),
shortcut: external_wp_keycodes_namespaceObject.displayShortcut.secondary('m')
}, (0,external_wp_i18n_namespaceObject.__)('Exit code editor'))), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-text-editor__body"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostTitle, null), (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostTextEditor, null)));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/arrow-left.js
/**
* WordPress dependencies
*/
const arrowLeft = (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: "M20 11.2H6.8l3.7-3.7-1-1L3.9 12l5.6 5.5 1-1-3.7-3.7H20z"
}));
/* harmony default export */ var arrow_left = (arrowLeft);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/visual-editor/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const isGutenbergPlugin = false ? 0 : false;
function MaybeIframe(_ref) {
let {
children,
contentRef,
shouldIframe,
styles,
style
} = _ref;
const ref = (0,external_wp_blockEditor_namespaceObject.__unstableUseMouseMoveTypingReset)();
if (!shouldIframe) {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.__unstableEditorStyles, {
styles: styles
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.WritingFlow, {
ref: contentRef,
className: "editor-styles-wrapper",
style: {
flex: '1',
...style
},
tabIndex: -1
}, children));
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.__unstableIframe, {
head: (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.__unstableEditorStyles, {
styles: styles
}),
ref: ref,
contentRef: contentRef,
style: {
width: '100%',
height: '100%',
display: 'block'
},
name: "editor-canvas"
}, children);
}
/**
* Given an array of nested blocks, find the first Post Content
* block inside it, recursing through any nesting levels.
*
* @param {Array} blocks A list of blocks.
*
* @return {Object | undefined} The Post Content block.
*/
function findPostContent(blocks) {
for (let i = 0; i < blocks.length; i++) {
if (blocks[i].name === 'core/post-content') {
return blocks[i];
}
if (blocks[i].innerBlocks.length) {
const nestedPostContent = findPostContent(blocks[i].innerBlocks);
if (nestedPostContent) {
return nestedPostContent;
}
}
}
}
function VisualEditor(_ref2) {
var _postContentBlock$att;
let {
styles
} = _ref2;
const {
deviceType,
isWelcomeGuideVisible,
isTemplateMode,
editedPostTemplate = {},
wrapperBlockName,
wrapperUniqueId,
isBlockBasedTheme
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
isFeatureActive,
isEditingTemplate,
__experimentalGetPreviewDeviceType,
getEditedPostTemplate
} = select(store_store);
const {
getCurrentPostId,
getCurrentPostType,
getEditorSettings
} = select(external_wp_editor_namespaceObject.store);
const _isTemplateMode = isEditingTemplate();
let _wrapperBlockName;
if (getCurrentPostType() === 'wp_block') {
_wrapperBlockName = 'core/block';
} else if (!_isTemplateMode) {
_wrapperBlockName = 'core/post-content';
}
const editorSettings = getEditorSettings();
const supportsTemplateMode = editorSettings.supportsTemplateMode;
const canEditTemplate = select(external_wp_coreData_namespaceObject.store).canUser('create', 'templates');
return {
deviceType: __experimentalGetPreviewDeviceType(),
isWelcomeGuideVisible: isFeatureActive('welcomeGuide'),
isTemplateMode: _isTemplateMode,
// Post template fetch returns a 404 on classic themes, which
// messes with e2e tests, so we check it's a block theme first.
editedPostTemplate: supportsTemplateMode && canEditTemplate ? getEditedPostTemplate() : undefined,
wrapperBlockName: _wrapperBlockName,
wrapperUniqueId: getCurrentPostId(),
isBlockBasedTheme: editorSettings.__unstableIsBlockBasedTheme
};
}, []);
const {
isCleanNewPost
} = (0,external_wp_data_namespaceObject.useSelect)(external_wp_editor_namespaceObject.store);
const hasMetaBoxes = (0,external_wp_data_namespaceObject.useSelect)(select => select(store_store).hasMetaBoxes(), []);
const {
themeHasDisabledLayoutStyles,
themeSupportsLayout,
isFocusMode
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const _settings = select(external_wp_blockEditor_namespaceObject.store).getSettings();
return {
themeHasDisabledLayoutStyles: _settings.disableLayoutStyles,
themeSupportsLayout: _settings.supportsLayout,
isFocusMode: _settings.focusMode
};
}, []);
const {
clearSelectedBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_blockEditor_namespaceObject.store);
const {
setIsEditingTemplate
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const desktopCanvasStyles = {
height: '100%',
width: '100%',
margin: 0,
display: 'flex',
flexFlow: 'column',
// Default background color so that grey
// .edit-post-editor-regions__content color doesn't show through.
background: 'white'
};
const templateModeStyles = { ...desktopCanvasStyles,
borderRadius: '2px 2px 0 0',
border: '1px solid #ddd',
borderBottom: 0
};
const resizedCanvasStyles = (0,external_wp_blockEditor_namespaceObject.__experimentalUseResizeCanvas)(deviceType, isTemplateMode);
const globalLayoutSettings = (0,external_wp_blockEditor_namespaceObject.useSetting)('layout');
const previewMode = 'is-' + deviceType.toLowerCase() + '-preview';
let animatedStyles = isTemplateMode ? templateModeStyles : desktopCanvasStyles;
if (resizedCanvasStyles) {
animatedStyles = resizedCanvasStyles;
}
let paddingBottom; // Add a constant padding for the typewritter effect. When typing at the
// bottom, there needs to be room to scroll up.
if (!hasMetaBoxes && !resizedCanvasStyles && !isTemplateMode) {
paddingBottom = '40vh';
}
const ref = (0,external_wp_element_namespaceObject.useRef)();
const contentRef = (0,external_wp_compose_namespaceObject.useMergeRefs)([ref, (0,external_wp_blockEditor_namespaceObject.__unstableUseClipboardHandler)(), (0,external_wp_blockEditor_namespaceObject.__unstableUseTypewriter)(), (0,external_wp_blockEditor_namespaceObject.__unstableUseTypingObserver)(), (0,external_wp_blockEditor_namespaceObject.__unstableUseBlockSelectionClearer)()]);
const blockSelectionClearerRef = (0,external_wp_blockEditor_namespaceObject.__unstableUseBlockSelectionClearer)(); // fallbackLayout is used if there is no Post Content,
// and for Post Title.
const fallbackLayout = (0,external_wp_element_namespaceObject.useMemo)(() => {
if (isTemplateMode) {
return {
type: 'default'
};
}
if (themeSupportsLayout) {
// We need to ensure support for wide and full alignments,
// so we add the constrained type.
return { ...globalLayoutSettings,
type: 'constrained'
};
} // Set default layout for classic themes so all alignments are supported.
return {
type: 'default'
};
}, [isTemplateMode, themeSupportsLayout, globalLayoutSettings]);
const postContentBlock = (0,external_wp_element_namespaceObject.useMemo)(() => {
// When in template editing mode, we can access the blocks directly.
if (editedPostTemplate !== null && editedPostTemplate !== void 0 && editedPostTemplate.blocks) {
return findPostContent(editedPostTemplate === null || editedPostTemplate === void 0 ? void 0 : editedPostTemplate.blocks);
} // If there are no blocks, we have to parse the content string.
// Best double-check it's a string otherwise the parse function gets unhappy.
const parseableContent = typeof (editedPostTemplate === null || editedPostTemplate === void 0 ? void 0 : editedPostTemplate.content) === 'string' ? editedPostTemplate === null || editedPostTemplate === void 0 ? void 0 : editedPostTemplate.content : '';
return findPostContent((0,external_wp_blocks_namespaceObject.parse)(parseableContent)) || {};
}, [editedPostTemplate === null || editedPostTemplate === void 0 ? void 0 : editedPostTemplate.content, editedPostTemplate === null || editedPostTemplate === void 0 ? void 0 : editedPostTemplate.blocks]);
const postContentLayoutClasses = (0,external_wp_blockEditor_namespaceObject.__experimentaluseLayoutClasses)(postContentBlock);
const blockListLayoutClass = classnames_default()({
'is-layout-flow': !themeSupportsLayout
}, themeSupportsLayout && postContentLayoutClasses);
const postContentLayoutStyles = (0,external_wp_blockEditor_namespaceObject.__experimentaluseLayoutStyles)(postContentBlock, '.block-editor-block-list__layout.is-root-container');
const layout = (postContentBlock === null || postContentBlock === void 0 ? void 0 : (_postContentBlock$att = postContentBlock.attributes) === null || _postContentBlock$att === void 0 ? void 0 : _postContentBlock$att.layout) || {}; // Update type for blocks using legacy layouts.
const postContentLayout = (0,external_wp_element_namespaceObject.useMemo)(() => {
return layout && ((layout === null || layout === void 0 ? void 0 : layout.type) === 'constrained' || layout !== null && layout !== void 0 && layout.inherit || layout !== null && layout !== void 0 && layout.contentSize || layout !== null && layout !== void 0 && layout.wideSize) ? { ...globalLayoutSettings,
...layout,
type: 'constrained'
} : { ...globalLayoutSettings,
...layout,
type: 'default'
};
}, [layout === null || layout === void 0 ? void 0 : layout.type, layout === null || layout === void 0 ? void 0 : layout.inherit, layout === null || layout === void 0 ? void 0 : layout.contentSize, layout === null || layout === void 0 ? void 0 : layout.wideSize, globalLayoutSettings]); // If there is a Post Content block we use its layout for the block list;
// if not, this must be a classic theme, in which case we use the fallback layout.
const blockListLayout = postContentBlock !== null && postContentBlock !== void 0 && postContentBlock.isValid ? postContentLayout : fallbackLayout;
const titleRef = (0,external_wp_element_namespaceObject.useRef)();
(0,external_wp_element_namespaceObject.useEffect)(() => {
var _titleRef$current;
if (isWelcomeGuideVisible || !isCleanNewPost()) {
return;
}
titleRef === null || titleRef === void 0 ? void 0 : (_titleRef$current = titleRef.current) === null || _titleRef$current === void 0 ? void 0 : _titleRef$current.focus();
}, [isWelcomeGuideVisible, isCleanNewPost]);
styles = (0,external_wp_element_namespaceObject.useMemo)(() => [...styles, {
// We should move this in to future to the body.
css: `.edit-post-visual-editor__post-title-wrapper{margin-top:4rem}` + (paddingBottom ? `body{padding-bottom:${paddingBottom}}` : '')
}], [styles]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockTools, {
__unstableContentRef: ref,
className: classnames_default()('edit-post-visual-editor', {
'is-template-mode': isTemplateMode
})
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.VisualEditorGlobalKeyboardShortcuts, null), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableMotion.div, {
className: "edit-post-visual-editor__content-area",
animate: {
padding: isTemplateMode ? '48px 48px 0' : '0'
},
ref: blockSelectionClearerRef
}, isTemplateMode && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "edit-post-visual-editor__exit-template-mode",
icon: arrow_left,
onClick: () => {
clearSelectedBlock();
setIsEditingTemplate(false);
}
}, (0,external_wp_i18n_namespaceObject.__)('Back')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableMotion.div, {
animate: animatedStyles,
initial: desktopCanvasStyles,
className: previewMode
}, (0,external_wp_element_namespaceObject.createElement)(MaybeIframe, {
shouldIframe: isGutenbergPlugin && isBlockBasedTheme && !hasMetaBoxes || isTemplateMode || deviceType === 'Tablet' || deviceType === 'Mobile',
contentRef: contentRef,
styles: styles
}, themeSupportsLayout && !themeHasDisabledLayoutStyles && !isTemplateMode && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.__experimentalLayoutStyle, {
selector: ".edit-post-visual-editor__post-title-wrapper, .block-editor-block-list__layout.is-root-container",
layout: fallbackLayout,
layoutDefinitions: globalLayoutSettings === null || globalLayoutSettings === void 0 ? void 0 : globalLayoutSettings.definitions
}), postContentLayoutStyles && (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.__experimentalLayoutStyle, {
layout: postContentLayout,
css: postContentLayoutStyles,
layoutDefinitions: globalLayoutSettings === null || globalLayoutSettings === void 0 ? void 0 : globalLayoutSettings.definitions
})), !isTemplateMode && (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('edit-post-visual-editor__post-title-wrapper', {
'is-focus-mode': isFocusMode
}, 'is-layout-flow'),
contentEditable: false
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostTitle, {
ref: titleRef
})), (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.__experimentalRecursionProvider, {
blockName: wrapperBlockName,
uniqueId: wrapperUniqueId
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockList, {
className: isTemplateMode ? 'wp-site-blocks' : `${blockListLayoutClass} wp-block-post-content` // Ensure root level blocks receive default/flow blockGap styling rules.
,
__experimentalLayout: blockListLayout
}))))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/keyboard-shortcuts/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function KeyboardShortcuts() {
const {
getBlockSelectionStart
} = (0,external_wp_data_namespaceObject.useSelect)(external_wp_blockEditor_namespaceObject.store);
const {
getEditorMode,
isEditorSidebarOpened,
isListViewOpened,
isFeatureActive
} = (0,external_wp_data_namespaceObject.useSelect)(store_store);
const isModeToggleDisabled = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
richEditingEnabled,
codeEditingEnabled
} = select(external_wp_editor_namespaceObject.store).getEditorSettings();
return !richEditingEnabled || !codeEditingEnabled;
}, []);
const {
createInfoNotice
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_notices_namespaceObject.store);
const {
switchEditorMode,
openGeneralSidebar,
closeGeneralSidebar,
toggleFeature,
setIsListViewOpened,
setIsInserterOpened
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const {
registerShortcut
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_keyboardShortcuts_namespaceObject.store);
const {
set: setPreference
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_preferences_namespaceObject.store);
const toggleDistractionFree = () => {
setPreference('core/edit-post', 'fixedToolbar', false);
setIsInserterOpened(false);
setIsListViewOpened(false);
closeGeneralSidebar();
};
const {
replaceBlocks
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_blockEditor_namespaceObject.store);
const {
getBlockName,
getSelectedBlockClientId,
getBlockAttributes
} = (0,external_wp_data_namespaceObject.useSelect)(external_wp_blockEditor_namespaceObject.store);
const handleTextLevelShortcut = (event, level) => {
event.preventDefault();
const destinationBlockName = level === 0 ? 'core/paragraph' : 'core/heading';
const currentClientId = getSelectedBlockClientId();
if (currentClientId === null) {
return;
}
const blockName = getBlockName(currentClientId);
if (blockName !== 'core/paragraph' && blockName !== 'core/heading') {
return;
}
const currentAttributes = getBlockAttributes(currentClientId);
const {
content: currentContent,
align: currentAlign
} = currentAttributes;
replaceBlocks(currentClientId, (0,external_wp_blocks_namespaceObject.createBlock)(destinationBlockName, {
level,
content: currentContent,
align: currentAlign
}));
};
(0,external_wp_element_namespaceObject.useEffect)(() => {
registerShortcut({
name: 'core/edit-post/toggle-mode',
category: 'global',
description: (0,external_wp_i18n_namespaceObject.__)('Switch between visual editor and code editor.'),
keyCombination: {
modifier: 'secondary',
character: 'm'
}
});
registerShortcut({
name: 'core/edit-post/toggle-distraction-free',
category: 'global',
description: (0,external_wp_i18n_namespaceObject.__)('Toggle distraction free mode.'),
keyCombination: {
modifier: 'primaryShift',
character: '\\'
}
});
registerShortcut({
name: 'core/edit-post/toggle-fullscreen',
category: 'global',
description: (0,external_wp_i18n_namespaceObject.__)('Toggle fullscreen mode.'),
keyCombination: {
modifier: 'secondary',
character: 'f'
}
});
registerShortcut({
name: 'core/edit-post/toggle-list-view',
category: 'global',
description: (0,external_wp_i18n_namespaceObject.__)('Open the block list view.'),
keyCombination: {
modifier: 'access',
character: 'o'
}
});
registerShortcut({
name: 'core/edit-post/toggle-sidebar',
category: 'global',
description: (0,external_wp_i18n_namespaceObject.__)('Show or hide the settings sidebar.'),
keyCombination: {
modifier: 'primaryShift',
character: ','
}
});
registerShortcut({
name: 'core/edit-post/next-region',
category: 'global',
description: (0,external_wp_i18n_namespaceObject.__)('Navigate to the next part of the editor.'),
keyCombination: {
modifier: 'ctrl',
character: '`'
},
aliases: [{
modifier: 'access',
character: 'n'
}]
});
registerShortcut({
name: 'core/edit-post/previous-region',
category: 'global',
description: (0,external_wp_i18n_namespaceObject.__)('Navigate to the previous part of the editor.'),
keyCombination: {
modifier: 'ctrlShift',
character: '`'
},
aliases: [{
modifier: 'access',
character: 'p'
}, {
modifier: 'ctrlShift',
character: '~'
}]
});
registerShortcut({
name: 'core/edit-post/keyboard-shortcuts',
category: 'main',
description: (0,external_wp_i18n_namespaceObject.__)('Display these keyboard shortcuts.'),
keyCombination: {
modifier: 'access',
character: 'h'
}
});
registerShortcut({
name: `core/block-editor/transform-heading-to-paragraph`,
category: 'block-library',
description: (0,external_wp_i18n_namespaceObject.__)('Transform heading to paragraph.'),
keyCombination: {
modifier: 'access',
character: `0`
}
});
[1, 2, 3, 4, 5, 6].forEach(level => {
registerShortcut({
name: `core/block-editor/transform-paragraph-to-heading-${level}`,
category: 'block-library',
description: (0,external_wp_i18n_namespaceObject.__)('Transform paragraph to heading.'),
keyCombination: {
modifier: 'access',
character: `${level}`
}
});
});
}, []);
(0,external_wp_keyboardShortcuts_namespaceObject.useShortcut)('core/edit-post/toggle-mode', () => {
switchEditorMode(getEditorMode() === 'visual' ? 'text' : 'visual');
}, {
isDisabled: isModeToggleDisabled
});
(0,external_wp_keyboardShortcuts_namespaceObject.useShortcut)('core/edit-post/toggle-fullscreen', () => {
toggleFeature('fullscreenMode');
});
(0,external_wp_keyboardShortcuts_namespaceObject.useShortcut)('core/edit-post/toggle-distraction-free', () => {
closeGeneralSidebar();
setIsListViewOpened(false);
toggleDistractionFree();
toggleFeature('distractionFree');
createInfoNotice(isFeatureActive('distractionFree') ? (0,external_wp_i18n_namespaceObject.__)('Distraction free mode turned on.') : (0,external_wp_i18n_namespaceObject.__)('Distraction free mode turned off.'), {
id: 'core/edit-post/distraction-free-mode/notice',
type: 'snackbar'
});
});
(0,external_wp_keyboardShortcuts_namespaceObject.useShortcut)('core/edit-post/toggle-sidebar', event => {
// This shortcut has no known clashes, but use preventDefault to prevent any
// obscure shortcuts from triggering.
event.preventDefault();
if (isEditorSidebarOpened()) {
closeGeneralSidebar();
} else {
const sidebarToOpen = getBlockSelectionStart() ? 'edit-post/block' : 'edit-post/document';
openGeneralSidebar(sidebarToOpen);
}
});
(0,external_wp_keyboardShortcuts_namespaceObject.useShortcut)('core/edit-post/toggle-list-view', () => setIsListViewOpened(!isListViewOpened()));
(0,external_wp_keyboardShortcuts_namespaceObject.useShortcut)('core/block-editor/transform-heading-to-paragraph', event => handleTextLevelShortcut(event, 0));
[1, 2, 3, 4, 5, 6].forEach(level => {
//the loop is based off on a constant therefore
//the hook will execute the same way every time
//eslint-disable-next-line react-hooks/rules-of-hooks
(0,external_wp_keyboardShortcuts_namespaceObject.useShortcut)(`core/block-editor/transform-paragraph-to-heading-${level}`, event => handleTextLevelShortcut(event, level));
});
return null;
}
/* harmony default export */ var keyboard_shortcuts = (KeyboardShortcuts);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/keyboard-shortcut-help-modal/config.js
/**
* WordPress dependencies
*/
const textFormattingShortcuts = [{
keyCombination: {
modifier: 'primary',
character: 'b'
},
description: (0,external_wp_i18n_namespaceObject.__)('Make the selected text bold.')
}, {
keyCombination: {
modifier: 'primary',
character: 'i'
},
description: (0,external_wp_i18n_namespaceObject.__)('Make the selected text italic.')
}, {
keyCombination: {
modifier: 'primary',
character: 'k'
},
description: (0,external_wp_i18n_namespaceObject.__)('Convert the selected text into a link.')
}, {
keyCombination: {
modifier: 'primaryShift',
character: 'k'
},
description: (0,external_wp_i18n_namespaceObject.__)('Remove a link.')
}, {
keyCombination: {
character: '[['
},
description: (0,external_wp_i18n_namespaceObject.__)('Insert a link to a post or page.')
}, {
keyCombination: {
modifier: 'primary',
character: 'u'
},
description: (0,external_wp_i18n_namespaceObject.__)('Underline the selected text.')
}, {
keyCombination: {
modifier: 'access',
character: 'd'
},
description: (0,external_wp_i18n_namespaceObject.__)('Strikethrough the selected text.')
}, {
keyCombination: {
modifier: 'access',
character: 'x'
},
description: (0,external_wp_i18n_namespaceObject.__)('Make the selected text inline code.')
}, {
keyCombination: {
modifier: 'access',
character: '0'
},
description: (0,external_wp_i18n_namespaceObject.__)('Convert the current heading to a paragraph.')
}, {
keyCombination: {
modifier: 'access',
character: '1-6'
},
description: (0,external_wp_i18n_namespaceObject.__)('Convert the current paragraph or heading to a heading of level 1 to 6.')
}];
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/keyboard-shortcut-help-modal/shortcut.js
/**
* WordPress dependencies
*/
function KeyCombination(_ref) {
let {
keyCombination,
forceAriaLabel
} = _ref;
const shortcut = keyCombination.modifier ? external_wp_keycodes_namespaceObject.displayShortcutList[keyCombination.modifier](keyCombination.character) : keyCombination.character;
const ariaLabel = keyCombination.modifier ? external_wp_keycodes_namespaceObject.shortcutAriaLabel[keyCombination.modifier](keyCombination.character) : keyCombination.character;
return (0,external_wp_element_namespaceObject.createElement)("kbd", {
className: "edit-post-keyboard-shortcut-help-modal__shortcut-key-combination",
"aria-label": forceAriaLabel || ariaLabel
}, (Array.isArray(shortcut) ? shortcut : [shortcut]).map((character, index) => {
if (character === '+') {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, {
key: index
}, character);
}
return (0,external_wp_element_namespaceObject.createElement)("kbd", {
key: index,
className: "edit-post-keyboard-shortcut-help-modal__shortcut-key"
}, character);
}));
}
function Shortcut(_ref2) {
let {
description,
keyCombination,
aliases = [],
ariaLabel
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-keyboard-shortcut-help-modal__shortcut-description"
}, description), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-keyboard-shortcut-help-modal__shortcut-term"
}, (0,external_wp_element_namespaceObject.createElement)(KeyCombination, {
keyCombination: keyCombination,
forceAriaLabel: ariaLabel
}), aliases.map((alias, index) => (0,external_wp_element_namespaceObject.createElement)(KeyCombination, {
keyCombination: alias,
forceAriaLabel: ariaLabel,
key: index
}))));
}
/* harmony default export */ var keyboard_shortcut_help_modal_shortcut = (Shortcut);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/keyboard-shortcut-help-modal/dynamic-shortcut.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function DynamicShortcut(_ref) {
let {
name
} = _ref;
const {
keyCombination,
description,
aliases
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getShortcutKeyCombination,
getShortcutDescription,
getShortcutAliases
} = select(external_wp_keyboardShortcuts_namespaceObject.store);
return {
keyCombination: getShortcutKeyCombination(name),
aliases: getShortcutAliases(name),
description: getShortcutDescription(name)
};
}, [name]);
if (!keyCombination) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(keyboard_shortcut_help_modal_shortcut, {
keyCombination: keyCombination,
description: description,
aliases: aliases
});
}
/* harmony default export */ var dynamic_shortcut = (DynamicShortcut);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/keyboard-shortcut-help-modal/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const MODAL_NAME = 'edit-post/keyboard-shortcut-help';
const ShortcutList = _ref => {
let {
shortcuts
} = _ref;
return (
/*
* Disable reason: The `list` ARIA role is redundant but
* Safari+VoiceOver won't announce the list otherwise.
*/
/* eslint-disable jsx-a11y/no-redundant-roles */
(0,external_wp_element_namespaceObject.createElement)("ul", {
className: "edit-post-keyboard-shortcut-help-modal__shortcut-list",
role: "list"
}, shortcuts.map((shortcut, index) => (0,external_wp_element_namespaceObject.createElement)("li", {
className: "edit-post-keyboard-shortcut-help-modal__shortcut",
key: index
}, typeof shortcut === 'string' ? (0,external_wp_element_namespaceObject.createElement)(dynamic_shortcut, {
name: shortcut
}) : (0,external_wp_element_namespaceObject.createElement)(keyboard_shortcut_help_modal_shortcut, shortcut))))
/* eslint-enable jsx-a11y/no-redundant-roles */
);
};
const ShortcutSection = _ref2 => {
let {
title,
shortcuts,
className
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)("section", {
className: classnames_default()('edit-post-keyboard-shortcut-help-modal__section', className)
}, !!title && (0,external_wp_element_namespaceObject.createElement)("h2", {
className: "edit-post-keyboard-shortcut-help-modal__section-title"
}, title), (0,external_wp_element_namespaceObject.createElement)(ShortcutList, {
shortcuts: shortcuts
}));
};
const ShortcutCategorySection = _ref3 => {
let {
title,
categoryName,
additionalShortcuts = []
} = _ref3;
const categoryShortcuts = (0,external_wp_data_namespaceObject.useSelect)(select => {
return select(external_wp_keyboardShortcuts_namespaceObject.store).getCategoryShortcuts(categoryName);
}, [categoryName]);
return (0,external_wp_element_namespaceObject.createElement)(ShortcutSection, {
title: title,
shortcuts: categoryShortcuts.concat(additionalShortcuts)
});
};
function KeyboardShortcutHelpModal(_ref4) {
let {
isModalActive,
toggleModal
} = _ref4;
(0,external_wp_keyboardShortcuts_namespaceObject.useShortcut)('core/edit-post/keyboard-shortcuts', toggleModal);
if (!isModalActive) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Modal, {
className: "edit-post-keyboard-shortcut-help-modal",
title: (0,external_wp_i18n_namespaceObject.__)('Keyboard shortcuts'),
closeButtonLabel: (0,external_wp_i18n_namespaceObject.__)('Close'),
onRequestClose: toggleModal
}, (0,external_wp_element_namespaceObject.createElement)(ShortcutSection, {
className: "edit-post-keyboard-shortcut-help-modal__main-shortcuts",
shortcuts: ['core/edit-post/keyboard-shortcuts']
}), (0,external_wp_element_namespaceObject.createElement)(ShortcutCategorySection, {
title: (0,external_wp_i18n_namespaceObject.__)('Global shortcuts'),
categoryName: "global"
}), (0,external_wp_element_namespaceObject.createElement)(ShortcutCategorySection, {
title: (0,external_wp_i18n_namespaceObject.__)('Selection shortcuts'),
categoryName: "selection"
}), (0,external_wp_element_namespaceObject.createElement)(ShortcutCategorySection, {
title: (0,external_wp_i18n_namespaceObject.__)('Block shortcuts'),
categoryName: "block",
additionalShortcuts: [{
keyCombination: {
character: '/'
},
description: (0,external_wp_i18n_namespaceObject.__)('Change the block type after adding a new paragraph.'),
/* translators: The forward-slash character. e.g. '/'. */
ariaLabel: (0,external_wp_i18n_namespaceObject.__)('Forward-slash')
}]
}), (0,external_wp_element_namespaceObject.createElement)(ShortcutSection, {
title: (0,external_wp_i18n_namespaceObject.__)('Text formatting'),
shortcuts: textFormattingShortcuts
}));
}
/* harmony default export */ var keyboard_shortcut_help_modal = ((0,external_wp_compose_namespaceObject.compose)([(0,external_wp_data_namespaceObject.withSelect)(select => ({
isModalActive: select(store_store).isModalActive(MODAL_NAME)
})), (0,external_wp_data_namespaceObject.withDispatch)((dispatch, _ref5) => {
let {
isModalActive
} = _ref5;
const {
openModal,
closeModal
} = dispatch(store_store);
return {
toggleModal: () => isModalActive ? closeModal() : openModal(MODAL_NAME)
};
})])(KeyboardShortcutHelpModal));
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/preferences-modal/options/enable-custom-fields.js
/**
* WordPress dependencies
*/
function CustomFieldsConfirmation(_ref) {
let {
willEnable
} = _ref;
const [isReloading, setIsReloading] = (0,external_wp_element_namespaceObject.useState)(false);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("p", {
className: "edit-post-preferences-modal__custom-fields-confirmation-message"
}, (0,external_wp_i18n_namespaceObject.__)('A page reload is required for this change. Make sure your content is saved before reloading.')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "edit-post-preferences-modal__custom-fields-confirmation-button",
variant: "secondary",
isBusy: isReloading,
disabled: isReloading,
onClick: () => {
setIsReloading(true);
document.getElementById('toggle-custom-fields-form').submit();
}
}, willEnable ? (0,external_wp_i18n_namespaceObject.__)('Enable & Reload') : (0,external_wp_i18n_namespaceObject.__)('Disable & Reload')));
}
function EnableCustomFieldsOption(_ref2) {
let {
label,
areCustomFieldsEnabled
} = _ref2;
const [isChecked, setIsChecked] = (0,external_wp_element_namespaceObject.useState)(areCustomFieldsEnabled);
return (0,external_wp_element_namespaceObject.createElement)(preferences_modal_base_option, {
label: label,
isChecked: isChecked,
onChange: setIsChecked
}, isChecked !== areCustomFieldsEnabled && (0,external_wp_element_namespaceObject.createElement)(CustomFieldsConfirmation, {
willEnable: isChecked
}));
}
/* harmony default export */ var enable_custom_fields = ((0,external_wp_data_namespaceObject.withSelect)(select => ({
areCustomFieldsEnabled: !!select(external_wp_editor_namespaceObject.store).getEditorSettings().enableCustomFields
}))(EnableCustomFieldsOption));
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/preferences-modal/options/enable-panel.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/* harmony default export */ var enable_panel = ((0,external_wp_compose_namespaceObject.compose)((0,external_wp_data_namespaceObject.withSelect)((select, _ref) => {
let {
panelName
} = _ref;
const {
isEditorPanelEnabled,
isEditorPanelRemoved
} = select(store_store);
return {
isRemoved: isEditorPanelRemoved(panelName),
isChecked: isEditorPanelEnabled(panelName)
};
}), (0,external_wp_compose_namespaceObject.ifCondition)(_ref2 => {
let {
isRemoved
} = _ref2;
return !isRemoved;
}), (0,external_wp_data_namespaceObject.withDispatch)((dispatch, _ref3) => {
let {
panelName
} = _ref3;
return {
onChange: () => dispatch(store_store).toggleEditorPanelEnabled(panelName)
};
}))(preferences_modal_base_option));
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/preferences-modal/options/enable-plugin-document-setting-panel.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const {
Fill,
Slot: enable_plugin_document_setting_panel_Slot
} = (0,external_wp_components_namespaceObject.createSlotFill)('EnablePluginDocumentSettingPanelOption');
const EnablePluginDocumentSettingPanelOption = _ref => {
let {
label,
panelName
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(Fill, null, (0,external_wp_element_namespaceObject.createElement)(enable_panel, {
label: label,
panelName: panelName
}));
};
EnablePluginDocumentSettingPanelOption.Slot = enable_plugin_document_setting_panel_Slot;
/* harmony default export */ var enable_plugin_document_setting_panel = (EnablePluginDocumentSettingPanelOption);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/preferences-modal/options/enable-publish-sidebar.js
/**
* WordPress dependencies
*/
/* harmony default export */ var enable_publish_sidebar = ((0,external_wp_compose_namespaceObject.compose)((0,external_wp_data_namespaceObject.withSelect)(select => ({
isChecked: select(external_wp_editor_namespaceObject.store).isPublishSidebarEnabled()
})), (0,external_wp_data_namespaceObject.withDispatch)(dispatch => {
const {
enablePublishSidebar,
disablePublishSidebar
} = dispatch(external_wp_editor_namespaceObject.store);
return {
onChange: isEnabled => isEnabled ? enablePublishSidebar() : disablePublishSidebar()
};
}), // In < medium viewports we override this option and always show the publish sidebar.
// See the edit-post's header component for the specific logic.
(0,external_wp_viewport_namespaceObject.ifViewportMatches)('medium'))(preferences_modal_base_option));
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/preferences-modal/options/enable-feature.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/* harmony default export */ var enable_feature = ((0,external_wp_compose_namespaceObject.compose)((0,external_wp_data_namespaceObject.withSelect)((select, _ref) => {
let {
featureName
} = _ref;
const {
isFeatureActive
} = select(store_store);
return {
isChecked: isFeatureActive(featureName)
};
}), (0,external_wp_data_namespaceObject.withDispatch)((dispatch, _ref2) => {
let {
featureName,
onToggle = () => {}
} = _ref2;
return {
onChange: () => {
onToggle();
dispatch(store_store).toggleFeature(featureName);
}
};
}))(preferences_modal_base_option));
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/preferences-modal/options/index.js
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/preferences-modal/meta-boxes-section.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function MetaBoxesSection(_ref) {
let {
areCustomFieldsRegistered,
metaBoxes,
...sectionProps
} = _ref;
// The 'Custom Fields' meta box is a special case that we handle separately.
const thirdPartyMetaBoxes = metaBoxes.filter(_ref2 => {
let {
id
} = _ref2;
return id !== 'postcustom';
});
if (!areCustomFieldsRegistered && thirdPartyMetaBoxes.length === 0) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(preferences_modal_section, sectionProps, areCustomFieldsRegistered && (0,external_wp_element_namespaceObject.createElement)(enable_custom_fields, {
label: (0,external_wp_i18n_namespaceObject.__)('Custom fields')
}), thirdPartyMetaBoxes.map(_ref3 => {
let {
id,
title
} = _ref3;
return (0,external_wp_element_namespaceObject.createElement)(enable_panel, {
key: id,
label: title,
panelName: `meta-box-${id}`
});
}));
}
/* harmony default export */ var meta_boxes_section = ((0,external_wp_data_namespaceObject.withSelect)(select => {
const {
getEditorSettings
} = select(external_wp_editor_namespaceObject.store);
const {
getAllMetaBoxes
} = select(store_store);
return {
// This setting should not live in the block editor's store.
areCustomFieldsRegistered: getEditorSettings().enableCustomFields !== undefined,
metaBoxes: getAllMetaBoxes()
};
})(MetaBoxesSection));
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/block-manager/checklist.js
/**
* WordPress dependencies
*/
function BlockTypesChecklist(_ref) {
let {
blockTypes,
value,
onItemChange
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("ul", {
className: "edit-post-block-manager__checklist"
}, blockTypes.map(blockType => (0,external_wp_element_namespaceObject.createElement)("li", {
key: blockType.name,
className: "edit-post-block-manager__checklist-item"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.CheckboxControl, {
__nextHasNoMarginBottom: true,
label: blockType.title,
checked: value.includes(blockType.name),
onChange: function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return onItemChange(blockType.name, ...args);
}
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockIcon, {
icon: blockType.icon
}))));
}
/* harmony default export */ var checklist = (BlockTypesChecklist);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/block-manager/category.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function BlockManagerCategory(_ref) {
let {
title,
blockTypes
} = _ref;
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(BlockManagerCategory);
const {
defaultAllowedBlockTypes,
hiddenBlockTypes
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getEditorSettings
} = select(external_wp_editor_namespaceObject.store);
const {
getHiddenBlockTypes
} = select(store_store);
return {
defaultAllowedBlockTypes: getEditorSettings().defaultAllowedBlockTypes,
hiddenBlockTypes: getHiddenBlockTypes()
};
}, []);
const filteredBlockTypes = (0,external_wp_element_namespaceObject.useMemo)(() => {
if (defaultAllowedBlockTypes === true) {
return blockTypes;
}
return blockTypes.filter(_ref2 => {
let {
name
} = _ref2;
return defaultAllowedBlockTypes === null || defaultAllowedBlockTypes === void 0 ? void 0 : defaultAllowedBlockTypes.includes(name);
});
}, [defaultAllowedBlockTypes, blockTypes]);
const {
showBlockTypes,
hideBlockTypes
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const toggleVisible = (0,external_wp_element_namespaceObject.useCallback)((blockName, nextIsChecked) => {
if (nextIsChecked) {
showBlockTypes(blockName);
} else {
hideBlockTypes(blockName);
}
}, []);
const toggleAllVisible = (0,external_wp_element_namespaceObject.useCallback)(nextIsChecked => {
const blockNames = blockTypes.map(_ref3 => {
let {
name
} = _ref3;
return name;
});
if (nextIsChecked) {
showBlockTypes(blockNames);
} else {
hideBlockTypes(blockNames);
}
}, [blockTypes]);
if (!filteredBlockTypes.length) {
return null;
}
const checkedBlockNames = filteredBlockTypes.map(_ref4 => {
let {
name
} = _ref4;
return name;
}).filter(type => !hiddenBlockTypes.includes(type));
const titleId = 'edit-post-block-manager__category-title-' + instanceId;
const isAllChecked = checkedBlockNames.length === filteredBlockTypes.length;
const isIndeterminate = !isAllChecked && checkedBlockNames.length > 0;
return (0,external_wp_element_namespaceObject.createElement)("div", {
role: "group",
"aria-labelledby": titleId,
className: "edit-post-block-manager__category"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.CheckboxControl, {
__nextHasNoMarginBottom: true,
checked: isAllChecked,
onChange: toggleAllVisible,
className: "edit-post-block-manager__category-title",
indeterminate: isIndeterminate,
label: (0,external_wp_element_namespaceObject.createElement)("span", {
id: titleId
}, title)
}), (0,external_wp_element_namespaceObject.createElement)(checklist, {
blockTypes: filteredBlockTypes,
value: checkedBlockNames,
onItemChange: toggleVisible
}));
}
/* harmony default export */ var block_manager_category = (BlockManagerCategory);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/block-manager/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function BlockManager(_ref) {
let {
blockTypes,
categories,
hasBlockSupport,
isMatchingSearchTerm,
numberOfHiddenBlocks
} = _ref;
const debouncedSpeak = (0,external_wp_compose_namespaceObject.useDebounce)(external_wp_a11y_namespaceObject.speak, 500);
const [search, setSearch] = (0,external_wp_element_namespaceObject.useState)(''); // Filtering occurs here (as opposed to `withSelect`) to avoid
// wasted renders by consequence of `Array#filter` producing
// a new value reference on each call.
blockTypes = blockTypes.filter(blockType => hasBlockSupport(blockType, 'inserter', true) && (!search || isMatchingSearchTerm(blockType, search)) && (!blockType.parent || blockType.parent.includes('core/post-content'))); // Announce search results on change
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (!search) {
return;
}
const count = blockTypes.length;
const resultsFoundMessage = (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %d: number of results. */
(0,external_wp_i18n_namespaceObject._n)('%d result found.', '%d results found.', count), count);
debouncedSpeak(resultsFoundMessage);
}, [blockTypes.length, search, debouncedSpeak]);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-block-manager__content"
}, !!numberOfHiddenBlocks && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-block-manager__disabled-blocks-count"
}, (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %d: number of blocks. */
(0,external_wp_i18n_namespaceObject._n)('%d block is hidden.', '%d blocks are hidden.', numberOfHiddenBlocks), numberOfHiddenBlocks)), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SearchControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Search for a block'),
placeholder: (0,external_wp_i18n_namespaceObject.__)('Search for a block'),
value: search,
onChange: nextSearch => setSearch(nextSearch),
className: "edit-post-block-manager__search"
}), (0,external_wp_element_namespaceObject.createElement)("div", {
tabIndex: "0",
role: "region",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Available block types'),
className: "edit-post-block-manager__results"
}, blockTypes.length === 0 && (0,external_wp_element_namespaceObject.createElement)("p", {
className: "edit-post-block-manager__no-results"
}, (0,external_wp_i18n_namespaceObject.__)('No blocks found.')), categories.map(category => (0,external_wp_element_namespaceObject.createElement)(block_manager_category, {
key: category.slug,
title: category.title,
blockTypes: blockTypes.filter(blockType => blockType.category === category.slug)
})), (0,external_wp_element_namespaceObject.createElement)(block_manager_category, {
title: (0,external_wp_i18n_namespaceObject.__)('Uncategorized'),
blockTypes: blockTypes.filter(_ref2 => {
let {
category
} = _ref2;
return !category;
})
})));
}
/* harmony default export */ var block_manager = ((0,external_wp_data_namespaceObject.withSelect)(select => {
const {
getBlockTypes,
getCategories,
hasBlockSupport,
isMatchingSearchTerm
} = select(external_wp_blocks_namespaceObject.store);
const {
getHiddenBlockTypes
} = select(store_store); // Some hidden blocks become unregistered
// by removing for instance the plugin that registered them, yet
// they're still remain as hidden by the user's action.
// We consider "hidden", blocks which were hidden and
// are still registered.
const blockTypes = getBlockTypes();
const hiddenBlockTypes = getHiddenBlockTypes().filter(hiddenBlock => {
return blockTypes.some(registeredBlock => registeredBlock.name === hiddenBlock);
});
const numberOfHiddenBlocks = Array.isArray(hiddenBlockTypes) && hiddenBlockTypes.length;
return {
blockTypes,
categories: getCategories(),
hasBlockSupport,
isMatchingSearchTerm,
numberOfHiddenBlocks
};
})(BlockManager));
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/preferences-modal/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const preferences_modal_MODAL_NAME = 'edit-post/preferences';
function EditPostPreferencesModal() {
const isLargeViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('medium');
const {
closeModal
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const [isModalActive, showBlockBreadcrumbsOption] = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getEditorSettings
} = select(external_wp_editor_namespaceObject.store);
const {
getEditorMode,
isFeatureActive
} = select(store_store);
const modalActive = select(store_store).isModalActive(preferences_modal_MODAL_NAME);
const mode = getEditorMode();
const isRichEditingEnabled = getEditorSettings().richEditingEnabled;
const isDistractionFreeEnabled = isFeatureActive('distractionFree');
return [modalActive, !isDistractionFreeEnabled && isLargeViewport && isRichEditingEnabled && mode === 'visual', isDistractionFreeEnabled];
}, [isLargeViewport]);
const {
closeGeneralSidebar,
setIsListViewOpened,
setIsInserterOpened
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const {
set: setPreference
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_preferences_namespaceObject.store);
const toggleDistractionFree = () => {
setPreference('core/edit-post', 'fixedToolbar', false);
setIsInserterOpened(false);
setIsListViewOpened(false);
closeGeneralSidebar();
};
const sections = (0,external_wp_element_namespaceObject.useMemo)(() => [{
name: 'general',
tabLabel: (0,external_wp_i18n_namespaceObject.__)('General'),
content: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, isLargeViewport && (0,external_wp_element_namespaceObject.createElement)(preferences_modal_section, {
title: (0,external_wp_i18n_namespaceObject.__)('Publishing'),
description: (0,external_wp_i18n_namespaceObject.__)('Change options related to publishing.')
}, (0,external_wp_element_namespaceObject.createElement)(enable_publish_sidebar, {
help: (0,external_wp_i18n_namespaceObject.__)('Review settings, such as visibility and tags.'),
label: (0,external_wp_i18n_namespaceObject.__)('Include pre-publish checklist')
})), (0,external_wp_element_namespaceObject.createElement)(preferences_modal_section, {
title: (0,external_wp_i18n_namespaceObject.__)('Appearance'),
description: (0,external_wp_i18n_namespaceObject.__)('Customize options related to the block editor interface and editing flow.')
}, (0,external_wp_element_namespaceObject.createElement)(enable_feature, {
featureName: "distractionFree",
onToggle: toggleDistractionFree,
help: (0,external_wp_i18n_namespaceObject.__)('Reduce visual distractions by hiding the toolbar and other elements to focus on writing.'),
label: (0,external_wp_i18n_namespaceObject.__)('Distraction free')
}), (0,external_wp_element_namespaceObject.createElement)(enable_feature, {
featureName: "focusMode",
help: (0,external_wp_i18n_namespaceObject.__)('Highlights the current block and fades other content.'),
label: (0,external_wp_i18n_namespaceObject.__)('Spotlight mode')
}), (0,external_wp_element_namespaceObject.createElement)(enable_feature, {
featureName: "showIconLabels",
label: (0,external_wp_i18n_namespaceObject.__)('Show button text labels'),
help: (0,external_wp_i18n_namespaceObject.__)('Show text instead of icons on buttons.')
}), (0,external_wp_element_namespaceObject.createElement)(enable_feature, {
featureName: "showListViewByDefault",
help: (0,external_wp_i18n_namespaceObject.__)('Opens the block list view sidebar by default.'),
label: (0,external_wp_i18n_namespaceObject.__)('Always open list view')
}), (0,external_wp_element_namespaceObject.createElement)(enable_feature, {
featureName: "themeStyles",
help: (0,external_wp_i18n_namespaceObject.__)('Make the editor look like your theme.'),
label: (0,external_wp_i18n_namespaceObject.__)('Use theme styles')
}), showBlockBreadcrumbsOption && (0,external_wp_element_namespaceObject.createElement)(enable_feature, {
featureName: "showBlockBreadcrumbs",
help: (0,external_wp_i18n_namespaceObject.__)('Shows block breadcrumbs at the bottom of the editor.'),
label: (0,external_wp_i18n_namespaceObject.__)('Display block breadcrumbs')
})))
}, {
name: 'blocks',
tabLabel: (0,external_wp_i18n_namespaceObject.__)('Blocks'),
content: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(preferences_modal_section, {
title: (0,external_wp_i18n_namespaceObject.__)('Block interactions'),
description: (0,external_wp_i18n_namespaceObject.__)('Customize how you interact with blocks in the block library and editing canvas.')
}, (0,external_wp_element_namespaceObject.createElement)(enable_feature, {
featureName: "mostUsedBlocks",
help: (0,external_wp_i18n_namespaceObject.__)('Places the most frequent blocks in the block library.'),
label: (0,external_wp_i18n_namespaceObject.__)('Show most used blocks')
}), (0,external_wp_element_namespaceObject.createElement)(enable_feature, {
featureName: "keepCaretInsideBlock",
help: (0,external_wp_i18n_namespaceObject.__)('Aids screen readers by stopping text caret from leaving blocks.'),
label: (0,external_wp_i18n_namespaceObject.__)('Contain text cursor inside block')
})), (0,external_wp_element_namespaceObject.createElement)(preferences_modal_section, {
title: (0,external_wp_i18n_namespaceObject.__)('Visible blocks'),
description: (0,external_wp_i18n_namespaceObject.__)("Disable blocks that you don't want to appear in the inserter. They can always be toggled back on later.")
}, (0,external_wp_element_namespaceObject.createElement)(block_manager, null)))
}, {
name: 'panels',
tabLabel: (0,external_wp_i18n_namespaceObject.__)('Panels'),
content: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(preferences_modal_section, {
title: (0,external_wp_i18n_namespaceObject.__)('Document settings'),
description: (0,external_wp_i18n_namespaceObject.__)('Choose what displays in the panel.')
}, (0,external_wp_element_namespaceObject.createElement)(enable_plugin_document_setting_panel.Slot, null), (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostTaxonomies, {
taxonomyWrapper: (content, taxonomy) => (0,external_wp_element_namespaceObject.createElement)(enable_panel, {
label: (0,external_lodash_namespaceObject.get)(taxonomy, ['labels', 'menu_name']),
panelName: `taxonomy-panel-${taxonomy.slug}`
})
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostFeaturedImageCheck, null, (0,external_wp_element_namespaceObject.createElement)(enable_panel, {
label: (0,external_wp_i18n_namespaceObject.__)('Featured image'),
panelName: "featured-image"
})), (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostExcerptCheck, null, (0,external_wp_element_namespaceObject.createElement)(enable_panel, {
label: (0,external_wp_i18n_namespaceObject.__)('Excerpt'),
panelName: "post-excerpt"
})), (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostTypeSupportCheck, {
supportKeys: ['comments', 'trackbacks']
}, (0,external_wp_element_namespaceObject.createElement)(enable_panel, {
label: (0,external_wp_i18n_namespaceObject.__)('Discussion'),
panelName: "discussion-panel"
})), (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PageAttributesCheck, null, (0,external_wp_element_namespaceObject.createElement)(enable_panel, {
label: (0,external_wp_i18n_namespaceObject.__)('Page attributes'),
panelName: "page-attributes"
}))), (0,external_wp_element_namespaceObject.createElement)(meta_boxes_section, {
title: (0,external_wp_i18n_namespaceObject.__)('Additional'),
description: (0,external_wp_i18n_namespaceObject.__)('Add extra areas to the editor.')
}))
}], [isLargeViewport, showBlockBreadcrumbsOption]);
if (!isModalActive) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(PreferencesModal, {
closeModal: closeModal
}, (0,external_wp_element_namespaceObject.createElement)(PreferencesModalTabs, {
sections: sections
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/browser-url/index.js
/**
* WordPress dependencies
*/
/**
* Returns the Post's Edit URL.
*
* @param {number} postId Post ID.
*
* @return {string} Post edit URL.
*/
function getPostEditURL(postId) {
return (0,external_wp_url_namespaceObject.addQueryArgs)('post.php', {
post: postId,
action: 'edit'
});
}
/**
* Returns the Post's Trashed URL.
*
* @param {number} postId Post ID.
* @param {string} postType Post Type.
*
* @return {string} Post trashed URL.
*/
function getPostTrashedURL(postId, postType) {
return (0,external_wp_url_namespaceObject.addQueryArgs)('edit.php', {
trashed: 1,
post_type: postType,
ids: postId
});
}
class BrowserURL extends external_wp_element_namespaceObject.Component {
constructor() {
super(...arguments);
this.state = {
historyId: null
};
}
componentDidUpdate(prevProps) {
const {
postId,
postStatus,
postType,
isSavingPost
} = this.props;
const {
historyId
} = this.state; // Posts are still dirty while saving so wait for saving to finish
// to avoid the unsaved changes warning when trashing posts.
if (postStatus === 'trash' && !isSavingPost) {
this.setTrashURL(postId, postType);
return;
}
if ((postId !== prevProps.postId || postId !== historyId) && postStatus !== 'auto-draft' && postId) {
this.setBrowserURL(postId);
}
}
/**
* Navigates the browser to the post trashed URL to show a notice about the trashed post.
*
* @param {number} postId Post ID.
* @param {string} postType Post Type.
*/
setTrashURL(postId, postType) {
window.location.href = getPostTrashedURL(postId, postType);
}
/**
* Replaces the browser URL with a post editor link for the given post ID.
*
* Note it is important that, since this function may be called when the
* editor first loads, the result generated `getPostEditURL` matches that
* produced by the server. Otherwise, the URL will change unexpectedly.
*
* @param {number} postId Post ID for which to generate post editor URL.
*/
setBrowserURL(postId) {
window.history.replaceState({
id: postId
}, 'Post ' + postId, getPostEditURL(postId));
this.setState(() => ({
historyId: postId
}));
}
render() {
return null;
}
}
/* harmony default export */ var browser_url = ((0,external_wp_data_namespaceObject.withSelect)(select => {
const {
getCurrentPost,
isSavingPost
} = select(external_wp_editor_namespaceObject.store);
const post = getCurrentPost();
let {
id,
status,
type
} = post;
const isTemplate = ['wp_template', 'wp_template_part'].includes(type);
if (isTemplate) {
id = post.wp_id;
}
return {
postId: id,
postStatus: status,
postType: type,
isSavingPost: isSavingPost()
};
})(BrowserURL));
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/wordpress.js
/**
* WordPress dependencies
*/
const wordpress = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "-2 -2 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M20 10c0-5.51-4.49-10-10-10C4.48 0 0 4.49 0 10c0 5.52 4.48 10 10 10 5.51 0 10-4.48 10-10zM7.78 15.37L4.37 6.22c.55-.02 1.17-.08 1.17-.08.5-.06.44-1.13-.06-1.11 0 0-1.45.11-2.37.11-.18 0-.37 0-.58-.01C4.12 2.69 6.87 1.11 10 1.11c2.33 0 4.45.87 6.05 2.34-.68-.11-1.65.39-1.65 1.58 0 .74.45 1.36.9 2.1.35.61.55 1.36.55 2.46 0 1.49-1.4 5-1.4 5l-3.03-8.37c.54-.02.82-.17.82-.17.5-.05.44-1.25-.06-1.22 0 0-1.44.12-2.38.12-.87 0-2.33-.12-2.33-.12-.5-.03-.56 1.2-.06 1.22l.92.08 1.26 3.41zM17.41 10c.24-.64.74-1.87.43-4.25.7 1.29 1.05 2.71 1.05 4.25 0 3.29-1.73 6.24-4.4 7.78.97-2.59 1.94-5.2 2.92-7.78zM6.1 18.09C3.12 16.65 1.11 13.53 1.11 10c0-1.3.23-2.48.72-3.59C3.25 10.3 4.67 14.2 6.1 18.09zm4.03-6.63l2.58 6.98c-.86.29-1.76.45-2.71.45-.79 0-1.57-.11-2.29-.33.81-2.38 1.62-4.74 2.42-7.1z"
}));
/* harmony default export */ var library_wordpress = (wordpress);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/header/fullscreen-mode-close/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function FullscreenModeClose(_ref) {
let {
showTooltip,
icon,
href
} = _ref;
const {
isActive,
isRequestingSiteIcon,
postType,
siteIconUrl
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getCurrentPostType
} = select(external_wp_editor_namespaceObject.store);
const {
isFeatureActive
} = select(store_store);
const {
getEntityRecord,
getPostType,
isResolving
} = select(external_wp_coreData_namespaceObject.store);
const siteData = getEntityRecord('root', '__unstableBase', undefined) || {};
return {
isActive: isFeatureActive('fullscreenMode'),
isRequestingSiteIcon: isResolving('getEntityRecord', ['root', '__unstableBase', undefined]),
postType: getPostType(getCurrentPostType()),
siteIconUrl: siteData.site_icon_url
};
}, []);
const disableMotion = (0,external_wp_compose_namespaceObject.useReducedMotion)();
if (!isActive || !postType) {
return null;
}
let buttonIcon = (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Icon, {
size: "36px",
icon: library_wordpress
});
const effect = {
expand: {
scale: 1.25,
transition: {
type: 'tween',
duration: '0.3'
}
}
};
if (siteIconUrl) {
buttonIcon = (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableMotion.img, {
variants: !disableMotion && effect,
alt: (0,external_wp_i18n_namespaceObject.__)('Site Icon'),
className: "edit-post-fullscreen-mode-close_site-icon",
src: siteIconUrl
});
}
if (isRequestingSiteIcon) {
buttonIcon = null;
} // Override default icon if custom icon is provided via props.
if (icon) {
buttonIcon = (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Icon, {
size: "36px",
icon: icon
});
}
const classes = classnames_default()({
'edit-post-fullscreen-mode-close': true,
'has-icon': siteIconUrl
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableMotion.div, {
whileHover: "expand"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: classes,
href: href !== null && href !== void 0 ? href : (0,external_wp_url_namespaceObject.addQueryArgs)('edit.php', {
post_type: postType.slug
}),
label: (0,external_lodash_namespaceObject.get)(postType, ['labels', 'view_items'], (0,external_wp_i18n_namespaceObject.__)('Back')),
showTooltip: showTooltip
}, buttonIcon));
}
/* harmony default export */ var fullscreen_mode_close = (FullscreenModeClose);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/list-view.js
/**
* WordPress dependencies
*/
const listView = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M13.8 5.2H3v1.5h10.8V5.2zm-3.6 12v1.5H21v-1.5H10.2zm7.2-6H6.6v1.5h10.8v-1.5z"
}));
/* harmony default export */ var list_view = (listView);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/plus.js
/**
* WordPress dependencies
*/
const plus = (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: "M18 11.2h-5.2V6h-1.6v5.2H6v1.6h5.2V18h1.6v-5.2H18z"
}));
/* harmony default export */ var library_plus = (plus);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/header/header-toolbar/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const preventDefault = event => {
event.preventDefault();
};
function HeaderToolbar() {
const inserterButton = (0,external_wp_element_namespaceObject.useRef)();
const {
setIsInserterOpened,
setIsListViewOpened
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const {
isInserterEnabled,
isInserterOpened,
isTextModeEnabled,
showIconLabels,
isListViewOpen,
listViewShortcut
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
hasInserterItems,
getBlockRootClientId,
getBlockSelectionEnd
} = select(external_wp_blockEditor_namespaceObject.store);
const {
getEditorSettings
} = select(external_wp_editor_namespaceObject.store);
const {
getEditorMode,
isFeatureActive,
isListViewOpened
} = select(store_store);
const {
getShortcutRepresentation
} = select(external_wp_keyboardShortcuts_namespaceObject.store);
return {
// This setting (richEditingEnabled) should not live in the block editor's setting.
isInserterEnabled: getEditorMode() === 'visual' && getEditorSettings().richEditingEnabled && hasInserterItems(getBlockRootClientId(getBlockSelectionEnd())),
isInserterOpened: select(store_store).isInserterOpened(),
isTextModeEnabled: getEditorMode() === 'text',
showIconLabels: isFeatureActive('showIconLabels'),
isListViewOpen: isListViewOpened(),
listViewShortcut: getShortcutRepresentation('core/edit-post/toggle-list-view')
};
}, []);
const isLargeViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('medium');
const isWideViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('wide');
/* translators: accessibility text for the editor toolbar */
const toolbarAriaLabel = (0,external_wp_i18n_namespaceObject.__)('Document tools');
const toggleListView = (0,external_wp_element_namespaceObject.useCallback)(() => setIsListViewOpened(!isListViewOpen), [setIsListViewOpened, isListViewOpen]);
const overflowItems = (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarItem, {
as: external_wp_components_namespaceObject.Button,
className: "edit-post-header-toolbar__document-overview-toggle",
icon: list_view,
disabled: isTextModeEnabled,
isPressed: isListViewOpen
/* translators: button label text should, if possible, be under 16 characters. */
,
label: (0,external_wp_i18n_namespaceObject.__)('Document Overview'),
onClick: toggleListView,
shortcut: listViewShortcut,
showTooltip: !showIconLabels,
variant: showIconLabels ? 'tertiary' : undefined
}));
const toggleInserter = (0,external_wp_element_namespaceObject.useCallback)(() => {
if (isInserterOpened) {
// Focusing the inserter button should close the inserter popover.
// However, there are some cases it won't close when the focus is lost.
// See https://github.com/WordPress/gutenberg/issues/43090 for more details.
inserterButton.current.focus();
setIsInserterOpened(false);
} else {
setIsInserterOpened(true);
}
}, [isInserterOpened, setIsInserterOpened]);
/* translators: button label text should, if possible, be under 16 characters. */
const longLabel = (0,external_wp_i18n_namespaceObject._x)('Toggle block inserter', 'Generic label for block inserter button');
const shortLabel = !isInserterOpened ? (0,external_wp_i18n_namespaceObject.__)('Add') : (0,external_wp_i18n_namespaceObject.__)('Close');
return (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.NavigableToolbar, {
className: "edit-post-header-toolbar",
"aria-label": toolbarAriaLabel
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-header-toolbar__left"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarItem, {
ref: inserterButton,
as: external_wp_components_namespaceObject.Button,
className: "edit-post-header-toolbar__inserter-toggle",
variant: "primary",
isPressed: isInserterOpened,
onMouseDown: preventDefault,
onClick: toggleInserter,
disabled: !isInserterEnabled,
icon: library_plus,
label: showIconLabels ? shortLabel : longLabel,
showTooltip: !showIconLabels
}), (isWideViewport || !showIconLabels) && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, isLargeViewport && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarItem, {
as: external_wp_blockEditor_namespaceObject.ToolSelector,
showTooltip: !showIconLabels,
variant: showIconLabels ? 'tertiary' : undefined,
disabled: isTextModeEnabled
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarItem, {
as: external_wp_editor_namespaceObject.EditorHistoryUndo,
showTooltip: !showIconLabels,
variant: showIconLabels ? 'tertiary' : undefined
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarItem, {
as: external_wp_editor_namespaceObject.EditorHistoryRedo,
showTooltip: !showIconLabels,
variant: showIconLabels ? 'tertiary' : undefined
}), overflowItems)));
}
/* harmony default export */ var header_toolbar = (HeaderToolbar);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/header/mode-switcher/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Set of available mode options.
*
* @type {Array}
*/
const MODES = [{
value: 'visual',
label: (0,external_wp_i18n_namespaceObject.__)('Visual editor')
}, {
value: 'text',
label: (0,external_wp_i18n_namespaceObject.__)('Code editor')
}];
function ModeSwitcher() {
const {
shortcut,
isRichEditingEnabled,
isCodeEditingEnabled,
isEditingTemplate,
mode
} = (0,external_wp_data_namespaceObject.useSelect)(select => ({
shortcut: select(external_wp_keyboardShortcuts_namespaceObject.store).getShortcutRepresentation('core/edit-post/toggle-mode'),
isRichEditingEnabled: select(external_wp_editor_namespaceObject.store).getEditorSettings().richEditingEnabled,
isCodeEditingEnabled: select(external_wp_editor_namespaceObject.store).getEditorSettings().codeEditingEnabled,
isEditingTemplate: select(store_store).isEditingTemplate(),
mode: select(store_store).getEditorMode()
}), []);
const {
switchEditorMode
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
if (isEditingTemplate) {
return null;
}
if (!isRichEditingEnabled || !isCodeEditingEnabled) {
return null;
}
const choices = MODES.map(choice => {
if (choice.value !== mode) {
return { ...choice,
shortcut
};
}
return choice;
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, {
label: (0,external_wp_i18n_namespaceObject.__)('Editor')
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItemsChoice, {
choices: choices,
value: mode,
onSelect: switchEditorMode
}));
}
/* harmony default export */ var mode_switcher = (ModeSwitcher);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/header/preferences-menu-item/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PreferencesMenuItem() {
const {
openModal
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
onClick: () => {
openModal('edit-post/preferences');
}
}, (0,external_wp_i18n_namespaceObject.__)('Preferences'));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/header/writing-menu/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function WritingMenu() {
const registry = (0,external_wp_data_namespaceObject.useRegistry)();
const isDistractionFree = (0,external_wp_data_namespaceObject.useSelect)(select => select(external_wp_blockEditor_namespaceObject.store).getSettings().isDistractionFree, []);
const blocks = (0,external_wp_data_namespaceObject.useSelect)(select => select(external_wp_blockEditor_namespaceObject.store).getBlocks(), []);
const {
setIsInserterOpened,
setIsListViewOpened,
closeGeneralSidebar
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const {
set: setPreference
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_preferences_namespaceObject.store);
const {
selectBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_blockEditor_namespaceObject.store);
const toggleDistractionFree = () => {
registry.batch(() => {
setPreference('core/edit-post', 'fixedToolbar', false);
setIsInserterOpened(false);
setIsListViewOpened(false);
closeGeneralSidebar();
if (!isDistractionFree && !!blocks.length) {
selectBlock(blocks[0].clientId);
}
});
};
const isLargeViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('medium');
if (!isLargeViewport) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, {
label: (0,external_wp_i18n_namespaceObject._x)('View', 'noun')
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_preferences_namespaceObject.PreferenceToggleMenuItem, {
scope: "core/edit-post",
disabled: isDistractionFree,
name: "fixedToolbar",
label: (0,external_wp_i18n_namespaceObject.__)('Top toolbar'),
info: (0,external_wp_i18n_namespaceObject.__)('Access all block and document tools in a single place'),
messageActivated: (0,external_wp_i18n_namespaceObject.__)('Top toolbar activated'),
messageDeactivated: (0,external_wp_i18n_namespaceObject.__)('Top toolbar deactivated')
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_preferences_namespaceObject.PreferenceToggleMenuItem, {
scope: "core/edit-post",
name: "focusMode",
label: (0,external_wp_i18n_namespaceObject.__)('Spotlight mode'),
info: (0,external_wp_i18n_namespaceObject.__)('Focus on one block at a time'),
messageActivated: (0,external_wp_i18n_namespaceObject.__)('Spotlight mode activated'),
messageDeactivated: (0,external_wp_i18n_namespaceObject.__)('Spotlight mode deactivated')
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_preferences_namespaceObject.PreferenceToggleMenuItem, {
scope: "core/edit-post",
name: "fullscreenMode",
label: (0,external_wp_i18n_namespaceObject.__)('Fullscreen mode'),
info: (0,external_wp_i18n_namespaceObject.__)('Show and hide admin UI'),
messageActivated: (0,external_wp_i18n_namespaceObject.__)('Fullscreen mode activated'),
messageDeactivated: (0,external_wp_i18n_namespaceObject.__)('Fullscreen mode deactivated'),
shortcut: external_wp_keycodes_namespaceObject.displayShortcut.secondary('f')
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_preferences_namespaceObject.PreferenceToggleMenuItem, {
scope: "core/edit-post",
name: "distractionFree",
onToggle: toggleDistractionFree,
label: (0,external_wp_i18n_namespaceObject.__)('Distraction free'),
info: (0,external_wp_i18n_namespaceObject.__)('Write with calmness'),
messageActivated: (0,external_wp_i18n_namespaceObject.__)('Distraction free mode activated'),
messageDeactivated: (0,external_wp_i18n_namespaceObject.__)('Distraction free mode deactivated'),
shortcut: external_wp_keycodes_namespaceObject.displayShortcut.primaryShift('\\')
}));
}
/* harmony default export */ var writing_menu = (WritingMenu);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/header/more-menu/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const MoreMenu = _ref => {
let {
showIconLabels
} = _ref;
const isLargeViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('large');
return (0,external_wp_element_namespaceObject.createElement)(MoreMenuDropdown, {
toggleProps: {
showTooltip: !showIconLabels,
...(showIconLabels && {
variant: 'tertiary'
})
}
}, _ref2 => {
let {
onClose
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, showIconLabels && !isLargeViewport && (0,external_wp_element_namespaceObject.createElement)(pinned_items.Slot, {
className: showIconLabels && 'show-icon-labels',
scope: "core/edit-post"
}), (0,external_wp_element_namespaceObject.createElement)(writing_menu, null), (0,external_wp_element_namespaceObject.createElement)(mode_switcher, null), (0,external_wp_element_namespaceObject.createElement)(action_item.Slot, {
name: "core/edit-post/plugin-more-menu",
label: (0,external_wp_i18n_namespaceObject.__)('Plugins'),
as: external_wp_components_namespaceObject.MenuGroup,
fillProps: {
onClick: onClose
}
}), (0,external_wp_element_namespaceObject.createElement)(tools_more_menu_group.Slot, {
fillProps: {
onClose
}
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, null, (0,external_wp_element_namespaceObject.createElement)(PreferencesMenuItem, null)));
});
};
/* harmony default export */ var more_menu = (MoreMenu);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/header/post-publish-button-or-toggle.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PostPublishButtonOrToggle(_ref) {
let {
forceIsDirty,
forceIsSaving,
hasPublishAction,
isBeingScheduled,
isPending,
isPublished,
isPublishSidebarEnabled,
isPublishSidebarOpened,
isScheduled,
togglePublishSidebar,
setEntitiesSavedStatesCallback
} = _ref;
const IS_TOGGLE = 'toggle';
const IS_BUTTON = 'button';
const isSmallerThanMediumViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('medium', '<');
let component;
/**
* Conditions to show a BUTTON (publish directly) or a TOGGLE (open publish sidebar):
*
* 1) We want to show a BUTTON when the post status is at the _final stage_
* for a particular role (see https://wordpress.org/support/article/post-status/):
*
* - is published
* - is scheduled to be published
* - is pending and can't be published (but only for viewports >= medium).
* Originally, we considered showing a button for pending posts that couldn't be published
* (for example, for an author with the contributor role). Some languages can have
* long translations for "Submit for review", so given the lack of UI real estate available
* we decided to take into account the viewport in that case.
* See: https://github.com/WordPress/gutenberg/issues/10475
*
* 2) Then, in small viewports, we'll show a TOGGLE.
*
* 3) Finally, we'll use the publish sidebar status to decide:
*
* - if it is enabled, we show a TOGGLE
* - if it is disabled, we show a BUTTON
*/
if (isPublished || isScheduled && isBeingScheduled || isPending && !hasPublishAction && !isSmallerThanMediumViewport) {
component = IS_BUTTON;
} else if (isSmallerThanMediumViewport) {
component = IS_TOGGLE;
} else if (isPublishSidebarEnabled) {
component = IS_TOGGLE;
} else {
component = IS_BUTTON;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostPublishButton, {
forceIsDirty: forceIsDirty,
forceIsSaving: forceIsSaving,
isOpen: isPublishSidebarOpened,
isToggle: component === IS_TOGGLE,
onToggle: togglePublishSidebar,
setEntitiesSavedStatesCallback: setEntitiesSavedStatesCallback
});
}
/* harmony default export */ var post_publish_button_or_toggle = ((0,external_wp_compose_namespaceObject.compose)((0,external_wp_data_namespaceObject.withSelect)(select => ({
hasPublishAction: (0,external_lodash_namespaceObject.get)(select(external_wp_editor_namespaceObject.store).getCurrentPost(), ['_links', 'wp:action-publish'], false),
isBeingScheduled: select(external_wp_editor_namespaceObject.store).isEditedPostBeingScheduled(),
isPending: select(external_wp_editor_namespaceObject.store).isCurrentPostPending(),
isPublished: select(external_wp_editor_namespaceObject.store).isCurrentPostPublished(),
isPublishSidebarEnabled: select(external_wp_editor_namespaceObject.store).isPublishSidebarEnabled(),
isPublishSidebarOpened: select(store_store).isPublishSidebarOpened(),
isScheduled: select(external_wp_editor_namespaceObject.store).isCurrentPostScheduled()
})), (0,external_wp_data_namespaceObject.withDispatch)(dispatch => {
const {
togglePublishSidebar
} = dispatch(store_store);
return {
togglePublishSidebar
};
}))(PostPublishButtonOrToggle));
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/device-preview/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function DevicePreview() {
const {
hasActiveMetaboxes,
isPostSaveable,
isSaving,
isViewable,
deviceType
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getEditedPostAttribute
} = select(external_wp_editor_namespaceObject.store);
const {
getPostType
} = select(external_wp_coreData_namespaceObject.store);
const postType = getPostType(getEditedPostAttribute('type'));
return {
hasActiveMetaboxes: select(store_store).hasMetaBoxes(),
isSaving: select(store_store).isSavingMetaBoxes(),
isPostSaveable: select(external_wp_editor_namespaceObject.store).isEditedPostSaveable(),
isViewable: (0,external_lodash_namespaceObject.get)(postType, ['viewable'], false),
deviceType: select(store_store).__experimentalGetPreviewDeviceType()
};
}, []);
const {
__experimentalSetPreviewDeviceType: setPreviewDeviceType
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.__experimentalPreviewOptions, {
isEnabled: isPostSaveable,
className: "edit-post-post-preview-dropdown",
deviceType: deviceType,
setDeviceType: setPreviewDeviceType
/* translators: button label text should, if possible, be under 16 characters. */
,
viewLabel: (0,external_wp_i18n_namespaceObject.__)('Preview')
}, isViewable && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, null, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-header-preview__grouping-external"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostPreviewButton, {
className: 'edit-post-header-preview__button-external',
role: "menuitem",
forceIsAutosaveable: hasActiveMetaboxes,
forcePreviewLink: isSaving ? null : undefined,
textContent: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_i18n_namespaceObject.__)('Preview in new tab'), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Icon, {
icon: library_external
}))
}))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/header/main-dashboard-button/index.js
/**
* WordPress dependencies
*/
const slotName = '__experimentalMainDashboardButton';
const {
Fill: main_dashboard_button_Fill,
Slot: MainDashboardButtonSlot
} = (0,external_wp_components_namespaceObject.createSlotFill)(slotName);
const MainDashboardButton = main_dashboard_button_Fill;
const main_dashboard_button_Slot = _ref => {
let {
children
} = _ref;
const fills = (0,external_wp_components_namespaceObject.__experimentalUseSlotFills)(slotName);
const hasFills = Boolean(fills && fills.length);
if (!hasFills) {
return children;
}
return (0,external_wp_element_namespaceObject.createElement)(MainDashboardButtonSlot, {
bubblesVirtually: true
});
};
MainDashboardButton.Slot = main_dashboard_button_Slot;
/* harmony default export */ var main_dashboard_button = (MainDashboardButton);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/chevron-down.js
/**
* WordPress dependencies
*/
const chevronDown = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M17.5 11.6L12 16l-5.5-4.4.9-1.2L12 14l4.5-3.6 1 1.2z"
}));
/* harmony default export */ var chevron_down = (chevronDown);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/header/template-title/delete-template.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function DeleteTemplate() {
const {
clearSelectedBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_blockEditor_namespaceObject.store);
const {
setIsEditingTemplate
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const {
getEditorSettings
} = (0,external_wp_data_namespaceObject.useSelect)(external_wp_editor_namespaceObject.store);
const {
updateEditorSettings,
editPost
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_editor_namespaceObject.store);
const {
deleteEntityRecord
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_coreData_namespaceObject.store);
const {
template
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
isEditingTemplate,
getEditedPostTemplate
} = select(store_store);
const _isEditing = isEditingTemplate();
return {
template: _isEditing ? getEditedPostTemplate() : null
};
}, []);
const [showConfirmDialog, setShowConfirmDialog] = (0,external_wp_element_namespaceObject.useState)(false);
if (!template || !template.wp_id) {
return null;
}
let templateTitle = template.slug;
if (template !== null && template !== void 0 && template.title) {
templateTitle = template.title;
}
const isRevertable = template === null || template === void 0 ? void 0 : template.has_theme_file;
const onDelete = () => {
var _settings$availableTe;
clearSelectedBlock();
setIsEditingTemplate(false);
setShowConfirmDialog(false);
editPost({
template: ''
});
const settings = getEditorSettings();
const newAvailableTemplates = Object.fromEntries(Object.entries((_settings$availableTe = settings.availableTemplates) !== null && _settings$availableTe !== void 0 ? _settings$availableTe : {}).filter(_ref => {
let [id] = _ref;
return id !== template.slug;
}));
updateEditorSettings({ ...settings,
availableTemplates: newAvailableTemplates
});
deleteEntityRecord('postType', 'wp_template', template.id, {
throwOnError: true
});
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, {
className: "edit-post-template-top-area__second-menu-group"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
className: "edit-post-template-top-area__delete-template-button",
isDestructive: !isRevertable,
onClick: () => {
setShowConfirmDialog(true);
},
info: isRevertable ? (0,external_wp_i18n_namespaceObject.__)('Use the template as supplied by the theme.') : undefined
}, isRevertable ? (0,external_wp_i18n_namespaceObject.__)('Clear customizations') : (0,external_wp_i18n_namespaceObject.__)('Delete template')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalConfirmDialog, {
isOpen: showConfirmDialog,
onConfirm: onDelete,
onCancel: () => {
setShowConfirmDialog(false);
}
}, (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: template name */
(0,external_wp_i18n_namespaceObject.__)('Are you sure you want to delete the %s template? It may be used by other pages or posts.'), templateTitle))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/header/template-title/edit-template-title.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function EditTemplateTitle() {
const [forceEmpty, setForceEmpty] = (0,external_wp_element_namespaceObject.useState)(false);
const {
template
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getEditedPostTemplate
} = select(store_store);
return {
template: getEditedPostTemplate()
};
}, []);
const {
editEntityRecord
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_coreData_namespaceObject.store);
const {
getEditorSettings
} = (0,external_wp_data_namespaceObject.useSelect)(external_wp_editor_namespaceObject.store);
const {
updateEditorSettings
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_editor_namespaceObject.store); // Only user-created and non-default templates can change the name.
if (!template.is_custom || template.has_theme_file) {
return null;
}
let templateTitle = (0,external_wp_i18n_namespaceObject.__)('Default');
if (template !== null && template !== void 0 && template.title) {
templateTitle = template.title;
} else if (!!template) {
templateTitle = template.slug;
}
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-site-template-details__group"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.TextControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Title'),
value: forceEmpty ? '' : templateTitle,
help: (0,external_wp_i18n_namespaceObject.__)('Give the template a title that indicates its purpose, e.g. "Full Width".'),
onChange: newTitle => {
// Allow having the field temporarily empty while typing.
if (!newTitle && !forceEmpty) {
setForceEmpty(true);
return;
}
setForceEmpty(false);
const settings = getEditorSettings();
const newAvailableTemplates = (0,external_lodash_namespaceObject.mapValues)(settings.availableTemplates, (existingTitle, id) => {
if (id !== template.slug) {
return existingTitle;
}
return newTitle;
});
updateEditorSettings({ ...settings,
availableTemplates: newAvailableTemplates
});
editEntityRecord('postType', 'wp_template', template.id, {
title: newTitle
});
},
onBlur: () => setForceEmpty(false)
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/header/template-title/template-description.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function TemplateDescription() {
const {
description,
title
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getEditedPostTemplate
} = select(store_store);
return {
title: getEditedPostTemplate().title,
description: getEditedPostTemplate().description
};
}, []);
if (!description) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-site-template-details__group"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalHeading, {
level: 4,
weight: 600
}, title), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalText, {
className: "edit-post-template-details__description",
size: "body",
as: "p",
style: {
marginTop: '12px'
}
}, description));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/header/template-title/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function TemplateTitle() {
const {
template,
isEditing,
title
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
isEditingTemplate,
getEditedPostTemplate
} = select(store_store);
const {
getEditedPostAttribute
} = select(external_wp_editor_namespaceObject.store);
const _isEditing = isEditingTemplate();
return {
template: _isEditing ? getEditedPostTemplate() : null,
isEditing: _isEditing,
title: getEditedPostAttribute('title') ? getEditedPostAttribute('title') : (0,external_wp_i18n_namespaceObject.__)('Untitled')
};
}, []);
const {
clearSelectedBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_blockEditor_namespaceObject.store);
const {
setIsEditingTemplate
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
if (!isEditing || !template) {
return null;
}
let templateTitle = (0,external_wp_i18n_namespaceObject.__)('Default');
if (template !== null && template !== void 0 && template.title) {
templateTitle = template.title;
} else if (!!template) {
templateTitle = template.slug;
}
const hasOptions = !!(template.custom || template.wp_id || template.description);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-template-top-area"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "edit-post-template-post-title",
isLink: true,
showTooltip: true,
label: (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: Title of the referring post, e.g: "Hello World!" */
(0,external_wp_i18n_namespaceObject.__)('Edit %s'), title),
onClick: () => {
clearSelectedBlock();
setIsEditingTemplate(false);
}
}, title), hasOptions ? (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Dropdown, {
popoverProps: {
placement: 'bottom'
},
contentClassName: "edit-post-template-top-area__popover",
renderToggle: _ref => {
let {
onToggle
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "edit-post-template-title",
isLink: true,
icon: chevron_down,
showTooltip: true,
onClick: onToggle,
label: (0,external_wp_i18n_namespaceObject.__)('Template Options')
}, templateTitle);
},
renderContent: () => (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(EditTemplateTitle, null), (0,external_wp_element_namespaceObject.createElement)(TemplateDescription, null), (0,external_wp_element_namespaceObject.createElement)(DeleteTemplate, null))
}) : (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalText, {
className: "edit-post-template-title",
size: "body",
style: {
lineHeight: '24px'
}
}, templateTitle));
}
/* harmony default export */ var template_title = (TemplateTitle);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/header/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function Header(_ref) {
let {
setEntitiesSavedStatesCallback
} = _ref;
const isLargeViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('large');
const {
hasActiveMetaboxes,
isPublishSidebarOpened,
isSaving,
showIconLabels,
isDistractionFreeMode
} = (0,external_wp_data_namespaceObject.useSelect)(select => ({
hasActiveMetaboxes: select(store_store).hasMetaBoxes(),
isPublishSidebarOpened: select(store_store).isPublishSidebarOpened(),
isSaving: select(store_store).isSavingMetaBoxes(),
showIconLabels: select(store_store).isFeatureActive('showIconLabels'),
isDistractionFreeMode: select(store_store).isFeatureActive('distractionFree')
}), []);
const isDistractionFree = isDistractionFreeMode && isLargeViewport;
const classes = classnames_default()('edit-post-header');
const slideY = {
hidden: isDistractionFree ? {
y: '-50'
} : {
y: 0
},
hover: {
y: 0,
transition: {
type: 'tween',
delay: 0.2
}
}
};
const slideX = {
hidden: isDistractionFree ? {
x: '-100%'
} : {
x: 0
},
hover: {
x: 0,
transition: {
type: 'tween',
delay: 0.2
}
}
};
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classes
}, (0,external_wp_element_namespaceObject.createElement)(main_dashboard_button.Slot, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableMotion.div, {
variants: slideX,
transition: {
type: 'tween',
delay: 0.8
}
}, (0,external_wp_element_namespaceObject.createElement)(fullscreen_mode_close, {
showTooltip: true
}))), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableMotion.div, {
variants: slideY,
transition: {
type: 'tween',
delay: 0.8
},
className: "edit-post-header__toolbar"
}, (0,external_wp_element_namespaceObject.createElement)(header_toolbar, null), (0,external_wp_element_namespaceObject.createElement)(template_title, null)), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableMotion.div, {
variants: slideY,
transition: {
type: 'tween',
delay: 0.8
},
className: "edit-post-header__settings"
}, !isPublishSidebarOpened && // This button isn't completely hidden by the publish sidebar.
// We can't hide the whole toolbar when the publish sidebar is open because
// we want to prevent mounting/unmounting the PostPublishButtonOrToggle DOM node.
// We track that DOM node to return focus to the PostPublishButtonOrToggle
// when the publish sidebar has been closed.
(0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostSavedState, {
forceIsDirty: hasActiveMetaboxes,
forceIsSaving: isSaving,
showIconLabels: showIconLabels
}), (0,external_wp_element_namespaceObject.createElement)(DevicePreview, null), (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostPreviewButton, {
forceIsAutosaveable: hasActiveMetaboxes,
forcePreviewLink: isSaving ? null : undefined
}), (0,external_wp_element_namespaceObject.createElement)(post_publish_button_or_toggle, {
forceIsDirty: hasActiveMetaboxes,
forceIsSaving: isSaving,
setEntitiesSavedStatesCallback: setEntitiesSavedStatesCallback
}), (isLargeViewport || !showIconLabels) && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(pinned_items.Slot, {
scope: "core/edit-post"
}), (0,external_wp_element_namespaceObject.createElement)(more_menu, {
showIconLabels: showIconLabels
})), showIconLabels && !isLargeViewport && (0,external_wp_element_namespaceObject.createElement)(more_menu, {
showIconLabels: showIconLabels
})));
}
/* harmony default export */ var header = (Header);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/close.js
/**
* WordPress dependencies
*/
const close_close = (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: "M13 11.8l6.1-6.3-1-1-6.1 6.2-6.1-6.2-1 1 6.1 6.3-6.5 6.7 1 1 6.5-6.6 6.5 6.6 1-1z"
}));
/* harmony default export */ var library_close = (close_close);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/secondary-sidebar/inserter-sidebar.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function InserterSidebar() {
const {
insertionPoint,
showMostUsedBlocks
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
isFeatureActive,
__experimentalGetInsertionPoint
} = select(store_store);
return {
insertionPoint: __experimentalGetInsertionPoint(),
showMostUsedBlocks: isFeatureActive('mostUsedBlocks')
};
}, []);
const {
setIsInserterOpened
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const isMobileViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('medium', '<');
const TagName = !isMobileViewport ? external_wp_components_namespaceObject.VisuallyHidden : 'div';
const [inserterDialogRef, inserterDialogProps] = (0,external_wp_compose_namespaceObject.__experimentalUseDialog)({
onClose: () => setIsInserterOpened(false),
focusOnMount: null
});
const libraryRef = (0,external_wp_element_namespaceObject.useRef)();
(0,external_wp_element_namespaceObject.useEffect)(() => {
libraryRef.current.focusSearch();
}, []);
return (0,external_wp_element_namespaceObject.createElement)("div", _extends({
ref: inserterDialogRef
}, inserterDialogProps, {
className: "edit-post-editor__inserter-panel"
}), (0,external_wp_element_namespaceObject.createElement)(TagName, {
className: "edit-post-editor__inserter-panel-header"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
icon: library_close,
label: (0,external_wp_i18n_namespaceObject.__)('Close block inserter'),
onClick: () => setIsInserterOpened(false)
})), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-editor__inserter-panel-content"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.__experimentalLibrary, {
showMostUsedBlocks: showMostUsedBlocks,
showInserterHelpPanel: true,
shouldFocusBlock: isMobileViewport,
rootClientId: insertionPoint.rootClientId,
__experimentalInsertionIndex: insertionPoint.insertionIndex,
__experimentalFilterValue: insertionPoint.filterValue,
ref: libraryRef
})));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/secondary-sidebar/list-view-outline.js
/**
* WordPress dependencies
*/
function EmptyOutlineIllustration() {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SVG, {
width: "138",
height: "148",
viewBox: "0 0 138 148",
fill: "none",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Rect, {
width: "138",
height: "148",
rx: "4",
fill: "#F0F6FC"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Line, {
x1: "44",
y1: "28",
x2: "24",
y2: "28",
stroke: "#DDDDDD"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Rect, {
x: "48",
y: "16",
width: "27",
height: "23",
rx: "4",
fill: "#DDDDDD"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Path, {
d: "M54.7585 32V23.2727H56.6037V26.8736H60.3494V23.2727H62.1903V32H60.3494V28.3949H56.6037V32H54.7585ZM67.4574 23.2727V32H65.6122V25.0241H65.5611L63.5625 26.277V24.6406L65.723 23.2727H67.4574Z",
fill: "black"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Line, {
x1: "55",
y1: "59",
x2: "24",
y2: "59",
stroke: "#DDDDDD"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Rect, {
x: "59",
y: "47",
width: "29",
height: "23",
rx: "4",
fill: "#DDDDDD"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Path, {
d: "M65.7585 63V54.2727H67.6037V57.8736H71.3494V54.2727H73.1903V63H71.3494V59.3949H67.6037V63H65.7585ZM74.6605 63V61.6705L77.767 58.794C78.0313 58.5384 78.2528 58.3082 78.4318 58.1037C78.6136 57.8991 78.7514 57.6989 78.8452 57.5028C78.9389 57.304 78.9858 57.0895 78.9858 56.8594C78.9858 56.6037 78.9276 56.3835 78.8111 56.1989C78.6946 56.0114 78.5355 55.8679 78.3338 55.7685C78.1321 55.6662 77.9034 55.6151 77.6477 55.6151C77.3807 55.6151 77.1477 55.669 76.9489 55.777C76.75 55.8849 76.5966 56.0398 76.4886 56.2415C76.3807 56.4432 76.3267 56.6832 76.3267 56.9616H74.5753C74.5753 56.3906 74.7045 55.8949 74.9631 55.4744C75.2216 55.054 75.5838 54.7287 76.0497 54.4986C76.5156 54.2685 77.0526 54.1534 77.6605 54.1534C78.2855 54.1534 78.8295 54.2642 79.2926 54.4858C79.7585 54.7045 80.1207 55.0085 80.3793 55.3977C80.6378 55.7869 80.767 56.233 80.767 56.7358C80.767 57.0653 80.7017 57.3906 80.571 57.7116C80.4432 58.0327 80.2145 58.3892 79.8849 58.7812C79.5554 59.1705 79.0909 59.6378 78.4915 60.1832L77.2173 61.4318V61.4915H80.8821V63H74.6605Z",
fill: "black"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Line, {
x1: "80",
y1: "90",
x2: "24",
y2: "90",
stroke: "#DDDDDD"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Rect, {
x: "84",
y: "78",
width: "30",
height: "23",
rx: "4",
fill: "#F0B849"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Path, {
d: "M90.7585 94V85.2727H92.6037V88.8736H96.3494V85.2727H98.1903V94H96.3494V90.3949H92.6037V94H90.7585ZM99.5284 92.4659V91.0128L103.172 85.2727H104.425V87.2841H103.683L101.386 90.919V90.9872H106.564V92.4659H99.5284ZM103.717 94V92.0227L103.751 91.3793V85.2727H105.482V94H103.717Z",
fill: "black"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Line, {
x1: "66",
y1: "121",
x2: "24",
y2: "121",
stroke: "#DDDDDD"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Rect, {
x: "70",
y: "109",
width: "29",
height: "23",
rx: "4",
fill: "#DDDDDD"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Path, {
d: "M76.7585 125V116.273H78.6037V119.874H82.3494V116.273H84.1903V125H82.3494V121.395H78.6037V125H76.7585ZM88.8864 125.119C88.25 125.119 87.6832 125.01 87.1861 124.791C86.6918 124.57 86.3011 124.266 86.0142 123.879C85.7301 123.49 85.5838 123.041 85.5753 122.533H87.4332C87.4446 122.746 87.5142 122.933 87.642 123.095C87.7727 123.254 87.946 123.378 88.1619 123.466C88.3778 123.554 88.6207 123.598 88.8906 123.598C89.1719 123.598 89.4205 123.548 89.6364 123.449C89.8523 123.349 90.0213 123.212 90.1435 123.036C90.2656 122.859 90.3267 122.656 90.3267 122.426C90.3267 122.193 90.2614 121.987 90.1307 121.808C90.0028 121.626 89.8182 121.484 89.5767 121.382C89.3381 121.28 89.054 121.229 88.7244 121.229H87.9105V119.874H88.7244C89.0028 119.874 89.2486 119.825 89.4616 119.729C89.6776 119.632 89.8452 119.499 89.9645 119.328C90.0838 119.155 90.1435 118.953 90.1435 118.723C90.1435 118.504 90.0909 118.312 89.9858 118.148C89.8835 117.98 89.7386 117.849 89.5511 117.756C89.3665 117.662 89.1506 117.615 88.9034 117.615C88.6534 117.615 88.4247 117.661 88.2173 117.751C88.0099 117.839 87.8438 117.966 87.7188 118.131C87.5938 118.295 87.527 118.489 87.5185 118.71H85.75C85.7585 118.207 85.902 117.764 86.1804 117.381C86.4588 116.997 86.8338 116.697 87.3054 116.482C87.7798 116.263 88.3153 116.153 88.9119 116.153C89.5142 116.153 90.0412 116.263 90.4929 116.482C90.9446 116.7 91.2955 116.996 91.5455 117.368C91.7983 117.737 91.9233 118.152 91.9205 118.612C91.9233 119.101 91.7713 119.509 91.4645 119.835C91.1605 120.162 90.7642 120.369 90.2756 120.457V120.526C90.9176 120.608 91.4063 120.831 91.7415 121.195C92.0795 121.555 92.2472 122.007 92.2443 122.55C92.2472 123.047 92.1037 123.489 91.8139 123.875C91.527 124.261 91.1307 124.565 90.625 124.787C90.1193 125.009 89.5398 125.119 88.8864 125.119Z",
fill: "black"
}));
}
function ListViewOutline() {
const {
headingCount
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getGlobalBlockCount
} = select(external_wp_blockEditor_namespaceObject.store);
return {
headingCount: getGlobalBlockCount('core/heading')
};
}, []);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-editor__list-view-overview"
}, (0,external_wp_element_namespaceObject.createElement)("div", null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalText, null, (0,external_wp_i18n_namespaceObject.__)('Characters:')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalText, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.CharacterCount, null))), (0,external_wp_element_namespaceObject.createElement)("div", null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalText, null, (0,external_wp_i18n_namespaceObject.__)('Words:')), (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.WordCount, null)), (0,external_wp_element_namespaceObject.createElement)("div", null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalText, null, (0,external_wp_i18n_namespaceObject.__)('Time to read:')), (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.TimeToRead, null))), headingCount > 0 ? (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.DocumentOutline, null) : (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-editor__list-view-empty-headings"
}, (0,external_wp_element_namespaceObject.createElement)(EmptyOutlineIllustration, null), (0,external_wp_element_namespaceObject.createElement)("p", null, (0,external_wp_i18n_namespaceObject.__)('Navigate the structure of your document and address issues like empty or incorrect heading levels.'))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/secondary-sidebar/list-view-sidebar.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ListViewSidebar() {
const {
setIsListViewOpened
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const focusOnMountRef = (0,external_wp_compose_namespaceObject.useFocusOnMount)('firstElement');
const headerFocusReturnRef = (0,external_wp_compose_namespaceObject.useFocusReturn)();
const contentFocusReturnRef = (0,external_wp_compose_namespaceObject.useFocusReturn)();
function closeOnEscape(event) {
if (event.keyCode === external_wp_keycodes_namespaceObject.ESCAPE && !event.defaultPrevented) {
event.preventDefault();
setIsListViewOpened(false);
}
}
const [tab, setTab] = (0,external_wp_element_namespaceObject.useState)('list-view');
return (// eslint-disable-next-line jsx-a11y/no-static-element-interactions
(0,external_wp_element_namespaceObject.createElement)("div", {
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Document Overview'),
className: "edit-post-editor__document-overview-panel",
onKeyDown: closeOnEscape
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-editor__document-overview-panel-header components-panel__header edit-post-sidebar__panel-tabs",
ref: headerFocusReturnRef
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
icon: close_small,
label: (0,external_wp_i18n_namespaceObject.__)('Close Document Overview Sidebar'),
onClick: () => setIsListViewOpened(false)
}), (0,external_wp_element_namespaceObject.createElement)("ul", null, (0,external_wp_element_namespaceObject.createElement)("li", null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
onClick: () => {
setTab('list-view');
},
className: classnames_default()('edit-post-sidebar__panel-tab', {
'is-active': tab === 'list-view'
}),
"aria-current": tab === 'list-view'
}, (0,external_wp_i18n_namespaceObject.__)('List View'))), (0,external_wp_element_namespaceObject.createElement)("li", null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
onClick: () => {
setTab('outline');
},
className: classnames_default()('edit-post-sidebar__panel-tab', {
'is-active': tab === 'outline'
}),
"aria-current": tab === 'outline'
}, (0,external_wp_i18n_namespaceObject.__)('Outline'))))), (0,external_wp_element_namespaceObject.createElement)("div", {
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([contentFocusReturnRef, focusOnMountRef]),
className: "edit-post-editor__list-view-container"
}, tab === 'list-view' && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-editor__list-view-panel-content"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.__experimentalListView, null)), tab === 'outline' && (0,external_wp_element_namespaceObject.createElement)(ListViewOutline, null)))
);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/drawer-left.js
/**
* WordPress dependencies
*/
const drawerLeft = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
width: "24",
height: "24",
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M18 4H6c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zM8.5 18.5H6c-.3 0-.5-.2-.5-.5V6c0-.3.2-.5.5-.5h2.5v13zm10-.5c0 .3-.2.5-.5.5h-8v-13h8c.3 0 .5.2.5.5v12z"
}));
/* harmony default export */ var drawer_left = (drawerLeft);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/drawer-right.js
/**
* WordPress dependencies
*/
const drawerRight = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
width: "24",
height: "24",
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M18 4H6c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-4 14.5H6c-.3 0-.5-.2-.5-.5V6c0-.3.2-.5.5-.5h8v13zm4.5-.5c0 .3-.2.5-.5.5h-2.5v-13H18c.3 0 .5.2.5.5v12z"
}));
/* harmony default export */ var drawer_right = (drawerRight);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/settings-header/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const SettingsHeader = _ref => {
let {
sidebarName
} = _ref;
const {
openGeneralSidebar
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const openDocumentSettings = () => openGeneralSidebar('edit-post/document');
const openBlockSettings = () => openGeneralSidebar('edit-post/block');
const {
documentLabel,
isTemplateMode
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const postTypeLabel = select(external_wp_editor_namespaceObject.store).getPostTypeLabel();
return {
// translators: Default label for the Document sidebar tab, not selected.
documentLabel: postTypeLabel || (0,external_wp_i18n_namespaceObject._x)('Document', 'noun'),
isTemplateMode: select(store_store).isEditingTemplate()
};
}, []);
const [documentAriaLabel, documentActiveClass] = sidebarName === 'edit-post/document' ? // translators: ARIA label for the Document sidebar tab, selected. %s: Document label.
[(0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('%s (selected)'), documentLabel), 'is-active'] : [documentLabel, ''];
const [blockAriaLabel, blockActiveClass] = sidebarName === 'edit-post/block' ? // translators: ARIA label for the Block Settings Sidebar tab, selected.
[(0,external_wp_i18n_namespaceObject.__)('Block (selected)'), 'is-active'] : // translators: ARIA label for the Block Settings Sidebar tab, not selected.
[(0,external_wp_i18n_namespaceObject.__)('Block'), ''];
const [templateAriaLabel, templateActiveClass] = sidebarName === 'edit-post/document' ? [(0,external_wp_i18n_namespaceObject.__)('Template (selected)'), 'is-active'] : [(0,external_wp_i18n_namespaceObject.__)('Template'), ''];
/* Use a list so screen readers will announce how many tabs there are. */
return (0,external_wp_element_namespaceObject.createElement)("ul", null, !isTemplateMode && (0,external_wp_element_namespaceObject.createElement)("li", null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
onClick: openDocumentSettings,
className: `edit-post-sidebar__panel-tab ${documentActiveClass}`,
"aria-label": documentAriaLabel,
"data-label": documentLabel
}, documentLabel)), isTemplateMode && (0,external_wp_element_namespaceObject.createElement)("li", null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
onClick: openDocumentSettings,
className: `edit-post-sidebar__panel-tab ${templateActiveClass}`,
"aria-label": templateAriaLabel,
"data-label": (0,external_wp_i18n_namespaceObject.__)('Template')
}, (0,external_wp_i18n_namespaceObject.__)('Template'))), (0,external_wp_element_namespaceObject.createElement)("li", null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
onClick: openBlockSettings,
className: `edit-post-sidebar__panel-tab ${blockActiveClass}`,
"aria-label": blockAriaLabel // translators: Data label for the Block Settings Sidebar tab.
,
"data-label": (0,external_wp_i18n_namespaceObject.__)('Block')
}, // translators: Text label for the Block Settings Sidebar tab.
(0,external_wp_i18n_namespaceObject.__)('Block'))));
};
/* harmony default export */ var settings_header = (SettingsHeader);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/post-visibility/index.js
/**
* WordPress dependencies
*/
function PostVisibility() {
// Use internal state instead of a ref to make sure that the component
// re-renders when the popover's anchor updates.
const [popoverAnchor, setPopoverAnchor] = (0,external_wp_element_namespaceObject.useState)(null); // Memoize popoverProps to avoid returning a new object every time.
const popoverProps = (0,external_wp_element_namespaceObject.useMemo)(() => ({
// Anchor the popover to the middle of the entire row so that it doesn't
// move around when the label changes.
anchor: popoverAnchor,
placement: 'bottom-end'
}), [popoverAnchor]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostVisibilityCheck, {
render: _ref => {
let {
canEdit
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelRow, {
ref: setPopoverAnchor,
className: "edit-post-post-visibility"
}, (0,external_wp_element_namespaceObject.createElement)("span", null, (0,external_wp_i18n_namespaceObject.__)('Visibility')), !canEdit && (0,external_wp_element_namespaceObject.createElement)("span", null, (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostVisibilityLabel, null)), canEdit && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Dropdown, {
contentClassName: "edit-post-post-visibility__dialog",
popoverProps: popoverProps,
focusOnMount: true,
renderToggle: _ref2 => {
let {
isOpen,
onToggle
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(PostVisibilityToggle, {
isOpen: isOpen,
onClick: onToggle
});
},
renderContent: _ref3 => {
let {
onClose
} = _ref3;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostVisibility, {
onClose: onClose
});
}
}));
}
});
}
function PostVisibilityToggle(_ref4) {
let {
isOpen,
onClick
} = _ref4;
const label = (0,external_wp_editor_namespaceObject.usePostVisibilityLabel)();
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "edit-post-post-visibility__toggle",
variant: "tertiary",
"aria-expanded": isOpen // translators: %s: Current post visibility.
,
"aria-label": (0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('Select visibility: %s'), label),
onClick: onClick
}, label);
}
/* harmony default export */ var post_visibility = (PostVisibility);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/post-trash/index.js
/**
* WordPress dependencies
*/
function PostTrash() {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostTrashCheck, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelRow, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostTrash, null)));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/post-schedule/index.js
/**
* WordPress dependencies
*/
function PostSchedule() {
// Use internal state instead of a ref to make sure that the component
// re-renders when the popover's anchor updates.
const [popoverAnchor, setPopoverAnchor] = (0,external_wp_element_namespaceObject.useState)(null); // Memoize popoverProps to avoid returning a new object every time.
const popoverProps = (0,external_wp_element_namespaceObject.useMemo)(() => ({
anchor: popoverAnchor,
placement: 'bottom-end'
}), [popoverAnchor]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostScheduleCheck, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelRow, {
className: "edit-post-post-schedule",
ref: setPopoverAnchor
}, (0,external_wp_element_namespaceObject.createElement)("span", null, (0,external_wp_i18n_namespaceObject.__)('Publish')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Dropdown, {
popoverProps: popoverProps,
contentClassName: "edit-post-post-schedule__dialog",
focusOnMount: true,
renderToggle: _ref => {
let {
isOpen,
onToggle
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(PostScheduleToggle, {
isOpen: isOpen,
onClick: onToggle
});
},
renderContent: _ref2 => {
let {
onClose
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostSchedule, {
onClose: onClose
});
}
})));
}
function PostScheduleToggle(_ref3) {
let {
isOpen,
onClick
} = _ref3;
const label = (0,external_wp_editor_namespaceObject.usePostScheduleLabel)();
const fullLabel = (0,external_wp_editor_namespaceObject.usePostScheduleLabel)({
full: true
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "edit-post-post-schedule__toggle",
variant: "tertiary",
label: fullLabel,
showTooltip: true,
"aria-expanded": isOpen // translators: %s: Current post date.
,
"aria-label": (0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('Change date: %s'), label),
onClick: onClick
}, label);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/post-sticky/index.js
/**
* WordPress dependencies
*/
function PostSticky() {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostStickyCheck, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelRow, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostSticky, null)));
}
/* harmony default export */ var post_sticky = (PostSticky);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/post-author/index.js
/**
* WordPress dependencies
*/
function PostAuthor() {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostAuthorCheck, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelRow, {
className: "edit-post-post-author"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostAuthor, null)));
}
/* harmony default export */ var post_author = (PostAuthor);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/post-slug/index.js
/**
* WordPress dependencies
*/
function PostSlug() {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostSlugCheck, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelRow, {
className: "edit-post-post-slug"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostSlug, null)));
}
/* harmony default export */ var post_slug = (PostSlug);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/post-format/index.js
/**
* WordPress dependencies
*/
function PostFormat() {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostFormatCheck, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelRow, {
className: "edit-post-post-format"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostFormat, null)));
}
/* harmony default export */ var post_format = (PostFormat);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/post-pending-status/index.js
/**
* WordPress dependencies
*/
function PostPendingStatus() {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostPendingStatusCheck, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelRow, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostPendingStatus, null)));
}
/* harmony default export */ var post_pending_status = (PostPendingStatus);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/plugin-post-status-info/index.js
/**
* Defines as extensibility slot for the Summary panel.
*/
/**
* WordPress dependencies
*/
const {
Fill: plugin_post_status_info_Fill,
Slot: plugin_post_status_info_Slot
} = (0,external_wp_components_namespaceObject.createSlotFill)('PluginPostStatusInfo');
/**
* Renders a row in the Summary panel of the Document sidebar.
* It should be noted that this is named and implemented around the function it serves
* and not its location, which may change in future iterations.
*
* @param {Object} props Component properties.
* @param {string} [props.className] An optional class name added to the row.
* @param {WPElement} props.children Children to be rendered.
*
* @example
* ```js
* // Using ES5 syntax
* var __ = wp.i18n.__;
* var PluginPostStatusInfo = wp.editPost.PluginPostStatusInfo;
*
* function MyPluginPostStatusInfo() {
* return wp.element.createElement(
* PluginPostStatusInfo,
* {
* className: 'my-plugin-post-status-info',
* },
* __( 'My post status info' )
* )
* }
* ```
*
* @example
* ```jsx
* // Using ESNext syntax
* import { __ } from '@wordpress/i18n';
* import { PluginPostStatusInfo } from '@wordpress/edit-post';
*
* const MyPluginPostStatusInfo = () => (
* <PluginPostStatusInfo
* className="my-plugin-post-status-info"
* >
* { __( 'My post status info' ) }
* </PluginPostStatusInfo>
* );
* ```
*
* @return {WPComponent} The component to be rendered.
*/
const PluginPostStatusInfo = _ref => {
let {
children,
className
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(plugin_post_status_info_Fill, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelRow, {
className: className
}, children));
};
PluginPostStatusInfo.Slot = plugin_post_status_info_Slot;
/* harmony default export */ var plugin_post_status_info = (PluginPostStatusInfo);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/add-template.js
/**
* WordPress dependencies
*/
const addTemplate = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M18.5 5.5V8H20V5.5H22.5V4H20V1.5H18.5V4H16V5.5H18.5ZM13.9624 4H6C4.89543 4 4 4.89543 4 6V18C4 19.1046 4.89543 20 6 20H18C19.1046 20 20 19.1046 20 18V10.0391H18.5V18C18.5 18.2761 18.2761 18.5 18 18.5H10L10 10.4917L16.4589 10.5139L16.4641 9.01389L5.5 8.97618V6C5.5 5.72386 5.72386 5.5 6 5.5H13.9624V4ZM5.5 10.4762V18C5.5 18.2761 5.72386 18.5 6 18.5H8.5L8.5 10.4865L5.5 10.4762Z"
}));
/* harmony default export */ var add_template = (addTemplate);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/post-template/create-modal.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const DEFAULT_TITLE = (0,external_wp_i18n_namespaceObject.__)('Custom Template');
function PostTemplateCreateModal(_ref) {
let {
onClose
} = _ref;
const defaultBlockTemplate = (0,external_wp_data_namespaceObject.useSelect)(select => select(external_wp_editor_namespaceObject.store).getEditorSettings().defaultBlockTemplate, []);
const {
__unstableCreateTemplate,
__unstableSwitchToTemplateMode
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const [title, setTitle] = (0,external_wp_element_namespaceObject.useState)('');
const [isBusy, setIsBusy] = (0,external_wp_element_namespaceObject.useState)(false);
const cancel = () => {
setTitle('');
onClose();
};
const submit = async event => {
event.preventDefault();
if (isBusy) {
return;
}
setIsBusy(true);
const newTemplateContent = defaultBlockTemplate !== null && defaultBlockTemplate !== void 0 ? defaultBlockTemplate : (0,external_wp_blocks_namespaceObject.serialize)([(0,external_wp_blocks_namespaceObject.createBlock)('core/group', {
tagName: 'header',
layout: {
inherit: true
}
}, [(0,external_wp_blocks_namespaceObject.createBlock)('core/site-title'), (0,external_wp_blocks_namespaceObject.createBlock)('core/site-tagline')]), (0,external_wp_blocks_namespaceObject.createBlock)('core/separator'), (0,external_wp_blocks_namespaceObject.createBlock)('core/group', {
tagName: 'main'
}, [(0,external_wp_blocks_namespaceObject.createBlock)('core/group', {
layout: {
inherit: true
}
}, [(0,external_wp_blocks_namespaceObject.createBlock)('core/post-title')]), (0,external_wp_blocks_namespaceObject.createBlock)('core/post-content', {
layout: {
inherit: true
}
})])]);
await __unstableCreateTemplate({
slug: (0,external_wp_url_namespaceObject.cleanForSlug)(title || DEFAULT_TITLE),
content: newTemplateContent,
title: title || DEFAULT_TITLE
});
setIsBusy(false);
cancel();
__unstableSwitchToTemplateMode(true);
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Modal, {
title: (0,external_wp_i18n_namespaceObject.__)('Create custom template'),
onRequestClose: cancel,
className: "edit-post-post-template__create-modal"
}, (0,external_wp_element_namespaceObject.createElement)("form", {
className: "edit-post-post-template__create-form",
onSubmit: submit
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalVStack, {
spacing: "3"
}, (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: DEFAULT_TITLE,
disabled: isBusy,
help: (0,external_wp_i18n_namespaceObject.__)('Describe the template, e.g. "Post with sidebar". A custom template can be manually applied to any post or page.')
}), (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: cancel
}, (0,external_wp_i18n_namespaceObject.__)('Cancel')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "primary",
type: "submit",
isBusy: isBusy,
"aria-disabled": isBusy
}, (0,external_wp_i18n_namespaceObject.__)('Create'))))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/post-template/form.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PostTemplateForm(_ref) {
var _options$find, _selectedOption$value;
let {
onClose
} = _ref;
const {
isPostsPage,
availableTemplates,
fetchedTemplates,
selectedTemplateSlug,
canCreate,
canEdit
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
canUser,
getEntityRecord,
getEntityRecords
} = select(external_wp_coreData_namespaceObject.store);
const editorSettings = select(external_wp_editor_namespaceObject.store).getEditorSettings();
const siteSettings = canUser('read', 'settings') ? getEntityRecord('root', 'site') : undefined;
const _isPostsPage = select(external_wp_editor_namespaceObject.store).getCurrentPostId() === (siteSettings === null || siteSettings === void 0 ? void 0 : siteSettings.page_for_posts);
const canCreateTemplates = canUser('create', 'templates');
return {
isPostsPage: _isPostsPage,
availableTemplates: editorSettings.availableTemplates,
fetchedTemplates: canCreateTemplates ? getEntityRecords('postType', 'wp_template', {
post_type: select(external_wp_editor_namespaceObject.store).getCurrentPostType(),
per_page: -1
}) : undefined,
selectedTemplateSlug: select(external_wp_editor_namespaceObject.store).getEditedPostAttribute('template'),
canCreate: canCreateTemplates && !_isPostsPage && editorSettings.supportsTemplateMode,
canEdit: canCreateTemplates && editorSettings.supportsTemplateMode && !!select(store_store).getEditedPostTemplate()
};
}, []);
const options = (0,external_wp_element_namespaceObject.useMemo)(() => Object.entries({ ...availableTemplates,
...Object.fromEntries((fetchedTemplates !== null && fetchedTemplates !== void 0 ? fetchedTemplates : []).map(_ref2 => {
let {
slug,
title
} = _ref2;
return [slug, title.rendered];
}))
}).map(_ref3 => {
let [slug, title] = _ref3;
return {
value: slug,
label: title
};
}), [availableTemplates, fetchedTemplates]);
const selectedOption = (_options$find = options.find(option => option.value === selectedTemplateSlug)) !== null && _options$find !== void 0 ? _options$find : options.find(option => !option.value); // The default option has '' value.
const {
editPost
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_editor_namespaceObject.store);
const {
__unstableSwitchToTemplateMode
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const [isCreateModalOpen, setIsCreateModalOpen] = (0,external_wp_element_namespaceObject.useState)(false);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-post-template__form"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.__experimentalInspectorPopoverHeader, {
title: (0,external_wp_i18n_namespaceObject.__)('Template'),
help: (0,external_wp_i18n_namespaceObject.__)('Templates define the way content is displayed when viewing your site.'),
actions: canCreate ? [{
icon: add_template,
label: (0,external_wp_i18n_namespaceObject.__)('Add template'),
onClick: () => setIsCreateModalOpen(true)
}] : [],
onClose: onClose
}), isPostsPage ? (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Notice, {
className: "edit-post-post-template__notice",
status: "warning",
isDismissible: false
}, (0,external_wp_i18n_namespaceObject.__)('The posts page template cannot be changed.')) : (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SelectControl, {
__nextHasNoMarginBottom: true,
hideLabelFromVision: true,
label: (0,external_wp_i18n_namespaceObject.__)('Template'),
value: (_selectedOption$value = selectedOption === null || selectedOption === void 0 ? void 0 : selectedOption.value) !== null && _selectedOption$value !== void 0 ? _selectedOption$value : '',
options: options,
onChange: slug => editPost({
template: slug || ''
})
}), canEdit && (0,external_wp_element_namespaceObject.createElement)("p", null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "link",
onClick: () => __unstableSwitchToTemplateMode()
}, (0,external_wp_i18n_namespaceObject.__)('Edit template'))), isCreateModalOpen && (0,external_wp_element_namespaceObject.createElement)(PostTemplateCreateModal, {
onClose: () => setIsCreateModalOpen(false)
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/post-template/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PostTemplate() {
// Use internal state instead of a ref to make sure that the component
// re-renders when the popover's anchor updates.
const [popoverAnchor, setPopoverAnchor] = (0,external_wp_element_namespaceObject.useState)(null); // Memoize popoverProps to avoid returning a new object every time.
const popoverProps = (0,external_wp_element_namespaceObject.useMemo)(() => ({
anchor: popoverAnchor,
placement: 'bottom-end'
}), [popoverAnchor]);
const isVisible = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _select$canUser;
const postTypeSlug = select(external_wp_editor_namespaceObject.store).getCurrentPostType();
const postType = select(external_wp_coreData_namespaceObject.store).getPostType(postTypeSlug);
if (!(postType !== null && postType !== void 0 && postType.viewable)) {
return false;
}
const settings = select(external_wp_editor_namespaceObject.store).getEditorSettings();
const hasTemplates = !!settings.availableTemplates && Object.keys(settings.availableTemplates).length > 0;
if (hasTemplates) {
return true;
}
if (!settings.supportsTemplateMode) {
return false;
}
const canCreateTemplates = (_select$canUser = select(external_wp_coreData_namespaceObject.store).canUser('create', 'templates')) !== null && _select$canUser !== void 0 ? _select$canUser : false;
return canCreateTemplates;
}, []);
if (!isVisible) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelRow, {
className: "edit-post-post-template",
ref: setPopoverAnchor
}, (0,external_wp_element_namespaceObject.createElement)("span", null, (0,external_wp_i18n_namespaceObject.__)('Template')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Dropdown, {
popoverProps: popoverProps,
className: "edit-post-post-template__dropdown",
contentClassName: "edit-post-post-template__dialog",
focusOnMount: true,
renderToggle: _ref => {
let {
isOpen,
onToggle
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(PostTemplateToggle, {
isOpen: isOpen,
onClick: onToggle
});
},
renderContent: _ref2 => {
let {
onClose
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(PostTemplateForm, {
onClose: onClose
});
}
}));
}
function PostTemplateToggle(_ref3) {
let {
isOpen,
onClick
} = _ref3;
const templateTitle = (0,external_wp_data_namespaceObject.useSelect)(select => {
const templateSlug = select(external_wp_editor_namespaceObject.store).getEditedPostAttribute('template');
const {
supportsTemplateMode,
availableTemplates
} = select(external_wp_editor_namespaceObject.store).getEditorSettings();
if (!supportsTemplateMode && availableTemplates[templateSlug]) {
return availableTemplates[templateSlug];
}
const template = select(external_wp_coreData_namespaceObject.store).canUser('create', 'templates') && select(store_store).getEditedPostTemplate();
return (template === null || template === void 0 ? void 0 : template.title) || (template === null || template === void 0 ? void 0 : template.slug) || (availableTemplates === null || availableTemplates === void 0 ? void 0 : availableTemplates[templateSlug]);
}, []);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "edit-post-post-template__toggle",
variant: "tertiary",
"aria-expanded": isOpen,
"aria-label": templateTitle ? (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: Name of the currently selected template.
(0,external_wp_i18n_namespaceObject.__)('Select template: %s'), templateTitle) : (0,external_wp_i18n_namespaceObject.__)('Select template'),
onClick: onClick
}, templateTitle !== null && templateTitle !== void 0 ? templateTitle : (0,external_wp_i18n_namespaceObject.__)('Default template'));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/post-url/index.js
/**
* WordPress dependencies
*/
function PostURL() {
// Use internal state instead of a ref to make sure that the component
// re-renders when the popover's anchor updates.
const [popoverAnchor, setPopoverAnchor] = (0,external_wp_element_namespaceObject.useState)(null); // Memoize popoverProps to avoid returning a new object every time.
const popoverProps = (0,external_wp_element_namespaceObject.useMemo)(() => ({
anchor: popoverAnchor,
placement: 'bottom-end'
}), [popoverAnchor]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostURLCheck, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelRow, {
className: "edit-post-post-url",
ref: setPopoverAnchor
}, (0,external_wp_element_namespaceObject.createElement)("span", null, (0,external_wp_i18n_namespaceObject.__)('URL')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Dropdown, {
popoverProps: popoverProps,
className: "edit-post-post-url__dropdown",
contentClassName: "edit-post-post-url__dialog",
focusOnMount: true,
renderToggle: _ref => {
let {
isOpen,
onToggle
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(PostURLToggle, {
isOpen: isOpen,
onClick: onToggle
});
},
renderContent: _ref2 => {
let {
onClose
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostURL, {
onClose: onClose
});
}
})));
}
function PostURLToggle(_ref3) {
let {
isOpen,
onClick
} = _ref3;
const label = (0,external_wp_editor_namespaceObject.usePostURLLabel)();
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "edit-post-post-url__toggle",
variant: "tertiary",
"aria-expanded": isOpen // translators: %s: Current post URL.
,
"aria-label": (0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('Change URL: %s'), label),
onClick: onClick
}, label);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/post-status/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Module Constants
*/
const PANEL_NAME = 'post-status';
function PostStatus(_ref) {
let {
isOpened,
onTogglePanel
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelBody, {
className: "edit-post-post-status",
title: (0,external_wp_i18n_namespaceObject.__)('Summary'),
opened: isOpened,
onToggle: onTogglePanel
}, (0,external_wp_element_namespaceObject.createElement)(plugin_post_status_info.Slot, null, fills => (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(post_visibility, null), (0,external_wp_element_namespaceObject.createElement)(PostSchedule, null), (0,external_wp_element_namespaceObject.createElement)(PostTemplate, null), (0,external_wp_element_namespaceObject.createElement)(PostURL, null), (0,external_wp_element_namespaceObject.createElement)(post_sticky, null), (0,external_wp_element_namespaceObject.createElement)(post_pending_status, null), (0,external_wp_element_namespaceObject.createElement)(post_format, null), (0,external_wp_element_namespaceObject.createElement)(post_slug, null), (0,external_wp_element_namespaceObject.createElement)(post_author, null), fills, (0,external_wp_element_namespaceObject.createElement)(PostTrash, null))));
}
/* harmony default export */ var post_status = ((0,external_wp_compose_namespaceObject.compose)([(0,external_wp_data_namespaceObject.withSelect)(select => {
// We use isEditorPanelRemoved to hide the panel if it was programatically removed. We do
// not use isEditorPanelEnabled since this panel should not be disabled through the UI.
const {
isEditorPanelRemoved,
isEditorPanelOpened
} = select(store_store);
return {
isRemoved: isEditorPanelRemoved(PANEL_NAME),
isOpened: isEditorPanelOpened(PANEL_NAME)
};
}), (0,external_wp_compose_namespaceObject.ifCondition)(_ref2 => {
let {
isRemoved
} = _ref2;
return !isRemoved;
}), (0,external_wp_data_namespaceObject.withDispatch)(dispatch => ({
onTogglePanel() {
return dispatch(store_store).toggleEditorPanelOpened(PANEL_NAME);
}
}))])(PostStatus));
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/last-revision/index.js
/**
* WordPress dependencies
*/
function LastRevision() {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostLastRevisionCheck, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelBody, {
className: "edit-post-last-revision__panel"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostLastRevision, null)));
}
/* harmony default export */ var last_revision = (LastRevision);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/post-taxonomies/taxonomy-panel.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function TaxonomyPanel(_ref) {
let {
isEnabled,
taxonomy,
isOpened,
onTogglePanel,
children
} = _ref;
if (!isEnabled) {
return null;
}
const taxonomyMenuName = (0,external_lodash_namespaceObject.get)(taxonomy, ['labels', 'menu_name']);
if (!taxonomyMenuName) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelBody, {
title: taxonomyMenuName,
opened: isOpened,
onToggle: onTogglePanel
}, children);
}
/* harmony default export */ var taxonomy_panel = ((0,external_wp_compose_namespaceObject.compose)((0,external_wp_data_namespaceObject.withSelect)((select, ownProps) => {
const slug = (0,external_lodash_namespaceObject.get)(ownProps.taxonomy, ['slug']);
const panelName = slug ? `taxonomy-panel-${slug}` : '';
return {
panelName,
isEnabled: slug ? select(store_store).isEditorPanelEnabled(panelName) : false,
isOpened: slug ? select(store_store).isEditorPanelOpened(panelName) : false
};
}), (0,external_wp_data_namespaceObject.withDispatch)((dispatch, ownProps) => ({
onTogglePanel: () => {
dispatch(store_store).toggleEditorPanelOpened(ownProps.panelName);
}
})))(TaxonomyPanel));
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/post-taxonomies/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PostTaxonomies() {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostTaxonomiesCheck, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostTaxonomies, {
taxonomyWrapper: (content, taxonomy) => {
return (0,external_wp_element_namespaceObject.createElement)(taxonomy_panel, {
taxonomy: taxonomy
}, content);
}
}));
}
/* harmony default export */ var post_taxonomies = (PostTaxonomies);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/featured-image/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Module Constants
*/
const featured_image_PANEL_NAME = 'featured-image';
function FeaturedImage(_ref) {
let {
isEnabled,
isOpened,
postType,
onTogglePanel
} = _ref;
if (!isEnabled) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostFeaturedImageCheck, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelBody, {
title: (0,external_lodash_namespaceObject.get)(postType, ['labels', 'featured_image'], (0,external_wp_i18n_namespaceObject.__)('Featured image')),
opened: isOpened,
onToggle: onTogglePanel
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostFeaturedImage, null)));
}
const applyWithSelect = (0,external_wp_data_namespaceObject.withSelect)(select => {
const {
getEditedPostAttribute
} = select(external_wp_editor_namespaceObject.store);
const {
getPostType
} = select(external_wp_coreData_namespaceObject.store);
const {
isEditorPanelEnabled,
isEditorPanelOpened
} = select(store_store);
return {
postType: getPostType(getEditedPostAttribute('type')),
isEnabled: isEditorPanelEnabled(featured_image_PANEL_NAME),
isOpened: isEditorPanelOpened(featured_image_PANEL_NAME)
};
});
const applyWithDispatch = (0,external_wp_data_namespaceObject.withDispatch)(dispatch => {
const {
toggleEditorPanelOpened
} = dispatch(store_store);
return {
onTogglePanel: function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return toggleEditorPanelOpened(featured_image_PANEL_NAME, ...args);
}
};
});
/* harmony default export */ var featured_image = ((0,external_wp_compose_namespaceObject.compose)(applyWithSelect, applyWithDispatch)(FeaturedImage));
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/post-excerpt/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Module Constants
*/
const post_excerpt_PANEL_NAME = 'post-excerpt';
function PostExcerpt(_ref) {
let {
isEnabled,
isOpened,
onTogglePanel
} = _ref;
if (!isEnabled) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostExcerptCheck, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelBody, {
title: (0,external_wp_i18n_namespaceObject.__)('Excerpt'),
opened: isOpened,
onToggle: onTogglePanel
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostExcerpt, null)));
}
/* harmony default export */ var post_excerpt = ((0,external_wp_compose_namespaceObject.compose)([(0,external_wp_data_namespaceObject.withSelect)(select => {
return {
isEnabled: select(store_store).isEditorPanelEnabled(post_excerpt_PANEL_NAME),
isOpened: select(store_store).isEditorPanelOpened(post_excerpt_PANEL_NAME)
};
}), (0,external_wp_data_namespaceObject.withDispatch)(dispatch => ({
onTogglePanel() {
return dispatch(store_store).toggleEditorPanelOpened(post_excerpt_PANEL_NAME);
}
}))])(PostExcerpt));
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/discussion-panel/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Module Constants
*/
const discussion_panel_PANEL_NAME = 'discussion-panel';
function DiscussionPanel(_ref) {
let {
isEnabled,
isOpened,
onTogglePanel
} = _ref;
if (!isEnabled) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostTypeSupportCheck, {
supportKeys: ['comments', 'trackbacks']
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelBody, {
title: (0,external_wp_i18n_namespaceObject.__)('Discussion'),
opened: isOpened,
onToggle: onTogglePanel
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostTypeSupportCheck, {
supportKeys: "comments"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelRow, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostComments, null))), (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostTypeSupportCheck, {
supportKeys: "trackbacks"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelRow, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostPingbacks, null)))));
}
/* harmony default export */ var discussion_panel = ((0,external_wp_compose_namespaceObject.compose)([(0,external_wp_data_namespaceObject.withSelect)(select => {
return {
isEnabled: select(store_store).isEditorPanelEnabled(discussion_panel_PANEL_NAME),
isOpened: select(store_store).isEditorPanelOpened(discussion_panel_PANEL_NAME)
};
}), (0,external_wp_data_namespaceObject.withDispatch)(dispatch => ({
onTogglePanel() {
return dispatch(store_store).toggleEditorPanelOpened(discussion_panel_PANEL_NAME);
}
}))])(DiscussionPanel));
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/page-attributes/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Module Constants
*/
const page_attributes_PANEL_NAME = 'page-attributes';
function PageAttributes() {
const {
isEnabled,
isOpened,
postType
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getEditedPostAttribute
} = select(external_wp_editor_namespaceObject.store);
const {
isEditorPanelEnabled,
isEditorPanelOpened
} = select(store_store);
const {
getPostType
} = select(external_wp_coreData_namespaceObject.store);
return {
isEnabled: isEditorPanelEnabled(page_attributes_PANEL_NAME),
isOpened: isEditorPanelOpened(page_attributes_PANEL_NAME),
postType: getPostType(getEditedPostAttribute('type'))
};
}, []);
const {
toggleEditorPanelOpened
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
if (!isEnabled || !postType) {
return null;
}
const onTogglePanel = function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return toggleEditorPanelOpened(page_attributes_PANEL_NAME, ...args);
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PageAttributesCheck, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelBody, {
title: (0,external_lodash_namespaceObject.get)(postType, ['labels', 'attributes'], (0,external_wp_i18n_namespaceObject.__)('Page attributes')),
opened: isOpened,
onToggle: onTogglePanel
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PageAttributesParent, null), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelRow, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PageAttributesOrder, null))));
}
/* harmony default export */ var page_attributes = (PageAttributes);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/meta-boxes/meta-boxes-area/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Render metabox area.
*
* @param {Object} props Component props.
* @param {string} props.location metabox location.
* @return {WPComponent} The component to be rendered.
*/
function MetaBoxesArea(_ref) {
let {
location
} = _ref;
const container = (0,external_wp_element_namespaceObject.useRef)(null);
const formRef = (0,external_wp_element_namespaceObject.useRef)(null);
(0,external_wp_element_namespaceObject.useEffect)(() => {
formRef.current = document.querySelector('.metabox-location-' + location);
if (formRef.current) {
container.current.appendChild(formRef.current);
}
return () => {
if (formRef.current) {
document.querySelector('#metaboxes').appendChild(formRef.current);
}
};
}, [location]);
const isSaving = (0,external_wp_data_namespaceObject.useSelect)(select => {
return select(store_store).isSavingMetaBoxes();
}, []);
const classes = classnames_default()('edit-post-meta-boxes-area', `is-${location}`, {
'is-loading': isSaving
});
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classes
}, isSaving && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Spinner, null), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-meta-boxes-area__container",
ref: container
}), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-meta-boxes-area__clear"
}));
}
/* harmony default export */ var meta_boxes_area = (MetaBoxesArea);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/meta-boxes/meta-box-visibility.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
class MetaBoxVisibility extends external_wp_element_namespaceObject.Component {
componentDidMount() {
this.updateDOM();
}
componentDidUpdate(prevProps) {
if (this.props.isVisible !== prevProps.isVisible) {
this.updateDOM();
}
}
updateDOM() {
const {
id,
isVisible
} = this.props;
const element = document.getElementById(id);
if (!element) {
return;
}
if (isVisible) {
element.classList.remove('is-hidden');
} else {
element.classList.add('is-hidden');
}
}
render() {
return null;
}
}
/* harmony default export */ var meta_box_visibility = ((0,external_wp_data_namespaceObject.withSelect)((select, _ref) => {
let {
id
} = _ref;
return {
isVisible: select(store_store).isEditorPanelEnabled(`meta-box-${id}`)
};
})(MetaBoxVisibility));
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/meta-boxes/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function MetaBoxes(_ref) {
let {
location
} = _ref;
const registry = (0,external_wp_data_namespaceObject.useRegistry)();
const {
metaBoxes,
areMetaBoxesInitialized,
isEditorReady
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
__unstableIsEditorReady
} = select(external_wp_editor_namespaceObject.store);
const {
getMetaBoxesPerLocation,
areMetaBoxesInitialized: _areMetaBoxesInitialized
} = select(store_store);
return {
metaBoxes: getMetaBoxesPerLocation(location),
areMetaBoxesInitialized: _areMetaBoxesInitialized(),
isEditorReady: __unstableIsEditorReady()
};
}, [location]); // When editor is ready, initialize postboxes (wp core script) and metabox
// saving. This initializes all meta box locations, not just this specific
// one.
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (isEditorReady && !areMetaBoxesInitialized) {
registry.dispatch(store_store).initializeMetaBoxes();
}
}, [isEditorReady, areMetaBoxesInitialized]);
if (!areMetaBoxesInitialized) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (metaBoxes !== null && metaBoxes !== void 0 ? metaBoxes : []).map(_ref2 => {
let {
id
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(meta_box_visibility, {
key: id,
id: id
});
}), (0,external_wp_element_namespaceObject.createElement)(meta_boxes_area, {
location: location
}));
}
;// CONCATENATED MODULE: external ["wp","warning"]
var external_wp_warning_namespaceObject = window["wp"]["warning"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/plugin-document-setting-panel/index.js
/**
* Defines as extensibility slot for the Settings sidebar
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const {
Fill: plugin_document_setting_panel_Fill,
Slot: plugin_document_setting_panel_Slot
} = (0,external_wp_components_namespaceObject.createSlotFill)('PluginDocumentSettingPanel');
const PluginDocumentSettingFill = _ref => {
let {
isEnabled,
panelName,
opened,
onToggle,
className,
title,
icon,
children
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(enable_plugin_document_setting_panel, {
label: title,
panelName: panelName
}), (0,external_wp_element_namespaceObject.createElement)(plugin_document_setting_panel_Fill, null, isEnabled && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelBody, {
className: className,
title: title,
icon: icon,
opened: opened,
onToggle: onToggle
}, children)));
};
/**
* Renders items below the Status & Availability panel in the Document Sidebar.
*
* @param {Object} props Component properties.
* @param {string} [props.name] The machine-friendly name for the panel.
* @param {string} [props.className] An optional class name added to the row.
* @param {string} [props.title] The title of the panel
* @param {WPBlockTypeIconRender} [props.icon=inherits from the plugin] The [Dashicon](https://developer.wordpress.org/resource/dashicons/) icon slug string, or an SVG WP element, to be rendered when the sidebar is pinned to toolbar.
*
* @example
* ```js
* // Using ES5 syntax
* var el = wp.element.createElement;
* var __ = wp.i18n.__;
* var registerPlugin = wp.plugins.registerPlugin;
* var PluginDocumentSettingPanel = wp.editPost.PluginDocumentSettingPanel;
*
* function MyDocumentSettingPlugin() {
* return el(
* PluginDocumentSettingPanel,
* {
* className: 'my-document-setting-plugin',
* title: 'My Panel',
* },
* __( 'My Document Setting Panel' )
* );
* }
*
* registerPlugin( 'my-document-setting-plugin', {
* render: MyDocumentSettingPlugin
* } );
* ```
*
* @example
* ```jsx
* // Using ESNext syntax
* import { registerPlugin } from '@wordpress/plugins';
* import { PluginDocumentSettingPanel } from '@wordpress/edit-post';
*
* const MyDocumentSettingTest = () => (
* <PluginDocumentSettingPanel className="my-document-setting-plugin" title="My Panel">
* <p>My Document Setting Panel</p>
* </PluginDocumentSettingPanel>
* );
*
* registerPlugin( 'document-setting-test', { render: MyDocumentSettingTest } );
* ```
*
* @return {WPComponent} The component to be rendered.
*/
const PluginDocumentSettingPanel = (0,external_wp_compose_namespaceObject.compose)((0,external_wp_plugins_namespaceObject.withPluginContext)((context, ownProps) => {
if (undefined === ownProps.name) {
typeof process !== "undefined" && process.env && "production" !== "production" ? 0 : void 0;
}
return {
panelName: `${context.name}/${ownProps.name}`
};
}), (0,external_wp_data_namespaceObject.withSelect)((select, _ref2) => {
let {
panelName
} = _ref2;
return {
opened: select(store_store).isEditorPanelOpened(panelName),
isEnabled: select(store_store).isEditorPanelEnabled(panelName)
};
}), (0,external_wp_data_namespaceObject.withDispatch)((dispatch, _ref3) => {
let {
panelName
} = _ref3;
return {
onToggle() {
return dispatch(store_store).toggleEditorPanelOpened(panelName);
}
};
}))(PluginDocumentSettingFill);
PluginDocumentSettingPanel.Slot = plugin_document_setting_panel_Slot;
/* harmony default export */ var plugin_document_setting_panel = (PluginDocumentSettingPanel);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/plugin-sidebar/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Renders a sidebar when activated. The contents within the `PluginSidebar` will appear as content within the sidebar.
* It also automatically renders a corresponding `PluginSidebarMenuItem` component when `isPinnable` flag is set to `true`.
* If you wish to display the sidebar, you can with use the `PluginSidebarMoreMenuItem` component or the `wp.data.dispatch` API:
*
* ```js
* wp.data.dispatch( 'core/edit-post' ).openGeneralSidebar( 'plugin-name/sidebar-name' );
* ```
*
* @see PluginSidebarMoreMenuItem
*
* @param {Object} props Element props.
* @param {string} props.name A string identifying the sidebar. Must be unique for every sidebar registered within the scope of your plugin.
* @param {string} [props.className] An optional class name added to the sidebar body.
* @param {string} props.title Title displayed at the top of the sidebar.
* @param {boolean} [props.isPinnable=true] Whether to allow to pin sidebar to the toolbar. When set to `true` it also automatically renders a corresponding menu item.
* @param {WPBlockTypeIconRender} [props.icon=inherits from the plugin] The [Dashicon](https://developer.wordpress.org/resource/dashicons/) icon slug string, or an SVG WP element, to be rendered when the sidebar is pinned to toolbar.
*
* @example
* ```js
* // Using ES5 syntax
* var __ = wp.i18n.__;
* var el = wp.element.createElement;
* var PanelBody = wp.components.PanelBody;
* var PluginSidebar = wp.editPost.PluginSidebar;
* var moreIcon = wp.element.createElement( 'svg' ); //... svg element.
*
* function MyPluginSidebar() {
* return el(
* PluginSidebar,
* {
* name: 'my-sidebar',
* title: 'My sidebar title',
* icon: moreIcon,
* },
* el(
* PanelBody,
* {},
* __( 'My sidebar content' )
* )
* );
* }
* ```
*
* @example
* ```jsx
* // Using ESNext syntax
* import { __ } from '@wordpress/i18n';
* import { PanelBody } from '@wordpress/components';
* import { PluginSidebar } from '@wordpress/edit-post';
* import { more } from '@wordpress/icons';
*
* const MyPluginSidebar = () => (
* <PluginSidebar
* name="my-sidebar"
* title="My sidebar title"
* icon={ more }
* >
* <PanelBody>
* { __( 'My sidebar content' ) }
* </PanelBody>
* </PluginSidebar>
* );
* ```
*/
function PluginSidebarEditPost(_ref) {
let {
className,
...props
} = _ref;
const {
postTitle,
shortcut,
showIconLabels
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
return {
postTitle: select(external_wp_editor_namespaceObject.store).getEditedPostAttribute('title'),
shortcut: select(external_wp_keyboardShortcuts_namespaceObject.store).getShortcutRepresentation('core/edit-post/toggle-sidebar'),
showIconLabels: select(store_store).isFeatureActive('showIconLabels')
};
}, []);
return (0,external_wp_element_namespaceObject.createElement)(complementary_area, _extends({
panelClassName: className,
className: "edit-post-sidebar",
smallScreenTitle: postTitle || (0,external_wp_i18n_namespaceObject.__)('(no title)'),
scope: "core/edit-post",
toggleShortcut: shortcut,
showIconLabels: showIconLabels
}, props));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/layout.js
/**
* WordPress dependencies
*/
const layout = (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: "M18 5.5H6a.5.5 0 00-.5.5v3h13V6a.5.5 0 00-.5-.5zm.5 5H10v8h8a.5.5 0 00.5-.5v-7.5zm-10 0h-3V18a.5.5 0 00.5.5h2.5v-8zM6 4h12a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2z"
}));
/* harmony default export */ var library_layout = (layout);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/template-summary/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function TemplateSummary() {
const template = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getEditedPostTemplate
} = select(store_store);
return getEditedPostTemplate();
}, []);
if (!template) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelBody, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Flex, {
align: "flex-start",
gap: "3"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexItem, null, (0,external_wp_element_namespaceObject.createElement)(icon, {
icon: library_layout
})), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexBlock, null, (0,external_wp_element_namespaceObject.createElement)("h2", {
className: "edit-post-template-summary__title"
}, (template === null || template === void 0 ? void 0 : template.title) || (template === null || template === void 0 ? void 0 : template.slug)), (0,external_wp_element_namespaceObject.createElement)("p", null, template === null || template === void 0 ? void 0 : template.description))));
}
/* harmony default export */ var template_summary = (TemplateSummary);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/settings-sidebar/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const SIDEBAR_ACTIVE_BY_DEFAULT = external_wp_element_namespaceObject.Platform.select({
web: true,
native: false
});
const SettingsSidebar = () => {
const {
sidebarName,
keyboardShortcut,
isTemplateMode
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
// The settings sidebar is used by the edit-post/document and edit-post/block sidebars.
// sidebarName represents the sidebar that is active or that should be active when the SettingsSidebar toggle button is pressed.
// If one of the two sidebars is active the component will contain the content of that sidebar.
// When neither of the two sidebars is active we can not simply return null, because the PluginSidebarEditPost
// component, besides being used to render the sidebar, also renders the toggle button. In that case sidebarName
// should contain the sidebar that will be active when the toggle button is pressed. If a block
// is selected, that should be edit-post/block otherwise it's edit-post/document.
let sidebar = select(store).getActiveComplementaryArea(store_store.name);
if (!['edit-post/document', 'edit-post/block'].includes(sidebar)) {
if (select(external_wp_blockEditor_namespaceObject.store).getBlockSelectionStart()) {
sidebar = 'edit-post/block';
}
sidebar = 'edit-post/document';
}
const shortcut = select(external_wp_keyboardShortcuts_namespaceObject.store).getShortcutRepresentation('core/edit-post/toggle-sidebar');
return {
sidebarName: sidebar,
keyboardShortcut: shortcut,
isTemplateMode: select(store_store).isEditingTemplate()
};
}, []);
return (0,external_wp_element_namespaceObject.createElement)(PluginSidebarEditPost, {
identifier: sidebarName,
header: (0,external_wp_element_namespaceObject.createElement)(settings_header, {
sidebarName: sidebarName
}),
closeLabel: (0,external_wp_i18n_namespaceObject.__)('Close settings'),
headerClassName: "edit-post-sidebar__panel-tabs"
/* translators: button label text should, if possible, be under 16 characters. */
,
title: (0,external_wp_i18n_namespaceObject.__)('Settings'),
toggleShortcut: keyboardShortcut,
icon: (0,external_wp_i18n_namespaceObject.isRTL)() ? drawer_left : drawer_right,
isActiveByDefault: SIDEBAR_ACTIVE_BY_DEFAULT
}, !isTemplateMode && sidebarName === 'edit-post/document' && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(post_status, null), (0,external_wp_element_namespaceObject.createElement)(plugin_document_setting_panel.Slot, null), (0,external_wp_element_namespaceObject.createElement)(last_revision, null), (0,external_wp_element_namespaceObject.createElement)(post_taxonomies, null), (0,external_wp_element_namespaceObject.createElement)(featured_image, null), (0,external_wp_element_namespaceObject.createElement)(post_excerpt, null), (0,external_wp_element_namespaceObject.createElement)(discussion_panel, null), (0,external_wp_element_namespaceObject.createElement)(page_attributes, null), (0,external_wp_element_namespaceObject.createElement)(MetaBoxes, {
location: "side"
})), isTemplateMode && sidebarName === 'edit-post/document' && (0,external_wp_element_namespaceObject.createElement)(template_summary, null), sidebarName === 'edit-post/block' && (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockInspector, null));
};
/* harmony default export */ var settings_sidebar = (SettingsSidebar);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/welcome-guide/image.js
function WelcomeGuideImage(_ref) {
let {
nonAnimatedSrc,
animatedSrc
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("picture", {
className: "edit-post-welcome-guide__image"
}, (0,external_wp_element_namespaceObject.createElement)("source", {
srcSet: nonAnimatedSrc,
media: "(prefers-reduced-motion: reduce)"
}), (0,external_wp_element_namespaceObject.createElement)("img", {
src: animatedSrc,
width: "312",
height: "240",
alt: ""
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/welcome-guide/default.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function WelcomeGuideDefault() {
const {
toggleFeature
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Guide, {
className: "edit-post-welcome-guide",
contentLabel: (0,external_wp_i18n_namespaceObject.__)('Welcome to the block editor'),
finishButtonText: (0,external_wp_i18n_namespaceObject.__)('Get started'),
onFinish: () => toggleFeature('welcomeGuide'),
pages: [{
image: (0,external_wp_element_namespaceObject.createElement)(WelcomeGuideImage, {
nonAnimatedSrc: "https://s.w.org/images/block-editor/welcome-canvas.svg",
animatedSrc: "https://s.w.org/images/block-editor/welcome-canvas.gif"
}),
content: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("h1", {
className: "edit-post-welcome-guide__heading"
}, (0,external_wp_i18n_namespaceObject.__)('Welcome to the block editor')), (0,external_wp_element_namespaceObject.createElement)("p", {
className: "edit-post-welcome-guide__text"
}, (0,external_wp_i18n_namespaceObject.__)('In the WordPress editor, each paragraph, image, or video is presented as a distinct “block” of content.')))
}, {
image: (0,external_wp_element_namespaceObject.createElement)(WelcomeGuideImage, {
nonAnimatedSrc: "https://s.w.org/images/block-editor/welcome-editor.svg",
animatedSrc: "https://s.w.org/images/block-editor/welcome-editor.gif"
}),
content: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("h1", {
className: "edit-post-welcome-guide__heading"
}, (0,external_wp_i18n_namespaceObject.__)('Make each block your own')), (0,external_wp_element_namespaceObject.createElement)("p", {
className: "edit-post-welcome-guide__text"
}, (0,external_wp_i18n_namespaceObject.__)('Each block comes with its own set of controls for changing things like color, width, and alignment. These will show and hide automatically when you have a block selected.')))
}, {
image: (0,external_wp_element_namespaceObject.createElement)(WelcomeGuideImage, {
nonAnimatedSrc: "https://s.w.org/images/block-editor/welcome-library.svg",
animatedSrc: "https://s.w.org/images/block-editor/welcome-library.gif"
}),
content: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("h1", {
className: "edit-post-welcome-guide__heading"
}, (0,external_wp_i18n_namespaceObject.__)('Get to know the block library')), (0,external_wp_element_namespaceObject.createElement)("p", {
className: "edit-post-welcome-guide__text"
}, (0,external_wp_element_namespaceObject.createInterpolateElement)((0,external_wp_i18n_namespaceObject.__)('All of the blocks available to you live in the block library. You’ll find it wherever you see the <InserterIconImage /> icon.'), {
InserterIconImage: (0,external_wp_element_namespaceObject.createElement)("img", {
alt: (0,external_wp_i18n_namespaceObject.__)('inserter'),
src: "data:image/svg+xml,%3Csvg width='18' height='18' viewBox='0 0 18 18' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='18' height='18' rx='2' fill='%231E1E1E'/%3E%3Cpath d='M9.22727 4V14M4 8.77273H14' stroke='white' stroke-width='1.5'/%3E%3C/svg%3E%0A"
})
})))
}, {
image: (0,external_wp_element_namespaceObject.createElement)(WelcomeGuideImage, {
nonAnimatedSrc: "https://s.w.org/images/block-editor/welcome-documentation.svg",
animatedSrc: "https://s.w.org/images/block-editor/welcome-documentation.gif"
}),
content: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("h1", {
className: "edit-post-welcome-guide__heading"
}, (0,external_wp_i18n_namespaceObject.__)('Learn how to use the block editor')), (0,external_wp_element_namespaceObject.createElement)("p", {
className: "edit-post-welcome-guide__text"
}, (0,external_wp_i18n_namespaceObject.__)('New to the block editor? Want to learn more about using it? '), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ExternalLink, {
href: (0,external_wp_i18n_namespaceObject.__)('https://wordpress.org/support/article/wordpress-editor/')
}, (0,external_wp_i18n_namespaceObject.__)("Here's a detailed guide."))))
}]
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/welcome-guide/template.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function WelcomeGuideTemplate() {
const {
toggleFeature
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Guide, {
className: "edit-template-welcome-guide",
contentLabel: (0,external_wp_i18n_namespaceObject.__)('Welcome to the template editor'),
finishButtonText: (0,external_wp_i18n_namespaceObject.__)('Get started'),
onFinish: () => toggleFeature('welcomeGuideTemplate'),
pages: [{
image: (0,external_wp_element_namespaceObject.createElement)(WelcomeGuideImage, {
nonAnimatedSrc: "https://s.w.org/images/block-editor/welcome-template-editor.svg",
animatedSrc: "https://s.w.org/images/block-editor/welcome-template-editor.gif"
}),
content: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("h1", {
className: "edit-post-welcome-guide__heading"
}, (0,external_wp_i18n_namespaceObject.__)('Welcome to the template editor')), (0,external_wp_element_namespaceObject.createElement)("p", {
className: "edit-post-welcome-guide__text"
}, (0,external_wp_i18n_namespaceObject.__)('Templates help define the layout of the site. You can customize all aspects of your posts and pages using blocks and patterns in this editor.')))
}]
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/welcome-guide/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function WelcomeGuide() {
const {
isActive,
isTemplateMode
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
isFeatureActive,
isEditingTemplate
} = select(store_store);
const _isTemplateMode = isEditingTemplate();
const feature = _isTemplateMode ? 'welcomeGuideTemplate' : 'welcomeGuide';
return {
isActive: isFeatureActive(feature),
isTemplateMode: _isTemplateMode
};
}, []);
if (!isActive) {
return null;
}
return isTemplateMode ? (0,external_wp_element_namespaceObject.createElement)(WelcomeGuideTemplate, null) : (0,external_wp_element_namespaceObject.createElement)(WelcomeGuideDefault, null);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/plugin-post-publish-panel/index.js
/**
* WordPress dependencies
*/
const {
Fill: plugin_post_publish_panel_Fill,
Slot: plugin_post_publish_panel_Slot
} = (0,external_wp_components_namespaceObject.createSlotFill)('PluginPostPublishPanel');
const PluginPostPublishPanelFill = _ref => {
let {
children,
className,
title,
initialOpen = false,
icon
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(plugin_post_publish_panel_Fill, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelBody, {
className: className,
initialOpen: initialOpen || !title,
title: title,
icon: icon
}, children));
};
/**
* Renders provided content to the post-publish panel in the publish flow
* (side panel that opens after a user publishes the post).
*
* @param {Object} props Component properties.
* @param {string} [props.className] An optional class name added to the panel.
* @param {string} [props.title] Title displayed at the top of the panel.
* @param {boolean} [props.initialOpen=false] Whether to have the panel initially opened. When no title is provided it is always opened.
* @param {WPBlockTypeIconRender} [props.icon=inherits from the plugin] The [Dashicon](https://developer.wordpress.org/resource/dashicons/) icon slug string, or an SVG WP element, to be rendered when the sidebar is pinned to toolbar.
*
* @example
* ```js
* // Using ES5 syntax
* var __ = wp.i18n.__;
* var PluginPostPublishPanel = wp.editPost.PluginPostPublishPanel;
*
* function MyPluginPostPublishPanel() {
* return wp.element.createElement(
* PluginPostPublishPanel,
* {
* className: 'my-plugin-post-publish-panel',
* title: __( 'My panel title' ),
* initialOpen: true,
* },
* __( 'My panel content' )
* );
* }
* ```
*
* @example
* ```jsx
* // Using ESNext syntax
* import { __ } from '@wordpress/i18n';
* import { PluginPostPublishPanel } from '@wordpress/edit-post';
*
* const MyPluginPostPublishPanel = () => (
* <PluginPostPublishPanel
* className="my-plugin-post-publish-panel"
* title={ __( 'My panel title' ) }
* initialOpen={ true }
* >
* { __( 'My panel content' ) }
* </PluginPostPublishPanel>
* );
* ```
*
* @return {WPComponent} The component to be rendered.
*/
const PluginPostPublishPanel = (0,external_wp_compose_namespaceObject.compose)((0,external_wp_plugins_namespaceObject.withPluginContext)((context, ownProps) => {
return {
icon: ownProps.icon || context.icon
};
}))(PluginPostPublishPanelFill);
PluginPostPublishPanel.Slot = plugin_post_publish_panel_Slot;
/* harmony default export */ var plugin_post_publish_panel = (PluginPostPublishPanel);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/sidebar/plugin-pre-publish-panel/index.js
/**
* WordPress dependencies
*/
const {
Fill: plugin_pre_publish_panel_Fill,
Slot: plugin_pre_publish_panel_Slot
} = (0,external_wp_components_namespaceObject.createSlotFill)('PluginPrePublishPanel');
const PluginPrePublishPanelFill = _ref => {
let {
children,
className,
title,
initialOpen = false,
icon
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(plugin_pre_publish_panel_Fill, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelBody, {
className: className,
initialOpen: initialOpen || !title,
title: title,
icon: icon
}, children));
};
/**
* Renders provided content to the pre-publish side panel in the publish flow
* (side panel that opens when a user first pushes "Publish" from the main editor).
*
* @param {Object} props Component props.
* @param {string} [props.className] An optional class name added to the panel.
* @param {string} [props.title] Title displayed at the top of the panel.
* @param {boolean} [props.initialOpen=false] Whether to have the panel initially opened.
* When no title is provided it is always opened.
* @param {WPBlockTypeIconRender} [props.icon=inherits from the plugin] The [Dashicon](https://developer.wordpress.org/resource/dashicons/)
* icon slug string, or an SVG WP element, to be rendered when
* the sidebar is pinned to toolbar.
*
* @example
* ```js
* // Using ES5 syntax
* var __ = wp.i18n.__;
* var PluginPrePublishPanel = wp.editPost.PluginPrePublishPanel;
*
* function MyPluginPrePublishPanel() {
* return wp.element.createElement(
* PluginPrePublishPanel,
* {
* className: 'my-plugin-pre-publish-panel',
* title: __( 'My panel title' ),
* initialOpen: true,
* },
* __( 'My panel content' )
* );
* }
* ```
*
* @example
* ```jsx
* // Using ESNext syntax
* import { __ } from '@wordpress/i18n';
* import { PluginPrePublishPanel } from '@wordpress/edit-post';
*
* const MyPluginPrePublishPanel = () => (
* <PluginPrePublishPanel
* className="my-plugin-pre-publish-panel"
* title={ __( 'My panel title' ) }
* initialOpen={ true }
* >
* { __( 'My panel content' ) }
* </PluginPrePublishPanel>
* );
* ```
*
* @return {WPComponent} The component to be rendered.
*/
const PluginPrePublishPanel = (0,external_wp_compose_namespaceObject.compose)((0,external_wp_plugins_namespaceObject.withPluginContext)((context, ownProps) => {
return {
icon: ownProps.icon || context.icon
};
}))(PluginPrePublishPanelFill);
PluginPrePublishPanel.Slot = plugin_pre_publish_panel_Slot;
/* harmony default export */ var plugin_pre_publish_panel = (PluginPrePublishPanel);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/layout/actions-panel.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const {
Fill: actions_panel_Fill,
Slot: actions_panel_Slot
} = (0,external_wp_components_namespaceObject.createSlotFill)('ActionsPanel');
const ActionsPanelFill = (/* unused pure expression or super */ null && (actions_panel_Fill));
function ActionsPanel(_ref) {
let {
setEntitiesSavedStatesCallback,
closeEntitiesSavedStates,
isEntitiesSavedStatesOpen
} = _ref;
const {
closePublishSidebar,
togglePublishSidebar
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const {
publishSidebarOpened,
hasActiveMetaboxes,
isSavingMetaBoxes,
hasNonPostEntityChanges
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
return {
publishSidebarOpened: select(store_store).isPublishSidebarOpened(),
hasActiveMetaboxes: select(store_store).hasMetaBoxes(),
isSavingMetaBoxes: select(store_store).isSavingMetaBoxes(),
hasNonPostEntityChanges: select(external_wp_editor_namespaceObject.store).hasNonPostEntityChanges()
};
}, []);
const openEntitiesSavedStates = (0,external_wp_element_namespaceObject.useCallback)(() => setEntitiesSavedStatesCallback(true), []); // It is ok for these components to be unmounted when not in visual use.
// We don't want more than one present at a time, decide which to render.
let unmountableContent;
if (publishSidebarOpened) {
unmountableContent = (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostPublishPanel, {
onClose: closePublishSidebar,
forceIsDirty: hasActiveMetaboxes,
forceIsSaving: isSavingMetaBoxes,
PrePublishExtension: plugin_pre_publish_panel.Slot,
PostPublishExtension: plugin_post_publish_panel.Slot
});
} else if (hasNonPostEntityChanges) {
unmountableContent = (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-layout__toggle-entities-saved-states-panel"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "secondary",
className: "edit-post-layout__toggle-entities-saved-states-panel-button",
onClick: openEntitiesSavedStates,
"aria-expanded": false
}, (0,external_wp_i18n_namespaceObject.__)('Open save panel')));
} else {
unmountableContent = (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-layout__toggle-publish-panel"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "secondary",
className: "edit-post-layout__toggle-publish-panel-button",
onClick: togglePublishSidebar,
"aria-expanded": false
}, (0,external_wp_i18n_namespaceObject.__)('Open publish panel')));
} // Since EntitiesSavedStates controls its own panel, we can keep it
// always mounted to retain its own component state (such as checkboxes).
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, isEntitiesSavedStatesOpen && (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.EntitiesSavedStates, {
close: closeEntitiesSavedStates
}), (0,external_wp_element_namespaceObject.createElement)(actions_panel_Slot, {
bubblesVirtually: true
}), !isEntitiesSavedStatesOpen && unmountableContent);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/start-page-options/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useStartPatterns() {
// A pattern is a start pattern if it includes 'core/post-content' in its blockTypes,
// and it has no postTypes declares and the current post type is page or if
// the current post type is part of the postTypes declared.
const {
blockPatternsWithPostContentBlockType,
postType
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getPatternsByBlockTypes
} = select(external_wp_blockEditor_namespaceObject.store);
const {
getCurrentPostType
} = select(external_wp_editor_namespaceObject.store);
return {
blockPatternsWithPostContentBlockType: getPatternsByBlockTypes('core/post-content'),
postType: getCurrentPostType()
};
}, []);
return (0,external_wp_element_namespaceObject.useMemo)(() => {
// filter patterns without postTypes declared if the current postType is page
// or patterns that declare the current postType in its post type array.
return blockPatternsWithPostContentBlockType.filter(pattern => {
return postType === 'page' && !pattern.postTypes || Array.isArray(pattern.postTypes) && pattern.postTypes.includes(postType);
});
}, [postType, blockPatternsWithPostContentBlockType]);
}
function PatternSelection(_ref) {
let {
onChoosePattern
} = _ref;
const blockPatterns = useStartPatterns();
const shownBlockPatterns = (0,external_wp_compose_namespaceObject.useAsyncList)(blockPatterns);
const {
resetEditorBlocks
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_editor_namespaceObject.store);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.__experimentalBlockPatternsList, {
blockPatterns: blockPatterns,
shownPatterns: shownBlockPatterns,
onClickPattern: (_pattern, blocks) => {
resetEditorBlocks(blocks);
onChoosePattern();
}
});
}
const START_PAGE_MODAL_STATES = {
INITIAL: 'INITIAL',
PATTERN: 'PATTERN',
CLOSED: 'CLOSED'
};
function StartPageOptions() {
const [modalState, setModalState] = (0,external_wp_element_namespaceObject.useState)(START_PAGE_MODAL_STATES.INITIAL);
const blockPatterns = useStartPatterns();
const hasStartPattern = blockPatterns.length > 0;
const shouldOpenModel = (0,external_wp_data_namespaceObject.useSelect)(select => {
if (!hasStartPattern || modalState !== START_PAGE_MODAL_STATES.INITIAL) {
return false;
}
const {
getEditedPostContent,
isEditedPostSaveable
} = select(external_wp_editor_namespaceObject.store);
const {
isEditingTemplate,
isFeatureActive
} = select(store_store);
return !isEditedPostSaveable() && '' === getEditedPostContent() && !isEditingTemplate() && !isFeatureActive('welcomeGuide');
}, [modalState, hasStartPattern]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (shouldOpenModel) {
setModalState(START_PAGE_MODAL_STATES.PATTERN);
}
}, [shouldOpenModel]);
if (modalState === START_PAGE_MODAL_STATES.INITIAL || modalState === START_PAGE_MODAL_STATES.CLOSED) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Modal, {
className: "edit-post-start-page-options__modal",
title: (0,external_wp_i18n_namespaceObject.__)('Choose a pattern'),
onRequestClose: () => {
setModalState(START_PAGE_MODAL_STATES.CLOSED);
}
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-start-page-options__modal-content"
}, modalState === START_PAGE_MODAL_STATES.PATTERN && (0,external_wp_element_namespaceObject.createElement)(PatternSelection, {
onChoosePattern: () => {
setModalState(START_PAGE_MODAL_STATES.CLOSED);
}
})));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/layout/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const interfaceLabels = {
/* translators: accessibility text for the editor top bar landmark region. */
header: (0,external_wp_i18n_namespaceObject.__)('Editor top bar'),
/* translators: accessibility text for the editor content landmark region. */
body: (0,external_wp_i18n_namespaceObject.__)('Editor content'),
/* translators: accessibility text for the editor settings landmark region. */
sidebar: (0,external_wp_i18n_namespaceObject.__)('Editor settings'),
/* translators: accessibility text for the editor publish landmark region. */
actions: (0,external_wp_i18n_namespaceObject.__)('Editor publish'),
/* translators: accessibility text for the editor footer landmark region. */
footer: (0,external_wp_i18n_namespaceObject.__)('Editor footer')
};
function Layout(_ref) {
let {
styles
} = _ref;
const isMobileViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('medium', '<');
const isHugeViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('huge', '>=');
const isLargeViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('large');
const {
openGeneralSidebar,
closeGeneralSidebar,
setIsInserterOpened
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const {
createErrorNotice
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_notices_namespaceObject.store);
const {
mode,
isFullscreenActive,
isRichEditingEnabled,
sidebarIsOpened,
hasActiveMetaboxes,
hasFixedToolbar,
previousShortcut,
nextShortcut,
hasBlockSelected,
isInserterOpened,
isListViewOpened,
showIconLabels,
isDistractionFree,
showBlockBreadcrumbs,
isTemplateMode,
documentLabel
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getEditorSettings,
getPostTypeLabel
} = select(external_wp_editor_namespaceObject.store);
const editorSettings = getEditorSettings();
const postTypeLabel = getPostTypeLabel();
return {
isTemplateMode: select(store_store).isEditingTemplate(),
hasFixedToolbar: select(store_store).isFeatureActive('fixedToolbar'),
sidebarIsOpened: !!(select(store).getActiveComplementaryArea(store_store.name) || select(store_store).isPublishSidebarOpened()),
isFullscreenActive: select(store_store).isFeatureActive('fullscreenMode'),
isInserterOpened: select(store_store).isInserterOpened(),
isListViewOpened: select(store_store).isListViewOpened(),
mode: select(store_store).getEditorMode(),
isRichEditingEnabled: editorSettings.richEditingEnabled,
hasActiveMetaboxes: select(store_store).hasMetaBoxes(),
previousShortcut: select(external_wp_keyboardShortcuts_namespaceObject.store).getAllShortcutKeyCombinations('core/edit-post/previous-region'),
nextShortcut: select(external_wp_keyboardShortcuts_namespaceObject.store).getAllShortcutKeyCombinations('core/edit-post/next-region'),
showIconLabels: select(store_store).isFeatureActive('showIconLabels'),
isDistractionFree: select(store_store).isFeatureActive('distractionFree'),
showBlockBreadcrumbs: select(store_store).isFeatureActive('showBlockBreadcrumbs'),
// translators: Default label for the Document in the Block Breadcrumb.
documentLabel: postTypeLabel || (0,external_wp_i18n_namespaceObject._x)('Document', 'noun')
};
}, []);
const openSidebarPanel = () => openGeneralSidebar(hasBlockSelected ? 'edit-post/block' : 'edit-post/document'); // Inserter and Sidebars are mutually exclusive
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (sidebarIsOpened && !isHugeViewport) {
setIsInserterOpened(false);
}
}, [sidebarIsOpened, isHugeViewport]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (isInserterOpened && !isHugeViewport) {
closeGeneralSidebar();
}
}, [isInserterOpened, isHugeViewport]); // Local state for save panel.
// Note 'truthy' callback implies an open panel.
const [entitiesSavedStatesCallback, setEntitiesSavedStatesCallback] = (0,external_wp_element_namespaceObject.useState)(false);
const closeEntitiesSavedStates = (0,external_wp_element_namespaceObject.useCallback)(arg => {
if (typeof entitiesSavedStatesCallback === 'function') {
entitiesSavedStatesCallback(arg);
}
setEntitiesSavedStatesCallback(false);
}, [entitiesSavedStatesCallback]);
const className = classnames_default()('edit-post-layout', 'is-mode-' + mode, {
'is-sidebar-opened': sidebarIsOpened,
'has-fixed-toolbar': hasFixedToolbar,
'has-metaboxes': hasActiveMetaboxes,
'show-icon-labels': showIconLabels,
'is-distraction-free': isDistractionFree && isLargeViewport,
'is-entity-save-view-open': !!entitiesSavedStatesCallback
});
const secondarySidebarLabel = isListViewOpened ? (0,external_wp_i18n_namespaceObject.__)('Document Overview') : (0,external_wp_i18n_namespaceObject.__)('Block Library');
const secondarySidebar = () => {
if (mode === 'visual' && isInserterOpened) {
return (0,external_wp_element_namespaceObject.createElement)(InserterSidebar, null);
}
if (mode === 'visual' && isListViewOpened) {
return (0,external_wp_element_namespaceObject.createElement)(ListViewSidebar, null);
}
return null;
};
function onPluginAreaError(name) {
createErrorNotice((0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: plugin name */
(0,external_wp_i18n_namespaceObject.__)('The "%s" plugin has encountered an error and cannot be rendered.'), name));
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(fullscreen_mode, {
isActive: isFullscreenActive
}), (0,external_wp_element_namespaceObject.createElement)(browser_url, null), (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.UnsavedChangesWarning, null), (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.AutosaveMonitor, null), (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.LocalAutosaveMonitor, null), (0,external_wp_element_namespaceObject.createElement)(keyboard_shortcuts, null), (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.EditorKeyboardShortcutsRegister, null), (0,external_wp_element_namespaceObject.createElement)(settings_sidebar, null), (0,external_wp_element_namespaceObject.createElement)(interface_skeleton, {
isDistractionFree: isDistractionFree && isLargeViewport,
className: className,
labels: { ...interfaceLabels,
secondarySidebar: secondarySidebarLabel
},
header: (0,external_wp_element_namespaceObject.createElement)(header, {
setEntitiesSavedStatesCallback: setEntitiesSavedStatesCallback
}),
editorNotices: (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.EditorNotices, null),
secondarySidebar: secondarySidebar(),
sidebar: (!isMobileViewport || sidebarIsOpened) && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, !isMobileViewport && !sidebarIsOpened && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-layout__toggle-sidebar-panel"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "secondary",
className: "edit-post-layout__toggle-sidebar-panel-button",
onClick: openSidebarPanel,
"aria-expanded": false
}, hasBlockSelected ? (0,external_wp_i18n_namespaceObject.__)('Open block settings') : (0,external_wp_i18n_namespaceObject.__)('Open document settings'))), (0,external_wp_element_namespaceObject.createElement)(complementary_area.Slot, {
scope: "core/edit-post"
})),
notices: (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.EditorSnackbars, null),
content: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, !isDistractionFree && (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.EditorNotices, null), (mode === 'text' || !isRichEditingEnabled) && (0,external_wp_element_namespaceObject.createElement)(TextEditor, null), isRichEditingEnabled && mode === 'visual' && (0,external_wp_element_namespaceObject.createElement)(VisualEditor, {
styles: styles
}), !isDistractionFree && !isTemplateMode && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-layout__metaboxes"
}, (0,external_wp_element_namespaceObject.createElement)(MetaBoxes, {
location: "normal"
}), (0,external_wp_element_namespaceObject.createElement)(MetaBoxes, {
location: "advanced"
})), isMobileViewport && sidebarIsOpened && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ScrollLock, null)),
footer: !isDistractionFree && !isMobileViewport && showBlockBreadcrumbs && isRichEditingEnabled && mode === 'visual' && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "edit-post-layout__footer"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockBreadcrumb, {
rootLabelText: documentLabel
})),
actions: (0,external_wp_element_namespaceObject.createElement)(ActionsPanel, {
closeEntitiesSavedStates: closeEntitiesSavedStates,
isEntitiesSavedStatesOpen: entitiesSavedStatesCallback,
setEntitiesSavedStatesCallback: setEntitiesSavedStatesCallback
}),
shortcuts: {
previous: previousShortcut,
next: nextShortcut
}
}), (0,external_wp_element_namespaceObject.createElement)(EditPostPreferencesModal, null), (0,external_wp_element_namespaceObject.createElement)(keyboard_shortcut_help_modal, null), (0,external_wp_element_namespaceObject.createElement)(WelcomeGuide, null), (0,external_wp_element_namespaceObject.createElement)(StartPageOptions, null), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Popover.Slot, null), (0,external_wp_element_namespaceObject.createElement)(external_wp_plugins_namespaceObject.PluginArea, {
onError: onPluginAreaError
}));
}
/* harmony default export */ var components_layout = (Layout);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/editor-initialization/listener-hooks.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* This listener hook monitors for block selection and triggers the appropriate
* sidebar state.
*
* @param {number} postId The current post id.
*/
const useBlockSelectionListener = postId => {
const {
hasBlockSelection,
isEditorSidebarOpened
} = (0,external_wp_data_namespaceObject.useSelect)(select => ({
hasBlockSelection: !!select(external_wp_blockEditor_namespaceObject.store).getBlockSelectionStart(),
isEditorSidebarOpened: select(constants_STORE_NAME).isEditorSidebarOpened()
}), [postId]);
const {
openGeneralSidebar
} = (0,external_wp_data_namespaceObject.useDispatch)(constants_STORE_NAME);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (!isEditorSidebarOpened) {
return;
}
if (hasBlockSelection) {
openGeneralSidebar('edit-post/block');
} else {
openGeneralSidebar('edit-post/document');
}
}, [hasBlockSelection, isEditorSidebarOpened]);
};
/**
* This listener hook monitors any change in permalink and updates the view
* post link in the admin bar.
*
* @param {number} postId
*/
const useUpdatePostLinkListener = postId => {
const {
newPermalink
} = (0,external_wp_data_namespaceObject.useSelect)(select => ({
newPermalink: select(external_wp_editor_namespaceObject.store).getCurrentPost().link
}), [postId]);
const nodeToUpdate = (0,external_wp_element_namespaceObject.useRef)();
(0,external_wp_element_namespaceObject.useEffect)(() => {
nodeToUpdate.current = document.querySelector(VIEW_AS_PREVIEW_LINK_SELECTOR) || document.querySelector(VIEW_AS_LINK_SELECTOR);
}, [postId]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (!newPermalink || !nodeToUpdate.current) {
return;
}
nodeToUpdate.current.setAttribute('href', newPermalink);
}, [newPermalink]);
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/editor-initialization/index.js
/**
* Internal dependencies
*/
/**
* Data component used for initializing the editor and re-initializes
* when postId changes or on unmount.
*
* @param {number} postId The id of the post.
* @return {null} This is a data component so does not render any ui.
*/
function EditorInitialization(_ref) {
let {
postId
} = _ref;
useBlockSelectionListener(postId);
useUpdatePostLinkListener(postId);
return null;
}
;// CONCATENATED MODULE: external ["wp","privateApis"]
var external_wp_privateApis_namespaceObject = window["wp"]["privateApis"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/private-apis.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/edit-post');
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/editor.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const {
ExperimentalEditorProvider
} = unlock(external_wp_editor_namespaceObject.privateApis);
function Editor(_ref) {
let {
postId,
postType,
settings,
initialEdits,
...props
} = _ref;
const {
hasFixedToolbar,
focusMode,
isDistractionFree,
hasInlineToolbar,
hasThemeStyles,
post,
preferredStyleVariations,
hiddenBlockTypes,
blockTypes,
keepCaretInsideBlock,
isTemplateMode,
template
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _getPostType$viewable, _getPostType;
const {
isFeatureActive,
__experimentalGetPreviewDeviceType,
isEditingTemplate,
getEditedPostTemplate,
getHiddenBlockTypes
} = select(store_store);
const {
getEntityRecord,
getPostType,
getEntityRecords,
canUser
} = select(external_wp_coreData_namespaceObject.store);
const {
getEditorSettings
} = select(external_wp_editor_namespaceObject.store);
const {
getBlockTypes
} = select(external_wp_blocks_namespaceObject.store);
const isTemplate = ['wp_template', 'wp_template_part'].includes(postType); // Ideally the initializeEditor function should be called using the ID of the REST endpoint.
// to avoid the special case.
let postObject;
if (isTemplate) {
const posts = getEntityRecords('postType', postType, {
wp_id: postId
});
postObject = posts === null || posts === void 0 ? void 0 : posts[0];
} else {
postObject = getEntityRecord('postType', postType, postId);
}
const supportsTemplateMode = getEditorSettings().supportsTemplateMode;
const isViewable = (_getPostType$viewable = (_getPostType = getPostType(postType)) === null || _getPostType === void 0 ? void 0 : _getPostType.viewable) !== null && _getPostType$viewable !== void 0 ? _getPostType$viewable : false;
const canEditTemplate = canUser('create', 'templates');
return {
hasFixedToolbar: isFeatureActive('fixedToolbar') || __experimentalGetPreviewDeviceType() !== 'Desktop',
focusMode: isFeatureActive('focusMode'),
isDistractionFree: isFeatureActive('distractionFree'),
hasInlineToolbar: isFeatureActive('inlineToolbar'),
hasThemeStyles: isFeatureActive('themeStyles'),
preferredStyleVariations: select(external_wp_preferences_namespaceObject.store).get('core/edit-post', 'preferredStyleVariations'),
hiddenBlockTypes: getHiddenBlockTypes(),
blockTypes: getBlockTypes(),
keepCaretInsideBlock: isFeatureActive('keepCaretInsideBlock'),
isTemplateMode: isEditingTemplate(),
template: supportsTemplateMode && isViewable && canEditTemplate ? getEditedPostTemplate() : null,
post: postObject
};
}, [postType, postId]);
const {
updatePreferredStyleVariations,
setIsInserterOpened
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const editorSettings = (0,external_wp_element_namespaceObject.useMemo)(() => {
const result = { ...settings,
__experimentalPreferredStyleVariations: {
value: preferredStyleVariations,
onChange: updatePreferredStyleVariations
},
hasFixedToolbar,
focusMode,
isDistractionFree,
hasInlineToolbar,
// This is marked as experimental to give time for the quick inserter to mature.
__experimentalSetIsInserterOpened: setIsInserterOpened,
keepCaretInsideBlock,
// Keep a reference of the `allowedBlockTypes` from the server to handle use cases
// where we need to differentiate if a block is disabled by the user or some plugin.
defaultAllowedBlockTypes: settings.allowedBlockTypes
}; // Omit hidden block types if exists and non-empty.
if (hiddenBlockTypes.length > 0) {
// Defer to passed setting for `allowedBlockTypes` if provided as
// anything other than `true` (where `true` is equivalent to allow
// all block types).
const defaultAllowedBlockTypes = true === settings.allowedBlockTypes ? blockTypes.map(_ref2 => {
let {
name
} = _ref2;
return name;
}) : settings.allowedBlockTypes || [];
result.allowedBlockTypes = defaultAllowedBlockTypes.filter(type => !hiddenBlockTypes.includes(type));
}
return result;
}, [settings, hasFixedToolbar, focusMode, isDistractionFree, hiddenBlockTypes, blockTypes, preferredStyleVariations, setIsInserterOpened, updatePreferredStyleVariations, keepCaretInsideBlock]);
const styles = (0,external_wp_element_namespaceObject.useMemo)(() => {
var _settings$styles;
const themeStyles = [];
const presetStyles = [];
(_settings$styles = settings.styles) === null || _settings$styles === void 0 ? void 0 : _settings$styles.forEach(style => {
if (!style.__unstableType || style.__unstableType === 'theme') {
themeStyles.push(style);
} else {
presetStyles.push(style);
}
});
const defaultEditorStyles = [...settings.defaultEditorStyles, ...presetStyles];
return hasThemeStyles && themeStyles.length ? settings.styles : defaultEditorStyles;
}, [settings, hasThemeStyles]);
if (!post) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_keyboardShortcuts_namespaceObject.ShortcutProvider, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SlotFillProvider, null, (0,external_wp_element_namespaceObject.createElement)(ExperimentalEditorProvider, _extends({
settings: editorSettings,
post: post,
initialEdits: initialEdits,
useSubRegistry: false,
__unstableTemplate: isTemplateMode ? template : undefined
}, props), (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.ErrorBoundary, null, (0,external_wp_element_namespaceObject.createElement)(EditorInitialization, {
postId: postId
}), (0,external_wp_element_namespaceObject.createElement)(components_layout, {
styles: styles
})), (0,external_wp_element_namespaceObject.createElement)(external_wp_editor_namespaceObject.PostLockedModal, null))));
}
/* harmony default export */ var editor = (Editor);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/block-settings-menu/plugin-block-settings-menu-item.js
/**
* WordPress dependencies
*/
const isEverySelectedBlockAllowed = (selected, allowed) => selected.filter(id => !allowed.includes(id)).length === 0;
/**
* Plugins may want to add an item to the menu either for every block
* or only for the specific ones provided in the `allowedBlocks` component property.
*
* If there are multiple blocks selected the item will be rendered if every block
* is of one allowed type (not necessarily the same).
*
* @param {string[]} selectedBlocks Array containing the names of the blocks selected
* @param {string[]} allowedBlocks Array containing the names of the blocks allowed
* @return {boolean} Whether the item will be rendered or not.
*/
const shouldRenderItem = (selectedBlocks, allowedBlocks) => !Array.isArray(allowedBlocks) || isEverySelectedBlockAllowed(selectedBlocks, allowedBlocks);
/**
* Renders a new item in the block settings menu.
*
* @param {Object} props Component props.
* @param {Array} [props.allowedBlocks] An array containing a list of block names for which the item should be shown. If not present, it'll be rendered for any block. If multiple blocks are selected, it'll be shown if and only if all of them are in the allowed list.
* @param {WPBlockTypeIconRender} [props.icon] The [Dashicon](https://developer.wordpress.org/resource/dashicons/) icon slug string, or an SVG WP element.
* @param {string} props.label The menu item text.
* @param {Function} props.onClick Callback function to be executed when the user click the menu item.
* @param {boolean} [props.small] Whether to render the label or not.
* @param {string} [props.role] The ARIA role for the menu item.
*
* @example
* ```js
* // Using ES5 syntax
* var __ = wp.i18n.__;
* var PluginBlockSettingsMenuItem = wp.editPost.PluginBlockSettingsMenuItem;
*
* function doOnClick(){
* // To be called when the user clicks the menu item.
* }
*
* function MyPluginBlockSettingsMenuItem() {
* return wp.element.createElement(
* PluginBlockSettingsMenuItem,
* {
* allowedBlocks: [ 'core/paragraph' ],
* icon: 'dashicon-name',
* label: __( 'Menu item text' ),
* onClick: doOnClick,
* }
* );
* }
* ```
*
* @example
* ```jsx
* // Using ESNext syntax
* import { __ } from '@wordpress/i18n';
* import { PluginBlockSettingsMenuItem } from '@wordpress/edit-post';
*
* const doOnClick = ( ) => {
* // To be called when the user clicks the menu item.
* };
*
* const MyPluginBlockSettingsMenuItem = () => (
* <PluginBlockSettingsMenuItem
* allowedBlocks={ [ 'core/paragraph' ] }
* icon='dashicon-name'
* label={ __( 'Menu item text' ) }
* onClick={ doOnClick } />
* );
* ```
*
* @return {WPComponent} The component to be rendered.
*/
const PluginBlockSettingsMenuItem = _ref => {
let {
allowedBlocks,
icon,
label,
onClick,
small,
role
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockSettingsMenuControls, null, _ref2 => {
let {
selectedBlocks,
onClose
} = _ref2;
if (!shouldRenderItem(selectedBlocks, allowedBlocks)) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
onClick: (0,external_wp_compose_namespaceObject.compose)(onClick, onClose),
icon: icon,
label: small ? label : undefined,
role: role
}, !small && label);
});
};
/* harmony default export */ var plugin_block_settings_menu_item = (PluginBlockSettingsMenuItem);
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/header/plugin-more-menu-item/index.js
/**
* WordPress dependencies
*/
/**
* Renders a menu item in `Plugins` group in `More Menu` drop down, and can be used to as a button or link depending on the props provided.
* The text within the component appears as the menu item label.
*
* @param {Object} props Component properties.
* @param {string} [props.href] When `href` is provided then the menu item is represented as an anchor rather than button. It corresponds to the `href` attribute of the anchor.
* @param {WPBlockTypeIconRender} [props.icon=inherits from the plugin] The [Dashicon](https://developer.wordpress.org/resource/dashicons/) icon slug string, or an SVG WP element, to be rendered to the left of the menu item label.
* @param {Function} [props.onClick=noop] The callback function to be executed when the user clicks the menu item.
* @param {...*} [props.other] Any additional props are passed through to the underlying [MenuItem](https://github.com/WordPress/gutenberg/tree/HEAD/packages/components/src/menu-item/README.md) component.
*
* @example
* ```js
* // Using ES5 syntax
* var __ = wp.i18n.__;
* var PluginMoreMenuItem = wp.editPost.PluginMoreMenuItem;
* var moreIcon = wp.element.createElement( 'svg' ); //... svg element.
*
* function onButtonClick() {
* alert( 'Button clicked.' );
* }
*
* function MyButtonMoreMenuItem() {
* return wp.element.createElement(
* PluginMoreMenuItem,
* {
* icon: moreIcon,
* onClick: onButtonClick,
* },
* __( 'My button title' )
* );
* }
* ```
*
* @example
* ```jsx
* // Using ESNext syntax
* import { __ } from '@wordpress/i18n';
* import { PluginMoreMenuItem } from '@wordpress/edit-post';
* import { more } from '@wordpress/icons';
*
* function onButtonClick() {
* alert( 'Button clicked.' );
* }
*
* const MyButtonMoreMenuItem = () => (
* <PluginMoreMenuItem
* icon={ more }
* onClick={ onButtonClick }
* >
* { __( 'My button title' ) }
* </PluginMoreMenuItem>
* );
* ```
*
* @return {WPComponent} The component to be rendered.
*/
/* harmony default export */ var plugin_more_menu_item = ((0,external_wp_compose_namespaceObject.compose)((0,external_wp_plugins_namespaceObject.withPluginContext)((context, ownProps) => {
var _ownProps$as;
return {
as: (_ownProps$as = ownProps.as) !== null && _ownProps$as !== void 0 ? _ownProps$as : external_wp_components_namespaceObject.MenuItem,
icon: ownProps.icon || context.icon,
name: 'core/edit-post/plugin-more-menu'
};
}))(action_item));
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/components/header/plugin-sidebar-more-menu-item/index.js
/**
* WordPress dependencies
*/
/**
* Renders a menu item in `Plugins` group in `More Menu` drop down,
* and can be used to activate the corresponding `PluginSidebar` component.
* The text within the component appears as the menu item label.
*
* @param {Object} props Component props.
* @param {string} props.target A string identifying the target sidebar you wish to be activated by this menu item. Must be the same as the `name` prop you have given to that sidebar.
* @param {WPBlockTypeIconRender} [props.icon=inherits from the plugin] The [Dashicon](https://developer.wordpress.org/resource/dashicons/) icon slug string, or an SVG WP element, to be rendered to the left of the menu item label.
*
* @example
* ```js
* // Using ES5 syntax
* var __ = wp.i18n.__;
* var PluginSidebarMoreMenuItem = wp.editPost.PluginSidebarMoreMenuItem;
* var moreIcon = wp.element.createElement( 'svg' ); //... svg element.
*
* function MySidebarMoreMenuItem() {
* return wp.element.createElement(
* PluginSidebarMoreMenuItem,
* {
* target: 'my-sidebar',
* icon: moreIcon,
* },
* __( 'My sidebar title' )
* )
* }
* ```
*
* @example
* ```jsx
* // Using ESNext syntax
* import { __ } from '@wordpress/i18n';
* import { PluginSidebarMoreMenuItem } from '@wordpress/edit-post';
* import { more } from '@wordpress/icons';
*
* const MySidebarMoreMenuItem = () => (
* <PluginSidebarMoreMenuItem
* target="my-sidebar"
* icon={ more }
* >
* { __( 'My sidebar title' ) }
* </PluginSidebarMoreMenuItem>
* );
* ```
*
* @return {WPComponent} The component to be rendered.
*/
function PluginSidebarMoreMenuItem(props) {
return (0,external_wp_element_namespaceObject.createElement)(ComplementaryAreaMoreMenuItem // Menu item is marked with unstable prop for backward compatibility.
// @see https://github.com/WordPress/gutenberg/issues/14457
, _extends({
__unstableExplicitMenuItem: true,
scope: "core/edit-post"
}, props));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/edit-post/build-module/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Initializes and returns an instance of Editor.
*
* @param {string} id Unique identifier for editor instance.
* @param {string} postType Post type of the post to edit.
* @param {Object} postId ID of the post to edit.
* @param {?Object} settings Editor settings object.
* @param {Object} initialEdits Programmatic edits to apply initially, to be
* considered as non-user-initiated (bypass for
* unsaved changes prompt).
*/
function initializeEditor(id, postType, postId, settings, initialEdits) {
const target = document.getElementById(id);
const root = (0,external_wp_element_namespaceObject.createRoot)(target);
(0,external_wp_data_namespaceObject.dispatch)(external_wp_preferences_namespaceObject.store).setDefaults('core/edit-post', {
editorMode: 'visual',
fixedToolbar: false,
fullscreenMode: true,
hiddenBlockTypes: [],
inactivePanels: [],
isPublishSidebarEnabled: true,
openPanels: ['post-status'],
preferredStyleVariations: {},
showBlockBreadcrumbs: true,
showIconLabels: false,
showListViewByDefault: false,
themeStyles: true,
welcomeGuide: true,
welcomeGuideTemplate: true
});
(0,external_wp_data_namespaceObject.dispatch)(external_wp_blocks_namespaceObject.store).__experimentalReapplyBlockTypeFilters(); // Check if the block list view should be open by default.
if ((0,external_wp_data_namespaceObject.select)(store_store).isFeatureActive('showListViewByDefault')) {
(0,external_wp_data_namespaceObject.dispatch)(store_store).setIsListViewOpened(true);
}
(0,external_wp_blockLibrary_namespaceObject.registerCoreBlocks)();
(0,external_wp_widgets_namespaceObject.registerLegacyWidgetBlock)({
inserter: false
});
(0,external_wp_widgets_namespaceObject.registerWidgetGroupBlock)({
inserter: false
});
if (false) {}
/*
* Prevent adding template part in the post editor.
* Only add the filter when the post editor is initialized, not imported.
* Also only add the filter(s) after registerCoreBlocks()
* so that common filters in the block library are not overwritten.
*/
(0,external_wp_hooks_namespaceObject.addFilter)('blockEditor.__unstableCanInsertBlockType', 'removeTemplatePartsFromInserter', (canInsert, blockType) => {
if (!(0,external_wp_data_namespaceObject.select)(store_store).isEditingTemplate() && blockType.name === 'core/template-part') {
return false;
}
return canInsert;
}); // Show a console log warning if the browser is not in Standards rendering mode.
const documentMode = document.compatMode === 'CSS1Compat' ? 'Standards' : 'Quirks';
if (documentMode !== 'Standards') {
// eslint-disable-next-line no-console
console.warn("Your browser is using Quirks Mode. \nThis can cause rendering issues such as blocks overlaying meta boxes in the editor. Quirks Mode can be triggered by PHP errors or HTML code appearing before the opening <!DOCTYPE html>. Try checking the raw page source or your site's PHP error log and resolving errors there, removing any HTML before the doctype, or disabling plugins.");
} // This is a temporary fix for a couple of issues specific to Webkit on iOS.
// Without this hack the browser scrolls the mobile toolbar off-screen.
// Once supported in Safari we can replace this in favor of preventScroll.
// For details see issue #18632 and PR #18686
// Specifically, we scroll `interface-interface-skeleton__body` to enable a fixed top toolbar.
// But Mobile Safari forces the `html` element to scroll upwards, hiding the toolbar.
const isIphone = window.navigator.userAgent.indexOf('iPhone') !== -1;
if (isIphone) {
window.addEventListener('scroll', event => {
const editorScrollContainer = document.getElementsByClassName('interface-interface-skeleton__body')[0];
if (event.target === document) {
// Scroll element into view by scrolling the editor container by the same amount
// that Mobile Safari tried to scroll the html element upwards.
if (window.scrollY > 100) {
editorScrollContainer.scrollTop = editorScrollContainer.scrollTop + window.scrollY;
} // Undo unwanted scroll on html element, but only in the visual editor.
if (document.getElementsByClassName('is-mode-visual')[0]) {
window.scrollTo(0, 0);
}
}
});
} // Prevent the default browser action for files dropped outside of dropzones.
window.addEventListener('dragover', e => e.preventDefault(), false);
window.addEventListener('drop', e => e.preventDefault(), false);
root.render((0,external_wp_element_namespaceObject.createElement)(editor, {
settings: settings,
postId: postId,
postType: postType,
initialEdits: initialEdits
}));
return root;
}
/**
* Used to reinitialize the editor after an error. Now it's a deprecated noop function.
*/
function reinitializeEditor() {
external_wp_deprecated_default()('wp.editPost.reinitializeEditor', {
since: '6.2',
version: '6.3'
});
}
}();
(window.wp = window.wp || {}).editPost = __webpack_exports__;
/******/ })()
; shortcode.js 0000666 00000041177 15123355174 0007120 0 ustar 00 /******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 9756:
/***/ (function(module) {
/**
* Memize options object.
*
* @typedef MemizeOptions
*
* @property {number} [maxSize] Maximum size of the cache.
*/
/**
* Internal cache entry.
*
* @typedef MemizeCacheNode
*
* @property {?MemizeCacheNode|undefined} [prev] Previous node.
* @property {?MemizeCacheNode|undefined} [next] Next node.
* @property {Array<*>} args Function arguments for cache
* entry.
* @property {*} val Function result.
*/
/**
* Properties of the enhanced function for controlling cache.
*
* @typedef MemizeMemoizedFunction
*
* @property {()=>void} clear Clear the cache.
*/
/**
* Accepts a function to be memoized, and returns a new memoized function, with
* optional options.
*
* @template {Function} F
*
* @param {F} fn Function to memoize.
* @param {MemizeOptions} [options] Options object.
*
* @return {F & MemizeMemoizedFunction} Memoized function.
*/
function memize( fn, options ) {
var size = 0;
/** @type {?MemizeCacheNode|undefined} */
var head;
/** @type {?MemizeCacheNode|undefined} */
var tail;
options = options || {};
function memoized( /* ...args */ ) {
var node = head,
len = arguments.length,
args, i;
searchCache: while ( node ) {
// Perform a shallow equality test to confirm that whether the node
// under test is a candidate for the arguments passed. Two arrays
// are shallowly equal if their length matches and each entry is
// strictly equal between the two sets. Avoid abstracting to a
// function which could incur an arguments leaking deoptimization.
// Check whether node arguments match arguments length
if ( node.args.length !== arguments.length ) {
node = node.next;
continue;
}
// Check whether node arguments match arguments values
for ( i = 0; i < len; i++ ) {
if ( node.args[ i ] !== arguments[ i ] ) {
node = node.next;
continue searchCache;
}
}
// At this point we can assume we've found a match
// Surface matched node to head if not already
if ( node !== head ) {
// As tail, shift to previous. Must only shift if not also
// head, since if both head and tail, there is no previous.
if ( node === tail ) {
tail = node.prev;
}
// Adjust siblings to point to each other. If node was tail,
// this also handles new tail's empty `next` assignment.
/** @type {MemizeCacheNode} */ ( node.prev ).next = node.next;
if ( node.next ) {
node.next.prev = node.prev;
}
node.next = head;
node.prev = null;
/** @type {MemizeCacheNode} */ ( head ).prev = node;
head = node;
}
// Return immediately
return node.val;
}
// No cached value found. Continue to insertion phase:
// Create a copy of arguments (avoid leaking deoptimization)
args = new Array( len );
for ( i = 0; i < len; i++ ) {
args[ i ] = arguments[ i ];
}
node = {
args: args,
// Generate the result from original function
val: fn.apply( null, args ),
};
// Don't need to check whether node is already head, since it would
// have been returned above already if it was
// Shift existing head down list
if ( head ) {
head.prev = node;
node.next = head;
} else {
// If no head, follows that there's no tail (at initial or reset)
tail = node;
}
// Trim tail if we're reached max size and are pending cache insertion
if ( size === /** @type {MemizeOptions} */ ( options ).maxSize ) {
tail = /** @type {MemizeCacheNode} */ ( tail ).prev;
/** @type {MemizeCacheNode} */ ( tail ).next = null;
} else {
size++;
}
head = node;
return node.val;
}
memoized.clear = function() {
head = null;
tail = null;
size = 0;
};
if ( false ) {}
// Ignore reason: There's not a clear solution to create an intersection of
// the function with additional properties, where the goal is to retain the
// function signature of the incoming argument and add control properties
// on the return value.
// @ts-ignore
return memoized;
}
module.exports = memize;
/***/ })
/******/ });
/************************************************************************/
/******/ // 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); }
/******/ }();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be in strict mode.
!function() {
"use strict";
/* unused harmony exports next, replace, string, regexp, attrs, fromMatch */
/* harmony import */ var memize__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9756);
/* harmony import */ var memize__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(memize__WEBPACK_IMPORTED_MODULE_0__);
/**
* External dependencies
*/
/**
* Shortcode attributes object.
*
* @typedef {Object} WPShortcodeAttrs
*
* @property {Object} named Object with named attributes.
* @property {Array} numeric Array with numeric attributes.
*/
/**
* Shortcode object.
*
* @typedef {Object} WPShortcode
*
* @property {string} tag Shortcode tag.
* @property {WPShortcodeAttrs} attrs Shortcode attributes.
* @property {string} content Shortcode content.
* @property {string} type Shortcode type: `self-closing`,
* `closed`, or `single`.
*/
/**
* @typedef {Object} WPShortcodeMatch
*
* @property {number} index Index the shortcode is found at.
* @property {string} content Matched content.
* @property {WPShortcode} shortcode Shortcode instance of the match.
*/
/**
* Find the next matching shortcode.
*
* @param {string} tag Shortcode tag.
* @param {string} text Text to search.
* @param {number} index Index to start search from.
*
* @return {WPShortcodeMatch | undefined} Matched information.
*/
function next(tag, text) {
let index = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 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 ('[' === 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 (match[1]) {
result.content = result.content.slice(1);
result.index++;
} // 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.
*
* @param {string} tag Shortcode tag.
* @param {string} text Text to search.
* @param {Function} callback Function to process the match and return
* replacement string.
*
* @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.
const result = callback(fromMatch(arguments)); // 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.
*
* Creates a shortcode instance and returns a string.
*
* Accepts the same `options` as the `shortcode()` constructor, containing a
* `tag` string, a string or object of `attrs`, a boolean indicating whether to
* format the shortcode using a `single` tag, and a `content` string.
*
* @param {Object} options
*
* @return {string} String representation of the shortcode.
*/
function string(options) {
return new shortcode(options).string();
}
/**
* Generate a RegExp to identify a shortcode.
*
* The base regex is functionally equivalent to the one found in
* `get_shortcode_regex()` in `wp-includes/shortcodes.php`.
*
* Capture groups:
*
* 1. An extra `[` to allow for escaping shortcodes with double `[[]]`
* 2. The shortcode name
* 3. The shortcode argument list
* 4. The self closing `/`
* 5. The content of a shortcode when it wraps some content.
* 6. The closing tag.
* 7. An extra `]` to allow for escaping shortcodes with double `[[]]`
*
* @param {string} tag Shortcode tag.
*
* @return {RegExp} Shortcode RegExp.
*/
function regexp(tag) {
return new RegExp('\\[(\\[?)(' + tag + ')(?![\\w-])([^\\]\\/]*(?:\\/(?!\\])[^\\]\\/]*)*?)(?:(\\/)\\]|\\](?:([^\\[]*(?:\\[(?!\\/\\2\\])[^\\[]*)*)(\\[\\/\\2\\]))?)(\\]?)', 'g');
}
/**
* Parse shortcode attributes.
*
* Shortcodes accept many types of attributes. These can chiefly be divided into
* named and numeric attributes:
*
* Named attributes are assigned on a key/value basis, while numeric attributes
* are treated as an array.
*
* Named attributes can be formatted as either `name="value"`, `name='value'`,
* or `name=value`. Numeric attributes can be formatted as `"value"` or just
* `value`.
*
* @param {string} text Serialised shortcode attributes.
*
* @return {WPShortcodeAttrs} Parsed shortcode attributes.
*/
const attrs = memize__WEBPACK_IMPORTED_MODULE_0___default()(text => {
const named = {};
const numeric = []; // This regular expression is reused from `shortcode_parse_atts()` in
// `wp-includes/shortcodes.php`.
//
// Capture groups:
//
// 1. An attribute name, that corresponds to...
// 2. a value in double quotes.
// 3. An attribute name, that corresponds to...
// 4. a value in single quotes.
// 5. An attribute name, that corresponds to...
// 6. an unquoted value.
// 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; // Map zero-width spaces to actual spaces.
text = text.replace(/[\u00a0\u200b]/g, ' ');
let match; // Match and normalize attributes.
while (match = pattern.exec(text)) {
if (match[1]) {
named[match[1].toLowerCase()] = match[2];
} else if (match[3]) {
named[match[3].toLowerCase()] = match[4];
} else if (match[5]) {
named[match[5].toLowerCase()] = match[6];
} else if (match[7]) {
numeric.push(match[7]);
} else if (match[8]) {
numeric.push(match[8]);
} else if (match[9]) {
numeric.push(match[9]);
}
}
return {
named,
numeric
};
});
/**
* Generate a Shortcode Object from a RegExp match.
*
* Accepts a `match` object from calling `regexp.exec()` on a `RegExp` generated
* by `regexp()`. `match` can also be set to the `arguments` from a callback
* passed to `regexp.replace()`.
*
* @param {Array} match Match array.
*
* @return {WPShortcode} Shortcode instance.
*/
function fromMatch(match) {
let type;
if (match[4]) {
type = 'self-closing';
} else if (match[6]) {
type = 'closed';
} else {
type = 'single';
}
return new shortcode({
tag: match[2],
attrs: match[3],
type,
content: match[5]
});
}
/**
* Creates a shortcode instance.
*
* To access a raw representation of a shortcode, pass an `options` object,
* containing a `tag` string, a string or object of `attrs`, a string indicating
* the `type` of the shortcode ('single', 'self-closing', or 'closed'), and a
* `content` string.
*
* @param {Object} options Options as described.
*
* @return {WPShortcode} Shortcode instance.
*/
const shortcode = Object.assign(function (options) {
const {
tag,
attrs: attributes,
type,
content
} = options || {};
Object.assign(this, {
tag,
type,
content
}); // Ensure we have a correctly formatted `attrs` object.
this.attrs = {
named: {},
numeric: []
};
if (!attributes) {
return;
}
const attributeTypes = ['named', 'numeric']; // Parse a string of attributes.
if (typeof attributes === 'string') {
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.
} else {
Object.entries(attributes).forEach(_ref => {
let [key, value] = _ref;
this.set(key, value);
});
}
}, {
next,
replace,
string,
regexp,
attrs,
fromMatch
});
Object.assign(shortcode.prototype, {
/**
* Get a shortcode attribute.
*
* Automatically detects whether `attr` is named or numeric and routes it
* accordingly.
*
* @param {(number|string)} attr Attribute key.
*
* @return {string} Attribute value.
*/
get(attr) {
return this.attrs[typeof attr === 'number' ? 'numeric' : 'named'][attr];
},
/**
* Set a shortcode attribute.
*
* Automatically detects whether `attr` is named or numeric and routes it
* accordingly.
*
* @param {(number|string)} attr Attribute key.
* @param {string} value Attribute value.
*
* @return {WPShortcode} Shortcode instance.
*/
set(attr, value) {
this.attrs[typeof attr === 'number' ? 'numeric' : 'named'][attr] = value;
return this;
},
/**
* Transform the shortcode into a string.
*
* @return {string} String representation of the shortcode.
*/
string() {
let text = '[' + this.tag;
this.attrs.numeric.forEach(value => {
if (/\s/.test(value)) {
text += ' "' + value + '"';
} else {
text += ' ' + value;
}
});
Object.entries(this.attrs.named).forEach(_ref2 => {
let [name, value] = _ref2;
text += ' ' + name + '="' + value + '"';
}); // 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.
text += ']';
if (this.content) {
text += this.content;
} // Add the closing tag.
return text + '[/' + this.tag + ']';
}
});
/* harmony default export */ __webpack_exports__["default"] = (shortcode);
}();
(window.wp = window.wp || {}).shortcode = __webpack_exports__["default"];
/******/ })()
; style-engine.min.js 0000666 00000011401 15123355174 0010276 0 ustar 00 /*! This file is auto-generated */
!function(){"use strict";var e={d:function(t,n){for(var o in n)e.o(n,o)&&!e.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:n[o]})},o: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,{compileCSS:function(){return h},getCSSRules:function(){return y}});var n=window.lodash;const o="var:";function r(e,t,o,r){const a=(0,n.get)(e,o);return a?[{selector:null==t?void 0:t.selector,key:r,value:i(a)}]:[]}function a(e,t,o,r){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:["top","right","bottom","left"];const g=(0,n.get)(e,o);if(!g)return[];const u=[];if("string"==typeof g)u.push({selector:null==t?void 0:t.selector,key:r.default,value:g});else{const e=a.reduce(((e,o)=>{const a=i((0,n.get)(g,[o]));return a&&e.push({selector:null==t?void 0:t.selector,key:null==r?void 0:r.individual.replace("%s",l(o)),value:a}),e}),[]);u.push(...e)}return u}function i(e){if("string"==typeof e&&e.startsWith(o)){return`var(--wp--${e.slice(o.length).split("|").map((e=>(0,n.kebabCase)(e))).join("--")})`}return e}function l(e){const[t,...n]=e;return t.toUpperCase()+n.join("")}function g(e){return(t,n)=>r(t,n,e,function(e){const[t,...n]=e;return t.toLowerCase()+n.map(l).join("")}(e))}function u(e){return(t,n)=>["color","style","width"].flatMap((o=>g(["border",e,o])(t,n)))}const d={name:"radius",generate:(e,t)=>a(e,t,["border","radius"],{default:"borderRadius",individual:"border%sRadius"},["topLeft","topRight","bottomLeft","bottomRight"])};const c={name:"color",generate:function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:["outline","color"],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"outlineColor";return r(e,t,n,o)}},s={name:"offset",generate:function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:["outline","offset"],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"outlineOffset";return r(e,t,n,o)}},f={name:"style",generate:function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:["outline","style"],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"outlineStyle";return r(e,t,n,o)}},p={name:"width",generate:function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:["outline","width"],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"outlineWidth";return r(e,t,n,o)}};const m=[...[{name:"color",generate:g(["border","color"])},{name:"style",generate:g(["border","style"])},{name:"width",generate:g(["border","width"])},d,{name:"borderTop",generate:u("top")},{name:"borderRight",generate:u("right")},{name:"borderBottom",generate:u("bottom")},{name:"borderLeft",generate:u("left")}],...[{name:"text",generate:(e,t)=>r(e,t,["color","text"],"color")},{name:"gradient",generate:(e,t)=>r(e,t,["color","gradient"],"background")},{name:"background",generate:(e,t)=>r(e,t,["color","background"],"backgroundColor")}],...[{name:"minHeight",generate:(e,t)=>r(e,t,["dimensions","minHeight"],"minHeight")}],...[c,f,s,p],...[{name:"margin",generate:(e,t)=>a(e,t,["spacing","margin"],{default:"margin",individual:"margin%s"})},{name:"padding",generate:(e,t)=>a(e,t,["spacing","padding"],{default:"padding",individual:"padding%s"})}],...[{name:"fontFamily",generate:(e,t)=>r(e,t,["typography","fontFamily"],"fontFamily")},{name:"fontSize",generate:(e,t)=>r(e,t,["typography","fontSize"],"fontSize")},{name:"fontStyle",generate:(e,t)=>r(e,t,["typography","fontStyle"],"fontStyle")},{name:"fontWeight",generate:(e,t)=>r(e,t,["typography","fontWeight"],"fontWeight")},{name:"letterSpacing",generate:(e,t)=>r(e,t,["typography","letterSpacing"],"letterSpacing")},{name:"letterSpacing",generate:(e,t)=>r(e,t,["typography","lineHeight"],"lineHeight")},{name:"textColumns",generate:(e,t)=>r(e,t,["typography","textColumns"],"columnCount")},{name:"textDecoration",generate:(e,t)=>r(e,t,["typography","textDecoration"],"textDecoration")},{name:"textTransform",generate:(e,t)=>r(e,t,["typography","textTransform"],"textTransform")}],...[{name:"shadow",generate:(e,t)=>r(e,t,["shadow"],"boxShadow")}]];function h(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const o=y(e,t);if(null==t||!t.selector){const e=[];return o.forEach((t=>{e.push(`${(0,n.kebabCase)(t.key)}: ${t.value};`)})),e.join(" ")}const r=(0,n.groupBy)(o,"selector"),a=Object.keys(r).reduce(((e,t)=>(e.push(`${t} { ${r[t].map((e=>`${(0,n.kebabCase)(e.key)}: ${e.value};`)).join(" ")} }`),e)),[]);return a.join("\n")}function y(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=[];return m.forEach((o=>{"function"==typeof o.generate&&n.push(...o.generate(e,t))})),n}(window.wp=window.wp||{}).styleEngine=t}(); dom.js 0000666 00000173002 15123355174 0005676 0 ustar 00 /******/ (function() { // webpackBootstrap
/******/ "use strict";
/******/ // The require scope
/******/ var __webpack_require__ = {};
/******/
/************************************************************************/
/******/ /* 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__ = {};
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"__unstableStripHTML": function() { return /* reexport */ stripHTML; },
"computeCaretRect": function() { return /* reexport */ computeCaretRect; },
"documentHasSelection": function() { return /* reexport */ documentHasSelection; },
"documentHasTextSelection": function() { return /* reexport */ documentHasTextSelection; },
"documentHasUncollapsedSelection": function() { return /* reexport */ documentHasUncollapsedSelection; },
"focus": function() { return /* binding */ build_module_focus; },
"getFilesFromDataTransfer": function() { return /* reexport */ getFilesFromDataTransfer; },
"getOffsetParent": function() { return /* reexport */ getOffsetParent; },
"getPhrasingContentSchema": function() { return /* reexport */ getPhrasingContentSchema; },
"getRectangleFromRange": function() { return /* reexport */ getRectangleFromRange; },
"getScrollContainer": function() { return /* reexport */ getScrollContainer; },
"insertAfter": function() { return /* reexport */ insertAfter; },
"isEmpty": function() { return /* reexport */ isEmpty; },
"isEntirelySelected": function() { return /* reexport */ isEntirelySelected; },
"isFormElement": function() { return /* reexport */ isFormElement; },
"isHorizontalEdge": function() { return /* reexport */ isHorizontalEdge; },
"isNumberInput": function() { return /* reexport */ isNumberInput; },
"isPhrasingContent": function() { return /* reexport */ isPhrasingContent; },
"isRTL": function() { return /* reexport */ isRTL; },
"isTextContent": function() { return /* reexport */ isTextContent; },
"isTextField": function() { return /* reexport */ isTextField; },
"isVerticalEdge": function() { return /* reexport */ isVerticalEdge; },
"placeCaretAtHorizontalEdge": function() { return /* reexport */ placeCaretAtHorizontalEdge; },
"placeCaretAtVerticalEdge": function() { return /* reexport */ placeCaretAtVerticalEdge; },
"remove": function() { return /* reexport */ remove; },
"removeInvalidHTML": function() { return /* reexport */ removeInvalidHTML; },
"replace": function() { return /* reexport */ replace; },
"replaceTag": function() { return /* reexport */ replaceTag; },
"safeHTML": function() { return /* reexport */ safeHTML; },
"unwrap": function() { return /* reexport */ unwrap; },
"wrap": function() { return /* reexport */ wrap; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/dom/build-module/focusable.js
var focusable_namespaceObject = {};
__webpack_require__.r(focusable_namespaceObject);
__webpack_require__.d(focusable_namespaceObject, {
"find": function() { return find; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/dom/build-module/tabbable.js
var tabbable_namespaceObject = {};
__webpack_require__.r(tabbable_namespaceObject);
__webpack_require__.d(tabbable_namespaceObject, {
"find": function() { return tabbable_find; },
"findNext": function() { return findNext; },
"findPrevious": function() { return findPrevious; },
"isTabbableIndex": function() { return isTabbableIndex; }
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/focusable.js
/**
* References:
*
* Focusable:
* - https://www.w3.org/TR/html5/editing.html#focus-management
*
* Sequential focus navigation:
* - https://www.w3.org/TR/html5/editing.html#sequential-focus-navigation-and-the-tabindex-attribute
*
* Disabled elements:
* - https://www.w3.org/TR/html5/disabled-elements.html#disabled-elements
*
* getClientRects algorithm (requiring layout box):
* - https://www.w3.org/TR/cssom-view-1/#extension-to-the-element-interface
*
* AREA elements associated with an IMG:
* - https://w3c.github.io/html/editing.html#data-model
*/
/**
* Returns a CSS selector used to query for focusable elements.
*
* @param {boolean} sequential If set, only query elements that are sequentially
* focusable. Non-interactive elements with a
* negative `tabindex` are focusable but not
* sequentially focusable.
* https://html.spec.whatwg.org/multipage/interaction.html#the-tabindex-attribute
*
* @return {string} CSS selector.
*/
function buildSelector(sequential) {
return [sequential ? '[tabindex]:not([tabindex^="-"])' : '[tabindex]', 'a[href]', 'button:not([disabled])', 'input:not([type="hidden"]):not([disabled])', 'select:not([disabled])', 'textarea:not([disabled])', 'iframe:not([tabindex^="-"])', 'object', 'embed', 'area[href]', '[contenteditable]:not([contenteditable=false])'].join(',');
}
/**
* Returns true if the specified element is visible (i.e. neither display: none
* nor visibility: hidden).
*
* @param {HTMLElement} element DOM element to test.
*
* @return {boolean} Whether element is visible.
*/
function isVisible(element) {
return element.offsetWidth > 0 || element.offsetHeight > 0 || element.getClientRects().length > 0;
}
/**
* Returns true if the specified area element is a valid focusable element, or
* false otherwise. Area is only focusable if within a map where a named map
* referenced by an image somewhere in the document.
*
* @param {HTMLAreaElement} element DOM area element to test.
*
* @return {boolean} Whether area element is valid for focus.
*/
function isValidFocusableArea(element) {
/** @type {HTMLMapElement | null} */
const map = element.closest('map[name]');
if (!map) {
return false;
}
/** @type {HTMLImageElement | null} */
const img = element.ownerDocument.querySelector('img[usemap="#' + map.name + '"]');
return !!img && isVisible(img);
}
/**
* Returns all focusable elements within a given context.
*
* @param {Element} context Element in which to search.
* @param {Object} [options]
* @param {boolean} [options.sequential] If set, only return elements that are
* sequentially focusable.
* Non-interactive elements with a
* negative `tabindex` are focusable but
* not sequentially focusable.
* https://html.spec.whatwg.org/multipage/interaction.html#the-tabindex-attribute
*
* @return {Element[]} Focusable elements.
*/
function find(context) {
let {
sequential = false
} = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
/* eslint-disable jsdoc/no-undefined-types */
/** @type {NodeListOf<HTMLElement>} */
/* eslint-enable jsdoc/no-undefined-types */
const elements = context.querySelectorAll(buildSelector(sequential));
return Array.from(elements).filter(element => {
if (!isVisible(element)) {
return false;
}
const {
nodeName
} = element;
if ('AREA' === nodeName) {
return isValidFocusableArea(
/** @type {HTMLAreaElement} */
element);
}
return true;
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/tabbable.js
/**
* Internal dependencies
*/
/**
* Returns the tab index of the given element. In contrast with the tabIndex
* property, this normalizes the default (0) to avoid browser inconsistencies,
* operating under the assumption that this function is only ever called with a
* focusable node.
*
* @see https://bugzilla.mozilla.org/show_bug.cgi?id=1190261
*
* @param {Element} element Element from which to retrieve.
*
* @return {number} Tab index of element (default 0).
*/
function getTabIndex(element) {
const tabIndex = element.getAttribute('tabindex');
return tabIndex === null ? 0 : parseInt(tabIndex, 10);
}
/**
* Returns true if the specified element is tabbable, or false otherwise.
*
* @param {Element} element Element to test.
*
* @return {boolean} Whether element is tabbable.
*/
function isTabbableIndex(element) {
return getTabIndex(element) !== -1;
}
/** @typedef {Element & { type?: string, checked?: boolean, name?: string }} MaybeHTMLInputElement */
/**
* Returns a stateful reducer function which constructs a filtered array of
* tabbable elements, where at most one radio input is selected for a given
* name, giving priority to checked input, falling back to the first
* encountered.
*
* @return {(acc: MaybeHTMLInputElement[], el: MaybeHTMLInputElement) => MaybeHTMLInputElement[]} Radio group collapse reducer.
*/
function createStatefulCollapseRadioGroup() {
/** @type {Record<string, MaybeHTMLInputElement>} */
const CHOSEN_RADIO_BY_NAME = {};
return function collapseRadioGroup(
/** @type {MaybeHTMLInputElement[]} */
result,
/** @type {MaybeHTMLInputElement} */
element) {
const {
nodeName,
type,
checked,
name
} = element; // For all non-radio tabbables, construct to array by concatenating.
if (nodeName !== 'INPUT' || type !== 'radio' || !name) {
return result.concat(element);
}
const hasChosen = CHOSEN_RADIO_BY_NAME.hasOwnProperty(name); // Omit by skipping concatenation if the radio element is not chosen.
const isChosen = checked || !hasChosen;
if (!isChosen) {
return result;
} // At this point, if there had been a chosen element, the current
// element is checked and should take priority. Retroactively remove
// the element which had previously been considered the chosen one.
if (hasChosen) {
const hadChosenElement = CHOSEN_RADIO_BY_NAME[name];
result = result.filter(e => e !== hadChosenElement);
}
CHOSEN_RADIO_BY_NAME[name] = element;
return result.concat(element);
};
}
/**
* An array map callback, returning an object with the element value and its
* array index location as properties. This is used to emulate a proper stable
* sort where equal tabIndex should be left in order of their occurrence in the
* document.
*
* @param {Element} element Element.
* @param {number} index Array index of element.
*
* @return {{ element: Element, index: number }} Mapped object with element, index.
*/
function mapElementToObjectTabbable(element, index) {
return {
element,
index
};
}
/**
* An array map callback, returning an element of the given mapped object's
* element value.
*
* @param {{ element: Element }} object Mapped object with element.
*
* @return {Element} Mapped object element.
*/
function mapObjectTabbableToElement(object) {
return object.element;
}
/**
* A sort comparator function used in comparing two objects of mapped elements.
*
* @see mapElementToObjectTabbable
*
* @param {{ element: Element, index: number }} a First object to compare.
* @param {{ element: Element, index: number }} b Second object to compare.
*
* @return {number} Comparator result.
*/
function compareObjectTabbables(a, b) {
const aTabIndex = getTabIndex(a.element);
const bTabIndex = getTabIndex(b.element);
if (aTabIndex === bTabIndex) {
return a.index - b.index;
}
return aTabIndex - bTabIndex;
}
/**
* Givin focusable elements, filters out tabbable element.
*
* @param {Element[]} focusables Focusable elements to filter.
*
* @return {Element[]} Tabbable elements.
*/
function filterTabbable(focusables) {
return focusables.filter(isTabbableIndex).map(mapElementToObjectTabbable).sort(compareObjectTabbables).map(mapObjectTabbableToElement).reduce(createStatefulCollapseRadioGroup(), []);
}
/**
* @param {Element} context
* @return {Element[]} Tabbable elements within the context.
*/
function tabbable_find(context) {
return filterTabbable(find(context));
}
/**
* Given a focusable element, find the preceding tabbable element.
*
* @param {Element} element The focusable element before which to look. Defaults
* to the active element.
*
* @return {Element|undefined} Preceding tabbable element.
*/
function findPrevious(element) {
return filterTabbable(find(element.ownerDocument.body)).reverse().find(focusable => {
return (// eslint-disable-next-line no-bitwise
element.compareDocumentPosition(focusable) & element.DOCUMENT_POSITION_PRECEDING
);
});
}
/**
* Given a focusable element, find the next tabbable element.
*
* @param {Element} element The focusable element after which to look. Defaults
* to the active element.
*
* @return {Element|undefined} Next tabbable element.
*/
function findNext(element) {
return filterTabbable(find(element.ownerDocument.body)).find(focusable => {
return (// eslint-disable-next-line no-bitwise
element.compareDocumentPosition(focusable) & element.DOCUMENT_POSITION_FOLLOWING
);
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/utils/assert-is-defined.js
function assertIsDefined(val, name) {
if (false) {}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/get-rectangle-from-range.js
/**
* Internal dependencies
*/
/**
* Get the rectangle of a given Range. Returns `null` if no suitable rectangle
* can be found.
*
* @param {Range} range The range.
*
* @return {DOMRect?} The rectangle.
*/
function getRectangleFromRange(range) {
// For uncollapsed ranges, get the rectangle that bounds the contents of the
// range; this a rectangle enclosing the union of the bounding rectangles
// for all the elements in the range.
if (!range.collapsed) {
const rects = Array.from(range.getClientRects()); // If there's just a single rect, return it.
if (rects.length === 1) {
return rects[0];
} // Ignore tiny selection at the edge of a range.
const filteredRects = rects.filter(_ref => {
let {
width
} = _ref;
return width > 1;
}); // If it's full of tiny selections, return browser default.
if (filteredRects.length === 0) {
return range.getBoundingClientRect();
}
if (filteredRects.length === 1) {
return filteredRects[0];
}
let {
top: furthestTop,
bottom: furthestBottom,
left: furthestLeft,
right: furthestRight
} = filteredRects[0];
for (const {
top,
bottom,
left,
right
} of filteredRects) {
if (top < furthestTop) furthestTop = top;
if (bottom > furthestBottom) furthestBottom = bottom;
if (left < furthestLeft) furthestLeft = left;
if (right > furthestRight) furthestRight = right;
}
return new window.DOMRect(furthestLeft, furthestTop, furthestRight - furthestLeft, furthestBottom - furthestTop);
}
const {
startContainer
} = range;
const {
ownerDocument
} = startContainer; // Correct invalid "BR" ranges. The cannot contain any children.
if (startContainer.nodeName === 'BR') {
const {
parentNode
} = startContainer;
assertIsDefined(parentNode, 'parentNode');
const index =
/** @type {Node[]} */
Array.from(parentNode.childNodes).indexOf(startContainer);
assertIsDefined(ownerDocument, 'ownerDocument');
range = ownerDocument.createRange();
range.setStart(parentNode, index);
range.setEnd(parentNode, index);
}
const rects = range.getClientRects(); // If we have multiple rectangles for a collapsed range, there's no way to
// know which it is, so don't return anything.
if (rects.length > 1) {
return null;
}
let rect = rects[0]; // If the collapsed range starts (and therefore ends) at an element node,
// `getClientRects` can be empty in some browsers. This can be resolved
// by adding a temporary text node with zero-width space to the range.
//
// See: https://stackoverflow.com/a/6847328/995445
if (!rect) {
assertIsDefined(ownerDocument, 'ownerDocument');
const padNode = ownerDocument.createTextNode('\u200b'); // Do not modify the live range.
range = range.cloneRange();
range.insertNode(padNode);
rect = range.getClientRects()[0];
assertIsDefined(padNode.parentNode, 'padNode.parentNode');
padNode.parentNode.removeChild(padNode);
}
return rect;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/compute-caret-rect.js
/**
* Internal dependencies
*/
/**
* Get the rectangle for the selection in a container.
*
* @param {Window} win The window of the selection.
*
* @return {DOMRect | null} The rectangle.
*/
function computeCaretRect(win) {
const selection = win.getSelection();
assertIsDefined(selection, 'selection');
const range = selection.rangeCount ? selection.getRangeAt(0) : null;
if (!range) {
return null;
}
return getRectangleFromRange(range);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/document-has-text-selection.js
/**
* Internal dependencies
*/
/**
* Check whether the current document has selected text. This applies to ranges
* of text in the document, and not selection inside `<input>` and `<textarea>`
* elements.
*
* See: https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection#Related_objects.
*
* @param {Document} doc The document to check.
*
* @return {boolean} True if there is selection, false if not.
*/
function documentHasTextSelection(doc) {
assertIsDefined(doc.defaultView, 'doc.defaultView');
const selection = doc.defaultView.getSelection();
assertIsDefined(selection, 'selection');
const range = selection.rangeCount ? selection.getRangeAt(0) : null;
return !!range && !range.collapsed;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/is-html-input-element.js
/* eslint-disable jsdoc/valid-types */
/**
* @param {Node} node
* @return {node is HTMLInputElement} Whether the node is an HTMLInputElement.
*/
function isHTMLInputElement(node) {
/* eslint-enable jsdoc/valid-types */
return (node === null || node === void 0 ? void 0 : node.nodeName) === 'INPUT';
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/is-text-field.js
/**
* Internal dependencies
*/
/* eslint-disable jsdoc/valid-types */
/**
* Check whether the given element is a text field, where text field is defined
* by the ability to select within the input, or that it is contenteditable.
*
* See: https://html.spec.whatwg.org/#textFieldSelection
*
* @param {Node} node The HTML element.
* @return {node is HTMLElement} True if the element is an text field, false if not.
*/
function isTextField(node) {
/* eslint-enable jsdoc/valid-types */
const nonTextInputs = ['button', 'checkbox', 'hidden', 'file', 'radio', 'image', 'range', 'reset', 'submit', 'number', 'email', 'time'];
return isHTMLInputElement(node) && node.type && !nonTextInputs.includes(node.type) || node.nodeName === 'TEXTAREA' ||
/** @type {HTMLElement} */
node.contentEditable === 'true';
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/input-field-has-uncollapsed-selection.js
/**
* Internal dependencies
*/
/**
* Check whether the given input field or textarea contains a (uncollapsed)
* selection of text.
*
* CAVEAT: Only specific text-based HTML inputs support the selection APIs
* needed to determine whether they have a collapsed or uncollapsed selection.
* This function defaults to returning `true` when the selection cannot be
* inspected, such as with `<input type="time">`. The rationale is that this
* should cause the block editor to defer to the browser's native selection
* handling (e.g. copying and pasting), thereby reducing friction for the user.
*
* See: https://html.spec.whatwg.org/multipage/input.html#do-not-apply
*
* @param {Element} element The HTML element.
*
* @return {boolean} Whether the input/textareaa element has some "selection".
*/
function inputFieldHasUncollapsedSelection(element) {
if (!isHTMLInputElement(element) && !isTextField(element)) {
return false;
} // Safari throws a type error when trying to get `selectionStart` and
// `selectionEnd` on non-text <input> elements, so a try/catch construct is
// necessary.
try {
const {
selectionStart,
selectionEnd
} =
/** @type {HTMLInputElement | HTMLTextAreaElement} */
element;
return (// `null` means the input type doesn't implement selection, thus we
// cannot determine whether the selection is collapsed, so we
// default to true.
selectionStart === null || // when not null, compare the two points
selectionStart !== selectionEnd
);
} catch (error) {
// This is Safari's way of saying that the input type doesn't implement
// selection, so we default to true.
return true;
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/document-has-uncollapsed-selection.js
/**
* Internal dependencies
*/
/**
* Check whether the current document has any sort of (uncollapsed) selection.
* This includes ranges of text across elements and any selection inside
* textual `<input>` and `<textarea>` elements.
*
* @param {Document} doc The document to check.
*
* @return {boolean} Whether there is any recognizable text selection in the document.
*/
function documentHasUncollapsedSelection(doc) {
return documentHasTextSelection(doc) || !!doc.activeElement && inputFieldHasUncollapsedSelection(doc.activeElement);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/document-has-selection.js
/**
* Internal dependencies
*/
/**
* Check whether the current document has a selection. This includes focus in
* input fields, textareas, and general rich-text selection.
*
* @param {Document} doc The document to check.
*
* @return {boolean} True if there is selection, false if not.
*/
function documentHasSelection(doc) {
return !!doc.activeElement && (isHTMLInputElement(doc.activeElement) || isTextField(doc.activeElement) || documentHasTextSelection(doc));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/get-computed-style.js
/**
* Internal dependencies
*/
/* eslint-disable jsdoc/valid-types */
/**
* @param {Element} element
* @return {ReturnType<Window['getComputedStyle']>} The computed style for the element.
*/
function getComputedStyle(element) {
/* eslint-enable jsdoc/valid-types */
assertIsDefined(element.ownerDocument.defaultView, 'element.ownerDocument.defaultView');
return element.ownerDocument.defaultView.getComputedStyle(element);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/get-scroll-container.js
/**
* Internal dependencies
*/
/**
* Given a DOM node, finds the closest scrollable container node.
*
* @param {Element | null} node Node from which to start.
*
* @return {Element | undefined} Scrollable container node, if found.
*/
function getScrollContainer(node) {
if (!node) {
return undefined;
} // Scrollable if scrollable height exceeds displayed...
if (node.scrollHeight > node.clientHeight) {
// ...except when overflow is defined to be hidden or visible
const {
overflowY
} = getComputedStyle(node);
if (/(auto|scroll)/.test(overflowY)) {
return node;
}
}
if (node.ownerDocument === node.parentNode) {
return node;
} // Continue traversing.
return getScrollContainer(
/** @type {Element} */
node.parentNode);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/get-offset-parent.js
/**
* Internal dependencies
*/
/**
* Returns the closest positioned element, or null under any of the conditions
* of the offsetParent specification. Unlike offsetParent, this function is not
* limited to HTMLElement and accepts any Node (e.g. Node.TEXT_NODE).
*
* @see https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsetparent
*
* @param {Node} node Node from which to find offset parent.
*
* @return {Node | null} Offset parent.
*/
function getOffsetParent(node) {
// Cannot retrieve computed style or offset parent only anything other than
// an element node, so find the closest element node.
let closestElement;
while (closestElement =
/** @type {Node} */
node.parentNode) {
if (closestElement.nodeType === closestElement.ELEMENT_NODE) {
break;
}
}
if (!closestElement) {
return null;
} // If the closest element is already positioned, return it, as offsetParent
// does not otherwise consider the node itself.
if (getComputedStyle(
/** @type {Element} */
closestElement).position !== 'static') {
return closestElement;
} // offsetParent is undocumented/draft.
return (
/** @type {Node & { offsetParent: Node }} */
closestElement.offsetParent
);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/is-input-or-text-area.js
/* eslint-disable jsdoc/valid-types */
/**
* @param {Element} element
* @return {element is HTMLInputElement | HTMLTextAreaElement} Whether the element is an input or textarea
*/
function isInputOrTextArea(element) {
/* eslint-enable jsdoc/valid-types */
return element.tagName === 'INPUT' || element.tagName === 'TEXTAREA';
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/is-entirely-selected.js
/**
* Internal dependencies
*/
/**
* Check whether the contents of the element have been entirely selected.
* Returns true if there is no possibility of selection.
*
* @param {HTMLElement} element The element to check.
*
* @return {boolean} True if entirely selected, false if not.
*/
function isEntirelySelected(element) {
if (isInputOrTextArea(element)) {
return element.selectionStart === 0 && element.value.length === element.selectionEnd;
}
if (!element.isContentEditable) {
return true;
}
const {
ownerDocument
} = element;
const {
defaultView
} = ownerDocument;
assertIsDefined(defaultView, 'defaultView');
const selection = defaultView.getSelection();
assertIsDefined(selection, 'selection');
const range = selection.rangeCount ? selection.getRangeAt(0) : null;
if (!range) {
return true;
}
const {
startContainer,
endContainer,
startOffset,
endOffset
} = range;
if (startContainer === element && endContainer === element && startOffset === 0 && endOffset === element.childNodes.length) {
return true;
}
const lastChild = element.lastChild;
assertIsDefined(lastChild, 'lastChild');
const endContainerContentLength = endContainer.nodeType === endContainer.TEXT_NODE ?
/** @type {Text} */
endContainer.data.length : endContainer.childNodes.length;
return isDeepChild(startContainer, element, 'firstChild') && isDeepChild(endContainer, element, 'lastChild') && startOffset === 0 && endOffset === endContainerContentLength;
}
/**
* Check whether the contents of the element have been entirely selected.
* Returns true if there is no possibility of selection.
*
* @param {HTMLElement|Node} query The element to check.
* @param {HTMLElement} container The container that we suspect "query" may be a first or last child of.
* @param {"firstChild"|"lastChild"} propName "firstChild" or "lastChild"
*
* @return {boolean} True if query is a deep first/last child of container, false otherwise.
*/
function isDeepChild(query, container, propName) {
/** @type {HTMLElement | ChildNode | null} */
let candidate = container;
do {
if (query === candidate) {
return true;
}
candidate = candidate[propName];
} while (candidate);
return false;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/is-form-element.js
/**
* Internal dependencies
*/
/**
*
* Detects if element is a form element.
*
* @param {Element} element The element to check.
*
* @return {boolean} True if form element and false otherwise.
*/
function isFormElement(element) {
if (!element) {
return false;
}
const {
tagName
} = element;
const checkForInputTextarea = isInputOrTextArea(element);
return checkForInputTextarea || tagName === 'BUTTON' || tagName === 'SELECT';
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/is-rtl.js
/**
* Internal dependencies
*/
/**
* Whether the element's text direction is right-to-left.
*
* @param {Element} element The element to check.
*
* @return {boolean} True if rtl, false if ltr.
*/
function isRTL(element) {
return getComputedStyle(element).direction === 'rtl';
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/get-range-height.js
/**
* Gets the height of the range without ignoring zero width rectangles, which
* some browsers ignore when creating a union.
*
* @param {Range} range The range to check.
* @return {number | undefined} Height of the range or undefined if the range has no client rectangles.
*/
function getRangeHeight(range) {
const rects = Array.from(range.getClientRects());
if (!rects.length) {
return;
}
const highestTop = Math.min(...rects.map(_ref => {
let {
top
} = _ref;
return top;
}));
const lowestBottom = Math.max(...rects.map(_ref2 => {
let {
bottom
} = _ref2;
return bottom;
}));
return lowestBottom - highestTop;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/is-selection-forward.js
/**
* Internal dependencies
*/
/**
* Returns true if the given selection object is in the forward direction, or
* false otherwise.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition
*
* @param {Selection} selection Selection object to check.
*
* @return {boolean} Whether the selection is forward.
*/
function isSelectionForward(selection) {
const {
anchorNode,
focusNode,
anchorOffset,
focusOffset
} = selection;
assertIsDefined(anchorNode, 'anchorNode');
assertIsDefined(focusNode, 'focusNode');
const position = anchorNode.compareDocumentPosition(focusNode); // Disable reason: `Node#compareDocumentPosition` returns a bitmask value,
// so bitwise operators are intended.
/* eslint-disable no-bitwise */
// Compare whether anchor node precedes focus node. If focus node (where
// end of selection occurs) is after the anchor node, it is forward.
if (position & anchorNode.DOCUMENT_POSITION_PRECEDING) {
return false;
}
if (position & anchorNode.DOCUMENT_POSITION_FOLLOWING) {
return true;
}
/* eslint-enable no-bitwise */
// `compareDocumentPosition` returns 0 when passed the same node, in which
// case compare offsets.
if (position === 0) {
return anchorOffset <= focusOffset;
} // This should never be reached, but return true as default case.
return true;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/caret-range-from-point.js
/**
* Polyfill.
* Get a collapsed range for a given point.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/Document/caretRangeFromPoint
*
* @param {DocumentMaybeWithCaretPositionFromPoint} doc The document of the range.
* @param {number} x Horizontal position within the current viewport.
* @param {number} y Vertical position within the current viewport.
*
* @return {Range | null} The best range for the given point.
*/
function caretRangeFromPoint(doc, x, y) {
if (doc.caretRangeFromPoint) {
return doc.caretRangeFromPoint(x, y);
}
if (!doc.caretPositionFromPoint) {
return null;
}
const point = doc.caretPositionFromPoint(x, y); // If x or y are negative, outside viewport, or there is no text entry node.
// https://developer.mozilla.org/en-US/docs/Web/API/Document/caretRangeFromPoint
if (!point) {
return null;
}
const range = doc.createRange();
range.setStart(point.offsetNode, point.offset);
range.collapse(true);
return range;
}
/**
* @typedef {{caretPositionFromPoint?: (x: number, y: number)=> CaretPosition | null} & Document } DocumentMaybeWithCaretPositionFromPoint
* @typedef {{ readonly offset: number; readonly offsetNode: Node; getClientRect(): DOMRect | null; }} CaretPosition
*/
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/hidden-caret-range-from-point.js
/**
* Internal dependencies
*/
/**
* Get a collapsed range for a given point.
* Gives the container a temporary high z-index (above any UI).
* This is preferred over getting the UI nodes and set styles there.
*
* @param {Document} doc The document of the range.
* @param {number} x Horizontal position within the current viewport.
* @param {number} y Vertical position within the current viewport.
* @param {HTMLElement} container Container in which the range is expected to be found.
*
* @return {?Range} The best range for the given point.
*/
function hiddenCaretRangeFromPoint(doc, x, y, container) {
const originalZIndex = container.style.zIndex;
const originalPosition = container.style.position;
const {
position = 'static'
} = getComputedStyle(container); // A z-index only works if the element position is not static.
if (position === 'static') {
container.style.position = 'relative';
}
container.style.zIndex = '10000';
const range = caretRangeFromPoint(doc, x, y);
container.style.zIndex = originalZIndex;
container.style.position = originalPosition;
return range;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/is-edge.js
/**
* Internal dependencies
*/
/**
* Check whether the selection is at the edge of the container. Checks for
* horizontal position by default. Set `onlyVertical` to true to check only
* vertically.
*
* @param {Element} container Focusable element.
* @param {boolean} isReverse Set to true to check left, false to check right.
* @param {boolean} [onlyVertical=false] Set to true to check only vertical position.
*
* @return {boolean} True if at the edge, false if not.
*/
function isEdge(container, isReverse) {
let onlyVertical = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (isInputOrTextArea(container) && typeof container.selectionStart === 'number') {
if (container.selectionStart !== container.selectionEnd) {
return false;
}
if (isReverse) {
return container.selectionStart === 0;
}
return container.value.length === container.selectionStart;
}
if (!
/** @type {HTMLElement} */
container.isContentEditable) {
return true;
}
const {
ownerDocument
} = container;
const {
defaultView
} = ownerDocument;
assertIsDefined(defaultView, 'defaultView');
const selection = defaultView.getSelection();
if (!selection || !selection.rangeCount) {
return false;
}
const range = selection.getRangeAt(0);
const collapsedRange = range.cloneRange();
const isForward = isSelectionForward(selection);
const isCollapsed = selection.isCollapsed; // Collapse in direction of selection.
if (!isCollapsed) {
collapsedRange.collapse(!isForward);
}
const collapsedRangeRect = getRectangleFromRange(collapsedRange);
const rangeRect = getRectangleFromRange(range);
if (!collapsedRangeRect || !rangeRect) {
return false;
} // Only consider the multiline selection at the edge if the direction is
// towards the edge. The selection is multiline if it is taller than the
// collapsed selection.
const rangeHeight = getRangeHeight(range);
if (!isCollapsed && rangeHeight && rangeHeight > collapsedRangeRect.height && isForward === isReverse) {
return false;
} // In the case of RTL scripts, the horizontal edge is at the opposite side.
const isReverseDir = isRTL(container) ? !isReverse : isReverse;
const containerRect = container.getBoundingClientRect(); // To check if a selection is at the edge, we insert a test selection at the
// edge of the container and check if the selections have the same vertical
// or horizontal position. If they do, the selection is at the edge.
// This method proves to be better than a DOM-based calculation for the
// horizontal edge, since it ignores empty textnodes and a trailing line
// break element. In other words, we need to check visual positioning, not
// DOM positioning.
// It also proves better than using the computed style for the vertical
// edge, because we cannot know the padding and line height reliably in
// pixels. `getComputedStyle` may return a value with different units.
const x = isReverseDir ? containerRect.left + 1 : containerRect.right - 1;
const y = isReverse ? containerRect.top + 1 : containerRect.bottom - 1;
const testRange = hiddenCaretRangeFromPoint(ownerDocument, x, y,
/** @type {HTMLElement} */
container);
if (!testRange) {
return false;
}
const testRect = getRectangleFromRange(testRange);
if (!testRect) {
return false;
}
const verticalSide = isReverse ? 'top' : 'bottom';
const horizontalSide = isReverseDir ? 'left' : 'right';
const verticalDiff = testRect[verticalSide] - rangeRect[verticalSide];
const horizontalDiff = testRect[horizontalSide] - collapsedRangeRect[horizontalSide]; // Allow the position to be 1px off.
const hasVerticalDiff = Math.abs(verticalDiff) <= 1;
const hasHorizontalDiff = Math.abs(horizontalDiff) <= 1;
return onlyVertical ? hasVerticalDiff : hasVerticalDiff && hasHorizontalDiff;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/is-horizontal-edge.js
/**
* Internal dependencies
*/
/**
* Check whether the selection is horizontally at the edge of the container.
*
* @param {Element} container Focusable element.
* @param {boolean} isReverse Set to true to check left, false for right.
*
* @return {boolean} True if at the horizontal edge, false if not.
*/
function isHorizontalEdge(container, isReverse) {
return isEdge(container, isReverse);
}
;// CONCATENATED MODULE: external ["wp","deprecated"]
var external_wp_deprecated_namespaceObject = window["wp"]["deprecated"];
var external_wp_deprecated_default = /*#__PURE__*/__webpack_require__.n(external_wp_deprecated_namespaceObject);
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/is-number-input.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/* eslint-disable jsdoc/valid-types */
/**
* Check whether the given element is an input field of type number.
*
* @param {Node} node The HTML node.
*
* @return {node is HTMLInputElement} True if the node is number input.
*/
function isNumberInput(node) {
external_wp_deprecated_default()('wp.dom.isNumberInput', {
since: '6.1',
version: '6.5'
});
/* eslint-enable jsdoc/valid-types */
return isHTMLInputElement(node) && node.type === 'number' && !isNaN(node.valueAsNumber);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/is-vertical-edge.js
/**
* Internal dependencies
*/
/**
* Check whether the selection is vertically at the edge of the container.
*
* @param {Element} container Focusable element.
* @param {boolean} isReverse Set to true to check top, false for bottom.
*
* @return {boolean} True if at the vertical edge, false if not.
*/
function isVerticalEdge(container, isReverse) {
return isEdge(container, isReverse, true);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/place-caret-at-edge.js
/**
* Internal dependencies
*/
/**
* Gets the range to place.
*
* @param {HTMLElement} container Focusable element.
* @param {boolean} isReverse True for end, false for start.
* @param {number|undefined} x X coordinate to vertically position.
*
* @return {Range|null} The range to place.
*/
function getRange(container, isReverse, x) {
const {
ownerDocument
} = container; // In the case of RTL scripts, the horizontal edge is at the opposite side.
const isReverseDir = isRTL(container) ? !isReverse : isReverse;
const containerRect = container.getBoundingClientRect(); // When placing at the end (isReverse), find the closest range to the bottom
// right corner. When placing at the start, to the top left corner.
// Ensure x is defined and within the container's boundaries. When it's
// exactly at the boundary, it's not considered within the boundaries.
if (x === undefined) {
x = isReverse ? containerRect.right - 1 : containerRect.left + 1;
} else if (x <= containerRect.left) {
x = containerRect.left + 1;
} else if (x >= containerRect.right) {
x = containerRect.right - 1;
}
const y = isReverseDir ? containerRect.bottom - 1 : containerRect.top + 1;
return hiddenCaretRangeFromPoint(ownerDocument, x, y, container);
}
/**
* Places the caret at start or end of a given element.
*
* @param {HTMLElement} container Focusable element.
* @param {boolean} isReverse True for end, false for start.
* @param {number|undefined} x X coordinate to vertically position.
*/
function placeCaretAtEdge(container, isReverse, x) {
if (!container) {
return;
}
container.focus();
if (isInputOrTextArea(container)) {
// The element may not support selection setting.
if (typeof container.selectionStart !== 'number') {
return;
}
if (isReverse) {
container.selectionStart = container.value.length;
container.selectionEnd = container.value.length;
} else {
container.selectionStart = 0;
container.selectionEnd = 0;
}
return;
}
if (!container.isContentEditable) {
return;
}
let range = getRange(container, isReverse, x); // If no range range can be created or it is outside the container, the
// element may be out of view.
if (!range || !range.startContainer || !container.contains(range.startContainer)) {
container.scrollIntoView(isReverse);
range = range = getRange(container, isReverse, x);
if (!range || !range.startContainer || !container.contains(range.startContainer)) {
return;
}
}
const {
ownerDocument
} = container;
const {
defaultView
} = ownerDocument;
assertIsDefined(defaultView, 'defaultView');
const selection = defaultView.getSelection();
assertIsDefined(selection, 'selection');
selection.removeAllRanges();
selection.addRange(range);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/place-caret-at-horizontal-edge.js
/**
* Internal dependencies
*/
/**
* Places the caret at start or end of a given element.
*
* @param {HTMLElement} container Focusable element.
* @param {boolean} isReverse True for end, false for start.
*/
function placeCaretAtHorizontalEdge(container, isReverse) {
return placeCaretAtEdge(container, isReverse, undefined);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/place-caret-at-vertical-edge.js
/**
* Internal dependencies
*/
/**
* Places the caret at the top or bottom of a given element.
*
* @param {HTMLElement} container Focusable element.
* @param {boolean} isReverse True for bottom, false for top.
* @param {DOMRect} [rect] The rectangle to position the caret with.
*/
function placeCaretAtVerticalEdge(container, isReverse, rect) {
return placeCaretAtEdge(container, isReverse, rect === null || rect === void 0 ? void 0 : rect.left);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/insert-after.js
/**
* Internal dependencies
*/
/**
* Given two DOM nodes, inserts the former in the DOM as the next sibling of
* the latter.
*
* @param {Node} newNode Node to be inserted.
* @param {Node} referenceNode Node after which to perform the insertion.
* @return {void}
*/
function insertAfter(newNode, referenceNode) {
assertIsDefined(referenceNode.parentNode, 'referenceNode.parentNode');
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/remove.js
/**
* Internal dependencies
*/
/**
* Given a DOM node, removes it from the DOM.
*
* @param {Node} node Node to be removed.
* @return {void}
*/
function remove(node) {
assertIsDefined(node.parentNode, 'node.parentNode');
node.parentNode.removeChild(node);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/replace.js
/**
* Internal dependencies
*/
/**
* Given two DOM nodes, replaces the former with the latter in the DOM.
*
* @param {Element} processedNode Node to be removed.
* @param {Element} newNode Node to be inserted in its place.
* @return {void}
*/
function replace(processedNode, newNode) {
assertIsDefined(processedNode.parentNode, 'processedNode.parentNode');
insertAfter(newNode, processedNode.parentNode);
remove(processedNode);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/unwrap.js
/**
* Internal dependencies
*/
/**
* Unwrap the given node. This means any child nodes are moved to the parent.
*
* @param {Node} node The node to unwrap.
*
* @return {void}
*/
function unwrap(node) {
const parent = node.parentNode;
assertIsDefined(parent, 'node.parentNode');
while (node.firstChild) {
parent.insertBefore(node.firstChild, node);
}
parent.removeChild(node);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/replace-tag.js
/**
* Internal dependencies
*/
/**
* Replaces the given node with a new node with the given tag name.
*
* @param {Element} node The node to replace
* @param {string} tagName The new tag name.
*
* @return {Element} The new node.
*/
function replaceTag(node, tagName) {
const newNode = node.ownerDocument.createElement(tagName);
while (node.firstChild) {
newNode.appendChild(node.firstChild);
}
assertIsDefined(node.parentNode, 'node.parentNode');
node.parentNode.replaceChild(newNode, node);
return newNode;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/wrap.js
/**
* Internal dependencies
*/
/**
* Wraps the given node with a new node with the given tag name.
*
* @param {Element} newNode The node to insert.
* @param {Element} referenceNode The node to wrap.
*/
function wrap(newNode, referenceNode) {
assertIsDefined(referenceNode.parentNode, 'referenceNode.parentNode');
referenceNode.parentNode.insertBefore(newNode, referenceNode);
newNode.appendChild(referenceNode);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/safe-html.js
/**
* Internal dependencies
*/
/**
* Strips scripts and on* attributes from HTML.
*
* @param {string} html HTML to sanitize.
*
* @return {string} The sanitized HTML.
*/
function safeHTML(html) {
const {
body
} = document.implementation.createHTMLDocument('');
body.innerHTML = html;
const elements = body.getElementsByTagName('*');
let elementIndex = elements.length;
while (elementIndex--) {
const element = elements[elementIndex];
if (element.tagName === 'SCRIPT') {
remove(element);
} else {
let attributeIndex = element.attributes.length;
while (attributeIndex--) {
const {
name: key
} = element.attributes[attributeIndex];
if (key.startsWith('on')) {
element.removeAttribute(key);
}
}
}
}
return body.innerHTML;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/strip-html.js
/**
* Internal dependencies
*/
/**
* Removes any HTML tags from the provided string.
*
* @param {string} html The string containing html.
*
* @return {string} The text content with any html removed.
*/
function stripHTML(html) {
// Remove any script tags or on* attributes otherwise their *contents* will be left
// in place following removal of HTML tags.
html = safeHTML(html);
const doc = document.implementation.createHTMLDocument('');
doc.body.innerHTML = html;
return doc.body.textContent || '';
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/is-empty.js
/**
* Recursively checks if an element is empty. An element is not empty if it
* contains text or contains elements with attributes such as images.
*
* @param {Element} element The element to check.
*
* @return {boolean} Whether or not the element is empty.
*/
function isEmpty(element) {
switch (element.nodeType) {
case element.TEXT_NODE:
// We cannot use \s since it includes special spaces which we want
// to preserve.
return /^[ \f\n\r\t\v\u00a0]*$/.test(element.nodeValue || '');
case element.ELEMENT_NODE:
if (element.hasAttributes()) {
return false;
} else if (!element.hasChildNodes()) {
return true;
}
return (
/** @type {Element[]} */
Array.from(element.childNodes).every(isEmpty)
);
default:
return true;
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/phrasing-content.js
/**
* All phrasing content elements.
*
* @see https://www.w3.org/TR/2011/WD-html5-20110525/content-models.html#phrasing-content-0
*/
/**
* @typedef {Record<string,SemanticElementDefinition>} ContentSchema
*/
/**
* @typedef SemanticElementDefinition
* @property {string[]} [attributes] Content attributes
* @property {ContentSchema} [children] Content attributes
*/
/**
* All text-level semantic elements.
*
* @see https://html.spec.whatwg.org/multipage/text-level-semantics.html
*
* @type {ContentSchema}
*/
const textContentSchema = {
strong: {},
em: {},
s: {},
del: {},
ins: {},
a: {
attributes: ['href', 'target', 'rel', 'id']
},
code: {},
abbr: {
attributes: ['title']
},
sub: {},
sup: {},
br: {},
small: {},
// To do: fix blockquote.
// cite: {},
q: {
attributes: ['cite']
},
dfn: {
attributes: ['title']
},
data: {
attributes: ['value']
},
time: {
attributes: ['datetime']
},
var: {},
samp: {},
kbd: {},
i: {},
b: {},
u: {},
mark: {},
ruby: {},
rt: {},
rp: {},
bdi: {
attributes: ['dir']
},
bdo: {
attributes: ['dir']
},
wbr: {},
'#text': {}
}; // Recursion is needed.
// Possible: strong > em > strong.
// Impossible: strong > strong.
const excludedElements = ['#text', 'br'];
Object.keys(textContentSchema).filter(element => !excludedElements.includes(element)).forEach(tag => {
const {
[tag]: removedTag,
...restSchema
} = textContentSchema;
textContentSchema[tag].children = restSchema;
});
/**
* Embedded content elements.
*
* @see https://www.w3.org/TR/2011/WD-html5-20110525/content-models.html#embedded-content-0
*
* @type {ContentSchema}
*/
const embeddedContentSchema = {
audio: {
attributes: ['src', 'preload', 'autoplay', 'mediagroup', 'loop', 'muted']
},
canvas: {
attributes: ['width', 'height']
},
embed: {
attributes: ['src', 'type', 'width', 'height']
},
img: {
attributes: ['alt', 'src', 'srcset', 'usemap', 'ismap', 'width', 'height']
},
object: {
attributes: ['data', 'type', 'name', 'usemap', 'form', 'width', 'height']
},
video: {
attributes: ['src', 'poster', 'preload', 'autoplay', 'mediagroup', 'loop', 'muted', 'controls', 'width', 'height']
}
};
/**
* Phrasing content elements.
*
* @see https://www.w3.org/TR/2011/WD-html5-20110525/content-models.html#phrasing-content-0
*/
const phrasingContentSchema = { ...textContentSchema,
...embeddedContentSchema
};
/**
* Get schema of possible paths for phrasing content.
*
* @see https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories#Phrasing_content
*
* @param {string} [context] Set to "paste" to exclude invisible elements and
* sensitive data.
*
* @return {Partial<ContentSchema>} Schema.
*/
function getPhrasingContentSchema(context) {
if (context !== 'paste') {
return phrasingContentSchema;
}
/**
* @type {Partial<ContentSchema>}
*/
const {
u,
// Used to mark misspelling. Shouldn't be pasted.
abbr,
// Invisible.
data,
// Invisible.
time,
// Invisible.
wbr,
// Invisible.
bdi,
// Invisible.
bdo,
// Invisible.
...remainingContentSchema
} = { ...phrasingContentSchema,
// We shouldn't paste potentially sensitive information which is not
// visible to the user when pasted, so strip the attributes.
ins: {
children: phrasingContentSchema.ins.children
},
del: {
children: phrasingContentSchema.del.children
}
};
return remainingContentSchema;
}
/**
* Find out whether or not the given node is phrasing content.
*
* @see https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories#Phrasing_content
*
* @param {Node} node The node to test.
*
* @return {boolean} True if phrasing content, false if not.
*/
function isPhrasingContent(node) {
const tag = node.nodeName.toLowerCase();
return getPhrasingContentSchema().hasOwnProperty(tag) || tag === 'span';
}
/**
* @param {Node} node
* @return {boolean} Node is text content
*/
function isTextContent(node) {
const tag = node.nodeName.toLowerCase();
return textContentSchema.hasOwnProperty(tag) || tag === 'span';
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/is-element.js
/* eslint-disable jsdoc/valid-types */
/**
* @param {Node | null | undefined} node
* @return {node is Element} True if node is an Element node
*/
function isElement(node) {
/* eslint-enable jsdoc/valid-types */
return !!node && node.nodeType === node.ELEMENT_NODE;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/clean-node-list.js
/**
* Internal dependencies
*/
const noop = () => {};
/* eslint-disable jsdoc/valid-types */
/**
* @typedef SchemaItem
* @property {string[]} [attributes] Attributes.
* @property {(string | RegExp)[]} [classes] Classnames or RegExp to test against.
* @property {'*' | { [tag: string]: SchemaItem }} [children] Child schemas.
* @property {string[]} [require] Selectors to test required children against. Leave empty or undefined if there are no requirements.
* @property {boolean} allowEmpty Whether to allow nodes without children.
* @property {(node: Node) => boolean} [isMatch] Function to test whether a node is a match. If left undefined any node will be assumed to match.
*/
/** @typedef {{ [tag: string]: SchemaItem }} Schema */
/* eslint-enable jsdoc/valid-types */
/**
* Given a schema, unwraps or removes nodes, attributes and classes on a node
* list.
*
* @param {NodeList} nodeList The nodeList to filter.
* @param {Document} doc The document of the nodeList.
* @param {Schema} schema An array of functions that can mutate with the provided node.
* @param {boolean} inline Whether to clean for inline mode.
*/
function cleanNodeList(nodeList, doc, schema, inline) {
Array.from(nodeList).forEach((
/** @type {Node & { nextElementSibling?: unknown }} */
node) => {
var _schema$tag$isMatch, _schema$tag;
const tag = node.nodeName.toLowerCase(); // It's a valid child, if the tag exists in the schema without an isMatch
// function, or with an isMatch function that matches the node.
if (schema.hasOwnProperty(tag) && (!schema[tag].isMatch || (_schema$tag$isMatch = (_schema$tag = schema[tag]).isMatch) !== null && _schema$tag$isMatch !== void 0 && _schema$tag$isMatch.call(_schema$tag, node))) {
if (isElement(node)) {
const {
attributes = [],
classes = [],
children,
require = [],
allowEmpty
} = schema[tag]; // If the node is empty and it's supposed to have children,
// remove the node.
if (children && !allowEmpty && isEmpty(node)) {
remove(node);
return;
}
if (node.hasAttributes()) {
// Strip invalid attributes.
Array.from(node.attributes).forEach(_ref => {
let {
name
} = _ref;
if (name !== 'class' && !attributes.includes(name)) {
node.removeAttribute(name);
}
}); // Strip invalid classes.
// In jsdom-jscore, 'node.classList' can be undefined.
// TODO: Explore patching this in jsdom-jscore.
if (node.classList && node.classList.length) {
const mattchers = classes.map(item => {
if (typeof item === 'string') {
return (
/** @type {string} */
className) => className === item;
} else if (item instanceof RegExp) {
return (
/** @type {string} */
className) => item.test(className);
}
return noop;
});
Array.from(node.classList).forEach(name => {
if (!mattchers.some(isMatch => isMatch(name))) {
node.classList.remove(name);
}
});
if (!node.classList.length) {
node.removeAttribute('class');
}
}
}
if (node.hasChildNodes()) {
// Do not filter any content.
if (children === '*') {
return;
} // Continue if the node is supposed to have children.
if (children) {
// If a parent requires certain children, but it does
// not have them, drop the parent and continue.
if (require.length && !node.querySelector(require.join(','))) {
cleanNodeList(node.childNodes, doc, schema, inline);
unwrap(node); // If the node is at the top, phrasing content, and
// contains children that are block content, unwrap
// the node because it is invalid.
} else if (node.parentNode && node.parentNode.nodeName === 'BODY' && isPhrasingContent(node)) {
cleanNodeList(node.childNodes, doc, schema, inline);
if (Array.from(node.childNodes).some(child => !isPhrasingContent(child))) {
unwrap(node);
}
} else {
cleanNodeList(node.childNodes, doc, children, inline);
} // Remove children if the node is not supposed to have any.
} else {
while (node.firstChild) {
remove(node.firstChild);
}
}
}
} // Invalid child. Continue with schema at the same place and unwrap.
} else {
cleanNodeList(node.childNodes, doc, schema, inline); // For inline mode, insert a line break when unwrapping nodes that
// are not phrasing content.
if (inline && !isPhrasingContent(node) && node.nextElementSibling) {
insertAfter(doc.createElement('br'), node);
}
unwrap(node);
}
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/remove-invalid-html.js
/**
* Internal dependencies
*/
/**
* Given a schema, unwraps or removes nodes, attributes and classes on HTML.
*
* @param {string} HTML The HTML to clean up.
* @param {import('./clean-node-list').Schema} schema Schema for the HTML.
* @param {boolean} inline Whether to clean for inline mode.
*
* @return {string} The cleaned up HTML.
*/
function removeInvalidHTML(HTML, schema, inline) {
const doc = document.implementation.createHTMLDocument('');
doc.body.innerHTML = HTML;
cleanNodeList(doc.body.childNodes, doc, schema, inline);
return doc.body.innerHTML;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/dom/index.js
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/data-transfer.js
/**
* Gets all files from a DataTransfer object.
*
* @param {DataTransfer} dataTransfer DataTransfer object to inspect.
*
* @return {File[]} An array containing all files.
*/
function getFilesFromDataTransfer(dataTransfer) {
const files = Array.from(dataTransfer.files);
Array.from(dataTransfer.items).forEach(item => {
const file = item.getAsFile();
if (file && !files.find(_ref => {
let {
name,
type,
size
} = _ref;
return name === file.name && type === file.type && size === file.size;
})) {
files.push(file);
}
});
return files;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/dom/build-module/index.js
/**
* Internal dependencies
*/
/**
* Object grouping `focusable` and `tabbable` utils
* under the keys with the same name.
*/
const build_module_focus = {
focusable: focusable_namespaceObject,
tabbable: tabbable_namespaceObject
};
(window.wp = window.wp || {}).dom = __webpack_exports__;
/******/ })()
; style-engine.js 0000666 00000041534 15123355174 0007526 0 ustar 00 /******/ (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__, {
"compileCSS": function() { return /* binding */ compileCSS; },
"getCSSRules": function() { return /* binding */ getCSSRules; }
});
;// CONCATENATED MODULE: external "lodash"
var external_lodash_namespaceObject = window["lodash"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/style-engine/build-module/styles/constants.js
const VARIABLE_REFERENCE_PREFIX = 'var:';
const VARIABLE_PATH_SEPARATOR_TOKEN_ATTRIBUTE = '|';
const VARIABLE_PATH_SEPARATOR_TOKEN_STYLE = '--';
;// CONCATENATED MODULE: ./node_modules/@wordpress/style-engine/build-module/styles/utils.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
/**
* Returns a JSON representation of the generated CSS rules.
*
* @param style Style object.
* @param options Options object with settings to adjust how the styles are generated.
* @param path An array of strings representing the path to the style value in the style object.
* @param ruleKey A CSS property key.
*
* @return GeneratedCSSRule[] CSS rules.
*/
function generateRule(style, options, path, ruleKey) {
const styleValue = (0,external_lodash_namespaceObject.get)(style, path);
return styleValue ? [{
selector: options === null || options === void 0 ? void 0 : 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.
*
* @param style Style object.
* @param options Options object with settings to adjust how the styles are generated.
* @param path An array of strings representing the path to the style value in the style object.
* @param ruleKeys An array of CSS property keys and patterns.
* @param individualProperties The "sides" or individual properties for which to generate rules.
*
* @return GeneratedCSSRule[] CSS rules.
*/
function generateBoxRules(style, options, path, ruleKeys) {
let individualProperties = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : ['top', 'right', 'bottom', 'left'];
const boxStyle = (0,external_lodash_namespaceObject.get)(style, path);
if (!boxStyle) {
return [];
}
const rules = [];
if (typeof boxStyle === 'string') {
rules.push({
selector: options === null || options === void 0 ? void 0 : options.selector,
key: ruleKeys.default,
value: boxStyle
});
} else {
const sideRules = individualProperties.reduce((acc, side) => {
const value = getCSSVarFromStyleValue((0,external_lodash_namespaceObject.get)(boxStyle, [side]));
if (value) {
acc.push({
selector: options === null || options === void 0 ? void 0 : options.selector,
key: ruleKeys === null || ruleKeys === void 0 ? void 0 : ruleKeys.individual.replace('%s', upperFirst(side)),
value
});
}
return acc;
}, []);
rules.push(...sideRules);
}
return rules;
}
/**
* Returns a CSS var value from incoming style value following the pattern `var:description|context|slug`.
*
* @param styleValue A raw style value.
*
* @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);
return `var(--wp--${variable})`;
}
return styleValue;
}
/**
* Capitalizes the first letter in a string.
*
* @param string The string whose first letter the function will capitalize.
*
* @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.
*
* @param strings The strings to join into a camelCase string.
*
* @return camelCase string.
*/
function camelCaseJoin(strings) {
const [firstItem, ...rest] = strings;
return firstItem.toLowerCase() + rest.map(upperFirst).join('');
}
;// 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.
*
* @param path An array of strings representing the path to the style value in the style object.
*
* @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.
*
* @param edge The edge to create CSS rules for.
*
* @return A function that generates CSS rules.
*/
function createBorderEdgeGenerateFunction(edge) {
return (style, options) => {
return ['color', 'style', 'width'].flatMap(key => {
const path = ['border', edge, key];
return createBorderGenerateFunction(path)(style, options);
});
};
}
const color = {
name: 'color',
generate: createBorderGenerateFunction(['border', 'color'])
};
const radius = {
name: 'radius',
generate: (style, options) => {
return generateBoxRules(style, options, ['border', 'radius'], {
default: 'borderRadius',
individual: 'border%sRadius'
}, ['topLeft', 'topRight', 'bottomLeft', 'bottomRight']);
}
};
const borderStyle = {
name: 'style',
generate: createBorderGenerateFunction(['border', 'style'])
};
const width = {
name: 'width',
generate: createBorderGenerateFunction(['border', 'width'])
};
const borderTop = {
name: 'borderTop',
generate: createBorderEdgeGenerateFunction('top')
};
const borderRight = {
name: 'borderRight',
generate: createBorderEdgeGenerateFunction('right')
};
const borderBottom = {
name: 'borderBottom',
generate: createBorderEdgeGenerateFunction('bottom')
};
const borderLeft = {
name: 'borderLeft',
generate: createBorderEdgeGenerateFunction('left')
};
/* harmony default export */ var border = ([color, borderStyle, width, radius, borderTop, borderRight, borderBottom, borderLeft]);
;// CONCATENATED MODULE: ./node_modules/@wordpress/style-engine/build-module/styles/color/background.js
/**
* Internal dependencies
*/
const background = {
name: 'background',
generate: (style, options) => {
return generateRule(style, options, ['color', 'background'], 'backgroundColor');
}
};
/* harmony default export */ var color_background = (background);
;// CONCATENATED MODULE: ./node_modules/@wordpress/style-engine/build-module/styles/color/gradient.js
/**
* Internal dependencies
*/
const gradient = {
name: 'gradient',
generate: (style, options) => {
return generateRule(style, options, ['color', 'gradient'], 'background');
}
};
/* harmony default export */ var color_gradient = (gradient);
;// CONCATENATED MODULE: ./node_modules/@wordpress/style-engine/build-module/styles/color/text.js
/**
* Internal dependencies
*/
const text_text = {
name: 'text',
generate: (style, options) => {
return generateRule(style, options, ['color', 'text'], 'color');
}
};
/* harmony default export */ var color_text = (text_text);
;// CONCATENATED MODULE: ./node_modules/@wordpress/style-engine/build-module/styles/color/index.js
/**
* Internal dependencies
*/
/* harmony default export */ var styles_color = ([color_text, color_gradient, color_background]);
;// CONCATENATED MODULE: ./node_modules/@wordpress/style-engine/build-module/styles/dimensions/index.js
/**
* Internal dependencies
*/
const minHeight = {
name: 'minHeight',
generate: (style, options) => {
return generateRule(style, options, ['dimensions', 'minHeight'], 'minHeight');
}
};
/* harmony default export */ var dimensions = ([minHeight]);
;// CONCATENATED MODULE: ./node_modules/@wordpress/style-engine/build-module/styles/shadow/index.js
/**
* Internal dependencies
*/
const shadow = {
name: 'shadow',
generate: (style, options) => {
return generateRule(style, options, ['shadow'], 'boxShadow');
}
};
/* harmony default export */ var styles_shadow = ([shadow]);
;// CONCATENATED MODULE: ./node_modules/@wordpress/style-engine/build-module/styles/outline/index.js
/**
* Internal dependencies
*/
const outline_color = {
name: 'color',
generate: function (style, options) {
let path = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ['outline', 'color'];
let ruleKey = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'outlineColor';
return generateRule(style, options, path, ruleKey);
}
};
const offset = {
name: 'offset',
generate: function (style, options) {
let path = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ['outline', 'offset'];
let ruleKey = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'outlineOffset';
return generateRule(style, options, path, ruleKey);
}
};
const outlineStyle = {
name: 'style',
generate: function (style, options) {
let path = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ['outline', 'style'];
let ruleKey = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'outlineStyle';
return generateRule(style, options, path, ruleKey);
}
};
const outline_width = {
name: 'width',
generate: function (style, options) {
let path = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ['outline', 'width'];
let ruleKey = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'outlineWidth';
return generateRule(style, options, path, ruleKey);
}
};
/* harmony default export */ var outline = ([outline_color, outlineStyle, offset, outline_width]);
;// CONCATENATED MODULE: ./node_modules/@wordpress/style-engine/build-module/styles/spacing/padding.js
/**
* Internal dependencies
*/
const padding = {
name: 'padding',
generate: (style, options) => {
return generateBoxRules(style, options, ['spacing', 'padding'], {
default: 'padding',
individual: 'padding%s'
});
}
};
/* harmony default export */ var spacing_padding = (padding);
;// CONCATENATED MODULE: ./node_modules/@wordpress/style-engine/build-module/styles/spacing/margin.js
/**
* Internal dependencies
*/
const margin = {
name: 'margin',
generate: (style, options) => {
return generateBoxRules(style, options, ['spacing', 'margin'], {
default: 'margin',
individual: 'margin%s'
});
}
};
/* harmony default export */ var spacing_margin = (margin);
;// CONCATENATED MODULE: ./node_modules/@wordpress/style-engine/build-module/styles/spacing/index.js
/**
* Internal dependencies
*/
/* harmony default export */ var spacing = ([spacing_margin, spacing_padding]);
;// CONCATENATED MODULE: ./node_modules/@wordpress/style-engine/build-module/styles/typography/index.js
/**
* Internal dependencies
*/
const fontSize = {
name: 'fontSize',
generate: (style, options) => {
return generateRule(style, options, ['typography', 'fontSize'], 'fontSize');
}
};
const fontStyle = {
name: 'fontStyle',
generate: (style, options) => {
return generateRule(style, options, ['typography', 'fontStyle'], 'fontStyle');
}
};
const fontWeight = {
name: 'fontWeight',
generate: (style, options) => {
return generateRule(style, options, ['typography', 'fontWeight'], 'fontWeight');
}
};
const fontFamily = {
name: 'fontFamily',
generate: (style, options) => {
return generateRule(style, options, ['typography', 'fontFamily'], 'fontFamily');
}
};
const letterSpacing = {
name: 'letterSpacing',
generate: (style, options) => {
return generateRule(style, options, ['typography', 'letterSpacing'], 'letterSpacing');
}
};
const lineHeight = {
name: 'letterSpacing',
generate: (style, options) => {
return generateRule(style, options, ['typography', 'lineHeight'], 'lineHeight');
}
};
const textColumns = {
name: 'textColumns',
generate: (style, options) => {
return generateRule(style, options, ['typography', 'textColumns'], 'columnCount');
}
};
const textDecoration = {
name: 'textDecoration',
generate: (style, options) => {
return generateRule(style, options, ['typography', 'textDecoration'], 'textDecoration');
}
};
const textTransform = {
name: 'textTransform',
generate: (style, options) => {
return generateRule(style, options, ['typography', 'textTransform'], 'textTransform');
}
};
/* harmony default export */ var typography = ([fontFamily, fontSize, fontStyle, fontWeight, letterSpacing, lineHeight, textColumns, textDecoration, textTransform]);
;// CONCATENATED MODULE: ./node_modules/@wordpress/style-engine/build-module/styles/index.js
/**
* Internal dependencies
*/
const styleDefinitions = [...border, ...styles_color, ...dimensions, ...outline, ...spacing, ...typography, ...styles_shadow];
;// 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.
*
* @since 6.1.0 Introduced in WordPress core.
*
* @param style Style object, for example, the value of a block's attributes.style object or the top level styles in theme.json
* @param options Options object with settings to adjust how the styles are generated.
*
* @return A generated stylesheet or inline style declarations.
*/
function compileCSS(style) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
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 !== null && options !== void 0 && options.selector)) {
const inlineRules = [];
rules.forEach(rule => {
inlineRules.push(`${(0,external_lodash_namespaceObject.kebabCase)(rule.key)}: ${rule.value};`);
});
return inlineRules.join(' ');
}
const groupedRules = (0,external_lodash_namespaceObject.groupBy)(rules, 'selector');
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(' ')} }`);
return acc;
}, []);
return selectorRules.join('\n');
}
/**
* Returns a JSON representation of the generated CSS rules.
*
* @since 6.1.0 Introduced in WordPress core.
*
* @param style Style object, for example, the value of a block's attributes.style object or the top level styles in theme.json
* @param options Options object with settings to adjust how the styles are generated.
*
* @return A collection of objects containing the selector, if any, the CSS property key (camelcase) and parsed CSS value.
*/
function getCSSRules(style) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const rules = [];
styleDefinitions.forEach(definition => {
if (typeof definition.generate === 'function') {
rules.push(...definition.generate(style, options));
}
});
return rules;
}
(window.wp = window.wp || {}).styleEngine = __webpack_exports__;
/******/ })()
; blocks.js 0000666 00002043637 15123355174 0006410 0 ustar 00 /******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 5619:
/***/ (function(module) {
"use strict";
// do not edit .js files directly - edit src/index.jst
var envHasBigInt64Array = typeof BigInt64Array !== 'undefined';
module.exports = function equal(a, b) {
if (a === b) return true;
if (a && b && typeof a == 'object' && typeof b == 'object') {
if (a.constructor !== b.constructor) return false;
var length, i, keys;
if (Array.isArray(a)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (!equal(a[i], b[i])) return false;
return true;
}
if ((a instanceof Map) && (b instanceof Map)) {
if (a.size !== b.size) return false;
for (i of a.entries())
if (!b.has(i[0])) return false;
for (i of a.entries())
if (!equal(i[1], b.get(i[0]))) return false;
return true;
}
if ((a instanceof Set) && (b instanceof Set)) {
if (a.size !== b.size) return false;
for (i of a.entries())
if (!b.has(i[0])) return false;
return true;
}
if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (a[i] !== b[i]) return false;
return true;
}
if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) return false;
for (i = length; i-- !== 0;)
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
for (i = length; i-- !== 0;) {
var key = keys[i];
if (!equal(a[key], b[key])) return false;
}
return true;
}
// true if both NaN, false otherwise
return a!==a && b!==b;
};
/***/ }),
/***/ 9756:
/***/ (function(module) {
/**
* Memize options object.
*
* @typedef MemizeOptions
*
* @property {number} [maxSize] Maximum size of the cache.
*/
/**
* Internal cache entry.
*
* @typedef MemizeCacheNode
*
* @property {?MemizeCacheNode|undefined} [prev] Previous node.
* @property {?MemizeCacheNode|undefined} [next] Next node.
* @property {Array<*>} args Function arguments for cache
* entry.
* @property {*} val Function result.
*/
/**
* Properties of the enhanced function for controlling cache.
*
* @typedef MemizeMemoizedFunction
*
* @property {()=>void} clear Clear the cache.
*/
/**
* Accepts a function to be memoized, and returns a new memoized function, with
* optional options.
*
* @template {Function} F
*
* @param {F} fn Function to memoize.
* @param {MemizeOptions} [options] Options object.
*
* @return {F & MemizeMemoizedFunction} Memoized function.
*/
function memize( fn, options ) {
var size = 0;
/** @type {?MemizeCacheNode|undefined} */
var head;
/** @type {?MemizeCacheNode|undefined} */
var tail;
options = options || {};
function memoized( /* ...args */ ) {
var node = head,
len = arguments.length,
args, i;
searchCache: while ( node ) {
// Perform a shallow equality test to confirm that whether the node
// under test is a candidate for the arguments passed. Two arrays
// are shallowly equal if their length matches and each entry is
// strictly equal between the two sets. Avoid abstracting to a
// function which could incur an arguments leaking deoptimization.
// Check whether node arguments match arguments length
if ( node.args.length !== arguments.length ) {
node = node.next;
continue;
}
// Check whether node arguments match arguments values
for ( i = 0; i < len; i++ ) {
if ( node.args[ i ] !== arguments[ i ] ) {
node = node.next;
continue searchCache;
}
}
// At this point we can assume we've found a match
// Surface matched node to head if not already
if ( node !== head ) {
// As tail, shift to previous. Must only shift if not also
// head, since if both head and tail, there is no previous.
if ( node === tail ) {
tail = node.prev;
}
// Adjust siblings to point to each other. If node was tail,
// this also handles new tail's empty `next` assignment.
/** @type {MemizeCacheNode} */ ( node.prev ).next = node.next;
if ( node.next ) {
node.next.prev = node.prev;
}
node.next = head;
node.prev = null;
/** @type {MemizeCacheNode} */ ( head ).prev = node;
head = node;
}
// Return immediately
return node.val;
}
// No cached value found. Continue to insertion phase:
// Create a copy of arguments (avoid leaking deoptimization)
args = new Array( len );
for ( i = 0; i < len; i++ ) {
args[ i ] = arguments[ i ];
}
node = {
args: args,
// Generate the result from original function
val: fn.apply( null, args ),
};
// Don't need to check whether node is already head, since it would
// have been returned above already if it was
// Shift existing head down list
if ( head ) {
head.prev = node;
node.next = head;
} else {
// If no head, follows that there's no tail (at initial or reset)
tail = node;
}
// Trim tail if we're reached max size and are pending cache insertion
if ( size === /** @type {MemizeOptions} */ ( options ).maxSize ) {
tail = /** @type {MemizeCacheNode} */ ( tail ).prev;
/** @type {MemizeCacheNode} */ ( tail ).next = null;
} else {
size++;
}
head = node;
return node.val;
}
memoized.clear = function() {
head = null;
tail = null;
size = 0;
};
if ( false ) {}
// Ignore reason: There's not a clear solution to create an intersection of
// the function with additional properties, where the goal is to retain the
// function signature of the incoming argument and add control properties
// on the return value.
// @ts-ignore
return memoized;
}
module.exports = memize;
/***/ }),
/***/ 4793:
/***/ (function(module) {
var characterMap = {
"À": "A",
"Á": "A",
"Â": "A",
"Ã": "A",
"Ä": "A",
"Å": "A",
"Ấ": "A",
"Ắ": "A",
"Ẳ": "A",
"Ẵ": "A",
"Ặ": "A",
"Æ": "AE",
"Ầ": "A",
"Ằ": "A",
"Ȃ": "A",
"Ç": "C",
"Ḉ": "C",
"È": "E",
"É": "E",
"Ê": "E",
"Ë": "E",
"Ế": "E",
"Ḗ": "E",
"Ề": "E",
"Ḕ": "E",
"Ḝ": "E",
"Ȇ": "E",
"Ì": "I",
"Í": "I",
"Î": "I",
"Ï": "I",
"Ḯ": "I",
"Ȋ": "I",
"Ð": "D",
"Ñ": "N",
"Ò": "O",
"Ó": "O",
"Ô": "O",
"Õ": "O",
"Ö": "O",
"Ø": "O",
"Ố": "O",
"Ṍ": "O",
"Ṓ": "O",
"Ȏ": "O",
"Ù": "U",
"Ú": "U",
"Û": "U",
"Ü": "U",
"Ý": "Y",
"à": "a",
"á": "a",
"â": "a",
"ã": "a",
"ä": "a",
"å": "a",
"ấ": "a",
"ắ": "a",
"ẳ": "a",
"ẵ": "a",
"ặ": "a",
"æ": "ae",
"ầ": "a",
"ằ": "a",
"ȃ": "a",
"ç": "c",
"ḉ": "c",
"è": "e",
"é": "e",
"ê": "e",
"ë": "e",
"ế": "e",
"ḗ": "e",
"ề": "e",
"ḕ": "e",
"ḝ": "e",
"ȇ": "e",
"ì": "i",
"í": "i",
"î": "i",
"ï": "i",
"ḯ": "i",
"ȋ": "i",
"ð": "d",
"ñ": "n",
"ò": "o",
"ó": "o",
"ô": "o",
"õ": "o",
"ö": "o",
"ø": "o",
"ố": "o",
"ṍ": "o",
"ṓ": "o",
"ȏ": "o",
"ù": "u",
"ú": "u",
"û": "u",
"ü": "u",
"ý": "y",
"ÿ": "y",
"Ā": "A",
"ā": "a",
"Ă": "A",
"ă": "a",
"Ą": "A",
"ą": "a",
"Ć": "C",
"ć": "c",
"Ĉ": "C",
"ĉ": "c",
"Ċ": "C",
"ċ": "c",
"Č": "C",
"č": "c",
"C̆": "C",
"c̆": "c",
"Ď": "D",
"ď": "d",
"Đ": "D",
"đ": "d",
"Ē": "E",
"ē": "e",
"Ĕ": "E",
"ĕ": "e",
"Ė": "E",
"ė": "e",
"Ę": "E",
"ę": "e",
"Ě": "E",
"ě": "e",
"Ĝ": "G",
"Ǵ": "G",
"ĝ": "g",
"ǵ": "g",
"Ğ": "G",
"ğ": "g",
"Ġ": "G",
"ġ": "g",
"Ģ": "G",
"ģ": "g",
"Ĥ": "H",
"ĥ": "h",
"Ħ": "H",
"ħ": "h",
"Ḫ": "H",
"ḫ": "h",
"Ĩ": "I",
"ĩ": "i",
"Ī": "I",
"ī": "i",
"Ĭ": "I",
"ĭ": "i",
"Į": "I",
"į": "i",
"İ": "I",
"ı": "i",
"IJ": "IJ",
"ij": "ij",
"Ĵ": "J",
"ĵ": "j",
"Ķ": "K",
"ķ": "k",
"Ḱ": "K",
"ḱ": "k",
"K̆": "K",
"k̆": "k",
"Ĺ": "L",
"ĺ": "l",
"Ļ": "L",
"ļ": "l",
"Ľ": "L",
"ľ": "l",
"Ŀ": "L",
"ŀ": "l",
"Ł": "l",
"ł": "l",
"Ḿ": "M",
"ḿ": "m",
"M̆": "M",
"m̆": "m",
"Ń": "N",
"ń": "n",
"Ņ": "N",
"ņ": "n",
"Ň": "N",
"ň": "n",
"ʼn": "n",
"N̆": "N",
"n̆": "n",
"Ō": "O",
"ō": "o",
"Ŏ": "O",
"ŏ": "o",
"Ő": "O",
"ő": "o",
"Œ": "OE",
"œ": "oe",
"P̆": "P",
"p̆": "p",
"Ŕ": "R",
"ŕ": "r",
"Ŗ": "R",
"ŗ": "r",
"Ř": "R",
"ř": "r",
"R̆": "R",
"r̆": "r",
"Ȓ": "R",
"ȓ": "r",
"Ś": "S",
"ś": "s",
"Ŝ": "S",
"ŝ": "s",
"Ş": "S",
"Ș": "S",
"ș": "s",
"ş": "s",
"Š": "S",
"š": "s",
"ß": "ss",
"Ţ": "T",
"ţ": "t",
"ț": "t",
"Ț": "T",
"Ť": "T",
"ť": "t",
"Ŧ": "T",
"ŧ": "t",
"T̆": "T",
"t̆": "t",
"Ũ": "U",
"ũ": "u",
"Ū": "U",
"ū": "u",
"Ŭ": "U",
"ŭ": "u",
"Ů": "U",
"ů": "u",
"Ű": "U",
"ű": "u",
"Ų": "U",
"ų": "u",
"Ȗ": "U",
"ȗ": "u",
"V̆": "V",
"v̆": "v",
"Ŵ": "W",
"ŵ": "w",
"Ẃ": "W",
"ẃ": "w",
"X̆": "X",
"x̆": "x",
"Ŷ": "Y",
"ŷ": "y",
"Ÿ": "Y",
"Y̆": "Y",
"y̆": "y",
"Ź": "Z",
"ź": "z",
"Ż": "Z",
"ż": "z",
"Ž": "Z",
"ž": "z",
"ſ": "s",
"ƒ": "f",
"Ơ": "O",
"ơ": "o",
"Ư": "U",
"ư": "u",
"Ǎ": "A",
"ǎ": "a",
"Ǐ": "I",
"ǐ": "i",
"Ǒ": "O",
"ǒ": "o",
"Ǔ": "U",
"ǔ": "u",
"Ǖ": "U",
"ǖ": "u",
"Ǘ": "U",
"ǘ": "u",
"Ǚ": "U",
"ǚ": "u",
"Ǜ": "U",
"ǜ": "u",
"Ứ": "U",
"ứ": "u",
"Ṹ": "U",
"ṹ": "u",
"Ǻ": "A",
"ǻ": "a",
"Ǽ": "AE",
"ǽ": "ae",
"Ǿ": "O",
"ǿ": "o",
"Þ": "TH",
"þ": "th",
"Ṕ": "P",
"ṕ": "p",
"Ṥ": "S",
"ṥ": "s",
"X́": "X",
"x́": "x",
"Ѓ": "Г",
"ѓ": "г",
"Ќ": "К",
"ќ": "к",
"A̋": "A",
"a̋": "a",
"E̋": "E",
"e̋": "e",
"I̋": "I",
"i̋": "i",
"Ǹ": "N",
"ǹ": "n",
"Ồ": "O",
"ồ": "o",
"Ṑ": "O",
"ṑ": "o",
"Ừ": "U",
"ừ": "u",
"Ẁ": "W",
"ẁ": "w",
"Ỳ": "Y",
"ỳ": "y",
"Ȁ": "A",
"ȁ": "a",
"Ȅ": "E",
"ȅ": "e",
"Ȉ": "I",
"ȉ": "i",
"Ȍ": "O",
"ȍ": "o",
"Ȑ": "R",
"ȑ": "r",
"Ȕ": "U",
"ȕ": "u",
"B̌": "B",
"b̌": "b",
"Č̣": "C",
"č̣": "c",
"Ê̌": "E",
"ê̌": "e",
"F̌": "F",
"f̌": "f",
"Ǧ": "G",
"ǧ": "g",
"Ȟ": "H",
"ȟ": "h",
"J̌": "J",
"ǰ": "j",
"Ǩ": "K",
"ǩ": "k",
"M̌": "M",
"m̌": "m",
"P̌": "P",
"p̌": "p",
"Q̌": "Q",
"q̌": "q",
"Ř̩": "R",
"ř̩": "r",
"Ṧ": "S",
"ṧ": "s",
"V̌": "V",
"v̌": "v",
"W̌": "W",
"w̌": "w",
"X̌": "X",
"x̌": "x",
"Y̌": "Y",
"y̌": "y",
"A̧": "A",
"a̧": "a",
"B̧": "B",
"b̧": "b",
"Ḑ": "D",
"ḑ": "d",
"Ȩ": "E",
"ȩ": "e",
"Ɛ̧": "E",
"ɛ̧": "e",
"Ḩ": "H",
"ḩ": "h",
"I̧": "I",
"i̧": "i",
"Ɨ̧": "I",
"ɨ̧": "i",
"M̧": "M",
"m̧": "m",
"O̧": "O",
"o̧": "o",
"Q̧": "Q",
"q̧": "q",
"U̧": "U",
"u̧": "u",
"X̧": "X",
"x̧": "x",
"Z̧": "Z",
"z̧": "z",
"й":"и",
"Й":"И",
"ё":"е",
"Ё":"Е",
};
var chars = Object.keys(characterMap).join('|');
var allAccents = new RegExp(chars, 'g');
var firstAccent = new RegExp(chars, '');
function matcher(match) {
return characterMap[match];
}
var removeAccents = function(string) {
return string.replace(allAccents, matcher);
};
var hasAccents = function(string) {
return !!string.match(firstAccent);
};
module.exports = removeAccents;
module.exports.has = hasAccents;
module.exports.remove = removeAccents;
/***/ }),
/***/ 7308:
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;;/*! showdown v 1.9.1 - 02-11-2019 */
(function(){
/**
* Created by Tivie on 13-07-2015.
*/
function getDefaultOpts (simple) {
'use strict';
var defaultOptions = {
omitExtraWLInCodeBlocks: {
defaultValue: false,
describe: 'Omit the default extra whiteline added to code blocks',
type: 'boolean'
},
noHeaderId: {
defaultValue: false,
describe: 'Turn on/off generated header id',
type: 'boolean'
},
prefixHeaderId: {
defaultValue: false,
describe: 'Add a prefix to the generated header ids. Passing a string will prefix that string to the header id. Setting to true will add a generic \'section-\' prefix',
type: 'string'
},
rawPrefixHeaderId: {
defaultValue: false,
describe: 'Setting this option to true will prevent showdown from modifying the prefix. This might result in malformed IDs (if, for instance, the " char is used in the prefix)',
type: 'boolean'
},
ghCompatibleHeaderId: {
defaultValue: false,
describe: 'Generate header ids compatible with github style (spaces are replaced with dashes, a bunch of non alphanumeric chars are removed)',
type: 'boolean'
},
rawHeaderId: {
defaultValue: false,
describe: 'Remove only spaces, \' and " from generated header ids (including prefixes), replacing them with dashes (-). WARNING: This might result in malformed ids',
type: 'boolean'
},
headerLevelStart: {
defaultValue: false,
describe: 'The header blocks level start',
type: 'integer'
},
parseImgDimensions: {
defaultValue: false,
describe: 'Turn on/off image dimension parsing',
type: 'boolean'
},
simplifiedAutoLink: {
defaultValue: false,
describe: 'Turn on/off GFM autolink style',
type: 'boolean'
},
excludeTrailingPunctuationFromURLs: {
defaultValue: false,
describe: 'Excludes trailing punctuation from links generated with autoLinking',
type: 'boolean'
},
literalMidWordUnderscores: {
defaultValue: false,
describe: 'Parse midword underscores as literal underscores',
type: 'boolean'
},
literalMidWordAsterisks: {
defaultValue: false,
describe: 'Parse midword asterisks as literal asterisks',
type: 'boolean'
},
strikethrough: {
defaultValue: false,
describe: 'Turn on/off strikethrough support',
type: 'boolean'
},
tables: {
defaultValue: false,
describe: 'Turn on/off tables support',
type: 'boolean'
},
tablesHeaderId: {
defaultValue: false,
describe: 'Add an id to table headers',
type: 'boolean'
},
ghCodeBlocks: {
defaultValue: true,
describe: 'Turn on/off GFM fenced code blocks support',
type: 'boolean'
},
tasklists: {
defaultValue: false,
describe: 'Turn on/off GFM tasklist support',
type: 'boolean'
},
smoothLivePreview: {
defaultValue: false,
describe: 'Prevents weird effects in live previews due to incomplete input',
type: 'boolean'
},
smartIndentationFix: {
defaultValue: false,
description: 'Tries to smartly fix indentation in es6 strings',
type: 'boolean'
},
disableForced4SpacesIndentedSublists: {
defaultValue: false,
description: 'Disables the requirement of indenting nested sublists by 4 spaces',
type: 'boolean'
},
simpleLineBreaks: {
defaultValue: false,
description: 'Parses simple line breaks as <br> (GFM Style)',
type: 'boolean'
},
requireSpaceBeforeHeadingText: {
defaultValue: false,
description: 'Makes adding a space between `#` and the header text mandatory (GFM Style)',
type: 'boolean'
},
ghMentions: {
defaultValue: false,
description: 'Enables github @mentions',
type: 'boolean'
},
ghMentionsLink: {
defaultValue: 'https://github.com/{u}',
description: 'Changes the link generated by @mentions. Only applies if ghMentions option is enabled.',
type: 'string'
},
encodeEmails: {
defaultValue: true,
description: 'Encode e-mail addresses through the use of Character Entities, transforming ASCII e-mail addresses into its equivalent decimal entities',
type: 'boolean'
},
openLinksInNewWindow: {
defaultValue: false,
description: 'Open all links in new windows',
type: 'boolean'
},
backslashEscapesHTMLTags: {
defaultValue: false,
description: 'Support for HTML Tag escaping. ex: \<div>foo\</div>',
type: 'boolean'
},
emoji: {
defaultValue: false,
description: 'Enable emoji support. Ex: `this is a :smile: emoji`',
type: 'boolean'
},
underline: {
defaultValue: false,
description: 'Enable support for underline. Syntax is double or triple underscores: `__underline word__`. With this option enabled, underscores no longer parses into `<em>` and `<strong>`',
type: 'boolean'
},
completeHTMLDocument: {
defaultValue: false,
description: 'Outputs a complete html document, including `<html>`, `<head>` and `<body>` tags',
type: 'boolean'
},
metadata: {
defaultValue: false,
description: 'Enable support for document metadata (defined at the top of the document between `«««` and `»»»` or between `---` and `---`).',
type: 'boolean'
},
splitAdjacentBlockquotes: {
defaultValue: false,
description: 'Split adjacent blockquote blocks',
type: 'boolean'
}
};
if (simple === false) {
return JSON.parse(JSON.stringify(defaultOptions));
}
var ret = {};
for (var opt in defaultOptions) {
if (defaultOptions.hasOwnProperty(opt)) {
ret[opt] = defaultOptions[opt].defaultValue;
}
}
return ret;
}
function allOptionsOn () {
'use strict';
var options = getDefaultOpts(true),
ret = {};
for (var opt in options) {
if (options.hasOwnProperty(opt)) {
ret[opt] = true;
}
}
return ret;
}
/**
* Created by Tivie on 06-01-2015.
*/
// Private properties
var showdown = {},
parsers = {},
extensions = {},
globalOptions = getDefaultOpts(true),
setFlavor = 'vanilla',
flavor = {
github: {
omitExtraWLInCodeBlocks: true,
simplifiedAutoLink: true,
excludeTrailingPunctuationFromURLs: true,
literalMidWordUnderscores: true,
strikethrough: true,
tables: true,
tablesHeaderId: true,
ghCodeBlocks: true,
tasklists: true,
disableForced4SpacesIndentedSublists: true,
simpleLineBreaks: true,
requireSpaceBeforeHeadingText: true,
ghCompatibleHeaderId: true,
ghMentions: true,
backslashEscapesHTMLTags: true,
emoji: true,
splitAdjacentBlockquotes: true
},
original: {
noHeaderId: true,
ghCodeBlocks: false
},
ghost: {
omitExtraWLInCodeBlocks: true,
parseImgDimensions: true,
simplifiedAutoLink: true,
excludeTrailingPunctuationFromURLs: true,
literalMidWordUnderscores: true,
strikethrough: true,
tables: true,
tablesHeaderId: true,
ghCodeBlocks: true,
tasklists: true,
smoothLivePreview: true,
simpleLineBreaks: true,
requireSpaceBeforeHeadingText: true,
ghMentions: false,
encodeEmails: true
},
vanilla: getDefaultOpts(true),
allOn: allOptionsOn()
};
/**
* helper namespace
* @type {{}}
*/
showdown.helper = {};
/**
* TODO LEGACY SUPPORT CODE
* @type {{}}
*/
showdown.extensions = {};
/**
* Set a global option
* @static
* @param {string} key
* @param {*} value
* @returns {showdown}
*/
showdown.setOption = function (key, value) {
'use strict';
globalOptions[key] = value;
return this;
};
/**
* Get a global option
* @static
* @param {string} key
* @returns {*}
*/
showdown.getOption = function (key) {
'use strict';
return globalOptions[key];
};
/**
* Get the global options
* @static
* @returns {{}}
*/
showdown.getOptions = function () {
'use strict';
return globalOptions;
};
/**
* Reset global options to the default values
* @static
*/
showdown.resetOptions = function () {
'use strict';
globalOptions = getDefaultOpts(true);
};
/**
* Set the flavor showdown should use as default
* @param {string} name
*/
showdown.setFlavor = function (name) {
'use strict';
if (!flavor.hasOwnProperty(name)) {
throw Error(name + ' flavor was not found');
}
showdown.resetOptions();
var preset = flavor[name];
setFlavor = name;
for (var option in preset) {
if (preset.hasOwnProperty(option)) {
globalOptions[option] = preset[option];
}
}
};
/**
* Get the currently set flavor
* @returns {string}
*/
showdown.getFlavor = function () {
'use strict';
return setFlavor;
};
/**
* Get the options of a specified flavor. Returns undefined if the flavor was not found
* @param {string} name Name of the flavor
* @returns {{}|undefined}
*/
showdown.getFlavorOptions = function (name) {
'use strict';
if (flavor.hasOwnProperty(name)) {
return flavor[name];
}
};
/**
* Get the default options
* @static
* @param {boolean} [simple=true]
* @returns {{}}
*/
showdown.getDefaultOptions = function (simple) {
'use strict';
return getDefaultOpts(simple);
};
/**
* Get or set a subParser
*
* subParser(name) - Get a registered subParser
* subParser(name, func) - Register a subParser
* @static
* @param {string} name
* @param {function} [func]
* @returns {*}
*/
showdown.subParser = function (name, func) {
'use strict';
if (showdown.helper.isString(name)) {
if (typeof func !== 'undefined') {
parsers[name] = func;
} else {
if (parsers.hasOwnProperty(name)) {
return parsers[name];
} else {
throw Error('SubParser named ' + name + ' not registered!');
}
}
}
};
/**
* Gets or registers an extension
* @static
* @param {string} name
* @param {object|function=} ext
* @returns {*}
*/
showdown.extension = function (name, ext) {
'use strict';
if (!showdown.helper.isString(name)) {
throw Error('Extension \'name\' must be a string');
}
name = showdown.helper.stdExtName(name);
// Getter
if (showdown.helper.isUndefined(ext)) {
if (!extensions.hasOwnProperty(name)) {
throw Error('Extension named ' + name + ' is not registered!');
}
return extensions[name];
// Setter
} else {
// Expand extension if it's wrapped in a function
if (typeof ext === 'function') {
ext = ext();
}
// Ensure extension is an array
if (!showdown.helper.isArray(ext)) {
ext = [ext];
}
var validExtension = validate(ext, name);
if (validExtension.valid) {
extensions[name] = ext;
} else {
throw Error(validExtension.error);
}
}
};
/**
* Gets all extensions registered
* @returns {{}}
*/
showdown.getAllExtensions = function () {
'use strict';
return extensions;
};
/**
* Remove an extension
* @param {string} name
*/
showdown.removeExtension = function (name) {
'use strict';
delete extensions[name];
};
/**
* Removes all extensions
*/
showdown.resetExtensions = function () {
'use strict';
extensions = {};
};
/**
* Validate extension
* @param {array} extension
* @param {string} name
* @returns {{valid: boolean, error: string}}
*/
function validate (extension, name) {
'use strict';
var errMsg = (name) ? 'Error in ' + name + ' extension->' : 'Error in unnamed extension',
ret = {
valid: true,
error: ''
};
if (!showdown.helper.isArray(extension)) {
extension = [extension];
}
for (var i = 0; i < extension.length; ++i) {
var baseMsg = errMsg + ' sub-extension ' + i + ': ',
ext = extension[i];
if (typeof ext !== 'object') {
ret.valid = false;
ret.error = baseMsg + 'must be an object, but ' + typeof ext + ' given';
return ret;
}
if (!showdown.helper.isString(ext.type)) {
ret.valid = false;
ret.error = baseMsg + 'property "type" must be a string, but ' + typeof ext.type + ' given';
return ret;
}
var type = ext.type = ext.type.toLowerCase();
// normalize extension type
if (type === 'language') {
type = ext.type = 'lang';
}
if (type === 'html') {
type = ext.type = 'output';
}
if (type !== 'lang' && type !== 'output' && type !== 'listener') {
ret.valid = false;
ret.error = baseMsg + 'type ' + type + ' is not recognized. Valid values: "lang/language", "output/html" or "listener"';
return ret;
}
if (type === 'listener') {
if (showdown.helper.isUndefined(ext.listeners)) {
ret.valid = false;
ret.error = baseMsg + '. Extensions of type "listener" must have a property called "listeners"';
return ret;
}
} else {
if (showdown.helper.isUndefined(ext.filter) && showdown.helper.isUndefined(ext.regex)) {
ret.valid = false;
ret.error = baseMsg + type + ' extensions must define either a "regex" property or a "filter" method';
return ret;
}
}
if (ext.listeners) {
if (typeof ext.listeners !== 'object') {
ret.valid = false;
ret.error = baseMsg + '"listeners" property must be an object but ' + typeof ext.listeners + ' given';
return ret;
}
for (var ln in ext.listeners) {
if (ext.listeners.hasOwnProperty(ln)) {
if (typeof ext.listeners[ln] !== 'function') {
ret.valid = false;
ret.error = baseMsg + '"listeners" property must be an hash of [event name]: [callback]. listeners.' + ln +
' must be a function but ' + typeof ext.listeners[ln] + ' given';
return ret;
}
}
}
}
if (ext.filter) {
if (typeof ext.filter !== 'function') {
ret.valid = false;
ret.error = baseMsg + '"filter" must be a function, but ' + typeof ext.filter + ' given';
return ret;
}
} else if (ext.regex) {
if (showdown.helper.isString(ext.regex)) {
ext.regex = new RegExp(ext.regex, 'g');
}
if (!(ext.regex instanceof RegExp)) {
ret.valid = false;
ret.error = baseMsg + '"regex" property must either be a string or a RegExp object, but ' + typeof ext.regex + ' given';
return ret;
}
if (showdown.helper.isUndefined(ext.replace)) {
ret.valid = false;
ret.error = baseMsg + '"regex" extensions must implement a replace string or function';
return ret;
}
}
}
return ret;
}
/**
* Validate extension
* @param {object} ext
* @returns {boolean}
*/
showdown.validateExtension = function (ext) {
'use strict';
var validateExtension = validate(ext, null);
if (!validateExtension.valid) {
console.warn(validateExtension.error);
return false;
}
return true;
};
/**
* showdownjs helper functions
*/
if (!showdown.hasOwnProperty('helper')) {
showdown.helper = {};
}
/**
* Check if var is string
* @static
* @param {string} a
* @returns {boolean}
*/
showdown.helper.isString = function (a) {
'use strict';
return (typeof a === 'string' || a instanceof String);
};
/**
* Check if var is a function
* @static
* @param {*} a
* @returns {boolean}
*/
showdown.helper.isFunction = function (a) {
'use strict';
var getType = {};
return a && getType.toString.call(a) === '[object Function]';
};
/**
* isArray helper function
* @static
* @param {*} a
* @returns {boolean}
*/
showdown.helper.isArray = function (a) {
'use strict';
return Array.isArray(a);
};
/**
* Check if value is undefined
* @static
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
*/
showdown.helper.isUndefined = function (value) {
'use strict';
return typeof value === 'undefined';
};
/**
* ForEach helper function
* Iterates over Arrays and Objects (own properties only)
* @static
* @param {*} obj
* @param {function} callback Accepts 3 params: 1. value, 2. key, 3. the original array/object
*/
showdown.helper.forEach = function (obj, callback) {
'use strict';
// check if obj is defined
if (showdown.helper.isUndefined(obj)) {
throw new Error('obj param is required');
}
if (showdown.helper.isUndefined(callback)) {
throw new Error('callback param is required');
}
if (!showdown.helper.isFunction(callback)) {
throw new Error('callback param must be a function/closure');
}
if (typeof obj.forEach === 'function') {
obj.forEach(callback);
} else if (showdown.helper.isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
callback(obj[i], i, obj);
}
} else if (typeof (obj) === 'object') {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
callback(obj[prop], prop, obj);
}
}
} else {
throw new Error('obj does not seem to be an array or an iterable object');
}
};
/**
* Standardidize extension name
* @static
* @param {string} s extension name
* @returns {string}
*/
showdown.helper.stdExtName = function (s) {
'use strict';
return s.replace(/[_?*+\/\\.^-]/g, '').replace(/\s/g, '').toLowerCase();
};
function escapeCharactersCallback (wholeMatch, m1) {
'use strict';
var charCodeToEscape = m1.charCodeAt(0);
return '¨E' + charCodeToEscape + 'E';
}
/**
* Callback used to escape characters when passing through String.replace
* @static
* @param {string} wholeMatch
* @param {string} m1
* @returns {string}
*/
showdown.helper.escapeCharactersCallback = escapeCharactersCallback;
/**
* Escape characters in a string
* @static
* @param {string} text
* @param {string} charsToEscape
* @param {boolean} afterBackslash
* @returns {XML|string|void|*}
*/
showdown.helper.escapeCharacters = function (text, charsToEscape, afterBackslash) {
'use strict';
// First we have to escape the escape characters so that
// we can build a character class out of them
var regexString = '([' + charsToEscape.replace(/([\[\]\\])/g, '\\$1') + '])';
if (afterBackslash) {
regexString = '\\\\' + regexString;
}
var regex = new RegExp(regexString, 'g');
text = text.replace(regex, escapeCharactersCallback);
return text;
};
/**
* Unescape HTML entities
* @param txt
* @returns {string}
*/
showdown.helper.unescapeHTMLEntities = function (txt) {
'use strict';
return txt
.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&');
};
var rgxFindMatchPos = function (str, left, right, flags) {
'use strict';
var f = flags || '',
g = f.indexOf('g') > -1,
x = new RegExp(left + '|' + right, 'g' + f.replace(/g/g, '')),
l = new RegExp(left, f.replace(/g/g, '')),
pos = [],
t, s, m, start, end;
do {
t = 0;
while ((m = x.exec(str))) {
if (l.test(m[0])) {
if (!(t++)) {
s = x.lastIndex;
start = s - m[0].length;
}
} else if (t) {
if (!--t) {
end = m.index + m[0].length;
var obj = {
left: {start: start, end: s},
match: {start: s, end: m.index},
right: {start: m.index, end: end},
wholeMatch: {start: start, end: end}
};
pos.push(obj);
if (!g) {
return pos;
}
}
}
}
} while (t && (x.lastIndex = s));
return pos;
};
/**
* matchRecursiveRegExp
*
* (c) 2007 Steven Levithan <stevenlevithan.com>
* MIT License
*
* Accepts a string to search, a left and right format delimiter
* as regex patterns, and optional regex flags. Returns an array
* of matches, allowing nested instances of left/right delimiters.
* Use the "g" flag to return all matches, otherwise only the
* first is returned. Be careful to ensure that the left and
* right format delimiters produce mutually exclusive matches.
* Backreferences are not supported within the right delimiter
* due to how it is internally combined with the left delimiter.
* When matching strings whose format delimiters are unbalanced
* to the left or right, the output is intentionally as a
* conventional regex library with recursion support would
* produce, e.g. "<<x>" and "<x>>" both produce ["x"] when using
* "<" and ">" as the delimiters (both strings contain a single,
* balanced instance of "<x>").
*
* examples:
* matchRecursiveRegExp("test", "\\(", "\\)")
* returns: []
* matchRecursiveRegExp("<t<<e>><s>>t<>", "<", ">", "g")
* returns: ["t<<e>><s>", ""]
* matchRecursiveRegExp("<div id=\"x\">test</div>", "<div\\b[^>]*>", "</div>", "gi")
* returns: ["test"]
*/
showdown.helper.matchRecursiveRegExp = function (str, left, right, flags) {
'use strict';
var matchPos = rgxFindMatchPos (str, left, right, flags),
results = [];
for (var i = 0; i < matchPos.length; ++i) {
results.push([
str.slice(matchPos[i].wholeMatch.start, matchPos[i].wholeMatch.end),
str.slice(matchPos[i].match.start, matchPos[i].match.end),
str.slice(matchPos[i].left.start, matchPos[i].left.end),
str.slice(matchPos[i].right.start, matchPos[i].right.end)
]);
}
return results;
};
/**
*
* @param {string} str
* @param {string|function} replacement
* @param {string} left
* @param {string} right
* @param {string} flags
* @returns {string}
*/
showdown.helper.replaceRecursiveRegExp = function (str, replacement, left, right, flags) {
'use strict';
if (!showdown.helper.isFunction(replacement)) {
var repStr = replacement;
replacement = function () {
return repStr;
};
}
var matchPos = rgxFindMatchPos(str, left, right, flags),
finalStr = str,
lng = matchPos.length;
if (lng > 0) {
var bits = [];
if (matchPos[0].wholeMatch.start !== 0) {
bits.push(str.slice(0, matchPos[0].wholeMatch.start));
}
for (var i = 0; i < lng; ++i) {
bits.push(
replacement(
str.slice(matchPos[i].wholeMatch.start, matchPos[i].wholeMatch.end),
str.slice(matchPos[i].match.start, matchPos[i].match.end),
str.slice(matchPos[i].left.start, matchPos[i].left.end),
str.slice(matchPos[i].right.start, matchPos[i].right.end)
)
);
if (i < lng - 1) {
bits.push(str.slice(matchPos[i].wholeMatch.end, matchPos[i + 1].wholeMatch.start));
}
}
if (matchPos[lng - 1].wholeMatch.end < str.length) {
bits.push(str.slice(matchPos[lng - 1].wholeMatch.end));
}
finalStr = bits.join('');
}
return finalStr;
};
/**
* Returns the index within the passed String object of the first occurrence of the specified regex,
* starting the search at fromIndex. Returns -1 if the value is not found.
*
* @param {string} str string to search
* @param {RegExp} regex Regular expression to search
* @param {int} [fromIndex = 0] Index to start the search
* @returns {Number}
* @throws InvalidArgumentError
*/
showdown.helper.regexIndexOf = function (str, regex, fromIndex) {
'use strict';
if (!showdown.helper.isString(str)) {
throw 'InvalidArgumentError: first parameter of showdown.helper.regexIndexOf function must be a string';
}
if (regex instanceof RegExp === false) {
throw 'InvalidArgumentError: second parameter of showdown.helper.regexIndexOf function must be an instance of RegExp';
}
var indexOf = str.substring(fromIndex || 0).search(regex);
return (indexOf >= 0) ? (indexOf + (fromIndex || 0)) : indexOf;
};
/**
* Splits the passed string object at the defined index, and returns an array composed of the two substrings
* @param {string} str string to split
* @param {int} index index to split string at
* @returns {[string,string]}
* @throws InvalidArgumentError
*/
showdown.helper.splitAtIndex = function (str, index) {
'use strict';
if (!showdown.helper.isString(str)) {
throw 'InvalidArgumentError: first parameter of showdown.helper.regexIndexOf function must be a string';
}
return [str.substring(0, index), str.substring(index)];
};
/**
* Obfuscate an e-mail address through the use of Character Entities,
* transforming ASCII characters into their equivalent decimal or hex entities.
*
* Since it has a random component, subsequent calls to this function produce different results
*
* @param {string} mail
* @returns {string}
*/
showdown.helper.encodeEmailAddress = function (mail) {
'use strict';
var encode = [
function (ch) {
return '&#' + ch.charCodeAt(0) + ';';
},
function (ch) {
return '&#x' + ch.charCodeAt(0).toString(16) + ';';
},
function (ch) {
return ch;
}
];
mail = mail.replace(/./g, function (ch) {
if (ch === '@') {
// this *must* be encoded. I insist.
ch = encode[Math.floor(Math.random() * 2)](ch);
} else {
var r = Math.random();
// roughly 10% raw, 45% hex, 45% dec
ch = (
r > 0.9 ? encode[2](ch) : r > 0.45 ? encode[1](ch) : encode[0](ch)
);
}
return ch;
});
return mail;
};
/**
*
* @param str
* @param targetLength
* @param padString
* @returns {string}
*/
showdown.helper.padEnd = function padEnd (str, targetLength, padString) {
'use strict';
/*jshint bitwise: false*/
// eslint-disable-next-line space-infix-ops
targetLength = targetLength>>0; //floor if number or convert non-number to 0;
/*jshint bitwise: true*/
padString = String(padString || ' ');
if (str.length > targetLength) {
return String(str);
} else {
targetLength = targetLength - str.length;
if (targetLength > padString.length) {
padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed
}
return String(str) + padString.slice(0,targetLength);
}
};
/**
* POLYFILLS
*/
// use this instead of builtin is undefined for IE8 compatibility
if (typeof console === 'undefined') {
console = {
warn: function (msg) {
'use strict';
alert(msg);
},
log: function (msg) {
'use strict';
alert(msg);
},
error: function (msg) {
'use strict';
throw msg;
}
};
}
/**
* Common regexes.
* We declare some common regexes to improve performance
*/
showdown.helper.regexes = {
asteriskDashAndColon: /([*_:~])/g
};
/**
* EMOJIS LIST
*/
showdown.helper.emojis = {
'+1':'\ud83d\udc4d',
'-1':'\ud83d\udc4e',
'100':'\ud83d\udcaf',
'1234':'\ud83d\udd22',
'1st_place_medal':'\ud83e\udd47',
'2nd_place_medal':'\ud83e\udd48',
'3rd_place_medal':'\ud83e\udd49',
'8ball':'\ud83c\udfb1',
'a':'\ud83c\udd70\ufe0f',
'ab':'\ud83c\udd8e',
'abc':'\ud83d\udd24',
'abcd':'\ud83d\udd21',
'accept':'\ud83c\ude51',
'aerial_tramway':'\ud83d\udea1',
'airplane':'\u2708\ufe0f',
'alarm_clock':'\u23f0',
'alembic':'\u2697\ufe0f',
'alien':'\ud83d\udc7d',
'ambulance':'\ud83d\ude91',
'amphora':'\ud83c\udffa',
'anchor':'\u2693\ufe0f',
'angel':'\ud83d\udc7c',
'anger':'\ud83d\udca2',
'angry':'\ud83d\ude20',
'anguished':'\ud83d\ude27',
'ant':'\ud83d\udc1c',
'apple':'\ud83c\udf4e',
'aquarius':'\u2652\ufe0f',
'aries':'\u2648\ufe0f',
'arrow_backward':'\u25c0\ufe0f',
'arrow_double_down':'\u23ec',
'arrow_double_up':'\u23eb',
'arrow_down':'\u2b07\ufe0f',
'arrow_down_small':'\ud83d\udd3d',
'arrow_forward':'\u25b6\ufe0f',
'arrow_heading_down':'\u2935\ufe0f',
'arrow_heading_up':'\u2934\ufe0f',
'arrow_left':'\u2b05\ufe0f',
'arrow_lower_left':'\u2199\ufe0f',
'arrow_lower_right':'\u2198\ufe0f',
'arrow_right':'\u27a1\ufe0f',
'arrow_right_hook':'\u21aa\ufe0f',
'arrow_up':'\u2b06\ufe0f',
'arrow_up_down':'\u2195\ufe0f',
'arrow_up_small':'\ud83d\udd3c',
'arrow_upper_left':'\u2196\ufe0f',
'arrow_upper_right':'\u2197\ufe0f',
'arrows_clockwise':'\ud83d\udd03',
'arrows_counterclockwise':'\ud83d\udd04',
'art':'\ud83c\udfa8',
'articulated_lorry':'\ud83d\ude9b',
'artificial_satellite':'\ud83d\udef0',
'astonished':'\ud83d\ude32',
'athletic_shoe':'\ud83d\udc5f',
'atm':'\ud83c\udfe7',
'atom_symbol':'\u269b\ufe0f',
'avocado':'\ud83e\udd51',
'b':'\ud83c\udd71\ufe0f',
'baby':'\ud83d\udc76',
'baby_bottle':'\ud83c\udf7c',
'baby_chick':'\ud83d\udc24',
'baby_symbol':'\ud83d\udebc',
'back':'\ud83d\udd19',
'bacon':'\ud83e\udd53',
'badminton':'\ud83c\udff8',
'baggage_claim':'\ud83d\udec4',
'baguette_bread':'\ud83e\udd56',
'balance_scale':'\u2696\ufe0f',
'balloon':'\ud83c\udf88',
'ballot_box':'\ud83d\uddf3',
'ballot_box_with_check':'\u2611\ufe0f',
'bamboo':'\ud83c\udf8d',
'banana':'\ud83c\udf4c',
'bangbang':'\u203c\ufe0f',
'bank':'\ud83c\udfe6',
'bar_chart':'\ud83d\udcca',
'barber':'\ud83d\udc88',
'baseball':'\u26be\ufe0f',
'basketball':'\ud83c\udfc0',
'basketball_man':'\u26f9\ufe0f',
'basketball_woman':'\u26f9\ufe0f‍\u2640\ufe0f',
'bat':'\ud83e\udd87',
'bath':'\ud83d\udec0',
'bathtub':'\ud83d\udec1',
'battery':'\ud83d\udd0b',
'beach_umbrella':'\ud83c\udfd6',
'bear':'\ud83d\udc3b',
'bed':'\ud83d\udecf',
'bee':'\ud83d\udc1d',
'beer':'\ud83c\udf7a',
'beers':'\ud83c\udf7b',
'beetle':'\ud83d\udc1e',
'beginner':'\ud83d\udd30',
'bell':'\ud83d\udd14',
'bellhop_bell':'\ud83d\udece',
'bento':'\ud83c\udf71',
'biking_man':'\ud83d\udeb4',
'bike':'\ud83d\udeb2',
'biking_woman':'\ud83d\udeb4‍\u2640\ufe0f',
'bikini':'\ud83d\udc59',
'biohazard':'\u2623\ufe0f',
'bird':'\ud83d\udc26',
'birthday':'\ud83c\udf82',
'black_circle':'\u26ab\ufe0f',
'black_flag':'\ud83c\udff4',
'black_heart':'\ud83d\udda4',
'black_joker':'\ud83c\udccf',
'black_large_square':'\u2b1b\ufe0f',
'black_medium_small_square':'\u25fe\ufe0f',
'black_medium_square':'\u25fc\ufe0f',
'black_nib':'\u2712\ufe0f',
'black_small_square':'\u25aa\ufe0f',
'black_square_button':'\ud83d\udd32',
'blonde_man':'\ud83d\udc71',
'blonde_woman':'\ud83d\udc71‍\u2640\ufe0f',
'blossom':'\ud83c\udf3c',
'blowfish':'\ud83d\udc21',
'blue_book':'\ud83d\udcd8',
'blue_car':'\ud83d\ude99',
'blue_heart':'\ud83d\udc99',
'blush':'\ud83d\ude0a',
'boar':'\ud83d\udc17',
'boat':'\u26f5\ufe0f',
'bomb':'\ud83d\udca3',
'book':'\ud83d\udcd6',
'bookmark':'\ud83d\udd16',
'bookmark_tabs':'\ud83d\udcd1',
'books':'\ud83d\udcda',
'boom':'\ud83d\udca5',
'boot':'\ud83d\udc62',
'bouquet':'\ud83d\udc90',
'bowing_man':'\ud83d\ude47',
'bow_and_arrow':'\ud83c\udff9',
'bowing_woman':'\ud83d\ude47‍\u2640\ufe0f',
'bowling':'\ud83c\udfb3',
'boxing_glove':'\ud83e\udd4a',
'boy':'\ud83d\udc66',
'bread':'\ud83c\udf5e',
'bride_with_veil':'\ud83d\udc70',
'bridge_at_night':'\ud83c\udf09',
'briefcase':'\ud83d\udcbc',
'broken_heart':'\ud83d\udc94',
'bug':'\ud83d\udc1b',
'building_construction':'\ud83c\udfd7',
'bulb':'\ud83d\udca1',
'bullettrain_front':'\ud83d\ude85',
'bullettrain_side':'\ud83d\ude84',
'burrito':'\ud83c\udf2f',
'bus':'\ud83d\ude8c',
'business_suit_levitating':'\ud83d\udd74',
'busstop':'\ud83d\ude8f',
'bust_in_silhouette':'\ud83d\udc64',
'busts_in_silhouette':'\ud83d\udc65',
'butterfly':'\ud83e\udd8b',
'cactus':'\ud83c\udf35',
'cake':'\ud83c\udf70',
'calendar':'\ud83d\udcc6',
'call_me_hand':'\ud83e\udd19',
'calling':'\ud83d\udcf2',
'camel':'\ud83d\udc2b',
'camera':'\ud83d\udcf7',
'camera_flash':'\ud83d\udcf8',
'camping':'\ud83c\udfd5',
'cancer':'\u264b\ufe0f',
'candle':'\ud83d\udd6f',
'candy':'\ud83c\udf6c',
'canoe':'\ud83d\udef6',
'capital_abcd':'\ud83d\udd20',
'capricorn':'\u2651\ufe0f',
'car':'\ud83d\ude97',
'card_file_box':'\ud83d\uddc3',
'card_index':'\ud83d\udcc7',
'card_index_dividers':'\ud83d\uddc2',
'carousel_horse':'\ud83c\udfa0',
'carrot':'\ud83e\udd55',
'cat':'\ud83d\udc31',
'cat2':'\ud83d\udc08',
'cd':'\ud83d\udcbf',
'chains':'\u26d3',
'champagne':'\ud83c\udf7e',
'chart':'\ud83d\udcb9',
'chart_with_downwards_trend':'\ud83d\udcc9',
'chart_with_upwards_trend':'\ud83d\udcc8',
'checkered_flag':'\ud83c\udfc1',
'cheese':'\ud83e\uddc0',
'cherries':'\ud83c\udf52',
'cherry_blossom':'\ud83c\udf38',
'chestnut':'\ud83c\udf30',
'chicken':'\ud83d\udc14',
'children_crossing':'\ud83d\udeb8',
'chipmunk':'\ud83d\udc3f',
'chocolate_bar':'\ud83c\udf6b',
'christmas_tree':'\ud83c\udf84',
'church':'\u26ea\ufe0f',
'cinema':'\ud83c\udfa6',
'circus_tent':'\ud83c\udfaa',
'city_sunrise':'\ud83c\udf07',
'city_sunset':'\ud83c\udf06',
'cityscape':'\ud83c\udfd9',
'cl':'\ud83c\udd91',
'clamp':'\ud83d\udddc',
'clap':'\ud83d\udc4f',
'clapper':'\ud83c\udfac',
'classical_building':'\ud83c\udfdb',
'clinking_glasses':'\ud83e\udd42',
'clipboard':'\ud83d\udccb',
'clock1':'\ud83d\udd50',
'clock10':'\ud83d\udd59',
'clock1030':'\ud83d\udd65',
'clock11':'\ud83d\udd5a',
'clock1130':'\ud83d\udd66',
'clock12':'\ud83d\udd5b',
'clock1230':'\ud83d\udd67',
'clock130':'\ud83d\udd5c',
'clock2':'\ud83d\udd51',
'clock230':'\ud83d\udd5d',
'clock3':'\ud83d\udd52',
'clock330':'\ud83d\udd5e',
'clock4':'\ud83d\udd53',
'clock430':'\ud83d\udd5f',
'clock5':'\ud83d\udd54',
'clock530':'\ud83d\udd60',
'clock6':'\ud83d\udd55',
'clock630':'\ud83d\udd61',
'clock7':'\ud83d\udd56',
'clock730':'\ud83d\udd62',
'clock8':'\ud83d\udd57',
'clock830':'\ud83d\udd63',
'clock9':'\ud83d\udd58',
'clock930':'\ud83d\udd64',
'closed_book':'\ud83d\udcd5',
'closed_lock_with_key':'\ud83d\udd10',
'closed_umbrella':'\ud83c\udf02',
'cloud':'\u2601\ufe0f',
'cloud_with_lightning':'\ud83c\udf29',
'cloud_with_lightning_and_rain':'\u26c8',
'cloud_with_rain':'\ud83c\udf27',
'cloud_with_snow':'\ud83c\udf28',
'clown_face':'\ud83e\udd21',
'clubs':'\u2663\ufe0f',
'cocktail':'\ud83c\udf78',
'coffee':'\u2615\ufe0f',
'coffin':'\u26b0\ufe0f',
'cold_sweat':'\ud83d\ude30',
'comet':'\u2604\ufe0f',
'computer':'\ud83d\udcbb',
'computer_mouse':'\ud83d\uddb1',
'confetti_ball':'\ud83c\udf8a',
'confounded':'\ud83d\ude16',
'confused':'\ud83d\ude15',
'congratulations':'\u3297\ufe0f',
'construction':'\ud83d\udea7',
'construction_worker_man':'\ud83d\udc77',
'construction_worker_woman':'\ud83d\udc77‍\u2640\ufe0f',
'control_knobs':'\ud83c\udf9b',
'convenience_store':'\ud83c\udfea',
'cookie':'\ud83c\udf6a',
'cool':'\ud83c\udd92',
'policeman':'\ud83d\udc6e',
'copyright':'\u00a9\ufe0f',
'corn':'\ud83c\udf3d',
'couch_and_lamp':'\ud83d\udecb',
'couple':'\ud83d\udc6b',
'couple_with_heart_woman_man':'\ud83d\udc91',
'couple_with_heart_man_man':'\ud83d\udc68‍\u2764\ufe0f‍\ud83d\udc68',
'couple_with_heart_woman_woman':'\ud83d\udc69‍\u2764\ufe0f‍\ud83d\udc69',
'couplekiss_man_man':'\ud83d\udc68‍\u2764\ufe0f‍\ud83d\udc8b‍\ud83d\udc68',
'couplekiss_man_woman':'\ud83d\udc8f',
'couplekiss_woman_woman':'\ud83d\udc69‍\u2764\ufe0f‍\ud83d\udc8b‍\ud83d\udc69',
'cow':'\ud83d\udc2e',
'cow2':'\ud83d\udc04',
'cowboy_hat_face':'\ud83e\udd20',
'crab':'\ud83e\udd80',
'crayon':'\ud83d\udd8d',
'credit_card':'\ud83d\udcb3',
'crescent_moon':'\ud83c\udf19',
'cricket':'\ud83c\udfcf',
'crocodile':'\ud83d\udc0a',
'croissant':'\ud83e\udd50',
'crossed_fingers':'\ud83e\udd1e',
'crossed_flags':'\ud83c\udf8c',
'crossed_swords':'\u2694\ufe0f',
'crown':'\ud83d\udc51',
'cry':'\ud83d\ude22',
'crying_cat_face':'\ud83d\ude3f',
'crystal_ball':'\ud83d\udd2e',
'cucumber':'\ud83e\udd52',
'cupid':'\ud83d\udc98',
'curly_loop':'\u27b0',
'currency_exchange':'\ud83d\udcb1',
'curry':'\ud83c\udf5b',
'custard':'\ud83c\udf6e',
'customs':'\ud83d\udec3',
'cyclone':'\ud83c\udf00',
'dagger':'\ud83d\udde1',
'dancer':'\ud83d\udc83',
'dancing_women':'\ud83d\udc6f',
'dancing_men':'\ud83d\udc6f‍\u2642\ufe0f',
'dango':'\ud83c\udf61',
'dark_sunglasses':'\ud83d\udd76',
'dart':'\ud83c\udfaf',
'dash':'\ud83d\udca8',
'date':'\ud83d\udcc5',
'deciduous_tree':'\ud83c\udf33',
'deer':'\ud83e\udd8c',
'department_store':'\ud83c\udfec',
'derelict_house':'\ud83c\udfda',
'desert':'\ud83c\udfdc',
'desert_island':'\ud83c\udfdd',
'desktop_computer':'\ud83d\udda5',
'male_detective':'\ud83d\udd75\ufe0f',
'diamond_shape_with_a_dot_inside':'\ud83d\udca0',
'diamonds':'\u2666\ufe0f',
'disappointed':'\ud83d\ude1e',
'disappointed_relieved':'\ud83d\ude25',
'dizzy':'\ud83d\udcab',
'dizzy_face':'\ud83d\ude35',
'do_not_litter':'\ud83d\udeaf',
'dog':'\ud83d\udc36',
'dog2':'\ud83d\udc15',
'dollar':'\ud83d\udcb5',
'dolls':'\ud83c\udf8e',
'dolphin':'\ud83d\udc2c',
'door':'\ud83d\udeaa',
'doughnut':'\ud83c\udf69',
'dove':'\ud83d\udd4a',
'dragon':'\ud83d\udc09',
'dragon_face':'\ud83d\udc32',
'dress':'\ud83d\udc57',
'dromedary_camel':'\ud83d\udc2a',
'drooling_face':'\ud83e\udd24',
'droplet':'\ud83d\udca7',
'drum':'\ud83e\udd41',
'duck':'\ud83e\udd86',
'dvd':'\ud83d\udcc0',
'e-mail':'\ud83d\udce7',
'eagle':'\ud83e\udd85',
'ear':'\ud83d\udc42',
'ear_of_rice':'\ud83c\udf3e',
'earth_africa':'\ud83c\udf0d',
'earth_americas':'\ud83c\udf0e',
'earth_asia':'\ud83c\udf0f',
'egg':'\ud83e\udd5a',
'eggplant':'\ud83c\udf46',
'eight_pointed_black_star':'\u2734\ufe0f',
'eight_spoked_asterisk':'\u2733\ufe0f',
'electric_plug':'\ud83d\udd0c',
'elephant':'\ud83d\udc18',
'email':'\u2709\ufe0f',
'end':'\ud83d\udd1a',
'envelope_with_arrow':'\ud83d\udce9',
'euro':'\ud83d\udcb6',
'european_castle':'\ud83c\udff0',
'european_post_office':'\ud83c\udfe4',
'evergreen_tree':'\ud83c\udf32',
'exclamation':'\u2757\ufe0f',
'expressionless':'\ud83d\ude11',
'eye':'\ud83d\udc41',
'eye_speech_bubble':'\ud83d\udc41‍\ud83d\udde8',
'eyeglasses':'\ud83d\udc53',
'eyes':'\ud83d\udc40',
'face_with_head_bandage':'\ud83e\udd15',
'face_with_thermometer':'\ud83e\udd12',
'fist_oncoming':'\ud83d\udc4a',
'factory':'\ud83c\udfed',
'fallen_leaf':'\ud83c\udf42',
'family_man_woman_boy':'\ud83d\udc6a',
'family_man_boy':'\ud83d\udc68‍\ud83d\udc66',
'family_man_boy_boy':'\ud83d\udc68‍\ud83d\udc66‍\ud83d\udc66',
'family_man_girl':'\ud83d\udc68‍\ud83d\udc67',
'family_man_girl_boy':'\ud83d\udc68‍\ud83d\udc67‍\ud83d\udc66',
'family_man_girl_girl':'\ud83d\udc68‍\ud83d\udc67‍\ud83d\udc67',
'family_man_man_boy':'\ud83d\udc68‍\ud83d\udc68‍\ud83d\udc66',
'family_man_man_boy_boy':'\ud83d\udc68‍\ud83d\udc68‍\ud83d\udc66‍\ud83d\udc66',
'family_man_man_girl':'\ud83d\udc68‍\ud83d\udc68‍\ud83d\udc67',
'family_man_man_girl_boy':'\ud83d\udc68‍\ud83d\udc68‍\ud83d\udc67‍\ud83d\udc66',
'family_man_man_girl_girl':'\ud83d\udc68‍\ud83d\udc68‍\ud83d\udc67‍\ud83d\udc67',
'family_man_woman_boy_boy':'\ud83d\udc68‍\ud83d\udc69‍\ud83d\udc66‍\ud83d\udc66',
'family_man_woman_girl':'\ud83d\udc68‍\ud83d\udc69‍\ud83d\udc67',
'family_man_woman_girl_boy':'\ud83d\udc68‍\ud83d\udc69‍\ud83d\udc67‍\ud83d\udc66',
'family_man_woman_girl_girl':'\ud83d\udc68‍\ud83d\udc69‍\ud83d\udc67‍\ud83d\udc67',
'family_woman_boy':'\ud83d\udc69‍\ud83d\udc66',
'family_woman_boy_boy':'\ud83d\udc69‍\ud83d\udc66‍\ud83d\udc66',
'family_woman_girl':'\ud83d\udc69‍\ud83d\udc67',
'family_woman_girl_boy':'\ud83d\udc69‍\ud83d\udc67‍\ud83d\udc66',
'family_woman_girl_girl':'\ud83d\udc69‍\ud83d\udc67‍\ud83d\udc67',
'family_woman_woman_boy':'\ud83d\udc69‍\ud83d\udc69‍\ud83d\udc66',
'family_woman_woman_boy_boy':'\ud83d\udc69‍\ud83d\udc69‍\ud83d\udc66‍\ud83d\udc66',
'family_woman_woman_girl':'\ud83d\udc69‍\ud83d\udc69‍\ud83d\udc67',
'family_woman_woman_girl_boy':'\ud83d\udc69‍\ud83d\udc69‍\ud83d\udc67‍\ud83d\udc66',
'family_woman_woman_girl_girl':'\ud83d\udc69‍\ud83d\udc69‍\ud83d\udc67‍\ud83d\udc67',
'fast_forward':'\u23e9',
'fax':'\ud83d\udce0',
'fearful':'\ud83d\ude28',
'feet':'\ud83d\udc3e',
'female_detective':'\ud83d\udd75\ufe0f‍\u2640\ufe0f',
'ferris_wheel':'\ud83c\udfa1',
'ferry':'\u26f4',
'field_hockey':'\ud83c\udfd1',
'file_cabinet':'\ud83d\uddc4',
'file_folder':'\ud83d\udcc1',
'film_projector':'\ud83d\udcfd',
'film_strip':'\ud83c\udf9e',
'fire':'\ud83d\udd25',
'fire_engine':'\ud83d\ude92',
'fireworks':'\ud83c\udf86',
'first_quarter_moon':'\ud83c\udf13',
'first_quarter_moon_with_face':'\ud83c\udf1b',
'fish':'\ud83d\udc1f',
'fish_cake':'\ud83c\udf65',
'fishing_pole_and_fish':'\ud83c\udfa3',
'fist_raised':'\u270a',
'fist_left':'\ud83e\udd1b',
'fist_right':'\ud83e\udd1c',
'flags':'\ud83c\udf8f',
'flashlight':'\ud83d\udd26',
'fleur_de_lis':'\u269c\ufe0f',
'flight_arrival':'\ud83d\udeec',
'flight_departure':'\ud83d\udeeb',
'floppy_disk':'\ud83d\udcbe',
'flower_playing_cards':'\ud83c\udfb4',
'flushed':'\ud83d\ude33',
'fog':'\ud83c\udf2b',
'foggy':'\ud83c\udf01',
'football':'\ud83c\udfc8',
'footprints':'\ud83d\udc63',
'fork_and_knife':'\ud83c\udf74',
'fountain':'\u26f2\ufe0f',
'fountain_pen':'\ud83d\udd8b',
'four_leaf_clover':'\ud83c\udf40',
'fox_face':'\ud83e\udd8a',
'framed_picture':'\ud83d\uddbc',
'free':'\ud83c\udd93',
'fried_egg':'\ud83c\udf73',
'fried_shrimp':'\ud83c\udf64',
'fries':'\ud83c\udf5f',
'frog':'\ud83d\udc38',
'frowning':'\ud83d\ude26',
'frowning_face':'\u2639\ufe0f',
'frowning_man':'\ud83d\ude4d‍\u2642\ufe0f',
'frowning_woman':'\ud83d\ude4d',
'middle_finger':'\ud83d\udd95',
'fuelpump':'\u26fd\ufe0f',
'full_moon':'\ud83c\udf15',
'full_moon_with_face':'\ud83c\udf1d',
'funeral_urn':'\u26b1\ufe0f',
'game_die':'\ud83c\udfb2',
'gear':'\u2699\ufe0f',
'gem':'\ud83d\udc8e',
'gemini':'\u264a\ufe0f',
'ghost':'\ud83d\udc7b',
'gift':'\ud83c\udf81',
'gift_heart':'\ud83d\udc9d',
'girl':'\ud83d\udc67',
'globe_with_meridians':'\ud83c\udf10',
'goal_net':'\ud83e\udd45',
'goat':'\ud83d\udc10',
'golf':'\u26f3\ufe0f',
'golfing_man':'\ud83c\udfcc\ufe0f',
'golfing_woman':'\ud83c\udfcc\ufe0f‍\u2640\ufe0f',
'gorilla':'\ud83e\udd8d',
'grapes':'\ud83c\udf47',
'green_apple':'\ud83c\udf4f',
'green_book':'\ud83d\udcd7',
'green_heart':'\ud83d\udc9a',
'green_salad':'\ud83e\udd57',
'grey_exclamation':'\u2755',
'grey_question':'\u2754',
'grimacing':'\ud83d\ude2c',
'grin':'\ud83d\ude01',
'grinning':'\ud83d\ude00',
'guardsman':'\ud83d\udc82',
'guardswoman':'\ud83d\udc82‍\u2640\ufe0f',
'guitar':'\ud83c\udfb8',
'gun':'\ud83d\udd2b',
'haircut_woman':'\ud83d\udc87',
'haircut_man':'\ud83d\udc87‍\u2642\ufe0f',
'hamburger':'\ud83c\udf54',
'hammer':'\ud83d\udd28',
'hammer_and_pick':'\u2692',
'hammer_and_wrench':'\ud83d\udee0',
'hamster':'\ud83d\udc39',
'hand':'\u270b',
'handbag':'\ud83d\udc5c',
'handshake':'\ud83e\udd1d',
'hankey':'\ud83d\udca9',
'hatched_chick':'\ud83d\udc25',
'hatching_chick':'\ud83d\udc23',
'headphones':'\ud83c\udfa7',
'hear_no_evil':'\ud83d\ude49',
'heart':'\u2764\ufe0f',
'heart_decoration':'\ud83d\udc9f',
'heart_eyes':'\ud83d\ude0d',
'heart_eyes_cat':'\ud83d\ude3b',
'heartbeat':'\ud83d\udc93',
'heartpulse':'\ud83d\udc97',
'hearts':'\u2665\ufe0f',
'heavy_check_mark':'\u2714\ufe0f',
'heavy_division_sign':'\u2797',
'heavy_dollar_sign':'\ud83d\udcb2',
'heavy_heart_exclamation':'\u2763\ufe0f',
'heavy_minus_sign':'\u2796',
'heavy_multiplication_x':'\u2716\ufe0f',
'heavy_plus_sign':'\u2795',
'helicopter':'\ud83d\ude81',
'herb':'\ud83c\udf3f',
'hibiscus':'\ud83c\udf3a',
'high_brightness':'\ud83d\udd06',
'high_heel':'\ud83d\udc60',
'hocho':'\ud83d\udd2a',
'hole':'\ud83d\udd73',
'honey_pot':'\ud83c\udf6f',
'horse':'\ud83d\udc34',
'horse_racing':'\ud83c\udfc7',
'hospital':'\ud83c\udfe5',
'hot_pepper':'\ud83c\udf36',
'hotdog':'\ud83c\udf2d',
'hotel':'\ud83c\udfe8',
'hotsprings':'\u2668\ufe0f',
'hourglass':'\u231b\ufe0f',
'hourglass_flowing_sand':'\u23f3',
'house':'\ud83c\udfe0',
'house_with_garden':'\ud83c\udfe1',
'houses':'\ud83c\udfd8',
'hugs':'\ud83e\udd17',
'hushed':'\ud83d\ude2f',
'ice_cream':'\ud83c\udf68',
'ice_hockey':'\ud83c\udfd2',
'ice_skate':'\u26f8',
'icecream':'\ud83c\udf66',
'id':'\ud83c\udd94',
'ideograph_advantage':'\ud83c\ude50',
'imp':'\ud83d\udc7f',
'inbox_tray':'\ud83d\udce5',
'incoming_envelope':'\ud83d\udce8',
'tipping_hand_woman':'\ud83d\udc81',
'information_source':'\u2139\ufe0f',
'innocent':'\ud83d\ude07',
'interrobang':'\u2049\ufe0f',
'iphone':'\ud83d\udcf1',
'izakaya_lantern':'\ud83c\udfee',
'jack_o_lantern':'\ud83c\udf83',
'japan':'\ud83d\uddfe',
'japanese_castle':'\ud83c\udfef',
'japanese_goblin':'\ud83d\udc7a',
'japanese_ogre':'\ud83d\udc79',
'jeans':'\ud83d\udc56',
'joy':'\ud83d\ude02',
'joy_cat':'\ud83d\ude39',
'joystick':'\ud83d\udd79',
'kaaba':'\ud83d\udd4b',
'key':'\ud83d\udd11',
'keyboard':'\u2328\ufe0f',
'keycap_ten':'\ud83d\udd1f',
'kick_scooter':'\ud83d\udef4',
'kimono':'\ud83d\udc58',
'kiss':'\ud83d\udc8b',
'kissing':'\ud83d\ude17',
'kissing_cat':'\ud83d\ude3d',
'kissing_closed_eyes':'\ud83d\ude1a',
'kissing_heart':'\ud83d\ude18',
'kissing_smiling_eyes':'\ud83d\ude19',
'kiwi_fruit':'\ud83e\udd5d',
'koala':'\ud83d\udc28',
'koko':'\ud83c\ude01',
'label':'\ud83c\udff7',
'large_blue_circle':'\ud83d\udd35',
'large_blue_diamond':'\ud83d\udd37',
'large_orange_diamond':'\ud83d\udd36',
'last_quarter_moon':'\ud83c\udf17',
'last_quarter_moon_with_face':'\ud83c\udf1c',
'latin_cross':'\u271d\ufe0f',
'laughing':'\ud83d\ude06',
'leaves':'\ud83c\udf43',
'ledger':'\ud83d\udcd2',
'left_luggage':'\ud83d\udec5',
'left_right_arrow':'\u2194\ufe0f',
'leftwards_arrow_with_hook':'\u21a9\ufe0f',
'lemon':'\ud83c\udf4b',
'leo':'\u264c\ufe0f',
'leopard':'\ud83d\udc06',
'level_slider':'\ud83c\udf9a',
'libra':'\u264e\ufe0f',
'light_rail':'\ud83d\ude88',
'link':'\ud83d\udd17',
'lion':'\ud83e\udd81',
'lips':'\ud83d\udc44',
'lipstick':'\ud83d\udc84',
'lizard':'\ud83e\udd8e',
'lock':'\ud83d\udd12',
'lock_with_ink_pen':'\ud83d\udd0f',
'lollipop':'\ud83c\udf6d',
'loop':'\u27bf',
'loud_sound':'\ud83d\udd0a',
'loudspeaker':'\ud83d\udce2',
'love_hotel':'\ud83c\udfe9',
'love_letter':'\ud83d\udc8c',
'low_brightness':'\ud83d\udd05',
'lying_face':'\ud83e\udd25',
'm':'\u24c2\ufe0f',
'mag':'\ud83d\udd0d',
'mag_right':'\ud83d\udd0e',
'mahjong':'\ud83c\udc04\ufe0f',
'mailbox':'\ud83d\udceb',
'mailbox_closed':'\ud83d\udcea',
'mailbox_with_mail':'\ud83d\udcec',
'mailbox_with_no_mail':'\ud83d\udced',
'man':'\ud83d\udc68',
'man_artist':'\ud83d\udc68‍\ud83c\udfa8',
'man_astronaut':'\ud83d\udc68‍\ud83d\ude80',
'man_cartwheeling':'\ud83e\udd38‍\u2642\ufe0f',
'man_cook':'\ud83d\udc68‍\ud83c\udf73',
'man_dancing':'\ud83d\udd7a',
'man_facepalming':'\ud83e\udd26‍\u2642\ufe0f',
'man_factory_worker':'\ud83d\udc68‍\ud83c\udfed',
'man_farmer':'\ud83d\udc68‍\ud83c\udf3e',
'man_firefighter':'\ud83d\udc68‍\ud83d\ude92',
'man_health_worker':'\ud83d\udc68‍\u2695\ufe0f',
'man_in_tuxedo':'\ud83e\udd35',
'man_judge':'\ud83d\udc68‍\u2696\ufe0f',
'man_juggling':'\ud83e\udd39‍\u2642\ufe0f',
'man_mechanic':'\ud83d\udc68‍\ud83d\udd27',
'man_office_worker':'\ud83d\udc68‍\ud83d\udcbc',
'man_pilot':'\ud83d\udc68‍\u2708\ufe0f',
'man_playing_handball':'\ud83e\udd3e‍\u2642\ufe0f',
'man_playing_water_polo':'\ud83e\udd3d‍\u2642\ufe0f',
'man_scientist':'\ud83d\udc68‍\ud83d\udd2c',
'man_shrugging':'\ud83e\udd37‍\u2642\ufe0f',
'man_singer':'\ud83d\udc68‍\ud83c\udfa4',
'man_student':'\ud83d\udc68‍\ud83c\udf93',
'man_teacher':'\ud83d\udc68‍\ud83c\udfeb',
'man_technologist':'\ud83d\udc68‍\ud83d\udcbb',
'man_with_gua_pi_mao':'\ud83d\udc72',
'man_with_turban':'\ud83d\udc73',
'tangerine':'\ud83c\udf4a',
'mans_shoe':'\ud83d\udc5e',
'mantelpiece_clock':'\ud83d\udd70',
'maple_leaf':'\ud83c\udf41',
'martial_arts_uniform':'\ud83e\udd4b',
'mask':'\ud83d\ude37',
'massage_woman':'\ud83d\udc86',
'massage_man':'\ud83d\udc86‍\u2642\ufe0f',
'meat_on_bone':'\ud83c\udf56',
'medal_military':'\ud83c\udf96',
'medal_sports':'\ud83c\udfc5',
'mega':'\ud83d\udce3',
'melon':'\ud83c\udf48',
'memo':'\ud83d\udcdd',
'men_wrestling':'\ud83e\udd3c‍\u2642\ufe0f',
'menorah':'\ud83d\udd4e',
'mens':'\ud83d\udeb9',
'metal':'\ud83e\udd18',
'metro':'\ud83d\ude87',
'microphone':'\ud83c\udfa4',
'microscope':'\ud83d\udd2c',
'milk_glass':'\ud83e\udd5b',
'milky_way':'\ud83c\udf0c',
'minibus':'\ud83d\ude90',
'minidisc':'\ud83d\udcbd',
'mobile_phone_off':'\ud83d\udcf4',
'money_mouth_face':'\ud83e\udd11',
'money_with_wings':'\ud83d\udcb8',
'moneybag':'\ud83d\udcb0',
'monkey':'\ud83d\udc12',
'monkey_face':'\ud83d\udc35',
'monorail':'\ud83d\ude9d',
'moon':'\ud83c\udf14',
'mortar_board':'\ud83c\udf93',
'mosque':'\ud83d\udd4c',
'motor_boat':'\ud83d\udee5',
'motor_scooter':'\ud83d\udef5',
'motorcycle':'\ud83c\udfcd',
'motorway':'\ud83d\udee3',
'mount_fuji':'\ud83d\uddfb',
'mountain':'\u26f0',
'mountain_biking_man':'\ud83d\udeb5',
'mountain_biking_woman':'\ud83d\udeb5‍\u2640\ufe0f',
'mountain_cableway':'\ud83d\udea0',
'mountain_railway':'\ud83d\ude9e',
'mountain_snow':'\ud83c\udfd4',
'mouse':'\ud83d\udc2d',
'mouse2':'\ud83d\udc01',
'movie_camera':'\ud83c\udfa5',
'moyai':'\ud83d\uddff',
'mrs_claus':'\ud83e\udd36',
'muscle':'\ud83d\udcaa',
'mushroom':'\ud83c\udf44',
'musical_keyboard':'\ud83c\udfb9',
'musical_note':'\ud83c\udfb5',
'musical_score':'\ud83c\udfbc',
'mute':'\ud83d\udd07',
'nail_care':'\ud83d\udc85',
'name_badge':'\ud83d\udcdb',
'national_park':'\ud83c\udfde',
'nauseated_face':'\ud83e\udd22',
'necktie':'\ud83d\udc54',
'negative_squared_cross_mark':'\u274e',
'nerd_face':'\ud83e\udd13',
'neutral_face':'\ud83d\ude10',
'new':'\ud83c\udd95',
'new_moon':'\ud83c\udf11',
'new_moon_with_face':'\ud83c\udf1a',
'newspaper':'\ud83d\udcf0',
'newspaper_roll':'\ud83d\uddde',
'next_track_button':'\u23ed',
'ng':'\ud83c\udd96',
'no_good_man':'\ud83d\ude45‍\u2642\ufe0f',
'no_good_woman':'\ud83d\ude45',
'night_with_stars':'\ud83c\udf03',
'no_bell':'\ud83d\udd15',
'no_bicycles':'\ud83d\udeb3',
'no_entry':'\u26d4\ufe0f',
'no_entry_sign':'\ud83d\udeab',
'no_mobile_phones':'\ud83d\udcf5',
'no_mouth':'\ud83d\ude36',
'no_pedestrians':'\ud83d\udeb7',
'no_smoking':'\ud83d\udead',
'non-potable_water':'\ud83d\udeb1',
'nose':'\ud83d\udc43',
'notebook':'\ud83d\udcd3',
'notebook_with_decorative_cover':'\ud83d\udcd4',
'notes':'\ud83c\udfb6',
'nut_and_bolt':'\ud83d\udd29',
'o':'\u2b55\ufe0f',
'o2':'\ud83c\udd7e\ufe0f',
'ocean':'\ud83c\udf0a',
'octopus':'\ud83d\udc19',
'oden':'\ud83c\udf62',
'office':'\ud83c\udfe2',
'oil_drum':'\ud83d\udee2',
'ok':'\ud83c\udd97',
'ok_hand':'\ud83d\udc4c',
'ok_man':'\ud83d\ude46‍\u2642\ufe0f',
'ok_woman':'\ud83d\ude46',
'old_key':'\ud83d\udddd',
'older_man':'\ud83d\udc74',
'older_woman':'\ud83d\udc75',
'om':'\ud83d\udd49',
'on':'\ud83d\udd1b',
'oncoming_automobile':'\ud83d\ude98',
'oncoming_bus':'\ud83d\ude8d',
'oncoming_police_car':'\ud83d\ude94',
'oncoming_taxi':'\ud83d\ude96',
'open_file_folder':'\ud83d\udcc2',
'open_hands':'\ud83d\udc50',
'open_mouth':'\ud83d\ude2e',
'open_umbrella':'\u2602\ufe0f',
'ophiuchus':'\u26ce',
'orange_book':'\ud83d\udcd9',
'orthodox_cross':'\u2626\ufe0f',
'outbox_tray':'\ud83d\udce4',
'owl':'\ud83e\udd89',
'ox':'\ud83d\udc02',
'package':'\ud83d\udce6',
'page_facing_up':'\ud83d\udcc4',
'page_with_curl':'\ud83d\udcc3',
'pager':'\ud83d\udcdf',
'paintbrush':'\ud83d\udd8c',
'palm_tree':'\ud83c\udf34',
'pancakes':'\ud83e\udd5e',
'panda_face':'\ud83d\udc3c',
'paperclip':'\ud83d\udcce',
'paperclips':'\ud83d\udd87',
'parasol_on_ground':'\u26f1',
'parking':'\ud83c\udd7f\ufe0f',
'part_alternation_mark':'\u303d\ufe0f',
'partly_sunny':'\u26c5\ufe0f',
'passenger_ship':'\ud83d\udef3',
'passport_control':'\ud83d\udec2',
'pause_button':'\u23f8',
'peace_symbol':'\u262e\ufe0f',
'peach':'\ud83c\udf51',
'peanuts':'\ud83e\udd5c',
'pear':'\ud83c\udf50',
'pen':'\ud83d\udd8a',
'pencil2':'\u270f\ufe0f',
'penguin':'\ud83d\udc27',
'pensive':'\ud83d\ude14',
'performing_arts':'\ud83c\udfad',
'persevere':'\ud83d\ude23',
'person_fencing':'\ud83e\udd3a',
'pouting_woman':'\ud83d\ude4e',
'phone':'\u260e\ufe0f',
'pick':'\u26cf',
'pig':'\ud83d\udc37',
'pig2':'\ud83d\udc16',
'pig_nose':'\ud83d\udc3d',
'pill':'\ud83d\udc8a',
'pineapple':'\ud83c\udf4d',
'ping_pong':'\ud83c\udfd3',
'pisces':'\u2653\ufe0f',
'pizza':'\ud83c\udf55',
'place_of_worship':'\ud83d\uded0',
'plate_with_cutlery':'\ud83c\udf7d',
'play_or_pause_button':'\u23ef',
'point_down':'\ud83d\udc47',
'point_left':'\ud83d\udc48',
'point_right':'\ud83d\udc49',
'point_up':'\u261d\ufe0f',
'point_up_2':'\ud83d\udc46',
'police_car':'\ud83d\ude93',
'policewoman':'\ud83d\udc6e‍\u2640\ufe0f',
'poodle':'\ud83d\udc29',
'popcorn':'\ud83c\udf7f',
'post_office':'\ud83c\udfe3',
'postal_horn':'\ud83d\udcef',
'postbox':'\ud83d\udcee',
'potable_water':'\ud83d\udeb0',
'potato':'\ud83e\udd54',
'pouch':'\ud83d\udc5d',
'poultry_leg':'\ud83c\udf57',
'pound':'\ud83d\udcb7',
'rage':'\ud83d\ude21',
'pouting_cat':'\ud83d\ude3e',
'pouting_man':'\ud83d\ude4e‍\u2642\ufe0f',
'pray':'\ud83d\ude4f',
'prayer_beads':'\ud83d\udcff',
'pregnant_woman':'\ud83e\udd30',
'previous_track_button':'\u23ee',
'prince':'\ud83e\udd34',
'princess':'\ud83d\udc78',
'printer':'\ud83d\udda8',
'purple_heart':'\ud83d\udc9c',
'purse':'\ud83d\udc5b',
'pushpin':'\ud83d\udccc',
'put_litter_in_its_place':'\ud83d\udeae',
'question':'\u2753',
'rabbit':'\ud83d\udc30',
'rabbit2':'\ud83d\udc07',
'racehorse':'\ud83d\udc0e',
'racing_car':'\ud83c\udfce',
'radio':'\ud83d\udcfb',
'radio_button':'\ud83d\udd18',
'radioactive':'\u2622\ufe0f',
'railway_car':'\ud83d\ude83',
'railway_track':'\ud83d\udee4',
'rainbow':'\ud83c\udf08',
'rainbow_flag':'\ud83c\udff3\ufe0f‍\ud83c\udf08',
'raised_back_of_hand':'\ud83e\udd1a',
'raised_hand_with_fingers_splayed':'\ud83d\udd90',
'raised_hands':'\ud83d\ude4c',
'raising_hand_woman':'\ud83d\ude4b',
'raising_hand_man':'\ud83d\ude4b‍\u2642\ufe0f',
'ram':'\ud83d\udc0f',
'ramen':'\ud83c\udf5c',
'rat':'\ud83d\udc00',
'record_button':'\u23fa',
'recycle':'\u267b\ufe0f',
'red_circle':'\ud83d\udd34',
'registered':'\u00ae\ufe0f',
'relaxed':'\u263a\ufe0f',
'relieved':'\ud83d\ude0c',
'reminder_ribbon':'\ud83c\udf97',
'repeat':'\ud83d\udd01',
'repeat_one':'\ud83d\udd02',
'rescue_worker_helmet':'\u26d1',
'restroom':'\ud83d\udebb',
'revolving_hearts':'\ud83d\udc9e',
'rewind':'\u23ea',
'rhinoceros':'\ud83e\udd8f',
'ribbon':'\ud83c\udf80',
'rice':'\ud83c\udf5a',
'rice_ball':'\ud83c\udf59',
'rice_cracker':'\ud83c\udf58',
'rice_scene':'\ud83c\udf91',
'right_anger_bubble':'\ud83d\uddef',
'ring':'\ud83d\udc8d',
'robot':'\ud83e\udd16',
'rocket':'\ud83d\ude80',
'rofl':'\ud83e\udd23',
'roll_eyes':'\ud83d\ude44',
'roller_coaster':'\ud83c\udfa2',
'rooster':'\ud83d\udc13',
'rose':'\ud83c\udf39',
'rosette':'\ud83c\udff5',
'rotating_light':'\ud83d\udea8',
'round_pushpin':'\ud83d\udccd',
'rowing_man':'\ud83d\udea3',
'rowing_woman':'\ud83d\udea3‍\u2640\ufe0f',
'rugby_football':'\ud83c\udfc9',
'running_man':'\ud83c\udfc3',
'running_shirt_with_sash':'\ud83c\udfbd',
'running_woman':'\ud83c\udfc3‍\u2640\ufe0f',
'sa':'\ud83c\ude02\ufe0f',
'sagittarius':'\u2650\ufe0f',
'sake':'\ud83c\udf76',
'sandal':'\ud83d\udc61',
'santa':'\ud83c\udf85',
'satellite':'\ud83d\udce1',
'saxophone':'\ud83c\udfb7',
'school':'\ud83c\udfeb',
'school_satchel':'\ud83c\udf92',
'scissors':'\u2702\ufe0f',
'scorpion':'\ud83e\udd82',
'scorpius':'\u264f\ufe0f',
'scream':'\ud83d\ude31',
'scream_cat':'\ud83d\ude40',
'scroll':'\ud83d\udcdc',
'seat':'\ud83d\udcba',
'secret':'\u3299\ufe0f',
'see_no_evil':'\ud83d\ude48',
'seedling':'\ud83c\udf31',
'selfie':'\ud83e\udd33',
'shallow_pan_of_food':'\ud83e\udd58',
'shamrock':'\u2618\ufe0f',
'shark':'\ud83e\udd88',
'shaved_ice':'\ud83c\udf67',
'sheep':'\ud83d\udc11',
'shell':'\ud83d\udc1a',
'shield':'\ud83d\udee1',
'shinto_shrine':'\u26e9',
'ship':'\ud83d\udea2',
'shirt':'\ud83d\udc55',
'shopping':'\ud83d\udecd',
'shopping_cart':'\ud83d\uded2',
'shower':'\ud83d\udebf',
'shrimp':'\ud83e\udd90',
'signal_strength':'\ud83d\udcf6',
'six_pointed_star':'\ud83d\udd2f',
'ski':'\ud83c\udfbf',
'skier':'\u26f7',
'skull':'\ud83d\udc80',
'skull_and_crossbones':'\u2620\ufe0f',
'sleeping':'\ud83d\ude34',
'sleeping_bed':'\ud83d\udecc',
'sleepy':'\ud83d\ude2a',
'slightly_frowning_face':'\ud83d\ude41',
'slightly_smiling_face':'\ud83d\ude42',
'slot_machine':'\ud83c\udfb0',
'small_airplane':'\ud83d\udee9',
'small_blue_diamond':'\ud83d\udd39',
'small_orange_diamond':'\ud83d\udd38',
'small_red_triangle':'\ud83d\udd3a',
'small_red_triangle_down':'\ud83d\udd3b',
'smile':'\ud83d\ude04',
'smile_cat':'\ud83d\ude38',
'smiley':'\ud83d\ude03',
'smiley_cat':'\ud83d\ude3a',
'smiling_imp':'\ud83d\ude08',
'smirk':'\ud83d\ude0f',
'smirk_cat':'\ud83d\ude3c',
'smoking':'\ud83d\udeac',
'snail':'\ud83d\udc0c',
'snake':'\ud83d\udc0d',
'sneezing_face':'\ud83e\udd27',
'snowboarder':'\ud83c\udfc2',
'snowflake':'\u2744\ufe0f',
'snowman':'\u26c4\ufe0f',
'snowman_with_snow':'\u2603\ufe0f',
'sob':'\ud83d\ude2d',
'soccer':'\u26bd\ufe0f',
'soon':'\ud83d\udd1c',
'sos':'\ud83c\udd98',
'sound':'\ud83d\udd09',
'space_invader':'\ud83d\udc7e',
'spades':'\u2660\ufe0f',
'spaghetti':'\ud83c\udf5d',
'sparkle':'\u2747\ufe0f',
'sparkler':'\ud83c\udf87',
'sparkles':'\u2728',
'sparkling_heart':'\ud83d\udc96',
'speak_no_evil':'\ud83d\ude4a',
'speaker':'\ud83d\udd08',
'speaking_head':'\ud83d\udde3',
'speech_balloon':'\ud83d\udcac',
'speedboat':'\ud83d\udea4',
'spider':'\ud83d\udd77',
'spider_web':'\ud83d\udd78',
'spiral_calendar':'\ud83d\uddd3',
'spiral_notepad':'\ud83d\uddd2',
'spoon':'\ud83e\udd44',
'squid':'\ud83e\udd91',
'stadium':'\ud83c\udfdf',
'star':'\u2b50\ufe0f',
'star2':'\ud83c\udf1f',
'star_and_crescent':'\u262a\ufe0f',
'star_of_david':'\u2721\ufe0f',
'stars':'\ud83c\udf20',
'station':'\ud83d\ude89',
'statue_of_liberty':'\ud83d\uddfd',
'steam_locomotive':'\ud83d\ude82',
'stew':'\ud83c\udf72',
'stop_button':'\u23f9',
'stop_sign':'\ud83d\uded1',
'stopwatch':'\u23f1',
'straight_ruler':'\ud83d\udccf',
'strawberry':'\ud83c\udf53',
'stuck_out_tongue':'\ud83d\ude1b',
'stuck_out_tongue_closed_eyes':'\ud83d\ude1d',
'stuck_out_tongue_winking_eye':'\ud83d\ude1c',
'studio_microphone':'\ud83c\udf99',
'stuffed_flatbread':'\ud83e\udd59',
'sun_behind_large_cloud':'\ud83c\udf25',
'sun_behind_rain_cloud':'\ud83c\udf26',
'sun_behind_small_cloud':'\ud83c\udf24',
'sun_with_face':'\ud83c\udf1e',
'sunflower':'\ud83c\udf3b',
'sunglasses':'\ud83d\ude0e',
'sunny':'\u2600\ufe0f',
'sunrise':'\ud83c\udf05',
'sunrise_over_mountains':'\ud83c\udf04',
'surfing_man':'\ud83c\udfc4',
'surfing_woman':'\ud83c\udfc4‍\u2640\ufe0f',
'sushi':'\ud83c\udf63',
'suspension_railway':'\ud83d\ude9f',
'sweat':'\ud83d\ude13',
'sweat_drops':'\ud83d\udca6',
'sweat_smile':'\ud83d\ude05',
'sweet_potato':'\ud83c\udf60',
'swimming_man':'\ud83c\udfca',
'swimming_woman':'\ud83c\udfca‍\u2640\ufe0f',
'symbols':'\ud83d\udd23',
'synagogue':'\ud83d\udd4d',
'syringe':'\ud83d\udc89',
'taco':'\ud83c\udf2e',
'tada':'\ud83c\udf89',
'tanabata_tree':'\ud83c\udf8b',
'taurus':'\u2649\ufe0f',
'taxi':'\ud83d\ude95',
'tea':'\ud83c\udf75',
'telephone_receiver':'\ud83d\udcde',
'telescope':'\ud83d\udd2d',
'tennis':'\ud83c\udfbe',
'tent':'\u26fa\ufe0f',
'thermometer':'\ud83c\udf21',
'thinking':'\ud83e\udd14',
'thought_balloon':'\ud83d\udcad',
'ticket':'\ud83c\udfab',
'tickets':'\ud83c\udf9f',
'tiger':'\ud83d\udc2f',
'tiger2':'\ud83d\udc05',
'timer_clock':'\u23f2',
'tipping_hand_man':'\ud83d\udc81‍\u2642\ufe0f',
'tired_face':'\ud83d\ude2b',
'tm':'\u2122\ufe0f',
'toilet':'\ud83d\udebd',
'tokyo_tower':'\ud83d\uddfc',
'tomato':'\ud83c\udf45',
'tongue':'\ud83d\udc45',
'top':'\ud83d\udd1d',
'tophat':'\ud83c\udfa9',
'tornado':'\ud83c\udf2a',
'trackball':'\ud83d\uddb2',
'tractor':'\ud83d\ude9c',
'traffic_light':'\ud83d\udea5',
'train':'\ud83d\ude8b',
'train2':'\ud83d\ude86',
'tram':'\ud83d\ude8a',
'triangular_flag_on_post':'\ud83d\udea9',
'triangular_ruler':'\ud83d\udcd0',
'trident':'\ud83d\udd31',
'triumph':'\ud83d\ude24',
'trolleybus':'\ud83d\ude8e',
'trophy':'\ud83c\udfc6',
'tropical_drink':'\ud83c\udf79',
'tropical_fish':'\ud83d\udc20',
'truck':'\ud83d\ude9a',
'trumpet':'\ud83c\udfba',
'tulip':'\ud83c\udf37',
'tumbler_glass':'\ud83e\udd43',
'turkey':'\ud83e\udd83',
'turtle':'\ud83d\udc22',
'tv':'\ud83d\udcfa',
'twisted_rightwards_arrows':'\ud83d\udd00',
'two_hearts':'\ud83d\udc95',
'two_men_holding_hands':'\ud83d\udc6c',
'two_women_holding_hands':'\ud83d\udc6d',
'u5272':'\ud83c\ude39',
'u5408':'\ud83c\ude34',
'u55b6':'\ud83c\ude3a',
'u6307':'\ud83c\ude2f\ufe0f',
'u6708':'\ud83c\ude37\ufe0f',
'u6709':'\ud83c\ude36',
'u6e80':'\ud83c\ude35',
'u7121':'\ud83c\ude1a\ufe0f',
'u7533':'\ud83c\ude38',
'u7981':'\ud83c\ude32',
'u7a7a':'\ud83c\ude33',
'umbrella':'\u2614\ufe0f',
'unamused':'\ud83d\ude12',
'underage':'\ud83d\udd1e',
'unicorn':'\ud83e\udd84',
'unlock':'\ud83d\udd13',
'up':'\ud83c\udd99',
'upside_down_face':'\ud83d\ude43',
'v':'\u270c\ufe0f',
'vertical_traffic_light':'\ud83d\udea6',
'vhs':'\ud83d\udcfc',
'vibration_mode':'\ud83d\udcf3',
'video_camera':'\ud83d\udcf9',
'video_game':'\ud83c\udfae',
'violin':'\ud83c\udfbb',
'virgo':'\u264d\ufe0f',
'volcano':'\ud83c\udf0b',
'volleyball':'\ud83c\udfd0',
'vs':'\ud83c\udd9a',
'vulcan_salute':'\ud83d\udd96',
'walking_man':'\ud83d\udeb6',
'walking_woman':'\ud83d\udeb6‍\u2640\ufe0f',
'waning_crescent_moon':'\ud83c\udf18',
'waning_gibbous_moon':'\ud83c\udf16',
'warning':'\u26a0\ufe0f',
'wastebasket':'\ud83d\uddd1',
'watch':'\u231a\ufe0f',
'water_buffalo':'\ud83d\udc03',
'watermelon':'\ud83c\udf49',
'wave':'\ud83d\udc4b',
'wavy_dash':'\u3030\ufe0f',
'waxing_crescent_moon':'\ud83c\udf12',
'wc':'\ud83d\udebe',
'weary':'\ud83d\ude29',
'wedding':'\ud83d\udc92',
'weight_lifting_man':'\ud83c\udfcb\ufe0f',
'weight_lifting_woman':'\ud83c\udfcb\ufe0f‍\u2640\ufe0f',
'whale':'\ud83d\udc33',
'whale2':'\ud83d\udc0b',
'wheel_of_dharma':'\u2638\ufe0f',
'wheelchair':'\u267f\ufe0f',
'white_check_mark':'\u2705',
'white_circle':'\u26aa\ufe0f',
'white_flag':'\ud83c\udff3\ufe0f',
'white_flower':'\ud83d\udcae',
'white_large_square':'\u2b1c\ufe0f',
'white_medium_small_square':'\u25fd\ufe0f',
'white_medium_square':'\u25fb\ufe0f',
'white_small_square':'\u25ab\ufe0f',
'white_square_button':'\ud83d\udd33',
'wilted_flower':'\ud83e\udd40',
'wind_chime':'\ud83c\udf90',
'wind_face':'\ud83c\udf2c',
'wine_glass':'\ud83c\udf77',
'wink':'\ud83d\ude09',
'wolf':'\ud83d\udc3a',
'woman':'\ud83d\udc69',
'woman_artist':'\ud83d\udc69‍\ud83c\udfa8',
'woman_astronaut':'\ud83d\udc69‍\ud83d\ude80',
'woman_cartwheeling':'\ud83e\udd38‍\u2640\ufe0f',
'woman_cook':'\ud83d\udc69‍\ud83c\udf73',
'woman_facepalming':'\ud83e\udd26‍\u2640\ufe0f',
'woman_factory_worker':'\ud83d\udc69‍\ud83c\udfed',
'woman_farmer':'\ud83d\udc69‍\ud83c\udf3e',
'woman_firefighter':'\ud83d\udc69‍\ud83d\ude92',
'woman_health_worker':'\ud83d\udc69‍\u2695\ufe0f',
'woman_judge':'\ud83d\udc69‍\u2696\ufe0f',
'woman_juggling':'\ud83e\udd39‍\u2640\ufe0f',
'woman_mechanic':'\ud83d\udc69‍\ud83d\udd27',
'woman_office_worker':'\ud83d\udc69‍\ud83d\udcbc',
'woman_pilot':'\ud83d\udc69‍\u2708\ufe0f',
'woman_playing_handball':'\ud83e\udd3e‍\u2640\ufe0f',
'woman_playing_water_polo':'\ud83e\udd3d‍\u2640\ufe0f',
'woman_scientist':'\ud83d\udc69‍\ud83d\udd2c',
'woman_shrugging':'\ud83e\udd37‍\u2640\ufe0f',
'woman_singer':'\ud83d\udc69‍\ud83c\udfa4',
'woman_student':'\ud83d\udc69‍\ud83c\udf93',
'woman_teacher':'\ud83d\udc69‍\ud83c\udfeb',
'woman_technologist':'\ud83d\udc69‍\ud83d\udcbb',
'woman_with_turban':'\ud83d\udc73‍\u2640\ufe0f',
'womans_clothes':'\ud83d\udc5a',
'womans_hat':'\ud83d\udc52',
'women_wrestling':'\ud83e\udd3c‍\u2640\ufe0f',
'womens':'\ud83d\udeba',
'world_map':'\ud83d\uddfa',
'worried':'\ud83d\ude1f',
'wrench':'\ud83d\udd27',
'writing_hand':'\u270d\ufe0f',
'x':'\u274c',
'yellow_heart':'\ud83d\udc9b',
'yen':'\ud83d\udcb4',
'yin_yang':'\u262f\ufe0f',
'yum':'\ud83d\ude0b',
'zap':'\u26a1\ufe0f',
'zipper_mouth_face':'\ud83e\udd10',
'zzz':'\ud83d\udca4',
/* special emojis :P */
'octocat': '<img alt=":octocat:" height="20" width="20" align="absmiddle" src="https://assets-cdn.github.com/images/icons/emoji/octocat.png">',
'showdown': '<span style="font-family: \'Anonymous Pro\', monospace; text-decoration: underline; text-decoration-style: dashed; text-decoration-color: #3e8b8a;text-underline-position: under;">S</span>'
};
/**
* Created by Estevao on 31-05-2015.
*/
/**
* Showdown Converter class
* @class
* @param {object} [converterOptions]
* @returns {Converter}
*/
showdown.Converter = function (converterOptions) {
'use strict';
var
/**
* Options used by this converter
* @private
* @type {{}}
*/
options = {},
/**
* Language extensions used by this converter
* @private
* @type {Array}
*/
langExtensions = [],
/**
* Output modifiers extensions used by this converter
* @private
* @type {Array}
*/
outputModifiers = [],
/**
* Event listeners
* @private
* @type {{}}
*/
listeners = {},
/**
* The flavor set in this converter
*/
setConvFlavor = setFlavor,
/**
* Metadata of the document
* @type {{parsed: {}, raw: string, format: string}}
*/
metadata = {
parsed: {},
raw: '',
format: ''
};
_constructor();
/**
* Converter constructor
* @private
*/
function _constructor () {
converterOptions = converterOptions || {};
for (var gOpt in globalOptions) {
if (globalOptions.hasOwnProperty(gOpt)) {
options[gOpt] = globalOptions[gOpt];
}
}
// Merge options
if (typeof converterOptions === 'object') {
for (var opt in converterOptions) {
if (converterOptions.hasOwnProperty(opt)) {
options[opt] = converterOptions[opt];
}
}
} else {
throw Error('Converter expects the passed parameter to be an object, but ' + typeof converterOptions +
' was passed instead.');
}
if (options.extensions) {
showdown.helper.forEach(options.extensions, _parseExtension);
}
}
/**
* Parse extension
* @param {*} ext
* @param {string} [name='']
* @private
*/
function _parseExtension (ext, name) {
name = name || null;
// If it's a string, the extension was previously loaded
if (showdown.helper.isString(ext)) {
ext = showdown.helper.stdExtName(ext);
name = ext;
// LEGACY_SUPPORT CODE
if (showdown.extensions[ext]) {
console.warn('DEPRECATION WARNING: ' + ext + ' is an old extension that uses a deprecated loading method.' +
'Please inform the developer that the extension should be updated!');
legacyExtensionLoading(showdown.extensions[ext], ext);
return;
// END LEGACY SUPPORT CODE
} else if (!showdown.helper.isUndefined(extensions[ext])) {
ext = extensions[ext];
} else {
throw Error('Extension "' + ext + '" could not be loaded. It was either not found or is not a valid extension.');
}
}
if (typeof ext === 'function') {
ext = ext();
}
if (!showdown.helper.isArray(ext)) {
ext = [ext];
}
var validExt = validate(ext, name);
if (!validExt.valid) {
throw Error(validExt.error);
}
for (var i = 0; i < ext.length; ++i) {
switch (ext[i].type) {
case 'lang':
langExtensions.push(ext[i]);
break;
case 'output':
outputModifiers.push(ext[i]);
break;
}
if (ext[i].hasOwnProperty('listeners')) {
for (var ln in ext[i].listeners) {
if (ext[i].listeners.hasOwnProperty(ln)) {
listen(ln, ext[i].listeners[ln]);
}
}
}
}
}
/**
* LEGACY_SUPPORT
* @param {*} ext
* @param {string} name
*/
function legacyExtensionLoading (ext, name) {
if (typeof ext === 'function') {
ext = ext(new showdown.Converter());
}
if (!showdown.helper.isArray(ext)) {
ext = [ext];
}
var valid = validate(ext, name);
if (!valid.valid) {
throw Error(valid.error);
}
for (var i = 0; i < ext.length; ++i) {
switch (ext[i].type) {
case 'lang':
langExtensions.push(ext[i]);
break;
case 'output':
outputModifiers.push(ext[i]);
break;
default:// should never reach here
throw Error('Extension loader error: Type unrecognized!!!');
}
}
}
/**
* Listen to an event
* @param {string} name
* @param {function} callback
*/
function listen (name, callback) {
if (!showdown.helper.isString(name)) {
throw Error('Invalid argument in converter.listen() method: name must be a string, but ' + typeof name + ' given');
}
if (typeof callback !== 'function') {
throw Error('Invalid argument in converter.listen() method: callback must be a function, but ' + typeof callback + ' given');
}
if (!listeners.hasOwnProperty(name)) {
listeners[name] = [];
}
listeners[name].push(callback);
}
function rTrimInputText (text) {
var rsp = text.match(/^\s*/)[0].length,
rgx = new RegExp('^\\s{0,' + rsp + '}', 'gm');
return text.replace(rgx, '');
}
/**
* Dispatch an event
* @private
* @param {string} evtName Event name
* @param {string} text Text
* @param {{}} options Converter Options
* @param {{}} globals
* @returns {string}
*/
this._dispatch = function dispatch (evtName, text, options, globals) {
if (listeners.hasOwnProperty(evtName)) {
for (var ei = 0; ei < listeners[evtName].length; ++ei) {
var nText = listeners[evtName][ei](evtName, text, this, options, globals);
if (nText && typeof nText !== 'undefined') {
text = nText;
}
}
}
return text;
};
/**
* Listen to an event
* @param {string} name
* @param {function} callback
* @returns {showdown.Converter}
*/
this.listen = function (name, callback) {
listen(name, callback);
return this;
};
/**
* Converts a markdown string into HTML
* @param {string} text
* @returns {*}
*/
this.makeHtml = function (text) {
//check if text is not falsy
if (!text) {
return text;
}
var globals = {
gHtmlBlocks: [],
gHtmlMdBlocks: [],
gHtmlSpans: [],
gUrls: {},
gTitles: {},
gDimensions: {},
gListLevel: 0,
hashLinkCounts: {},
langExtensions: langExtensions,
outputModifiers: outputModifiers,
converter: this,
ghCodeBlocks: [],
metadata: {
parsed: {},
raw: '',
format: ''
}
};
// This lets us use ¨ trema as an escape char to avoid md5 hashes
// The choice of character is arbitrary; anything that isn't
// magic in Markdown will work.
text = text.replace(/¨/g, '¨T');
// Replace $ with ¨D
// RegExp interprets $ as a special character
// when it's in a replacement string
text = text.replace(/\$/g, '¨D');
// Standardize line endings
text = text.replace(/\r\n/g, '\n'); // DOS to Unix
text = text.replace(/\r/g, '\n'); // Mac to Unix
// Stardardize line spaces
text = text.replace(/\u00A0/g, ' ');
if (options.smartIndentationFix) {
text = rTrimInputText(text);
}
// Make sure text begins and ends with a couple of newlines:
text = '\n\n' + text + '\n\n';
// detab
text = showdown.subParser('detab')(text, options, globals);
/**
* Strip any lines consisting only of spaces and tabs.
* This makes subsequent regexs easier to write, because we can
* match consecutive blank lines with /\n+/ instead of something
* contorted like /[ \t]*\n+/
*/
text = text.replace(/^[ \t]+$/mg, '');
//run languageExtensions
showdown.helper.forEach(langExtensions, function (ext) {
text = showdown.subParser('runExtension')(ext, text, options, globals);
});
// run the sub parsers
text = showdown.subParser('metadata')(text, options, globals);
text = showdown.subParser('hashPreCodeTags')(text, options, globals);
text = showdown.subParser('githubCodeBlocks')(text, options, globals);
text = showdown.subParser('hashHTMLBlocks')(text, options, globals);
text = showdown.subParser('hashCodeTags')(text, options, globals);
text = showdown.subParser('stripLinkDefinitions')(text, options, globals);
text = showdown.subParser('blockGamut')(text, options, globals);
text = showdown.subParser('unhashHTMLSpans')(text, options, globals);
text = showdown.subParser('unescapeSpecialChars')(text, options, globals);
// attacklab: Restore dollar signs
text = text.replace(/¨D/g, '$$');
// attacklab: Restore tremas
text = text.replace(/¨T/g, '¨');
// render a complete html document instead of a partial if the option is enabled
text = showdown.subParser('completeHTMLDocument')(text, options, globals);
// Run output modifiers
showdown.helper.forEach(outputModifiers, function (ext) {
text = showdown.subParser('runExtension')(ext, text, options, globals);
});
// update metadata
metadata = globals.metadata;
return text;
};
/**
* Converts an HTML string into a markdown string
* @param src
* @param [HTMLParser] A WHATWG DOM and HTML parser, such as JSDOM. If none is supplied, window.document will be used.
* @returns {string}
*/
this.makeMarkdown = this.makeMd = function (src, HTMLParser) {
// replace \r\n with \n
src = src.replace(/\r\n/g, '\n');
src = src.replace(/\r/g, '\n'); // old macs
// due to an edge case, we need to find this: > <
// to prevent removing of non silent white spaces
// ex: <em>this is</em> <strong>sparta</strong>
src = src.replace(/>[ \t]+</, '>¨NBSP;<');
if (!HTMLParser) {
if (window && window.document) {
HTMLParser = window.document;
} else {
throw new Error('HTMLParser is undefined. If in a webworker or nodejs environment, you need to provide a WHATWG DOM and HTML such as JSDOM');
}
}
var doc = HTMLParser.createElement('div');
doc.innerHTML = src;
var globals = {
preList: substitutePreCodeTags(doc)
};
// remove all newlines and collapse spaces
clean(doc);
// some stuff, like accidental reference links must now be escaped
// TODO
// doc.innerHTML = doc.innerHTML.replace(/\[[\S\t ]]/);
var nodes = doc.childNodes,
mdDoc = '';
for (var i = 0; i < nodes.length; i++) {
mdDoc += showdown.subParser('makeMarkdown.node')(nodes[i], globals);
}
function clean (node) {
for (var n = 0; n < node.childNodes.length; ++n) {
var child = node.childNodes[n];
if (child.nodeType === 3) {
if (!/\S/.test(child.nodeValue)) {
node.removeChild(child);
--n;
} else {
child.nodeValue = child.nodeValue.split('\n').join(' ');
child.nodeValue = child.nodeValue.replace(/(\s)+/g, '$1');
}
} else if (child.nodeType === 1) {
clean(child);
}
}
}
// find all pre tags and replace contents with placeholder
// we need this so that we can remove all indentation from html
// to ease up parsing
function substitutePreCodeTags (doc) {
var pres = doc.querySelectorAll('pre'),
presPH = [];
for (var i = 0; i < pres.length; ++i) {
if (pres[i].childElementCount === 1 && pres[i].firstChild.tagName.toLowerCase() === 'code') {
var content = pres[i].firstChild.innerHTML.trim(),
language = pres[i].firstChild.getAttribute('data-language') || '';
// if data-language attribute is not defined, then we look for class language-*
if (language === '') {
var classes = pres[i].firstChild.className.split(' ');
for (var c = 0; c < classes.length; ++c) {
var matches = classes[c].match(/^language-(.+)$/);
if (matches !== null) {
language = matches[1];
break;
}
}
}
// unescape html entities in content
content = showdown.helper.unescapeHTMLEntities(content);
presPH.push(content);
pres[i].outerHTML = '<precode language="' + language + '" precodenum="' + i.toString() + '"></precode>';
} else {
presPH.push(pres[i].innerHTML);
pres[i].innerHTML = '';
pres[i].setAttribute('prenum', i.toString());
}
}
return presPH;
}
return mdDoc;
};
/**
* Set an option of this Converter instance
* @param {string} key
* @param {*} value
*/
this.setOption = function (key, value) {
options[key] = value;
};
/**
* Get the option of this Converter instance
* @param {string} key
* @returns {*}
*/
this.getOption = function (key) {
return options[key];
};
/**
* Get the options of this Converter instance
* @returns {{}}
*/
this.getOptions = function () {
return options;
};
/**
* Add extension to THIS converter
* @param {{}} extension
* @param {string} [name=null]
*/
this.addExtension = function (extension, name) {
name = name || null;
_parseExtension(extension, name);
};
/**
* Use a global registered extension with THIS converter
* @param {string} extensionName Name of the previously registered extension
*/
this.useExtension = function (extensionName) {
_parseExtension(extensionName);
};
/**
* Set the flavor THIS converter should use
* @param {string} name
*/
this.setFlavor = function (name) {
if (!flavor.hasOwnProperty(name)) {
throw Error(name + ' flavor was not found');
}
var preset = flavor[name];
setConvFlavor = name;
for (var option in preset) {
if (preset.hasOwnProperty(option)) {
options[option] = preset[option];
}
}
};
/**
* Get the currently set flavor of this converter
* @returns {string}
*/
this.getFlavor = function () {
return setConvFlavor;
};
/**
* Remove an extension from THIS converter.
* Note: This is a costly operation. It's better to initialize a new converter
* and specify the extensions you wish to use
* @param {Array} extension
*/
this.removeExtension = function (extension) {
if (!showdown.helper.isArray(extension)) {
extension = [extension];
}
for (var a = 0; a < extension.length; ++a) {
var ext = extension[a];
for (var i = 0; i < langExtensions.length; ++i) {
if (langExtensions[i] === ext) {
langExtensions[i].splice(i, 1);
}
}
for (var ii = 0; ii < outputModifiers.length; ++i) {
if (outputModifiers[ii] === ext) {
outputModifiers[ii].splice(i, 1);
}
}
}
};
/**
* Get all extension of THIS converter
* @returns {{language: Array, output: Array}}
*/
this.getAllExtensions = function () {
return {
language: langExtensions,
output: outputModifiers
};
};
/**
* Get the metadata of the previously parsed document
* @param raw
* @returns {string|{}}
*/
this.getMetadata = function (raw) {
if (raw) {
return metadata.raw;
} else {
return metadata.parsed;
}
};
/**
* Get the metadata format of the previously parsed document
* @returns {string}
*/
this.getMetadataFormat = function () {
return metadata.format;
};
/**
* Private: set a single key, value metadata pair
* @param {string} key
* @param {string} value
*/
this._setMetadataPair = function (key, value) {
metadata.parsed[key] = value;
};
/**
* Private: set metadata format
* @param {string} format
*/
this._setMetadataFormat = function (format) {
metadata.format = format;
};
/**
* Private: set metadata raw text
* @param {string} raw
*/
this._setMetadataRaw = function (raw) {
metadata.raw = raw;
};
};
/**
* Turn Markdown link shortcuts into XHTML <a> tags.
*/
showdown.subParser('anchors', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('anchors.before', text, options, globals);
var writeAnchorTag = function (wholeMatch, linkText, linkId, url, m5, m6, title) {
if (showdown.helper.isUndefined(title)) {
title = '';
}
linkId = linkId.toLowerCase();
// Special case for explicit empty url
if (wholeMatch.search(/\(<?\s*>? ?(['"].*['"])?\)$/m) > -1) {
url = '';
} else if (!url) {
if (!linkId) {
// lower-case and turn embedded newlines into spaces
linkId = linkText.toLowerCase().replace(/ ?\n/g, ' ');
}
url = '#' + linkId;
if (!showdown.helper.isUndefined(globals.gUrls[linkId])) {
url = globals.gUrls[linkId];
if (!showdown.helper.isUndefined(globals.gTitles[linkId])) {
title = globals.gTitles[linkId];
}
} else {
return wholeMatch;
}
}
//url = showdown.helper.escapeCharacters(url, '*_', false); // replaced line to improve performance
url = url.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);
var result = '<a href="' + url + '"';
if (title !== '' && title !== null) {
title = title.replace(/"/g, '"');
//title = showdown.helper.escapeCharacters(title, '*_', false); // replaced line to improve performance
title = title.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);
result += ' title="' + title + '"';
}
// optionLinksInNewWindow only applies
// to external links. Hash links (#) open in same page
if (options.openLinksInNewWindow && !/^#/.test(url)) {
// escaped _
result += ' rel="noopener noreferrer" target="¨E95Eblank"';
}
result += '>' + linkText + '</a>';
return result;
};
// First, handle reference-style links: [link text] [id]
text = text.replace(/\[((?:\[[^\]]*]|[^\[\]])*)] ?(?:\n *)?\[(.*?)]()()()()/g, writeAnchorTag);
// Next, inline-style links: [link text](url "optional title")
// cases with crazy urls like ./image/cat1).png
text = text.replace(/\[((?:\[[^\]]*]|[^\[\]])*)]()[ \t]*\([ \t]?<([^>]*)>(?:[ \t]*((["'])([^"]*?)\5))?[ \t]?\)/g,
writeAnchorTag);
// normal cases
text = text.replace(/\[((?:\[[^\]]*]|[^\[\]])*)]()[ \t]*\([ \t]?<?([\S]+?(?:\([\S]*?\)[\S]*?)?)>?(?:[ \t]*((["'])([^"]*?)\5))?[ \t]?\)/g,
writeAnchorTag);
// handle reference-style shortcuts: [link text]
// These must come last in case you've also got [link test][1]
// or [link test](/foo)
text = text.replace(/\[([^\[\]]+)]()()()()()/g, writeAnchorTag);
// Lastly handle GithubMentions if option is enabled
if (options.ghMentions) {
text = text.replace(/(^|\s)(\\)?(@([a-z\d]+(?:[a-z\d.-]+?[a-z\d]+)*))/gmi, function (wm, st, escape, mentions, username) {
if (escape === '\\') {
return st + mentions;
}
//check if options.ghMentionsLink is a string
if (!showdown.helper.isString(options.ghMentionsLink)) {
throw new Error('ghMentionsLink option must be a string');
}
var lnk = options.ghMentionsLink.replace(/\{u}/g, username),
target = '';
if (options.openLinksInNewWindow) {
target = ' rel="noopener noreferrer" target="¨E95Eblank"';
}
return st + '<a href="' + lnk + '"' + target + '>' + mentions + '</a>';
});
}
text = globals.converter._dispatch('anchors.after', text, options, globals);
return text;
});
// url allowed chars [a-z\d_.~:/?#[]@!$&'()*+,;=-]
var simpleURLRegex = /([*~_]+|\b)(((https?|ftp|dict):\/\/|www\.)[^'">\s]+?\.[^'">\s]+?)()(\1)?(?=\s|$)(?!["<>])/gi,
simpleURLRegex2 = /([*~_]+|\b)(((https?|ftp|dict):\/\/|www\.)[^'">\s]+\.[^'">\s]+?)([.!?,()\[\]])?(\1)?(?=\s|$)(?!["<>])/gi,
delimUrlRegex = /()<(((https?|ftp|dict):\/\/|www\.)[^'">\s]+)()>()/gi,
simpleMailRegex = /(^|\s)(?:mailto:)?([A-Za-z0-9!#$%&'*+-/=?^_`{|}~.]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)(?=$|\s)/gmi,
delimMailRegex = /<()(?:mailto:)?([-.\w]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,
replaceLink = function (options) {
'use strict';
return function (wm, leadingMagicChars, link, m2, m3, trailingPunctuation, trailingMagicChars) {
link = link.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);
var lnkTxt = link,
append = '',
target = '',
lmc = leadingMagicChars || '',
tmc = trailingMagicChars || '';
if (/^www\./i.test(link)) {
link = link.replace(/^www\./i, 'http://www.');
}
if (options.excludeTrailingPunctuationFromURLs && trailingPunctuation) {
append = trailingPunctuation;
}
if (options.openLinksInNewWindow) {
target = ' rel="noopener noreferrer" target="¨E95Eblank"';
}
return lmc + '<a href="' + link + '"' + target + '>' + lnkTxt + '</a>' + append + tmc;
};
},
replaceMail = function (options, globals) {
'use strict';
return function (wholeMatch, b, mail) {
var href = 'mailto:';
b = b || '';
mail = showdown.subParser('unescapeSpecialChars')(mail, options, globals);
if (options.encodeEmails) {
href = showdown.helper.encodeEmailAddress(href + mail);
mail = showdown.helper.encodeEmailAddress(mail);
} else {
href = href + mail;
}
return b + '<a href="' + href + '">' + mail + '</a>';
};
};
showdown.subParser('autoLinks', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('autoLinks.before', text, options, globals);
text = text.replace(delimUrlRegex, replaceLink(options));
text = text.replace(delimMailRegex, replaceMail(options, globals));
text = globals.converter._dispatch('autoLinks.after', text, options, globals);
return text;
});
showdown.subParser('simplifiedAutoLinks', function (text, options, globals) {
'use strict';
if (!options.simplifiedAutoLink) {
return text;
}
text = globals.converter._dispatch('simplifiedAutoLinks.before', text, options, globals);
if (options.excludeTrailingPunctuationFromURLs) {
text = text.replace(simpleURLRegex2, replaceLink(options));
} else {
text = text.replace(simpleURLRegex, replaceLink(options));
}
text = text.replace(simpleMailRegex, replaceMail(options, globals));
text = globals.converter._dispatch('simplifiedAutoLinks.after', text, options, globals);
return text;
});
/**
* These are all the transformations that form block-level
* tags like paragraphs, headers, and list items.
*/
showdown.subParser('blockGamut', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('blockGamut.before', text, options, globals);
// we parse blockquotes first so that we can have headings and hrs
// inside blockquotes
text = showdown.subParser('blockQuotes')(text, options, globals);
text = showdown.subParser('headers')(text, options, globals);
// Do Horizontal Rules:
text = showdown.subParser('horizontalRule')(text, options, globals);
text = showdown.subParser('lists')(text, options, globals);
text = showdown.subParser('codeBlocks')(text, options, globals);
text = showdown.subParser('tables')(text, options, globals);
// We already ran _HashHTMLBlocks() before, in Markdown(), but that
// was to escape raw HTML in the original Markdown source. This time,
// we're escaping the markup we've just created, so that we don't wrap
// <p> tags around block-level tags.
text = showdown.subParser('hashHTMLBlocks')(text, options, globals);
text = showdown.subParser('paragraphs')(text, options, globals);
text = globals.converter._dispatch('blockGamut.after', text, options, globals);
return text;
});
showdown.subParser('blockQuotes', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('blockQuotes.before', text, options, globals);
// add a couple extra lines after the text and endtext mark
text = text + '\n\n';
var rgx = /(^ {0,3}>[ \t]?.+\n(.+\n)*\n*)+/gm;
if (options.splitAdjacentBlockquotes) {
rgx = /^ {0,3}>[\s\S]*?(?:\n\n)/gm;
}
text = text.replace(rgx, function (bq) {
// attacklab: hack around Konqueror 3.5.4 bug:
// "----------bug".replace(/^-/g,"") == "bug"
bq = bq.replace(/^[ \t]*>[ \t]?/gm, ''); // trim one level of quoting
// attacklab: clean up hack
bq = bq.replace(/¨0/g, '');
bq = bq.replace(/^[ \t]+$/gm, ''); // trim whitespace-only lines
bq = showdown.subParser('githubCodeBlocks')(bq, options, globals);
bq = showdown.subParser('blockGamut')(bq, options, globals); // recurse
bq = bq.replace(/(^|\n)/g, '$1 ');
// These leading spaces screw with <pre> content, so we need to fix that:
bq = bq.replace(/(\s*<pre>[^\r]+?<\/pre>)/gm, function (wholeMatch, m1) {
var pre = m1;
// attacklab: hack around Konqueror 3.5.4 bug:
pre = pre.replace(/^ /mg, '¨0');
pre = pre.replace(/¨0/g, '');
return pre;
});
return showdown.subParser('hashBlock')('<blockquote>\n' + bq + '\n</blockquote>', options, globals);
});
text = globals.converter._dispatch('blockQuotes.after', text, options, globals);
return text;
});
/**
* Process Markdown `<pre><code>` blocks.
*/
showdown.subParser('codeBlocks', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('codeBlocks.before', text, options, globals);
// sentinel workarounds for lack of \A and \Z, safari\khtml bug
text += '¨0';
var pattern = /(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=¨0))/g;
text = text.replace(pattern, function (wholeMatch, m1, m2) {
var codeblock = m1,
nextChar = m2,
end = '\n';
codeblock = showdown.subParser('outdent')(codeblock, options, globals);
codeblock = showdown.subParser('encodeCode')(codeblock, options, globals);
codeblock = showdown.subParser('detab')(codeblock, options, globals);
codeblock = codeblock.replace(/^\n+/g, ''); // trim leading newlines
codeblock = codeblock.replace(/\n+$/g, ''); // trim trailing newlines
if (options.omitExtraWLInCodeBlocks) {
end = '';
}
codeblock = '<pre><code>' + codeblock + end + '</code></pre>';
return showdown.subParser('hashBlock')(codeblock, options, globals) + nextChar;
});
// strip sentinel
text = text.replace(/¨0/, '');
text = globals.converter._dispatch('codeBlocks.after', text, options, globals);
return text;
});
/**
*
* * Backtick quotes are used for <code></code> spans.
*
* * You can use multiple backticks as the delimiters if you want to
* include literal backticks in the code span. So, this input:
*
* Just type ``foo `bar` baz`` at the prompt.
*
* Will translate to:
*
* <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
*
* There's no arbitrary limit to the number of backticks you
* can use as delimters. If you need three consecutive backticks
* in your code, use four for delimiters, etc.
*
* * You can use spaces to get literal backticks at the edges:
*
* ... type `` `bar` `` ...
*
* Turns to:
*
* ... type <code>`bar`</code> ...
*/
showdown.subParser('codeSpans', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('codeSpans.before', text, options, globals);
if (typeof text === 'undefined') {
text = '';
}
text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,
function (wholeMatch, m1, m2, m3) {
var c = m3;
c = c.replace(/^([ \t]*)/g, ''); // leading whitespace
c = c.replace(/[ \t]*$/g, ''); // trailing whitespace
c = showdown.subParser('encodeCode')(c, options, globals);
c = m1 + '<code>' + c + '</code>';
c = showdown.subParser('hashHTMLSpans')(c, options, globals);
return c;
}
);
text = globals.converter._dispatch('codeSpans.after', text, options, globals);
return text;
});
/**
* Create a full HTML document from the processed markdown
*/
showdown.subParser('completeHTMLDocument', function (text, options, globals) {
'use strict';
if (!options.completeHTMLDocument) {
return text;
}
text = globals.converter._dispatch('completeHTMLDocument.before', text, options, globals);
var doctype = 'html',
doctypeParsed = '<!DOCTYPE HTML>\n',
title = '',
charset = '<meta charset="utf-8">\n',
lang = '',
metadata = '';
if (typeof globals.metadata.parsed.doctype !== 'undefined') {
doctypeParsed = '<!DOCTYPE ' + globals.metadata.parsed.doctype + '>\n';
doctype = globals.metadata.parsed.doctype.toString().toLowerCase();
if (doctype === 'html' || doctype === 'html5') {
charset = '<meta charset="utf-8">';
}
}
for (var meta in globals.metadata.parsed) {
if (globals.metadata.parsed.hasOwnProperty(meta)) {
switch (meta.toLowerCase()) {
case 'doctype':
break;
case 'title':
title = '<title>' + globals.metadata.parsed.title + '</title>\n';
break;
case 'charset':
if (doctype === 'html' || doctype === 'html5') {
charset = '<meta charset="' + globals.metadata.parsed.charset + '">\n';
} else {
charset = '<meta name="charset" content="' + globals.metadata.parsed.charset + '">\n';
}
break;
case 'language':
case 'lang':
lang = ' lang="' + globals.metadata.parsed[meta] + '"';
metadata += '<meta name="' + meta + '" content="' + globals.metadata.parsed[meta] + '">\n';
break;
default:
metadata += '<meta name="' + meta + '" content="' + globals.metadata.parsed[meta] + '">\n';
}
}
}
text = doctypeParsed + '<html' + lang + '>\n<head>\n' + title + charset + metadata + '</head>\n<body>\n' + text.trim() + '\n</body>\n</html>';
text = globals.converter._dispatch('completeHTMLDocument.after', text, options, globals);
return text;
});
/**
* Convert all tabs to spaces
*/
showdown.subParser('detab', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('detab.before', text, options, globals);
// expand first n-1 tabs
text = text.replace(/\t(?=\t)/g, ' '); // g_tab_width
// replace the nth with two sentinels
text = text.replace(/\t/g, '¨A¨B');
// use the sentinel to anchor our regex so it doesn't explode
text = text.replace(/¨B(.+?)¨A/g, function (wholeMatch, m1) {
var leadingText = m1,
numSpaces = 4 - leadingText.length % 4; // g_tab_width
// there *must* be a better way to do this:
for (var i = 0; i < numSpaces; i++) {
leadingText += ' ';
}
return leadingText;
});
// clean up sentinels
text = text.replace(/¨A/g, ' '); // g_tab_width
text = text.replace(/¨B/g, '');
text = globals.converter._dispatch('detab.after', text, options, globals);
return text;
});
showdown.subParser('ellipsis', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('ellipsis.before', text, options, globals);
text = text.replace(/\.\.\./g, '…');
text = globals.converter._dispatch('ellipsis.after', text, options, globals);
return text;
});
/**
* Turn emoji codes into emojis
*
* List of supported emojis: https://github.com/showdownjs/showdown/wiki/Emojis
*/
showdown.subParser('emoji', function (text, options, globals) {
'use strict';
if (!options.emoji) {
return text;
}
text = globals.converter._dispatch('emoji.before', text, options, globals);
var emojiRgx = /:([\S]+?):/g;
text = text.replace(emojiRgx, function (wm, emojiCode) {
if (showdown.helper.emojis.hasOwnProperty(emojiCode)) {
return showdown.helper.emojis[emojiCode];
}
return wm;
});
text = globals.converter._dispatch('emoji.after', text, options, globals);
return text;
});
/**
* Smart processing for ampersands and angle brackets that need to be encoded.
*/
showdown.subParser('encodeAmpsAndAngles', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('encodeAmpsAndAngles.before', text, options, globals);
// Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
// http://bumppo.net/projects/amputator/
text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g, '&');
// Encode naked <'s
text = text.replace(/<(?![a-z\/?$!])/gi, '<');
// Encode <
text = text.replace(/</g, '<');
// Encode >
text = text.replace(/>/g, '>');
text = globals.converter._dispatch('encodeAmpsAndAngles.after', text, options, globals);
return text;
});
/**
* Returns the string, with after processing the following backslash escape sequences.
*
* attacklab: The polite way to do this is with the new escapeCharacters() function:
*
* text = escapeCharacters(text,"\\",true);
* text = escapeCharacters(text,"`*_{}[]()>#+-.!",true);
*
* ...but we're sidestepping its use of the (slow) RegExp constructor
* as an optimization for Firefox. This function gets called a LOT.
*/
showdown.subParser('encodeBackslashEscapes', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('encodeBackslashEscapes.before', text, options, globals);
text = text.replace(/\\(\\)/g, showdown.helper.escapeCharactersCallback);
text = text.replace(/\\([`*_{}\[\]()>#+.!~=|-])/g, showdown.helper.escapeCharactersCallback);
text = globals.converter._dispatch('encodeBackslashEscapes.after', text, options, globals);
return text;
});
/**
* Encode/escape certain characters inside Markdown code runs.
* The point is that in code, these characters are literals,
* and lose their special Markdown meanings.
*/
showdown.subParser('encodeCode', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('encodeCode.before', text, options, globals);
// Encode all ampersands; HTML entities are not
// entities within a Markdown code span.
text = text
.replace(/&/g, '&')
// Do the angle bracket song and dance:
.replace(/</g, '<')
.replace(/>/g, '>')
// Now, escape characters that are magic in Markdown:
.replace(/([*_{}\[\]\\=~-])/g, showdown.helper.escapeCharactersCallback);
text = globals.converter._dispatch('encodeCode.after', text, options, globals);
return text;
});
/**
* Within tags -- meaning between < and > -- encode [\ ` * _ ~ =] so they
* don't conflict with their use in Markdown for code, italics and strong.
*/
showdown.subParser('escapeSpecialCharsWithinTagAttributes', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('escapeSpecialCharsWithinTagAttributes.before', text, options, globals);
// Build a regex to find HTML tags.
var tags = /<\/?[a-z\d_:-]+(?:[\s]+[\s\S]+?)?>/gi,
comments = /<!(--(?:(?:[^>-]|-[^>])(?:[^-]|-[^-])*)--)>/gi;
text = text.replace(tags, function (wholeMatch) {
return wholeMatch
.replace(/(.)<\/?code>(?=.)/g, '$1`')
.replace(/([\\`*_~=|])/g, showdown.helper.escapeCharactersCallback);
});
text = text.replace(comments, function (wholeMatch) {
return wholeMatch
.replace(/([\\`*_~=|])/g, showdown.helper.escapeCharactersCallback);
});
text = globals.converter._dispatch('escapeSpecialCharsWithinTagAttributes.after', text, options, globals);
return text;
});
/**
* Handle github codeblocks prior to running HashHTML so that
* HTML contained within the codeblock gets escaped properly
* Example:
* ```ruby
* def hello_world(x)
* puts "Hello, #{x}"
* end
* ```
*/
showdown.subParser('githubCodeBlocks', function (text, options, globals) {
'use strict';
// early exit if option is not enabled
if (!options.ghCodeBlocks) {
return text;
}
text = globals.converter._dispatch('githubCodeBlocks.before', text, options, globals);
text += '¨0';
text = text.replace(/(?:^|\n)(?: {0,3})(```+|~~~+)(?: *)([^\s`~]*)\n([\s\S]*?)\n(?: {0,3})\1/g, function (wholeMatch, delim, language, codeblock) {
var end = (options.omitExtraWLInCodeBlocks) ? '' : '\n';
// First parse the github code block
codeblock = showdown.subParser('encodeCode')(codeblock, options, globals);
codeblock = showdown.subParser('detab')(codeblock, options, globals);
codeblock = codeblock.replace(/^\n+/g, ''); // trim leading newlines
codeblock = codeblock.replace(/\n+$/g, ''); // trim trailing whitespace
codeblock = '<pre><code' + (language ? ' class="' + language + ' language-' + language + '"' : '') + '>' + codeblock + end + '</code></pre>';
codeblock = showdown.subParser('hashBlock')(codeblock, options, globals);
// Since GHCodeblocks can be false positives, we need to
// store the primitive text and the parsed text in a global var,
// and then return a token
return '\n\n¨G' + (globals.ghCodeBlocks.push({text: wholeMatch, codeblock: codeblock}) - 1) + 'G\n\n';
});
// attacklab: strip sentinel
text = text.replace(/¨0/, '');
return globals.converter._dispatch('githubCodeBlocks.after', text, options, globals);
});
showdown.subParser('hashBlock', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('hashBlock.before', text, options, globals);
text = text.replace(/(^\n+|\n+$)/g, '');
text = '\n\n¨K' + (globals.gHtmlBlocks.push(text) - 1) + 'K\n\n';
text = globals.converter._dispatch('hashBlock.after', text, options, globals);
return text;
});
/**
* Hash and escape <code> elements that should not be parsed as markdown
*/
showdown.subParser('hashCodeTags', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('hashCodeTags.before', text, options, globals);
var repFunc = function (wholeMatch, match, left, right) {
var codeblock = left + showdown.subParser('encodeCode')(match, options, globals) + right;
return '¨C' + (globals.gHtmlSpans.push(codeblock) - 1) + 'C';
};
// Hash naked <code>
text = showdown.helper.replaceRecursiveRegExp(text, repFunc, '<code\\b[^>]*>', '</code>', 'gim');
text = globals.converter._dispatch('hashCodeTags.after', text, options, globals);
return text;
});
showdown.subParser('hashElement', function (text, options, globals) {
'use strict';
return function (wholeMatch, m1) {
var blockText = m1;
// Undo double lines
blockText = blockText.replace(/\n\n/g, '\n');
blockText = blockText.replace(/^\n/, '');
// strip trailing blank lines
blockText = blockText.replace(/\n+$/g, '');
// Replace the element text with a marker ("¨KxK" where x is its key)
blockText = '\n\n¨K' + (globals.gHtmlBlocks.push(blockText) - 1) + 'K\n\n';
return blockText;
};
});
showdown.subParser('hashHTMLBlocks', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('hashHTMLBlocks.before', text, options, globals);
var blockTags = [
'pre',
'div',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'blockquote',
'table',
'dl',
'ol',
'ul',
'script',
'noscript',
'form',
'fieldset',
'iframe',
'math',
'style',
'section',
'header',
'footer',
'nav',
'article',
'aside',
'address',
'audio',
'canvas',
'figure',
'hgroup',
'output',
'video',
'p'
],
repFunc = function (wholeMatch, match, left, right) {
var txt = wholeMatch;
// check if this html element is marked as markdown
// if so, it's contents should be parsed as markdown
if (left.search(/\bmarkdown\b/) !== -1) {
txt = left + globals.converter.makeHtml(match) + right;
}
return '\n\n¨K' + (globals.gHtmlBlocks.push(txt) - 1) + 'K\n\n';
};
if (options.backslashEscapesHTMLTags) {
// encode backslash escaped HTML tags
text = text.replace(/\\<(\/?[^>]+?)>/g, function (wm, inside) {
return '<' + inside + '>';
});
}
// hash HTML Blocks
for (var i = 0; i < blockTags.length; ++i) {
var opTagPos,
rgx1 = new RegExp('^ {0,3}(<' + blockTags[i] + '\\b[^>]*>)', 'im'),
patLeft = '<' + blockTags[i] + '\\b[^>]*>',
patRight = '</' + blockTags[i] + '>';
// 1. Look for the first position of the first opening HTML tag in the text
while ((opTagPos = showdown.helper.regexIndexOf(text, rgx1)) !== -1) {
// if the HTML tag is \ escaped, we need to escape it and break
//2. Split the text in that position
var subTexts = showdown.helper.splitAtIndex(text, opTagPos),
//3. Match recursively
newSubText1 = showdown.helper.replaceRecursiveRegExp(subTexts[1], repFunc, patLeft, patRight, 'im');
// prevent an infinite loop
if (newSubText1 === subTexts[1]) {
break;
}
text = subTexts[0].concat(newSubText1);
}
}
// HR SPECIAL CASE
text = text.replace(/(\n {0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,
showdown.subParser('hashElement')(text, options, globals));
// Special case for standalone HTML comments
text = showdown.helper.replaceRecursiveRegExp(text, function (txt) {
return '\n\n¨K' + (globals.gHtmlBlocks.push(txt) - 1) + 'K\n\n';
}, '^ {0,3}<!--', '-->', 'gm');
// PHP and ASP-style processor instructions (<?...?> and <%...%>)
text = text.replace(/(?:\n\n)( {0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,
showdown.subParser('hashElement')(text, options, globals));
text = globals.converter._dispatch('hashHTMLBlocks.after', text, options, globals);
return text;
});
/**
* Hash span elements that should not be parsed as markdown
*/
showdown.subParser('hashHTMLSpans', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('hashHTMLSpans.before', text, options, globals);
function hashHTMLSpan (html) {
return '¨C' + (globals.gHtmlSpans.push(html) - 1) + 'C';
}
// Hash Self Closing tags
text = text.replace(/<[^>]+?\/>/gi, function (wm) {
return hashHTMLSpan(wm);
});
// Hash tags without properties
text = text.replace(/<([^>]+?)>[\s\S]*?<\/\1>/g, function (wm) {
return hashHTMLSpan(wm);
});
// Hash tags with properties
text = text.replace(/<([^>]+?)\s[^>]+?>[\s\S]*?<\/\1>/g, function (wm) {
return hashHTMLSpan(wm);
});
// Hash self closing tags without />
text = text.replace(/<[^>]+?>/gi, function (wm) {
return hashHTMLSpan(wm);
});
/*showdown.helper.matchRecursiveRegExp(text, '<code\\b[^>]*>', '</code>', 'gi');*/
text = globals.converter._dispatch('hashHTMLSpans.after', text, options, globals);
return text;
});
/**
* Unhash HTML spans
*/
showdown.subParser('unhashHTMLSpans', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('unhashHTMLSpans.before', text, options, globals);
for (var i = 0; i < globals.gHtmlSpans.length; ++i) {
var repText = globals.gHtmlSpans[i],
// limiter to prevent infinite loop (assume 10 as limit for recurse)
limit = 0;
while (/¨C(\d+)C/.test(repText)) {
var num = RegExp.$1;
repText = repText.replace('¨C' + num + 'C', globals.gHtmlSpans[num]);
if (limit === 10) {
console.error('maximum nesting of 10 spans reached!!!');
break;
}
++limit;
}
text = text.replace('¨C' + i + 'C', repText);
}
text = globals.converter._dispatch('unhashHTMLSpans.after', text, options, globals);
return text;
});
/**
* Hash and escape <pre><code> elements that should not be parsed as markdown
*/
showdown.subParser('hashPreCodeTags', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('hashPreCodeTags.before', text, options, globals);
var repFunc = function (wholeMatch, match, left, right) {
// encode html entities
var codeblock = left + showdown.subParser('encodeCode')(match, options, globals) + right;
return '\n\n¨G' + (globals.ghCodeBlocks.push({text: wholeMatch, codeblock: codeblock}) - 1) + 'G\n\n';
};
// Hash <pre><code>
text = showdown.helper.replaceRecursiveRegExp(text, repFunc, '^ {0,3}<pre\\b[^>]*>\\s*<code\\b[^>]*>', '^ {0,3}</code>\\s*</pre>', 'gim');
text = globals.converter._dispatch('hashPreCodeTags.after', text, options, globals);
return text;
});
showdown.subParser('headers', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('headers.before', text, options, globals);
var headerLevelStart = (isNaN(parseInt(options.headerLevelStart))) ? 1 : parseInt(options.headerLevelStart),
// Set text-style headers:
// Header 1
// ========
//
// Header 2
// --------
//
setextRegexH1 = (options.smoothLivePreview) ? /^(.+)[ \t]*\n={2,}[ \t]*\n+/gm : /^(.+)[ \t]*\n=+[ \t]*\n+/gm,
setextRegexH2 = (options.smoothLivePreview) ? /^(.+)[ \t]*\n-{2,}[ \t]*\n+/gm : /^(.+)[ \t]*\n-+[ \t]*\n+/gm;
text = text.replace(setextRegexH1, function (wholeMatch, m1) {
var spanGamut = showdown.subParser('spanGamut')(m1, options, globals),
hID = (options.noHeaderId) ? '' : ' id="' + headerId(m1) + '"',
hLevel = headerLevelStart,
hashBlock = '<h' + hLevel + hID + '>' + spanGamut + '</h' + hLevel + '>';
return showdown.subParser('hashBlock')(hashBlock, options, globals);
});
text = text.replace(setextRegexH2, function (matchFound, m1) {
var spanGamut = showdown.subParser('spanGamut')(m1, options, globals),
hID = (options.noHeaderId) ? '' : ' id="' + headerId(m1) + '"',
hLevel = headerLevelStart + 1,
hashBlock = '<h' + hLevel + hID + '>' + spanGamut + '</h' + hLevel + '>';
return showdown.subParser('hashBlock')(hashBlock, options, globals);
});
// atx-style headers:
// # Header 1
// ## Header 2
// ## Header 2 with closing hashes ##
// ...
// ###### Header 6
//
var atxStyle = (options.requireSpaceBeforeHeadingText) ? /^(#{1,6})[ \t]+(.+?)[ \t]*#*\n+/gm : /^(#{1,6})[ \t]*(.+?)[ \t]*#*\n+/gm;
text = text.replace(atxStyle, function (wholeMatch, m1, m2) {
var hText = m2;
if (options.customizedHeaderId) {
hText = m2.replace(/\s?\{([^{]+?)}\s*$/, '');
}
var span = showdown.subParser('spanGamut')(hText, options, globals),
hID = (options.noHeaderId) ? '' : ' id="' + headerId(m2) + '"',
hLevel = headerLevelStart - 1 + m1.length,
header = '<h' + hLevel + hID + '>' + span + '</h' + hLevel + '>';
return showdown.subParser('hashBlock')(header, options, globals);
});
function headerId (m) {
var title,
prefix;
// It is separate from other options to allow combining prefix and customized
if (options.customizedHeaderId) {
var match = m.match(/\{([^{]+?)}\s*$/);
if (match && match[1]) {
m = match[1];
}
}
title = m;
// Prefix id to prevent causing inadvertent pre-existing style matches.
if (showdown.helper.isString(options.prefixHeaderId)) {
prefix = options.prefixHeaderId;
} else if (options.prefixHeaderId === true) {
prefix = 'section-';
} else {
prefix = '';
}
if (!options.rawPrefixHeaderId) {
title = prefix + title;
}
if (options.ghCompatibleHeaderId) {
title = title
.replace(/ /g, '-')
// replace previously escaped chars (&, ¨ and $)
.replace(/&/g, '')
.replace(/¨T/g, '')
.replace(/¨D/g, '')
// replace rest of the chars (&~$ are repeated as they might have been escaped)
// borrowed from github's redcarpet (some they should produce similar results)
.replace(/[&+$,\/:;=?@"#{}|^¨~\[\]`\\*)(%.!'<>]/g, '')
.toLowerCase();
} else if (options.rawHeaderId) {
title = title
.replace(/ /g, '-')
// replace previously escaped chars (&, ¨ and $)
.replace(/&/g, '&')
.replace(/¨T/g, '¨')
.replace(/¨D/g, '$')
// replace " and '
.replace(/["']/g, '-')
.toLowerCase();
} else {
title = title
.replace(/[^\w]/g, '')
.toLowerCase();
}
if (options.rawPrefixHeaderId) {
title = prefix + title;
}
if (globals.hashLinkCounts[title]) {
title = title + '-' + (globals.hashLinkCounts[title]++);
} else {
globals.hashLinkCounts[title] = 1;
}
return title;
}
text = globals.converter._dispatch('headers.after', text, options, globals);
return text;
});
/**
* Turn Markdown link shortcuts into XHTML <a> tags.
*/
showdown.subParser('horizontalRule', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('horizontalRule.before', text, options, globals);
var key = showdown.subParser('hashBlock')('<hr />', options, globals);
text = text.replace(/^ {0,2}( ?-){3,}[ \t]*$/gm, key);
text = text.replace(/^ {0,2}( ?\*){3,}[ \t]*$/gm, key);
text = text.replace(/^ {0,2}( ?_){3,}[ \t]*$/gm, key);
text = globals.converter._dispatch('horizontalRule.after', text, options, globals);
return text;
});
/**
* Turn Markdown image shortcuts into <img> tags.
*/
showdown.subParser('images', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('images.before', text, options, globals);
var inlineRegExp = /!\[([^\]]*?)][ \t]*()\([ \t]?<?([\S]+?(?:\([\S]*?\)[\S]*?)?)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(["'])([^"]*?)\6)?[ \t]?\)/g,
crazyRegExp = /!\[([^\]]*?)][ \t]*()\([ \t]?<([^>]*)>(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(?:(["'])([^"]*?)\6))?[ \t]?\)/g,
base64RegExp = /!\[([^\]]*?)][ \t]*()\([ \t]?<?(data:.+?\/.+?;base64,[A-Za-z0-9+/=\n]+?)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(["'])([^"]*?)\6)?[ \t]?\)/g,
referenceRegExp = /!\[([^\]]*?)] ?(?:\n *)?\[([\s\S]*?)]()()()()()/g,
refShortcutRegExp = /!\[([^\[\]]+)]()()()()()/g;
function writeImageTagBase64 (wholeMatch, altText, linkId, url, width, height, m5, title) {
url = url.replace(/\s/g, '');
return writeImageTag (wholeMatch, altText, linkId, url, width, height, m5, title);
}
function writeImageTag (wholeMatch, altText, linkId, url, width, height, m5, title) {
var gUrls = globals.gUrls,
gTitles = globals.gTitles,
gDims = globals.gDimensions;
linkId = linkId.toLowerCase();
if (!title) {
title = '';
}
// Special case for explicit empty url
if (wholeMatch.search(/\(<?\s*>? ?(['"].*['"])?\)$/m) > -1) {
url = '';
} else if (url === '' || url === null) {
if (linkId === '' || linkId === null) {
// lower-case and turn embedded newlines into spaces
linkId = altText.toLowerCase().replace(/ ?\n/g, ' ');
}
url = '#' + linkId;
if (!showdown.helper.isUndefined(gUrls[linkId])) {
url = gUrls[linkId];
if (!showdown.helper.isUndefined(gTitles[linkId])) {
title = gTitles[linkId];
}
if (!showdown.helper.isUndefined(gDims[linkId])) {
width = gDims[linkId].width;
height = gDims[linkId].height;
}
} else {
return wholeMatch;
}
}
altText = altText
.replace(/"/g, '"')
//altText = showdown.helper.escapeCharacters(altText, '*_', false);
.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);
//url = showdown.helper.escapeCharacters(url, '*_', false);
url = url.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);
var result = '<img src="' + url + '" alt="' + altText + '"';
if (title && showdown.helper.isString(title)) {
title = title
.replace(/"/g, '"')
//title = showdown.helper.escapeCharacters(title, '*_', false);
.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);
result += ' title="' + title + '"';
}
if (width && height) {
width = (width === '*') ? 'auto' : width;
height = (height === '*') ? 'auto' : height;
result += ' width="' + width + '"';
result += ' height="' + height + '"';
}
result += ' />';
return result;
}
// First, handle reference-style labeled images: ![alt text][id]
text = text.replace(referenceRegExp, writeImageTag);
// Next, handle inline images: 
// base64 encoded images
text = text.replace(base64RegExp, writeImageTagBase64);
// cases with crazy urls like ./image/cat1).png
text = text.replace(crazyRegExp, writeImageTag);
// normal cases
text = text.replace(inlineRegExp, writeImageTag);
// handle reference-style shortcuts: ![img text]
text = text.replace(refShortcutRegExp, writeImageTag);
text = globals.converter._dispatch('images.after', text, options, globals);
return text;
});
showdown.subParser('italicsAndBold', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('italicsAndBold.before', text, options, globals);
// it's faster to have 3 separate regexes for each case than have just one
// because of backtracing, in some cases, it could lead to an exponential effect
// called "catastrophic backtrace". Ominous!
function parseInside (txt, left, right) {
/*
if (options.simplifiedAutoLink) {
txt = showdown.subParser('simplifiedAutoLinks')(txt, options, globals);
}
*/
return left + txt + right;
}
// Parse underscores
if (options.literalMidWordUnderscores) {
text = text.replace(/\b___(\S[\s\S]*?)___\b/g, function (wm, txt) {
return parseInside (txt, '<strong><em>', '</em></strong>');
});
text = text.replace(/\b__(\S[\s\S]*?)__\b/g, function (wm, txt) {
return parseInside (txt, '<strong>', '</strong>');
});
text = text.replace(/\b_(\S[\s\S]*?)_\b/g, function (wm, txt) {
return parseInside (txt, '<em>', '</em>');
});
} else {
text = text.replace(/___(\S[\s\S]*?)___/g, function (wm, m) {
return (/\S$/.test(m)) ? parseInside (m, '<strong><em>', '</em></strong>') : wm;
});
text = text.replace(/__(\S[\s\S]*?)__/g, function (wm, m) {
return (/\S$/.test(m)) ? parseInside (m, '<strong>', '</strong>') : wm;
});
text = text.replace(/_([^\s_][\s\S]*?)_/g, function (wm, m) {
// !/^_[^_]/.test(m) - test if it doesn't start with __ (since it seems redundant, we removed it)
return (/\S$/.test(m)) ? parseInside (m, '<em>', '</em>') : wm;
});
}
// Now parse asterisks
if (options.literalMidWordAsterisks) {
text = text.replace(/([^*]|^)\B\*\*\*(\S[\s\S]*?)\*\*\*\B(?!\*)/g, function (wm, lead, txt) {
return parseInside (txt, lead + '<strong><em>', '</em></strong>');
});
text = text.replace(/([^*]|^)\B\*\*(\S[\s\S]*?)\*\*\B(?!\*)/g, function (wm, lead, txt) {
return parseInside (txt, lead + '<strong>', '</strong>');
});
text = text.replace(/([^*]|^)\B\*(\S[\s\S]*?)\*\B(?!\*)/g, function (wm, lead, txt) {
return parseInside (txt, lead + '<em>', '</em>');
});
} else {
text = text.replace(/\*\*\*(\S[\s\S]*?)\*\*\*/g, function (wm, m) {
return (/\S$/.test(m)) ? parseInside (m, '<strong><em>', '</em></strong>') : wm;
});
text = text.replace(/\*\*(\S[\s\S]*?)\*\*/g, function (wm, m) {
return (/\S$/.test(m)) ? parseInside (m, '<strong>', '</strong>') : wm;
});
text = text.replace(/\*([^\s*][\s\S]*?)\*/g, function (wm, m) {
// !/^\*[^*]/.test(m) - test if it doesn't start with ** (since it seems redundant, we removed it)
return (/\S$/.test(m)) ? parseInside (m, '<em>', '</em>') : wm;
});
}
text = globals.converter._dispatch('italicsAndBold.after', text, options, globals);
return text;
});
/**
* Form HTML ordered (numbered) and unordered (bulleted) lists.
*/
showdown.subParser('lists', function (text, options, globals) {
'use strict';
/**
* Process the contents of a single ordered or unordered list, splitting it
* into individual list items.
* @param {string} listStr
* @param {boolean} trimTrailing
* @returns {string}
*/
function processListItems (listStr, trimTrailing) {
// The $g_list_level global keeps track of when we're inside a list.
// Each time we enter a list, we increment it; when we leave a list,
// we decrement. If it's zero, we're not in a list anymore.
//
// We do this because when we're not inside a list, we want to treat
// something like this:
//
// I recommend upgrading to version
// 8. Oops, now this line is treated
// as a sub-list.
//
// As a single paragraph, despite the fact that the second line starts
// with a digit-period-space sequence.
//
// Whereas when we're inside a list (or sub-list), that line will be
// treated as the start of a sub-list. What a kludge, huh? This is
// an aspect of Markdown's syntax that's hard to parse perfectly
// without resorting to mind-reading. Perhaps the solution is to
// change the syntax rules such that sub-lists must start with a
// starting cardinal number; e.g. "1." or "a.".
globals.gListLevel++;
// trim trailing blank lines:
listStr = listStr.replace(/\n{2,}$/, '\n');
// attacklab: add sentinel to emulate \z
listStr += '¨0';
var rgx = /(\n)?(^ {0,3})([*+-]|\d+[.])[ \t]+((\[(x|X| )?])?[ \t]*[^\r]+?(\n{1,2}))(?=\n*(¨0| {0,3}([*+-]|\d+[.])[ \t]+))/gm,
isParagraphed = (/\n[ \t]*\n(?!¨0)/.test(listStr));
// Since version 1.5, nesting sublists requires 4 spaces (or 1 tab) indentation,
// which is a syntax breaking change
// activating this option reverts to old behavior
if (options.disableForced4SpacesIndentedSublists) {
rgx = /(\n)?(^ {0,3})([*+-]|\d+[.])[ \t]+((\[(x|X| )?])?[ \t]*[^\r]+?(\n{1,2}))(?=\n*(¨0|\2([*+-]|\d+[.])[ \t]+))/gm;
}
listStr = listStr.replace(rgx, function (wholeMatch, m1, m2, m3, m4, taskbtn, checked) {
checked = (checked && checked.trim() !== '');
var item = showdown.subParser('outdent')(m4, options, globals),
bulletStyle = '';
// Support for github tasklists
if (taskbtn && options.tasklists) {
bulletStyle = ' class="task-list-item" style="list-style-type: none;"';
item = item.replace(/^[ \t]*\[(x|X| )?]/m, function () {
var otp = '<input type="checkbox" disabled style="margin: 0px 0.35em 0.25em -1.6em; vertical-align: middle;"';
if (checked) {
otp += ' checked';
}
otp += '>';
return otp;
});
}
// ISSUE #312
// This input: - - - a
// causes trouble to the parser, since it interprets it as:
// <ul><li><li><li>a</li></li></li></ul>
// instead of:
// <ul><li>- - a</li></ul>
// So, to prevent it, we will put a marker (¨A)in the beginning of the line
// Kind of hackish/monkey patching, but seems more effective than overcomplicating the list parser
item = item.replace(/^([-*+]|\d\.)[ \t]+[\S\n ]*/g, function (wm2) {
return '¨A' + wm2;
});
// m1 - Leading line or
// Has a double return (multi paragraph) or
// Has sublist
if (m1 || (item.search(/\n{2,}/) > -1)) {
item = showdown.subParser('githubCodeBlocks')(item, options, globals);
item = showdown.subParser('blockGamut')(item, options, globals);
} else {
// Recursion for sub-lists:
item = showdown.subParser('lists')(item, options, globals);
item = item.replace(/\n$/, ''); // chomp(item)
item = showdown.subParser('hashHTMLBlocks')(item, options, globals);
// Colapse double linebreaks
item = item.replace(/\n\n+/g, '\n\n');
if (isParagraphed) {
item = showdown.subParser('paragraphs')(item, options, globals);
} else {
item = showdown.subParser('spanGamut')(item, options, globals);
}
}
// now we need to remove the marker (¨A)
item = item.replace('¨A', '');
// we can finally wrap the line in list item tags
item = '<li' + bulletStyle + '>' + item + '</li>\n';
return item;
});
// attacklab: strip sentinel
listStr = listStr.replace(/¨0/g, '');
globals.gListLevel--;
if (trimTrailing) {
listStr = listStr.replace(/\s+$/, '');
}
return listStr;
}
function styleStartNumber (list, listType) {
// check if ol and starts by a number different than 1
if (listType === 'ol') {
var res = list.match(/^ *(\d+)\./);
if (res && res[1] !== '1') {
return ' start="' + res[1] + '"';
}
}
return '';
}
/**
* Check and parse consecutive lists (better fix for issue #142)
* @param {string} list
* @param {string} listType
* @param {boolean} trimTrailing
* @returns {string}
*/
function parseConsecutiveLists (list, listType, trimTrailing) {
// check if we caught 2 or more consecutive lists by mistake
// we use the counterRgx, meaning if listType is UL we look for OL and vice versa
var olRgx = (options.disableForced4SpacesIndentedSublists) ? /^ ?\d+\.[ \t]/gm : /^ {0,3}\d+\.[ \t]/gm,
ulRgx = (options.disableForced4SpacesIndentedSublists) ? /^ ?[*+-][ \t]/gm : /^ {0,3}[*+-][ \t]/gm,
counterRxg = (listType === 'ul') ? olRgx : ulRgx,
result = '';
if (list.search(counterRxg) !== -1) {
(function parseCL (txt) {
var pos = txt.search(counterRxg),
style = styleStartNumber(list, listType);
if (pos !== -1) {
// slice
result += '\n\n<' + listType + style + '>\n' + processListItems(txt.slice(0, pos), !!trimTrailing) + '</' + listType + '>\n';
// invert counterType and listType
listType = (listType === 'ul') ? 'ol' : 'ul';
counterRxg = (listType === 'ul') ? olRgx : ulRgx;
//recurse
parseCL(txt.slice(pos));
} else {
result += '\n\n<' + listType + style + '>\n' + processListItems(txt, !!trimTrailing) + '</' + listType + '>\n';
}
})(list);
} else {
var style = styleStartNumber(list, listType);
result = '\n\n<' + listType + style + '>\n' + processListItems(list, !!trimTrailing) + '</' + listType + '>\n';
}
return result;
}
/** Start of list parsing **/
text = globals.converter._dispatch('lists.before', text, options, globals);
// add sentinel to hack around khtml/safari bug:
// http://bugs.webkit.org/show_bug.cgi?id=11231
text += '¨0';
if (globals.gListLevel) {
text = text.replace(/^(( {0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(¨0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm,
function (wholeMatch, list, m2) {
var listType = (m2.search(/[*+-]/g) > -1) ? 'ul' : 'ol';
return parseConsecutiveLists(list, listType, true);
}
);
} else {
text = text.replace(/(\n\n|^\n?)(( {0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(¨0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm,
function (wholeMatch, m1, list, m3) {
var listType = (m3.search(/[*+-]/g) > -1) ? 'ul' : 'ol';
return parseConsecutiveLists(list, listType, false);
}
);
}
// strip sentinel
text = text.replace(/¨0/, '');
text = globals.converter._dispatch('lists.after', text, options, globals);
return text;
});
/**
* Parse metadata at the top of the document
*/
showdown.subParser('metadata', function (text, options, globals) {
'use strict';
if (!options.metadata) {
return text;
}
text = globals.converter._dispatch('metadata.before', text, options, globals);
function parseMetadataContents (content) {
// raw is raw so it's not changed in any way
globals.metadata.raw = content;
// escape chars forbidden in html attributes
// double quotes
content = content
// ampersand first
.replace(/&/g, '&')
// double quotes
.replace(/"/g, '"');
content = content.replace(/\n {4}/g, ' ');
content.replace(/^([\S ]+): +([\s\S]+?)$/gm, function (wm, key, value) {
globals.metadata.parsed[key] = value;
return '';
});
}
text = text.replace(/^\s*«««+(\S*?)\n([\s\S]+?)\n»»»+\n/, function (wholematch, format, content) {
parseMetadataContents(content);
return '¨M';
});
text = text.replace(/^\s*---+(\S*?)\n([\s\S]+?)\n---+\n/, function (wholematch, format, content) {
if (format) {
globals.metadata.format = format;
}
parseMetadataContents(content);
return '¨M';
});
text = text.replace(/¨M/g, '');
text = globals.converter._dispatch('metadata.after', text, options, globals);
return text;
});
/**
* Remove one level of line-leading tabs or spaces
*/
showdown.subParser('outdent', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('outdent.before', text, options, globals);
// attacklab: hack around Konqueror 3.5.4 bug:
// "----------bug".replace(/^-/g,"") == "bug"
text = text.replace(/^(\t|[ ]{1,4})/gm, '¨0'); // attacklab: g_tab_width
// attacklab: clean up hack
text = text.replace(/¨0/g, '');
text = globals.converter._dispatch('outdent.after', text, options, globals);
return text;
});
/**
*
*/
showdown.subParser('paragraphs', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('paragraphs.before', text, options, globals);
// Strip leading and trailing lines:
text = text.replace(/^\n+/g, '');
text = text.replace(/\n+$/g, '');
var grafs = text.split(/\n{2,}/g),
grafsOut = [],
end = grafs.length; // Wrap <p> tags
for (var i = 0; i < end; i++) {
var str = grafs[i];
// if this is an HTML marker, copy it
if (str.search(/¨(K|G)(\d+)\1/g) >= 0) {
grafsOut.push(str);
// test for presence of characters to prevent empty lines being parsed
// as paragraphs (resulting in undesired extra empty paragraphs)
} else if (str.search(/\S/) >= 0) {
str = showdown.subParser('spanGamut')(str, options, globals);
str = str.replace(/^([ \t]*)/g, '<p>');
str += '</p>';
grafsOut.push(str);
}
}
/** Unhashify HTML blocks */
end = grafsOut.length;
for (i = 0; i < end; i++) {
var blockText = '',
grafsOutIt = grafsOut[i],
codeFlag = false;
// if this is a marker for an html block...
// use RegExp.test instead of string.search because of QML bug
while (/¨(K|G)(\d+)\1/.test(grafsOutIt)) {
var delim = RegExp.$1,
num = RegExp.$2;
if (delim === 'K') {
blockText = globals.gHtmlBlocks[num];
} else {
// we need to check if ghBlock is a false positive
if (codeFlag) {
// use encoded version of all text
blockText = showdown.subParser('encodeCode')(globals.ghCodeBlocks[num].text, options, globals);
} else {
blockText = globals.ghCodeBlocks[num].codeblock;
}
}
blockText = blockText.replace(/\$/g, '$$$$'); // Escape any dollar signs
grafsOutIt = grafsOutIt.replace(/(\n\n)?¨(K|G)\d+\2(\n\n)?/, blockText);
// Check if grafsOutIt is a pre->code
if (/^<pre\b[^>]*>\s*<code\b[^>]*>/.test(grafsOutIt)) {
codeFlag = true;
}
}
grafsOut[i] = grafsOutIt;
}
text = grafsOut.join('\n');
// Strip leading and trailing lines:
text = text.replace(/^\n+/g, '');
text = text.replace(/\n+$/g, '');
return globals.converter._dispatch('paragraphs.after', text, options, globals);
});
/**
* Run extension
*/
showdown.subParser('runExtension', function (ext, text, options, globals) {
'use strict';
if (ext.filter) {
text = ext.filter(text, globals.converter, options);
} else if (ext.regex) {
// TODO remove this when old extension loading mechanism is deprecated
var re = ext.regex;
if (!(re instanceof RegExp)) {
re = new RegExp(re, 'g');
}
text = text.replace(re, ext.replace);
}
return text;
});
/**
* These are all the transformations that occur *within* block-level
* tags like paragraphs, headers, and list items.
*/
showdown.subParser('spanGamut', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('spanGamut.before', text, options, globals);
text = showdown.subParser('codeSpans')(text, options, globals);
text = showdown.subParser('escapeSpecialCharsWithinTagAttributes')(text, options, globals);
text = showdown.subParser('encodeBackslashEscapes')(text, options, globals);
// Process anchor and image tags. Images must come first,
// because ![foo][f] looks like an anchor.
text = showdown.subParser('images')(text, options, globals);
text = showdown.subParser('anchors')(text, options, globals);
// Make links out of things like `<http://example.com/>`
// Must come after anchors, because you can use < and >
// delimiters in inline links like [this](<url>).
text = showdown.subParser('autoLinks')(text, options, globals);
text = showdown.subParser('simplifiedAutoLinks')(text, options, globals);
text = showdown.subParser('emoji')(text, options, globals);
text = showdown.subParser('underline')(text, options, globals);
text = showdown.subParser('italicsAndBold')(text, options, globals);
text = showdown.subParser('strikethrough')(text, options, globals);
text = showdown.subParser('ellipsis')(text, options, globals);
// we need to hash HTML tags inside spans
text = showdown.subParser('hashHTMLSpans')(text, options, globals);
// now we encode amps and angles
text = showdown.subParser('encodeAmpsAndAngles')(text, options, globals);
// Do hard breaks
if (options.simpleLineBreaks) {
// GFM style hard breaks
// only add line breaks if the text does not contain a block (special case for lists)
if (!/\n\n¨K/.test(text)) {
text = text.replace(/\n+/g, '<br />\n');
}
} else {
// Vanilla hard breaks
text = text.replace(/ +\n/g, '<br />\n');
}
text = globals.converter._dispatch('spanGamut.after', text, options, globals);
return text;
});
showdown.subParser('strikethrough', function (text, options, globals) {
'use strict';
function parseInside (txt) {
if (options.simplifiedAutoLink) {
txt = showdown.subParser('simplifiedAutoLinks')(txt, options, globals);
}
return '<del>' + txt + '</del>';
}
if (options.strikethrough) {
text = globals.converter._dispatch('strikethrough.before', text, options, globals);
text = text.replace(/(?:~){2}([\s\S]+?)(?:~){2}/g, function (wm, txt) { return parseInside(txt); });
text = globals.converter._dispatch('strikethrough.after', text, options, globals);
}
return text;
});
/**
* Strips link definitions from text, stores the URLs and titles in
* hash references.
* Link defs are in the form: ^[id]: url "optional title"
*/
showdown.subParser('stripLinkDefinitions', function (text, options, globals) {
'use strict';
var regex = /^ {0,3}\[(.+)]:[ \t]*\n?[ \t]*<?([^>\s]+)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*\n?[ \t]*(?:(\n*)["|'(](.+?)["|')][ \t]*)?(?:\n+|(?=¨0))/gm,
base64Regex = /^ {0,3}\[(.+)]:[ \t]*\n?[ \t]*<?(data:.+?\/.+?;base64,[A-Za-z0-9+/=\n]+?)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*\n?[ \t]*(?:(\n*)["|'(](.+?)["|')][ \t]*)?(?:\n\n|(?=¨0)|(?=\n\[))/gm;
// attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
text += '¨0';
var replaceFunc = function (wholeMatch, linkId, url, width, height, blankLines, title) {
linkId = linkId.toLowerCase();
if (url.match(/^data:.+?\/.+?;base64,/)) {
// remove newlines
globals.gUrls[linkId] = url.replace(/\s/g, '');
} else {
globals.gUrls[linkId] = showdown.subParser('encodeAmpsAndAngles')(url, options, globals); // Link IDs are case-insensitive
}
if (blankLines) {
// Oops, found blank lines, so it's not a title.
// Put back the parenthetical statement we stole.
return blankLines + title;
} else {
if (title) {
globals.gTitles[linkId] = title.replace(/"|'/g, '"');
}
if (options.parseImgDimensions && width && height) {
globals.gDimensions[linkId] = {
width: width,
height: height
};
}
}
// Completely remove the definition from the text
return '';
};
// first we try to find base64 link references
text = text.replace(base64Regex, replaceFunc);
text = text.replace(regex, replaceFunc);
// attacklab: strip sentinel
text = text.replace(/¨0/, '');
return text;
});
showdown.subParser('tables', function (text, options, globals) {
'use strict';
if (!options.tables) {
return text;
}
var tableRgx = /^ {0,3}\|?.+\|.+\n {0,3}\|?[ \t]*:?[ \t]*(?:[-=]){2,}[ \t]*:?[ \t]*\|[ \t]*:?[ \t]*(?:[-=]){2,}[\s\S]+?(?:\n\n|¨0)/gm,
//singeColTblRgx = /^ {0,3}\|.+\|\n {0,3}\|[ \t]*:?[ \t]*(?:[-=]){2,}[ \t]*:?[ \t]*\|[ \t]*\n(?: {0,3}\|.+\|\n)+(?:\n\n|¨0)/gm;
singeColTblRgx = /^ {0,3}\|.+\|[ \t]*\n {0,3}\|[ \t]*:?[ \t]*(?:[-=]){2,}[ \t]*:?[ \t]*\|[ \t]*\n( {0,3}\|.+\|[ \t]*\n)*(?:\n|¨0)/gm;
function parseStyles (sLine) {
if (/^:[ \t]*--*$/.test(sLine)) {
return ' style="text-align:left;"';
} else if (/^--*[ \t]*:[ \t]*$/.test(sLine)) {
return ' style="text-align:right;"';
} else if (/^:[ \t]*--*[ \t]*:$/.test(sLine)) {
return ' style="text-align:center;"';
} else {
return '';
}
}
function parseHeaders (header, style) {
var id = '';
header = header.trim();
// support both tablesHeaderId and tableHeaderId due to error in documentation so we don't break backwards compatibility
if (options.tablesHeaderId || options.tableHeaderId) {
id = ' id="' + header.replace(/ /g, '_').toLowerCase() + '"';
}
header = showdown.subParser('spanGamut')(header, options, globals);
return '<th' + id + style + '>' + header + '</th>\n';
}
function parseCells (cell, style) {
var subText = showdown.subParser('spanGamut')(cell, options, globals);
return '<td' + style + '>' + subText + '</td>\n';
}
function buildTable (headers, cells) {
var tb = '<table>\n<thead>\n<tr>\n',
tblLgn = headers.length;
for (var i = 0; i < tblLgn; ++i) {
tb += headers[i];
}
tb += '</tr>\n</thead>\n<tbody>\n';
for (i = 0; i < cells.length; ++i) {
tb += '<tr>\n';
for (var ii = 0; ii < tblLgn; ++ii) {
tb += cells[i][ii];
}
tb += '</tr>\n';
}
tb += '</tbody>\n</table>\n';
return tb;
}
function parseTable (rawTable) {
var i, tableLines = rawTable.split('\n');
for (i = 0; i < tableLines.length; ++i) {
// strip wrong first and last column if wrapped tables are used
if (/^ {0,3}\|/.test(tableLines[i])) {
tableLines[i] = tableLines[i].replace(/^ {0,3}\|/, '');
}
if (/\|[ \t]*$/.test(tableLines[i])) {
tableLines[i] = tableLines[i].replace(/\|[ \t]*$/, '');
}
// parse code spans first, but we only support one line code spans
tableLines[i] = showdown.subParser('codeSpans')(tableLines[i], options, globals);
}
var rawHeaders = tableLines[0].split('|').map(function (s) { return s.trim();}),
rawStyles = tableLines[1].split('|').map(function (s) { return s.trim();}),
rawCells = [],
headers = [],
styles = [],
cells = [];
tableLines.shift();
tableLines.shift();
for (i = 0; i < tableLines.length; ++i) {
if (tableLines[i].trim() === '') {
continue;
}
rawCells.push(
tableLines[i]
.split('|')
.map(function (s) {
return s.trim();
})
);
}
if (rawHeaders.length < rawStyles.length) {
return rawTable;
}
for (i = 0; i < rawStyles.length; ++i) {
styles.push(parseStyles(rawStyles[i]));
}
for (i = 0; i < rawHeaders.length; ++i) {
if (showdown.helper.isUndefined(styles[i])) {
styles[i] = '';
}
headers.push(parseHeaders(rawHeaders[i], styles[i]));
}
for (i = 0; i < rawCells.length; ++i) {
var row = [];
for (var ii = 0; ii < headers.length; ++ii) {
if (showdown.helper.isUndefined(rawCells[i][ii])) {
}
row.push(parseCells(rawCells[i][ii], styles[ii]));
}
cells.push(row);
}
return buildTable(headers, cells);
}
text = globals.converter._dispatch('tables.before', text, options, globals);
// find escaped pipe characters
text = text.replace(/\\(\|)/g, showdown.helper.escapeCharactersCallback);
// parse multi column tables
text = text.replace(tableRgx, parseTable);
// parse one column tables
text = text.replace(singeColTblRgx, parseTable);
text = globals.converter._dispatch('tables.after', text, options, globals);
return text;
});
showdown.subParser('underline', function (text, options, globals) {
'use strict';
if (!options.underline) {
return text;
}
text = globals.converter._dispatch('underline.before', text, options, globals);
if (options.literalMidWordUnderscores) {
text = text.replace(/\b___(\S[\s\S]*?)___\b/g, function (wm, txt) {
return '<u>' + txt + '</u>';
});
text = text.replace(/\b__(\S[\s\S]*?)__\b/g, function (wm, txt) {
return '<u>' + txt + '</u>';
});
} else {
text = text.replace(/___(\S[\s\S]*?)___/g, function (wm, m) {
return (/\S$/.test(m)) ? '<u>' + m + '</u>' : wm;
});
text = text.replace(/__(\S[\s\S]*?)__/g, function (wm, m) {
return (/\S$/.test(m)) ? '<u>' + m + '</u>' : wm;
});
}
// escape remaining underscores to prevent them being parsed by italic and bold
text = text.replace(/(_)/g, showdown.helper.escapeCharactersCallback);
text = globals.converter._dispatch('underline.after', text, options, globals);
return text;
});
/**
* Swap back in all the special characters we've hidden.
*/
showdown.subParser('unescapeSpecialChars', function (text, options, globals) {
'use strict';
text = globals.converter._dispatch('unescapeSpecialChars.before', text, options, globals);
text = text.replace(/¨E(\d+)E/g, function (wholeMatch, m1) {
var charCodeToReplace = parseInt(m1);
return String.fromCharCode(charCodeToReplace);
});
text = globals.converter._dispatch('unescapeSpecialChars.after', text, options, globals);
return text;
});
showdown.subParser('makeMarkdown.blockquote', function (node, globals) {
'use strict';
var txt = '';
if (node.hasChildNodes()) {
var children = node.childNodes,
childrenLength = children.length;
for (var i = 0; i < childrenLength; ++i) {
var innerTxt = showdown.subParser('makeMarkdown.node')(children[i], globals);
if (innerTxt === '') {
continue;
}
txt += innerTxt;
}
}
// cleanup
txt = txt.trim();
txt = '> ' + txt.split('\n').join('\n> ');
return txt;
});
showdown.subParser('makeMarkdown.codeBlock', function (node, globals) {
'use strict';
var lang = node.getAttribute('language'),
num = node.getAttribute('precodenum');
return '```' + lang + '\n' + globals.preList[num] + '\n```';
});
showdown.subParser('makeMarkdown.codeSpan', function (node) {
'use strict';
return '`' + node.innerHTML + '`';
});
showdown.subParser('makeMarkdown.emphasis', function (node, globals) {
'use strict';
var txt = '';
if (node.hasChildNodes()) {
txt += '*';
var children = node.childNodes,
childrenLength = children.length;
for (var i = 0; i < childrenLength; ++i) {
txt += showdown.subParser('makeMarkdown.node')(children[i], globals);
}
txt += '*';
}
return txt;
});
showdown.subParser('makeMarkdown.header', function (node, globals, headerLevel) {
'use strict';
var headerMark = new Array(headerLevel + 1).join('#'),
txt = '';
if (node.hasChildNodes()) {
txt = headerMark + ' ';
var children = node.childNodes,
childrenLength = children.length;
for (var i = 0; i < childrenLength; ++i) {
txt += showdown.subParser('makeMarkdown.node')(children[i], globals);
}
}
return txt;
});
showdown.subParser('makeMarkdown.hr', function () {
'use strict';
return '---';
});
showdown.subParser('makeMarkdown.image', function (node) {
'use strict';
var txt = '';
if (node.hasAttribute('src')) {
txt += ' + '>';
if (node.hasAttribute('width') && node.hasAttribute('height')) {
txt += ' =' + node.getAttribute('width') + 'x' + node.getAttribute('height');
}
if (node.hasAttribute('title')) {
txt += ' "' + node.getAttribute('title') + '"';
}
txt += ')';
}
return txt;
});
showdown.subParser('makeMarkdown.links', function (node, globals) {
'use strict';
var txt = '';
if (node.hasChildNodes() && node.hasAttribute('href')) {
var children = node.childNodes,
childrenLength = children.length;
txt = '[';
for (var i = 0; i < childrenLength; ++i) {
txt += showdown.subParser('makeMarkdown.node')(children[i], globals);
}
txt += '](';
txt += '<' + node.getAttribute('href') + '>';
if (node.hasAttribute('title')) {
txt += ' "' + node.getAttribute('title') + '"';
}
txt += ')';
}
return txt;
});
showdown.subParser('makeMarkdown.list', function (node, globals, type) {
'use strict';
var txt = '';
if (!node.hasChildNodes()) {
return '';
}
var listItems = node.childNodes,
listItemsLenght = listItems.length,
listNum = node.getAttribute('start') || 1;
for (var i = 0; i < listItemsLenght; ++i) {
if (typeof listItems[i].tagName === 'undefined' || listItems[i].tagName.toLowerCase() !== 'li') {
continue;
}
// define the bullet to use in list
var bullet = '';
if (type === 'ol') {
bullet = listNum.toString() + '. ';
} else {
bullet = '- ';
}
// parse list item
txt += bullet + showdown.subParser('makeMarkdown.listItem')(listItems[i], globals);
++listNum;
}
// add comment at the end to prevent consecutive lists to be parsed as one
txt += '\n<!-- -->\n';
return txt.trim();
});
showdown.subParser('makeMarkdown.listItem', function (node, globals) {
'use strict';
var listItemTxt = '';
var children = node.childNodes,
childrenLenght = children.length;
for (var i = 0; i < childrenLenght; ++i) {
listItemTxt += showdown.subParser('makeMarkdown.node')(children[i], globals);
}
// if it's only one liner, we need to add a newline at the end
if (!/\n$/.test(listItemTxt)) {
listItemTxt += '\n';
} else {
// it's multiparagraph, so we need to indent
listItemTxt = listItemTxt
.split('\n')
.join('\n ')
.replace(/^ {4}$/gm, '')
.replace(/\n\n+/g, '\n\n');
}
return listItemTxt;
});
showdown.subParser('makeMarkdown.node', function (node, globals, spansOnly) {
'use strict';
spansOnly = spansOnly || false;
var txt = '';
// edge case of text without wrapper paragraph
if (node.nodeType === 3) {
return showdown.subParser('makeMarkdown.txt')(node, globals);
}
// HTML comment
if (node.nodeType === 8) {
return '<!--' + node.data + '-->\n\n';
}
// process only node elements
if (node.nodeType !== 1) {
return '';
}
var tagName = node.tagName.toLowerCase();
switch (tagName) {
//
// BLOCKS
//
case 'h1':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 1) + '\n\n'; }
break;
case 'h2':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 2) + '\n\n'; }
break;
case 'h3':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 3) + '\n\n'; }
break;
case 'h4':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 4) + '\n\n'; }
break;
case 'h5':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 5) + '\n\n'; }
break;
case 'h6':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.header')(node, globals, 6) + '\n\n'; }
break;
case 'p':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.paragraph')(node, globals) + '\n\n'; }
break;
case 'blockquote':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.blockquote')(node, globals) + '\n\n'; }
break;
case 'hr':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.hr')(node, globals) + '\n\n'; }
break;
case 'ol':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.list')(node, globals, 'ol') + '\n\n'; }
break;
case 'ul':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.list')(node, globals, 'ul') + '\n\n'; }
break;
case 'precode':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.codeBlock')(node, globals) + '\n\n'; }
break;
case 'pre':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.pre')(node, globals) + '\n\n'; }
break;
case 'table':
if (!spansOnly) { txt = showdown.subParser('makeMarkdown.table')(node, globals) + '\n\n'; }
break;
//
// SPANS
//
case 'code':
txt = showdown.subParser('makeMarkdown.codeSpan')(node, globals);
break;
case 'em':
case 'i':
txt = showdown.subParser('makeMarkdown.emphasis')(node, globals);
break;
case 'strong':
case 'b':
txt = showdown.subParser('makeMarkdown.strong')(node, globals);
break;
case 'del':
txt = showdown.subParser('makeMarkdown.strikethrough')(node, globals);
break;
case 'a':
txt = showdown.subParser('makeMarkdown.links')(node, globals);
break;
case 'img':
txt = showdown.subParser('makeMarkdown.image')(node, globals);
break;
default:
txt = node.outerHTML + '\n\n';
}
// common normalization
// TODO eventually
return txt;
});
showdown.subParser('makeMarkdown.paragraph', function (node, globals) {
'use strict';
var txt = '';
if (node.hasChildNodes()) {
var children = node.childNodes,
childrenLength = children.length;
for (var i = 0; i < childrenLength; ++i) {
txt += showdown.subParser('makeMarkdown.node')(children[i], globals);
}
}
// some text normalization
txt = txt.trim();
return txt;
});
showdown.subParser('makeMarkdown.pre', function (node, globals) {
'use strict';
var num = node.getAttribute('prenum');
return '<pre>' + globals.preList[num] + '</pre>';
});
showdown.subParser('makeMarkdown.strikethrough', function (node, globals) {
'use strict';
var txt = '';
if (node.hasChildNodes()) {
txt += '~~';
var children = node.childNodes,
childrenLength = children.length;
for (var i = 0; i < childrenLength; ++i) {
txt += showdown.subParser('makeMarkdown.node')(children[i], globals);
}
txt += '~~';
}
return txt;
});
showdown.subParser('makeMarkdown.strong', function (node, globals) {
'use strict';
var txt = '';
if (node.hasChildNodes()) {
txt += '**';
var children = node.childNodes,
childrenLength = children.length;
for (var i = 0; i < childrenLength; ++i) {
txt += showdown.subParser('makeMarkdown.node')(children[i], globals);
}
txt += '**';
}
return txt;
});
showdown.subParser('makeMarkdown.table', function (node, globals) {
'use strict';
var txt = '',
tableArray = [[], []],
headings = node.querySelectorAll('thead>tr>th'),
rows = node.querySelectorAll('tbody>tr'),
i, ii;
for (i = 0; i < headings.length; ++i) {
var headContent = showdown.subParser('makeMarkdown.tableCell')(headings[i], globals),
allign = '---';
if (headings[i].hasAttribute('style')) {
var style = headings[i].getAttribute('style').toLowerCase().replace(/\s/g, '');
switch (style) {
case 'text-align:left;':
allign = ':---';
break;
case 'text-align:right;':
allign = '---:';
break;
case 'text-align:center;':
allign = ':---:';
break;
}
}
tableArray[0][i] = headContent.trim();
tableArray[1][i] = allign;
}
for (i = 0; i < rows.length; ++i) {
var r = tableArray.push([]) - 1,
cols = rows[i].getElementsByTagName('td');
for (ii = 0; ii < headings.length; ++ii) {
var cellContent = ' ';
if (typeof cols[ii] !== 'undefined') {
cellContent = showdown.subParser('makeMarkdown.tableCell')(cols[ii], globals);
}
tableArray[r].push(cellContent);
}
}
var cellSpacesCount = 3;
for (i = 0; i < tableArray.length; ++i) {
for (ii = 0; ii < tableArray[i].length; ++ii) {
var strLen = tableArray[i][ii].length;
if (strLen > cellSpacesCount) {
cellSpacesCount = strLen;
}
}
}
for (i = 0; i < tableArray.length; ++i) {
for (ii = 0; ii < tableArray[i].length; ++ii) {
if (i === 1) {
if (tableArray[i][ii].slice(-1) === ':') {
tableArray[i][ii] = showdown.helper.padEnd(tableArray[i][ii].slice(-1), cellSpacesCount - 1, '-') + ':';
} else {
tableArray[i][ii] = showdown.helper.padEnd(tableArray[i][ii], cellSpacesCount, '-');
}
} else {
tableArray[i][ii] = showdown.helper.padEnd(tableArray[i][ii], cellSpacesCount);
}
}
txt += '| ' + tableArray[i].join(' | ') + ' |\n';
}
return txt.trim();
});
showdown.subParser('makeMarkdown.tableCell', function (node, globals) {
'use strict';
var txt = '';
if (!node.hasChildNodes()) {
return '';
}
var children = node.childNodes,
childrenLength = children.length;
for (var i = 0; i < childrenLength; ++i) {
txt += showdown.subParser('makeMarkdown.node')(children[i], globals, true);
}
return txt.trim();
});
showdown.subParser('makeMarkdown.txt', function (node) {
'use strict';
var txt = node.nodeValue;
// multiple spaces are collapsed
txt = txt.replace(/ +/g, ' ');
// replace the custom ¨NBSP; with a space
txt = txt.replace(/¨NBSP;/g, ' ');
// ", <, > and & should replace escaped html entities
txt = showdown.helper.unescapeHTMLEntities(txt);
// escape markdown magic characters
// emphasis, strong and strikethrough - can appear everywhere
// we also escape pipe (|) because of tables
// and escape ` because of code blocks and spans
txt = txt.replace(/([*_~|`])/g, '\\$1');
// escape > because of blockquotes
txt = txt.replace(/^(\s*)>/g, '\\$1>');
// hash character, only troublesome at the beginning of a line because of headers
txt = txt.replace(/^#/gm, '\\#');
// horizontal rules
txt = txt.replace(/^(\s*)([-=]{3,})(\s*)$/, '$1\\$2$3');
// dot, because of ordered lists, only troublesome at the beginning of a line when preceded by an integer
txt = txt.replace(/^( {0,3}\d+)\./gm, '$1\\.');
// +, * and -, at the beginning of a line becomes a list, so we need to escape them also (asterisk was already escaped)
txt = txt.replace(/^( {0,3})([+-])/gm, '$1\\$2');
// images and links, ] followed by ( is problematic, so we escape it
txt = txt.replace(/]([\s]*)\(/g, '\\]$1\\(');
// reference URIs must also be escaped
txt = txt.replace(/^ {0,3}\[([\S \t]*?)]:/gm, '\\[$1]:');
return txt;
});
var root = this;
// AMD Loader
if (true) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {
'use strict';
return showdown;
}).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
// CommonJS/nodeJS Loader
} else {}
}).call(this);
/***/ })
/******/ });
/************************************************************************/
/******/ // 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].call(module.exports, 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 in strict mode.
!function() {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"__EXPERIMENTAL_ELEMENTS": function() { return /* reexport */ __EXPERIMENTAL_ELEMENTS; },
"__EXPERIMENTAL_PATHS_WITH_MERGE": function() { return /* reexport */ __EXPERIMENTAL_PATHS_WITH_MERGE; },
"__EXPERIMENTAL_STYLE_PROPERTY": function() { return /* reexport */ __EXPERIMENTAL_STYLE_PROPERTY; },
"__experimentalCloneSanitizedBlock": function() { return /* reexport */ __experimentalCloneSanitizedBlock; },
"__experimentalGetAccessibleBlockLabel": function() { return /* reexport */ getAccessibleBlockLabel; },
"__experimentalGetBlockAttributesNamesByRole": function() { return /* reexport */ __experimentalGetBlockAttributesNamesByRole; },
"__experimentalGetBlockLabel": function() { return /* reexport */ getBlockLabel; },
"__experimentalSanitizeBlockAttributes": function() { return /* reexport */ __experimentalSanitizeBlockAttributes; },
"__unstableGetBlockProps": function() { return /* reexport */ getBlockProps; },
"__unstableGetInnerBlocksProps": function() { return /* reexport */ getInnerBlocksProps; },
"__unstableSerializeAndClean": function() { return /* reexport */ __unstableSerializeAndClean; },
"children": function() { return /* reexport */ children; },
"cloneBlock": function() { return /* reexport */ cloneBlock; },
"createBlock": function() { return /* reexport */ createBlock; },
"createBlocksFromInnerBlocksTemplate": function() { return /* reexport */ createBlocksFromInnerBlocksTemplate; },
"doBlocksMatchTemplate": function() { return /* reexport */ doBlocksMatchTemplate; },
"findTransform": function() { return /* reexport */ findTransform; },
"getBlockAttributes": function() { return /* reexport */ getBlockAttributes; },
"getBlockContent": function() { return /* reexport */ getBlockInnerHTML; },
"getBlockDefaultClassName": function() { return /* reexport */ getBlockDefaultClassName; },
"getBlockFromExample": function() { return /* reexport */ getBlockFromExample; },
"getBlockMenuDefaultClassName": function() { return /* reexport */ getBlockMenuDefaultClassName; },
"getBlockSupport": function() { return /* reexport */ getBlockSupport; },
"getBlockTransforms": function() { return /* reexport */ getBlockTransforms; },
"getBlockType": function() { return /* reexport */ getBlockType; },
"getBlockTypes": function() { return /* reexport */ getBlockTypes; },
"getBlockVariations": function() { return /* reexport */ getBlockVariations; },
"getCategories": function() { return /* reexport */ categories_getCategories; },
"getChildBlockNames": function() { return /* reexport */ getChildBlockNames; },
"getDefaultBlockName": function() { return /* reexport */ getDefaultBlockName; },
"getFreeformContentHandlerName": function() { return /* reexport */ getFreeformContentHandlerName; },
"getGroupingBlockName": function() { return /* reexport */ getGroupingBlockName; },
"getPhrasingContentSchema": function() { return /* reexport */ deprecatedGetPhrasingContentSchema; },
"getPossibleBlockTransformations": function() { return /* reexport */ getPossibleBlockTransformations; },
"getSaveContent": function() { return /* reexport */ getSaveContent; },
"getSaveElement": function() { return /* reexport */ getSaveElement; },
"getUnregisteredTypeHandlerName": function() { return /* reexport */ getUnregisteredTypeHandlerName; },
"hasBlockSupport": function() { return /* reexport */ hasBlockSupport; },
"hasChildBlocks": function() { return /* reexport */ hasChildBlocks; },
"hasChildBlocksWithInserterSupport": function() { return /* reexport */ hasChildBlocksWithInserterSupport; },
"isReusableBlock": function() { return /* reexport */ isReusableBlock; },
"isTemplatePart": function() { return /* reexport */ isTemplatePart; },
"isUnmodifiedBlock": function() { return /* reexport */ isUnmodifiedBlock; },
"isUnmodifiedDefaultBlock": function() { return /* reexport */ isUnmodifiedDefaultBlock; },
"isValidBlockContent": function() { return /* reexport */ isValidBlockContent; },
"isValidIcon": function() { return /* reexport */ isValidIcon; },
"node": function() { return /* reexport */ node; },
"normalizeIconObject": function() { return /* reexport */ normalizeIconObject; },
"parse": function() { return /* reexport */ parser_parse; },
"parseWithAttributeSchema": function() { return /* reexport */ parseWithAttributeSchema; },
"pasteHandler": function() { return /* reexport */ pasteHandler; },
"rawHandler": function() { return /* reexport */ rawHandler; },
"registerBlockCollection": function() { return /* reexport */ registerBlockCollection; },
"registerBlockStyle": function() { return /* reexport */ registerBlockStyle; },
"registerBlockType": function() { return /* reexport */ registerBlockType; },
"registerBlockVariation": function() { return /* reexport */ registerBlockVariation; },
"serialize": function() { return /* reexport */ serialize; },
"serializeRawBlock": function() { return /* reexport */ serializeRawBlock; },
"setCategories": function() { return /* reexport */ categories_setCategories; },
"setDefaultBlockName": function() { return /* reexport */ setDefaultBlockName; },
"setFreeformContentHandlerName": function() { return /* reexport */ setFreeformContentHandlerName; },
"setGroupingBlockName": function() { return /* reexport */ setGroupingBlockName; },
"setUnregisteredTypeHandlerName": function() { return /* reexport */ setUnregisteredTypeHandlerName; },
"store": function() { return /* reexport */ store; },
"switchToBlockType": function() { return /* reexport */ switchToBlockType; },
"synchronizeBlocksWithTemplate": function() { return /* reexport */ synchronizeBlocksWithTemplate; },
"unregisterBlockStyle": function() { return /* reexport */ unregisterBlockStyle; },
"unregisterBlockType": function() { return /* reexport */ unregisterBlockType; },
"unregisterBlockVariation": function() { return /* reexport */ unregisterBlockVariation; },
"unstable__bootstrapServerSideBlockDefinitions": function() { return /* reexport */ unstable__bootstrapServerSideBlockDefinitions; },
"updateCategory": function() { return /* reexport */ categories_updateCategory; },
"validateBlock": function() { return /* reexport */ validateBlock; },
"withBlockContentContext": function() { return /* reexport */ withBlockContentContext; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/blocks/build-module/store/selectors.js
var selectors_namespaceObject = {};
__webpack_require__.r(selectors_namespaceObject);
__webpack_require__.d(selectors_namespaceObject, {
"__experimentalGetUnprocessedBlockTypes": function() { return __experimentalGetUnprocessedBlockTypes; },
"__experimentalHasContentRoleAttribute": function() { return __experimentalHasContentRoleAttribute; },
"getActiveBlockVariation": function() { return getActiveBlockVariation; },
"getBlockStyles": function() { return getBlockStyles; },
"getBlockSupport": function() { return selectors_getBlockSupport; },
"getBlockType": function() { return selectors_getBlockType; },
"getBlockTypes": function() { return selectors_getBlockTypes; },
"getBlockVariations": function() { return selectors_getBlockVariations; },
"getCategories": function() { return getCategories; },
"getChildBlockNames": function() { return selectors_getChildBlockNames; },
"getCollections": function() { return getCollections; },
"getDefaultBlockName": function() { return selectors_getDefaultBlockName; },
"getDefaultBlockVariation": function() { return getDefaultBlockVariation; },
"getFreeformFallbackBlockName": function() { return getFreeformFallbackBlockName; },
"getGroupingBlockName": function() { return selectors_getGroupingBlockName; },
"getUnregisteredFallbackBlockName": function() { return getUnregisteredFallbackBlockName; },
"hasBlockSupport": function() { return selectors_hasBlockSupport; },
"hasChildBlocks": function() { return selectors_hasChildBlocks; },
"hasChildBlocksWithInserterSupport": function() { return selectors_hasChildBlocksWithInserterSupport; },
"isMatchingSearchTerm": function() { return isMatchingSearchTerm; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/blocks/build-module/store/actions.js
var actions_namespaceObject = {};
__webpack_require__.r(actions_namespaceObject);
__webpack_require__.d(actions_namespaceObject, {
"__experimentalReapplyBlockTypeFilters": function() { return __experimentalReapplyBlockTypeFilters; },
"__experimentalRegisterBlockType": function() { return __experimentalRegisterBlockType; },
"addBlockCollection": function() { return addBlockCollection; },
"addBlockStyles": function() { return addBlockStyles; },
"addBlockTypes": function() { return addBlockTypes; },
"addBlockVariations": function() { return addBlockVariations; },
"removeBlockCollection": function() { return removeBlockCollection; },
"removeBlockStyles": function() { return removeBlockStyles; },
"removeBlockTypes": function() { return removeBlockTypes; },
"removeBlockVariations": function() { return removeBlockVariations; },
"setCategories": function() { return setCategories; },
"setDefaultBlockName": function() { return actions_setDefaultBlockName; },
"setFreeformFallbackBlockName": function() { return setFreeformFallbackBlockName; },
"setGroupingBlockName": function() { return actions_setGroupingBlockName; },
"setUnregisteredFallbackBlockName": function() { return setUnregisteredFallbackBlockName; },
"updateCategory": function() { return updateCategory; }
});
;// CONCATENATED MODULE: external ["wp","data"]
var external_wp_data_namespaceObject = window["wp"]["data"];
;// CONCATENATED MODULE: external "lodash"
var external_lodash_namespaceObject = window["lodash"];
;// CONCATENATED MODULE: external ["wp","i18n"]
var external_wp_i18n_namespaceObject = window["wp"]["i18n"];
;// CONCATENATED MODULE: ./node_modules/colord/index.mjs
var r={grad:.9,turn:360,rad:360/(2*Math.PI)},t=function(r){return"string"==typeof r?r.length>0:"number"==typeof r},n=function(r,t,n){return void 0===t&&(t=0),void 0===n&&(n=Math.pow(10,t)),Math.round(n*r)/n+0},e=function(r,t,n){return void 0===t&&(t=0),void 0===n&&(n=1),r>n?n:r>t?r:t},u=function(r){return(r=isFinite(r)?r%360:0)>0?r:r+360},a=function(r){return{r:e(r.r,0,255),g:e(r.g,0,255),b:e(r.b,0,255),a:e(r.a)}},o=function(r){return{r:n(r.r),g:n(r.g),b:n(r.b),a:n(r.a,3)}},i=/^#([0-9a-f]{3,8})$/i,s=function(r){var t=r.toString(16);return t.length<2?"0"+t:t},h=function(r){var t=r.r,n=r.g,e=r.b,u=r.a,a=Math.max(t,n,e),o=a-Math.min(t,n,e),i=o?a===t?(n-e)/o:a===n?2+(e-t)/o:4+(t-n)/o:0;return{h:60*(i<0?i+6:i),s:a?o/a*100:0,v:a/255*100,a:u}},b=function(r){var t=r.h,n=r.s,e=r.v,u=r.a;t=t/360*6,n/=100,e/=100;var a=Math.floor(t),o=e*(1-n),i=e*(1-(t-a)*n),s=e*(1-(1-t+a)*n),h=a%6;return{r:255*[e,i,o,o,s,e][h],g:255*[s,e,e,i,o,o][h],b:255*[o,o,s,e,e,i][h],a:u}},g=function(r){return{h:u(r.h),s:e(r.s,0,100),l:e(r.l,0,100),a:e(r.a)}},d=function(r){return{h:n(r.h),s:n(r.s),l:n(r.l),a:n(r.a,3)}},f=function(r){return b((n=(t=r).s,{h:t.h,s:(n*=((e=t.l)<50?e:100-e)/100)>0?2*n/(e+n)*100:0,v:e+n,a:t.a}));var t,n,e},c=function(r){return{h:(t=h(r)).h,s:(u=(200-(n=t.s))*(e=t.v)/100)>0&&u<200?n*e/100/(u<=100?u:200-u)*100:0,l:u/2,a:t.a};var t,n,e,u},l=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,p=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,v=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,m=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,y={string:[[function(r){var t=i.exec(r);return t?(r=t[1]).length<=4?{r:parseInt(r[0]+r[0],16),g:parseInt(r[1]+r[1],16),b:parseInt(r[2]+r[2],16),a:4===r.length?n(parseInt(r[3]+r[3],16)/255,2):1}:6===r.length||8===r.length?{r:parseInt(r.substr(0,2),16),g:parseInt(r.substr(2,2),16),b:parseInt(r.substr(4,2),16),a:8===r.length?n(parseInt(r.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(r){var t=v.exec(r)||m.exec(r);return t?t[2]!==t[4]||t[4]!==t[6]?null:a({r:Number(t[1])/(t[2]?100/255:1),g:Number(t[3])/(t[4]?100/255:1),b:Number(t[5])/(t[6]?100/255:1),a:void 0===t[7]?1:Number(t[7])/(t[8]?100:1)}):null},"rgb"],[function(t){var n=l.exec(t)||p.exec(t);if(!n)return null;var e,u,a=g({h:(e=n[1],u=n[2],void 0===u&&(u="deg"),Number(e)*(r[u]||1)),s:Number(n[3]),l:Number(n[4]),a:void 0===n[5]?1:Number(n[5])/(n[6]?100:1)});return f(a)},"hsl"]],object:[[function(r){var n=r.r,e=r.g,u=r.b,o=r.a,i=void 0===o?1:o;return t(n)&&t(e)&&t(u)?a({r:Number(n),g:Number(e),b:Number(u),a:Number(i)}):null},"rgb"],[function(r){var n=r.h,e=r.s,u=r.l,a=r.a,o=void 0===a?1:a;if(!t(n)||!t(e)||!t(u))return null;var i=g({h:Number(n),s:Number(e),l:Number(u),a:Number(o)});return f(i)},"hsl"],[function(r){var n=r.h,a=r.s,o=r.v,i=r.a,s=void 0===i?1:i;if(!t(n)||!t(a)||!t(o))return null;var h=function(r){return{h:u(r.h),s:e(r.s,0,100),v:e(r.v,0,100),a:e(r.a)}}({h:Number(n),s:Number(a),v:Number(o),a:Number(s)});return b(h)},"hsv"]]},N=function(r,t){for(var n=0;n<t.length;n++){var e=t[n][0](r);if(e)return[e,t[n][1]]}return[null,void 0]},x=function(r){return"string"==typeof r?N(r.trim(),y.string):"object"==typeof r&&null!==r?N(r,y.object):[null,void 0]},I=function(r){return x(r)[1]},M=function(r,t){var n=c(r);return{h:n.h,s:e(n.s+100*t,0,100),l:n.l,a:n.a}},H=function(r){return(299*r.r+587*r.g+114*r.b)/1e3/255},$=function(r,t){var n=c(r);return{h:n.h,s:n.s,l:e(n.l+100*t,0,100),a:n.a}},j=function(){function r(r){this.parsed=x(r)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return r.prototype.isValid=function(){return null!==this.parsed},r.prototype.brightness=function(){return n(H(this.rgba),2)},r.prototype.isDark=function(){return H(this.rgba)<.5},r.prototype.isLight=function(){return H(this.rgba)>=.5},r.prototype.toHex=function(){return r=o(this.rgba),t=r.r,e=r.g,u=r.b,i=(a=r.a)<1?s(n(255*a)):"","#"+s(t)+s(e)+s(u)+i;var r,t,e,u,a,i},r.prototype.toRgb=function(){return o(this.rgba)},r.prototype.toRgbString=function(){return r=o(this.rgba),t=r.r,n=r.g,e=r.b,(u=r.a)<1?"rgba("+t+", "+n+", "+e+", "+u+")":"rgb("+t+", "+n+", "+e+")";var r,t,n,e,u},r.prototype.toHsl=function(){return d(c(this.rgba))},r.prototype.toHslString=function(){return r=d(c(this.rgba)),t=r.h,n=r.s,e=r.l,(u=r.a)<1?"hsla("+t+", "+n+"%, "+e+"%, "+u+")":"hsl("+t+", "+n+"%, "+e+"%)";var r,t,n,e,u},r.prototype.toHsv=function(){return r=h(this.rgba),{h:n(r.h),s:n(r.s),v:n(r.v),a:n(r.a,3)};var r},r.prototype.invert=function(){return w({r:255-(r=this.rgba).r,g:255-r.g,b:255-r.b,a:r.a});var r},r.prototype.saturate=function(r){return void 0===r&&(r=.1),w(M(this.rgba,r))},r.prototype.desaturate=function(r){return void 0===r&&(r=.1),w(M(this.rgba,-r))},r.prototype.grayscale=function(){return w(M(this.rgba,-1))},r.prototype.lighten=function(r){return void 0===r&&(r=.1),w($(this.rgba,r))},r.prototype.darken=function(r){return void 0===r&&(r=.1),w($(this.rgba,-r))},r.prototype.rotate=function(r){return void 0===r&&(r=15),this.hue(this.hue()+r)},r.prototype.alpha=function(r){return"number"==typeof r?w({r:(t=this.rgba).r,g:t.g,b:t.b,a:r}):n(this.rgba.a,3);var t},r.prototype.hue=function(r){var t=c(this.rgba);return"number"==typeof r?w({h:r,s:t.s,l:t.l,a:t.a}):n(t.h)},r.prototype.isEqual=function(r){return this.toHex()===w(r).toHex()},r}(),w=function(r){return r instanceof j?r:new j(r)},S=[],k=function(r){r.forEach(function(r){S.indexOf(r)<0&&(r(j,y),S.push(r))})},E=function(){return new j({r:255*Math.random(),g:255*Math.random(),b:255*Math.random()})};
;// CONCATENATED MODULE: ./node_modules/colord/plugins/names.mjs
/* harmony default export */ function names(e,f){var a={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},r={};for(var d in a)r[a[d]]=d;var l={};e.prototype.toName=function(f){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var d,i,n=r[this.toHex()];if(n)return n;if(null==f?void 0:f.closest){var o=this.toRgb(),t=1/0,b="black";if(!l.length)for(var c in a)l[c]=new e(a[c]).toRgb();for(var g in a){var u=(d=o,i=l[g],Math.pow(d.r-i.r,2)+Math.pow(d.g-i.g,2)+Math.pow(d.b-i.b,2));u<t&&(t=u,b=g)}return b}};f.string.push([function(f){var r=f.toLowerCase(),d="transparent"===r?"#0000":a[r];return d?new e(d).toRgb():null},"name"])}
;// CONCATENATED MODULE: ./node_modules/colord/plugins/a11y.mjs
var a11y_o=function(o){var t=o/255;return t<.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)},a11y_t=function(t){return.2126*a11y_o(t.r)+.7152*a11y_o(t.g)+.0722*a11y_o(t.b)};/* harmony default export */ function a11y(o){o.prototype.luminance=function(){return o=a11y_t(this.rgba),void 0===(r=2)&&(r=0),void 0===n&&(n=Math.pow(10,r)),Math.round(n*o)/n+0;var o,r,n},o.prototype.contrast=function(r){void 0===r&&(r="#FFF");var n,a,i,e,v,u,d,c=r instanceof o?r:new o(r);return e=this.rgba,v=c.toRgb(),u=a11y_t(e),d=a11y_t(v),n=u>d?(u+.05)/(d+.05):(d+.05)/(u+.05),void 0===(a=2)&&(a=0),void 0===i&&(i=Math.pow(10,a)),Math.floor(i*n)/i+0},o.prototype.isReadable=function(o,t){return void 0===o&&(o="#FFF"),void 0===t&&(t={}),this.contrast(o)>=(e=void 0===(i=(r=t).size)?"normal":i,"AAA"===(a=void 0===(n=r.level)?"AA":n)&&"normal"===e?7:"AA"===a&&"large"===e?3:4.5);var r,n,a,i,e}}
;// CONCATENATED MODULE: external ["wp","element"]
var external_wp_element_namespaceObject = window["wp"]["element"];
;// CONCATENATED MODULE: external ["wp","dom"]
var external_wp_dom_namespaceObject = window["wp"]["dom"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/constants.js
const BLOCK_ICON_DEFAULT = 'block-default';
/**
* Array of valid keys in a block type settings deprecation object.
*
* @type {string[]}
*/
const DEPRECATED_ENTRY_KEYS = ['attributes', 'supports', 'save', 'migrate', 'isEligible', 'apiVersion'];
const __EXPERIMENTAL_STYLE_PROPERTY = {
// Kept for back-compatibility purposes.
'--wp--style--color--link': {
value: ['color', 'link'],
support: ['color', 'link']
},
background: {
value: ['color', 'gradient'],
support: ['color', 'gradients'],
useEngine: true
},
backgroundColor: {
value: ['color', 'background'],
support: ['color', 'background'],
requiresOptOut: true,
useEngine: true
},
borderColor: {
value: ['border', 'color'],
support: ['__experimentalBorder', 'color'],
useEngine: true
},
borderRadius: {
value: ['border', 'radius'],
support: ['__experimentalBorder', 'radius'],
properties: {
borderTopLeftRadius: 'topLeft',
borderTopRightRadius: 'topRight',
borderBottomLeftRadius: 'bottomLeft',
borderBottomRightRadius: 'bottomRight'
},
useEngine: true
},
borderStyle: {
value: ['border', 'style'],
support: ['__experimentalBorder', 'style'],
useEngine: true
},
borderWidth: {
value: ['border', 'width'],
support: ['__experimentalBorder', 'width'],
useEngine: true
},
borderTopColor: {
value: ['border', 'top', 'color'],
support: ['__experimentalBorder', 'color'],
useEngine: true
},
borderTopStyle: {
value: ['border', 'top', 'style'],
support: ['__experimentalBorder', 'style'],
useEngine: true
},
borderTopWidth: {
value: ['border', 'top', 'width'],
support: ['__experimentalBorder', 'width'],
useEngine: true
},
borderRightColor: {
value: ['border', 'right', 'color'],
support: ['__experimentalBorder', 'color'],
useEngine: true
},
borderRightStyle: {
value: ['border', 'right', 'style'],
support: ['__experimentalBorder', 'style'],
useEngine: true
},
borderRightWidth: {
value: ['border', 'right', 'width'],
support: ['__experimentalBorder', 'width'],
useEngine: true
},
borderBottomColor: {
value: ['border', 'bottom', 'color'],
support: ['__experimentalBorder', 'color'],
useEngine: true
},
borderBottomStyle: {
value: ['border', 'bottom', 'style'],
support: ['__experimentalBorder', 'style'],
useEngine: true
},
borderBottomWidth: {
value: ['border', 'bottom', 'width'],
support: ['__experimentalBorder', 'width'],
useEngine: true
},
borderLeftColor: {
value: ['border', 'left', 'color'],
support: ['__experimentalBorder', 'color'],
useEngine: true
},
borderLeftStyle: {
value: ['border', 'left', 'style'],
support: ['__experimentalBorder', 'style'],
useEngine: true
},
borderLeftWidth: {
value: ['border', 'left', 'width'],
support: ['__experimentalBorder', 'width'],
useEngine: true
},
color: {
value: ['color', 'text'],
support: ['color', 'text'],
requiresOptOut: true,
useEngine: true
},
filter: {
value: ['filter', 'duotone'],
support: ['color', '__experimentalDuotone']
},
linkColor: {
value: ['elements', 'link', 'color', 'text'],
support: ['color', 'link']
},
buttonColor: {
value: ['elements', 'button', 'color', 'text'],
support: ['color', 'button']
},
buttonBackgroundColor: {
value: ['elements', 'button', 'color', 'background'],
support: ['color', 'button']
},
fontFamily: {
value: ['typography', 'fontFamily'],
support: ['typography', '__experimentalFontFamily'],
useEngine: true
},
fontSize: {
value: ['typography', 'fontSize'],
support: ['typography', 'fontSize'],
useEngine: true
},
fontStyle: {
value: ['typography', 'fontStyle'],
support: ['typography', '__experimentalFontStyle'],
useEngine: true
},
fontWeight: {
value: ['typography', 'fontWeight'],
support: ['typography', '__experimentalFontWeight'],
useEngine: true
},
lineHeight: {
value: ['typography', 'lineHeight'],
support: ['typography', 'lineHeight'],
useEngine: true
},
margin: {
value: ['spacing', 'margin'],
support: ['spacing', 'margin'],
properties: {
marginTop: 'top',
marginRight: 'right',
marginBottom: 'bottom',
marginLeft: 'left'
},
useEngine: true
},
minHeight: {
value: ['dimensions', 'minHeight'],
support: ['dimensions', 'minHeight'],
useEngine: true
},
padding: {
value: ['spacing', 'padding'],
support: ['spacing', 'padding'],
properties: {
paddingTop: 'top',
paddingRight: 'right',
paddingBottom: 'bottom',
paddingLeft: 'left'
},
useEngine: true
},
textDecoration: {
value: ['typography', 'textDecoration'],
support: ['typography', '__experimentalTextDecoration'],
useEngine: true
},
textTransform: {
value: ['typography', 'textTransform'],
support: ['typography', '__experimentalTextTransform'],
useEngine: true
},
letterSpacing: {
value: ['typography', 'letterSpacing'],
support: ['typography', '__experimentalLetterSpacing'],
useEngine: true
},
'--wp--style--root--padding': {
value: ['spacing', 'padding'],
support: ['spacing', 'padding'],
properties: {
'--wp--style--root--padding-top': 'top',
'--wp--style--root--padding-right': 'right',
'--wp--style--root--padding-bottom': 'bottom',
'--wp--style--root--padding-left': 'left'
},
rootOnly: true
}
};
const __EXPERIMENTAL_ELEMENTS = {
link: 'a',
heading: 'h1, h2, h3, h4, h5, h6',
h1: 'h1',
h2: 'h2',
h3: 'h3',
h4: 'h4',
h5: 'h5',
h6: 'h6',
button: '.wp-element-button, .wp-block-button__link',
caption: '.wp-element-caption, .wp-block-audio figcaption, .wp-block-embed figcaption, .wp-block-gallery figcaption, .wp-block-image figcaption, .wp-block-table figcaption, .wp-block-video figcaption',
cite: 'cite'
};
const __EXPERIMENTAL_PATHS_WITH_MERGE = {
'color.duotone': true,
'color.gradients': true,
'color.palette': true,
'typography.fontFamilies': true,
'typography.fontSizes': true,
'spacing.spacingSizes': true
};
;// CONCATENATED MODULE: ./node_modules/tslib/tslib.es6.js
/*! *****************************************************************************
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 */
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 __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 (_) 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;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (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: n === "return" } : 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;
}
;// 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/pascal-case/dist.es2015/index.js
function pascalCaseTransform(input, index) {
var firstChar = input.charAt(0);
var lowerChars = input.substr(1).toLowerCase();
if (index > 0 && firstChar >= "0" && firstChar <= "9") {
return "_" + firstChar + lowerChars;
}
return "" + firstChar.toUpperCase() + lowerChars;
}
function dist_es2015_pascalCaseTransformMerge(input) {
return input.charAt(0).toUpperCase() + input.slice(1).toLowerCase();
}
function pascalCase(input, options) {
if (options === void 0) { options = {}; }
return noCase(input, __assign({ delimiter: "", transform: pascalCaseTransform }, options));
}
;// CONCATENATED MODULE: ./node_modules/camel-case/dist.es2015/index.js
function camelCaseTransform(input, index) {
if (index === 0)
return input.toLowerCase();
return pascalCaseTransform(input, index);
}
function camelCaseTransformMerge(input, index) {
if (index === 0)
return input.toLowerCase();
return pascalCaseTransformMerge(input);
}
function camelCase(input, options) {
if (options === void 0) { options = {}; }
return pascalCase(input, __assign({ transform: camelCaseTransform }, options));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/registration.js
/* eslint no-console: [ 'error', { allow: [ 'error', 'warn' ] } ] */
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const i18nBlockSchema = {
title: "block title",
description: "block description",
keywords: ["block keyword"],
styles: [{
label: "block style label"
}],
variations: [{
title: "block variation title",
description: "block variation description",
keywords: ["block variation keyword"]
}]
};
/**
* An icon type definition. One of a Dashicon slug, an element,
* or a component.
*
* @typedef {(string|WPElement|WPComponent)} WPIcon
*
* @see https://developer.wordpress.org/resource/dashicons/
*/
/**
* Render behavior of a block type icon; one of a Dashicon slug, an element,
* or a component.
*
* @typedef {WPIcon} WPBlockTypeIconRender
*/
/**
* An object describing a normalized block type icon.
*
* @typedef {Object} WPBlockTypeIconDescriptor
*
* @property {WPBlockTypeIconRender} src Render behavior of the icon,
* one of a Dashicon slug, an
* element, or a component.
* @property {string} background Optimal background hex string
* color when displaying icon.
* @property {string} foreground Optimal foreground hex string
* color when displaying icon.
* @property {string} shadowColor Optimal shadow hex string
* color when displaying icon.
*/
/**
* Value to use to render the icon for a block type in an editor interface,
* either a Dashicon slug, an element, a component, or an object describing
* the icon.
*
* @typedef {(WPBlockTypeIconDescriptor|WPBlockTypeIconRender)} WPBlockTypeIcon
*/
/**
* Named block variation scopes.
*
* @typedef {'block'|'inserter'|'transform'} WPBlockVariationScope
*/
/**
* An object describing a variation defined for the block type.
*
* @typedef {Object} WPBlockVariation
*
* @property {string} name The unique and machine-readable name.
* @property {string} title A human-readable variation title.
* @property {string} [description] A detailed variation description.
* @property {string} [category] Block type category classification,
* used in search interfaces to arrange
* block types by category.
* @property {WPIcon} [icon] An icon helping to visualize the variation.
* @property {boolean} [isDefault] Indicates whether the current variation is
* the default one. Defaults to `false`.
* @property {Object} [attributes] Values which override block attributes.
* @property {Array[]} [innerBlocks] Initial configuration of nested blocks.
* @property {Object} [example] Example provides structured data for
* the block preview. You can set to
* `undefined` to disable the preview shown
* for the block type.
* @property {WPBlockVariationScope[]} [scope] The list of scopes where the variation
* is applicable. When not provided, it
* assumes all available scopes.
* @property {string[]} [keywords] An array of terms (which can be translated)
* that help users discover the variation
* while searching.
* @property {Function|string[]} [isActive] This can be a function or an array of block attributes.
* Function that accepts a block's attributes and the
* variation's attributes and determines if a variation is active.
* This function doesn't try to find a match dynamically based
* on all block's attributes, as in many cases some attributes are irrelevant.
* An example would be for `embed` block where we only care
* about `providerNameSlug` attribute's value.
* We can also use a `string[]` to tell which attributes
* should be compared as a shorthand. Each attributes will
* be matched and the variation will be active if all of them are matching.
*/
/**
* Defined behavior of a block type.
*
* @typedef {Object} WPBlockType
*
* @property {string} name Block type's namespaced name.
* @property {string} title Human-readable block type label.
* @property {string} [description] A detailed block type description.
* @property {string} [category] Block type category classification,
* used in search interfaces to arrange
* block types by category.
* @property {WPBlockTypeIcon} [icon] Block type icon.
* @property {string[]} [keywords] Additional keywords to produce block
* type as result in search interfaces.
* @property {Object} [attributes] Block type attributes.
* @property {WPComponent} [save] Optional component describing
* serialized markup structure of a
* block type.
* @property {WPComponent} edit Component rendering an element to
* manipulate the attributes of a block
* in the context of an editor.
* @property {WPBlockVariation[]} [variations] The list of block variations.
* @property {Object} [example] Example provides structured data for
* the block preview. When not defined
* then no preview is shown.
*/
const serverSideBlockDefinitions = {};
function isObject(object) {
return object !== null && typeof object === 'object';
}
/**
* Sets the server side block definition of blocks.
*
* @param {Object} definitions Server-side block definitions
*/
// eslint-disable-next-line camelcase
function unstable__bootstrapServerSideBlockDefinitions(definitions) {
for (const blockName of Object.keys(definitions)) {
// Don't overwrite if already set. It covers the case when metadata
// was initialized from the server.
if (serverSideBlockDefinitions[blockName]) {
// We still need to polyfill `apiVersion` for WordPress version
// lower than 5.7. If it isn't present in the definition shared
// from the server, we try to fallback to the definition passed.
// @see https://github.com/WordPress/gutenberg/pull/29279
if (serverSideBlockDefinitions[blockName].apiVersion === undefined && definitions[blockName].apiVersion) {
serverSideBlockDefinitions[blockName].apiVersion = definitions[blockName].apiVersion;
} // The `ancestor` prop is not included in the definitions shared
// from the server yet, so it needs to be polyfilled as well.
// @see https://github.com/WordPress/gutenberg/pull/39894
if (serverSideBlockDefinitions[blockName].ancestor === undefined && definitions[blockName].ancestor) {
serverSideBlockDefinitions[blockName].ancestor = definitions[blockName].ancestor;
}
continue;
}
serverSideBlockDefinitions[blockName] = Object.fromEntries(Object.entries(definitions[blockName]).filter(_ref => {
let [, value] = _ref;
return value !== null && value !== undefined;
}).map(_ref2 => {
let [key, value] = _ref2;
return [camelCase(key), value];
}));
}
}
/**
* Gets block settings from metadata loaded from `block.json` file.
*
* @param {Object} metadata Block metadata loaded from `block.json`.
* @param {string} metadata.textdomain Textdomain to use with translations.
*
* @return {Object} Block settings.
*/
function getBlockSettingsFromMetadata(_ref3) {
let {
textdomain,
...metadata
} = _ref3;
const allowedFields = ['apiVersion', 'title', 'category', 'parent', 'ancestor', 'icon', 'description', 'keywords', 'attributes', 'providesContext', 'usesContext', 'supports', 'styles', 'example', 'variations'];
const settings = Object.fromEntries(Object.entries(metadata).filter(_ref4 => {
let [key] = _ref4;
return allowedFields.includes(key);
}));
if (textdomain) {
Object.keys(i18nBlockSchema).forEach(key => {
if (!settings[key]) {
return;
}
settings[key] = translateBlockSettingUsingI18nSchema(i18nBlockSchema[key], settings[key], textdomain);
});
}
return settings;
}
/**
* Registers a new block provided a unique name and an object defining its
* behavior. Once registered, the block is made available as an option to any
* editor interface where blocks are implemented.
*
* For more in-depth information on registering a custom block see the [Create a block tutorial](docs/how-to-guides/block-tutorial/README.md)
*
* @param {string|Object} blockNameOrMetadata Block type name or its metadata.
* @param {Object} settings Block settings.
*
* @example
* ```js
* import { __ } from '@wordpress/i18n';
* import { registerBlockType } from '@wordpress/blocks'
*
* registerBlockType( 'namespace/block-name', {
* title: __( 'My First Block' ),
* edit: () => <div>{ __( 'Hello from the editor!' ) }</div>,
* save: () => <div>Hello from the saved content!</div>,
* } );
* ```
*
* @return {WPBlockType | undefined} The block, if it has been successfully registered;
* otherwise `undefined`.
*/
function registerBlockType(blockNameOrMetadata, settings) {
const name = isObject(blockNameOrMetadata) ? blockNameOrMetadata.name : blockNameOrMetadata;
if (typeof name !== 'string') {
console.error('Block names must be strings.');
return;
}
if (!/^[a-z][a-z0-9-]*\/[a-z][a-z0-9-]*$/.test(name)) {
console.error('Block names must contain a namespace prefix, include only lowercase alphanumeric characters or dashes, and start with a letter. Example: my-plugin/my-custom-block');
return;
}
if ((0,external_wp_data_namespaceObject.select)(store).getBlockType(name)) {
console.error('Block "' + name + '" is already registered.');
return;
}
if (isObject(blockNameOrMetadata)) {
unstable__bootstrapServerSideBlockDefinitions({
[name]: getBlockSettingsFromMetadata(blockNameOrMetadata)
});
}
const blockType = {
name,
icon: BLOCK_ICON_DEFAULT,
keywords: [],
attributes: {},
providesContext: {},
usesContext: [],
supports: {},
styles: [],
variations: [],
save: () => null,
...(serverSideBlockDefinitions === null || serverSideBlockDefinitions === void 0 ? void 0 : serverSideBlockDefinitions[name]),
...settings
};
(0,external_wp_data_namespaceObject.dispatch)(store).__experimentalRegisterBlockType(blockType);
return (0,external_wp_data_namespaceObject.select)(store).getBlockType(name);
}
/**
* Translates block settings provided with metadata using the i18n schema.
*
* @param {string|string[]|Object[]} i18nSchema I18n schema for the block setting.
* @param {string|string[]|Object[]} settingValue Value for the block setting.
* @param {string} textdomain Textdomain to use with translations.
*
* @return {string|string[]|Object[]} Translated setting.
*/
function translateBlockSettingUsingI18nSchema(i18nSchema, settingValue, textdomain) {
if (typeof i18nSchema === 'string' && typeof settingValue === 'string') {
// eslint-disable-next-line @wordpress/i18n-no-variables, @wordpress/i18n-text-domain
return (0,external_wp_i18n_namespaceObject._x)(settingValue, i18nSchema, textdomain);
}
if (Array.isArray(i18nSchema) && i18nSchema.length && Array.isArray(settingValue)) {
return settingValue.map(value => translateBlockSettingUsingI18nSchema(i18nSchema[0], value, textdomain));
}
if (isObject(i18nSchema) && Object.entries(i18nSchema).length && isObject(settingValue)) {
return Object.keys(settingValue).reduce((accumulator, key) => {
if (!i18nSchema[key]) {
accumulator[key] = settingValue[key];
return accumulator;
}
accumulator[key] = translateBlockSettingUsingI18nSchema(i18nSchema[key], settingValue[key], textdomain);
return accumulator;
}, {});
}
return settingValue;
}
/**
* Registers a new block collection to group blocks in the same namespace in the inserter.
*
* @param {string} namespace The namespace to group blocks by in the inserter; corresponds to the block namespace.
* @param {Object} settings The block collection settings.
* @param {string} settings.title The title to display in the block inserter.
* @param {Object} [settings.icon] The icon to display in the block inserter.
*
* @example
* ```js
* import { __ } from '@wordpress/i18n';
* import { registerBlockCollection, registerBlockType } from '@wordpress/blocks';
*
* // Register the collection.
* registerBlockCollection( 'my-collection', {
* title: __( 'Custom Collection' ),
* } );
*
* // Register a block in the same namespace to add it to the collection.
* registerBlockType( 'my-collection/block-name', {
* title: __( 'My First Block' ),
* edit: () => <div>{ __( 'Hello from the editor!' ) }</div>,
* save: () => <div>'Hello from the saved content!</div>,
* } );
* ```
*/
function registerBlockCollection(namespace, _ref5) {
let {
title,
icon
} = _ref5;
(0,external_wp_data_namespaceObject.dispatch)(store).addBlockCollection(namespace, title, icon);
}
/**
* Unregisters a block collection
*
* @param {string} namespace The namespace to group blocks by in the inserter; corresponds to the block namespace
*
* @example
* ```js
* import { unregisterBlockCollection } from '@wordpress/blocks';
*
* unregisterBlockCollection( 'my-collection' );
* ```
*/
function unregisterBlockCollection(namespace) {
dispatch(blocksStore).removeBlockCollection(namespace);
}
/**
* Unregisters a block.
*
* @param {string} name Block name.
*
* @example
* ```js
* import { __ } from '@wordpress/i18n';
* import { unregisterBlockType } from '@wordpress/blocks';
*
* const ExampleComponent = () => {
* return (
* <Button
* onClick={ () =>
* unregisterBlockType( 'my-collection/block-name' )
* }
* >
* { __( 'Unregister my custom block.' ) }
* </Button>
* );
* };
* ```
*
* @return {WPBlockType | undefined} The previous block value, if it has been successfully
* unregistered; otherwise `undefined`.
*/
function unregisterBlockType(name) {
const oldBlock = (0,external_wp_data_namespaceObject.select)(store).getBlockType(name);
if (!oldBlock) {
console.error('Block "' + name + '" is not registered.');
return;
}
(0,external_wp_data_namespaceObject.dispatch)(store).removeBlockTypes(name);
return oldBlock;
}
/**
* Assigns name of block for handling non-block content.
*
* @param {string} blockName Block name.
*/
function setFreeformContentHandlerName(blockName) {
(0,external_wp_data_namespaceObject.dispatch)(store).setFreeformFallbackBlockName(blockName);
}
/**
* Retrieves name of block handling non-block content, or undefined if no
* handler has been defined.
*
* @return {?string} Block name.
*/
function getFreeformContentHandlerName() {
return (0,external_wp_data_namespaceObject.select)(store).getFreeformFallbackBlockName();
}
/**
* Retrieves name of block used for handling grouping interactions.
*
* @return {?string} Block name.
*/
function getGroupingBlockName() {
return (0,external_wp_data_namespaceObject.select)(store).getGroupingBlockName();
}
/**
* Assigns name of block handling unregistered block types.
*
* @param {string} blockName Block name.
*/
function setUnregisteredTypeHandlerName(blockName) {
(0,external_wp_data_namespaceObject.dispatch)(store).setUnregisteredFallbackBlockName(blockName);
}
/**
* Retrieves name of block handling unregistered block types, or undefined if no
* handler has been defined.
*
* @return {?string} Block name.
*/
function getUnregisteredTypeHandlerName() {
return (0,external_wp_data_namespaceObject.select)(store).getUnregisteredFallbackBlockName();
}
/**
* Assigns the default block name.
*
* @param {string} name Block name.
*
* @example
* ```js
* import { setDefaultBlockName } from '@wordpress/blocks';
*
* const ExampleComponent = () => {
*
* return (
* <Button onClick={ () => setDefaultBlockName( 'core/heading' ) }>
* { __( 'Set the default block to Heading' ) }
* </Button>
* );
* };
* ```
*/
function setDefaultBlockName(name) {
(0,external_wp_data_namespaceObject.dispatch)(store).setDefaultBlockName(name);
}
/**
* Assigns name of block for handling block grouping interactions.
*
* @param {string} name Block name.
*
* @example
* ```js
* import { setGroupingBlockName } from '@wordpress/blocks';
*
* const ExampleComponent = () => {
*
* return (
* <Button onClick={ () => setGroupingBlockName( 'core/columns' ) }>
* { __( 'Set the default block to Heading' ) }
* </Button>
* );
* };
* ```
*/
function setGroupingBlockName(name) {
(0,external_wp_data_namespaceObject.dispatch)(store).setGroupingBlockName(name);
}
/**
* Retrieves the default block name.
*
* @return {?string} Block name.
*/
function getDefaultBlockName() {
return (0,external_wp_data_namespaceObject.select)(store).getDefaultBlockName();
}
/**
* Returns a registered block type.
*
* @param {string} name Block name.
*
* @return {?Object} Block type.
*/
function getBlockType(name) {
var _select;
return (_select = (0,external_wp_data_namespaceObject.select)(store)) === null || _select === void 0 ? void 0 : _select.getBlockType(name);
}
/**
* Returns all registered blocks.
*
* @return {Array} Block settings.
*/
function getBlockTypes() {
return (0,external_wp_data_namespaceObject.select)(store).getBlockTypes();
}
/**
* Returns the block support value for a feature, if defined.
*
* @param {(string|Object)} nameOrType Block name or type object
* @param {string} feature Feature to retrieve
* @param {*} defaultSupports Default value to return if not
* explicitly defined
*
* @return {?*} Block support value
*/
function getBlockSupport(nameOrType, feature, defaultSupports) {
return (0,external_wp_data_namespaceObject.select)(store).getBlockSupport(nameOrType, feature, defaultSupports);
}
/**
* Returns true if the block defines support for a feature, or false otherwise.
*
* @param {(string|Object)} nameOrType Block name or type object.
* @param {string} feature Feature to test.
* @param {boolean} defaultSupports Whether feature is supported by
* default if not explicitly defined.
*
* @return {boolean} Whether block supports feature.
*/
function hasBlockSupport(nameOrType, feature, defaultSupports) {
return (0,external_wp_data_namespaceObject.select)(store).hasBlockSupport(nameOrType, feature, defaultSupports);
}
/**
* Determines whether or not the given block is a reusable block. This is a
* special block type that is used to point to a global block stored via the
* API.
*
* @param {Object} blockOrType Block or Block Type to test.
*
* @return {boolean} Whether the given block is a reusable block.
*/
function isReusableBlock(blockOrType) {
return (blockOrType === null || blockOrType === void 0 ? void 0 : blockOrType.name) === 'core/block';
}
/**
* Determines whether or not the given block is a template part. This is a
* special block type that allows composing a page template out of reusable
* design elements.
*
* @param {Object} blockOrType Block or Block Type to test.
*
* @return {boolean} Whether the given block is a template part.
*/
function isTemplatePart(blockOrType) {
return (blockOrType === null || blockOrType === void 0 ? void 0 : blockOrType.name) === 'core/template-part';
}
/**
* Returns an array with the child blocks of a given block.
*
* @param {string} blockName Name of block (example: “latest-posts”).
*
* @return {Array} Array of child block names.
*/
const getChildBlockNames = blockName => {
return (0,external_wp_data_namespaceObject.select)(store).getChildBlockNames(blockName);
};
/**
* Returns a boolean indicating if a block has child blocks or not.
*
* @param {string} blockName Name of block (example: “latest-posts”).
*
* @return {boolean} True if a block contains child blocks and false otherwise.
*/
const hasChildBlocks = blockName => {
return (0,external_wp_data_namespaceObject.select)(store).hasChildBlocks(blockName);
};
/**
* Returns a boolean indicating if a block has at least one child block with inserter support.
*
* @param {string} blockName Block type name.
*
* @return {boolean} True if a block contains at least one child blocks with inserter support
* and false otherwise.
*/
const hasChildBlocksWithInserterSupport = blockName => {
return (0,external_wp_data_namespaceObject.select)(store).hasChildBlocksWithInserterSupport(blockName);
};
/**
* Registers a new block style for the given block.
*
* For more information on connecting the styles with CSS [the official documentation](/docs/reference-guides/block-api/block-styles.md#styles)
*
* @param {string} blockName Name of block (example: “core/latest-posts”).
* @param {Object} styleVariation Object containing `name` which is the class name applied to the block and `label` which identifies the variation to the user.
*
* @example
* ```js
* import { __ } from '@wordpress/i18n';
* import { registerBlockStyle } from '@wordpress/blocks';
* import { Button } from '@wordpress/components';
*
*
* const ExampleComponent = () => {
* return (
* <Button
* onClick={ () => {
* registerBlockStyle( 'core/quote', {
* name: 'fancy-quote',
* label: __( 'Fancy Quote' ),
* } );
* } }
* >
* { __( 'Add a new block style for core/quote' ) }
* </Button>
* );
* };
* ```
*/
const registerBlockStyle = (blockName, styleVariation) => {
(0,external_wp_data_namespaceObject.dispatch)(store).addBlockStyles(blockName, styleVariation);
};
/**
* Unregisters a block style for the given block.
*
* @param {string} blockName Name of block (example: “core/latest-posts”).
* @param {string} styleVariationName Name of class applied to the block.
*
* @example
* ```js
* import { __ } from '@wordpress/i18n';
* import { unregisterBlockStyle } from '@wordpress/blocks';
* import { Button } from '@wordpress/components';
*
* const ExampleComponent = () => {
* return (
* <Button
* onClick={ () => {
* unregisterBlockStyle( 'core/quote', 'plain' );
* } }
* >
* { __( 'Remove the "Plain" block style for core/quote' ) }
* </Button>
* );
* };
* ```
*/
const unregisterBlockStyle = (blockName, styleVariationName) => {
(0,external_wp_data_namespaceObject.dispatch)(store).removeBlockStyles(blockName, styleVariationName);
};
/**
* Returns an array with the variations of a given block type.
* Ignored from documentation as the recommended usage is via useSelect from @wordpress/data.
*
* @ignore
*
* @param {string} blockName Name of block (example: “core/columns”).
* @param {WPBlockVariationScope} [scope] Block variation scope name.
*
* @return {(WPBlockVariation[]|void)} Block variations.
*/
const getBlockVariations = (blockName, scope) => {
return (0,external_wp_data_namespaceObject.select)(store).getBlockVariations(blockName, scope);
};
/**
* Registers a new block variation for the given block type.
*
* For more information on block variations see [the official documentation ](/docs/reference-guides/block-api/block-variations.md)
*
* @param {string} blockName Name of the block (example: “core/columns”).
* @param {WPBlockVariation} variation Object describing a block variation.
*
* @example
* ```js
* import { __ } from '@wordpress/i18n';
* import { registerBlockVariation } from '@wordpress/blocks';
* import { Button } from '@wordpress/components';
*
* const ExampleComponent = () => {
* return (
* <Button
* onClick={ () => {
* registerBlockVariation( 'core/embed', {
* name: 'custom',
* title: __( 'My Custom Embed' ),
* attributes: { providerNameSlug: 'custom' },
* } );
* } }
* >
* __( 'Add a custom variation for core/embed' ) }
* </Button>
* );
* };
* ```
*/
const registerBlockVariation = (blockName, variation) => {
(0,external_wp_data_namespaceObject.dispatch)(store).addBlockVariations(blockName, variation);
};
/**
* Unregisters a block variation defined for the given block type.
*
* @param {string} blockName Name of the block (example: “core/columns”).
* @param {string} variationName Name of the variation defined for the block.
*
* @example
* ```js
* import { __ } from '@wordpress/i18n';
* import { unregisterBlockVariation } from '@wordpress/blocks';
* import { Button } from '@wordpress/components';
*
* const ExampleComponent = () => {
* return (
* <Button
* onClick={ () => {
* unregisterBlockVariation( 'core/embed', 'youtube' );
* } }
* >
* { __( 'Remove the YouTube variation from core/embed' ) }
* </Button>
* );
* };
* ```
*/
const unregisterBlockVariation = (blockName, variationName) => {
(0,external_wp_data_namespaceObject.dispatch)(store).removeBlockVariations(blockName, variationName);
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/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);
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);
if (!getRandomValues) {
throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
}
}
return getRandomValues(rnds8);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/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/blocks/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/blocks/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 = [];
for (var stringify_i = 0; stringify_i < 256; ++stringify_i) {
byteToHex.push((stringify_i + 0x100).toString(16).substr(1));
}
function stringify(arr) {
var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 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
// 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)) {
throw TypeError('Stringified UUID is invalid');
}
return uuid;
}
/* harmony default export */ var esm_browser_stringify = (stringify);
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/node_modules/uuid/dist/esm-browser/v4.js
function v4(options, buf, offset) {
options = options || {};
var 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
if (buf) {
offset = offset || 0;
for (var i = 0; i < 16; ++i) {
buf[offset + i] = rnds[i];
}
return buf;
}
return esm_browser_stringify(rnds);
}
/* harmony default export */ var esm_browser_v4 = (v4);
;// CONCATENATED MODULE: external ["wp","hooks"]
var external_wp_hooks_namespaceObject = window["wp"]["hooks"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/factory.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Returns a block object given its type and attributes.
*
* @param {string} name Block name.
* @param {Object} attributes Block attributes.
* @param {?Array} innerBlocks Nested blocks.
*
* @return {Object} Block object.
*/
function createBlock(name) {
let attributes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
let innerBlocks = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
const sanitizedAttributes = __experimentalSanitizeBlockAttributes(name, attributes);
const clientId = esm_browser_v4(); // Blocks are stored with a unique ID, the assigned type name, the block
// attributes, and their inner blocks.
return {
clientId,
name,
isValid: true,
attributes: sanitizedAttributes,
innerBlocks
};
}
/**
* Given an array of InnerBlocks templates or Block Objects,
* returns an array of created Blocks from them.
* It handles the case of having InnerBlocks as Blocks by
* converting them to the proper format to continue recursively.
*
* @param {Array} innerBlocksOrTemplate Nested blocks or InnerBlocks templates.
*
* @return {Object[]} Array of Block objects.
*/
function createBlocksFromInnerBlocksTemplate() {
let innerBlocksOrTemplate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
return innerBlocksOrTemplate.map(innerBlock => {
const innerBlockTemplate = Array.isArray(innerBlock) ? innerBlock : [innerBlock.name, innerBlock.attributes, innerBlock.innerBlocks];
const [name, attributes, innerBlocks = []] = innerBlockTemplate;
return createBlock(name, attributes, createBlocksFromInnerBlocksTemplate(innerBlocks));
});
}
/**
* Given a block object, returns a copy of the block object while sanitizing its attributes,
* optionally merging new attributes and/or replacing its inner blocks.
*
* @param {Object} block Block instance.
* @param {Object} mergeAttributes Block attributes.
* @param {?Array} newInnerBlocks Nested blocks.
*
* @return {Object} A cloned block.
*/
function __experimentalCloneSanitizedBlock(block) {
let mergeAttributes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
let newInnerBlocks = arguments.length > 2 ? arguments[2] : undefined;
const clientId = esm_browser_v4();
const sanitizedAttributes = __experimentalSanitizeBlockAttributes(block.name, { ...block.attributes,
...mergeAttributes
});
return { ...block,
clientId,
attributes: sanitizedAttributes,
innerBlocks: newInnerBlocks || block.innerBlocks.map(innerBlock => __experimentalCloneSanitizedBlock(innerBlock))
};
}
/**
* Given a block object, returns a copy of the block object,
* optionally merging new attributes and/or replacing its inner blocks.
*
* @param {Object} block Block instance.
* @param {Object} mergeAttributes Block attributes.
* @param {?Array} newInnerBlocks Nested blocks.
*
* @return {Object} A cloned block.
*/
function cloneBlock(block) {
let mergeAttributes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
let newInnerBlocks = arguments.length > 2 ? arguments[2] : undefined;
const clientId = esm_browser_v4();
return { ...block,
clientId,
attributes: { ...block.attributes,
...mergeAttributes
},
innerBlocks: newInnerBlocks || block.innerBlocks.map(innerBlock => cloneBlock(innerBlock))
};
}
/**
* Returns a boolean indicating whether a transform is possible based on
* various bits of context.
*
* @param {Object} transform The transform object to validate.
* @param {string} direction Is this a 'from' or 'to' transform.
* @param {Array} blocks The blocks to transform from.
*
* @return {boolean} Is the transform possible?
*/
const isPossibleTransformForSource = (transform, direction, blocks) => {
if (!blocks.length) {
return false;
} // If multiple blocks are selected, only multi block transforms
// or wildcard transforms are allowed.
const isMultiBlock = blocks.length > 1;
const firstBlockName = blocks[0].name;
const isValidForMultiBlocks = isWildcardBlockTransform(transform) || !isMultiBlock || transform.isMultiBlock;
if (!isValidForMultiBlocks) {
return false;
} // Check non-wildcard transforms to ensure that transform is valid
// for a block selection of multiple blocks of different types.
if (!isWildcardBlockTransform(transform) && !blocks.every(block => block.name === firstBlockName)) {
return false;
} // Only consider 'block' type transforms as valid.
const isBlockType = transform.type === 'block';
if (!isBlockType) {
return false;
} // Check if the transform's block name matches the source block (or is a wildcard)
// only if this is a transform 'from'.
const sourceBlock = blocks[0];
const hasMatchingName = direction !== 'from' || transform.blocks.indexOf(sourceBlock.name) !== -1 || isWildcardBlockTransform(transform);
if (!hasMatchingName) {
return false;
} // Don't allow single Grouping blocks to be transformed into
// a Grouping block.
if (!isMultiBlock && direction === 'from' && isContainerGroupBlock(sourceBlock.name) && isContainerGroupBlock(transform.blockName)) {
return false;
} // If the transform has a `isMatch` function specified, check that it returns true.
if (!maybeCheckTransformIsMatch(transform, blocks)) {
return false;
}
if (transform.usingMobileTransformations && isWildcardBlockTransform(transform) && !isContainerGroupBlock(sourceBlock.name)) {
return false;
}
return true;
};
/**
* Returns block types that the 'blocks' can be transformed into, based on
* 'from' transforms on other blocks.
*
* @param {Array} blocks The blocks to transform from.
*
* @return {Array} Block types that the blocks can be transformed into.
*/
const getBlockTypesForPossibleFromTransforms = blocks => {
if (!blocks.length) {
return [];
}
const allBlockTypes = getBlockTypes(); // filter all blocks to find those with a 'from' transform.
const blockTypesWithPossibleFromTransforms = allBlockTypes.filter(blockType => {
const fromTransforms = getBlockTransforms('from', blockType.name);
return !!findTransform(fromTransforms, transform => {
return isPossibleTransformForSource(transform, 'from', blocks);
});
});
return blockTypesWithPossibleFromTransforms;
};
/**
* Returns block types that the 'blocks' can be transformed into, based on
* the source block's own 'to' transforms.
*
* @param {Array} blocks The blocks to transform from.
*
* @return {Array} Block types that the source can be transformed into.
*/
const getBlockTypesForPossibleToTransforms = blocks => {
if (!blocks.length) {
return [];
}
const sourceBlock = blocks[0];
const blockType = getBlockType(sourceBlock.name);
const transformsTo = blockType ? getBlockTransforms('to', blockType.name) : []; // filter all 'to' transforms to find those that are possible.
const possibleTransforms = transformsTo.filter(transform => {
return transform && isPossibleTransformForSource(transform, 'to', blocks);
}); // Build a list of block names using the possible 'to' transforms.
const blockNames = possibleTransforms.map(transformation => transformation.blocks).flat(); // Map block names to block types.
return blockNames.map(name => name === '*' ? name : getBlockType(name));
};
/**
* Determines whether transform is a "block" type
* and if so whether it is a "wildcard" transform
* ie: targets "any" block type
*
* @param {Object} t the Block transform object
*
* @return {boolean} whether transform is a wildcard transform
*/
const isWildcardBlockTransform = t => t && t.type === 'block' && Array.isArray(t.blocks) && t.blocks.includes('*');
/**
* Determines whether the given Block is the core Block which
* acts as a container Block for other Blocks as part of the
* Grouping mechanics
*
* @param {string} name the name of the Block to test against
*
* @return {boolean} whether or not the Block is the container Block type
*/
const isContainerGroupBlock = name => name === getGroupingBlockName();
/**
* Returns an array of block types that the set of blocks received as argument
* can be transformed into.
*
* @param {Array} blocks Blocks array.
*
* @return {Array} Block types that the blocks argument can be transformed to.
*/
function getPossibleBlockTransformations(blocks) {
if (!blocks.length) {
return [];
}
const blockTypesForFromTransforms = getBlockTypesForPossibleFromTransforms(blocks);
const blockTypesForToTransforms = getBlockTypesForPossibleToTransforms(blocks);
return [...new Set([...blockTypesForFromTransforms, ...blockTypesForToTransforms])];
}
/**
* Given an array of transforms, returns the highest-priority transform where
* the predicate function returns a truthy value. A higher-priority transform
* is one with a lower priority value (i.e. first in priority order). Returns
* null if the transforms set is empty or the predicate function returns a
* falsey value for all entries.
*
* @param {Object[]} transforms Transforms to search.
* @param {Function} predicate Function returning true on matching transform.
*
* @return {?Object} Highest-priority transform candidate.
*/
function findTransform(transforms, predicate) {
// The hooks library already has built-in mechanisms for managing priority
// queue, so leverage via locally-defined instance.
const hooks = (0,external_wp_hooks_namespaceObject.createHooks)();
for (let i = 0; i < transforms.length; i++) {
const candidate = transforms[i];
if (predicate(candidate)) {
hooks.addFilter('transform', 'transform/' + i.toString(), result => result ? result : candidate, candidate.priority);
}
} // Filter name is arbitrarily chosen but consistent with above aggregation.
return hooks.applyFilters('transform', null);
}
/**
* Returns normal block transforms for a given transform direction, optionally
* for a specific block by name, or an empty array if there are no transforms.
* If no block name is provided, returns transforms for all blocks. A normal
* transform object includes `blockName` as a property.
*
* @param {string} direction Transform direction ("to", "from").
* @param {string|Object} blockTypeOrName Block type or name.
*
* @return {Array} Block transforms for direction.
*/
function getBlockTransforms(direction, blockTypeOrName) {
// When retrieving transforms for all block types, recurse into self.
if (blockTypeOrName === undefined) {
return getBlockTypes().map(_ref => {
let {
name
} = _ref;
return getBlockTransforms(direction, name);
}).flat();
} // Validate that block type exists and has array of direction.
const blockType = normalizeBlockType(blockTypeOrName);
const {
name: blockName,
transforms
} = blockType || {};
if (!transforms || !Array.isArray(transforms[direction])) {
return [];
}
const usingMobileTransformations = transforms.supportedMobileTransforms && Array.isArray(transforms.supportedMobileTransforms);
const filteredTransforms = usingMobileTransformations ? transforms[direction].filter(t => {
if (t.type === 'raw') {
return true;
}
if (!t.blocks || !t.blocks.length) {
return false;
}
if (isWildcardBlockTransform(t)) {
return true;
}
return t.blocks.every(transformBlockName => transforms.supportedMobileTransforms.includes(transformBlockName));
}) : transforms[direction]; // Map transforms to normal form.
return filteredTransforms.map(transform => ({ ...transform,
blockName,
usingMobileTransformations
}));
}
/**
* Checks that a given transforms isMatch method passes for given source blocks.
*
* @param {Object} transform A transform object.
* @param {Array} blocks Blocks array.
*
* @return {boolean} True if given blocks are a match for the transform.
*/
function maybeCheckTransformIsMatch(transform, blocks) {
if (typeof transform.isMatch !== 'function') {
return true;
}
const sourceBlock = blocks[0];
const attributes = transform.isMultiBlock ? blocks.map(block => block.attributes) : sourceBlock.attributes;
const block = transform.isMultiBlock ? blocks : sourceBlock;
return transform.isMatch(attributes, block);
}
/**
* Switch one or more blocks into one or more blocks of the new block type.
*
* @param {Array|Object} blocks Blocks array or block object.
* @param {string} name Block name.
*
* @return {?Array} Array of blocks or null.
*/
function switchToBlockType(blocks, name) {
const blocksArray = Array.isArray(blocks) ? blocks : [blocks];
const isMultiBlock = blocksArray.length > 1;
const firstBlock = blocksArray[0];
const sourceName = firstBlock.name; // Find the right transformation by giving priority to the "to"
// transformation.
const transformationsFrom = getBlockTransforms('from', name);
const transformationsTo = getBlockTransforms('to', sourceName);
const transformation = findTransform(transformationsTo, t => t.type === 'block' && t.blocks.indexOf(name) !== -1 && (!isMultiBlock || t.isMultiBlock) && maybeCheckTransformIsMatch(t, blocksArray)) || findTransform(transformationsFrom, t => t.type === 'block' && (isWildcardBlockTransform(t) || t.blocks.indexOf(sourceName) !== -1) && (!isMultiBlock || t.isMultiBlock) && maybeCheckTransformIsMatch(t, blocksArray)); // Stop if there is no valid transformation.
if (!transformation) {
return null;
}
let transformationResults;
if (transformation.isMultiBlock) {
if ('__experimentalConvert' in transformation) {
transformationResults = transformation.__experimentalConvert(blocksArray);
} else {
transformationResults = transformation.transform(blocksArray.map(currentBlock => currentBlock.attributes), blocksArray.map(currentBlock => currentBlock.innerBlocks));
}
} else if ('__experimentalConvert' in transformation) {
transformationResults = transformation.__experimentalConvert(firstBlock);
} else {
transformationResults = transformation.transform(firstBlock.attributes, firstBlock.innerBlocks);
} // Ensure that the transformation function returned an object or an array
// of objects.
if (transformationResults === null || typeof transformationResults !== 'object') {
return null;
} // If the transformation function returned a single object, we want to work
// with an array instead.
transformationResults = Array.isArray(transformationResults) ? transformationResults : [transformationResults]; // Ensure that every block object returned by the transformation has a
// valid block type.
if (transformationResults.some(result => !getBlockType(result.name))) {
return null;
} // When unwrapping blocks (`switchToBlockType( wrapperblocks, '*' )`), do
// not run filters on the unwrapped blocks. They shoud remain as they are.
if (name === '*') {
return transformationResults;
}
const hasSwitchedBlock = transformationResults.some(result => result.name === name); // Ensure that at least one block object returned by the transformation has
// the expected "destination" block type.
if (!hasSwitchedBlock) {
return null;
}
const ret = transformationResults.map((result, index, results) => {
/**
* Filters an individual transform result from block transformation.
* All of the original blocks are passed, since transformations are
* many-to-many, not one-to-one.
*
* @param {Object} transformedBlock The transformed block.
* @param {Object[]} blocks Original blocks transformed.
* @param {Object[]} index Index of the transformed block on the array of results.
* @param {Object[]} results An array all the blocks that resulted from the transformation.
*/
return (0,external_wp_hooks_namespaceObject.applyFilters)('blocks.switchToBlockType.transformedBlock', result, blocks, index, results);
});
return ret;
}
/**
* Create a block object from the example API.
*
* @param {string} name
* @param {Object} example
*
* @return {Object} block.
*/
const getBlockFromExample = (name, example) => {
var _example$innerBlocks;
return createBlock(name, example.attributes, ((_example$innerBlocks = example.innerBlocks) !== null && _example$innerBlocks !== void 0 ? _example$innerBlocks : []).map(innerBlock => getBlockFromExample(innerBlock.name, innerBlock)));
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/utils.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
k([names, a11y]);
/**
* Array of icon colors containing a color to be used if the icon color
* was not explicitly set but the icon background color was.
*
* @type {Object}
*/
const ICON_COLORS = ['#191e23', '#f8f9f9'];
/**
* Determines whether the block's attributes are equal to the default attributes
* which means the block is unmodified.
*
* @param {WPBlock} block Block Object
*
* @return {boolean} Whether the block is an unmodified block.
*/
function isUnmodifiedBlock(block) {
var _blockType$attributes;
// Cache a created default block if no cache exists or the default block
// name changed.
if (!isUnmodifiedBlock[block.name]) {
isUnmodifiedBlock[block.name] = createBlock(block.name);
}
const newBlock = isUnmodifiedBlock[block.name];
const blockType = getBlockType(block.name);
return Object.keys((_blockType$attributes = blockType === null || blockType === void 0 ? void 0 : blockType.attributes) !== null && _blockType$attributes !== void 0 ? _blockType$attributes : {}).every(key => newBlock.attributes[key] === block.attributes[key]);
}
/**
* Determines whether the block is a default block and its attributes are equal
* to the default attributes which means the block is unmodified.
*
* @param {WPBlock} block Block Object
*
* @return {boolean} Whether the block is an unmodified default block.
*/
function isUnmodifiedDefaultBlock(block) {
return block.name === getDefaultBlockName() && isUnmodifiedBlock(block);
}
/**
* Function that checks if the parameter is a valid icon.
*
* @param {*} icon Parameter to be checked.
*
* @return {boolean} True if the parameter is a valid icon and false otherwise.
*/
function isValidIcon(icon) {
return !!icon && (typeof icon === 'string' || (0,external_wp_element_namespaceObject.isValidElement)(icon) || typeof icon === 'function' || icon instanceof external_wp_element_namespaceObject.Component);
}
/**
* Function that receives an icon as set by the blocks during the registration
* and returns a new icon object that is normalized so we can rely on just on possible icon structure
* in the codebase.
*
* @param {WPBlockTypeIconRender} icon Render behavior of a block type icon;
* one of a Dashicon slug, an element, or a
* component.
*
* @return {WPBlockTypeIconDescriptor} Object describing the icon.
*/
function normalizeIconObject(icon) {
icon = icon || BLOCK_ICON_DEFAULT;
if (isValidIcon(icon)) {
return {
src: icon
};
}
if ('background' in icon) {
const colordBgColor = w(icon.background);
const getColorContrast = iconColor => colordBgColor.contrast(iconColor);
const maxContrast = Math.max(...ICON_COLORS.map(getColorContrast));
return { ...icon,
foreground: icon.foreground ? icon.foreground : ICON_COLORS.find(iconColor => getColorContrast(iconColor) === maxContrast),
shadowColor: colordBgColor.alpha(0.3).toRgbString()
};
}
return icon;
}
/**
* Normalizes block type passed as param. When string is passed then
* it converts it to the matching block type object.
* It passes the original object otherwise.
*
* @param {string|Object} blockTypeOrName Block type or name.
*
* @return {?Object} Block type.
*/
function normalizeBlockType(blockTypeOrName) {
if (typeof blockTypeOrName === 'string') {
return getBlockType(blockTypeOrName);
}
return blockTypeOrName;
}
/**
* Get the label for the block, usually this is either the block title,
* or the value of the block's `label` function when that's specified.
*
* @param {Object} blockType The block type.
* @param {Object} attributes The values of the block's attributes.
* @param {Object} context The intended use for the label.
*
* @return {string} The block label.
*/
function getBlockLabel(blockType, attributes) {
let context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'visual';
const {
__experimentalLabel: getLabel,
title
} = blockType;
const label = getLabel && getLabel(attributes, {
context
});
if (!label) {
return title;
} // Strip any HTML (i.e. RichText formatting) before returning.
return (0,external_wp_dom_namespaceObject.__unstableStripHTML)(label);
}
/**
* Get a label for the block for use by screenreaders, this is more descriptive
* than the visual label and includes the block title and the value of the
* `getLabel` function if it's specified.
*
* @param {?Object} blockType The block type.
* @param {Object} attributes The values of the block's attributes.
* @param {?number} position The position of the block in the block list.
* @param {string} [direction='vertical'] The direction of the block layout.
*
* @return {string} The block label.
*/
function getAccessibleBlockLabel(blockType, attributes, position) {
let direction = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'vertical';
// `title` is already localized, `label` is a user-supplied value.
const title = blockType === null || blockType === void 0 ? void 0 : blockType.title;
const label = blockType ? getBlockLabel(blockType, attributes, 'accessibility') : '';
const hasPosition = position !== undefined; // getBlockLabel returns the block title as a fallback when there's no label,
// if it did return the title, this function needs to avoid adding the
// title twice within the accessible label. Use this `hasLabel` boolean to
// handle that.
const hasLabel = label && label !== title;
if (hasPosition && direction === 'vertical') {
if (hasLabel) {
return (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: accessibility text. 1: The block title. 2: The block row number. 3: The block label.. */
(0,external_wp_i18n_namespaceObject.__)('%1$s Block. Row %2$d. %3$s'), title, position, label);
}
return (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: accessibility text. 1: The block title. 2: The block row number. */
(0,external_wp_i18n_namespaceObject.__)('%1$s Block. Row %2$d'), title, position);
} else if (hasPosition && direction === 'horizontal') {
if (hasLabel) {
return (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: accessibility text. 1: The block title. 2: The block column number. 3: The block label.. */
(0,external_wp_i18n_namespaceObject.__)('%1$s Block. Column %2$d. %3$s'), title, position, label);
}
return (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: accessibility text. 1: The block title. 2: The block column number. */
(0,external_wp_i18n_namespaceObject.__)('%1$s Block. Column %2$d'), title, position);
}
if (hasLabel) {
return (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: accessibility text. %1: The block title. %2: The block label. */
(0,external_wp_i18n_namespaceObject.__)('%1$s Block. %2$s'), title, label);
}
return (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: accessibility text. %s: The block title. */
(0,external_wp_i18n_namespaceObject.__)('%s Block'), title);
}
/**
* Ensure attributes contains only values defined by block type, and merge
* default values for missing attributes.
*
* @param {string} name The block's name.
* @param {Object} attributes The block's attributes.
* @return {Object} The sanitized attributes.
*/
function __experimentalSanitizeBlockAttributes(name, attributes) {
// Get the type definition associated with a registered block.
const blockType = getBlockType(name);
if (undefined === blockType) {
throw new Error(`Block type '${name}' is not registered.`);
}
return Object.entries(blockType.attributes).reduce((accumulator, _ref) => {
let [key, schema] = _ref;
const value = attributes[key];
if (undefined !== value) {
accumulator[key] = value;
} else if (schema.hasOwnProperty('default')) {
accumulator[key] = schema.default;
}
if (['node', 'children'].indexOf(schema.source) !== -1) {
// Ensure value passed is always an array, which we're expecting in
// the RichText component to handle the deprecated value.
if (typeof accumulator[key] === 'string') {
accumulator[key] = [accumulator[key]];
} else if (!Array.isArray(accumulator[key])) {
accumulator[key] = [];
}
}
return accumulator;
}, {});
}
/**
* Filter block attributes by `role` and return their names.
*
* @param {string} name Block attribute's name.
* @param {string} role The role of a block attribute.
*
* @return {string[]} The attribute names that have the provided role.
*/
function __experimentalGetBlockAttributesNamesByRole(name, role) {
var _getBlockType;
const attributes = (_getBlockType = getBlockType(name)) === null || _getBlockType === void 0 ? void 0 : _getBlockType.attributes;
if (!attributes) return [];
const attributesNames = Object.keys(attributes);
if (!role) return attributesNames;
return attributesNames.filter(attributeName => {
var _attributes$attribute;
return ((_attributes$attribute = attributes[attributeName]) === null || _attributes$attribute === void 0 ? void 0 : _attributes$attribute.__experimentalRole) === role;
});
}
/**
* Return a new object with the specified keys omitted.
*
* @param {Object} object Original object.
* @param {Array} keys Keys to be omitted.
*
* @return {Object} Object with omitted keys.
*/
function omit(object, keys) {
return Object.fromEntries(Object.entries(object).filter(_ref2 => {
let [key] = _ref2;
return !keys.includes(key);
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/store/reducer.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* @typedef {Object} WPBlockCategory
*
* @property {string} slug Unique category slug.
* @property {string} title Category label, for display in user interface.
*/
/**
* Default set of categories.
*
* @type {WPBlockCategory[]}
*/
const DEFAULT_CATEGORIES = [{
slug: 'text',
title: (0,external_wp_i18n_namespaceObject.__)('Text')
}, {
slug: 'media',
title: (0,external_wp_i18n_namespaceObject.__)('Media')
}, {
slug: 'design',
title: (0,external_wp_i18n_namespaceObject.__)('Design')
}, {
slug: 'widgets',
title: (0,external_wp_i18n_namespaceObject.__)('Widgets')
}, {
slug: 'theme',
title: (0,external_wp_i18n_namespaceObject.__)('Theme')
}, {
slug: 'embed',
title: (0,external_wp_i18n_namespaceObject.__)('Embeds')
}, {
slug: 'reusable',
title: (0,external_wp_i18n_namespaceObject.__)('Reusable blocks')
}]; // Key block types by their name.
function keyBlockTypesByName(types) {
return types.reduce((newBlockTypes, block) => ({ ...newBlockTypes,
[block.name]: block
}), {});
} // Filter items to ensure they're unique by their name.
function getUniqueItemsByName(items) {
return items.reduce((acc, currentItem) => {
if (!acc.some(item => item.name === currentItem.name)) {
acc.push(currentItem);
}
return acc;
}, []);
}
/**
* Reducer managing the unprocessed block types in a form passed when registering the by block.
* It's for internal use only. It allows recomputing the processed block types on-demand after block type filters
* get added or removed.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
function unprocessedBlockTypes() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'ADD_UNPROCESSED_BLOCK_TYPE':
return { ...state,
[action.blockType.name]: action.blockType
};
case 'REMOVE_BLOCK_TYPES':
return omit(state, action.names);
}
return state;
}
/**
* Reducer managing the processed block types with all filters applied.
* The state is derived from the `unprocessedBlockTypes` reducer.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
function blockTypes() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'ADD_BLOCK_TYPES':
return { ...state,
...keyBlockTypesByName(action.blockTypes)
};
case 'REMOVE_BLOCK_TYPES':
return omit(state, action.names);
}
return state;
}
/**
* Reducer managing the block styles.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
function blockStyles() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'ADD_BLOCK_TYPES':
return { ...state,
...(0,external_lodash_namespaceObject.mapValues)(keyBlockTypesByName(action.blockTypes), blockType => getUniqueItemsByName([...(0,external_lodash_namespaceObject.get)(blockType, ['styles'], []).map(style => ({ ...style,
source: 'block'
})), ...(0,external_lodash_namespaceObject.get)(state, [blockType.name], []).filter(_ref => {
let {
source
} = _ref;
return 'block' !== source;
})]))
};
case 'ADD_BLOCK_STYLES':
return { ...state,
[action.blockName]: getUniqueItemsByName([...(0,external_lodash_namespaceObject.get)(state, [action.blockName], []), ...action.styles])
};
case 'REMOVE_BLOCK_STYLES':
return { ...state,
[action.blockName]: (0,external_lodash_namespaceObject.get)(state, [action.blockName], []).filter(style => action.styleNames.indexOf(style.name) === -1)
};
}
return state;
}
/**
* Reducer managing the block variations.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
function blockVariations() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'ADD_BLOCK_TYPES':
return { ...state,
...(0,external_lodash_namespaceObject.mapValues)(keyBlockTypesByName(action.blockTypes), blockType => {
return getUniqueItemsByName([...(0,external_lodash_namespaceObject.get)(blockType, ['variations'], []).map(variation => ({ ...variation,
source: 'block'
})), ...(0,external_lodash_namespaceObject.get)(state, [blockType.name], []).filter(_ref2 => {
let {
source
} = _ref2;
return 'block' !== source;
})]);
})
};
case 'ADD_BLOCK_VARIATIONS':
return { ...state,
[action.blockName]: getUniqueItemsByName([...(0,external_lodash_namespaceObject.get)(state, [action.blockName], []), ...action.variations])
};
case 'REMOVE_BLOCK_VARIATIONS':
return { ...state,
[action.blockName]: (0,external_lodash_namespaceObject.get)(state, [action.blockName], []).filter(variation => action.variationNames.indexOf(variation.name) === -1)
};
}
return state;
}
/**
* Higher-order Reducer creating a reducer keeping track of given block name.
*
* @param {string} setActionType Action type.
*
* @return {Function} Reducer.
*/
function createBlockNameSetterReducer(setActionType) {
return function () {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'REMOVE_BLOCK_TYPES':
if (action.names.indexOf(state) !== -1) {
return null;
}
return state;
case setActionType:
return action.name || null;
}
return state;
};
}
const defaultBlockName = createBlockNameSetterReducer('SET_DEFAULT_BLOCK_NAME');
const freeformFallbackBlockName = createBlockNameSetterReducer('SET_FREEFORM_FALLBACK_BLOCK_NAME');
const unregisteredFallbackBlockName = createBlockNameSetterReducer('SET_UNREGISTERED_FALLBACK_BLOCK_NAME');
const groupingBlockName = createBlockNameSetterReducer('SET_GROUPING_BLOCK_NAME');
/**
* Reducer managing the categories
*
* @param {WPBlockCategory[]} state Current state.
* @param {Object} action Dispatched action.
*
* @return {WPBlockCategory[]} Updated state.
*/
function categories() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DEFAULT_CATEGORIES;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'SET_CATEGORIES':
return action.categories || [];
case 'UPDATE_CATEGORY':
{
if (!action.category || (0,external_lodash_namespaceObject.isEmpty)(action.category)) {
return state;
}
const categoryToChange = state.find(_ref3 => {
let {
slug
} = _ref3;
return slug === action.slug;
});
if (categoryToChange) {
return state.map(category => {
if (category.slug === action.slug) {
return { ...category,
...action.category
};
}
return category;
});
}
}
}
return state;
}
function collections() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'ADD_BLOCK_COLLECTION':
return { ...state,
[action.namespace]: {
title: action.title,
icon: action.icon
}
};
case 'REMOVE_BLOCK_COLLECTION':
return omit(state, action.namespace);
}
return state;
}
/* harmony default export */ var reducer = ((0,external_wp_data_namespaceObject.combineReducers)({
unprocessedBlockTypes,
blockTypes,
blockStyles,
blockVariations,
defaultBlockName,
freeformFallbackBlockName,
unregisteredFallbackBlockName,
groupingBlockName,
categories,
collections
}));
;// CONCATENATED MODULE: ./node_modules/rememo/rememo.js
/** @typedef {(...args: any[]) => *[]} GetDependants */
/** @typedef {() => void} Clear */
/**
* @typedef {{
* getDependants: GetDependants,
* clear: Clear
* }} EnhancedSelector
*/
/**
* Internal cache entry.
*
* @typedef CacheNode
*
* @property {?CacheNode|undefined} [prev] Previous node.
* @property {?CacheNode|undefined} [next] Next node.
* @property {*[]} args Function arguments for cache entry.
* @property {*} val Function result.
*/
/**
* @typedef Cache
*
* @property {Clear} clear Function to clear cache.
* @property {boolean} [isUniqueByDependants] Whether dependants are valid in
* considering cache uniqueness. A cache is unique if dependents are all arrays
* or objects.
* @property {CacheNode?} [head] Cache head.
* @property {*[]} [lastDependants] Dependants from previous invocation.
*/
/**
* Arbitrary value used as key for referencing cache object in WeakMap tree.
*
* @type {{}}
*/
var LEAF_KEY = {};
/**
* Returns the first argument as the sole entry in an array.
*
* @template T
*
* @param {T} value Value to return.
*
* @return {[T]} Value returned as entry in array.
*/
function arrayOf(value) {
return [value];
}
/**
* Returns true if the value passed is object-like, or false otherwise. A value
* is object-like if it can support property assignment, e.g. object or array.
*
* @param {*} value Value to test.
*
* @return {boolean} Whether value is object-like.
*/
function isObjectLike(value) {
return !!value && 'object' === typeof value;
}
/**
* Creates and returns a new cache object.
*
* @return {Cache} Cache object.
*/
function createCache() {
/** @type {Cache} */
var cache = {
clear: function () {
cache.head = null;
},
};
return cache;
}
/**
* Returns true if entries within the two arrays are strictly equal by
* reference from a starting index.
*
* @param {*[]} a First array.
* @param {*[]} b Second array.
* @param {number} fromIndex Index from which to start comparison.
*
* @return {boolean} Whether arrays are shallowly equal.
*/
function isShallowEqual(a, b, fromIndex) {
var i;
if (a.length !== b.length) {
return false;
}
for (i = fromIndex; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
/**
* Returns a memoized selector function. The getDependants function argument is
* called before the memoized selector and is expected to return an immutable
* reference or array of references on which the selector depends for computing
* its own return value. The memoize cache is preserved only as long as those
* dependant references remain the same. If getDependants returns a different
* reference(s), the cache is cleared and the selector value regenerated.
*
* @template {(...args: *[]) => *} S
*
* @param {S} selector Selector function.
* @param {GetDependants=} getDependants Dependant getter returning an array of
* references used in cache bust consideration.
*/
/* harmony default export */ function rememo(selector, getDependants) {
/** @type {WeakMap<*,*>} */
var rootCache;
/** @type {GetDependants} */
var normalizedGetDependants = getDependants ? getDependants : arrayOf;
/**
* Returns the cache for a given dependants array. When possible, a WeakMap
* will be used to create a unique cache for each set of dependants. This
* is feasible due to the nature of WeakMap in allowing garbage collection
* to occur on entries where the key object is no longer referenced. Since
* WeakMap requires the key to be an object, this is only possible when the
* dependant is object-like. The root cache is created as a hierarchy where
* each top-level key is the first entry in a dependants set, the value a
* WeakMap where each key is the next dependant, and so on. This continues
* so long as the dependants are object-like. If no dependants are object-
* like, then the cache is shared across all invocations.
*
* @see isObjectLike
*
* @param {*[]} dependants Selector dependants.
*
* @return {Cache} Cache object.
*/
function getCache(dependants) {
var caches = rootCache,
isUniqueByDependants = true,
i,
dependant,
map,
cache;
for (i = 0; i < dependants.length; i++) {
dependant = dependants[i];
// Can only compose WeakMap from object-like key.
if (!isObjectLike(dependant)) {
isUniqueByDependants = false;
break;
}
// Does current segment of cache already have a WeakMap?
if (caches.has(dependant)) {
// Traverse into nested WeakMap.
caches = caches.get(dependant);
} else {
// Create, set, and traverse into a new one.
map = new WeakMap();
caches.set(dependant, map);
caches = map;
}
}
// We use an arbitrary (but consistent) object as key for the last item
// in the WeakMap to serve as our running cache.
if (!caches.has(LEAF_KEY)) {
cache = createCache();
cache.isUniqueByDependants = isUniqueByDependants;
caches.set(LEAF_KEY, cache);
}
return caches.get(LEAF_KEY);
}
/**
* Resets root memoization cache.
*/
function clear() {
rootCache = new WeakMap();
}
/* eslint-disable jsdoc/check-param-names */
/**
* The augmented selector call, considering first whether dependants have
* changed before passing it to underlying memoize function.
*
* @param {*} source Source object for derivation.
* @param {...*} extraArgs Additional arguments to pass to selector.
*
* @return {*} Selector result.
*/
/* eslint-enable jsdoc/check-param-names */
function callSelector(/* source, ...extraArgs */) {
var len = arguments.length,
cache,
node,
i,
args,
dependants;
// Create copy of arguments (avoid leaking deoptimization).
args = new Array(len);
for (i = 0; i < len; i++) {
args[i] = arguments[i];
}
dependants = normalizedGetDependants.apply(null, args);
cache = getCache(dependants);
// If not guaranteed uniqueness by dependants (primitive type), shallow
// compare against last dependants and, if references have changed,
// destroy cache to recalculate result.
if (!cache.isUniqueByDependants) {
if (
cache.lastDependants &&
!isShallowEqual(dependants, cache.lastDependants, 0)
) {
cache.clear();
}
cache.lastDependants = dependants;
}
node = cache.head;
while (node) {
// Check whether node arguments match arguments
if (!isShallowEqual(node.args, args, 1)) {
node = node.next;
continue;
}
// At this point we can assume we've found a match
// Surface matched node to head if not already
if (node !== cache.head) {
// Adjust siblings to point to each other.
/** @type {CacheNode} */ (node.prev).next = node.next;
if (node.next) {
node.next.prev = node.prev;
}
node.next = cache.head;
node.prev = null;
/** @type {CacheNode} */ (cache.head).prev = node;
cache.head = node;
}
// Return immediately
return node.val;
}
// No cached value found. Continue to insertion phase:
node = /** @type {CacheNode} */ ({
// Generate the result from original function
val: selector.apply(null, args),
});
// Avoid including the source object in the cache.
args[0] = null;
node.args = args;
// Don't need to check whether node is already head, since it would
// have been returned above already if it was
// Shift existing head down list
if (cache.head) {
cache.head.prev = node;
node.next = cache.head;
}
cache.head = node;
return node.val;
}
callSelector.getDependants = normalizedGetDependants;
callSelector.clear = clear;
clear();
return /** @type {S & EnhancedSelector} */ (callSelector);
}
// EXTERNAL MODULE: ./node_modules/remove-accents/index.js
var remove_accents = __webpack_require__(4793);
var remove_accents_default = /*#__PURE__*/__webpack_require__.n(remove_accents);
;// CONCATENATED MODULE: external ["wp","compose"]
var external_wp_compose_namespaceObject = window["wp"]["compose"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/store/selectors.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/** @typedef {import('../api/registration').WPBlockVariation} WPBlockVariation */
/** @typedef {import('../api/registration').WPBlockVariationScope} WPBlockVariationScope */
/** @typedef {import('./reducer').WPBlockCategory} WPBlockCategory */
/**
* Given a block name or block type object, returns the corresponding
* normalized block type object.
*
* @param {Object} state Blocks state.
* @param {(string|Object)} nameOrType Block name or type object
*
* @return {Object} Block type object.
*/
const getNormalizedBlockType = (state, nameOrType) => 'string' === typeof nameOrType ? selectors_getBlockType(state, nameOrType) : nameOrType;
/**
* Returns all the unprocessed block types as passed during the registration.
*
* @param {Object} state Data state.
*
* @return {Array} Unprocessed block types.
*/
function __experimentalGetUnprocessedBlockTypes(state) {
return state.unprocessedBlockTypes;
}
/**
* Returns all the available block types.
*
* @param {Object} state Data state.
*
* @example
* ```js
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const blockTypes = useSelect(
* ( select ) => select( blocksStore ).getBlockTypes(),
* []
* );
*
* return (
* <ul>
* { blockTypes.map( ( block ) => (
* <li key={ block.name }>{ block.title }</li>
* ) ) }
* </ul>
* );
* };
* ```
*
* @return {Array} Block Types.
*/
const selectors_getBlockTypes = rememo(state => Object.values(state.blockTypes), state => [state.blockTypes]);
/**
* Returns a block type by name.
*
* @param {Object} state Data state.
* @param {string} name Block type name.
*
* @example
* ```js
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const paragraphBlock = useSelect( ( select ) =>
* ( select ) => select( blocksStore ).getBlockType( 'core/paragraph' ),
* []
* );
*
* return (
* <ul>
* { paragraphBlock &&
* Object.entries( paragraphBlock.supports ).map(
* ( blockSupportsEntry ) => {
* const [ propertyName, value ] = blockSupportsEntry;
* return (
* <li
* key={ propertyName }
* >{ `${ propertyName } : ${ value }` }</li>
* );
* }
* ) }
* </ul>
* );
* };
* ```
*
* @return {Object?} Block Type.
*/
function selectors_getBlockType(state, name) {
return state.blockTypes[name];
}
/**
* Returns block styles by block name.
*
* @param {Object} state Data state.
* @param {string} name Block type name.
*
* @example
* ```js
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const buttonBlockStyles = useSelect( ( select ) =>
* select( blocksStore ).getBlockStyles( 'core/button' ),
* []
* );
*
* return (
* <ul>
* { buttonBlockStyles &&
* buttonBlockStyles.map( ( style ) => (
* <li key={ style.name }>{ style.label }</li>
* ) ) }
* </ul>
* );
* };
* ```
*
* @return {Array?} Block Styles.
*/
function getBlockStyles(state, name) {
return state.blockStyles[name];
}
/**
* Returns block variations by block name.
*
* @param {Object} state Data state.
* @param {string} blockName Block type name.
* @param {WPBlockVariationScope} [scope] Block variation scope name.
*
* @example
* ```js
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const socialLinkVariations = useSelect( ( select ) =>
* select( blocksStore ).getBlockVariations( 'core/social-link' ),
* []
* );
*
* return (
* <ul>
* { socialLinkVariations &&
* socialLinkVariations.map( ( variation ) => (
* <li key={ variation.name }>{ variation.title }</li>
* ) ) }
* </ul>
* );
* };
* ```
*
* @return {(WPBlockVariation[]|void)} Block variations.
*/
const selectors_getBlockVariations = rememo((state, blockName, scope) => {
const variations = state.blockVariations[blockName];
if (!variations || !scope) {
return variations;
}
return variations.filter(variation => {
// For backward compatibility reasons, variation's scope defaults to
// `block` and `inserter` when not set.
return (variation.scope || ['block', 'inserter']).includes(scope);
});
}, (state, blockName) => [state.blockVariations[blockName]]);
/**
* Returns the active block variation for a given block based on its attributes.
* Variations are determined by their `isActive` property.
* Which is either an array of block attribute keys or a function.
*
* In case of an array of block attribute keys, the `attributes` are compared
* to the variation's attributes using strict equality check.
*
* In case of function type, the function should accept a block's attributes
* and the variation's attributes and determines if a variation is active.
* A function that accepts a block's attributes and the variation's attributes and determines if a variation is active.
*
* @param {Object} state Data state.
* @param {string} blockName Name of block (example: “core/columns”).
* @param {Object} attributes Block attributes used to determine active variation.
* @param {WPBlockVariationScope} [scope] Block variation scope name.
*
* @example
* ```js
* import { __ } from '@wordpress/i18n';
* import { store as blocksStore } from '@wordpress/blocks';
* import { store as blockEditorStore } from '@wordpress/block-editor';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* // This example assumes that a core/embed block is the first block in the Block Editor.
* const activeBlockVariation = useSelect( ( select ) => {
* // Retrieve the list of blocks.
* const [ firstBlock ] = select( blockEditorStore ).getBlocks()
*
* // Return the active block variation for the first block.
* return select( blocksStore ).getActiveBlockVariation(
* firstBlock.name,
* firstBlock.attributes
* );
* }, [] );
*
* return activeBlockVariation && activeBlockVariation.name === 'spotify' ? (
* <p>{ __( 'Spotify variation' ) }</p>
* ) : (
* <p>{ __( 'Other variation' ) }</p>
* );
* };
* ```
*
* @return {(WPBlockVariation|undefined)} Active block variation.
*/
function getActiveBlockVariation(state, blockName, attributes, scope) {
const variations = selectors_getBlockVariations(state, blockName, scope);
const match = variations === null || variations === void 0 ? void 0 : variations.find(variation => {
var _variation$isActive;
if (Array.isArray(variation.isActive)) {
const blockType = selectors_getBlockType(state, blockName);
const attributeKeys = Object.keys((blockType === null || blockType === void 0 ? void 0 : blockType.attributes) || {});
const definedAttributes = variation.isActive.filter(attribute => attributeKeys.includes(attribute));
if (definedAttributes.length === 0) {
return false;
}
return definedAttributes.every(attribute => attributes[attribute] === variation.attributes[attribute]);
}
return (_variation$isActive = variation.isActive) === null || _variation$isActive === void 0 ? void 0 : _variation$isActive.call(variation, attributes, variation.attributes);
});
return match;
}
/**
* Returns the default block variation for the given block type.
* When there are multiple variations annotated as the default one,
* the last added item is picked. This simplifies registering overrides.
* When there is no default variation set, it returns the first item.
*
* @param {Object} state Data state.
* @param {string} blockName Block type name.
* @param {WPBlockVariationScope} [scope] Block variation scope name.
*
* @example
* ```js
* import { __, sprintf } from '@wordpress/i18n';
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const defaultEmbedBlockVariation = useSelect( ( select ) =>
* select( blocksStore ).getDefaultBlockVariation( 'core/embed' ),
* []
* );
*
* return (
* defaultEmbedBlockVariation && (
* <p>
* { sprintf(
* __( 'core/embed default variation: %s' ),
* defaultEmbedBlockVariation.title
* ) }
* </p>
* )
* );
* };
* ```
*
* @return {?WPBlockVariation} The default block variation.
*/
function getDefaultBlockVariation(state, blockName, scope) {
const variations = selectors_getBlockVariations(state, blockName, scope);
const defaultVariation = [...variations].reverse().find(_ref => {
let {
isDefault
} = _ref;
return !!isDefault;
});
return defaultVariation || variations[0];
}
/**
* Returns all the available block categories.
*
* @param {Object} state Data state.
*
* @example
* ```js
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect, } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const blockCategories = useSelect( ( select ) =>
* select( blocksStore ).getCategories(),
* []
* );
*
* return (
* <ul>
* { blockCategories.map( ( category ) => (
* <li key={ category.slug }>{ category.title }</li>
* ) ) }
* </ul>
* );
* };
* ```
*
* @return {WPBlockCategory[]} Categories list.
*/
function getCategories(state) {
return state.categories;
}
/**
* Returns all the available collections.
*
* @param {Object} state Data state.
*
* @example
* ```js
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const blockCollections = useSelect( ( select ) =>
* select( blocksStore ).getCollections(),
* []
* );
*
* return (
* <ul>
* { Object.values( blockCollections ).length > 0 &&
* Object.values( blockCollections ).map( ( collection ) => (
* <li key={ collection.title }>{ collection.title }</li>
* ) ) }
* </ul>
* );
* };
* ```
*
* @return {Object} Collections list.
*/
function getCollections(state) {
return state.collections;
}
/**
* Returns the name of the default block name.
*
* @param {Object} state Data state.
*
* @example
* ```js
* import { __, sprintf } from '@wordpress/i18n';
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const defaultBlockName = useSelect( ( select ) =>
* select( blocksStore ).getDefaultBlockName(),
* []
* );
*
* return (
* defaultBlockName && (
* <p>
* { sprintf( __( 'Default block name: %s' ), defaultBlockName ) }
* </p>
* )
* );
* };
* ```
*
* @return {string?} Default block name.
*/
function selectors_getDefaultBlockName(state) {
return state.defaultBlockName;
}
/**
* Returns the name of the block for handling non-block content.
*
* @param {Object} state Data state.
*
* @example
* ```js
* import { __, sprintf } from '@wordpress/i18n';
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const freeformFallbackBlockName = useSelect( ( select ) =>
* select( blocksStore ).getFreeformFallbackBlockName(),
* []
* );
*
* return (
* freeformFallbackBlockName && (
* <p>
* { sprintf( __(
* 'Freeform fallback block name: %s' ),
* freeformFallbackBlockName
* ) }
* </p>
* )
* );
* };
* ```
*
* @return {string?} Name of the block for handling non-block content.
*/
function getFreeformFallbackBlockName(state) {
return state.freeformFallbackBlockName;
}
/**
* Returns the name of the block for handling unregistered blocks.
*
* @param {Object} state Data state.
*
* @example
* ```js
* import { __, sprintf } from '@wordpress/i18n';
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const unregisteredFallbackBlockName = useSelect( ( select ) =>
* select( blocksStore ).getUnregisteredFallbackBlockName(),
* []
* );
*
* return (
* unregisteredFallbackBlockName && (
* <p>
* { sprintf( __(
* 'Unregistered fallback block name: %s' ),
* unregisteredFallbackBlockName
* ) }
* </p>
* )
* );
* };
* ```
*
* @return {string?} Name of the block for handling unregistered blocks.
*/
function getUnregisteredFallbackBlockName(state) {
return state.unregisteredFallbackBlockName;
}
/**
* Returns the name of the block for handling the grouping of blocks.
*
* @param {Object} state Data state.
*
* @example
* ```js
* import { __, sprintf } from '@wordpress/i18n';
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const groupingBlockName = useSelect( ( select ) =>
* select( blocksStore ).getGroupingBlockName(),
* []
* );
*
* return (
* groupingBlockName && (
* <p>
* { sprintf(
* __( 'Default grouping block name: %s' ),
* groupingBlockName
* ) }
* </p>
* )
* );
* };
* ```
*
* @return {string?} Name of the block for handling the grouping of blocks.
*/
function selectors_getGroupingBlockName(state) {
return state.groupingBlockName;
}
/**
* Returns an array with the child blocks of a given block.
*
* @param {Object} state Data state.
* @param {string} blockName Block type name.
*
* @example
* ```js
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const childBlockNames = useSelect( ( select ) =>
* select( blocksStore ).getChildBlockNames( 'core/navigation' ),
* []
* );
*
* return (
* <ul>
* { childBlockNames &&
* childBlockNames.map( ( child ) => (
* <li key={ child }>{ child }</li>
* ) ) }
* </ul>
* );
* };
* ```
*
* @return {Array} Array of child block names.
*/
const selectors_getChildBlockNames = rememo((state, blockName) => {
return selectors_getBlockTypes(state).filter(blockType => {
var _blockType$parent;
return (_blockType$parent = blockType.parent) === null || _blockType$parent === void 0 ? void 0 : _blockType$parent.includes(blockName);
}).map(_ref2 => {
let {
name
} = _ref2;
return name;
});
}, state => [state.blockTypes]);
/**
* Returns the block support value for a feature, if defined.
*
* @param {Object} state Data state.
* @param {(string|Object)} nameOrType Block name or type object
* @param {Array|string} feature Feature to retrieve
* @param {*} defaultSupports Default value to return if not
* explicitly defined
*
* @example
* ```js
* import { __, sprintf } from '@wordpress/i18n';
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const paragraphBlockSupportValue = useSelect( ( select ) =>
* select( blocksStore ).getBlockSupport( 'core/paragraph', 'anchor' ),
* []
* );
*
* return (
* <p>
* { sprintf(
* __( 'core/paragraph supports.anchor value: %s' ),
* paragraphBlockSupportValue
* ) }
* </p>
* );
* };
* ```
*
* @return {?*} Block support value
*/
const selectors_getBlockSupport = (state, nameOrType, feature, defaultSupports) => {
const blockType = getNormalizedBlockType(state, nameOrType);
if (!(blockType !== null && blockType !== void 0 && blockType.supports)) {
return defaultSupports;
}
return (0,external_lodash_namespaceObject.get)(blockType.supports, feature, defaultSupports);
};
/**
* Returns true if the block defines support for a feature, or false otherwise.
*
* @param {Object} state Data state.
* @param {(string|Object)} nameOrType Block name or type object.
* @param {string} feature Feature to test.
* @param {boolean} defaultSupports Whether feature is supported by
* default if not explicitly defined.
*
* @example
* ```js
* import { __, sprintf } from '@wordpress/i18n';
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const paragraphBlockSupportClassName = useSelect( ( select ) =>
* select( blocksStore ).hasBlockSupport( 'core/paragraph', 'className' ),
* []
* );
*
* return (
* <p>
* { sprintf(
* __( 'core/paragraph supports custom class name?: %s' ),
* paragraphBlockSupportClassName
* ) }
* /p>
* );
* };
* ```
*
* @return {boolean} Whether block supports feature.
*/
function selectors_hasBlockSupport(state, nameOrType, feature, defaultSupports) {
return !!selectors_getBlockSupport(state, nameOrType, feature, defaultSupports);
}
/**
* Returns true if the block type by the given name or object value matches a
* search term, or false otherwise.
*
* @param {Object} state Blocks state.
* @param {(string|Object)} nameOrType Block name or type object.
* @param {string} searchTerm Search term by which to filter.
*
* @example
* ```js
* import { __, sprintf } from '@wordpress/i18n';
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const termFound = useSelect(
* ( select ) =>
* select( blocksStore ).isMatchingSearchTerm(
* 'core/navigation',
* 'theme'
* ),
* []
* );
*
* return (
* <p>
* { sprintf(
* __(
* 'Search term was found in the title, keywords, category or description in block.json: %s'
* ),
* termFound
* ) }
* </p>
* );
* };
* ```
*
* @return {Object[]} Whether block type matches search term.
*/
function isMatchingSearchTerm(state, nameOrType, searchTerm) {
var _blockType$keywords;
const blockType = getNormalizedBlockType(state, nameOrType);
const getNormalizedSearchTerm = (0,external_wp_compose_namespaceObject.pipe)([// Disregard diacritics.
// Input: "média"
term => remove_accents_default()(term !== null && term !== void 0 ? term : ''), // Lowercase.
// Input: "MEDIA"
term => term.toLowerCase(), // Strip leading and trailing whitespace.
// Input: " media "
term => term.trim()]);
const normalizedSearchTerm = getNormalizedSearchTerm(searchTerm);
const isSearchMatch = (0,external_wp_compose_namespaceObject.pipe)([getNormalizedSearchTerm, normalizedCandidate => normalizedCandidate.includes(normalizedSearchTerm)]);
return isSearchMatch(blockType.title) || ((_blockType$keywords = blockType.keywords) === null || _blockType$keywords === void 0 ? void 0 : _blockType$keywords.some(isSearchMatch)) || isSearchMatch(blockType.category) || typeof blockType.description === 'string' && isSearchMatch(blockType.description);
}
/**
* Returns a boolean indicating if a block has child blocks or not.
*
* @param {Object} state Data state.
* @param {string} blockName Block type name.
*
* @example
* ```js
* import { __, sprintf } from '@wordpress/i18n';
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const navigationBlockHasChildBlocks = useSelect( ( select ) =>
* select( blocksStore ).hasChildBlocks( 'core/navigation' ),
* []
* );
*
* return (
* <p>
* { sprintf(
* __( 'core/navigation has child blocks: %s' ),
* navigationBlockHasChildBlocks
* ) }
* </p>
* );
* };
* ```
*
* @return {boolean} True if a block contains child blocks and false otherwise.
*/
const selectors_hasChildBlocks = (state, blockName) => {
return selectors_getChildBlockNames(state, blockName).length > 0;
};
/**
* Returns a boolean indicating if a block has at least one child block with inserter support.
*
* @param {Object} state Data state.
* @param {string} blockName Block type name.
*
* @example
* ```js
* import { __, sprintf } from '@wordpress/i18n';
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const navigationBlockHasChildBlocksWithInserterSupport = useSelect( ( select ) =>
* select( blocksStore ).hasChildBlocksWithInserterSupport(
* 'core/navigation'
* ),
* []
* );
*
* return (
* <p>
* { sprintf(
* __( 'core/navigation has child blocks with inserter support: %s' ),
* navigationBlockHasChildBlocksWithInserterSupport
* ) }
* </p>
* );
* };
* ```
*
* @return {boolean} True if a block contains at least one child blocks with inserter support
* and false otherwise.
*/
const selectors_hasChildBlocksWithInserterSupport = (state, blockName) => {
return selectors_getChildBlockNames(state, blockName).some(childBlockName => {
return selectors_hasBlockSupport(state, childBlockName, 'inserter', true);
});
};
/**
* DO-NOT-USE in production.
* This selector is created for internal/experimental only usage and may be
* removed anytime without any warning, causing breakage on any plugin or theme invoking it.
*/
const __experimentalHasContentRoleAttribute = rememo((state, blockTypeName) => {
const blockType = selectors_getBlockType(state, blockTypeName);
if (!blockType) {
return false;
}
return Object.entries(blockType.attributes).some(_ref3 => {
let [, {
__experimentalRole
}] = _ref3;
return __experimentalRole === 'content';
});
}, (state, blockTypeName) => {
var _state$blockTypes$blo;
return [(_state$blockTypes$blo = state.blockTypes[blockTypeName]) === null || _state$blockTypes$blo === void 0 ? void 0 : _state$blockTypes$blo.attributes];
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/node_modules/is-plain-object/dist/is-plain-object.mjs
/*!
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*/
function is_plain_object_isObject(o) {
return Object.prototype.toString.call(o) === '[object Object]';
}
function isPlainObject(o) {
var ctor,prot;
if (is_plain_object_isObject(o) === false) return false;
// If has modified constructor
ctor = o.constructor;
if (ctor === undefined) return true;
// If has modified prototype
prot = ctor.prototype;
if (is_plain_object_isObject(prot) === false) return false;
// If constructor does not have an Object-specific method
if (prot.hasOwnProperty('isPrototypeOf') === false) {
return false;
}
// Most likely a plain Object
return true;
}
;// CONCATENATED MODULE: external ["wp","deprecated"]
var external_wp_deprecated_namespaceObject = window["wp"]["deprecated"];
var external_wp_deprecated_default = /*#__PURE__*/__webpack_require__.n(external_wp_deprecated_namespaceObject);
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/store/actions.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/** @typedef {import('../api/registration').WPBlockVariation} WPBlockVariation */
/** @typedef {import('../api/registration').WPBlockType} WPBlockType */
/** @typedef {import('./reducer').WPBlockCategory} WPBlockCategory */
const {
error,
warn
} = window.console;
/**
* Mapping of legacy category slugs to their latest normal values, used to
* accommodate updates of the default set of block categories.
*
* @type {Record<string,string>}
*/
const LEGACY_CATEGORY_MAPPING = {
common: 'text',
formatting: 'text',
layout: 'design'
};
/**
* Whether the argument is a function.
*
* @param {*} maybeFunc The argument to check.
* @return {boolean} True if the argument is a function, false otherwise.
*/
function isFunction(maybeFunc) {
return typeof maybeFunc === 'function';
}
/**
* Takes the unprocessed block type data and applies all the existing filters for the registered block type.
* Next, it validates all the settings and performs additional processing to the block type definition.
*
* @param {WPBlockType} blockType Unprocessed block type settings.
* @param {Object} thunkArgs Argument object for the thunk middleware.
* @param {Function} thunkArgs.select Function to select from the store.
*
* @return {WPBlockType | undefined} The block, if it has been successfully registered; otherwise `undefined`.
*/
const processBlockType = (blockType, _ref) => {
let {
select
} = _ref;
const {
name
} = blockType;
const settings = (0,external_wp_hooks_namespaceObject.applyFilters)('blocks.registerBlockType', { ...blockType
}, name, null);
if (settings.description && typeof settings.description !== 'string') {
external_wp_deprecated_default()('Declaring non-string block descriptions', {
since: '6.2'
});
}
if (settings.deprecated) {
settings.deprecated = settings.deprecated.map(deprecation => Object.fromEntries(Object.entries( // Only keep valid deprecation keys.
(0,external_wp_hooks_namespaceObject.applyFilters)('blocks.registerBlockType', // Merge deprecation keys with pre-filter settings
// so that filters that depend on specific keys being
// present don't fail.
{ // Omit deprecation keys here so that deprecations
// can opt out of specific keys like "supports".
...omit(blockType, DEPRECATED_ENTRY_KEYS),
...deprecation
}, name, deprecation)).filter(_ref2 => {
let [key] = _ref2;
return DEPRECATED_ENTRY_KEYS.includes(key);
})));
}
if (!isPlainObject(settings)) {
error('Block settings must be a valid object.');
return;
}
if (!isFunction(settings.save)) {
error('The "save" property must be a valid function.');
return;
}
if ('edit' in settings && !isFunction(settings.edit)) {
error('The "edit" property must be a valid function.');
return;
} // Canonicalize legacy categories to equivalent fallback.
if (LEGACY_CATEGORY_MAPPING.hasOwnProperty(settings.category)) {
settings.category = LEGACY_CATEGORY_MAPPING[settings.category];
}
if ('category' in settings && !select.getCategories().some(_ref3 => {
let {
slug
} = _ref3;
return slug === settings.category;
})) {
warn('The block "' + name + '" is registered with an invalid category "' + settings.category + '".');
delete settings.category;
}
if (!('title' in settings) || settings.title === '') {
error('The block "' + name + '" must have a title.');
return;
}
if (typeof settings.title !== 'string') {
error('Block titles must be strings.');
return;
}
settings.icon = normalizeIconObject(settings.icon);
if (!isValidIcon(settings.icon.src)) {
error('The icon passed is invalid. ' + 'The icon should be a string, an element, a function, or an object following the specifications documented in https://developer.wordpress.org/block-editor/developers/block-api/block-registration/#icon-optional');
return;
}
return settings;
};
/**
* Returns an action object used in signalling that block types have been added.
* Ignored from documentation as the recommended usage for this action through registerBlockType from @wordpress/blocks.
*
* @ignore
*
* @param {WPBlockType|WPBlockType[]} blockTypes Object or array of objects representing blocks to added.
*
*
* @return {Object} Action object.
*/
function addBlockTypes(blockTypes) {
return {
type: 'ADD_BLOCK_TYPES',
blockTypes: Array.isArray(blockTypes) ? blockTypes : [blockTypes]
};
}
/**
* Signals that the passed block type's settings should be stored in the state.
*
* @param {WPBlockType} blockType Unprocessed block type settings.
*/
const __experimentalRegisterBlockType = blockType => _ref4 => {
let {
dispatch,
select
} = _ref4;
dispatch({
type: 'ADD_UNPROCESSED_BLOCK_TYPE',
blockType
});
const processedBlockType = processBlockType(blockType, {
select
});
if (!processedBlockType) {
return;
}
dispatch.addBlockTypes(processedBlockType);
};
/**
* Signals that all block types should be computed again.
* It uses stored unprocessed block types and all the most recent list of registered filters.
*
* It addresses the issue where third party block filters get registered after third party blocks. A sample sequence:
* 1. Filter A.
* 2. Block B.
* 3. Block C.
* 4. Filter D.
* 5. Filter E.
* 6. Block F.
* 7. Filter G.
* In this scenario some filters would not get applied for all blocks because they are registered too late.
*/
const __experimentalReapplyBlockTypeFilters = () => _ref5 => {
let {
dispatch,
select
} = _ref5;
const unprocessedBlockTypes = select.__experimentalGetUnprocessedBlockTypes();
const processedBlockTypes = Object.keys(unprocessedBlockTypes).reduce((accumulator, blockName) => {
const result = processBlockType(unprocessedBlockTypes[blockName], {
select
});
if (result) {
accumulator.push(result);
}
return accumulator;
}, []);
if (!processedBlockTypes.length) {
return;
}
dispatch.addBlockTypes(processedBlockTypes);
};
/**
* Returns an action object used to remove a registered block type.
* Ignored from documentation as the recommended usage for this action through unregisterBlockType from @wordpress/blocks.
*
* @ignore
*
* @param {string|string[]} names Block name or array of block names to be removed.
*
*
* @return {Object} Action object.
*/
function removeBlockTypes(names) {
return {
type: 'REMOVE_BLOCK_TYPES',
names: Array.isArray(names) ? names : [names]
};
}
/**
* Returns an action object used in signalling that new block styles have been added.
* Ignored from documentation as the recommended usage for this action through registerBlockStyle from @wordpress/blocks.
*
* @param {string} blockName Block name.
* @param {Array|Object} styles Block style object or array of block style objects.
*
* @ignore
*
* @return {Object} Action object.
*/
function addBlockStyles(blockName, styles) {
return {
type: 'ADD_BLOCK_STYLES',
styles: Array.isArray(styles) ? styles : [styles],
blockName
};
}
/**
* Returns an action object used in signalling that block styles have been removed.
* Ignored from documentation as the recommended usage for this action through unregisterBlockStyle from @wordpress/blocks.
*
* @ignore
*
* @param {string} blockName Block name.
* @param {Array|string} styleNames Block style names or array of block style names.
*
* @return {Object} Action object.
*/
function removeBlockStyles(blockName, styleNames) {
return {
type: 'REMOVE_BLOCK_STYLES',
styleNames: Array.isArray(styleNames) ? styleNames : [styleNames],
blockName
};
}
/**
* Returns an action object used in signalling that new block variations have been added.
* Ignored from documentation as the recommended usage for this action through registerBlockVariation from @wordpress/blocks.
*
* @ignore
*
* @param {string} blockName Block name.
* @param {WPBlockVariation|WPBlockVariation[]} variations Block variations.
*
* @return {Object} Action object.
*/
function addBlockVariations(blockName, variations) {
return {
type: 'ADD_BLOCK_VARIATIONS',
variations: Array.isArray(variations) ? variations : [variations],
blockName
};
}
/**
* Returns an action object used in signalling that block variations have been removed.
* Ignored from documentation as the recommended usage for this action through unregisterBlockVariation from @wordpress/blocks.
*
* @ignore
*
* @param {string} blockName Block name.
* @param {string|string[]} variationNames Block variation names.
*
* @return {Object} Action object.
*/
function removeBlockVariations(blockName, variationNames) {
return {
type: 'REMOVE_BLOCK_VARIATIONS',
variationNames: Array.isArray(variationNames) ? variationNames : [variationNames],
blockName
};
}
/**
* Returns an action object used to set the default block name.
* Ignored from documentation as the recommended usage for this action through setDefaultBlockName from @wordpress/blocks.
*
* @ignore
*
* @param {string} name Block name.
*
* @return {Object} Action object.
*/
function actions_setDefaultBlockName(name) {
return {
type: 'SET_DEFAULT_BLOCK_NAME',
name
};
}
/**
* Returns an action object used to set the name of the block used as a fallback
* for non-block content.
* Ignored from documentation as the recommended usage for this action through setFreeformContentHandlerName from @wordpress/blocks.
*
* @ignore
*
* @param {string} name Block name.
*
* @return {Object} Action object.
*/
function setFreeformFallbackBlockName(name) {
return {
type: 'SET_FREEFORM_FALLBACK_BLOCK_NAME',
name
};
}
/**
* Returns an action object used to set the name of the block used as a fallback
* for unregistered blocks.
* Ignored from documentation as the recommended usage for this action through setUnregisteredTypeHandlerName from @wordpress/blocks.
*
* @ignore
*
* @param {string} name Block name.
*
* @return {Object} Action object.
*/
function setUnregisteredFallbackBlockName(name) {
return {
type: 'SET_UNREGISTERED_FALLBACK_BLOCK_NAME',
name
};
}
/**
* Returns an action object used to set the name of the block used
* when grouping other blocks
* eg: in "Group/Ungroup" interactions
* Ignored from documentation as the recommended usage for this action through setGroupingBlockName from @wordpress/blocks.
*
* @ignore
*
* @param {string} name Block name.
*
* @return {Object} Action object.
*/
function actions_setGroupingBlockName(name) {
return {
type: 'SET_GROUPING_BLOCK_NAME',
name
};
}
/**
* Returns an action object used to set block categories.
* Ignored from documentation as the recommended usage for this action through setCategories from @wordpress/blocks.
*
* @ignore
*
* @param {WPBlockCategory[]} categories Block categories.
*
* @return {Object} Action object.
*/
function setCategories(categories) {
return {
type: 'SET_CATEGORIES',
categories
};
}
/**
* Returns an action object used to update a category.
* Ignored from documentation as the recommended usage for this action through updateCategory from @wordpress/blocks.
*
* @ignore
*
* @param {string} slug Block category slug.
* @param {Object} category Object containing the category properties that should be updated.
*
* @return {Object} Action object.
*/
function updateCategory(slug, category) {
return {
type: 'UPDATE_CATEGORY',
slug,
category
};
}
/**
* Returns an action object used to add block collections
* Ignored from documentation as the recommended usage for this action through registerBlockCollection from @wordpress/blocks.
*
* @ignore
*
* @param {string} namespace The namespace of the blocks to put in the collection
* @param {string} title The title to display in the block inserter
* @param {Object} icon (optional) The icon to display in the block inserter
*
* @return {Object} Action object.
*/
function addBlockCollection(namespace, title, icon) {
return {
type: 'ADD_BLOCK_COLLECTION',
namespace,
title,
icon
};
}
/**
* Returns an action object used to remove block collections
* Ignored from documentation as the recommended usage for this action through unregisterBlockCollection from @wordpress/blocks.
*
* @ignore
*
* @param {string} namespace The namespace of the blocks to put in the collection
*
* @return {Object} Action object.
*/
function removeBlockCollection(namespace) {
return {
type: 'REMOVE_BLOCK_COLLECTION',
namespace
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/store/constants.js
const STORE_NAME = 'core/blocks';
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/store/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Store definition for the blocks 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, {
reducer: reducer,
selectors: selectors_namespaceObject,
actions: actions_namespaceObject
});
(0,external_wp_data_namespaceObject.register)(store);
;// CONCATENATED MODULE: external ["wp","blockSerializationDefaultParser"]
var external_wp_blockSerializationDefaultParser_namespaceObject = window["wp"]["blockSerializationDefaultParser"];
;// CONCATENATED MODULE: external ["wp","autop"]
var external_wp_autop_namespaceObject = window["wp"]["autop"];
;// CONCATENATED MODULE: external ["wp","isShallowEqual"]
var external_wp_isShallowEqual_namespaceObject = window["wp"]["isShallowEqual"];
var external_wp_isShallowEqual_default = /*#__PURE__*/__webpack_require__.n(external_wp_isShallowEqual_namespaceObject);
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/parser/serialize-raw-block.js
/**
* Internal dependencies
*/
/**
* @typedef {Object} Options Serialization options.
* @property {boolean} [isCommentDelimited=true] Whether to output HTML comments around blocks.
*/
/** @typedef {import("./").WPRawBlock} WPRawBlock */
/**
* Serializes a block node into the native HTML-comment-powered block format.
* CAVEAT: This function is intended for re-serializing blocks as parsed by
* valid parsers and skips any validation steps. This is NOT a generic
* serialization function for in-memory blocks. For most purposes, see the
* following functions available in the `@wordpress/blocks` package:
*
* @see serializeBlock
* @see serialize
*
* For more on the format of block nodes as returned by valid parsers:
*
* @see `@wordpress/block-serialization-default-parser` package
* @see `@wordpress/block-serialization-spec-parser` package
*
* @param {WPRawBlock} rawBlock A block node as returned by a valid parser.
* @param {Options} [options={}] Serialization options.
*
* @return {string} An HTML string representing a block.
*/
function serializeRawBlock(rawBlock) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const {
isCommentDelimited = true
} = options;
const {
blockName,
attrs = {},
innerBlocks = [],
innerContent = []
} = rawBlock;
let childIndex = 0;
const content = innerContent.map(item => // `null` denotes a nested block, otherwise we have an HTML fragment.
item !== null ? item : serializeRawBlock(innerBlocks[childIndex++], options)).join('\n').replace(/\n+/g, '\n').trim();
return isCommentDelimited ? getCommentDelimitedContent(blockName, attrs, content) : content;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/serializer.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/** @typedef {import('./parser').WPBlock} WPBlock */
/**
* @typedef {Object} WPBlockSerializationOptions Serialization Options.
*
* @property {boolean} isInnerBlocks Whether we are serializing inner blocks.
*/
/**
* Returns the block's default classname from its name.
*
* @param {string} blockName The block name.
*
* @return {string} The block's default class.
*/
function getBlockDefaultClassName(blockName) {
// Generated HTML classes for blocks follow the `wp-block-{name}` nomenclature.
// Blocks provided by WordPress drop the prefixes 'core/' or 'core-' (historically used in 'core-embed/').
const className = 'wp-block-' + blockName.replace(/\//, '-').replace(/^core-/, '');
return (0,external_wp_hooks_namespaceObject.applyFilters)('blocks.getBlockDefaultClassName', className, blockName);
}
/**
* Returns the block's default menu item classname from its name.
*
* @param {string} blockName The block name.
*
* @return {string} The block's default menu item class.
*/
function getBlockMenuDefaultClassName(blockName) {
// Generated HTML classes for blocks follow the `editor-block-list-item-{name}` nomenclature.
// Blocks provided by WordPress drop the prefixes 'core/' or 'core-' (historically used in 'core-embed/').
const className = 'editor-block-list-item-' + blockName.replace(/\//, '-').replace(/^core-/, '');
return (0,external_wp_hooks_namespaceObject.applyFilters)('blocks.getBlockMenuDefaultClassName', className, blockName);
}
const blockPropsProvider = {};
const innerBlocksPropsProvider = {};
/**
* Call within a save function to get the props for the block wrapper.
*
* @param {Object} props Optional. Props to pass to the element.
*/
function getBlockProps() {
let props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const {
blockType,
attributes
} = blockPropsProvider;
return (0,external_wp_hooks_namespaceObject.applyFilters)('blocks.getSaveContent.extraProps', { ...props
}, blockType, attributes);
}
/**
* Call within a save function to get the props for the inner blocks wrapper.
*
* @param {Object} props Optional. Props to pass to the element.
*/
function getInnerBlocksProps() {
let props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const {
innerBlocks
} = innerBlocksPropsProvider; // Value is an array of blocks, so defer to block serializer.
const html = serialize(innerBlocks, {
isInnerBlocks: true
}); // Use special-cased raw HTML tag to avoid default escaping.
const children = (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.RawHTML, null, html);
return { ...props,
children
};
}
/**
* Given a block type containing a save render implementation and attributes, returns the
* enhanced element to be saved or string when raw HTML expected.
*
* @param {string|Object} blockTypeOrName Block type or name.
* @param {Object} attributes Block attributes.
* @param {?Array} innerBlocks Nested blocks.
*
* @return {Object|string} Save element or raw HTML string.
*/
function getSaveElement(blockTypeOrName, attributes) {
let innerBlocks = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
const blockType = normalizeBlockType(blockTypeOrName);
let {
save
} = blockType; // Component classes are unsupported for save since serialization must
// occur synchronously. For improved interoperability with higher-order
// components which often return component class, emulate basic support.
if (save.prototype instanceof external_wp_element_namespaceObject.Component) {
const instance = new save({
attributes
});
save = instance.render.bind(instance);
}
blockPropsProvider.blockType = blockType;
blockPropsProvider.attributes = attributes;
innerBlocksPropsProvider.innerBlocks = innerBlocks;
let element = save({
attributes,
innerBlocks
});
if (element !== null && typeof element === 'object' && (0,external_wp_hooks_namespaceObject.hasFilter)('blocks.getSaveContent.extraProps') && !(blockType.apiVersion > 1)) {
/**
* Filters the props applied to the block save result element.
*
* @param {Object} props Props applied to save element.
* @param {WPBlock} blockType Block type definition.
* @param {Object} attributes Block attributes.
*/
const props = (0,external_wp_hooks_namespaceObject.applyFilters)('blocks.getSaveContent.extraProps', { ...element.props
}, blockType, attributes);
if (!external_wp_isShallowEqual_default()(props, element.props)) {
element = (0,external_wp_element_namespaceObject.cloneElement)(element, props);
}
}
/**
* Filters the save result of a block during serialization.
*
* @param {WPElement} element Block save result.
* @param {WPBlock} blockType Block type definition.
* @param {Object} attributes Block attributes.
*/
return (0,external_wp_hooks_namespaceObject.applyFilters)('blocks.getSaveElement', element, blockType, attributes);
}
/**
* Given a block type containing a save render implementation and attributes, returns the
* static markup to be saved.
*
* @param {string|Object} blockTypeOrName Block type or name.
* @param {Object} attributes Block attributes.
* @param {?Array} innerBlocks Nested blocks.
*
* @return {string} Save content.
*/
function getSaveContent(blockTypeOrName, attributes, innerBlocks) {
const blockType = normalizeBlockType(blockTypeOrName);
return (0,external_wp_element_namespaceObject.renderToString)(getSaveElement(blockType, attributes, innerBlocks));
}
/**
* Returns attributes which are to be saved and serialized into the block
* comment delimiter.
*
* When a block exists in memory it contains as its attributes both those
* parsed the block comment delimiter _and_ those which matched from the
* contents of the block.
*
* This function returns only those attributes which are needed to persist and
* which cannot be matched from the block content.
*
* @param {Object<string,*>} blockType Block type.
* @param {Object<string,*>} attributes Attributes from in-memory block data.
*
* @return {Object<string,*>} Subset of attributes for comment serialization.
*/
function getCommentAttributes(blockType, attributes) {
var _blockType$attributes;
return Object.entries((_blockType$attributes = blockType.attributes) !== null && _blockType$attributes !== void 0 ? _blockType$attributes : {}).reduce((accumulator, _ref) => {
let [key, attributeSchema] = _ref;
const value = attributes[key]; // Ignore undefined values.
if (undefined === value) {
return accumulator;
} // Ignore all attributes but the ones with an "undefined" source
// "undefined" source refers to attributes saved in the block comment.
if (attributeSchema.source !== undefined) {
return accumulator;
} // Ignore default value.
if ('default' in attributeSchema && attributeSchema.default === value) {
return accumulator;
} // Otherwise, include in comment set.
accumulator[key] = value;
return accumulator;
}, {});
}
/**
* Given an attributes object, returns a string in the serialized attributes
* format prepared for post content.
*
* @param {Object} attributes Attributes object.
*
* @return {string} Serialized attributes.
*/
function serializeAttributes(attributes) {
return JSON.stringify(attributes) // Don't break HTML comments.
.replace(/--/g, '\\u002d\\u002d') // Don't break non-standard-compliant tools.
.replace(/</g, '\\u003c').replace(/>/g, '\\u003e').replace(/&/g, '\\u0026') // Bypass server stripslashes behavior which would unescape stringify's
// escaping of quotation mark.
//
// See: https://developer.wordpress.org/reference/functions/wp_kses_stripslashes/
.replace(/\\"/g, '\\u0022');
}
/**
* Given a block object, returns the Block's Inner HTML markup.
*
* @param {Object} block Block instance.
*
* @return {string} HTML.
*/
function getBlockInnerHTML(block) {
// If block was parsed as invalid or encounters an error while generating
// save content, use original content instead to avoid content loss. If a
// block contains nested content, exempt it from this condition because we
// otherwise have no access to its original content and content loss would
// still occur.
let saveContent = block.originalContent;
if (block.isValid || block.innerBlocks.length) {
try {
saveContent = getSaveContent(block.name, block.attributes, block.innerBlocks);
} catch (error) {}
}
return saveContent;
}
/**
* Returns the content of a block, including comment delimiters.
*
* @param {string} rawBlockName Block name.
* @param {Object} attributes Block attributes.
* @param {string} content Block save content.
*
* @return {string} Comment-delimited block content.
*/
function getCommentDelimitedContent(rawBlockName, attributes, content) {
const serializedAttributes = attributes && Object.entries(attributes).length ? serializeAttributes(attributes) + ' ' : ''; // Strip core blocks of their namespace prefix.
const blockName = rawBlockName !== null && rawBlockName !== void 0 && rawBlockName.startsWith('core/') ? rawBlockName.slice(5) : rawBlockName; // @todo make the `wp:` prefix potentially configurable.
if (!content) {
return `<!-- wp:${blockName} ${serializedAttributes}/-->`;
}
return `<!-- wp:${blockName} ${serializedAttributes}-->\n` + content + `\n<!-- /wp:${blockName} -->`;
}
/**
* Returns the content of a block, including comment delimiters, determining
* serialized attributes and content form from the current state of the block.
*
* @param {WPBlock} block Block instance.
* @param {WPBlockSerializationOptions} options Serialization options.
*
* @return {string} Serialized block.
*/
function serializeBlock(block) {
let {
isInnerBlocks = false
} = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (!block.isValid && block.__unstableBlockSource) {
return serializeRawBlock(block.__unstableBlockSource);
}
const blockName = block.name;
const saveContent = getBlockInnerHTML(block);
if (blockName === getUnregisteredTypeHandlerName() || !isInnerBlocks && blockName === getFreeformContentHandlerName()) {
return saveContent;
}
const blockType = getBlockType(blockName);
if (!blockType) {
return saveContent;
}
const saveAttributes = getCommentAttributes(blockType, block.attributes);
return getCommentDelimitedContent(blockName, saveAttributes, saveContent);
}
function __unstableSerializeAndClean(blocks) {
// A single unmodified default block is assumed to
// be equivalent to an empty post.
if (blocks.length === 1 && isUnmodifiedDefaultBlock(blocks[0])) {
blocks = [];
}
let content = serialize(blocks); // For compatibility, treat a post consisting of a
// single freeform block as legacy content and apply
// pre-block-editor removep'd content formatting.
if (blocks.length === 1 && blocks[0].name === getFreeformContentHandlerName()) {
content = (0,external_wp_autop_namespaceObject.removep)(content);
}
return content;
}
/**
* Takes a block or set of blocks and returns the serialized post content.
*
* @param {Array} blocks Block(s) to serialize.
* @param {WPBlockSerializationOptions} options Serialization options.
*
* @return {string} The post content.
*/
function serialize(blocks, options) {
const blocksArray = Array.isArray(blocks) ? blocks : [blocks];
return blocksArray.map(block => serializeBlock(block, options)).join('\n\n');
}
;// CONCATENATED MODULE: ./node_modules/simple-html-tokenizer/dist/es6/index.js
/**
* generated from https://raw.githubusercontent.com/w3c/html/26b5126f96f736f796b9e29718138919dd513744/entities.json
* do not edit
*/
var namedCharRefs = {
Aacute: "Á", aacute: "á", Abreve: "Ă", abreve: "ă", ac: "∾", acd: "∿", acE: "∾̳", Acirc: "Â", acirc: "â", acute: "´", Acy: "А", acy: "а", AElig: "Æ", aelig: "æ", af: "\u2061", Afr: "𝔄", afr: "𝔞", Agrave: "À", agrave: "à", alefsym: "ℵ", aleph: "ℵ", Alpha: "Α", alpha: "α", Amacr: "Ā", amacr: "ā", amalg: "⨿", amp: "&", AMP: "&", andand: "⩕", And: "⩓", and: "∧", andd: "⩜", andslope: "⩘", andv: "⩚", ang: "∠", ange: "⦤", angle: "∠", angmsdaa: "⦨", angmsdab: "⦩", angmsdac: "⦪", angmsdad: "⦫", angmsdae: "⦬", angmsdaf: "⦭", angmsdag: "⦮", angmsdah: "⦯", angmsd: "∡", angrt: "∟", angrtvb: "⊾", angrtvbd: "⦝", angsph: "∢", angst: "Å", angzarr: "⍼", Aogon: "Ą", aogon: "ą", Aopf: "𝔸", aopf: "𝕒", apacir: "⩯", ap: "≈", apE: "⩰", ape: "≊", apid: "≋", apos: "'", ApplyFunction: "\u2061", approx: "≈", approxeq: "≊", Aring: "Å", aring: "å", Ascr: "𝒜", ascr: "𝒶", Assign: "≔", ast: "*", asymp: "≈", asympeq: "≍", Atilde: "Ã", atilde: "ã", Auml: "Ä", auml: "ä", awconint: "∳", awint: "⨑", backcong: "≌", backepsilon: "϶", backprime: "‵", backsim: "∽", backsimeq: "⋍", Backslash: "∖", Barv: "⫧", barvee: "⊽", barwed: "⌅", Barwed: "⌆", barwedge: "⌅", bbrk: "⎵", bbrktbrk: "⎶", bcong: "≌", Bcy: "Б", bcy: "б", bdquo: "„", becaus: "∵", because: "∵", Because: "∵", bemptyv: "⦰", bepsi: "϶", bernou: "ℬ", Bernoullis: "ℬ", Beta: "Β", beta: "β", beth: "ℶ", between: "≬", Bfr: "𝔅", bfr: "𝔟", bigcap: "⋂", bigcirc: "◯", bigcup: "⋃", bigodot: "⨀", bigoplus: "⨁", bigotimes: "⨂", bigsqcup: "⨆", bigstar: "★", bigtriangledown: "▽", bigtriangleup: "△", biguplus: "⨄", bigvee: "⋁", bigwedge: "⋀", bkarow: "⤍", blacklozenge: "⧫", blacksquare: "▪", blacktriangle: "▴", blacktriangledown: "▾", blacktriangleleft: "◂", blacktriangleright: "▸", blank: "␣", blk12: "▒", blk14: "░", blk34: "▓", block: "█", bne: "=⃥", bnequiv: "≡⃥", bNot: "⫭", bnot: "⌐", Bopf: "𝔹", bopf: "𝕓", bot: "⊥", bottom: "⊥", bowtie: "⋈", boxbox: "⧉", boxdl: "┐", boxdL: "╕", boxDl: "╖", boxDL: "╗", boxdr: "┌", boxdR: "╒", boxDr: "╓", boxDR: "╔", boxh: "─", boxH: "═", boxhd: "┬", boxHd: "╤", boxhD: "╥", boxHD: "╦", boxhu: "┴", boxHu: "╧", boxhU: "╨", boxHU: "╩", boxminus: "⊟", boxplus: "⊞", boxtimes: "⊠", boxul: "┘", boxuL: "╛", boxUl: "╜", boxUL: "╝", boxur: "└", boxuR: "╘", boxUr: "╙", boxUR: "╚", boxv: "│", boxV: "║", boxvh: "┼", boxvH: "╪", boxVh: "╫", boxVH: "╬", boxvl: "┤", boxvL: "╡", boxVl: "╢", boxVL: "╣", boxvr: "├", boxvR: "╞", boxVr: "╟", boxVR: "╠", bprime: "‵", breve: "˘", Breve: "˘", brvbar: "¦", bscr: "𝒷", Bscr: "ℬ", bsemi: "⁏", bsim: "∽", bsime: "⋍", bsolb: "⧅", bsol: "\\", bsolhsub: "⟈", bull: "•", bullet: "•", bump: "≎", bumpE: "⪮", bumpe: "≏", Bumpeq: "≎", bumpeq: "≏", Cacute: "Ć", cacute: "ć", capand: "⩄", capbrcup: "⩉", capcap: "⩋", cap: "∩", Cap: "⋒", capcup: "⩇", capdot: "⩀", CapitalDifferentialD: "ⅅ", caps: "∩︀", caret: "⁁", caron: "ˇ", Cayleys: "ℭ", ccaps: "⩍", Ccaron: "Č", ccaron: "č", Ccedil: "Ç", ccedil: "ç", Ccirc: "Ĉ", ccirc: "ĉ", Cconint: "∰", ccups: "⩌", ccupssm: "⩐", Cdot: "Ċ", cdot: "ċ", cedil: "¸", Cedilla: "¸", cemptyv: "⦲", cent: "¢", centerdot: "·", CenterDot: "·", cfr: "𝔠", Cfr: "ℭ", CHcy: "Ч", chcy: "ч", check: "✓", checkmark: "✓", Chi: "Χ", chi: "χ", circ: "ˆ", circeq: "≗", circlearrowleft: "↺", circlearrowright: "↻", circledast: "⊛", circledcirc: "⊚", circleddash: "⊝", CircleDot: "⊙", circledR: "®", circledS: "Ⓢ", CircleMinus: "⊖", CirclePlus: "⊕", CircleTimes: "⊗", cir: "○", cirE: "⧃", cire: "≗", cirfnint: "⨐", cirmid: "⫯", cirscir: "⧂", ClockwiseContourIntegral: "∲", CloseCurlyDoubleQuote: "”", CloseCurlyQuote: "’", clubs: "♣", clubsuit: "♣", colon: ":", Colon: "∷", Colone: "⩴", colone: "≔", coloneq: "≔", comma: ",", commat: "@", comp: "∁", compfn: "∘", complement: "∁", complexes: "ℂ", cong: "≅", congdot: "⩭", Congruent: "≡", conint: "∮", Conint: "∯", ContourIntegral: "∮", copf: "𝕔", Copf: "ℂ", coprod: "∐", Coproduct: "∐", copy: "©", COPY: "©", copysr: "℗", CounterClockwiseContourIntegral: "∳", crarr: "↵", cross: "✗", Cross: "⨯", Cscr: "𝒞", cscr: "𝒸", csub: "⫏", csube: "⫑", csup: "⫐", csupe: "⫒", ctdot: "⋯", cudarrl: "⤸", cudarrr: "⤵", cuepr: "⋞", cuesc: "⋟", cularr: "↶", cularrp: "⤽", cupbrcap: "⩈", cupcap: "⩆", CupCap: "≍", cup: "∪", Cup: "⋓", cupcup: "⩊", cupdot: "⊍", cupor: "⩅", cups: "∪︀", curarr: "↷", curarrm: "⤼", curlyeqprec: "⋞", curlyeqsucc: "⋟", curlyvee: "⋎", curlywedge: "⋏", curren: "¤", curvearrowleft: "↶", curvearrowright: "↷", cuvee: "⋎", cuwed: "⋏", cwconint: "∲", cwint: "∱", cylcty: "⌭", dagger: "†", Dagger: "‡", daleth: "ℸ", darr: "↓", Darr: "↡", dArr: "⇓", dash: "‐", Dashv: "⫤", dashv: "⊣", dbkarow: "⤏", dblac: "˝", Dcaron: "Ď", dcaron: "ď", Dcy: "Д", dcy: "д", ddagger: "‡", ddarr: "⇊", DD: "ⅅ", dd: "ⅆ", DDotrahd: "⤑", ddotseq: "⩷", deg: "°", Del: "∇", Delta: "Δ", delta: "δ", demptyv: "⦱", dfisht: "⥿", Dfr: "𝔇", dfr: "𝔡", dHar: "⥥", dharl: "⇃", dharr: "⇂", DiacriticalAcute: "´", DiacriticalDot: "˙", DiacriticalDoubleAcute: "˝", DiacriticalGrave: "`", DiacriticalTilde: "˜", diam: "⋄", diamond: "⋄", Diamond: "⋄", diamondsuit: "♦", diams: "♦", die: "¨", DifferentialD: "ⅆ", digamma: "ϝ", disin: "⋲", div: "÷", divide: "÷", divideontimes: "⋇", divonx: "⋇", DJcy: "Ђ", djcy: "ђ", dlcorn: "⌞", dlcrop: "⌍", dollar: "$", Dopf: "𝔻", dopf: "𝕕", Dot: "¨", dot: "˙", DotDot: "⃜", doteq: "≐", doteqdot: "≑", DotEqual: "≐", dotminus: "∸", dotplus: "∔", dotsquare: "⊡", doublebarwedge: "⌆", DoubleContourIntegral: "∯", DoubleDot: "¨", DoubleDownArrow: "⇓", DoubleLeftArrow: "⇐", DoubleLeftRightArrow: "⇔", DoubleLeftTee: "⫤", DoubleLongLeftArrow: "⟸", DoubleLongLeftRightArrow: "⟺", DoubleLongRightArrow: "⟹", DoubleRightArrow: "⇒", DoubleRightTee: "⊨", DoubleUpArrow: "⇑", DoubleUpDownArrow: "⇕", DoubleVerticalBar: "∥", DownArrowBar: "⤓", downarrow: "↓", DownArrow: "↓", Downarrow: "⇓", DownArrowUpArrow: "⇵", DownBreve: "̑", downdownarrows: "⇊", downharpoonleft: "⇃", downharpoonright: "⇂", DownLeftRightVector: "⥐", DownLeftTeeVector: "⥞", DownLeftVectorBar: "⥖", DownLeftVector: "↽", DownRightTeeVector: "⥟", DownRightVectorBar: "⥗", DownRightVector: "⇁", DownTeeArrow: "↧", DownTee: "⊤", drbkarow: "⤐", drcorn: "⌟", drcrop: "⌌", Dscr: "𝒟", dscr: "𝒹", DScy: "Ѕ", dscy: "ѕ", dsol: "⧶", Dstrok: "Đ", dstrok: "đ", dtdot: "⋱", dtri: "▿", dtrif: "▾", duarr: "⇵", duhar: "⥯", dwangle: "⦦", DZcy: "Џ", dzcy: "џ", dzigrarr: "⟿", Eacute: "É", eacute: "é", easter: "⩮", Ecaron: "Ě", ecaron: "ě", Ecirc: "Ê", ecirc: "ê", ecir: "≖", ecolon: "≕", Ecy: "Э", ecy: "э", eDDot: "⩷", Edot: "Ė", edot: "ė", eDot: "≑", ee: "ⅇ", efDot: "≒", Efr: "𝔈", efr: "𝔢", eg: "⪚", Egrave: "È", egrave: "è", egs: "⪖", egsdot: "⪘", el: "⪙", Element: "∈", elinters: "⏧", ell: "ℓ", els: "⪕", elsdot: "⪗", Emacr: "Ē", emacr: "ē", empty: "∅", emptyset: "∅", EmptySmallSquare: "◻", emptyv: "∅", EmptyVerySmallSquare: "▫", emsp13: " ", emsp14: " ", emsp: " ", ENG: "Ŋ", eng: "ŋ", ensp: " ", Eogon: "Ę", eogon: "ę", Eopf: "𝔼", eopf: "𝕖", epar: "⋕", eparsl: "⧣", eplus: "⩱", epsi: "ε", Epsilon: "Ε", epsilon: "ε", epsiv: "ϵ", eqcirc: "≖", eqcolon: "≕", eqsim: "≂", eqslantgtr: "⪖", eqslantless: "⪕", Equal: "⩵", equals: "=", EqualTilde: "≂", equest: "≟", Equilibrium: "⇌", equiv: "≡", equivDD: "⩸", eqvparsl: "⧥", erarr: "⥱", erDot: "≓", escr: "ℯ", Escr: "ℰ", esdot: "≐", Esim: "⩳", esim: "≂", Eta: "Η", eta: "η", ETH: "Ð", eth: "ð", Euml: "Ë", euml: "ë", euro: "€", excl: "!", exist: "∃", Exists: "∃", expectation: "ℰ", exponentiale: "ⅇ", ExponentialE: "ⅇ", fallingdotseq: "≒", Fcy: "Ф", fcy: "ф", female: "♀", ffilig: "ffi", fflig: "ff", ffllig: "ffl", Ffr: "𝔉", ffr: "𝔣", filig: "fi", FilledSmallSquare: "◼", FilledVerySmallSquare: "▪", fjlig: "fj", flat: "♭", fllig: "fl", fltns: "▱", fnof: "ƒ", Fopf: "𝔽", fopf: "𝕗", forall: "∀", ForAll: "∀", fork: "⋔", forkv: "⫙", Fouriertrf: "ℱ", fpartint: "⨍", frac12: "½", frac13: "⅓", frac14: "¼", frac15: "⅕", frac16: "⅙", frac18: "⅛", frac23: "⅔", frac25: "⅖", frac34: "¾", frac35: "⅗", frac38: "⅜", frac45: "⅘", frac56: "⅚", frac58: "⅝", frac78: "⅞", frasl: "⁄", frown: "⌢", fscr: "𝒻", Fscr: "ℱ", gacute: "ǵ", Gamma: "Γ", gamma: "γ", Gammad: "Ϝ", gammad: "ϝ", gap: "⪆", Gbreve: "Ğ", gbreve: "ğ", Gcedil: "Ģ", Gcirc: "Ĝ", gcirc: "ĝ", Gcy: "Г", gcy: "г", Gdot: "Ġ", gdot: "ġ", ge: "≥", gE: "≧", gEl: "⪌", gel: "⋛", geq: "≥", geqq: "≧", geqslant: "⩾", gescc: "⪩", ges: "⩾", gesdot: "⪀", gesdoto: "⪂", gesdotol: "⪄", gesl: "⋛︀", gesles: "⪔", Gfr: "𝔊", gfr: "𝔤", gg: "≫", Gg: "⋙", ggg: "⋙", gimel: "ℷ", GJcy: "Ѓ", gjcy: "ѓ", gla: "⪥", gl: "≷", glE: "⪒", glj: "⪤", gnap: "⪊", gnapprox: "⪊", gne: "⪈", gnE: "≩", gneq: "⪈", gneqq: "≩", gnsim: "⋧", Gopf: "𝔾", gopf: "𝕘", grave: "`", GreaterEqual: "≥", GreaterEqualLess: "⋛", GreaterFullEqual: "≧", GreaterGreater: "⪢", GreaterLess: "≷", GreaterSlantEqual: "⩾", GreaterTilde: "≳", Gscr: "𝒢", gscr: "ℊ", gsim: "≳", gsime: "⪎", gsiml: "⪐", gtcc: "⪧", gtcir: "⩺", gt: ">", GT: ">", Gt: "≫", gtdot: "⋗", gtlPar: "⦕", gtquest: "⩼", gtrapprox: "⪆", gtrarr: "⥸", gtrdot: "⋗", gtreqless: "⋛", gtreqqless: "⪌", gtrless: "≷", gtrsim: "≳", gvertneqq: "≩︀", gvnE: "≩︀", Hacek: "ˇ", hairsp: " ", half: "½", hamilt: "ℋ", HARDcy: "Ъ", hardcy: "ъ", harrcir: "⥈", harr: "↔", hArr: "⇔", harrw: "↭", Hat: "^", hbar: "ℏ", Hcirc: "Ĥ", hcirc: "ĥ", hearts: "♥", heartsuit: "♥", hellip: "…", hercon: "⊹", hfr: "𝔥", Hfr: "ℌ", HilbertSpace: "ℋ", hksearow: "⤥", hkswarow: "⤦", hoarr: "⇿", homtht: "∻", hookleftarrow: "↩", hookrightarrow: "↪", hopf: "𝕙", Hopf: "ℍ", horbar: "―", HorizontalLine: "─", hscr: "𝒽", Hscr: "ℋ", hslash: "ℏ", Hstrok: "Ħ", hstrok: "ħ", HumpDownHump: "≎", HumpEqual: "≏", hybull: "⁃", hyphen: "‐", Iacute: "Í", iacute: "í", ic: "\u2063", Icirc: "Î", icirc: "î", Icy: "И", icy: "и", Idot: "İ", IEcy: "Е", iecy: "е", iexcl: "¡", iff: "⇔", ifr: "𝔦", Ifr: "ℑ", Igrave: "Ì", igrave: "ì", ii: "ⅈ", iiiint: "⨌", iiint: "∭", iinfin: "⧜", iiota: "℩", IJlig: "IJ", ijlig: "ij", Imacr: "Ī", imacr: "ī", image: "ℑ", ImaginaryI: "ⅈ", imagline: "ℐ", imagpart: "ℑ", imath: "ı", Im: "ℑ", imof: "⊷", imped: "Ƶ", Implies: "⇒", incare: "℅", in: "∈", infin: "∞", infintie: "⧝", inodot: "ı", intcal: "⊺", int: "∫", Int: "∬", integers: "ℤ", Integral: "∫", intercal: "⊺", Intersection: "⋂", intlarhk: "⨗", intprod: "⨼", InvisibleComma: "\u2063", InvisibleTimes: "\u2062", IOcy: "Ё", iocy: "ё", Iogon: "Į", iogon: "į", Iopf: "𝕀", iopf: "𝕚", Iota: "Ι", iota: "ι", iprod: "⨼", iquest: "¿", iscr: "𝒾", Iscr: "ℐ", isin: "∈", isindot: "⋵", isinE: "⋹", isins: "⋴", isinsv: "⋳", isinv: "∈", it: "\u2062", Itilde: "Ĩ", itilde: "ĩ", Iukcy: "І", iukcy: "і", Iuml: "Ï", iuml: "ï", Jcirc: "Ĵ", jcirc: "ĵ", Jcy: "Й", jcy: "й", Jfr: "𝔍", jfr: "𝔧", jmath: "ȷ", Jopf: "𝕁", jopf: "𝕛", Jscr: "𝒥", jscr: "𝒿", Jsercy: "Ј", jsercy: "ј", Jukcy: "Є", jukcy: "є", Kappa: "Κ", kappa: "κ", kappav: "ϰ", Kcedil: "Ķ", kcedil: "ķ", Kcy: "К", kcy: "к", Kfr: "𝔎", kfr: "𝔨", kgreen: "ĸ", KHcy: "Х", khcy: "х", KJcy: "Ќ", kjcy: "ќ", Kopf: "𝕂", kopf: "𝕜", Kscr: "𝒦", kscr: "𝓀", lAarr: "⇚", Lacute: "Ĺ", lacute: "ĺ", laemptyv: "⦴", lagran: "ℒ", Lambda: "Λ", lambda: "λ", lang: "⟨", Lang: "⟪", langd: "⦑", langle: "⟨", lap: "⪅", Laplacetrf: "ℒ", laquo: "«", larrb: "⇤", larrbfs: "⤟", larr: "←", Larr: "↞", lArr: "⇐", larrfs: "⤝", larrhk: "↩", larrlp: "↫", larrpl: "⤹", larrsim: "⥳", larrtl: "↢", latail: "⤙", lAtail: "⤛", lat: "⪫", late: "⪭", lates: "⪭︀", lbarr: "⤌", lBarr: "⤎", lbbrk: "❲", lbrace: "{", lbrack: "[", lbrke: "⦋", lbrksld: "⦏", lbrkslu: "⦍", Lcaron: "Ľ", lcaron: "ľ", Lcedil: "Ļ", lcedil: "ļ", lceil: "⌈", lcub: "{", Lcy: "Л", lcy: "л", ldca: "⤶", ldquo: "“", ldquor: "„", ldrdhar: "⥧", ldrushar: "⥋", ldsh: "↲", le: "≤", lE: "≦", LeftAngleBracket: "⟨", LeftArrowBar: "⇤", leftarrow: "←", LeftArrow: "←", Leftarrow: "⇐", LeftArrowRightArrow: "⇆", leftarrowtail: "↢", LeftCeiling: "⌈", LeftDoubleBracket: "⟦", LeftDownTeeVector: "⥡", LeftDownVectorBar: "⥙", LeftDownVector: "⇃", LeftFloor: "⌊", leftharpoondown: "↽", leftharpoonup: "↼", leftleftarrows: "⇇", leftrightarrow: "↔", LeftRightArrow: "↔", Leftrightarrow: "⇔", leftrightarrows: "⇆", leftrightharpoons: "⇋", leftrightsquigarrow: "↭", LeftRightVector: "⥎", LeftTeeArrow: "↤", LeftTee: "⊣", LeftTeeVector: "⥚", leftthreetimes: "⋋", LeftTriangleBar: "⧏", LeftTriangle: "⊲", LeftTriangleEqual: "⊴", LeftUpDownVector: "⥑", LeftUpTeeVector: "⥠", LeftUpVectorBar: "⥘", LeftUpVector: "↿", LeftVectorBar: "⥒", LeftVector: "↼", lEg: "⪋", leg: "⋚", leq: "≤", leqq: "≦", leqslant: "⩽", lescc: "⪨", les: "⩽", lesdot: "⩿", lesdoto: "⪁", lesdotor: "⪃", lesg: "⋚︀", lesges: "⪓", lessapprox: "⪅", lessdot: "⋖", lesseqgtr: "⋚", lesseqqgtr: "⪋", LessEqualGreater: "⋚", LessFullEqual: "≦", LessGreater: "≶", lessgtr: "≶", LessLess: "⪡", lesssim: "≲", LessSlantEqual: "⩽", LessTilde: "≲", lfisht: "⥼", lfloor: "⌊", Lfr: "𝔏", lfr: "𝔩", lg: "≶", lgE: "⪑", lHar: "⥢", lhard: "↽", lharu: "↼", lharul: "⥪", lhblk: "▄", LJcy: "Љ", ljcy: "љ", llarr: "⇇", ll: "≪", Ll: "⋘", llcorner: "⌞", Lleftarrow: "⇚", llhard: "⥫", lltri: "◺", Lmidot: "Ŀ", lmidot: "ŀ", lmoustache: "⎰", lmoust: "⎰", lnap: "⪉", lnapprox: "⪉", lne: "⪇", lnE: "≨", lneq: "⪇", lneqq: "≨", lnsim: "⋦", loang: "⟬", loarr: "⇽", lobrk: "⟦", longleftarrow: "⟵", LongLeftArrow: "⟵", Longleftarrow: "⟸", longleftrightarrow: "⟷", LongLeftRightArrow: "⟷", Longleftrightarrow: "⟺", longmapsto: "⟼", longrightarrow: "⟶", LongRightArrow: "⟶", Longrightarrow: "⟹", looparrowleft: "↫", looparrowright: "↬", lopar: "⦅", Lopf: "𝕃", lopf: "𝕝", loplus: "⨭", lotimes: "⨴", lowast: "∗", lowbar: "_", LowerLeftArrow: "↙", LowerRightArrow: "↘", loz: "◊", lozenge: "◊", lozf: "⧫", lpar: "(", lparlt: "⦓", lrarr: "⇆", lrcorner: "⌟", lrhar: "⇋", lrhard: "⥭", lrm: "\u200e", lrtri: "⊿", lsaquo: "‹", lscr: "𝓁", Lscr: "ℒ", lsh: "↰", Lsh: "↰", lsim: "≲", lsime: "⪍", lsimg: "⪏", lsqb: "[", lsquo: "‘", lsquor: "‚", Lstrok: "Ł", lstrok: "ł", ltcc: "⪦", ltcir: "⩹", lt: "<", LT: "<", Lt: "≪", ltdot: "⋖", lthree: "⋋", ltimes: "⋉", ltlarr: "⥶", ltquest: "⩻", ltri: "◃", ltrie: "⊴", ltrif: "◂", ltrPar: "⦖", lurdshar: "⥊", luruhar: "⥦", lvertneqq: "≨︀", lvnE: "≨︀", macr: "¯", male: "♂", malt: "✠", maltese: "✠", Map: "⤅", map: "↦", mapsto: "↦", mapstodown: "↧", mapstoleft: "↤", mapstoup: "↥", marker: "▮", mcomma: "⨩", Mcy: "М", mcy: "м", mdash: "—", mDDot: "∺", measuredangle: "∡", MediumSpace: " ", Mellintrf: "ℳ", Mfr: "𝔐", mfr: "𝔪", mho: "℧", micro: "µ", midast: "*", midcir: "⫰", mid: "∣", middot: "·", minusb: "⊟", minus: "−", minusd: "∸", minusdu: "⨪", MinusPlus: "∓", mlcp: "⫛", mldr: "…", mnplus: "∓", models: "⊧", Mopf: "𝕄", mopf: "𝕞", mp: "∓", mscr: "𝓂", Mscr: "ℳ", mstpos: "∾", Mu: "Μ", mu: "μ", multimap: "⊸", mumap: "⊸", nabla: "∇", Nacute: "Ń", nacute: "ń", nang: "∠⃒", nap: "≉", napE: "⩰̸", napid: "≋̸", napos: "ʼn", napprox: "≉", natural: "♮", naturals: "ℕ", natur: "♮", nbsp: " ", nbump: "≎̸", nbumpe: "≏̸", ncap: "⩃", Ncaron: "Ň", ncaron: "ň", Ncedil: "Ņ", ncedil: "ņ", ncong: "≇", ncongdot: "⩭̸", ncup: "⩂", Ncy: "Н", ncy: "н", ndash: "–", nearhk: "⤤", nearr: "↗", neArr: "⇗", nearrow: "↗", ne: "≠", nedot: "≐̸", NegativeMediumSpace: "", NegativeThickSpace: "", NegativeThinSpace: "", NegativeVeryThinSpace: "", nequiv: "≢", nesear: "⤨", nesim: "≂̸", NestedGreaterGreater: "≫", NestedLessLess: "≪", NewLine: "\u000a", nexist: "∄", nexists: "∄", Nfr: "𝔑", nfr: "𝔫", ngE: "≧̸", nge: "≱", ngeq: "≱", ngeqq: "≧̸", ngeqslant: "⩾̸", nges: "⩾̸", nGg: "⋙̸", ngsim: "≵", nGt: "≫⃒", ngt: "≯", ngtr: "≯", nGtv: "≫̸", nharr: "↮", nhArr: "⇎", nhpar: "⫲", ni: "∋", nis: "⋼", nisd: "⋺", niv: "∋", NJcy: "Њ", njcy: "њ", nlarr: "↚", nlArr: "⇍", nldr: "‥", nlE: "≦̸", nle: "≰", nleftarrow: "↚", nLeftarrow: "⇍", nleftrightarrow: "↮", nLeftrightarrow: "⇎", nleq: "≰", nleqq: "≦̸", nleqslant: "⩽̸", nles: "⩽̸", nless: "≮", nLl: "⋘̸", nlsim: "≴", nLt: "≪⃒", nlt: "≮", nltri: "⋪", nltrie: "⋬", nLtv: "≪̸", nmid: "∤", NoBreak: "\u2060", NonBreakingSpace: " ", nopf: "𝕟", Nopf: "ℕ", Not: "⫬", not: "¬", NotCongruent: "≢", NotCupCap: "≭", NotDoubleVerticalBar: "∦", NotElement: "∉", NotEqual: "≠", NotEqualTilde: "≂̸", NotExists: "∄", NotGreater: "≯", NotGreaterEqual: "≱", NotGreaterFullEqual: "≧̸", NotGreaterGreater: "≫̸", NotGreaterLess: "≹", NotGreaterSlantEqual: "⩾̸", NotGreaterTilde: "≵", NotHumpDownHump: "≎̸", NotHumpEqual: "≏̸", notin: "∉", notindot: "⋵̸", notinE: "⋹̸", notinva: "∉", notinvb: "⋷", notinvc: "⋶", NotLeftTriangleBar: "⧏̸", NotLeftTriangle: "⋪", NotLeftTriangleEqual: "⋬", NotLess: "≮", NotLessEqual: "≰", NotLessGreater: "≸", NotLessLess: "≪̸", NotLessSlantEqual: "⩽̸", NotLessTilde: "≴", NotNestedGreaterGreater: "⪢̸", NotNestedLessLess: "⪡̸", notni: "∌", notniva: "∌", notnivb: "⋾", notnivc: "⋽", NotPrecedes: "⊀", NotPrecedesEqual: "⪯̸", NotPrecedesSlantEqual: "⋠", NotReverseElement: "∌", NotRightTriangleBar: "⧐̸", NotRightTriangle: "⋫", NotRightTriangleEqual: "⋭", NotSquareSubset: "⊏̸", NotSquareSubsetEqual: "⋢", NotSquareSuperset: "⊐̸", NotSquareSupersetEqual: "⋣", NotSubset: "⊂⃒", NotSubsetEqual: "⊈", NotSucceeds: "⊁", NotSucceedsEqual: "⪰̸", NotSucceedsSlantEqual: "⋡", NotSucceedsTilde: "≿̸", NotSuperset: "⊃⃒", NotSupersetEqual: "⊉", NotTilde: "≁", NotTildeEqual: "≄", NotTildeFullEqual: "≇", NotTildeTilde: "≉", NotVerticalBar: "∤", nparallel: "∦", npar: "∦", nparsl: "⫽⃥", npart: "∂̸", npolint: "⨔", npr: "⊀", nprcue: "⋠", nprec: "⊀", npreceq: "⪯̸", npre: "⪯̸", nrarrc: "⤳̸", nrarr: "↛", nrArr: "⇏", nrarrw: "↝̸", nrightarrow: "↛", nRightarrow: "⇏", nrtri: "⋫", nrtrie: "⋭", nsc: "⊁", nsccue: "⋡", nsce: "⪰̸", Nscr: "𝒩", nscr: "𝓃", nshortmid: "∤", nshortparallel: "∦", nsim: "≁", nsime: "≄", nsimeq: "≄", nsmid: "∤", nspar: "∦", nsqsube: "⋢", nsqsupe: "⋣", nsub: "⊄", nsubE: "⫅̸", nsube: "⊈", nsubset: "⊂⃒", nsubseteq: "⊈", nsubseteqq: "⫅̸", nsucc: "⊁", nsucceq: "⪰̸", nsup: "⊅", nsupE: "⫆̸", nsupe: "⊉", nsupset: "⊃⃒", nsupseteq: "⊉", nsupseteqq: "⫆̸", ntgl: "≹", Ntilde: "Ñ", ntilde: "ñ", ntlg: "≸", ntriangleleft: "⋪", ntrianglelefteq: "⋬", ntriangleright: "⋫", ntrianglerighteq: "⋭", Nu: "Ν", nu: "ν", num: "#", numero: "№", numsp: " ", nvap: "≍⃒", nvdash: "⊬", nvDash: "⊭", nVdash: "⊮", nVDash: "⊯", nvge: "≥⃒", nvgt: ">⃒", nvHarr: "⤄", nvinfin: "⧞", nvlArr: "⤂", nvle: "≤⃒", nvlt: "<⃒", nvltrie: "⊴⃒", nvrArr: "⤃", nvrtrie: "⊵⃒", nvsim: "∼⃒", nwarhk: "⤣", nwarr: "↖", nwArr: "⇖", nwarrow: "↖", nwnear: "⤧", Oacute: "Ó", oacute: "ó", oast: "⊛", Ocirc: "Ô", ocirc: "ô", ocir: "⊚", Ocy: "О", ocy: "о", odash: "⊝", Odblac: "Ő", odblac: "ő", odiv: "⨸", odot: "⊙", odsold: "⦼", OElig: "Œ", oelig: "œ", ofcir: "⦿", Ofr: "𝔒", ofr: "𝔬", ogon: "˛", Ograve: "Ò", ograve: "ò", ogt: "⧁", ohbar: "⦵", ohm: "Ω", oint: "∮", olarr: "↺", olcir: "⦾", olcross: "⦻", oline: "‾", olt: "⧀", Omacr: "Ō", omacr: "ō", Omega: "Ω", omega: "ω", Omicron: "Ο", omicron: "ο", omid: "⦶", ominus: "⊖", Oopf: "𝕆", oopf: "𝕠", opar: "⦷", OpenCurlyDoubleQuote: "“", OpenCurlyQuote: "‘", operp: "⦹", oplus: "⊕", orarr: "↻", Or: "⩔", or: "∨", ord: "⩝", order: "ℴ", orderof: "ℴ", ordf: "ª", ordm: "º", origof: "⊶", oror: "⩖", orslope: "⩗", orv: "⩛", oS: "Ⓢ", Oscr: "𝒪", oscr: "ℴ", Oslash: "Ø", oslash: "ø", osol: "⊘", Otilde: "Õ", otilde: "õ", otimesas: "⨶", Otimes: "⨷", otimes: "⊗", Ouml: "Ö", ouml: "ö", ovbar: "⌽", OverBar: "‾", OverBrace: "⏞", OverBracket: "⎴", OverParenthesis: "⏜", para: "¶", parallel: "∥", par: "∥", parsim: "⫳", parsl: "⫽", part: "∂", PartialD: "∂", Pcy: "П", pcy: "п", percnt: "%", period: ".", permil: "‰", perp: "⊥", pertenk: "‱", Pfr: "𝔓", pfr: "𝔭", Phi: "Φ", phi: "φ", phiv: "ϕ", phmmat: "ℳ", phone: "☎", Pi: "Π", pi: "π", pitchfork: "⋔", piv: "ϖ", planck: "ℏ", planckh: "ℎ", plankv: "ℏ", plusacir: "⨣", plusb: "⊞", pluscir: "⨢", plus: "+", plusdo: "∔", plusdu: "⨥", pluse: "⩲", PlusMinus: "±", plusmn: "±", plussim: "⨦", plustwo: "⨧", pm: "±", Poincareplane: "ℌ", pointint: "⨕", popf: "𝕡", Popf: "ℙ", pound: "£", prap: "⪷", Pr: "⪻", pr: "≺", prcue: "≼", precapprox: "⪷", prec: "≺", preccurlyeq: "≼", Precedes: "≺", PrecedesEqual: "⪯", PrecedesSlantEqual: "≼", PrecedesTilde: "≾", preceq: "⪯", precnapprox: "⪹", precneqq: "⪵", precnsim: "⋨", pre: "⪯", prE: "⪳", precsim: "≾", prime: "′", Prime: "″", primes: "ℙ", prnap: "⪹", prnE: "⪵", prnsim: "⋨", prod: "∏", Product: "∏", profalar: "⌮", profline: "⌒", profsurf: "⌓", prop: "∝", Proportional: "∝", Proportion: "∷", propto: "∝", prsim: "≾", prurel: "⊰", Pscr: "𝒫", pscr: "𝓅", Psi: "Ψ", psi: "ψ", puncsp: " ", Qfr: "𝔔", qfr: "𝔮", qint: "⨌", qopf: "𝕢", Qopf: "ℚ", qprime: "⁗", Qscr: "𝒬", qscr: "𝓆", quaternions: "ℍ", quatint: "⨖", quest: "?", questeq: "≟", quot: "\"", QUOT: "\"", rAarr: "⇛", race: "∽̱", Racute: "Ŕ", racute: "ŕ", radic: "√", raemptyv: "⦳", rang: "⟩", Rang: "⟫", rangd: "⦒", range: "⦥", rangle: "⟩", raquo: "»", rarrap: "⥵", rarrb: "⇥", rarrbfs: "⤠", rarrc: "⤳", rarr: "→", Rarr: "↠", rArr: "⇒", rarrfs: "⤞", rarrhk: "↪", rarrlp: "↬", rarrpl: "⥅", rarrsim: "⥴", Rarrtl: "⤖", rarrtl: "↣", rarrw: "↝", ratail: "⤚", rAtail: "⤜", ratio: "∶", rationals: "ℚ", rbarr: "⤍", rBarr: "⤏", RBarr: "⤐", rbbrk: "❳", rbrace: "}", rbrack: "]", rbrke: "⦌", rbrksld: "⦎", rbrkslu: "⦐", Rcaron: "Ř", rcaron: "ř", Rcedil: "Ŗ", rcedil: "ŗ", rceil: "⌉", rcub: "}", Rcy: "Р", rcy: "р", rdca: "⤷", rdldhar: "⥩", rdquo: "”", rdquor: "”", rdsh: "↳", real: "ℜ", realine: "ℛ", realpart: "ℜ", reals: "ℝ", Re: "ℜ", rect: "▭", reg: "®", REG: "®", ReverseElement: "∋", ReverseEquilibrium: "⇋", ReverseUpEquilibrium: "⥯", rfisht: "⥽", rfloor: "⌋", rfr: "𝔯", Rfr: "ℜ", rHar: "⥤", rhard: "⇁", rharu: "⇀", rharul: "⥬", Rho: "Ρ", rho: "ρ", rhov: "ϱ", RightAngleBracket: "⟩", RightArrowBar: "⇥", rightarrow: "→", RightArrow: "→", Rightarrow: "⇒", RightArrowLeftArrow: "⇄", rightarrowtail: "↣", RightCeiling: "⌉", RightDoubleBracket: "⟧", RightDownTeeVector: "⥝", RightDownVectorBar: "⥕", RightDownVector: "⇂", RightFloor: "⌋", rightharpoondown: "⇁", rightharpoonup: "⇀", rightleftarrows: "⇄", rightleftharpoons: "⇌", rightrightarrows: "⇉", rightsquigarrow: "↝", RightTeeArrow: "↦", RightTee: "⊢", RightTeeVector: "⥛", rightthreetimes: "⋌", RightTriangleBar: "⧐", RightTriangle: "⊳", RightTriangleEqual: "⊵", RightUpDownVector: "⥏", RightUpTeeVector: "⥜", RightUpVectorBar: "⥔", RightUpVector: "↾", RightVectorBar: "⥓", RightVector: "⇀", ring: "˚", risingdotseq: "≓", rlarr: "⇄", rlhar: "⇌", rlm: "\u200f", rmoustache: "⎱", rmoust: "⎱", rnmid: "⫮", roang: "⟭", roarr: "⇾", robrk: "⟧", ropar: "⦆", ropf: "𝕣", Ropf: "ℝ", roplus: "⨮", rotimes: "⨵", RoundImplies: "⥰", rpar: ")", rpargt: "⦔", rppolint: "⨒", rrarr: "⇉", Rrightarrow: "⇛", rsaquo: "›", rscr: "𝓇", Rscr: "ℛ", rsh: "↱", Rsh: "↱", rsqb: "]", rsquo: "’", rsquor: "’", rthree: "⋌", rtimes: "⋊", rtri: "▹", rtrie: "⊵", rtrif: "▸", rtriltri: "⧎", RuleDelayed: "⧴", ruluhar: "⥨", rx: "℞", Sacute: "Ś", sacute: "ś", sbquo: "‚", scap: "⪸", Scaron: "Š", scaron: "š", Sc: "⪼", sc: "≻", sccue: "≽", sce: "⪰", scE: "⪴", Scedil: "Ş", scedil: "ş", Scirc: "Ŝ", scirc: "ŝ", scnap: "⪺", scnE: "⪶", scnsim: "⋩", scpolint: "⨓", scsim: "≿", Scy: "С", scy: "с", sdotb: "⊡", sdot: "⋅", sdote: "⩦", searhk: "⤥", searr: "↘", seArr: "⇘", searrow: "↘", sect: "§", semi: ";", seswar: "⤩", setminus: "∖", setmn: "∖", sext: "✶", Sfr: "𝔖", sfr: "𝔰", sfrown: "⌢", sharp: "♯", SHCHcy: "Щ", shchcy: "щ", SHcy: "Ш", shcy: "ш", ShortDownArrow: "↓", ShortLeftArrow: "←", shortmid: "∣", shortparallel: "∥", ShortRightArrow: "→", ShortUpArrow: "↑", shy: "\u00ad", Sigma: "Σ", sigma: "σ", sigmaf: "ς", sigmav: "ς", sim: "∼", simdot: "⩪", sime: "≃", simeq: "≃", simg: "⪞", simgE: "⪠", siml: "⪝", simlE: "⪟", simne: "≆", simplus: "⨤", simrarr: "⥲", slarr: "←", SmallCircle: "∘", smallsetminus: "∖", smashp: "⨳", smeparsl: "⧤", smid: "∣", smile: "⌣", smt: "⪪", smte: "⪬", smtes: "⪬︀", SOFTcy: "Ь", softcy: "ь", solbar: "⌿", solb: "⧄", sol: "/", Sopf: "𝕊", sopf: "𝕤", spades: "♠", spadesuit: "♠", spar: "∥", sqcap: "⊓", sqcaps: "⊓︀", sqcup: "⊔", sqcups: "⊔︀", Sqrt: "√", sqsub: "⊏", sqsube: "⊑", sqsubset: "⊏", sqsubseteq: "⊑", sqsup: "⊐", sqsupe: "⊒", sqsupset: "⊐", sqsupseteq: "⊒", square: "□", Square: "□", SquareIntersection: "⊓", SquareSubset: "⊏", SquareSubsetEqual: "⊑", SquareSuperset: "⊐", SquareSupersetEqual: "⊒", SquareUnion: "⊔", squarf: "▪", squ: "□", squf: "▪", srarr: "→", Sscr: "𝒮", sscr: "𝓈", ssetmn: "∖", ssmile: "⌣", sstarf: "⋆", Star: "⋆", star: "☆", starf: "★", straightepsilon: "ϵ", straightphi: "ϕ", strns: "¯", sub: "⊂", Sub: "⋐", subdot: "⪽", subE: "⫅", sube: "⊆", subedot: "⫃", submult: "⫁", subnE: "⫋", subne: "⊊", subplus: "⪿", subrarr: "⥹", subset: "⊂", Subset: "⋐", subseteq: "⊆", subseteqq: "⫅", SubsetEqual: "⊆", subsetneq: "⊊", subsetneqq: "⫋", subsim: "⫇", subsub: "⫕", subsup: "⫓", succapprox: "⪸", succ: "≻", succcurlyeq: "≽", Succeeds: "≻", SucceedsEqual: "⪰", SucceedsSlantEqual: "≽", SucceedsTilde: "≿", succeq: "⪰", succnapprox: "⪺", succneqq: "⪶", succnsim: "⋩", succsim: "≿", SuchThat: "∋", sum: "∑", Sum: "∑", sung: "♪", sup1: "¹", sup2: "²", sup3: "³", sup: "⊃", Sup: "⋑", supdot: "⪾", supdsub: "⫘", supE: "⫆", supe: "⊇", supedot: "⫄", Superset: "⊃", SupersetEqual: "⊇", suphsol: "⟉", suphsub: "⫗", suplarr: "⥻", supmult: "⫂", supnE: "⫌", supne: "⊋", supplus: "⫀", supset: "⊃", Supset: "⋑", supseteq: "⊇", supseteqq: "⫆", supsetneq: "⊋", supsetneqq: "⫌", supsim: "⫈", supsub: "⫔", supsup: "⫖", swarhk: "⤦", swarr: "↙", swArr: "⇙", swarrow: "↙", swnwar: "⤪", szlig: "ß", Tab: "\u0009", target: "⌖", Tau: "Τ", tau: "τ", tbrk: "⎴", Tcaron: "Ť", tcaron: "ť", Tcedil: "Ţ", tcedil: "ţ", Tcy: "Т", tcy: "т", tdot: "⃛", telrec: "⌕", Tfr: "𝔗", tfr: "𝔱", there4: "∴", therefore: "∴", Therefore: "∴", Theta: "Θ", theta: "θ", thetasym: "ϑ", thetav: "ϑ", thickapprox: "≈", thicksim: "∼", ThickSpace: " ", ThinSpace: " ", thinsp: " ", thkap: "≈", thksim: "∼", THORN: "Þ", thorn: "þ", tilde: "˜", Tilde: "∼", TildeEqual: "≃", TildeFullEqual: "≅", TildeTilde: "≈", timesbar: "⨱", timesb: "⊠", times: "×", timesd: "⨰", tint: "∭", toea: "⤨", topbot: "⌶", topcir: "⫱", top: "⊤", Topf: "𝕋", topf: "𝕥", topfork: "⫚", tosa: "⤩", tprime: "‴", trade: "™", TRADE: "™", triangle: "▵", triangledown: "▿", triangleleft: "◃", trianglelefteq: "⊴", triangleq: "≜", triangleright: "▹", trianglerighteq: "⊵", tridot: "◬", trie: "≜", triminus: "⨺", TripleDot: "⃛", triplus: "⨹", trisb: "⧍", tritime: "⨻", trpezium: "⏢", Tscr: "𝒯", tscr: "𝓉", TScy: "Ц", tscy: "ц", TSHcy: "Ћ", tshcy: "ћ", Tstrok: "Ŧ", tstrok: "ŧ", twixt: "≬", twoheadleftarrow: "↞", twoheadrightarrow: "↠", Uacute: "Ú", uacute: "ú", uarr: "↑", Uarr: "↟", uArr: "⇑", Uarrocir: "⥉", Ubrcy: "Ў", ubrcy: "ў", Ubreve: "Ŭ", ubreve: "ŭ", Ucirc: "Û", ucirc: "û", Ucy: "У", ucy: "у", udarr: "⇅", Udblac: "Ű", udblac: "ű", udhar: "⥮", ufisht: "⥾", Ufr: "𝔘", ufr: "𝔲", Ugrave: "Ù", ugrave: "ù", uHar: "⥣", uharl: "↿", uharr: "↾", uhblk: "▀", ulcorn: "⌜", ulcorner: "⌜", ulcrop: "⌏", ultri: "◸", Umacr: "Ū", umacr: "ū", uml: "¨", UnderBar: "_", UnderBrace: "⏟", UnderBracket: "⎵", UnderParenthesis: "⏝", Union: "⋃", UnionPlus: "⊎", Uogon: "Ų", uogon: "ų", Uopf: "𝕌", uopf: "𝕦", UpArrowBar: "⤒", uparrow: "↑", UpArrow: "↑", Uparrow: "⇑", UpArrowDownArrow: "⇅", updownarrow: "↕", UpDownArrow: "↕", Updownarrow: "⇕", UpEquilibrium: "⥮", upharpoonleft: "↿", upharpoonright: "↾", uplus: "⊎", UpperLeftArrow: "↖", UpperRightArrow: "↗", upsi: "υ", Upsi: "ϒ", upsih: "ϒ", Upsilon: "Υ", upsilon: "υ", UpTeeArrow: "↥", UpTee: "⊥", upuparrows: "⇈", urcorn: "⌝", urcorner: "⌝", urcrop: "⌎", Uring: "Ů", uring: "ů", urtri: "◹", Uscr: "𝒰", uscr: "𝓊", utdot: "⋰", Utilde: "Ũ", utilde: "ũ", utri: "▵", utrif: "▴", uuarr: "⇈", Uuml: "Ü", uuml: "ü", uwangle: "⦧", vangrt: "⦜", varepsilon: "ϵ", varkappa: "ϰ", varnothing: "∅", varphi: "ϕ", varpi: "ϖ", varpropto: "∝", varr: "↕", vArr: "⇕", varrho: "ϱ", varsigma: "ς", varsubsetneq: "⊊︀", varsubsetneqq: "⫋︀", varsupsetneq: "⊋︀", varsupsetneqq: "⫌︀", vartheta: "ϑ", vartriangleleft: "⊲", vartriangleright: "⊳", vBar: "⫨", Vbar: "⫫", vBarv: "⫩", Vcy: "В", vcy: "в", vdash: "⊢", vDash: "⊨", Vdash: "⊩", VDash: "⊫", Vdashl: "⫦", veebar: "⊻", vee: "∨", Vee: "⋁", veeeq: "≚", vellip: "⋮", verbar: "|", Verbar: "‖", vert: "|", Vert: "‖", VerticalBar: "∣", VerticalLine: "|", VerticalSeparator: "❘", VerticalTilde: "≀", VeryThinSpace: " ", Vfr: "𝔙", vfr: "𝔳", vltri: "⊲", vnsub: "⊂⃒", vnsup: "⊃⃒", Vopf: "𝕍", vopf: "𝕧", vprop: "∝", vrtri: "⊳", Vscr: "𝒱", vscr: "𝓋", vsubnE: "⫋︀", vsubne: "⊊︀", vsupnE: "⫌︀", vsupne: "⊋︀", Vvdash: "⊪", vzigzag: "⦚", Wcirc: "Ŵ", wcirc: "ŵ", wedbar: "⩟", wedge: "∧", Wedge: "⋀", wedgeq: "≙", weierp: "℘", Wfr: "𝔚", wfr: "𝔴", Wopf: "𝕎", wopf: "𝕨", wp: "℘", wr: "≀", wreath: "≀", Wscr: "𝒲", wscr: "𝓌", xcap: "⋂", xcirc: "◯", xcup: "⋃", xdtri: "▽", Xfr: "𝔛", xfr: "𝔵", xharr: "⟷", xhArr: "⟺", Xi: "Ξ", xi: "ξ", xlarr: "⟵", xlArr: "⟸", xmap: "⟼", xnis: "⋻", xodot: "⨀", Xopf: "𝕏", xopf: "𝕩", xoplus: "⨁", xotime: "⨂", xrarr: "⟶", xrArr: "⟹", Xscr: "𝒳", xscr: "𝓍", xsqcup: "⨆", xuplus: "⨄", xutri: "△", xvee: "⋁", xwedge: "⋀", Yacute: "Ý", yacute: "ý", YAcy: "Я", yacy: "я", Ycirc: "Ŷ", ycirc: "ŷ", Ycy: "Ы", ycy: "ы", yen: "¥", Yfr: "𝔜", yfr: "𝔶", YIcy: "Ї", yicy: "ї", Yopf: "𝕐", yopf: "𝕪", Yscr: "𝒴", yscr: "𝓎", YUcy: "Ю", yucy: "ю", yuml: "ÿ", Yuml: "Ÿ", Zacute: "Ź", zacute: "ź", Zcaron: "Ž", zcaron: "ž", Zcy: "З", zcy: "з", Zdot: "Ż", zdot: "ż", zeetrf: "ℨ", ZeroWidthSpace: "", Zeta: "Ζ", zeta: "ζ", zfr: "𝔷", Zfr: "ℨ", ZHcy: "Ж", zhcy: "ж", zigrarr: "⇝", zopf: "𝕫", Zopf: "ℤ", Zscr: "𝒵", zscr: "𝓏", zwj: "\u200d", zwnj: "\u200c"
};
var HEXCHARCODE = /^#[xX]([A-Fa-f0-9]+)$/;
var CHARCODE = /^#([0-9]+)$/;
var NAMED = /^([A-Za-z0-9]+)$/;
var EntityParser = /** @class */ (function () {
function EntityParser(named) {
this.named = named;
}
EntityParser.prototype.parse = function (entity) {
if (!entity) {
return;
}
var matches = entity.match(HEXCHARCODE);
if (matches) {
return String.fromCharCode(parseInt(matches[1], 16));
}
matches = entity.match(CHARCODE);
if (matches) {
return String.fromCharCode(parseInt(matches[1], 10));
}
matches = entity.match(NAMED);
if (matches) {
return this.named[matches[1]];
}
};
return EntityParser;
}());
var WSP = /[\t\n\f ]/;
var ALPHA = /[A-Za-z]/;
var CRLF = /\r\n?/g;
function isSpace(char) {
return WSP.test(char);
}
function isAlpha(char) {
return ALPHA.test(char);
}
function preprocessInput(input) {
return input.replace(CRLF, '\n');
}
var EventedTokenizer = /** @class */ (function () {
function EventedTokenizer(delegate, entityParser, mode) {
if (mode === void 0) { mode = 'precompile'; }
this.delegate = delegate;
this.entityParser = entityParser;
this.mode = mode;
this.state = "beforeData" /* beforeData */;
this.line = -1;
this.column = -1;
this.input = '';
this.index = -1;
this.tagNameBuffer = '';
this.states = {
beforeData: function () {
var char = this.peek();
if (char === '<' && !this.isIgnoredEndTag()) {
this.transitionTo("tagOpen" /* tagOpen */);
this.markTagStart();
this.consume();
}
else {
if (this.mode === 'precompile' && char === '\n') {
var tag = this.tagNameBuffer.toLowerCase();
if (tag === 'pre' || tag === 'textarea') {
this.consume();
}
}
this.transitionTo("data" /* data */);
this.delegate.beginData();
}
},
data: function () {
var char = this.peek();
var tag = this.tagNameBuffer;
if (char === '<' && !this.isIgnoredEndTag()) {
this.delegate.finishData();
this.transitionTo("tagOpen" /* tagOpen */);
this.markTagStart();
this.consume();
}
else if (char === '&' && tag !== 'script' && tag !== 'style') {
this.consume();
this.delegate.appendToData(this.consumeCharRef() || '&');
}
else {
this.consume();
this.delegate.appendToData(char);
}
},
tagOpen: function () {
var char = this.consume();
if (char === '!') {
this.transitionTo("markupDeclarationOpen" /* markupDeclarationOpen */);
}
else if (char === '/') {
this.transitionTo("endTagOpen" /* endTagOpen */);
}
else if (char === '@' || char === ':' || isAlpha(char)) {
this.transitionTo("tagName" /* tagName */);
this.tagNameBuffer = '';
this.delegate.beginStartTag();
this.appendToTagName(char);
}
},
markupDeclarationOpen: function () {
var char = this.consume();
if (char === '-' && this.peek() === '-') {
this.consume();
this.transitionTo("commentStart" /* commentStart */);
this.delegate.beginComment();
}
else {
var maybeDoctype = char.toUpperCase() + this.input.substring(this.index, this.index + 6).toUpperCase();
if (maybeDoctype === 'DOCTYPE') {
this.consume();
this.consume();
this.consume();
this.consume();
this.consume();
this.consume();
this.transitionTo("doctype" /* doctype */);
if (this.delegate.beginDoctype)
this.delegate.beginDoctype();
}
}
},
doctype: function () {
var char = this.consume();
if (isSpace(char)) {
this.transitionTo("beforeDoctypeName" /* beforeDoctypeName */);
}
},
beforeDoctypeName: function () {
var char = this.consume();
if (isSpace(char)) {
return;
}
else {
this.transitionTo("doctypeName" /* doctypeName */);
if (this.delegate.appendToDoctypeName)
this.delegate.appendToDoctypeName(char.toLowerCase());
}
},
doctypeName: function () {
var char = this.consume();
if (isSpace(char)) {
this.transitionTo("afterDoctypeName" /* afterDoctypeName */);
}
else if (char === '>') {
if (this.delegate.endDoctype)
this.delegate.endDoctype();
this.transitionTo("beforeData" /* beforeData */);
}
else {
if (this.delegate.appendToDoctypeName)
this.delegate.appendToDoctypeName(char.toLowerCase());
}
},
afterDoctypeName: function () {
var char = this.consume();
if (isSpace(char)) {
return;
}
else if (char === '>') {
if (this.delegate.endDoctype)
this.delegate.endDoctype();
this.transitionTo("beforeData" /* beforeData */);
}
else {
var nextSixChars = char.toUpperCase() + this.input.substring(this.index, this.index + 5).toUpperCase();
var isPublic = nextSixChars.toUpperCase() === 'PUBLIC';
var isSystem = nextSixChars.toUpperCase() === 'SYSTEM';
if (isPublic || isSystem) {
this.consume();
this.consume();
this.consume();
this.consume();
this.consume();
this.consume();
}
if (isPublic) {
this.transitionTo("afterDoctypePublicKeyword" /* afterDoctypePublicKeyword */);
}
else if (isSystem) {
this.transitionTo("afterDoctypeSystemKeyword" /* afterDoctypeSystemKeyword */);
}
}
},
afterDoctypePublicKeyword: function () {
var char = this.peek();
if (isSpace(char)) {
this.transitionTo("beforeDoctypePublicIdentifier" /* beforeDoctypePublicIdentifier */);
this.consume();
}
else if (char === '"') {
this.transitionTo("doctypePublicIdentifierDoubleQuoted" /* doctypePublicIdentifierDoubleQuoted */);
this.consume();
}
else if (char === "'") {
this.transitionTo("doctypePublicIdentifierSingleQuoted" /* doctypePublicIdentifierSingleQuoted */);
this.consume();
}
else if (char === '>') {
this.consume();
if (this.delegate.endDoctype)
this.delegate.endDoctype();
this.transitionTo("beforeData" /* beforeData */);
}
},
doctypePublicIdentifierDoubleQuoted: function () {
var char = this.consume();
if (char === '"') {
this.transitionTo("afterDoctypePublicIdentifier" /* afterDoctypePublicIdentifier */);
}
else if (char === '>') {
if (this.delegate.endDoctype)
this.delegate.endDoctype();
this.transitionTo("beforeData" /* beforeData */);
}
else {
if (this.delegate.appendToDoctypePublicIdentifier)
this.delegate.appendToDoctypePublicIdentifier(char);
}
},
doctypePublicIdentifierSingleQuoted: function () {
var char = this.consume();
if (char === "'") {
this.transitionTo("afterDoctypePublicIdentifier" /* afterDoctypePublicIdentifier */);
}
else if (char === '>') {
if (this.delegate.endDoctype)
this.delegate.endDoctype();
this.transitionTo("beforeData" /* beforeData */);
}
else {
if (this.delegate.appendToDoctypePublicIdentifier)
this.delegate.appendToDoctypePublicIdentifier(char);
}
},
afterDoctypePublicIdentifier: function () {
var char = this.consume();
if (isSpace(char)) {
this.transitionTo("betweenDoctypePublicAndSystemIdentifiers" /* betweenDoctypePublicAndSystemIdentifiers */);
}
else if (char === '>') {
if (this.delegate.endDoctype)
this.delegate.endDoctype();
this.transitionTo("beforeData" /* beforeData */);
}
else if (char === '"') {
this.transitionTo("doctypeSystemIdentifierDoubleQuoted" /* doctypeSystemIdentifierDoubleQuoted */);
}
else if (char === "'") {
this.transitionTo("doctypeSystemIdentifierSingleQuoted" /* doctypeSystemIdentifierSingleQuoted */);
}
},
betweenDoctypePublicAndSystemIdentifiers: function () {
var char = this.consume();
if (isSpace(char)) {
return;
}
else if (char === '>') {
if (this.delegate.endDoctype)
this.delegate.endDoctype();
this.transitionTo("beforeData" /* beforeData */);
}
else if (char === '"') {
this.transitionTo("doctypeSystemIdentifierDoubleQuoted" /* doctypeSystemIdentifierDoubleQuoted */);
}
else if (char === "'") {
this.transitionTo("doctypeSystemIdentifierSingleQuoted" /* doctypeSystemIdentifierSingleQuoted */);
}
},
doctypeSystemIdentifierDoubleQuoted: function () {
var char = this.consume();
if (char === '"') {
this.transitionTo("afterDoctypeSystemIdentifier" /* afterDoctypeSystemIdentifier */);
}
else if (char === '>') {
if (this.delegate.endDoctype)
this.delegate.endDoctype();
this.transitionTo("beforeData" /* beforeData */);
}
else {
if (this.delegate.appendToDoctypeSystemIdentifier)
this.delegate.appendToDoctypeSystemIdentifier(char);
}
},
doctypeSystemIdentifierSingleQuoted: function () {
var char = this.consume();
if (char === "'") {
this.transitionTo("afterDoctypeSystemIdentifier" /* afterDoctypeSystemIdentifier */);
}
else if (char === '>') {
if (this.delegate.endDoctype)
this.delegate.endDoctype();
this.transitionTo("beforeData" /* beforeData */);
}
else {
if (this.delegate.appendToDoctypeSystemIdentifier)
this.delegate.appendToDoctypeSystemIdentifier(char);
}
},
afterDoctypeSystemIdentifier: function () {
var char = this.consume();
if (isSpace(char)) {
return;
}
else if (char === '>') {
if (this.delegate.endDoctype)
this.delegate.endDoctype();
this.transitionTo("beforeData" /* beforeData */);
}
},
commentStart: function () {
var char = this.consume();
if (char === '-') {
this.transitionTo("commentStartDash" /* commentStartDash */);
}
else if (char === '>') {
this.delegate.finishComment();
this.transitionTo("beforeData" /* beforeData */);
}
else {
this.delegate.appendToCommentData(char);
this.transitionTo("comment" /* comment */);
}
},
commentStartDash: function () {
var char = this.consume();
if (char === '-') {
this.transitionTo("commentEnd" /* commentEnd */);
}
else if (char === '>') {
this.delegate.finishComment();
this.transitionTo("beforeData" /* beforeData */);
}
else {
this.delegate.appendToCommentData('-');
this.transitionTo("comment" /* comment */);
}
},
comment: function () {
var char = this.consume();
if (char === '-') {
this.transitionTo("commentEndDash" /* commentEndDash */);
}
else {
this.delegate.appendToCommentData(char);
}
},
commentEndDash: function () {
var char = this.consume();
if (char === '-') {
this.transitionTo("commentEnd" /* commentEnd */);
}
else {
this.delegate.appendToCommentData('-' + char);
this.transitionTo("comment" /* comment */);
}
},
commentEnd: function () {
var char = this.consume();
if (char === '>') {
this.delegate.finishComment();
this.transitionTo("beforeData" /* beforeData */);
}
else {
this.delegate.appendToCommentData('--' + char);
this.transitionTo("comment" /* comment */);
}
},
tagName: function () {
var char = this.consume();
if (isSpace(char)) {
this.transitionTo("beforeAttributeName" /* beforeAttributeName */);
}
else if (char === '/') {
this.transitionTo("selfClosingStartTag" /* selfClosingStartTag */);
}
else if (char === '>') {
this.delegate.finishTag();
this.transitionTo("beforeData" /* beforeData */);
}
else {
this.appendToTagName(char);
}
},
endTagName: function () {
var char = this.consume();
if (isSpace(char)) {
this.transitionTo("beforeAttributeName" /* beforeAttributeName */);
this.tagNameBuffer = '';
}
else if (char === '/') {
this.transitionTo("selfClosingStartTag" /* selfClosingStartTag */);
this.tagNameBuffer = '';
}
else if (char === '>') {
this.delegate.finishTag();
this.transitionTo("beforeData" /* beforeData */);
this.tagNameBuffer = '';
}
else {
this.appendToTagName(char);
}
},
beforeAttributeName: function () {
var char = this.peek();
if (isSpace(char)) {
this.consume();
return;
}
else if (char === '/') {
this.transitionTo("selfClosingStartTag" /* selfClosingStartTag */);
this.consume();
}
else if (char === '>') {
this.consume();
this.delegate.finishTag();
this.transitionTo("beforeData" /* beforeData */);
}
else if (char === '=') {
this.delegate.reportSyntaxError('attribute name cannot start with equals sign');
this.transitionTo("attributeName" /* attributeName */);
this.delegate.beginAttribute();
this.consume();
this.delegate.appendToAttributeName(char);
}
else {
this.transitionTo("attributeName" /* attributeName */);
this.delegate.beginAttribute();
}
},
attributeName: function () {
var char = this.peek();
if (isSpace(char)) {
this.transitionTo("afterAttributeName" /* afterAttributeName */);
this.consume();
}
else if (char === '/') {
this.delegate.beginAttributeValue(false);
this.delegate.finishAttributeValue();
this.consume();
this.transitionTo("selfClosingStartTag" /* selfClosingStartTag */);
}
else if (char === '=') {
this.transitionTo("beforeAttributeValue" /* beforeAttributeValue */);
this.consume();
}
else if (char === '>') {
this.delegate.beginAttributeValue(false);
this.delegate.finishAttributeValue();
this.consume();
this.delegate.finishTag();
this.transitionTo("beforeData" /* beforeData */);
}
else if (char === '"' || char === "'" || char === '<') {
this.delegate.reportSyntaxError(char + ' is not a valid character within attribute names');
this.consume();
this.delegate.appendToAttributeName(char);
}
else {
this.consume();
this.delegate.appendToAttributeName(char);
}
},
afterAttributeName: function () {
var char = this.peek();
if (isSpace(char)) {
this.consume();
return;
}
else if (char === '/') {
this.delegate.beginAttributeValue(false);
this.delegate.finishAttributeValue();
this.consume();
this.transitionTo("selfClosingStartTag" /* selfClosingStartTag */);
}
else if (char === '=') {
this.consume();
this.transitionTo("beforeAttributeValue" /* beforeAttributeValue */);
}
else if (char === '>') {
this.delegate.beginAttributeValue(false);
this.delegate.finishAttributeValue();
this.consume();
this.delegate.finishTag();
this.transitionTo("beforeData" /* beforeData */);
}
else {
this.delegate.beginAttributeValue(false);
this.delegate.finishAttributeValue();
this.transitionTo("attributeName" /* attributeName */);
this.delegate.beginAttribute();
this.consume();
this.delegate.appendToAttributeName(char);
}
},
beforeAttributeValue: function () {
var char = this.peek();
if (isSpace(char)) {
this.consume();
}
else if (char === '"') {
this.transitionTo("attributeValueDoubleQuoted" /* attributeValueDoubleQuoted */);
this.delegate.beginAttributeValue(true);
this.consume();
}
else if (char === "'") {
this.transitionTo("attributeValueSingleQuoted" /* attributeValueSingleQuoted */);
this.delegate.beginAttributeValue(true);
this.consume();
}
else if (char === '>') {
this.delegate.beginAttributeValue(false);
this.delegate.finishAttributeValue();
this.consume();
this.delegate.finishTag();
this.transitionTo("beforeData" /* beforeData */);
}
else {
this.transitionTo("attributeValueUnquoted" /* attributeValueUnquoted */);
this.delegate.beginAttributeValue(false);
this.consume();
this.delegate.appendToAttributeValue(char);
}
},
attributeValueDoubleQuoted: function () {
var char = this.consume();
if (char === '"') {
this.delegate.finishAttributeValue();
this.transitionTo("afterAttributeValueQuoted" /* afterAttributeValueQuoted */);
}
else if (char === '&') {
this.delegate.appendToAttributeValue(this.consumeCharRef() || '&');
}
else {
this.delegate.appendToAttributeValue(char);
}
},
attributeValueSingleQuoted: function () {
var char = this.consume();
if (char === "'") {
this.delegate.finishAttributeValue();
this.transitionTo("afterAttributeValueQuoted" /* afterAttributeValueQuoted */);
}
else if (char === '&') {
this.delegate.appendToAttributeValue(this.consumeCharRef() || '&');
}
else {
this.delegate.appendToAttributeValue(char);
}
},
attributeValueUnquoted: function () {
var char = this.peek();
if (isSpace(char)) {
this.delegate.finishAttributeValue();
this.consume();
this.transitionTo("beforeAttributeName" /* beforeAttributeName */);
}
else if (char === '/') {
this.delegate.finishAttributeValue();
this.consume();
this.transitionTo("selfClosingStartTag" /* selfClosingStartTag */);
}
else if (char === '&') {
this.consume();
this.delegate.appendToAttributeValue(this.consumeCharRef() || '&');
}
else if (char === '>') {
this.delegate.finishAttributeValue();
this.consume();
this.delegate.finishTag();
this.transitionTo("beforeData" /* beforeData */);
}
else {
this.consume();
this.delegate.appendToAttributeValue(char);
}
},
afterAttributeValueQuoted: function () {
var char = this.peek();
if (isSpace(char)) {
this.consume();
this.transitionTo("beforeAttributeName" /* beforeAttributeName */);
}
else if (char === '/') {
this.consume();
this.transitionTo("selfClosingStartTag" /* selfClosingStartTag */);
}
else if (char === '>') {
this.consume();
this.delegate.finishTag();
this.transitionTo("beforeData" /* beforeData */);
}
else {
this.transitionTo("beforeAttributeName" /* beforeAttributeName */);
}
},
selfClosingStartTag: function () {
var char = this.peek();
if (char === '>') {
this.consume();
this.delegate.markTagAsSelfClosing();
this.delegate.finishTag();
this.transitionTo("beforeData" /* beforeData */);
}
else {
this.transitionTo("beforeAttributeName" /* beforeAttributeName */);
}
},
endTagOpen: function () {
var char = this.consume();
if (char === '@' || char === ':' || isAlpha(char)) {
this.transitionTo("endTagName" /* endTagName */);
this.tagNameBuffer = '';
this.delegate.beginEndTag();
this.appendToTagName(char);
}
}
};
this.reset();
}
EventedTokenizer.prototype.reset = function () {
this.transitionTo("beforeData" /* beforeData */);
this.input = '';
this.tagNameBuffer = '';
this.index = 0;
this.line = 1;
this.column = 0;
this.delegate.reset();
};
EventedTokenizer.prototype.transitionTo = function (state) {
this.state = state;
};
EventedTokenizer.prototype.tokenize = function (input) {
this.reset();
this.tokenizePart(input);
this.tokenizeEOF();
};
EventedTokenizer.prototype.tokenizePart = function (input) {
this.input += preprocessInput(input);
while (this.index < this.input.length) {
var handler = this.states[this.state];
if (handler !== undefined) {
handler.call(this);
}
else {
throw new Error("unhandled state " + this.state);
}
}
};
EventedTokenizer.prototype.tokenizeEOF = function () {
this.flushData();
};
EventedTokenizer.prototype.flushData = function () {
if (this.state === 'data') {
this.delegate.finishData();
this.transitionTo("beforeData" /* beforeData */);
}
};
EventedTokenizer.prototype.peek = function () {
return this.input.charAt(this.index);
};
EventedTokenizer.prototype.consume = function () {
var char = this.peek();
this.index++;
if (char === '\n') {
this.line++;
this.column = 0;
}
else {
this.column++;
}
return char;
};
EventedTokenizer.prototype.consumeCharRef = function () {
var endIndex = this.input.indexOf(';', this.index);
if (endIndex === -1) {
return;
}
var entity = this.input.slice(this.index, endIndex);
var chars = this.entityParser.parse(entity);
if (chars) {
var count = entity.length;
// consume the entity chars
while (count) {
this.consume();
count--;
}
// consume the `;`
this.consume();
return chars;
}
};
EventedTokenizer.prototype.markTagStart = function () {
this.delegate.tagOpen();
};
EventedTokenizer.prototype.appendToTagName = function (char) {
this.tagNameBuffer += char;
this.delegate.appendToTagName(char);
};
EventedTokenizer.prototype.isIgnoredEndTag = function () {
var tag = this.tagNameBuffer;
return (tag === 'title' && this.input.substring(this.index, this.index + 8) !== '</title>') ||
(tag === 'style' && this.input.substring(this.index, this.index + 8) !== '</style>') ||
(tag === 'script' && this.input.substring(this.index, this.index + 9) !== '</script>');
};
return EventedTokenizer;
}());
var Tokenizer = /** @class */ (function () {
function Tokenizer(entityParser, options) {
if (options === void 0) { options = {}; }
this.options = options;
this.token = null;
this.startLine = 1;
this.startColumn = 0;
this.tokens = [];
this.tokenizer = new EventedTokenizer(this, entityParser, options.mode);
this._currentAttribute = undefined;
}
Tokenizer.prototype.tokenize = function (input) {
this.tokens = [];
this.tokenizer.tokenize(input);
return this.tokens;
};
Tokenizer.prototype.tokenizePart = function (input) {
this.tokens = [];
this.tokenizer.tokenizePart(input);
return this.tokens;
};
Tokenizer.prototype.tokenizeEOF = function () {
this.tokens = [];
this.tokenizer.tokenizeEOF();
return this.tokens[0];
};
Tokenizer.prototype.reset = function () {
this.token = null;
this.startLine = 1;
this.startColumn = 0;
};
Tokenizer.prototype.current = function () {
var token = this.token;
if (token === null) {
throw new Error('token was unexpectedly null');
}
if (arguments.length === 0) {
return token;
}
for (var i = 0; i < arguments.length; i++) {
if (token.type === arguments[i]) {
return token;
}
}
throw new Error("token type was unexpectedly " + token.type);
};
Tokenizer.prototype.push = function (token) {
this.token = token;
this.tokens.push(token);
};
Tokenizer.prototype.currentAttribute = function () {
return this._currentAttribute;
};
Tokenizer.prototype.addLocInfo = function () {
if (this.options.loc) {
this.current().loc = {
start: {
line: this.startLine,
column: this.startColumn
},
end: {
line: this.tokenizer.line,
column: this.tokenizer.column
}
};
}
this.startLine = this.tokenizer.line;
this.startColumn = this.tokenizer.column;
};
// Data
Tokenizer.prototype.beginDoctype = function () {
this.push({
type: "Doctype" /* Doctype */,
name: '',
});
};
Tokenizer.prototype.appendToDoctypeName = function (char) {
this.current("Doctype" /* Doctype */).name += char;
};
Tokenizer.prototype.appendToDoctypePublicIdentifier = function (char) {
var doctype = this.current("Doctype" /* Doctype */);
if (doctype.publicIdentifier === undefined) {
doctype.publicIdentifier = char;
}
else {
doctype.publicIdentifier += char;
}
};
Tokenizer.prototype.appendToDoctypeSystemIdentifier = function (char) {
var doctype = this.current("Doctype" /* Doctype */);
if (doctype.systemIdentifier === undefined) {
doctype.systemIdentifier = char;
}
else {
doctype.systemIdentifier += char;
}
};
Tokenizer.prototype.endDoctype = function () {
this.addLocInfo();
};
Tokenizer.prototype.beginData = function () {
this.push({
type: "Chars" /* Chars */,
chars: ''
});
};
Tokenizer.prototype.appendToData = function (char) {
this.current("Chars" /* Chars */).chars += char;
};
Tokenizer.prototype.finishData = function () {
this.addLocInfo();
};
// Comment
Tokenizer.prototype.beginComment = function () {
this.push({
type: "Comment" /* Comment */,
chars: ''
});
};
Tokenizer.prototype.appendToCommentData = function (char) {
this.current("Comment" /* Comment */).chars += char;
};
Tokenizer.prototype.finishComment = function () {
this.addLocInfo();
};
// Tags - basic
Tokenizer.prototype.tagOpen = function () { };
Tokenizer.prototype.beginStartTag = function () {
this.push({
type: "StartTag" /* StartTag */,
tagName: '',
attributes: [],
selfClosing: false
});
};
Tokenizer.prototype.beginEndTag = function () {
this.push({
type: "EndTag" /* EndTag */,
tagName: ''
});
};
Tokenizer.prototype.finishTag = function () {
this.addLocInfo();
};
Tokenizer.prototype.markTagAsSelfClosing = function () {
this.current("StartTag" /* StartTag */).selfClosing = true;
};
// Tags - name
Tokenizer.prototype.appendToTagName = function (char) {
this.current("StartTag" /* StartTag */, "EndTag" /* EndTag */).tagName += char;
};
// Tags - attributes
Tokenizer.prototype.beginAttribute = function () {
this._currentAttribute = ['', '', false];
};
Tokenizer.prototype.appendToAttributeName = function (char) {
this.currentAttribute()[0] += char;
};
Tokenizer.prototype.beginAttributeValue = function (isQuoted) {
this.currentAttribute()[2] = isQuoted;
};
Tokenizer.prototype.appendToAttributeValue = function (char) {
this.currentAttribute()[1] += char;
};
Tokenizer.prototype.finishAttributeValue = function () {
this.current("StartTag" /* StartTag */).attributes.push(this._currentAttribute);
};
Tokenizer.prototype.reportSyntaxError = function (message) {
this.current().syntaxError = message;
};
return Tokenizer;
}());
function tokenize(input, options) {
var tokenizer = new Tokenizer(new EntityParser(namedCharRefs), options);
return tokenizer.tokenize(input);
}
// EXTERNAL MODULE: ./node_modules/fast-deep-equal/es6/index.js
var es6 = __webpack_require__(5619);
var es6_default = /*#__PURE__*/__webpack_require__.n(es6);
;// CONCATENATED MODULE: external ["wp","htmlEntities"]
var external_wp_htmlEntities_namespaceObject = window["wp"]["htmlEntities"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/validation/logger.js
/**
* @typedef LoggerItem
* @property {Function} log Which logger recorded the message
* @property {Array<any>} args White arguments were supplied to the logger
*/
function createLogger() {
/**
* Creates a log handler with block validation prefix.
*
* @param {Function} logger Original logger function.
*
* @return {Function} Augmented logger function.
*/
function createLogHandler(logger) {
let log = function (message) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return logger('Block validation: ' + message, ...args);
}; // In test environments, pre-process string substitutions to improve
// readability of error messages. We'd prefer to avoid pulling in this
// dependency in runtime environments, and it can be dropped by a combo
// of Webpack env substitution + UglifyJS dead code elimination.
if (false) {}
return log;
}
return {
// eslint-disable-next-line no-console
error: createLogHandler(console.error),
// eslint-disable-next-line no-console
warning: createLogHandler(console.warn),
getItems() {
return [];
}
};
}
function createQueuedLogger() {
/**
* The list of enqueued log actions to print.
*
* @type {Array<LoggerItem>}
*/
const queue = [];
const logger = createLogger();
return {
error() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
queue.push({
log: logger.error,
args
});
},
warning() {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
queue.push({
log: logger.warning,
args
});
},
getItems() {
return queue;
}
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/validation/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/** @typedef {import('../parser').WPBlock} WPBlock */
/** @typedef {import('../registration').WPBlockType} WPBlockType */
/** @typedef {import('./logger').LoggerItem} LoggerItem */
const identity = x => x;
/**
* Globally matches any consecutive whitespace
*
* @type {RegExp}
*/
const REGEXP_WHITESPACE = /[\t\n\r\v\f ]+/g;
/**
* Matches a string containing only whitespace
*
* @type {RegExp}
*/
const REGEXP_ONLY_WHITESPACE = /^[\t\n\r\v\f ]*$/;
/**
* Matches a CSS URL type value
*
* @type {RegExp}
*/
const REGEXP_STYLE_URL_TYPE = /^url\s*\(['"\s]*(.*?)['"\s]*\)$/;
/**
* Boolean attributes are attributes whose presence as being assigned is
* meaningful, even if only empty.
*
* See: https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#boolean-attributes
* Extracted from: https://html.spec.whatwg.org/multipage/indices.html#attributes-3
*
* Object.keys( Array.from( document.querySelectorAll( '#attributes-1 > tbody > tr' ) )
* .filter( ( tr ) => tr.lastChild.textContent.indexOf( 'Boolean attribute' ) !== -1 )
* .reduce( ( result, tr ) => Object.assign( result, {
* [ tr.firstChild.textContent.trim() ]: true
* } ), {} ) ).sort();
*
* @type {Array}
*/
const BOOLEAN_ATTRIBUTES = ['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
* valid enumerated value.
*
* See: https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#enumerated-attribute
* Extracted from: https://html.spec.whatwg.org/multipage/indices.html#attributes-3
*
* Object.keys( Array.from( document.querySelectorAll( '#attributes-1 > tbody > tr' ) )
* .filter( ( tr ) => /^("(.+?)";?\s*)+/.test( tr.lastChild.textContent.trim() ) )
* .reduce( ( result, tr ) => Object.assign( result, {
* [ tr.firstChild.textContent.trim() ]: true
* } ), {} ) ).sort();
*
* @type {Array}
*/
const ENUMERATED_ATTRIBUTES = ['autocapitalize', 'autocomplete', 'charset', 'contenteditable', 'crossorigin', 'decoding', 'dir', 'draggable', 'enctype', 'formenctype', 'formmethod', 'http-equiv', 'inputmode', 'kind', 'method', 'preload', 'scope', 'shape', 'spellcheck', 'translate', 'type', 'wrap'];
/**
* Meaningful attributes are those who cannot be safely ignored when omitted in
* one HTML markup string and not another.
*
* @type {Array}
*/
const MEANINGFUL_ATTRIBUTES = [...BOOLEAN_ATTRIBUTES, ...ENUMERATED_ATTRIBUTES];
/**
* Array of functions which receive a text string on which to apply normalizing
* behavior for consideration in text token equivalence, carefully ordered from
* least-to-most expensive operations.
*
* @type {Array}
*/
const TEXT_NORMALIZATIONS = [identity, getTextWithCollapsedWhitespace];
/**
* Regular expression matching a named character reference. In lieu of bundling
* a full set of references, the pattern covers the minimal necessary to test
* positively against the full set.
*
* "The ampersand must be followed by one of the names given in the named
* character references section, using the same case."
*
* Tested aginst "12.5 Named character references":
*
* ```
* const references = Array.from( document.querySelectorAll(
* '#named-character-references-table tr[id^=entity-] td:first-child'
* ) ).map( ( code ) => code.textContent )
* references.every( ( reference ) => /^[\da-z]+$/i.test( reference ) )
* ```
*
* @see https://html.spec.whatwg.org/multipage/syntax.html#character-references
* @see https://html.spec.whatwg.org/multipage/named-characters.html#named-character-references
*
* @type {RegExp}
*/
const REGEXP_NAMED_CHARACTER_REFERENCE = /^[\da-z]+$/i;
/**
* Regular expression matching a decimal character reference.
*
* "The ampersand must be followed by a U+0023 NUMBER SIGN character (#),
* followed by one or more ASCII digits, representing a base-ten integer"
*
* @see https://html.spec.whatwg.org/multipage/syntax.html#character-references
*
* @type {RegExp}
*/
const REGEXP_DECIMAL_CHARACTER_REFERENCE = /^#\d+$/;
/**
* Regular expression matching a hexadecimal character reference.
*
* "The ampersand must be followed by a U+0023 NUMBER SIGN character (#), which
* must be followed by either a U+0078 LATIN SMALL LETTER X character (x) or a
* U+0058 LATIN CAPITAL LETTER X character (X), which must then be followed by
* one or more ASCII hex digits, representing a hexadecimal integer"
*
* @see https://html.spec.whatwg.org/multipage/syntax.html#character-references
*
* @type {RegExp}
*/
const REGEXP_HEXADECIMAL_CHARACTER_REFERENCE = /^#x[\da-f]+$/i;
/**
* Returns true if the given string is a valid character reference segment, or
* false otherwise. The text should be stripped of `&` and `;` demarcations.
*
* @param {string} text Text to test.
*
* @return {boolean} Whether text is valid character reference.
*/
function isValidCharacterReference(text) {
return REGEXP_NAMED_CHARACTER_REFERENCE.test(text) || REGEXP_DECIMAL_CHARACTER_REFERENCE.test(text) || REGEXP_HEXADECIMAL_CHARACTER_REFERENCE.test(text);
}
/**
* Subsitute EntityParser class for `simple-html-tokenizer` which uses the
* implementation of `decodeEntities` from `html-entities`, in order to avoid
* bundling a massive named character reference.
*
* @see https://github.com/tildeio/simple-html-tokenizer/tree/HEAD/src/entity-parser.ts
*/
class DecodeEntityParser {
/**
* Returns a substitute string for an entity string sequence between `&`
* and `;`, or undefined if no substitution should occur.
*
* @param {string} entity Entity fragment discovered in HTML.
*
* @return {string | undefined} Entity substitute value.
*/
parse(entity) {
if (isValidCharacterReference(entity)) {
return (0,external_wp_htmlEntities_namespaceObject.decodeEntities)('&' + entity + ';');
}
}
}
/**
* Given a specified string, returns an array of strings split by consecutive
* whitespace, ignoring leading or trailing whitespace.
*
* @param {string} text Original text.
*
* @return {string[]} Text pieces split on whitespace.
*/
function getTextPiecesSplitOnWhitespace(text) {
return text.trim().split(REGEXP_WHITESPACE);
}
/**
* Given a specified string, returns a new trimmed string where all consecutive
* whitespace is collapsed to a single space.
*
* @param {string} text Original text.
*
* @return {string} Trimmed text with consecutive whitespace collapsed.
*/
function getTextWithCollapsedWhitespace(text) {
// This is an overly simplified whitespace comparison. The specification is
// more prescriptive of whitespace behavior in inline and block contexts.
//
// See: https://medium.com/@patrickbrosset/when-does-white-space-matter-in-html-b90e8a7cdd33
return getTextPiecesSplitOnWhitespace(text).join(' ');
}
/**
* Returns attribute pairs of the given StartTag token, including only pairs
* where the value is non-empty or the attribute is a boolean attribute, an
* enumerated attribute, or a custom data- attribute.
*
* @see MEANINGFUL_ATTRIBUTES
*
* @param {Object} token StartTag token.
*
* @return {Array[]} Attribute pairs.
*/
function getMeaningfulAttributePairs(token) {
return token.attributes.filter(pair => {
const [key, value] = pair;
return value || key.indexOf('data-') === 0 || MEANINGFUL_ATTRIBUTES.includes(key);
});
}
/**
* Returns true if two text tokens (with `chars` property) are equivalent, or
* false otherwise.
*
* @param {Object} actual Actual token.
* @param {Object} expected Expected token.
* @param {Object} logger Validation logger object.
*
* @return {boolean} Whether two text tokens are equivalent.
*/
function isEquivalentTextTokens(actual, expected) {
let logger = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : createLogger();
// This function is intentionally written as syntactically "ugly" as a hot
// path optimization. Text is progressively normalized in order from least-
// to-most operationally expensive, until the earliest point at which text
// can be confidently inferred as being equal.
let actualChars = actual.chars;
let expectedChars = expected.chars;
for (let i = 0; i < TEXT_NORMALIZATIONS.length; i++) {
const normalize = TEXT_NORMALIZATIONS[i];
actualChars = normalize(actualChars);
expectedChars = normalize(expectedChars);
if (actualChars === expectedChars) {
return true;
}
}
logger.warning('Expected text `%s`, saw `%s`.', expected.chars, actual.chars);
return false;
}
/**
* Given a CSS length value, returns a normalized CSS length value for strict equality
* comparison.
*
* @param {string} value CSS length value.
*
* @return {string} Normalized CSS length value.
*/
function getNormalizedLength(value) {
if (0 === parseFloat(value)) {
return '0';
} // Normalize strings with floats to always include a leading zero.
if (value.indexOf('.') === 0) {
return '0' + value;
}
return value;
}
/**
* Given a style value, returns a normalized style value for strict equality
* comparison.
*
* @param {string} value Style value.
*
* @return {string} Normalized style value.
*/
function getNormalizedStyleValue(value) {
const textPieces = getTextPiecesSplitOnWhitespace(value);
const normalizedPieces = textPieces.map(getNormalizedLength);
const result = normalizedPieces.join(' ');
return result // Normalize URL type to omit whitespace or quotes.
.replace(REGEXP_STYLE_URL_TYPE, 'url($1)');
}
/**
* Given a style attribute string, returns an object of style properties.
*
* @param {string} text Style attribute.
*
* @return {Object} Style properties.
*/
function getStyleProperties(text) {
const pairs = text // Trim ending semicolon (avoid including in split)
.replace(/;?\s*$/, '') // Split on property assignment.
.split(';') // For each property assignment...
.map(style => {
// ...split further into key-value pairs.
const [key, ...valueParts] = style.split(':');
const value = valueParts.join(':');
return [key.trim(), getNormalizedStyleValue(value.trim())];
});
return Object.fromEntries(pairs);
}
/**
* Attribute-specific equality handlers
*
* @type {Object}
*/
const isEqualAttributesOfName = {
class: (actual, expected) => {
// Class matches if members are the same, even if out of order or
// superfluous whitespace between.
const [actualPieces, expectedPieces] = [actual, expected].map(getTextPiecesSplitOnWhitespace);
const actualDiff = actualPieces.filter(c => !expectedPieces.includes(c));
const expectedDiff = expectedPieces.filter(c => !actualPieces.includes(c));
return actualDiff.length === 0 && expectedDiff.length === 0;
},
style: (actual, expected) => {
return es6_default()(...[actual, expected].map(getStyleProperties));
},
// For each boolean attribute, mere presence of attribute in both is enough
// to assume equivalence.
...Object.fromEntries(BOOLEAN_ATTRIBUTES.map(attribute => [attribute, () => true]))
};
/**
* Given two sets of attribute tuples, returns true if the attribute sets are
* equivalent.
*
* @param {Array[]} actual Actual attributes tuples.
* @param {Array[]} expected Expected attributes tuples.
* @param {Object} logger Validation logger object.
*
* @return {boolean} Whether attributes are equivalent.
*/
function isEqualTagAttributePairs(actual, expected) {
let logger = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : createLogger();
// Attributes is tokenized as tuples. Their lengths should match. This also
// avoids us needing to check both attributes sets, since if A has any keys
// which do not exist in B, we know the sets to be different.
if (actual.length !== expected.length) {
logger.warning('Expected attributes %o, instead saw %o.', expected, actual);
return false;
} // Attributes are not guaranteed to occur in the same order. For validating
// actual attributes, first convert the set of expected attribute values to
// an object, for lookup by key.
const expectedAttributes = {};
for (let i = 0; i < expected.length; i++) {
expectedAttributes[expected[i][0].toLowerCase()] = expected[i][1];
}
for (let i = 0; i < actual.length; i++) {
const [name, actualValue] = actual[i];
const nameLower = name.toLowerCase(); // As noted above, if missing member in B, assume different.
if (!expectedAttributes.hasOwnProperty(nameLower)) {
logger.warning('Encountered unexpected attribute `%s`.', name);
return false;
}
const expectedValue = expectedAttributes[nameLower];
const isEqualAttributes = isEqualAttributesOfName[nameLower];
if (isEqualAttributes) {
// Defer custom attribute equality handling.
if (!isEqualAttributes(actualValue, expectedValue)) {
logger.warning('Expected attribute `%s` of value `%s`, saw `%s`.', name, expectedValue, actualValue);
return false;
}
} else if (actualValue !== expectedValue) {
// Otherwise strict inequality should bail.
logger.warning('Expected attribute `%s` of value `%s`, saw `%s`.', name, expectedValue, actualValue);
return false;
}
}
return true;
}
/**
* Token-type-specific equality handlers
*
* @type {Object}
*/
const isEqualTokensOfType = {
StartTag: function (actual, expected) {
let logger = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : createLogger();
if (actual.tagName !== expected.tagName && // Optimization: Use short-circuit evaluation to defer case-
// insensitive check on the assumption that the majority case will
// have exactly equal tag names.
actual.tagName.toLowerCase() !== expected.tagName.toLowerCase()) {
logger.warning('Expected tag name `%s`, instead saw `%s`.', expected.tagName, actual.tagName);
return false;
}
return isEqualTagAttributePairs(...[actual, expected].map(getMeaningfulAttributePairs), logger);
},
Chars: isEquivalentTextTokens,
Comment: isEquivalentTextTokens
};
/**
* Given an array of tokens, returns the first token which is not purely
* whitespace.
*
* Mutates the tokens array.
*
* @param {Object[]} tokens Set of tokens to search.
*
* @return {Object | undefined} Next non-whitespace token.
*/
function getNextNonWhitespaceToken(tokens) {
let token;
while (token = tokens.shift()) {
if (token.type !== 'Chars') {
return token;
}
if (!REGEXP_ONLY_WHITESPACE.test(token.chars)) {
return token;
}
}
}
/**
* Tokenize an HTML string, gracefully handling any errors thrown during
* underlying tokenization.
*
* @param {string} html HTML string to tokenize.
* @param {Object} logger Validation logger object.
*
* @return {Object[]|null} Array of valid tokenized HTML elements, or null on error
*/
function getHTMLTokens(html) {
let logger = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : createLogger();
try {
return new Tokenizer(new DecodeEntityParser()).tokenize(html);
} catch (e) {
logger.warning('Malformed HTML detected: %s', html);
}
return null;
}
/**
* Returns true if the next HTML token closes the current token.
*
* @param {Object} currentToken Current token to compare with.
* @param {Object|undefined} nextToken Next token to compare against.
*
* @return {boolean} true if `nextToken` closes `currentToken`, false otherwise
*/
function isClosedByToken(currentToken, nextToken) {
// Ensure this is a self closed token.
if (!currentToken.selfClosing) {
return false;
} // Check token names and determine if nextToken is the closing tag for currentToken.
if (nextToken && nextToken.tagName === currentToken.tagName && nextToken.type === 'EndTag') {
return true;
}
return false;
}
/**
* Returns true if the given HTML strings are effectively equivalent, or
* false otherwise. Invalid HTML is not considered equivalent, even if the
* strings directly match.
*
* @param {string} actual Actual HTML string.
* @param {string} expected Expected HTML string.
* @param {Object} logger Validation logger object.
*
* @return {boolean} Whether HTML strings are equivalent.
*/
function isEquivalentHTML(actual, expected) {
let logger = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : createLogger();
// Short-circuit if markup is identical.
if (actual === expected) {
return true;
} // Tokenize input content and reserialized save content.
const [actualTokens, expectedTokens] = [actual, expected].map(html => getHTMLTokens(html, logger)); // If either is malformed then stop comparing - the strings are not equivalent.
if (!actualTokens || !expectedTokens) {
return false;
}
let actualToken, expectedToken;
while (actualToken = getNextNonWhitespaceToken(actualTokens)) {
expectedToken = getNextNonWhitespaceToken(expectedTokens); // Inequal if exhausted all expected tokens.
if (!expectedToken) {
logger.warning('Expected end of content, instead saw %o.', actualToken);
return false;
} // Inequal if next non-whitespace token of each set are not same type.
if (actualToken.type !== expectedToken.type) {
logger.warning('Expected token of type `%s` (%o), instead saw `%s` (%o).', expectedToken.type, expectedToken, actualToken.type, actualToken);
return false;
} // Defer custom token type equality handling, otherwise continue and
// assume as equal.
const isEqualTokens = isEqualTokensOfType[actualToken.type];
if (isEqualTokens && !isEqualTokens(actualToken, expectedToken, logger)) {
return false;
} // Peek at the next tokens (actual and expected) to see if they close
// a self-closing tag.
if (isClosedByToken(actualToken, expectedTokens[0])) {
// Consume the next expected token that closes the current actual
// self-closing token.
getNextNonWhitespaceToken(expectedTokens);
} else if (isClosedByToken(expectedToken, actualTokens[0])) {
// Consume the next actual token that closes the current expected
// self-closing token.
getNextNonWhitespaceToken(actualTokens);
}
}
if (expectedToken = getNextNonWhitespaceToken(expectedTokens)) {
// If any non-whitespace tokens remain in expected token set, this
// indicates inequality.
logger.warning('Expected %o, instead saw end of content.', expectedToken);
return false;
}
return true;
}
/**
* Returns an object with `isValid` property set to `true` if the parsed block
* is valid given the input content. A block is considered valid if, when serialized
* with assumed attributes, the content matches the original value. If block is
* invalid, this function returns all validations issues as well.
*
* @param {string|Object} blockTypeOrName Block type.
* @param {Object} attributes Parsed block attributes.
* @param {string} originalBlockContent Original block content.
* @param {Object} logger Validation logger object.
*
* @return {Object} Whether block is valid and contains validation messages.
*/
/**
* Returns an object with `isValid` property set to `true` if the parsed block
* is valid given the input content. A block is considered valid if, when serialized
* with assumed attributes, the content matches the original value. If block is
* invalid, this function returns all validations issues as well.
*
* @param {WPBlock} block block object.
* @param {WPBlockType|string} [blockTypeOrName = block.name] Block type or name, inferred from block if not given.
*
* @return {[boolean,Array<LoggerItem>]} validation results.
*/
function validateBlock(block) {
let blockTypeOrName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : block.name;
const isFallbackBlock = block.name === getFreeformContentHandlerName() || block.name === getUnregisteredTypeHandlerName(); // Shortcut to avoid costly validation.
if (isFallbackBlock) {
return [true, []];
}
const logger = createQueuedLogger();
const blockType = normalizeBlockType(blockTypeOrName);
let generatedBlockContent;
try {
generatedBlockContent = getSaveContent(blockType, block.attributes);
} catch (error) {
logger.error('Block validation failed because an error occurred while generating block content:\n\n%s', error.toString());
return [false, logger.getItems()];
}
const isValid = isEquivalentHTML(block.originalContent, generatedBlockContent, logger);
if (!isValid) {
logger.error('Block validation failed for `%s` (%o).\n\nContent generated by `save` function:\n\n%s\n\nContent retrieved from post body:\n\n%s', blockType.name, blockType, generatedBlockContent, block.originalContent);
}
return [isValid, logger.getItems()];
}
/**
* Returns true if the parsed block is valid given the input content. A block
* is considered valid if, when serialized with assumed attributes, the content
* matches the original value.
*
* Logs to console in development environments when invalid.
*
* @deprecated Use validateBlock instead to avoid data loss.
*
* @param {string|Object} blockTypeOrName Block type.
* @param {Object} attributes Parsed block attributes.
* @param {string} originalBlockContent Original block content.
*
* @return {boolean} Whether block is valid.
*/
function isValidBlockContent(blockTypeOrName, attributes, originalBlockContent) {
external_wp_deprecated_default()('isValidBlockContent introduces opportunity for data loss', {
since: '12.6',
plugin: 'Gutenberg',
alternative: 'validateBlock'
});
const blockType = normalizeBlockType(blockTypeOrName);
const block = {
name: blockType.name,
attributes,
innerBlocks: [],
originalContent: originalBlockContent
};
const [isValid] = validateBlock(block, blockType);
return isValid;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/parser/convert-legacy-block.js
/**
* Convert legacy blocks to their canonical form. This function is used
* both in the parser level for previous content and to convert such blocks
* used in Custom Post Types templates.
*
* @param {string} name The block's name
* @param {Object} attributes The block's attributes
*
* @return {[string, Object]} The block's name and attributes, changed accordingly if a match was found
*/
function convertLegacyBlockNameAndAttributes(name, attributes) {
const newAttributes = { ...attributes
}; // Convert 'core/cover-image' block in existing content to 'core/cover'.
if ('core/cover-image' === name) {
name = 'core/cover';
} // Convert 'core/text' blocks in existing content to 'core/paragraph'.
if ('core/text' === name || 'core/cover-text' === name) {
name = 'core/paragraph';
} // Convert derivative blocks such as 'core/social-link-wordpress' to the
// canonical form 'core/social-link'.
if (name && name.indexOf('core/social-link-') === 0) {
// Capture `social-link-wordpress` into `{"service":"wordpress"}`
newAttributes.service = name.substring(17);
name = 'core/social-link';
} // Convert derivative blocks such as 'core-embed/instagram' to the
// canonical form 'core/embed'.
if (name && name.indexOf('core-embed/') === 0) {
// Capture `core-embed/instagram` into `{"providerNameSlug":"instagram"}`
const providerSlug = name.substring(11);
const deprecated = {
speaker: 'speaker-deck',
polldaddy: 'crowdsignal'
};
newAttributes.providerNameSlug = providerSlug in deprecated ? deprecated[providerSlug] : providerSlug; // This is needed as the `responsive` attribute was passed
// in a different way before the refactoring to block variations.
if (!['amazon-kindle', 'wordpress'].includes(providerSlug)) {
newAttributes.responsive = true;
}
name = 'core/embed';
} // Convert Post Comment blocks in existing content to Comment blocks.
// TODO: Remove these checks when WordPress 6.0 is released.
if (name === 'core/post-comment-author') {
name = 'core/comment-author-name';
}
if (name === 'core/post-comment-content') {
name = 'core/comment-content';
}
if (name === 'core/post-comment-date') {
name = 'core/comment-date';
}
if (name === 'core/comments-query-loop') {
name = 'core/comments';
const {
className = ''
} = newAttributes;
if (!className.includes('wp-block-comments-query-loop')) {
newAttributes.className = ['wp-block-comments-query-loop', className].join(' ');
} // Note that we also had to add a deprecation to the block in order
// for the ID change to work.
}
if (name === 'core/post-comments') {
name = 'core/comments';
newAttributes.legacy = true;
}
return [name, newAttributes];
}
;// CONCATENATED MODULE: ./node_modules/hpq/es/get-path.js
/**
* Given object and string of dot-delimited path segments, returns value at
* path or undefined if path cannot be resolved.
*
* @param object Lookup object
* @param path Path to resolve
* @return Resolved value
*/
function getPath(object, path) {
var segments = path.split('.');
var segment;
while (segment = segments.shift()) {
if (!(segment in object)) {
return;
}
object = object[segment];
}
return object;
}
;// CONCATENATED MODULE: ./node_modules/hpq/es/index.js
/**
* Internal dependencies
*/
/**
* Function returning a DOM document created by `createHTMLDocument`. The same
* document is returned between invocations.
*
* @return DOM document.
*/
var getDocument = function () {
var doc;
return function () {
if (!doc) {
doc = document.implementation.createHTMLDocument('');
}
return doc;
};
}();
/**
* Given a markup string or DOM element, creates an object aligning with the
* shape of the matchers object, or the value returned by the matcher.
*
* @param source Source content
* @param matchers Matcher function or object of matchers
*/
/**
* Given a markup string or DOM element, creates an object aligning with the
* shape of the matchers object, or the value returned by the matcher.
*
* @param source Source content
* @param matchers Matcher function or object of matchers
*/
function parse(source, matchers) {
if (!matchers) {
return;
}
// Coerce to element
if ('string' === typeof source) {
var doc = getDocument();
doc.body.innerHTML = source;
source = doc.body;
}
// Return singular value
if (typeof matchers === 'function') {
return matchers(source);
}
// Bail if we can't handle matchers
if (Object !== matchers.constructor) {
return;
}
// Shape result by matcher object
return Object.keys(matchers).reduce(function (memo, key) {
var inner = matchers[key];
memo[key] = parse(source, inner);
return memo;
}, {});
}
/**
* Generates a function which matches node of type selector, returning an
* attribute by property if the attribute exists. If no selector is passed,
* returns property of the query element.
*
* @param name Property name
* @return Property value
*/
/**
* Generates a function which matches node of type selector, returning an
* attribute by property if the attribute exists. If no selector is passed,
* returns property of the query element.
*
* @param selector Optional selector
* @param name Property name
* @return Property value
*/
function prop(arg1, arg2) {
var name;
var selector;
if (1 === arguments.length) {
name = arg1;
selector = undefined;
} else {
name = arg2;
selector = arg1;
}
return function (node) {
var match = node;
if (selector) {
match = node.querySelector(selector);
}
if (match) {
return getPath(match, name);
}
};
}
/**
* Generates a function which matches node of type selector, returning an
* attribute by name if the attribute exists. If no selector is passed,
* returns attribute of the query element.
*
* @param name Attribute name
* @return Attribute value
*/
/**
* Generates a function which matches node of type selector, returning an
* attribute by name if the attribute exists. If no selector is passed,
* returns attribute of the query element.
*
* @param selector Optional selector
* @param name Attribute name
* @return Attribute value
*/
function attr(arg1, arg2) {
var name;
var selector;
if (1 === arguments.length) {
name = arg1;
selector = undefined;
} else {
name = arg2;
selector = arg1;
}
return function (node) {
var attributes = prop(selector, 'attributes')(node);
if (attributes && Object.prototype.hasOwnProperty.call(attributes, name)) {
return attributes[name].value;
}
};
}
/**
* Convenience for `prop( selector, 'innerHTML' )`.
*
* @see prop()
*
* @param selector Optional selector
* @return Inner HTML
*/
function html(selector) {
return prop(selector, 'innerHTML');
}
/**
* Convenience for `prop( selector, 'textContent' )`.
*
* @see prop()
*
* @param selector Optional selector
* @return Text content
*/
function es_text(selector) {
return prop(selector, 'textContent');
}
/**
* Creates a new matching context by first finding elements matching selector
* using querySelectorAll before then running another `parse` on `matchers`
* scoped to the matched elements.
*
* @see parse()
*
* @param selector Selector to match
* @param matchers Matcher function or object of matchers
* @return Matcher function which returns an array of matched value(s)
*/
function query(selector, matchers) {
return function (node) {
var matches = node.querySelectorAll(selector);
return [].map.call(matches, function (match) {
return parse(match, matchers);
});
};
}
// EXTERNAL MODULE: ./node_modules/memize/index.js
var memize = __webpack_require__(9756);
var memize_default = /*#__PURE__*/__webpack_require__.n(memize);
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/matchers.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function matchers_html(selector, multilineTag) {
return domNode => {
let match = domNode;
if (selector) {
match = domNode.querySelector(selector);
}
if (!match) {
return '';
}
if (multilineTag) {
let value = '';
const length = match.children.length;
for (let index = 0; index < length; index++) {
const child = match.children[index];
if (child.nodeName.toLowerCase() !== multilineTag) {
continue;
}
value += child.outerHTML;
}
return value;
}
return match.innerHTML;
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/node.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* A representation of a single node within a block's rich text value. If
* representing a text node, the value is simply a string of the node value.
* As representing an element node, it is an object of:
*
* 1. `type` (string): Tag name.
* 2. `props` (object): Attributes and children array of WPBlockNode.
*
* @typedef {string|Object} WPBlockNode
*/
/**
* Given a single node and a node type (e.g. `'br'`), returns true if the node
* corresponds to that type, false otherwise.
*
* @param {WPBlockNode} node Block node to test
* @param {string} type Node to type to test against.
*
* @return {boolean} Whether node is of intended type.
*/
function isNodeOfType(node, type) {
external_wp_deprecated_default()('wp.blocks.node.isNodeOfType', {
since: '6.1',
version: '6.3',
link: 'https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/introducing-attributes-and-editable-fields/'
});
return node && node.type === type;
}
/**
* Given an object implementing the NamedNodeMap interface, returns a plain
* object equivalent value of name, value key-value pairs.
*
* @see https://dom.spec.whatwg.org/#interface-namednodemap
*
* @param {NamedNodeMap} nodeMap NamedNodeMap to convert to object.
*
* @return {Object} Object equivalent value of NamedNodeMap.
*/
function getNamedNodeMapAsObject(nodeMap) {
const result = {};
for (let i = 0; i < nodeMap.length; i++) {
const {
name,
value
} = nodeMap[i];
result[name] = value;
}
return result;
}
/**
* Given a DOM Element or Text node, returns an equivalent block node. Throws
* if passed any node type other than element or text.
*
* @throws {TypeError} If non-element/text node is passed.
*
* @param {Node} domNode DOM node to convert.
*
* @return {WPBlockNode} Block node equivalent to DOM node.
*/
function fromDOM(domNode) {
external_wp_deprecated_default()('wp.blocks.node.fromDOM', {
since: '6.1',
version: '6.3',
alternative: 'wp.richText.create',
link: 'https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/introducing-attributes-and-editable-fields/'
});
if (domNode.nodeType === domNode.TEXT_NODE) {
return domNode.nodeValue;
}
if (domNode.nodeType !== domNode.ELEMENT_NODE) {
throw new TypeError('A block node can only be created from a node of type text or ' + 'element.');
}
return {
type: domNode.nodeName.toLowerCase(),
props: { ...getNamedNodeMapAsObject(domNode.attributes),
children: children_fromDOM(domNode.childNodes)
}
};
}
/**
* Given a block node, returns its HTML string representation.
*
* @param {WPBlockNode} node Block node to convert to string.
*
* @return {string} String HTML representation of block node.
*/
function toHTML(node) {
external_wp_deprecated_default()('wp.blocks.node.toHTML', {
since: '6.1',
version: '6.3',
alternative: 'wp.richText.toHTMLString',
link: 'https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/introducing-attributes-and-editable-fields/'
});
return children_toHTML([node]);
}
/**
* Given a selector, returns an hpq matcher generating a WPBlockNode value
* matching the selector result.
*
* @param {string} selector DOM selector.
*
* @return {Function} hpq matcher.
*/
function node_matcher(selector) {
external_wp_deprecated_default()('wp.blocks.node.matcher', {
since: '6.1',
version: '6.3',
alternative: 'html source',
link: 'https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/introducing-attributes-and-editable-fields/'
});
return domNode => {
let match = domNode;
if (selector) {
match = domNode.querySelector(selector);
}
try {
return fromDOM(match);
} catch (error) {
return null;
}
};
}
/**
* Object of utility functions used in managing block attribute values of
* source `node`.
*
* @see https://github.com/WordPress/gutenberg/pull/10439
*
* @deprecated since 4.0. The `node` source should not be used, and can be
* replaced by the `html` source.
*
* @private
*/
/* harmony default export */ var node = ({
isNodeOfType,
fromDOM,
toHTML,
matcher: node_matcher
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/children.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* A representation of a block's rich text value.
*
* @typedef {WPBlockNode[]} WPBlockChildren
*/
/**
* Given block children, returns a serialize-capable WordPress element.
*
* @param {WPBlockChildren} children Block children object to convert.
*
* @return {WPElement} A serialize-capable element.
*/
function getSerializeCapableElement(children) {
// The fact that block children are compatible with the element serializer is
// merely an implementation detail that currently serves to be true, but
// should not be mistaken as being a guarantee on the external API. The
// public API only offers guarantees to work with strings (toHTML) and DOM
// elements (fromDOM), and should provide utilities to manipulate the value
// rather than expect consumers to inspect or construct its shape (concat).
return children;
}
/**
* Given block children, returns an array of block nodes.
*
* @param {WPBlockChildren} children Block children object to convert.
*
* @return {Array<WPBlockNode>} An array of individual block nodes.
*/
function getChildrenArray(children) {
external_wp_deprecated_default()('wp.blocks.children.getChildrenArray', {
since: '6.1',
version: '6.3',
link: 'https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/introducing-attributes-and-editable-fields/'
}); // The fact that block children are compatible with the element serializer
// is merely an implementation detail that currently serves to be true, but
// should not be mistaken as being a guarantee on the external API.
return children;
}
/**
* Given two or more block nodes, returns a new block node representing a
* concatenation of its values.
*
* @param {...WPBlockChildren} blockNodes Block nodes to concatenate.
*
* @return {WPBlockChildren} Concatenated block node.
*/
function concat() {
external_wp_deprecated_default()('wp.blocks.children.concat', {
since: '6.1',
version: '6.3',
alternative: 'wp.richText.concat',
link: 'https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/introducing-attributes-and-editable-fields/'
});
const result = [];
for (var _len = arguments.length, blockNodes = new Array(_len), _key = 0; _key < _len; _key++) {
blockNodes[_key] = arguments[_key];
}
for (let i = 0; i < blockNodes.length; i++) {
const blockNode = Array.isArray(blockNodes[i]) ? blockNodes[i] : [blockNodes[i]];
for (let j = 0; j < blockNode.length; j++) {
const child = blockNode[j];
const canConcatToPreviousString = typeof child === 'string' && typeof result[result.length - 1] === 'string';
if (canConcatToPreviousString) {
result[result.length - 1] += child;
} else {
result.push(child);
}
}
}
return result;
}
/**
* Given an iterable set of DOM nodes, returns equivalent block children.
* Ignores any non-element/text nodes included in set.
*
* @param {Iterable.<Node>} domNodes Iterable set of DOM nodes to convert.
*
* @return {WPBlockChildren} Block children equivalent to DOM nodes.
*/
function children_fromDOM(domNodes) {
external_wp_deprecated_default()('wp.blocks.children.fromDOM', {
since: '6.1',
version: '6.3',
alternative: 'wp.richText.create',
link: 'https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/introducing-attributes-and-editable-fields/'
});
const result = [];
for (let i = 0; i < domNodes.length; i++) {
try {
result.push(fromDOM(domNodes[i]));
} catch (error) {// Simply ignore if DOM node could not be converted.
}
}
return result;
}
/**
* Given a block node, returns its HTML string representation.
*
* @param {WPBlockChildren} children Block node(s) to convert to string.
*
* @return {string} String HTML representation of block node.
*/
function children_toHTML(children) {
external_wp_deprecated_default()('wp.blocks.children.toHTML', {
since: '6.1',
version: '6.3',
alternative: 'wp.richText.toHTMLString',
link: 'https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/introducing-attributes-and-editable-fields/'
});
const element = getSerializeCapableElement(children);
return (0,external_wp_element_namespaceObject.renderToString)(element);
}
/**
* Given a selector, returns an hpq matcher generating a WPBlockChildren value
* matching the selector result.
*
* @param {string} selector DOM selector.
*
* @return {Function} hpq matcher.
*/
function children_matcher(selector) {
external_wp_deprecated_default()('wp.blocks.children.matcher', {
since: '6.1',
version: '6.3',
alternative: 'html source',
link: 'https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/introducing-attributes-and-editable-fields/'
});
return domNode => {
let match = domNode;
if (selector) {
match = domNode.querySelector(selector);
}
if (match) {
return children_fromDOM(match.childNodes);
}
return [];
};
}
/**
* Object of utility functions used in managing block attribute values of
* source `children`.
*
* @see https://github.com/WordPress/gutenberg/pull/10439
*
* @deprecated since 4.0. The `children` source should not be used, and can be
* replaced by the `html` source.
*
* @private
*/
/* harmony default export */ var children = ({
concat,
getChildrenArray,
fromDOM: children_fromDOM,
toHTML: children_toHTML,
matcher: children_matcher
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/parser/get-block-attributes.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Higher-order hpq matcher which enhances an attribute matcher to return true
* or false depending on whether the original matcher returns undefined. This
* is useful for boolean attributes (e.g. disabled) whose attribute values may
* be technically falsey (empty string), though their mere presence should be
* enough to infer as true.
*
* @param {Function} matcher Original hpq matcher.
*
* @return {Function} Enhanced hpq matcher.
*/
const toBooleanAttributeMatcher = matcher => (0,external_wp_compose_namespaceObject.pipe)([matcher, // Expected values from `attr( 'disabled' )`:
//
// <input>
// - Value: `undefined`
// - Transformed: `false`
//
// <input disabled>
// - Value: `''`
// - Transformed: `true`
//
// <input disabled="disabled">
// - Value: `'disabled'`
// - Transformed: `true`
value => value !== undefined]);
/**
* Returns true if value is of the given JSON schema type, or false otherwise.
*
* @see http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.25
*
* @param {*} value Value to test.
* @param {string} type Type to test.
*
* @return {boolean} Whether value is of type.
*/
function isOfType(value, type) {
switch (type) {
case 'string':
return typeof value === 'string';
case 'boolean':
return typeof value === 'boolean';
case 'object':
return !!value && value.constructor === Object;
case 'null':
return value === null;
case 'array':
return Array.isArray(value);
case 'integer':
case 'number':
return typeof value === 'number';
}
return true;
}
/**
* Returns true if value is of an array of given JSON schema types, or false
* otherwise.
*
* @see http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.25
*
* @param {*} value Value to test.
* @param {string[]} types Types to test.
*
* @return {boolean} Whether value is of types.
*/
function isOfTypes(value, types) {
return types.some(type => isOfType(value, type));
}
/**
* Given an attribute key, an attribute's schema, a block's raw content and the
* commentAttributes returns the attribute value depending on its source
* definition of the given attribute key.
*
* @param {string} attributeKey Attribute key.
* @param {Object} attributeSchema Attribute's schema.
* @param {Node} innerDOM Parsed DOM of block's inner HTML.
* @param {Object} commentAttributes Block's comment attributes.
* @param {string} innerHTML Raw HTML from block node's innerHTML property.
*
* @return {*} Attribute value.
*/
function getBlockAttribute(attributeKey, attributeSchema, innerDOM, commentAttributes, innerHTML) {
let value;
switch (attributeSchema.source) {
// An undefined source means that it's an attribute serialized to the
// block's "comment".
case undefined:
value = commentAttributes ? commentAttributes[attributeKey] : undefined;
break;
// raw source means that it's the original raw block content.
case 'raw':
value = innerHTML;
break;
case 'attribute':
case 'property':
case 'html':
case 'text':
case 'children':
case 'node':
case 'query':
case 'tag':
value = parseWithAttributeSchema(innerDOM, attributeSchema);
break;
}
if (!isValidByType(value, attributeSchema.type) || !isValidByEnum(value, attributeSchema.enum)) {
// Reject the value if it is not valid. Reverting to the undefined
// value ensures the default is respected, if applicable.
value = undefined;
}
if (value === undefined) {
value = attributeSchema.default;
}
return value;
}
/**
* Returns true if value is valid per the given block attribute schema type
* definition, or false otherwise.
*
* @see https://json-schema.org/latest/json-schema-validation.html#rfc.section.6.1.1
*
* @param {*} value Value to test.
* @param {?(Array<string>|string)} type Block attribute schema type.
*
* @return {boolean} Whether value is valid.
*/
function isValidByType(value, type) {
return type === undefined || isOfTypes(value, Array.isArray(type) ? type : [type]);
}
/**
* Returns true if value is valid per the given block attribute schema enum
* definition, or false otherwise.
*
* @see https://json-schema.org/latest/json-schema-validation.html#rfc.section.6.1.2
*
* @param {*} value Value to test.
* @param {?Array} enumSet Block attribute schema enum.
*
* @return {boolean} Whether value is valid.
*/
function isValidByEnum(value, enumSet) {
return !Array.isArray(enumSet) || enumSet.includes(value);
}
/**
* Returns an hpq matcher given a source object.
*
* @param {Object} sourceConfig Attribute Source object.
*
* @return {Function} A hpq Matcher.
*/
const matcherFromSource = memize_default()(sourceConfig => {
switch (sourceConfig.source) {
case 'attribute':
let matcher = attr(sourceConfig.selector, sourceConfig.attribute);
if (sourceConfig.type === 'boolean') {
matcher = toBooleanAttributeMatcher(matcher);
}
return matcher;
case 'html':
return matchers_html(sourceConfig.selector, sourceConfig.multiline);
case 'text':
return es_text(sourceConfig.selector);
case 'children':
return children_matcher(sourceConfig.selector);
case 'node':
return node_matcher(sourceConfig.selector);
case 'query':
const subMatchers = (0,external_lodash_namespaceObject.mapValues)(sourceConfig.query, matcherFromSource);
return query(sourceConfig.selector, subMatchers);
case 'tag':
return (0,external_wp_compose_namespaceObject.pipe)([prop(sourceConfig.selector, 'nodeName'), nodeName => nodeName ? nodeName.toLowerCase() : undefined]);
default:
// eslint-disable-next-line no-console
console.error(`Unknown source type "${sourceConfig.source}"`);
}
});
/**
* Parse a HTML string into DOM tree.
*
* @param {string|Node} innerHTML HTML string or already parsed DOM node.
*
* @return {Node} Parsed DOM node.
*/
function parseHtml(innerHTML) {
return parse(innerHTML, h => h);
}
/**
* Given a block's raw content and an attribute's schema returns the attribute's
* value depending on its source.
*
* @param {string|Node} innerHTML Block's raw content.
* @param {Object} attributeSchema Attribute's schema.
*
* @return {*} Attribute value.
*/
function parseWithAttributeSchema(innerHTML, attributeSchema) {
return matcherFromSource(attributeSchema)(parseHtml(innerHTML));
}
/**
* Returns the block attributes of a registered block node given its type.
*
* @param {string|Object} blockTypeOrName Block type or name.
* @param {string|Node} innerHTML Raw block content.
* @param {?Object} attributes Known block attributes (from delimiters).
*
* @return {Object} All block attributes.
*/
function getBlockAttributes(blockTypeOrName, innerHTML) {
let attributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
const doc = parseHtml(innerHTML);
const blockType = normalizeBlockType(blockTypeOrName);
const blockAttributes = (0,external_lodash_namespaceObject.mapValues)(blockType.attributes, (schema, key) => getBlockAttribute(key, schema, doc, attributes, innerHTML));
return (0,external_wp_hooks_namespaceObject.applyFilters)('blocks.getBlockAttributes', blockAttributes, blockType, innerHTML, attributes);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/parser/fix-custom-classname.js
/**
* Internal dependencies
*/
const CLASS_ATTR_SCHEMA = {
type: 'string',
source: 'attribute',
selector: '[data-custom-class-name] > *',
attribute: 'class'
};
/**
* Given an HTML string, returns an array of class names assigned to the root
* element in the markup.
*
* @param {string} innerHTML Markup string from which to extract classes.
*
* @return {string[]} Array of class names assigned to the root element.
*/
function getHTMLRootElementClasses(innerHTML) {
const parsed = parseWithAttributeSchema(`<div data-custom-class-name>${innerHTML}</div>`, CLASS_ATTR_SCHEMA);
return parsed ? parsed.trim().split(/\s+/) : [];
}
/**
* Given a parsed set of block attributes, if the block supports custom class
* names and an unknown class (per the block's serialization behavior) is
* found, the unknown classes are treated as custom classes. This prevents the
* block from being considered as invalid.
*
* @param {Object} blockAttributes Original block attributes.
* @param {Object} blockType Block type settings.
* @param {string} innerHTML Original block markup.
*
* @return {Object} Filtered block attributes.
*/
function fixCustomClassname(blockAttributes, blockType, innerHTML) {
if (hasBlockSupport(blockType, 'customClassName', true)) {
// To determine difference, serialize block given the known set of
// attributes, with the exception of `className`. This will determine
// the default set of classes. From there, any difference in innerHTML
// can be considered as custom classes.
const {
className: omittedClassName,
...attributesSansClassName
} = blockAttributes;
const serialized = getSaveContent(blockType, attributesSansClassName);
const defaultClasses = getHTMLRootElementClasses(serialized);
const actualClasses = getHTMLRootElementClasses(innerHTML);
const customClasses = actualClasses.filter(className => !defaultClasses.includes(className));
if (customClasses.length) {
blockAttributes.className = customClasses.join(' ');
} else if (serialized) {
delete blockAttributes.className;
}
}
return blockAttributes;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/parser/apply-built-in-validation-fixes.js
/**
* Internal dependencies
*/
/**
* Attempts to fix block invalidation by applying build-in validation fixes
* like moving all extra classNames to the className attribute.
*
* @param {WPBlock} block block object.
* @param {import('../registration').WPBlockType} blockType Block type. This is normalize not necessary and
* can be inferred from the block name,
* but it's here for performance reasons.
*
* @return {WPBlock} Fixed block object
*/
function applyBuiltInValidationFixes(block, blockType) {
const updatedBlockAttributes = fixCustomClassname(block.attributes, blockType, block.originalContent);
return { ...block,
attributes: updatedBlockAttributes
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/parser/apply-block-deprecated-versions.js
/**
* Internal dependencies
*/
/**
* Function that takes no arguments and always returns false.
*
* @return {boolean} Always returns false.
*/
function stubFalse() {
return false;
}
/**
* Given a block object, returns a new copy of the block with any applicable
* deprecated migrations applied, or the original block if it was both valid
* and no eligible migrations exist.
*
* @param {import(".").WPBlock} block Parsed and invalid block object.
* @param {import(".").WPRawBlock} rawBlock Raw block object.
* @param {import('../registration').WPBlockType} blockType Block type. This is normalize not necessary and
* can be inferred from the block name,
* but it's here for performance reasons.
*
* @return {import(".").WPBlock} Migrated block object.
*/
function applyBlockDeprecatedVersions(block, rawBlock, blockType) {
const parsedAttributes = rawBlock.attrs;
const {
deprecated: deprecatedDefinitions
} = blockType; // Bail early if there are no registered deprecations to be handled.
if (!deprecatedDefinitions || !deprecatedDefinitions.length) {
return block;
} // By design, blocks lack any sort of version tracking. Instead, to process
// outdated content the system operates a queue out of all the defined
// attribute shapes and tries each definition until the input produces a
// valid result. This mechanism seeks to avoid polluting the user-space with
// machine-specific code. An invalid block is thus a block that could not be
// matched successfully with any of the registered deprecation definitions.
for (let i = 0; i < deprecatedDefinitions.length; i++) {
// A block can opt into a migration even if the block is valid by
// defining `isEligible` on its deprecation. If the block is both valid
// and does not opt to migrate, skip.
const {
isEligible = stubFalse
} = deprecatedDefinitions[i];
if (block.isValid && !isEligible(parsedAttributes, block.innerBlocks)) {
continue;
} // Block type properties which could impact either serialization or
// parsing are not considered in the deprecated block type by default,
// and must be explicitly provided.
const deprecatedBlockType = Object.assign(omit(blockType, DEPRECATED_ENTRY_KEYS), deprecatedDefinitions[i]);
let migratedBlock = { ...block,
attributes: getBlockAttributes(deprecatedBlockType, block.originalContent, parsedAttributes)
}; // Ignore the deprecation if it produces a block which is not valid.
let [isValid] = validateBlock(migratedBlock, deprecatedBlockType); // If the migrated block is not valid initially, try the built-in fixes.
if (!isValid) {
migratedBlock = applyBuiltInValidationFixes(migratedBlock, deprecatedBlockType);
[isValid] = validateBlock(migratedBlock, deprecatedBlockType);
} // An invalid block does not imply incorrect HTML but the fact block
// source information could be lost on re-serialization.
if (!isValid) {
continue;
}
let migratedInnerBlocks = migratedBlock.innerBlocks;
let migratedAttributes = migratedBlock.attributes; // A block may provide custom behavior to assign new attributes and/or
// inner blocks.
const {
migrate
} = deprecatedBlockType;
if (migrate) {
let migrated = migrate(migratedAttributes, block.innerBlocks);
if (!Array.isArray(migrated)) {
migrated = [migrated];
}
[migratedAttributes = parsedAttributes, migratedInnerBlocks = block.innerBlocks] = migrated;
}
block = { ...block,
attributes: migratedAttributes,
innerBlocks: migratedInnerBlocks,
isValid: true,
validationIssues: []
};
}
return block;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/parser/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* The raw structure of a block includes its attributes, inner
* blocks, and inner HTML. It is important to distinguish inner blocks from
* the HTML content of the block as only the latter is relevant for block
* validation and edit operations.
*
* @typedef WPRawBlock
*
* @property {string=} blockName Block name
* @property {Object=} attrs Block raw or comment attributes.
* @property {string} innerHTML HTML content of the block.
* @property {(string|null)[]} innerContent Content without inner blocks.
* @property {WPRawBlock[]} innerBlocks Inner Blocks.
*/
/**
* Fully parsed block object.
*
* @typedef WPBlock
*
* @property {string} name Block name
* @property {Object} attributes Block raw or comment attributes.
* @property {WPBlock[]} innerBlocks Inner Blocks.
* @property {string} originalContent Original content of the block before validation fixes.
* @property {boolean} isValid Whether the block is valid.
* @property {Object[]} validationIssues Validation issues.
* @property {WPRawBlock} [__unstableBlockSource] Un-processed original copy of block if created through parser.
*/
/**
* @typedef {Object} ParseOptions
* @property {boolean?} __unstableSkipMigrationLogs If a block is migrated from a deprecated version, skip logging the migration details.
* @property {boolean?} __unstableSkipAutop Whether to skip autop when processing freeform content.
*/
/**
* Convert legacy blocks to their canonical form. This function is used
* both in the parser level for previous content and to convert such blocks
* used in Custom Post Types templates.
*
* @param {WPRawBlock} rawBlock
*
* @return {WPRawBlock} The block's name and attributes, changed accordingly if a match was found
*/
function convertLegacyBlocks(rawBlock) {
const [correctName, correctedAttributes] = convertLegacyBlockNameAndAttributes(rawBlock.blockName, rawBlock.attrs);
return { ...rawBlock,
blockName: correctName,
attrs: correctedAttributes
};
}
/**
* Normalize the raw block by applying the fallback block name if none given,
* sanitize the parsed HTML...
*
* @param {WPRawBlock} rawBlock The raw block object.
* @param {ParseOptions?} options Extra options for handling block parsing.
*
* @return {WPRawBlock} The normalized block object.
*/
function normalizeRawBlock(rawBlock, options) {
const fallbackBlockName = getFreeformContentHandlerName(); // If the grammar parsing don't produce any block name, use the freeform block.
const rawBlockName = rawBlock.blockName || getFreeformContentHandlerName();
const rawAttributes = rawBlock.attrs || {};
const rawInnerBlocks = rawBlock.innerBlocks || [];
let rawInnerHTML = rawBlock.innerHTML.trim(); // Fallback content may be upgraded from classic content expecting implicit
// automatic paragraphs, so preserve them. Assumes wpautop is idempotent,
// meaning there are no negative consequences to repeated autop calls.
if (rawBlockName === fallbackBlockName && !(options !== null && options !== void 0 && options.__unstableSkipAutop)) {
rawInnerHTML = (0,external_wp_autop_namespaceObject.autop)(rawInnerHTML).trim();
}
return { ...rawBlock,
blockName: rawBlockName,
attrs: rawAttributes,
innerHTML: rawInnerHTML,
innerBlocks: rawInnerBlocks
};
}
/**
* Uses the "unregistered blockType" to create a block object.
*
* @param {WPRawBlock} rawBlock block.
*
* @return {WPRawBlock} The unregistered block object.
*/
function createMissingBlockType(rawBlock) {
const unregisteredFallbackBlock = getUnregisteredTypeHandlerName() || getFreeformContentHandlerName(); // Preserve undelimited content for use by the unregistered type
// handler. A block node's `innerHTML` isn't enough, as that field only
// carries the block's own HTML and not its nested blocks.
const originalUndelimitedContent = serializeRawBlock(rawBlock, {
isCommentDelimited: false
}); // Preserve full block content for use by the unregistered type
// handler, block boundaries included.
const originalContent = serializeRawBlock(rawBlock, {
isCommentDelimited: true
});
return {
blockName: unregisteredFallbackBlock,
attrs: {
originalName: rawBlock.blockName,
originalContent,
originalUndelimitedContent
},
innerHTML: rawBlock.blockName ? originalContent : rawBlock.innerHTML,
innerBlocks: rawBlock.innerBlocks,
innerContent: rawBlock.innerContent
};
}
/**
* Validates a block and wraps with validation meta.
*
* The name here is regrettable but `validateBlock` is already taken.
*
* @param {WPBlock} unvalidatedBlock
* @param {import('../registration').WPBlockType} blockType
* @return {WPBlock} validated block, with auto-fixes if initially invalid
*/
function applyBlockValidation(unvalidatedBlock, blockType) {
// Attempt to validate the block.
const [isValid] = validateBlock(unvalidatedBlock, blockType);
if (isValid) {
return { ...unvalidatedBlock,
isValid,
validationIssues: []
};
} // If the block is invalid, attempt some built-in fixes
// like custom classNames handling.
const fixedBlock = applyBuiltInValidationFixes(unvalidatedBlock, blockType); // Attempt to validate the block once again after the built-in fixes.
const [isFixedValid, validationIssues] = validateBlock(unvalidatedBlock, blockType);
return { ...fixedBlock,
isValid: isFixedValid,
validationIssues
};
}
/**
* Given a raw block returned by grammar parsing, returns a fully parsed block.
*
* @param {WPRawBlock} rawBlock The raw block object.
* @param {ParseOptions} options Extra options for handling block parsing.
*
* @return {WPBlock | undefined} Fully parsed block.
*/
function parseRawBlock(rawBlock, options) {
let normalizedBlock = normalizeRawBlock(rawBlock, options); // During the lifecycle of the project, we renamed some old blocks
// and transformed others to new blocks. To avoid breaking existing content,
// we added this function to properly parse the old content.
normalizedBlock = convertLegacyBlocks(normalizedBlock); // Try finding the type for known block name.
let blockType = getBlockType(normalizedBlock.blockName); // If not blockType is found for the specified name, fallback to the "unregistedBlockType".
if (!blockType) {
normalizedBlock = createMissingBlockType(normalizedBlock);
blockType = getBlockType(normalizedBlock.blockName);
} // If it's an empty freeform block or there's no blockType (no missing block handler)
// Then, just ignore the block.
// It might be a good idea to throw a warning here.
// TODO: I'm unsure about the unregisteredFallbackBlock check,
// it might ignore some dynamic unregistered third party blocks wrongly.
const isFallbackBlock = normalizedBlock.blockName === getFreeformContentHandlerName() || normalizedBlock.blockName === getUnregisteredTypeHandlerName();
if (!blockType || !normalizedBlock.innerHTML && isFallbackBlock) {
return;
} // Parse inner blocks recursively.
const parsedInnerBlocks = normalizedBlock.innerBlocks.map(innerBlock => parseRawBlock(innerBlock, options)) // See https://github.com/WordPress/gutenberg/pull/17164.
.filter(innerBlock => !!innerBlock); // Get the fully parsed block.
const parsedBlock = createBlock(normalizedBlock.blockName, getBlockAttributes(blockType, normalizedBlock.innerHTML, normalizedBlock.attrs), parsedInnerBlocks);
parsedBlock.originalContent = normalizedBlock.innerHTML;
const validatedBlock = applyBlockValidation(parsedBlock, blockType);
const {
validationIssues
} = validatedBlock; // Run the block deprecation and migrations.
// This is performed on both invalid and valid blocks because
// migration using the `migrate` functions should run even
// if the output is deemed valid.
const updatedBlock = applyBlockDeprecatedVersions(validatedBlock, normalizedBlock, blockType);
if (!updatedBlock.isValid) {
// Preserve the original unprocessed version of the block
// that we received (no fixes, no deprecations) so that
// we can save it as close to exactly the same way as
// we loaded it. This is important to avoid corruption
// and data loss caused by block implementations trying
// to process data that isn't fully recognized.
updatedBlock.__unstableBlockSource = rawBlock;
}
if (!validatedBlock.isValid && updatedBlock.isValid && !(options !== null && options !== void 0 && options.__unstableSkipMigrationLogs)) {
/* eslint-disable no-console */
console.groupCollapsed('Updated Block: %s', blockType.name);
console.info('Block successfully updated for `%s` (%o).\n\nNew content generated by `save` function:\n\n%s\n\nContent retrieved from post body:\n\n%s', blockType.name, blockType, getSaveContent(blockType, updatedBlock.attributes), updatedBlock.originalContent);
console.groupEnd();
/* eslint-enable no-console */
} else if (!validatedBlock.isValid && !updatedBlock.isValid) {
validationIssues.forEach(_ref => {
let {
log,
args
} = _ref;
return log(...args);
});
}
return updatedBlock;
}
/**
* Utilizes an optimized token-driven parser based on the Gutenberg grammar spec
* defined through a parsing expression grammar to take advantage of the regular
* cadence provided by block delimiters -- composed syntactically through HTML
* comments -- which, given a general HTML document as an input, returns a block
* list array representation.
*
* This is a recursive-descent parser that scans linearly once through the input
* document. Instead of directly recursing it utilizes a trampoline mechanism to
* prevent stack overflow. This initial pass is mainly interested in separating
* and isolating the blocks serialized in the document and manifestly not in the
* content within the blocks.
*
* @see
* https://developer.wordpress.org/block-editor/packages/packages-block-serialization-default-parser/
*
* @param {string} content The post content.
* @param {ParseOptions} options Extra options for handling block parsing.
*
* @return {Array} Block list.
*/
function parser_parse(content, options) {
return (0,external_wp_blockSerializationDefaultParser_namespaceObject.parse)(content).reduce((accumulator, rawBlock) => {
const block = parseRawBlock(rawBlock, options);
if (block) {
accumulator.push(block);
}
return accumulator;
}, []);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/get-raw-transforms.js
/**
* Internal dependencies
*/
function getRawTransforms() {
return getBlockTransforms('from').filter(_ref => {
let {
type
} = _ref;
return type === 'raw';
}).map(transform => {
return transform.isMatch ? transform : { ...transform,
isMatch: node => transform.selector && node.matches(transform.selector)
};
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/html-to-blocks.js
/**
* Internal dependencies
*/
/**
* Converts HTML directly to blocks. Looks for a matching transform for each
* top-level tag. The HTML should be filtered to not have any text between
* top-level tags and formatted in a way that blocks can handle the HTML.
*
* @param {string} html HTML to convert.
* @param {Function} handler The handler calling htmlToBlocks: either rawHandler
* or pasteHandler.
*
* @return {Array} An array of blocks.
*/
function htmlToBlocks(html, handler) {
const doc = document.implementation.createHTMLDocument('');
doc.body.innerHTML = html;
return Array.from(doc.body.children).flatMap(node => {
const rawTransform = findTransform(getRawTransforms(), _ref => {
let {
isMatch
} = _ref;
return isMatch(node);
});
if (!rawTransform) {
return createBlock( // Should not be hardcoded.
'core/html', getBlockAttributes('core/html', node.outerHTML));
}
const {
transform,
blockName
} = rawTransform;
if (transform) {
return transform(node, handler);
}
return createBlock(blockName, getBlockAttributes(blockName, node.outerHTML));
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/normalise-blocks.js
/**
* WordPress dependencies
*/
function normaliseBlocks(HTML) {
const decuDoc = document.implementation.createHTMLDocument('');
const accuDoc = document.implementation.createHTMLDocument('');
const decu = decuDoc.body;
const accu = accuDoc.body;
decu.innerHTML = HTML;
while (decu.firstChild) {
const node = decu.firstChild; // Text nodes: wrap in a paragraph, or append to previous.
if (node.nodeType === node.TEXT_NODE) {
if ((0,external_wp_dom_namespaceObject.isEmpty)(node)) {
decu.removeChild(node);
} else {
if (!accu.lastChild || accu.lastChild.nodeName !== 'P') {
accu.appendChild(accuDoc.createElement('P'));
}
accu.lastChild.appendChild(node);
} // Element nodes.
} else if (node.nodeType === node.ELEMENT_NODE) {
// BR nodes: create a new paragraph on double, or append to previous.
if (node.nodeName === 'BR') {
if (node.nextSibling && node.nextSibling.nodeName === 'BR') {
accu.appendChild(accuDoc.createElement('P'));
decu.removeChild(node.nextSibling);
} // Don't append to an empty paragraph.
if (accu.lastChild && accu.lastChild.nodeName === 'P' && accu.lastChild.hasChildNodes()) {
accu.lastChild.appendChild(node);
} else {
decu.removeChild(node);
}
} else if (node.nodeName === 'P') {
// Only append non-empty paragraph nodes.
if ((0,external_wp_dom_namespaceObject.isEmpty)(node)) {
decu.removeChild(node);
} else {
accu.appendChild(node);
}
} else if ((0,external_wp_dom_namespaceObject.isPhrasingContent)(node)) {
if (!accu.lastChild || accu.lastChild.nodeName !== 'P') {
accu.appendChild(accuDoc.createElement('P'));
}
accu.lastChild.appendChild(node);
} else {
accu.appendChild(node);
}
} else {
decu.removeChild(node);
}
}
return accu.innerHTML;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/special-comment-converter.js
/**
* WordPress dependencies
*/
/**
* Looks for `<!--nextpage-->` and `<!--more-->` comments and
* replaces them with a custom element representing a future block.
*
* The custom element is a way to bypass the rest of the `raw-handling`
* transforms, which would eliminate other kinds of node with which to carry
* `<!--more-->`'s data: nodes with `data` attributes, empty paragraphs, etc.
*
* The custom element is then expected to be recognized by any registered
* block's `raw` transform.
*
* @param {Node} node The node to be processed.
* @param {Document} doc The document of the node.
* @return {void}
*/
function specialCommentConverter(node, doc) {
if (node.nodeType !== node.COMMENT_NODE) {
return;
}
if (node.nodeValue === 'nextpage') {
(0,external_wp_dom_namespaceObject.replace)(node, createNextpage(doc));
return;
}
if (node.nodeValue.indexOf('more') === 0) {
moreCommentConverter(node, doc);
}
}
/**
* Convert `<!--more-->` as well as the `<!--more Some text-->` variant
* and its `<!--noteaser-->` companion into the custom element
* described in `specialCommentConverter()`.
*
* @param {Node} node The node to be processed.
* @param {Document} doc The document of the node.
* @return {void}
*/
function moreCommentConverter(node, doc) {
// Grab any custom text in the comment.
const customText = node.nodeValue.slice(4).trim();
/*
* When a `<!--more-->` comment is found, we need to look for any
* `<!--noteaser-->` sibling, but it may not be a direct sibling
* (whitespace typically lies in between)
*/
let sibling = node;
let noTeaser = false;
while (sibling = sibling.nextSibling) {
if (sibling.nodeType === sibling.COMMENT_NODE && sibling.nodeValue === 'noteaser') {
noTeaser = true;
(0,external_wp_dom_namespaceObject.remove)(sibling);
break;
}
}
const moreBlock = createMore(customText, noTeaser, doc); // If our `<!--more-->` comment is in the middle of a paragraph, we should
// split the paragraph in two and insert the more block in between. If not,
// the more block will eventually end up being inserted after the paragraph.
if (!node.parentNode || node.parentNode.nodeName !== 'P' || node.parentNode.childNodes.length === 1) {
(0,external_wp_dom_namespaceObject.replace)(node, moreBlock);
} else {
const childNodes = Array.from(node.parentNode.childNodes);
const nodeIndex = childNodes.indexOf(node);
const wrapperNode = node.parentNode.parentNode || doc.body;
const paragraphBuilder = (acc, child) => {
if (!acc) {
acc = doc.createElement('p');
}
acc.appendChild(child);
return acc;
}; // Split the original parent node and insert our more block
[childNodes.slice(0, nodeIndex).reduce(paragraphBuilder, null), moreBlock, childNodes.slice(nodeIndex + 1).reduce(paragraphBuilder, null)].forEach(element => element && wrapperNode.insertBefore(element, node.parentNode)); // Remove the old parent paragraph
(0,external_wp_dom_namespaceObject.remove)(node.parentNode);
}
}
function createMore(customText, noTeaser, doc) {
const node = doc.createElement('wp-block');
node.dataset.block = 'core/more';
if (customText) {
node.dataset.customText = customText;
}
if (noTeaser) {
// "Boolean" data attribute.
node.dataset.noTeaser = '';
}
return node;
}
function createNextpage(doc) {
const node = doc.createElement('wp-block');
node.dataset.block = 'core/nextpage';
return node;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/list-reducer.js
/**
* WordPress dependencies
*/
function isList(node) {
return node.nodeName === 'OL' || node.nodeName === 'UL';
}
function shallowTextContent(element) {
return Array.from(element.childNodes).map(_ref => {
let {
nodeValue = ''
} = _ref;
return nodeValue;
}).join('');
}
function listReducer(node) {
if (!isList(node)) {
return;
}
const list = node;
const prevElement = node.previousElementSibling; // Merge with previous list if:
// * There is a previous list of the same type.
// * There is only one list item.
if (prevElement && prevElement.nodeName === node.nodeName && list.children.length === 1) {
// Move all child nodes, including any text nodes, if any.
while (list.firstChild) {
prevElement.appendChild(list.firstChild);
}
list.parentNode.removeChild(list);
}
const parentElement = node.parentNode; // Nested list with empty parent item.
if (parentElement && parentElement.nodeName === 'LI' && parentElement.children.length === 1 && !/\S/.test(shallowTextContent(parentElement))) {
const parentListItem = parentElement;
const prevListItem = parentListItem.previousElementSibling;
const parentList = parentListItem.parentNode;
if (prevListItem) {
prevListItem.appendChild(list);
parentList.removeChild(parentListItem);
} else {
parentList.parentNode.insertBefore(list, parentList);
parentList.parentNode.removeChild(parentList);
}
} // Invalid: OL/UL > OL/UL.
if (parentElement && isList(parentElement)) {
const prevListItem = node.previousElementSibling;
if (prevListItem) {
prevListItem.appendChild(node);
} else {
(0,external_wp_dom_namespaceObject.unwrap)(node);
}
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/blockquote-normaliser.js
/**
* Internal dependencies
*/
function blockquoteNormaliser(node) {
if (node.nodeName !== 'BLOCKQUOTE') {
return;
}
node.innerHTML = normaliseBlocks(node.innerHTML);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/figure-content-reducer.js
/**
* WordPress dependencies
*/
/**
* Whether or not the given node is figure content.
*
* @param {Node} node The node to check.
* @param {Object} schema The schema to use.
*
* @return {boolean} True if figure content, false if not.
*/
function isFigureContent(node, schema) {
var _schema$figure$childr, _schema$figure;
const tag = node.nodeName.toLowerCase(); // We are looking for tags that can be a child of the figure tag, excluding
// `figcaption` and any phrasing content.
if (tag === 'figcaption' || (0,external_wp_dom_namespaceObject.isTextContent)(node)) {
return false;
}
return tag in ((_schema$figure$childr = schema === null || schema === void 0 ? void 0 : (_schema$figure = schema.figure) === null || _schema$figure === void 0 ? void 0 : _schema$figure.children) !== null && _schema$figure$childr !== void 0 ? _schema$figure$childr : {});
}
/**
* Whether or not the given node can have an anchor.
*
* @param {Node} node The node to check.
* @param {Object} schema The schema to use.
*
* @return {boolean} True if it can, false if not.
*/
function canHaveAnchor(node, schema) {
var _schema$figure$childr2, _schema$figure2, _schema$figure2$child, _schema$figure2$child2;
const tag = node.nodeName.toLowerCase();
return tag in ((_schema$figure$childr2 = schema === null || schema === void 0 ? void 0 : (_schema$figure2 = schema.figure) === null || _schema$figure2 === void 0 ? void 0 : (_schema$figure2$child = _schema$figure2.children) === null || _schema$figure2$child === void 0 ? void 0 : (_schema$figure2$child2 = _schema$figure2$child.a) === null || _schema$figure2$child2 === void 0 ? void 0 : _schema$figure2$child2.children) !== null && _schema$figure$childr2 !== void 0 ? _schema$figure$childr2 : {});
}
/**
* Wraps the given element in a figure element.
*
* @param {Element} element The element to wrap.
* @param {Element} beforeElement The element before which to place the figure.
*/
function wrapFigureContent(element) {
let beforeElement = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : element;
const figure = element.ownerDocument.createElement('figure');
beforeElement.parentNode.insertBefore(figure, beforeElement);
figure.appendChild(element);
}
/**
* This filter takes figure content out of paragraphs, wraps it in a figure
* element, and moves any anchors with it if needed.
*
* @param {Node} node The node to filter.
* @param {Document} doc The document of the node.
* @param {Object} schema The schema to use.
*
* @return {void}
*/
function figureContentReducer(node, doc, schema) {
if (!isFigureContent(node, schema)) {
return;
}
let nodeToInsert = node;
const parentNode = node.parentNode; // If the figure content can have an anchor and its parent is an anchor with
// only the figure content, take the anchor out instead of just the content.
if (canHaveAnchor(node, schema) && parentNode.nodeName === 'A' && parentNode.childNodes.length === 1) {
nodeToInsert = node.parentNode;
}
const wrapper = nodeToInsert.closest('p,div'); // If wrapped in a paragraph or div, only extract if it's aligned or if
// there is no text content.
// Otherwise, if directly at the root, wrap in a figure element.
if (wrapper) {
// In jsdom-jscore, 'node.classList' can be undefined.
// In this case, default to extract as it offers a better UI experience on mobile.
if (!node.classList) {
wrapFigureContent(nodeToInsert, wrapper);
} else if (node.classList.contains('alignright') || node.classList.contains('alignleft') || node.classList.contains('aligncenter') || !wrapper.textContent.trim()) {
wrapFigureContent(nodeToInsert, wrapper);
}
} else if (nodeToInsert.parentNode.nodeName === 'BODY') {
wrapFigureContent(nodeToInsert);
}
}
;// CONCATENATED MODULE: external ["wp","shortcode"]
var external_wp_shortcode_namespaceObject = window["wp"]["shortcode"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/shortcode-converter.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const castArray = maybeArray => Array.isArray(maybeArray) ? maybeArray : [maybeArray];
function segmentHTMLToShortcodeBlock(HTML) {
let lastIndex = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
let excludedBlockNames = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
// Get all matches.
const transformsFrom = getBlockTransforms('from');
const transformation = findTransform(transformsFrom, transform => excludedBlockNames.indexOf(transform.blockName) === -1 && transform.type === 'shortcode' && castArray(transform.tag).some(tag => (0,external_wp_shortcode_namespaceObject.regexp)(tag).test(HTML)));
if (!transformation) {
return [HTML];
}
const transformTags = castArray(transformation.tag);
const transformTag = transformTags.find(tag => (0,external_wp_shortcode_namespaceObject.regexp)(tag).test(HTML));
let match;
const previousIndex = lastIndex;
if (match = (0,external_wp_shortcode_namespaceObject.next)(transformTag, HTML, lastIndex)) {
var _match$shortcode$cont;
lastIndex = match.index + match.content.length;
const beforeHTML = HTML.substr(0, match.index);
const afterHTML = HTML.substr(lastIndex); // If the shortcode content does not contain HTML and the shortcode is
// not on a new line (or in paragraph from Markdown converter),
// consider the shortcode as inline text, and thus skip conversion for
// this segment.
if (!((_match$shortcode$cont = match.shortcode.content) !== null && _match$shortcode$cont !== void 0 && _match$shortcode$cont.includes('<')) && !(/(\n|<p>)\s*$/.test(beforeHTML) && /^\s*(\n|<\/p>)/.test(afterHTML))) {
return segmentHTMLToShortcodeBlock(HTML, lastIndex);
} // If a transformation's `isMatch` predicate fails for the inbound
// shortcode, try again by excluding the current block type.
//
// This is the only call to `segmentHTMLToShortcodeBlock` that should
// ever carry over `excludedBlockNames`. Other calls in the module
// should skip that argument as a way to reset the exclusion state, so
// that one `isMatch` fail in an HTML fragment doesn't prevent any
// valid matches in subsequent fragments.
if (transformation.isMatch && !transformation.isMatch(match.shortcode.attrs)) {
return segmentHTMLToShortcodeBlock(HTML, previousIndex, [...excludedBlockNames, transformation.blockName]);
}
let blocks = [];
if (typeof transformation.transform === 'function') {
// Passing all of `match` as second argument is intentionally broad
// but shouldn't be too relied upon.
//
// See: https://github.com/WordPress/gutenberg/pull/3610#discussion_r152546926
blocks = [].concat(transformation.transform(match.shortcode.attrs, match)); // Applying the built-in fixes can enhance the attributes with missing content like "className".
blocks = blocks.map(block => {
block.originalContent = match.shortcode.content;
return applyBuiltInValidationFixes(block, getBlockType(block.name));
});
} else {
const attributes = Object.fromEntries(Object.entries(transformation.attributes).filter(_ref => {
let [, schema] = _ref;
return schema.shortcode;
}) // Passing all of `match` as second argument is intentionally broad
// but shouldn't be too relied upon.
//
// See: https://github.com/WordPress/gutenberg/pull/3610#discussion_r152546926
.map(_ref2 => {
let [key, schema] = _ref2;
return [key, schema.shortcode(match.shortcode.attrs, match)];
}));
const blockType = getBlockType(transformation.blockName);
if (!blockType) {
return [HTML];
}
const transformationBlockType = { ...blockType,
attributes: transformation.attributes
};
let block = createBlock(transformation.blockName, getBlockAttributes(transformationBlockType, match.shortcode.content, attributes)); // Applying the built-in fixes can enhance the attributes with missing content like "className".
block.originalContent = match.shortcode.content;
block = applyBuiltInValidationFixes(block, transformationBlockType);
blocks = [block];
}
return [...segmentHTMLToShortcodeBlock(beforeHTML), ...blocks, ...segmentHTMLToShortcodeBlock(afterHTML)];
}
return [HTML];
}
/* harmony default export */ var shortcode_converter = (segmentHTMLToShortcodeBlock);
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/utils.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function getBlockContentSchemaFromTransforms(transforms, context) {
const phrasingContentSchema = (0,external_wp_dom_namespaceObject.getPhrasingContentSchema)(context);
const schemaArgs = {
phrasingContentSchema,
isPaste: context === 'paste'
};
const schemas = transforms.map(_ref => {
let {
isMatch,
blockName,
schema
} = _ref;
const hasAnchorSupport = hasBlockSupport(blockName, 'anchor');
schema = typeof schema === 'function' ? schema(schemaArgs) : schema; // If the block does not has anchor support and the transform does not
// provides an isMatch we can return the schema right away.
if (!hasAnchorSupport && !isMatch) {
return schema;
}
return (0,external_lodash_namespaceObject.mapValues)(schema, value => {
let attributes = value.attributes || []; // If the block supports the "anchor" functionality, it needs to keep its ID attribute.
if (hasAnchorSupport) {
attributes = [...attributes, 'id'];
}
return { ...value,
attributes,
isMatch: isMatch ? isMatch : undefined
};
});
});
return (0,external_lodash_namespaceObject.mergeWith)({}, ...schemas, (objValue, srcValue, key) => {
switch (key) {
case 'children':
{
if (objValue === '*' || srcValue === '*') {
return '*';
}
return { ...objValue,
...srcValue
};
}
case 'attributes':
case 'require':
{
return [...(objValue || []), ...(srcValue || [])];
}
case 'isMatch':
{
// If one of the values being merge is undefined (matches everything),
// the result of the merge will be undefined.
if (!objValue || !srcValue) {
return undefined;
} // When merging two isMatch functions, the result is a new function
// that returns if one of the source functions returns true.
return function () {
return objValue(...arguments) || srcValue(...arguments);
};
}
}
});
}
/**
* Gets the block content schema, which is extracted and merged from all
* registered blocks with raw transfroms.
*
* @param {string} context Set to "paste" when in paste context, where the
* schema is more strict.
*
* @return {Object} A complete block content schema.
*/
function getBlockContentSchema(context) {
return getBlockContentSchemaFromTransforms(getRawTransforms(), context);
}
/**
* Checks whether HTML can be considered plain text. That is, it does not contain
* any elements that are not line breaks.
*
* @param {string} HTML The HTML to check.
*
* @return {boolean} Whether the HTML can be considered plain text.
*/
function isPlain(HTML) {
return !/<(?!br[ />])/i.test(HTML);
}
/**
* Given node filters, deeply filters and mutates a NodeList.
*
* @param {NodeList} nodeList The nodeList to filter.
* @param {Array} filters An array of functions that can mutate with the provided node.
* @param {Document} doc The document of the nodeList.
* @param {Object} schema The schema to use.
*/
function deepFilterNodeList(nodeList, filters, doc, schema) {
Array.from(nodeList).forEach(node => {
deepFilterNodeList(node.childNodes, filters, doc, schema);
filters.forEach(item => {
// Make sure the node is still attached to the document.
if (!doc.contains(node)) {
return;
}
item(node, doc, schema);
});
});
}
/**
* Given node filters, deeply filters HTML tags.
* Filters from the deepest nodes to the top.
*
* @param {string} HTML The HTML to filter.
* @param {Array} filters An array of functions that can mutate with the provided node.
* @param {Object} schema The schema to use.
*
* @return {string} The filtered HTML.
*/
function deepFilterHTML(HTML) {
let filters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
let schema = arguments.length > 2 ? arguments[2] : undefined;
const doc = document.implementation.createHTMLDocument('');
doc.body.innerHTML = HTML;
deepFilterNodeList(doc.body.childNodes, filters, doc, schema);
return doc.body.innerHTML;
}
/**
* Gets a sibling within text-level context.
*
* @param {Element} node The subject node.
* @param {string} which "next" or "previous".
*/
function getSibling(node, which) {
const sibling = node[`${which}Sibling`];
if (sibling && (0,external_wp_dom_namespaceObject.isPhrasingContent)(sibling)) {
return sibling;
}
const {
parentNode
} = node;
if (!parentNode || !(0,external_wp_dom_namespaceObject.isPhrasingContent)(parentNode)) {
return;
}
return getSibling(parentNode, which);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function deprecatedGetPhrasingContentSchema(context) {
external_wp_deprecated_default()('wp.blocks.getPhrasingContentSchema', {
since: '5.6',
alternative: 'wp.dom.getPhrasingContentSchema'
});
return (0,external_wp_dom_namespaceObject.getPhrasingContentSchema)(context);
}
/**
* Converts an HTML string to known blocks.
*
* @param {Object} $1
* @param {string} $1.HTML The HTML to convert.
*
* @return {Array} A list of blocks.
*/
function rawHandler(_ref) {
let {
HTML = ''
} = _ref;
// If we detect block delimiters, parse entirely as blocks.
if (HTML.indexOf('<!-- wp:') !== -1) {
return parser_parse(HTML);
} // An array of HTML strings and block objects. The blocks replace matched
// shortcodes.
const pieces = shortcode_converter(HTML);
const blockContentSchema = getBlockContentSchema();
return pieces.map(piece => {
// Already a block from shortcode.
if (typeof piece !== 'string') {
return piece;
} // These filters are essential for some blocks to be able to transform
// from raw HTML. These filters move around some content or add
// additional tags, they do not remove any content.
const filters = [// Needed to adjust invalid lists.
listReducer, // Needed to create more and nextpage blocks.
specialCommentConverter, // Needed to create media blocks.
figureContentReducer, // Needed to create the quote block, which cannot handle text
// without wrapper paragraphs.
blockquoteNormaliser];
piece = deepFilterHTML(piece, filters, blockContentSchema);
piece = normaliseBlocks(piece);
return htmlToBlocks(piece, rawHandler);
}).flat().filter(Boolean);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/comment-remover.js
/**
* WordPress dependencies
*/
/**
* Looks for comments, and removes them.
*
* @param {Node} node The node to be processed.
* @return {void}
*/
function commentRemover(node) {
if (node.nodeType === node.COMMENT_NODE) {
(0,external_wp_dom_namespaceObject.remove)(node);
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/is-inline-content.js
/**
* WordPress dependencies
*/
/**
* Checks if the given node should be considered inline content, optionally
* depending on a context tag.
*
* @param {Node} node Node name.
* @param {string} contextTag Tag name.
*
* @return {boolean} True if the node is inline content, false if nohe.
*/
function isInline(node, contextTag) {
if ((0,external_wp_dom_namespaceObject.isTextContent)(node)) {
return true;
}
if (!contextTag) {
return false;
}
const tag = node.nodeName.toLowerCase();
const inlineAllowedTagGroups = [['ul', 'li', 'ol'], ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']];
return inlineAllowedTagGroups.some(tagGroup => [tag, contextTag].filter(t => !tagGroup.includes(t)).length === 0);
}
function deepCheck(nodes, contextTag) {
return nodes.every(node => isInline(node, contextTag) && deepCheck(Array.from(node.children), contextTag));
}
function isDoubleBR(node) {
return node.nodeName === 'BR' && node.previousSibling && node.previousSibling.nodeName === 'BR';
}
function isInlineContent(HTML, contextTag) {
const doc = document.implementation.createHTMLDocument('');
doc.body.innerHTML = HTML;
const nodes = Array.from(doc.body.children);
return !nodes.some(isDoubleBR) && deepCheck(nodes, contextTag);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/phrasing-content-reducer.js
/**
* WordPress dependencies
*/
function phrasingContentReducer(node, doc) {
// In jsdom-jscore, 'node.style' can be null.
// TODO: Explore fixing this by patching jsdom-jscore.
if (node.nodeName === 'SPAN' && node.style) {
const {
fontWeight,
fontStyle,
textDecorationLine,
textDecoration,
verticalAlign
} = node.style;
if (fontWeight === 'bold' || fontWeight === '700') {
(0,external_wp_dom_namespaceObject.wrap)(doc.createElement('strong'), node);
}
if (fontStyle === 'italic') {
(0,external_wp_dom_namespaceObject.wrap)(doc.createElement('em'), node);
} // Some DOM implementations (Safari, JSDom) don't support
// style.textDecorationLine, so we check style.textDecoration as a
// fallback.
if (textDecorationLine === 'line-through' || textDecoration.includes('line-through')) {
(0,external_wp_dom_namespaceObject.wrap)(doc.createElement('s'), node);
}
if (verticalAlign === 'super') {
(0,external_wp_dom_namespaceObject.wrap)(doc.createElement('sup'), node);
} else if (verticalAlign === 'sub') {
(0,external_wp_dom_namespaceObject.wrap)(doc.createElement('sub'), node);
}
} else if (node.nodeName === 'B') {
node = (0,external_wp_dom_namespaceObject.replaceTag)(node, 'strong');
} else if (node.nodeName === 'I') {
node = (0,external_wp_dom_namespaceObject.replaceTag)(node, 'em');
} else if (node.nodeName === 'A') {
// In jsdom-jscore, 'node.target' can be null.
// TODO: Explore fixing this by patching jsdom-jscore.
if (node.target && node.target.toLowerCase() === '_blank') {
node.rel = 'noreferrer noopener';
} else {
node.removeAttribute('target');
node.removeAttribute('rel');
} // Saves anchor elements name attribute as id
if (node.name && !node.id) {
node.id = node.name;
} // Keeps id only if there is an internal link pointing to it
if (node.id && !node.ownerDocument.querySelector(`[href="#${node.id}"]`)) {
node.removeAttribute('id');
}
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/head-remover.js
function headRemover(node) {
if (node.nodeName !== 'SCRIPT' && node.nodeName !== 'NOSCRIPT' && node.nodeName !== 'TEMPLATE' && node.nodeName !== 'STYLE') {
return;
}
node.parentNode.removeChild(node);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/ms-list-converter.js
/**
* Browser dependencies
*/
const {
parseInt: ms_list_converter_parseInt
} = window;
function ms_list_converter_isList(node) {
return node.nodeName === 'OL' || node.nodeName === 'UL';
}
function msListConverter(node, doc) {
if (node.nodeName !== 'P') {
return;
}
const style = node.getAttribute('style');
if (!style) {
return;
} // Quick check.
if (style.indexOf('mso-list') === -1) {
return;
}
const matches = /mso-list\s*:[^;]+level([0-9]+)/i.exec(style);
if (!matches) {
return;
}
let level = ms_list_converter_parseInt(matches[1], 10) - 1 || 0;
const prevNode = node.previousElementSibling; // Add new list if no previous.
if (!prevNode || !ms_list_converter_isList(prevNode)) {
// See https://html.spec.whatwg.org/multipage/grouping-content.html#attr-ol-type.
const type = node.textContent.trim().slice(0, 1);
const isNumeric = /[1iIaA]/.test(type);
const newListNode = doc.createElement(isNumeric ? 'ol' : 'ul');
if (isNumeric) {
newListNode.setAttribute('type', type);
}
node.parentNode.insertBefore(newListNode, node);
}
const listNode = node.previousElementSibling;
const listType = listNode.nodeName;
const listItem = doc.createElement('li');
let receivingNode = listNode; // Remove the first span with list info.
node.removeChild(node.firstChild); // Add content.
while (node.firstChild) {
listItem.appendChild(node.firstChild);
} // Change pointer depending on indentation level.
while (level--) {
receivingNode = receivingNode.lastChild || receivingNode; // If it's a list, move pointer to the last item.
if (ms_list_converter_isList(receivingNode)) {
receivingNode = receivingNode.lastChild || receivingNode;
}
} // Make sure we append to a list.
if (!ms_list_converter_isList(receivingNode)) {
receivingNode = receivingNode.appendChild(doc.createElement(listType));
} // Append the list item to the list.
receivingNode.appendChild(listItem); // Remove the wrapper paragraph.
node.parentNode.removeChild(node);
}
;// CONCATENATED MODULE: external ["wp","blob"]
var external_wp_blob_namespaceObject = window["wp"]["blob"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/image-corrector.js
/**
* WordPress dependencies
*/
/**
* Browser dependencies
*/
const {
atob,
File
} = window;
function imageCorrector(node) {
if (node.nodeName !== 'IMG') {
return;
}
if (node.src.indexOf('file:') === 0) {
node.src = '';
} // This piece cannot be tested outside a browser env.
if (node.src.indexOf('data:') === 0) {
const [properties, data] = node.src.split(',');
const [type] = properties.slice(5).split(';');
if (!data || !type) {
node.src = '';
return;
}
let decoded; // Can throw DOMException!
try {
decoded = atob(data);
} catch (e) {
node.src = '';
return;
}
const uint8Array = new Uint8Array(decoded.length);
for (let i = 0; i < uint8Array.length; i++) {
uint8Array[i] = decoded.charCodeAt(i);
}
const name = type.replace('/', '.');
const file = new File([uint8Array], name, {
type
});
node.src = (0,external_wp_blob_namespaceObject.createBlobURL)(file);
} // Remove trackers and hardly visible images.
if (node.height === 1 || node.width === 1) {
node.parentNode.removeChild(node);
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/div-normaliser.js
/**
* Internal dependencies
*/
function divNormaliser(node) {
if (node.nodeName !== 'DIV') {
return;
}
node.innerHTML = normaliseBlocks(node.innerHTML);
}
// EXTERNAL MODULE: ./node_modules/showdown/dist/showdown.js
var showdown = __webpack_require__(7308);
var showdown_default = /*#__PURE__*/__webpack_require__.n(showdown);
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/markdown-converter.js
/**
* External dependencies
*/
// Reuse the same showdown converter.
const converter = new (showdown_default()).Converter({
noHeaderId: true,
tables: true,
literalMidWordUnderscores: true,
omitExtraWLInCodeBlocks: true,
simpleLineBreaks: true,
strikethrough: true
});
/**
* Corrects the Slack Markdown variant of the code block.
* If uncorrected, it will be converted to inline code.
*
* @see https://get.slack.help/hc/en-us/articles/202288908-how-can-i-add-formatting-to-my-messages-#code-blocks
*
* @param {string} text The potential Markdown text to correct.
*
* @return {string} The corrected Markdown.
*/
function slackMarkdownVariantCorrector(text) {
return text.replace(/((?:^|\n)```)([^\n`]+)(```(?:$|\n))/, (match, p1, p2, p3) => `${p1}\n${p2}\n${p3}`);
}
function bulletsToAsterisks(text) {
return text.replace(/(^|\n)•( +)/g, '$1*$2');
}
/**
* Converts a piece of text into HTML based on any Markdown present.
* Also decodes any encoded HTML.
*
* @param {string} text The plain text to convert.
*
* @return {string} HTML.
*/
function markdownConverter(text) {
return converter.makeHtml(slackMarkdownVariantCorrector(bulletsToAsterisks(text)));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/iframe-remover.js
/**
* Removes iframes.
*
* @param {Node} node The node to check.
*
* @return {void}
*/
function iframeRemover(node) {
if (node.nodeName === 'IFRAME') {
const text = node.ownerDocument.createTextNode(node.src);
node.parentNode.replaceChild(text, node);
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/google-docs-uid-remover.js
/**
* WordPress dependencies
*/
function googleDocsUIdRemover(node) {
if (!node.id || node.id.indexOf('docs-internal-guid-') !== 0) {
return;
} // Google Docs sometimes wraps the content in a B tag. We don't want to keep
// this.
if (node.tagName === 'B') {
(0,external_wp_dom_namespaceObject.unwrap)(node);
} else {
node.removeAttribute('id');
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/html-formatting-remover.js
/**
* Internal dependencies
*/
function isFormattingSpace(character) {
return character === ' ' || character === '\r' || character === '\n' || character === '\t';
}
/**
* Removes spacing that formats HTML.
*
* @see https://www.w3.org/TR/css-text-3/#white-space-processing
*
* @param {Node} node The node to be processed.
* @return {void}
*/
function htmlFormattingRemover(node) {
if (node.nodeType !== node.TEXT_NODE) {
return;
} // Ignore pre content. Note that this does not use Element#closest due to
// a combination of (a) node may not be Element and (b) node.parentElement
// does not have full support in all browsers (Internet Exporer).
//
// See: https://developer.mozilla.org/en-US/docs/Web/API/Node/parentElement#Browser_compatibility
/** @type {Node?} */
let parent = node;
while (parent = parent.parentNode) {
if (parent.nodeType === parent.ELEMENT_NODE && parent.nodeName === 'PRE') {
return;
}
} // First, replace any sequence of HTML formatting space with a single space.
let newData = node.data.replace(/[ \r\n\t]+/g, ' '); // Remove the leading space if the text element is at the start of a block,
// is preceded by a line break element, or has a space in the previous
// node.
if (newData[0] === ' ') {
const previousSibling = getSibling(node, 'previous');
if (!previousSibling || previousSibling.nodeName === 'BR' || previousSibling.textContent.slice(-1) === ' ') {
newData = newData.slice(1);
}
} // Remove the trailing space if the text element is at the end of a block,
// is succeded by a line break element, or has a space in the next text
// node.
if (newData[newData.length - 1] === ' ') {
const nextSibling = getSibling(node, 'next');
if (!nextSibling || nextSibling.nodeName === 'BR' || nextSibling.nodeType === nextSibling.TEXT_NODE && isFormattingSpace(nextSibling.textContent[0])) {
newData = newData.slice(0, -1);
}
} // If there's no data left, remove the node, so `previousSibling` stays
// accurate. Otherwise, update the node data.
if (!newData) {
node.parentNode.removeChild(node);
} else {
node.data = newData;
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/br-remover.js
/**
* Internal dependencies
*/
/**
* Removes trailing br elements from text-level content.
*
* @param {Element} node Node to check.
*/
function brRemover(node) {
if (node.nodeName !== 'BR') {
return;
}
if (getSibling(node, 'next')) {
return;
}
node.parentNode.removeChild(node);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/empty-paragraph-remover.js
/**
* Removes empty paragraph elements.
*
* @param {Element} node Node to check.
*/
function emptyParagraphRemover(node) {
if (node.nodeName !== 'P') {
return;
}
if (node.hasChildNodes()) {
return;
}
node.parentNode.removeChild(node);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/slack-paragraph-corrector.js
/**
* Replaces Slack paragraph markup with a double line break (later converted to
* a proper paragraph).
*
* @param {Element} node Node to check.
*/
function slackParagraphCorrector(node) {
if (node.nodeName !== 'SPAN') {
return;
}
if (node.getAttribute('data-stringify-type') !== 'paragraph-break') {
return;
}
const {
parentNode
} = node;
parentNode.insertBefore(node.ownerDocument.createElement('br'), node);
parentNode.insertBefore(node.ownerDocument.createElement('br'), node);
parentNode.removeChild(node);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/raw-handling/paste-handler.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Browser dependencies
*/
const {
console: paste_handler_console
} = window;
/**
* Filters HTML to only contain phrasing content.
*
* @param {string} HTML The HTML to filter.
* @param {boolean} preserveWhiteSpace Whether or not to preserve consequent white space.
*
* @return {string} HTML only containing phrasing content.
*/
function filterInlineHTML(HTML, preserveWhiteSpace) {
HTML = deepFilterHTML(HTML, [headRemover, googleDocsUIdRemover, phrasingContentReducer, commentRemover]);
HTML = (0,external_wp_dom_namespaceObject.removeInvalidHTML)(HTML, (0,external_wp_dom_namespaceObject.getPhrasingContentSchema)('paste'), {
inline: true
});
if (!preserveWhiteSpace) {
HTML = deepFilterHTML(HTML, [htmlFormattingRemover, brRemover]);
} // Allows us to ask for this information when we get a report.
paste_handler_console.log('Processed inline HTML:\n\n', HTML);
return HTML;
}
/**
* Converts an HTML string to known blocks. Strips everything else.
*
* @param {Object} options
* @param {string} [options.HTML] The HTML to convert.
* @param {string} [options.plainText] Plain text version.
* @param {string} [options.mode] Handle content as blocks or inline content.
* * 'AUTO': Decide based on the content passed.
* * 'INLINE': Always handle as inline content, and return string.
* * 'BLOCKS': Always handle as blocks, and return array of blocks.
* @param {Array} [options.tagName] The tag into which content will be inserted.
* @param {boolean} [options.preserveWhiteSpace] Whether or not to preserve consequent white space.
*
* @return {Array|string} A list of blocks or a string, depending on `handlerMode`.
*/
function pasteHandler(_ref) {
let {
HTML = '',
plainText = '',
mode = 'AUTO',
tagName,
preserveWhiteSpace
} = _ref;
// First of all, strip any meta tags.
HTML = HTML.replace(/<meta[^>]+>/g, ''); // Strip Windows markers.
HTML = HTML.replace(/^\s*<html[^>]*>\s*<body[^>]*>(?:\s*<!--\s*StartFragment\s*-->)?/i, '');
HTML = HTML.replace(/(?:<!--\s*EndFragment\s*-->\s*)?<\/body>\s*<\/html>\s*$/i, ''); // If we detect block delimiters in HTML, parse entirely as blocks.
if (mode !== 'INLINE') {
// Check plain text if there is no HTML.
const content = HTML ? HTML : plainText;
if (content.indexOf('<!-- wp:') !== -1) {
return parser_parse(content);
}
} // Normalize unicode to use composed characters.
// This is unsupported in IE 11 but it's a nice-to-have feature, not mandatory.
// Not normalizing the content will only affect older browsers and won't
// entirely break the app.
// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize
// See: https://core.trac.wordpress.org/ticket/30130
// See: https://github.com/WordPress/gutenberg/pull/6983#pullrequestreview-125151075
if (String.prototype.normalize) {
HTML = HTML.normalize();
} // Parse Markdown (and encoded HTML) if:
// * There is a plain text version.
// * There is no HTML version, or it has no formatting.
if (plainText && (!HTML || isPlain(HTML))) {
HTML = plainText; // The markdown converter (Showdown) trims whitespace.
if (!/^\s+$/.test(plainText)) {
HTML = markdownConverter(HTML);
} // Switch to inline mode if:
// * The current mode is AUTO.
// * The original plain text had no line breaks.
// * The original plain text was not an HTML paragraph.
// * The converted text is just a paragraph.
if (mode === 'AUTO' && plainText.indexOf('\n') === -1 && plainText.indexOf('<p>') !== 0 && HTML.indexOf('<p>') === 0) {
mode = 'INLINE';
}
}
if (mode === 'INLINE') {
return filterInlineHTML(HTML, preserveWhiteSpace);
} // Must be run before checking if it's inline content.
HTML = deepFilterHTML(HTML, [slackParagraphCorrector]); // An array of HTML strings and block objects. The blocks replace matched
// shortcodes.
const pieces = shortcode_converter(HTML); // The call to shortcodeConverter will always return more than one element
// if shortcodes are matched. The reason is when shortcodes are matched
// empty HTML strings are included.
const hasShortcodes = pieces.length > 1;
if (mode === 'AUTO' && !hasShortcodes && isInlineContent(HTML, tagName)) {
return filterInlineHTML(HTML, preserveWhiteSpace);
}
const phrasingContentSchema = (0,external_wp_dom_namespaceObject.getPhrasingContentSchema)('paste');
const blockContentSchema = getBlockContentSchema('paste');
const blocks = pieces.map(piece => {
// Already a block from shortcode.
if (typeof piece !== 'string') {
return piece;
}
const filters = [googleDocsUIdRemover, msListConverter, headRemover, listReducer, imageCorrector, phrasingContentReducer, specialCommentConverter, commentRemover, iframeRemover, figureContentReducer, blockquoteNormaliser, divNormaliser];
const schema = { ...blockContentSchema,
// Keep top-level phrasing content, normalised by `normaliseBlocks`.
...phrasingContentSchema
};
piece = deepFilterHTML(piece, filters, blockContentSchema);
piece = (0,external_wp_dom_namespaceObject.removeInvalidHTML)(piece, schema);
piece = normaliseBlocks(piece);
piece = deepFilterHTML(piece, [htmlFormattingRemover, brRemover, emptyParagraphRemover], blockContentSchema); // Allows us to ask for this information when we get a report.
paste_handler_console.log('Processed HTML piece:\n\n', piece);
return htmlToBlocks(piece, pasteHandler);
}).flat().filter(Boolean); // If we're allowed to return inline content, and there is only one
// inlineable block, and the original plain text content does not have any
// line breaks, then treat it as inline paste.
if (mode === 'AUTO' && blocks.length === 1 && hasBlockSupport(blocks[0].name, '__unstablePasteTextInline', false)) {
const trimRegex = /^[\n]+|[\n]+$/g; // Don't catch line breaks at the start or end.
const trimmedPlainText = plainText.replace(trimRegex, '');
if (trimmedPlainText !== '' && trimmedPlainText.indexOf('\n') === -1) {
return (0,external_wp_dom_namespaceObject.removeInvalidHTML)(getBlockInnerHTML(blocks[0]), phrasingContentSchema).replace(trimRegex, '');
}
}
return blocks;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/categories.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/** @typedef {import('../store/reducer').WPBlockCategory} WPBlockCategory */
/**
* Returns all the block categories.
* Ignored from documentation as the recommended usage is via useSelect from @wordpress/data.
*
* @ignore
*
* @return {WPBlockCategory[]} Block categories.
*/
function categories_getCategories() {
return (0,external_wp_data_namespaceObject.select)(store).getCategories();
}
/**
* Sets the block categories.
*
* @param {WPBlockCategory[]} categories Block categories.
*
* @example
* ```js
* import { __ } from '@wordpress/i18n';
* import { store as blocksStore, setCategories } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
* import { Button } from '@wordpress/components';
*
* const ExampleComponent = () => {
* // Retrieve the list of current categories.
* const blockCategories = useSelect(
* ( select ) => select( blocksStore ).getCategories(),
* []
* );
*
* return (
* <Button
* onClick={ () => {
* // Add a custom category to the existing list.
* setCategories( [
* ...blockCategories,
* { title: 'Custom Category', slug: 'custom-category' },
* ] );
* } }
* >
* { __( 'Add a new custom block category' ) }
* </Button>
* );
* };
* ```
*/
function categories_setCategories(categories) {
(0,external_wp_data_namespaceObject.dispatch)(store).setCategories(categories);
}
/**
* Updates a category.
*
* @param {string} slug Block category slug.
* @param {WPBlockCategory} category Object containing the category properties
* that should be updated.
*
* @example
* ```js
* import { __ } from '@wordpress/i18n';
* import { updateCategory } from '@wordpress/blocks';
* import { Button } from '@wordpress/components';
*
* const ExampleComponent = () => {
* return (
* <Button
* onClick={ () => {
* updateCategory( 'text', { title: __( 'Written Word' ) } );
* } }
* >
* { __( 'Update Text category title' ) }
* </Button>
* ) ;
* };
* ```
*/
function categories_updateCategory(slug, category) {
(0,external_wp_data_namespaceObject.dispatch)(store).updateCategory(slug, category);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/templates.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Checks whether a list of blocks matches a template by comparing the block names.
*
* @param {Array} blocks Block list.
* @param {Array} template Block template.
*
* @return {boolean} Whether the list of blocks matches a templates.
*/
function doBlocksMatchTemplate() {
let blocks = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
let template = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
return blocks.length === template.length && template.every((_ref, index) => {
let [name,, innerBlocksTemplate] = _ref;
const block = blocks[index];
return name === block.name && doBlocksMatchTemplate(block.innerBlocks, innerBlocksTemplate);
});
}
/**
* Synchronize a block list with a block template.
*
* Synchronizing a block list with a block template means that we loop over the blocks
* keep the block as is if it matches the block at the same position in the template
* (If it has the same name) and if doesn't match, we create a new block based on the template.
* Extra blocks not present in the template are removed.
*
* @param {Array} blocks Block list.
* @param {Array} template Block template.
*
* @return {Array} Updated Block list.
*/
function synchronizeBlocksWithTemplate() {
let blocks = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
let template = arguments.length > 1 ? arguments[1] : undefined;
// If no template is provided, return blocks unmodified.
if (!template) {
return blocks;
}
return template.map((_ref2, index) => {
var _blockType$attributes;
let [name, attributes, innerBlocksTemplate] = _ref2;
const block = blocks[index];
if (block && block.name === name) {
const innerBlocks = synchronizeBlocksWithTemplate(block.innerBlocks, innerBlocksTemplate);
return { ...block,
innerBlocks
};
} // To support old templates that were using the "children" format
// for the attributes using "html" strings now, we normalize the template attributes
// before creating the blocks.
const blockType = getBlockType(name);
const isHTMLAttribute = attributeDefinition => (attributeDefinition === null || attributeDefinition === void 0 ? void 0 : attributeDefinition.source) === 'html';
const isQueryAttribute = attributeDefinition => (attributeDefinition === null || attributeDefinition === void 0 ? void 0 : attributeDefinition.source) === 'query';
const normalizeAttributes = (schema, values) => {
if (!values) {
return {};
}
return Object.fromEntries(Object.entries(values).map(_ref3 => {
let [key, value] = _ref3;
return [key, normalizeAttribute(schema[key], value)];
}));
};
const normalizeAttribute = (definition, value) => {
if (isHTMLAttribute(definition) && Array.isArray(value)) {
// Introduce a deprecated call at this point
// When we're confident that "children" format should be removed from the templates.
return (0,external_wp_element_namespaceObject.renderToString)(value);
}
if (isQueryAttribute(definition) && value) {
return value.map(subValues => {
return normalizeAttributes(definition.query, subValues);
});
}
return value;
};
const normalizedAttributes = normalizeAttributes((_blockType$attributes = blockType === null || blockType === void 0 ? void 0 : blockType.attributes) !== null && _blockType$attributes !== void 0 ? _blockType$attributes : {}, attributes);
let [blockName, blockAttributes] = convertLegacyBlockNameAndAttributes(name, normalizedAttributes); // If a Block is undefined at this point, use the core/missing block as
// a placeholder for a better user experience.
if (undefined === getBlockType(blockName)) {
blockAttributes = {
originalName: name,
originalContent: '',
originalUndelimitedContent: ''
};
blockName = 'core/missing';
}
return createBlock(blockName, blockAttributes, synchronizeBlocksWithTemplate([], innerBlocksTemplate));
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/api/index.js
// The blocktype is the most important concept within the block API. It defines
// all aspects of the block configuration and its interfaces, including `edit`
// and `save`. The transforms specification allows converting one blocktype to
// another through formulas defined by either the source or the destination.
// Switching a blocktype is to be considered a one-way operation implying a
// transformation in the opposite way has to be handled explicitly.
// The block tree is composed of a collection of block nodes. Blocks contained
// within other blocks are called inner blocks. An important design
// consideration is that inner blocks are -- conceptually -- not part of the
// territory established by the parent block that contains them.
//
// This has multiple practical implications: when parsing, we can safely dispose
// of any block boundary found within a block from the innerHTML property when
// transfering to state. Not doing so would have a compounding effect on memory
// and uncertainty over the source of truth. This can be illustrated in how,
// given a tree of `n` nested blocks, the entry node would have to contain the
// actual content of each block while each subsequent block node in the state
// tree would replicate the entire chain `n-1`, meaning the extreme end node
// would have been replicated `n` times as the tree is traversed and would
// generate uncertainty as to which one is to hold the current value of the
// block. For composition, it also means inner blocks can effectively be child
// components whose mechanisms can be shielded from the `edit` implementation
// and just passed along.
// While block transformations account for a specific surface of the API, there
// are also raw transformations which handle arbitrary sources not made out of
// blocks but producing block basaed on various heursitics. This includes
// pasting rich text or HTML data.
// The process of serialization aims to deflate the internal memory of the block
// editor and its state representation back into an HTML valid string. This
// process restores the document integrity and inserts invisible delimiters
// around each block with HTML comment boundaries which can contain any extra
// attributes needed to operate with the block later on.
// Validation is the process of comparing a block source with its output before
// there is any user input or interaction with a block. When this operation
// fails -- for whatever reason -- the block is to be considered invalid. As
// part of validating a block the system will attempt to run the source against
// any provided deprecation definitions.
//
// Worth emphasizing that validation is not a case of whether the markup is
// merely HTML spec-compliant but about how the editor knows to create such
// markup and that its inability to create an identical result can be a strong
// indicator of potential data loss (the invalidation is then a protective
// measure).
//
// The invalidation process can also be deconstructed in phases: 1) validate the
// block exists; 2) validate the source matches the output; 3) validate the
// source matches deprecated outputs; 4) work through the significance of
// differences. These are stacked in a way that favors performance and optimizes
// for the majority of cases. That is to say, the evaluation logic can become
// more sophisticated the further down it goes in the process as the cost is
// accounted for. The first logic checks have to be extremely efficient since
// they will be run for all valid and invalid blocks alike. However, once a
// block is detected as invalid -- failing the three first steps -- it is
// adequate to spend more time determining validity before throwing a conflict.
// Blocks are inherently indifferent about where the data they operate with ends
// up being saved. For example, all blocks can have a static and dynamic aspect
// to them depending on the needs. The static nature of a block is the `save()`
// definition that is meant to be serialized into HTML and which can be left
// void. Any block can also register a `render_callback` on the server, which
// makes its output dynamic either in part or in its totality.
//
// Child blocks are defined as a relationship that builds on top of the inner
// blocks mechanism. A child block is a block node of a particular type that can
// only exist within the inner block boundaries of a specific parent type. This
// allows block authors to compose specific blocks that are not meant to be used
// outside of a specified parent block context. Thus, child blocks extend the
// concept of inner blocks to support a more direct relationship between sets of
// blocks. The addition of parent–child would be a subset of the inner block
// functionality under the premise that certain blocks only make sense as
// children of another block.
// Templates are, in a general sense, a basic collection of block nodes with any
// given set of predefined attributes that are supplied as the initial state of
// an inner blocks group. These nodes can, in turn, contain any number of nested
// blocks within their definition. Templates allow both to specify a default
// state for an editor session or a default set of blocks for any inner block
// implementation within a specific block.
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/deprecated.js
/**
* WordPress dependencies
*/
/**
* A Higher Order Component used to inject BlockContent using context to the
* wrapped component.
*
* @deprecated
*
* @param {WPComponent} OriginalComponent The component to enhance.
* @return {WPComponent} The same component.
*/
function withBlockContentContext(OriginalComponent) {
external_wp_deprecated_default()('wp.blocks.withBlockContentContext', {
since: '6.1'
});
return OriginalComponent;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/blocks/build-module/index.js
// A "block" is the abstract term used to describe units of markup that,
// when composed together, form the content or layout of a page.
// The API for blocks is exposed via `wp.blocks`.
//
// Supported blocks are registered by calling `registerBlockType`. Once registered,
// the block is made available as an option to the editor interface.
//
// Blocks are inferred from the HTML source of a post through a parsing mechanism
// and then stored as objects in state, from which it is then rendered for editing.
}();
(window.wp = window.wp || {}).blocks = __webpack_exports__;
/******/ })()
; block-directory.js 0000666 00000222322 15123355174 0010213 0 ustar 00 /******/ (function() { // webpackBootstrap
/******/ "use strict";
/******/ // The require scope
/******/ var __webpack_require__ = {};
/******/
/************************************************************************/
/******/ /* 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__ = {};
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"store": function() { return /* reexport */ store; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/block-directory/build-module/store/selectors.js
var selectors_namespaceObject = {};
__webpack_require__.r(selectors_namespaceObject);
__webpack_require__.d(selectors_namespaceObject, {
"getDownloadableBlocks": function() { return getDownloadableBlocks; },
"getErrorNoticeForBlock": function() { return getErrorNoticeForBlock; },
"getErrorNotices": function() { return getErrorNotices; },
"getInstalledBlockTypes": function() { return getInstalledBlockTypes; },
"getNewBlockTypes": function() { return getNewBlockTypes; },
"getUnusedBlockTypes": function() { return getUnusedBlockTypes; },
"isInstalling": function() { return isInstalling; },
"isRequestingDownloadableBlocks": function() { return isRequestingDownloadableBlocks; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/block-directory/build-module/store/actions.js
var actions_namespaceObject = {};
__webpack_require__.r(actions_namespaceObject);
__webpack_require__.d(actions_namespaceObject, {
"addInstalledBlockType": function() { return addInstalledBlockType; },
"clearErrorNotice": function() { return clearErrorNotice; },
"fetchDownloadableBlocks": function() { return fetchDownloadableBlocks; },
"installBlockType": function() { return installBlockType; },
"receiveDownloadableBlocks": function() { return receiveDownloadableBlocks; },
"removeInstalledBlockType": function() { return removeInstalledBlockType; },
"setErrorNotice": function() { return setErrorNotice; },
"setIsInstalling": function() { return setIsInstalling; },
"uninstallBlockType": function() { return uninstallBlockType; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/block-directory/build-module/store/resolvers.js
var resolvers_namespaceObject = {};
__webpack_require__.r(resolvers_namespaceObject);
__webpack_require__.d(resolvers_namespaceObject, {
"getDownloadableBlocks": function() { return resolvers_getDownloadableBlocks; }
});
;// CONCATENATED MODULE: external ["wp","element"]
var external_wp_element_namespaceObject = window["wp"]["element"];
;// CONCATENATED MODULE: external ["wp","plugins"]
var external_wp_plugins_namespaceObject = window["wp"]["plugins"];
;// CONCATENATED MODULE: external ["wp","hooks"]
var external_wp_hooks_namespaceObject = window["wp"]["hooks"];
;// CONCATENATED MODULE: external ["wp","blocks"]
var external_wp_blocks_namespaceObject = window["wp"]["blocks"];
;// CONCATENATED MODULE: external ["wp","data"]
var external_wp_data_namespaceObject = window["wp"]["data"];
;// CONCATENATED MODULE: external ["wp","editor"]
var external_wp_editor_namespaceObject = window["wp"]["editor"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/store/reducer.js
/**
* WordPress dependencies
*/
/**
* Reducer returning an array of downloadable blocks.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
const downloadableBlocks = function () {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'FETCH_DOWNLOADABLE_BLOCKS':
return { ...state,
[action.filterValue]: {
isRequesting: true
}
};
case 'RECEIVE_DOWNLOADABLE_BLOCKS':
return { ...state,
[action.filterValue]: {
results: action.downloadableBlocks,
isRequesting: false
}
};
}
return state;
};
/**
* Reducer managing the installation and deletion of blocks.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
const blockManagement = function () {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
installedBlockTypes: [],
isInstalling: {}
};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'ADD_INSTALLED_BLOCK_TYPE':
return { ...state,
installedBlockTypes: [...state.installedBlockTypes, action.item]
};
case 'REMOVE_INSTALLED_BLOCK_TYPE':
return { ...state,
installedBlockTypes: state.installedBlockTypes.filter(blockType => blockType.name !== action.item.name)
};
case 'SET_INSTALLING_BLOCK':
return { ...state,
isInstalling: { ...state.isInstalling,
[action.blockId]: action.isInstalling
}
};
}
return state;
};
/**
* Reducer returning an object of error notices.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
const errorNotices = function () {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'SET_ERROR_NOTICE':
return { ...state,
[action.blockId]: {
message: action.message,
isFatal: action.isFatal
}
};
case 'CLEAR_ERROR_NOTICE':
const {
[action.blockId]: blockId,
...restState
} = state;
return restState;
}
return state;
};
/* harmony default export */ var reducer = ((0,external_wp_data_namespaceObject.combineReducers)({
downloadableBlocks,
blockManagement,
errorNotices
}));
;// CONCATENATED MODULE: external ["wp","blockEditor"]
var external_wp_blockEditor_namespaceObject = window["wp"]["blockEditor"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/store/utils/has-block-type.js
/**
* Check if a block list contains a specific block type. Recursively searches
* through `innerBlocks` if they exist.
*
* @param {Object} blockType A block object to search for.
* @param {Object[]} blocks The list of blocks to look through.
*
* @return {boolean} Whether the blockType is found.
*/
function hasBlockType(blockType) {
let blocks = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
if (!blocks.length) {
return false;
}
if (blocks.some(_ref => {
let {
name
} = _ref;
return name === blockType.name;
})) {
return true;
}
for (let i = 0; i < blocks.length; i++) {
if (hasBlockType(blockType, blocks[i].innerBlocks)) {
return true;
}
}
return false;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/store/selectors.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Returns true if application is requesting for downloadable blocks.
*
* @param {Object} state Global application state.
* @param {string} filterValue Search string.
*
* @return {boolean} Whether a request is in progress for the blocks list.
*/
function isRequestingDownloadableBlocks(state, filterValue) {
var _state$downloadableBl, _state$downloadableBl2;
return (_state$downloadableBl = (_state$downloadableBl2 = state.downloadableBlocks[filterValue]) === null || _state$downloadableBl2 === void 0 ? void 0 : _state$downloadableBl2.isRequesting) !== null && _state$downloadableBl !== void 0 ? _state$downloadableBl : false;
}
/**
* Returns the available uninstalled blocks.
*
* @param {Object} state Global application state.
* @param {string} filterValue Search string.
*
* @return {Array} Downloadable blocks.
*/
function getDownloadableBlocks(state, filterValue) {
var _state$downloadableBl3, _state$downloadableBl4;
return (_state$downloadableBl3 = (_state$downloadableBl4 = state.downloadableBlocks[filterValue]) === null || _state$downloadableBl4 === void 0 ? void 0 : _state$downloadableBl4.results) !== null && _state$downloadableBl3 !== void 0 ? _state$downloadableBl3 : [];
}
/**
* Returns the block types that have been installed on the server in this
* session.
*
* @param {Object} state Global application state.
*
* @return {Array} Block type items
*/
function getInstalledBlockTypes(state) {
return state.blockManagement.installedBlockTypes;
}
/**
* Returns block types that have been installed on the server and used in the
* current post.
*
* @param {Object} state Global application state.
*
* @return {Array} Block type items.
*/
const getNewBlockTypes = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => state => {
const usedBlockTree = select(external_wp_blockEditor_namespaceObject.store).getBlocks();
const installedBlockTypes = getInstalledBlockTypes(state);
return installedBlockTypes.filter(blockType => hasBlockType(blockType, usedBlockTree));
});
/**
* Returns the block types that have been installed on the server but are not
* used in the current post.
*
* @param {Object} state Global application state.
*
* @return {Array} Block type items.
*/
const getUnusedBlockTypes = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => state => {
const usedBlockTree = select(external_wp_blockEditor_namespaceObject.store).getBlocks();
const installedBlockTypes = getInstalledBlockTypes(state);
return installedBlockTypes.filter(blockType => !hasBlockType(blockType, usedBlockTree));
});
/**
* Returns true if a block plugin install is in progress.
*
* @param {Object} state Global application state.
* @param {string} blockId Id of the block.
*
* @return {boolean} Whether this block is currently being installed.
*/
function isInstalling(state, blockId) {
return state.blockManagement.isInstalling[blockId] || false;
}
/**
* Returns all block error notices.
*
* @param {Object} state Global application state.
*
* @return {Object} Object with error notices.
*/
function getErrorNotices(state) {
return state.errorNotices;
}
/**
* Returns the error notice for a given block.
*
* @param {Object} state Global application state.
* @param {string} blockId The ID of the block plugin. eg: my-block
*
* @return {string|boolean} The error text, or false if no error.
*/
function getErrorNoticeForBlock(state, blockId) {
return state.errorNotices[blockId];
}
;// CONCATENATED MODULE: external ["wp","i18n"]
var external_wp_i18n_namespaceObject = window["wp"]["i18n"];
;// CONCATENATED MODULE: external ["wp","apiFetch"]
var external_wp_apiFetch_namespaceObject = window["wp"]["apiFetch"];
var external_wp_apiFetch_default = /*#__PURE__*/__webpack_require__.n(external_wp_apiFetch_namespaceObject);
;// CONCATENATED MODULE: external ["wp","notices"]
var external_wp_notices_namespaceObject = window["wp"]["notices"];
;// CONCATENATED MODULE: external ["wp","url"]
var external_wp_url_namespaceObject = window["wp"]["url"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/store/load-assets.js
/**
* WordPress dependencies
*/
/**
* Load an asset for a block.
*
* This function returns a Promise that will resolve once the asset is loaded,
* or in the case of Stylesheets and Inline JavaScript, will resolve immediately.
*
* @param {HTMLElement} el A HTML Element asset to inject.
*
* @return {Promise} Promise which will resolve when the asset is loaded.
*/
const loadAsset = el => {
return new Promise((resolve, reject) => {
/*
* Reconstruct the passed element, this is required as inserting the Node directly
* won't always fire the required onload events, even if the asset wasn't already loaded.
*/
const newNode = document.createElement(el.nodeName);
['id', 'rel', 'src', 'href', 'type'].forEach(attr => {
if (el[attr]) {
newNode[attr] = el[attr];
}
}); // Append inline <script> contents.
if (el.innerHTML) {
newNode.appendChild(document.createTextNode(el.innerHTML));
}
newNode.onload = () => resolve(true);
newNode.onerror = () => reject(new Error('Error loading asset.'));
document.body.appendChild(newNode); // Resolve Stylesheets and Inline JavaScript immediately.
if ('link' === newNode.nodeName.toLowerCase() || 'script' === newNode.nodeName.toLowerCase() && !newNode.src) {
resolve();
}
});
};
/**
* Load the asset files for a block
*/
async function loadAssets() {
/*
* Fetch the current URL (post-new.php, or post.php?post=1&action=edit) and compare the
* JavaScript and CSS assets loaded between the pages. This imports the required assets
* for the block into the current page while not requiring that we know them up-front.
* In the future this can be improved by reliance upon block.json and/or a script-loader
* dependency API.
*/
const response = await external_wp_apiFetch_default()({
url: document.location.href,
parse: false
});
const data = await response.text();
const doc = new window.DOMParser().parseFromString(data, 'text/html');
const newAssets = Array.from(doc.querySelectorAll('link[rel="stylesheet"],script')).filter(asset => asset.id && !document.getElementById(asset.id));
/*
* Load each asset in order, as they may depend upon an earlier loaded script.
* Stylesheets and Inline Scripts will resolve immediately upon insertion.
*/
for (const newAsset of newAssets) {
await loadAsset(newAsset);
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/store/utils/get-plugin-url.js
/**
* Get the plugin's direct API link out of a block-directory response.
*
* @param {Object} block The block object
*
* @return {string} The plugin URL, if exists.
*/
function getPluginUrl(block) {
if (!block) {
return false;
}
const link = block.links['wp:plugin'] || block.links.self;
if (link && link.length) {
return link[0].href;
}
return false;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/store/actions.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Returns an action object used in signalling that the downloadable blocks
* have been requested and are loading.
*
* @param {string} filterValue Search string.
*
* @return {Object} Action object.
*/
function fetchDownloadableBlocks(filterValue) {
return {
type: 'FETCH_DOWNLOADABLE_BLOCKS',
filterValue
};
}
/**
* Returns an action object used in signalling that the downloadable blocks
* have been updated.
*
* @param {Array} downloadableBlocks Downloadable blocks.
* @param {string} filterValue Search string.
*
* @return {Object} Action object.
*/
function receiveDownloadableBlocks(downloadableBlocks, filterValue) {
return {
type: 'RECEIVE_DOWNLOADABLE_BLOCKS',
downloadableBlocks,
filterValue
};
}
/**
* Action triggered to install a block plugin.
*
* @param {Object} block The block item returned by search.
*
* @return {boolean} Whether the block was successfully installed & loaded.
*/
const installBlockType = block => async _ref => {
let {
registry,
dispatch
} = _ref;
const {
id,
name
} = block;
let success = false;
dispatch.clearErrorNotice(id);
try {
dispatch.setIsInstalling(id, true); // If we have a wp:plugin link, the plugin is installed but inactive.
const url = getPluginUrl(block);
let links = {};
if (url) {
await external_wp_apiFetch_default()({
method: 'PUT',
url,
data: {
status: 'active'
}
});
} else {
const response = await external_wp_apiFetch_default()({
method: 'POST',
path: 'wp/v2/plugins',
data: {
slug: id,
status: 'active'
}
}); // Add the `self` link for newly-installed blocks.
links = response._links;
}
dispatch.addInstalledBlockType({ ...block,
links: { ...block.links,
...links
}
}); // Ensures that the block metadata is propagated to the editor when registered on the server.
const metadataFields = ['api_version', 'title', 'category', 'parent', 'icon', 'description', 'keywords', 'attributes', 'provides_context', 'uses_context', 'supports', 'styles', 'example', 'variations'];
await external_wp_apiFetch_default()({
path: (0,external_wp_url_namespaceObject.addQueryArgs)(`/wp/v2/block-types/${name}`, {
_fields: metadataFields
})
}) // Ignore when the block is not registered on the server.
.catch(() => {}).then(response => {
if (!response) {
return;
}
(0,external_wp_blocks_namespaceObject.unstable__bootstrapServerSideBlockDefinitions)({
[name]: Object.fromEntries(Object.entries(response).filter(_ref2 => {
let [key] = _ref2;
return metadataFields.includes(key);
}))
});
});
await loadAssets();
const registeredBlocks = registry.select(external_wp_blocks_namespaceObject.store).getBlockTypes();
if (!registeredBlocks.some(i => i.name === name)) {
throw new Error((0,external_wp_i18n_namespaceObject.__)('Error registering block. Try reloading the page.'));
}
registry.dispatch(external_wp_notices_namespaceObject.store).createInfoNotice((0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s is the block title.
(0,external_wp_i18n_namespaceObject.__)('Block %s installed and added.'), block.title), {
speak: true,
type: 'snackbar'
});
success = true;
} catch (error) {
let message = error.message || (0,external_wp_i18n_namespaceObject.__)('An error occurred.'); // Errors we throw are fatal.
let isFatal = error instanceof Error; // Specific API errors that are fatal.
const fatalAPIErrors = {
folder_exists: (0,external_wp_i18n_namespaceObject.__)('This block is already installed. Try reloading the page.'),
unable_to_connect_to_filesystem: (0,external_wp_i18n_namespaceObject.__)('Error installing block. You can reload the page and try again.')
};
if (fatalAPIErrors[error.code]) {
isFatal = true;
message = fatalAPIErrors[error.code];
}
dispatch.setErrorNotice(id, message, isFatal);
registry.dispatch(external_wp_notices_namespaceObject.store).createErrorNotice(message, {
speak: true,
isDismissible: true
});
}
dispatch.setIsInstalling(id, false);
return success;
};
/**
* Action triggered to uninstall a block plugin.
*
* @param {Object} block The blockType object.
*/
const uninstallBlockType = block => async _ref3 => {
let {
registry,
dispatch
} = _ref3;
try {
const url = getPluginUrl(block);
await external_wp_apiFetch_default()({
method: 'PUT',
url,
data: {
status: 'inactive'
}
});
await external_wp_apiFetch_default()({
method: 'DELETE',
url
});
dispatch.removeInstalledBlockType(block);
} catch (error) {
registry.dispatch(external_wp_notices_namespaceObject.store).createErrorNotice(error.message || (0,external_wp_i18n_namespaceObject.__)('An error occurred.'));
}
};
/**
* Returns an action object used to add a block type to the "newly installed"
* tracking list.
*
* @param {Object} item The block item with the block id and name.
*
* @return {Object} Action object.
*/
function addInstalledBlockType(item) {
return {
type: 'ADD_INSTALLED_BLOCK_TYPE',
item
};
}
/**
* Returns an action object used to remove a block type from the "newly installed"
* tracking list.
*
* @param {string} item The block item with the block id and name.
*
* @return {Object} Action object.
*/
function removeInstalledBlockType(item) {
return {
type: 'REMOVE_INSTALLED_BLOCK_TYPE',
item
};
}
/**
* Returns an action object used to indicate install in progress.
*
* @param {string} blockId
* @param {boolean} isInstalling
*
* @return {Object} Action object.
*/
function setIsInstalling(blockId, isInstalling) {
return {
type: 'SET_INSTALLING_BLOCK',
blockId,
isInstalling
};
}
/**
* Sets an error notice to be displayed to the user for a given block.
*
* @param {string} blockId The ID of the block plugin. eg: my-block
* @param {string} message The message shown in the notice.
* @param {boolean} isFatal Whether the user can recover from the error.
*
* @return {Object} Action object.
*/
function setErrorNotice(blockId, message) {
let isFatal = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
return {
type: 'SET_ERROR_NOTICE',
blockId,
message,
isFatal
};
}
/**
* Sets the error notice to empty for specific block.
*
* @param {string} blockId The ID of the block plugin. eg: my-block
*
* @return {Object} Action object.
*/
function clearErrorNotice(blockId) {
return {
type: 'CLEAR_ERROR_NOTICE',
blockId
};
}
;// CONCATENATED MODULE: ./node_modules/tslib/tslib.es6.js
/*! *****************************************************************************
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 */
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 __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 (_) 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;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (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: n === "return" } : 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;
}
;// 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/pascal-case/dist.es2015/index.js
function pascalCaseTransform(input, index) {
var firstChar = input.charAt(0);
var lowerChars = input.substr(1).toLowerCase();
if (index > 0 && firstChar >= "0" && firstChar <= "9") {
return "_" + firstChar + lowerChars;
}
return "" + firstChar.toUpperCase() + lowerChars;
}
function dist_es2015_pascalCaseTransformMerge(input) {
return input.charAt(0).toUpperCase() + input.slice(1).toLowerCase();
}
function pascalCase(input, options) {
if (options === void 0) { options = {}; }
return noCase(input, __assign({ delimiter: "", transform: pascalCaseTransform }, options));
}
;// CONCATENATED MODULE: ./node_modules/camel-case/dist.es2015/index.js
function camelCaseTransform(input, index) {
if (index === 0)
return input.toLowerCase();
return pascalCaseTransform(input, index);
}
function camelCaseTransformMerge(input, index) {
if (index === 0)
return input.toLowerCase();
return pascalCaseTransformMerge(input);
}
function camelCase(input, options) {
if (options === void 0) { options = {}; }
return pascalCase(input, __assign({ transform: camelCaseTransform }, options));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/store/resolvers.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const resolvers_getDownloadableBlocks = filterValue => async _ref => {
let {
dispatch
} = _ref;
if (!filterValue) {
return;
}
try {
dispatch(fetchDownloadableBlocks(filterValue));
const results = await external_wp_apiFetch_default()({
path: `wp/v2/block-directory/search?term=${filterValue}`
});
const blocks = results.map(result => Object.fromEntries(Object.entries(result).map(_ref2 => {
let [key, value] = _ref2;
return [camelCase(key), value];
})));
dispatch(receiveDownloadableBlocks(blocks, filterValue));
} catch {}
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/store/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Module Constants
*/
const STORE_NAME = 'core/block-directory';
/**
* Block editor data store configuration.
*
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/data/README.md#registerStore
*
* @type {Object}
*/
const storeConfig = {
reducer: reducer,
selectors: selectors_namespaceObject,
actions: actions_namespaceObject,
resolvers: resolvers_namespaceObject
};
/**
* Store definition for the block directory 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);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/components/auto-block-uninstaller/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function AutoBlockUninstaller() {
const {
uninstallBlockType
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const shouldRemoveBlockTypes = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
isAutosavingPost,
isSavingPost
} = select(external_wp_editor_namespaceObject.store);
return isSavingPost() && !isAutosavingPost();
}, []);
const unusedBlockTypes = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).getUnusedBlockTypes(), []);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (shouldRemoveBlockTypes && unusedBlockTypes.length) {
unusedBlockTypes.forEach(blockType => {
uninstallBlockType(blockType);
(0,external_wp_blocks_namespaceObject.unregisterBlockType)(blockType.name);
});
}
}, [shouldRemoveBlockTypes]);
return null;
}
;// CONCATENATED MODULE: external ["wp","compose"]
var external_wp_compose_namespaceObject = window["wp"]["compose"];
;// CONCATENATED MODULE: external ["wp","components"]
var external_wp_components_namespaceObject = window["wp"]["components"];
;// CONCATENATED MODULE: external ["wp","coreData"]
var external_wp_coreData_namespaceObject = window["wp"]["coreData"];
;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/extends.js
function _extends() {
return _extends = Object.assign ? Object.assign.bind() : function (n) {
for (var e = 1; e < arguments.length; e++) {
var t = arguments[e];
for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
}
return n;
}, _extends.apply(null, arguments);
}
;// CONCATENATED MODULE: external ["wp","htmlEntities"]
var external_wp_htmlEntities_namespaceObject = window["wp"]["htmlEntities"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/icon/index.js
/**
* WordPress dependencies
*/
/** @typedef {{icon: JSX.Element, size?: number} & import('@wordpress/primitives').SVGProps} IconProps */
/**
* Return an SVG icon.
*
* @param {IconProps} props icon is the SVG component to render
* size is a number specifiying the icon size in pixels
* Other props will be passed to wrapped SVG component
*
* @return {JSX.Element} Icon component
*/
function Icon(_ref) {
let {
icon,
size = 24,
...props
} = _ref;
return (0,external_wp_element_namespaceObject.cloneElement)(icon, {
width: size,
height: size,
...props
});
}
/* harmony default export */ var icon = (Icon);
;// CONCATENATED MODULE: external ["wp","primitives"]
var external_wp_primitives_namespaceObject = window["wp"]["primitives"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/star-filled.js
/**
* WordPress dependencies
*/
const starFilled = (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: "M11.776 4.454a.25.25 0 01.448 0l2.069 4.192a.25.25 0 00.188.137l4.626.672a.25.25 0 01.139.426l-3.348 3.263a.25.25 0 00-.072.222l.79 4.607a.25.25 0 01-.362.263l-4.138-2.175a.25.25 0 00-.232 0l-4.138 2.175a.25.25 0 01-.363-.263l.79-4.607a.25.25 0 00-.071-.222L4.754 9.881a.25.25 0 01.139-.426l4.626-.672a.25.25 0 00.188-.137l2.069-4.192z"
}));
/* harmony default export */ var star_filled = (starFilled);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/star-half.js
/**
* WordPress dependencies
*/
const starHalf = (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: "M9.518 8.783a.25.25 0 00.188-.137l2.069-4.192a.25.25 0 01.448 0l2.07 4.192a.25.25 0 00.187.137l4.626.672a.25.25 0 01.139.427l-3.347 3.262a.25.25 0 00-.072.222l.79 4.607a.25.25 0 01-.363.264l-4.137-2.176a.25.25 0 00-.233 0l-4.138 2.175a.25.25 0 01-.362-.263l.79-4.607a.25.25 0 00-.072-.222L4.753 9.882a.25.25 0 01.14-.427l4.625-.672zM12 14.533c.28 0 .559.067.814.2l1.895.997-.362-2.11a1.75 1.75 0 01.504-1.55l1.533-1.495-2.12-.308a1.75 1.75 0 01-1.317-.957L12 7.39v7.143z"
}));
/* harmony default export */ var star_half = (starHalf);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/star-empty.js
/**
* WordPress dependencies
*/
const starEmpty = (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, {
fillRule: "evenodd",
d: "M9.706 8.646a.25.25 0 01-.188.137l-4.626.672a.25.25 0 00-.139.427l3.348 3.262a.25.25 0 01.072.222l-.79 4.607a.25.25 0 00.362.264l4.138-2.176a.25.25 0 01.233 0l4.137 2.175a.25.25 0 00.363-.263l-.79-4.607a.25.25 0 01.072-.222l3.347-3.262a.25.25 0 00-.139-.427l-4.626-.672a.25.25 0 01-.188-.137l-2.069-4.192a.25.25 0 00-.448 0L9.706 8.646zM12 7.39l-.948 1.921a1.75 1.75 0 01-1.317.957l-2.12.308 1.534 1.495c.412.402.6.982.503 1.55l-.362 2.11 1.896-.997a1.75 1.75 0 011.629 0l1.895.997-.362-2.11a1.75 1.75 0 01.504-1.55l1.533-1.495-2.12-.308a1.75 1.75 0 01-1.317-.957L12 7.39z",
clipRule: "evenodd"
}));
/* harmony default export */ var star_empty = (starEmpty);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/components/block-ratings/stars.js
/**
* WordPress dependencies
*/
function Stars(_ref) {
let {
rating
} = _ref;
const stars = Math.round(rating / 0.5) * 0.5;
const fullStarCount = Math.floor(rating);
const halfStarCount = Math.ceil(rating - fullStarCount);
const emptyStarCount = 5 - (fullStarCount + halfStarCount);
return (0,external_wp_element_namespaceObject.createElement)("span", {
"aria-label": (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: number of stars. */
(0,external_wp_i18n_namespaceObject.__)('%s out of 5 stars'), stars)
}, Array.from({
length: fullStarCount
}).map((_, i) => (0,external_wp_element_namespaceObject.createElement)(icon, {
key: `full_stars_${i}`,
className: "block-directory-block-ratings__star-full",
icon: star_filled,
size: 16
})), Array.from({
length: halfStarCount
}).map((_, i) => (0,external_wp_element_namespaceObject.createElement)(icon, {
key: `half_stars_${i}`,
className: "block-directory-block-ratings__star-half-full",
icon: star_half,
size: 16
})), Array.from({
length: emptyStarCount
}).map((_, i) => (0,external_wp_element_namespaceObject.createElement)(icon, {
key: `empty_stars_${i}`,
className: "block-directory-block-ratings__star-empty",
icon: star_empty,
size: 16
})));
}
/* harmony default export */ var stars = (Stars);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/components/block-ratings/index.js
/**
* Internal dependencies
*/
const BlockRatings = _ref => {
let {
rating
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-directory-block-ratings"
}, (0,external_wp_element_namespaceObject.createElement)(stars, {
rating: rating
}));
};
/* harmony default export */ var block_ratings = (BlockRatings);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/components/downloadable-block-icon/index.js
/**
* WordPress dependencies
*/
function DownloadableBlockIcon(_ref) {
let {
icon
} = _ref;
const className = 'block-directory-downloadable-block-icon';
return icon.match(/\.(jpeg|jpg|gif|png|svg)(?:\?.*)?$/) !== null ? (0,external_wp_element_namespaceObject.createElement)("img", {
className: className,
src: icon,
alt: ""
}) : (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockIcon, {
className: className,
icon: icon,
showColors: true
});
}
/* harmony default export */ var downloadable_block_icon = (DownloadableBlockIcon);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/components/downloadable-block-notice/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const DownloadableBlockNotice = _ref => {
let {
block
} = _ref;
const errorNotice = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).getErrorNoticeForBlock(block.id), [block]);
if (!errorNotice) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-directory-downloadable-block-notice"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-directory-downloadable-block-notice__content"
}, errorNotice.message, errorNotice.isFatal ? ' ' + (0,external_wp_i18n_namespaceObject.__)('Try reloading the page.') : null));
};
/* harmony default export */ var downloadable_block_notice = (DownloadableBlockNotice);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/components/downloadable-block-list-item/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
// Return the appropriate block item label, given the block data and status.
function getDownloadableBlockLabel(_ref, _ref2) {
let {
title,
rating,
ratingCount
} = _ref;
let {
hasNotice,
isInstalled,
isInstalling
} = _ref2;
const stars = Math.round(rating / 0.5) * 0.5;
if (!isInstalled && hasNotice) {
/* translators: %1$s: block title */
return (0,external_wp_i18n_namespaceObject.sprintf)('Retry installing %s.', (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(title));
}
if (isInstalled) {
/* translators: %1$s: block title */
return (0,external_wp_i18n_namespaceObject.sprintf)('Add %s.', (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(title));
}
if (isInstalling) {
/* translators: %1$s: block title */
return (0,external_wp_i18n_namespaceObject.sprintf)('Installing %s.', (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(title));
} // No ratings yet, just use the title.
if (ratingCount < 1) {
/* translators: %1$s: block title */
return (0,external_wp_i18n_namespaceObject.sprintf)('Install %s.', (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(title));
}
return (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %1$s: block title, %2$s: average rating, %3$s: total ratings count. */
(0,external_wp_i18n_namespaceObject._n)('Install %1$s. %2$s stars with %3$s review.', 'Install %1$s. %2$s stars with %3$s reviews.', ratingCount), (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(title), stars, ratingCount);
}
function DownloadableBlockListItem(_ref3) {
let {
composite,
item,
onClick
} = _ref3;
const {
author,
description,
icon,
rating,
title
} = item; // getBlockType returns a block object if this block exists, or null if not.
const isInstalled = !!(0,external_wp_blocks_namespaceObject.getBlockType)(item.name);
const {
hasNotice,
isInstalling,
isInstallable
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getErrorNoticeForBlock,
isInstalling: isBlockInstalling
} = select(store);
const notice = getErrorNoticeForBlock(item.id);
const hasFatal = notice && notice.isFatal;
return {
hasNotice: !!notice,
isInstalling: isBlockInstalling(item.id),
isInstallable: !hasFatal
};
}, [item]);
let statusText = '';
if (isInstalled) {
statusText = (0,external_wp_i18n_namespaceObject.__)('Installed!');
} else if (isInstalling) {
statusText = (0,external_wp_i18n_namespaceObject.__)('Installing…');
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableCompositeItem, _extends({
__experimentalIsFocusable: true,
role: "option",
as: external_wp_components_namespaceObject.Button
}, composite, {
className: "block-directory-downloadable-block-list-item",
onClick: event => {
event.preventDefault();
onClick();
},
isBusy: isInstalling,
disabled: isInstalling || !isInstallable,
label: getDownloadableBlockLabel(item, {
hasNotice,
isInstalled,
isInstalling
}),
showTooltip: true,
tooltipPosition: "top center"
}), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-directory-downloadable-block-list-item__icon"
}, (0,external_wp_element_namespaceObject.createElement)(downloadable_block_icon, {
icon: icon,
title: title
}), isInstalling ? (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-directory-downloadable-block-list-item__spinner"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Spinner, null)) : (0,external_wp_element_namespaceObject.createElement)(block_ratings, {
rating: rating
})), (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-directory-downloadable-block-list-item__details"
}, (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-directory-downloadable-block-list-item__title"
}, (0,external_wp_element_namespaceObject.createInterpolateElement)((0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %1$s: block title, %2$s: author name. */
(0,external_wp_i18n_namespaceObject.__)('%1$s <span>by %2$s</span>'), (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(title), author), {
span: (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-directory-downloadable-block-list-item__author"
})
})), hasNotice ? (0,external_wp_element_namespaceObject.createElement)(downloadable_block_notice, {
block: item
}) : (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-directory-downloadable-block-list-item__desc"
}, !!statusText ? statusText : (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(description)), isInstallable && !(isInstalled || isInstalling) && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.VisuallyHidden, null, (0,external_wp_i18n_namespaceObject.__)('Install block')))));
}
/* harmony default export */ var downloadable_block_list_item = (DownloadableBlockListItem);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/components/downloadable-blocks-list/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const noop = () => {};
function DownloadableBlocksList(_ref) {
let {
items,
onHover = noop,
onSelect
} = _ref;
const composite = (0,external_wp_components_namespaceObject.__unstableUseCompositeState)();
const {
installBlockType
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
if (!items.length) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableComposite, _extends({}, composite, {
role: "listbox",
className: "block-directory-downloadable-blocks-list",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Blocks available for install')
}), items.map(item => {
return (0,external_wp_element_namespaceObject.createElement)(downloadable_block_list_item, {
key: item.id,
composite: composite,
onClick: () => {
// Check if the block is registered (`getBlockType`
// will return an object). If so, insert the block.
// This prevents installing existing plugins.
if ((0,external_wp_blocks_namespaceObject.getBlockType)(item.name)) {
onSelect(item);
} else {
installBlockType(item).then(success => {
if (success) {
onSelect(item);
}
});
}
onHover(null);
},
onHover: onHover,
item: item
});
}));
}
/* harmony default export */ var downloadable_blocks_list = (DownloadableBlocksList);
;// CONCATENATED MODULE: external ["wp","a11y"]
var external_wp_a11y_namespaceObject = window["wp"]["a11y"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/components/downloadable-blocks-panel/inserter-panel.js
/**
* WordPress dependencies
*/
function DownloadableBlocksInserterPanel(_ref) {
let {
children,
downloadableItems,
hasLocalBlocks
} = _ref;
const count = downloadableItems.length;
(0,external_wp_element_namespaceObject.useEffect)(() => {
(0,external_wp_a11y_namespaceObject.speak)((0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %d: number of available blocks. */
(0,external_wp_i18n_namespaceObject._n)('%d additional block is available to install.', '%d additional blocks are available to install.', count), count));
}, [count]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, !hasLocalBlocks && (0,external_wp_element_namespaceObject.createElement)("p", {
className: "block-directory-downloadable-blocks-panel__no-local"
}, (0,external_wp_i18n_namespaceObject.__)('No results available from your installed blocks.')), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__quick-inserter-separator"
}), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-directory-downloadable-blocks-panel"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-directory-downloadable-blocks-panel__header"
}, (0,external_wp_element_namespaceObject.createElement)("h2", {
className: "block-directory-downloadable-blocks-panel__title"
}, (0,external_wp_i18n_namespaceObject.__)('Available to install')), (0,external_wp_element_namespaceObject.createElement)("p", {
className: "block-directory-downloadable-blocks-panel__description"
}, (0,external_wp_i18n_namespaceObject.__)('Select a block to install and add it to your post.'))), children));
}
/* harmony default export */ var inserter_panel = (DownloadableBlocksInserterPanel);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/block-default.js
/**
* WordPress dependencies
*/
const blockDefault = (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 8h-1V6h-5v2h-2V6H6v2H5c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-8c0-1.1-.9-2-2-2zm.5 10c0 .3-.2.5-.5.5H5c-.3 0-.5-.2-.5-.5v-8c0-.3.2-.5.5-.5h14c.3 0 .5.2.5.5v8z"
}));
/* harmony default export */ var block_default = (blockDefault);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/components/downloadable-blocks-panel/no-results.js
/**
* WordPress dependencies
*/
function DownloadableBlocksNoResults() {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__no-results"
}, (0,external_wp_element_namespaceObject.createElement)(icon, {
className: "block-editor-inserter__no-results-icon",
icon: block_default
}), (0,external_wp_element_namespaceObject.createElement)("p", null, (0,external_wp_i18n_namespaceObject.__)('No results found.'))), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__tips"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Tip, null, (0,external_wp_i18n_namespaceObject.__)('Interested in creating your own block?'), (0,external_wp_element_namespaceObject.createElement)("br", null), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ExternalLink, {
href: "https://developer.wordpress.org/block-editor/"
}, (0,external_wp_i18n_namespaceObject.__)('Get started here'), "."))));
}
/* harmony default export */ var no_results = (DownloadableBlocksNoResults);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/components/downloadable-blocks-panel/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function DownloadableBlocksPanel(_ref) {
let {
downloadableItems,
onSelect,
onHover,
hasLocalBlocks,
hasPermission,
isLoading,
isTyping
} = _ref;
if (typeof hasPermission === 'undefined' || isLoading || isTyping) {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, hasPermission && !hasLocalBlocks && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("p", {
className: "block-directory-downloadable-blocks-panel__no-local"
}, (0,external_wp_i18n_namespaceObject.__)('No results available from your installed blocks.')), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__quick-inserter-separator"
})), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-directory-downloadable-blocks-panel has-blocks-loading"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Spinner, null)));
}
if (false === hasPermission) {
if (!hasLocalBlocks) {
return (0,external_wp_element_namespaceObject.createElement)(no_results, null);
}
return null;
}
return !!downloadableItems.length ? (0,external_wp_element_namespaceObject.createElement)(inserter_panel, {
downloadableItems: downloadableItems,
hasLocalBlocks: hasLocalBlocks
}, (0,external_wp_element_namespaceObject.createElement)(downloadable_blocks_list, {
items: downloadableItems,
onSelect: onSelect,
onHover: onHover
})) : !hasLocalBlocks && (0,external_wp_element_namespaceObject.createElement)(no_results, null);
}
/* harmony default export */ var downloadable_blocks_panel = ((0,external_wp_compose_namespaceObject.compose)([(0,external_wp_data_namespaceObject.withSelect)((select, _ref2) => {
let {
filterValue,
rootClientId = null
} = _ref2;
const {
getDownloadableBlocks,
isRequestingDownloadableBlocks
} = select(store);
const {
canInsertBlockType
} = select(external_wp_blockEditor_namespaceObject.store);
const hasPermission = select(external_wp_coreData_namespaceObject.store).canUser('read', 'block-directory/search');
function getInstallableBlocks(term) {
return getDownloadableBlocks(term).filter(block => canInsertBlockType(block, rootClientId, true));
}
const downloadableItems = hasPermission ? getInstallableBlocks(filterValue) : [];
const isLoading = isRequestingDownloadableBlocks(filterValue);
return {
downloadableItems,
hasPermission,
isLoading
};
})])(DownloadableBlocksPanel));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/plugins/inserter-menu-downloadable-blocks-panel/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function InserterMenuDownloadableBlocksPanel() {
const [debouncedFilterValue, setFilterValue] = (0,external_wp_element_namespaceObject.useState)('');
const debouncedSetFilterValue = (0,external_wp_compose_namespaceObject.debounce)(setFilterValue, 400);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.__unstableInserterMenuExtension, null, _ref => {
let {
onSelect,
onHover,
filterValue,
hasItems,
rootClientId
} = _ref;
if (debouncedFilterValue !== filterValue) {
debouncedSetFilterValue(filterValue);
}
if (!debouncedFilterValue) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(downloadable_blocks_panel, {
onSelect: onSelect,
onHover: onHover,
rootClientId: rootClientId,
filterValue: debouncedFilterValue,
hasLocalBlocks: hasItems,
isTyping: filterValue !== debouncedFilterValue
});
});
}
/* harmony default export */ var inserter_menu_downloadable_blocks_panel = (InserterMenuDownloadableBlocksPanel);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/components/compact-list/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function CompactList(_ref) {
let {
items
} = _ref;
if (!items.length) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)("ul", {
className: "block-directory-compact-list"
}, items.map(_ref2 => {
let {
icon,
id,
title,
author
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)("li", {
key: id,
className: "block-directory-compact-list__item"
}, (0,external_wp_element_namespaceObject.createElement)(downloadable_block_icon, {
icon: icon,
title: title
}), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-directory-compact-list__item-details"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-directory-compact-list__item-title"
}, title), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-directory-compact-list__item-author"
}, (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: Name of the block author. */
(0,external_wp_i18n_namespaceObject.__)('By %s'), author))));
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/plugins/installed-blocks-pre-publish-panel/index.js
var _window$wp$editPost, _window, _window$wp;
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
// We shouldn't import the edit-post package directly
// because it would include the wp-edit-post in all pages loading the block-directory script.
const {
PluginPrePublishPanel
} = (_window$wp$editPost = (_window = window) === null || _window === void 0 ? void 0 : (_window$wp = _window.wp) === null || _window$wp === void 0 ? void 0 : _window$wp.editPost) !== null && _window$wp$editPost !== void 0 ? _window$wp$editPost : {};
function InstalledBlocksPrePublishPanel() {
const newBlockTypes = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).getNewBlockTypes(), []);
if (!newBlockTypes.length) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(PluginPrePublishPanel, {
icon: block_default,
title: (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %d: number of blocks (number).
(0,external_wp_i18n_namespaceObject._n)('Added: %d block', 'Added: %d blocks', newBlockTypes.length), newBlockTypes.length),
initialOpen: true
}, (0,external_wp_element_namespaceObject.createElement)("p", {
className: "installed-blocks-pre-publish-panel__copy"
}, (0,external_wp_i18n_namespaceObject._n)('The following block has been added to your site.', 'The following blocks have been added to your site.', newBlockTypes.length)), (0,external_wp_element_namespaceObject.createElement)(CompactList, {
items: newBlockTypes
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/plugins/get-install-missing/install-button.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function InstallButton(_ref) {
let {
attributes,
block,
clientId
} = _ref;
const isInstallingBlock = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).isInstalling(block.id), [block.id]);
const {
installBlockType
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const {
replaceBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_blockEditor_namespaceObject.store);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
onClick: () => installBlockType(block).then(success => {
if (success) {
const blockType = (0,external_wp_blocks_namespaceObject.getBlockType)(block.name);
const [originalBlock] = (0,external_wp_blocks_namespaceObject.parse)(attributes.originalContent);
if (originalBlock && blockType) {
replaceBlock(clientId, (0,external_wp_blocks_namespaceObject.createBlock)(blockType.name, originalBlock.attributes, originalBlock.innerBlocks));
}
}
}),
disabled: isInstallingBlock,
isBusy: isInstallingBlock,
variant: "primary"
}, (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: block name */
(0,external_wp_i18n_namespaceObject.__)('Install %s'), block.title));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/plugins/get-install-missing/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const getInstallMissing = OriginalComponent => props => {
const {
originalName
} = props.attributes; // Disable reason: This is a valid component, but it's mistaken for a callback.
// eslint-disable-next-line react-hooks/rules-of-hooks
const {
block,
hasPermission
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getDownloadableBlocks
} = select(store);
const blocks = getDownloadableBlocks('block:' + originalName).filter(_ref => {
let {
name
} = _ref;
return originalName === name;
});
return {
hasPermission: select(external_wp_coreData_namespaceObject.store).canUser('read', 'block-directory/search'),
block: blocks.length && blocks[0]
};
}, [originalName]); // The user can't install blocks, or the block isn't available for download.
if (!hasPermission || !block) {
return (0,external_wp_element_namespaceObject.createElement)(OriginalComponent, props);
}
return (0,external_wp_element_namespaceObject.createElement)(ModifiedWarning, _extends({}, props, {
originalBlock: block
}));
};
const ModifiedWarning = _ref2 => {
let {
originalBlock,
...props
} = _ref2;
const {
originalName,
originalUndelimitedContent,
clientId
} = props.attributes;
const {
replaceBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_blockEditor_namespaceObject.store);
const convertToHTML = () => {
replaceBlock(props.clientId, (0,external_wp_blocks_namespaceObject.createBlock)('core/html', {
content: originalUndelimitedContent
}));
};
const hasContent = !!originalUndelimitedContent;
const hasHTMLBlock = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
canInsertBlockType,
getBlockRootClientId
} = select(external_wp_blockEditor_namespaceObject.store);
return canInsertBlockType('core/html', getBlockRootClientId(clientId));
}, [clientId]);
let messageHTML = (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: block name */
(0,external_wp_i18n_namespaceObject.__)('Your site doesn’t include support for the %s block. You can try installing the block or remove it entirely.'), originalBlock.title || originalName);
const actions = [(0,external_wp_element_namespaceObject.createElement)(InstallButton, {
key: "install",
block: originalBlock,
attributes: props.attributes,
clientId: props.clientId
})];
if (hasContent && hasHTMLBlock) {
messageHTML = (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: block name */
(0,external_wp_i18n_namespaceObject.__)('Your site doesn’t include support for the %s block. You can try installing the block, convert it to a Custom HTML block, or remove it entirely.'), originalBlock.title || originalName);
actions.push((0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
key: "convert",
onClick: convertToHTML,
variant: "tertiary"
}, (0,external_wp_i18n_namespaceObject.__)('Keep as HTML')));
}
return (0,external_wp_element_namespaceObject.createElement)("div", (0,external_wp_blockEditor_namespaceObject.useBlockProps)(), (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.Warning, {
actions: actions
}, messageHTML), (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.RawHTML, null, originalUndelimitedContent));
};
/* harmony default export */ var get_install_missing = (getInstallMissing);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/plugins/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
(0,external_wp_plugins_namespaceObject.registerPlugin)('block-directory', {
render() {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(AutoBlockUninstaller, null), (0,external_wp_element_namespaceObject.createElement)(inserter_menu_downloadable_blocks_panel, null), (0,external_wp_element_namespaceObject.createElement)(InstalledBlocksPrePublishPanel, null));
}
});
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'block-directory/fallback', (settings, name) => {
if (name !== 'core/missing') {
return settings;
}
settings.edit = get_install_missing(settings.edit);
return settings;
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-directory/build-module/index.js
/**
* Internal dependencies
*/
(window.wp = window.wp || {}).blockDirectory = __webpack_exports__;
/******/ })()
; format-library.min.js 0000666 00000051401 15123355174 0010631 0 ustar 00 /*! This file is auto-generated */
!function(){"use strict";var e={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);var n=window.wp.richText,r=window.wp.element,o=window.wp.i18n,a=window.wp.blockEditor,l=window.wp.primitives;var c=(0,r.createElement)(l.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,r.createElement)(l.Path,{d:"M14.7 11.3c1-.6 1.5-1.6 1.5-3 0-2.3-1.3-3.4-4-3.4H7v14h5.8c1.4 0 2.5-.3 3.3-1 .8-.7 1.2-1.7 1.2-2.9.1-1.9-.8-3.1-2.6-3.7zm-5.1-4h2.3c.6 0 1.1.1 1.4.4.3.3.5.7.5 1.2s-.2 1-.5 1.2c-.3.3-.8.4-1.4.4H9.6V7.3zm4.6 9c-.4.3-1 .4-1.7.4H9.6v-3.9h2.9c.7 0 1.3.2 1.7.5.4.3.6.8.6 1.5s-.2 1.2-.6 1.5z"}));const i="core/bold",s=(0,o.__)("Bold"),u={name:i,title:s,tagName:"strong",className:null,edit(e){let{isActive:t,value:o,onChange:l,onFocus:u}=e;function m(){l((0,n.toggleFormat)(o,{type:i,title:s}))}return(0,r.createElement)(r.Fragment,null,(0,r.createElement)(a.RichTextShortcut,{type:"primary",character:"b",onUse:m}),(0,r.createElement)(a.RichTextToolbarButton,{name:"bold",icon:c,title:s,onClick:function(){l((0,n.toggleFormat)(o,{type:i})),u()},isActive:t,shortcutType:"primary",shortcutCharacter:"b"}),(0,r.createElement)(a.__unstableRichTextInputEvent,{inputType:"formatBold",onInput:m}))}};var m=(0,r.createElement)(l.SVG,{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},(0,r.createElement)(l.Path,{d:"M20.8 10.7l-4.3-4.3-1.1 1.1 4.3 4.3c.1.1.1.3 0 .4l-4.3 4.3 1.1 1.1 4.3-4.3c.7-.8.7-1.9 0-2.6zM4.2 11.8l4.3-4.3-1-1-4.3 4.3c-.7.7-.7 1.8 0 2.5l4.3 4.3 1.1-1.1-4.3-4.3c-.2-.1-.2-.3-.1-.4z"}));const h="core/code",p=(0,o.__)("Inline code"),g={name:h,title:p,tagName:"code",className:null,__unstableInputRule(e){const{start:t,text:r}=e;if("`"!==r.slice(t-1,t))return e;const o=r.slice(0,t-1).lastIndexOf("`");if(-1===o)return e;const a=o,l=t-2;return a===l?e:(e=(0,n.remove)(e,a,a+1),e=(0,n.remove)(e,l,l+1),e=(0,n.applyFormat)(e,{type:h},a,l))},edit(e){let{value:t,onChange:o,onFocus:l,isActive:c}=e;function i(){o((0,n.toggleFormat)(t,{type:h,title:p})),l()}return(0,r.createElement)(r.Fragment,null,(0,r.createElement)(a.RichTextShortcut,{type:"access",character:"x",onUse:i}),(0,r.createElement)(a.RichTextToolbarButton,{icon:m,title:p,onClick:i,isActive:c,role:"menuitemcheckbox"}))}};var v=window.wp.components;var d=(0,r.createElement)(l.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"-2 -2 24 24"},(0,r.createElement)(l.Path,{d:"M6.734 16.106l2.176-2.38-1.093-1.028-3.846 4.158 3.846 4.157 1.093-1.027-2.176-2.38h2.811c1.125 0 2.25.03 3.374 0 1.428-.001 3.362-.25 4.963-1.277 1.66-1.065 2.868-2.906 2.868-5.859 0-2.479-1.327-4.896-3.65-5.93-1.82-.813-3.044-.8-4.806-.788l-.567.002v1.5c.184 0 .368 0 .553-.002 1.82-.007 2.704-.014 4.21.657 1.854.827 2.76 2.657 2.76 4.561 0 2.472-.973 3.824-2.178 4.596-1.258.807-2.864 1.04-4.163 1.04h-.02c-1.115.03-2.229 0-3.344 0H6.734z"}));const w=["image"],b="core/image",f=(0,o.__)("Inline image"),y={name:b,title:f,keywords:[(0,o.__)("photo"),(0,o.__)("media")],object:!0,tagName:"img",className:null,attributes:{className:"class",style:"style",url:"src",alt:"alt"},edit:function(e){let{value:t,onChange:o,onFocus:l,isObjectActive:c,activeObjectAttributes:i,contentRef:s}=e;const[u,m]=(0,r.useState)(!1);function h(){m(!1)}return(0,r.createElement)(a.MediaUploadCheck,null,(0,r.createElement)(a.RichTextToolbarButton,{icon:(0,r.createElement)(v.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,r.createElement)(v.Path,{d:"M4 18.5h16V17H4v1.5zM16 13v1.5h4V13h-4zM5.1 15h7.8c.6 0 1.1-.5 1.1-1.1V6.1c0-.6-.5-1.1-1.1-1.1H5.1C4.5 5 4 5.5 4 6.1v7.8c0 .6.5 1.1 1.1 1.1zm.4-8.5h7V10l-1-1c-.3-.3-.8-.3-1 0l-1.6 1.5-1.2-.7c-.3-.2-.6-.2-.9 0l-1.3 1V6.5zm0 6.1l1.8-1.3 1.3.8c.3.2.7.2.9-.1l1.5-1.4 1.5 1.4v1.5h-7v-.9z"})),title:f,onClick:function(){m(!0)},isActive:c}),u&&(0,r.createElement)(a.MediaUpload,{allowedTypes:w,onSelect:e=>{let{id:r,url:a,alt:c,width:i}=e;h(),o((0,n.insertObject)(t,{type:b,attributes:{className:`wp-image-${r}`,style:`width: ${Math.min(i,150)}px;`,url:a,alt:c}})),l()},onClose:h,render:e=>{let{open:t}=e;return t(),null}}),c&&(0,r.createElement)(E,{value:t,onChange:o,activeObjectAttributes:i,contentRef:s}))}};function E(e){let{value:t,onChange:a,activeObjectAttributes:l,contentRef:c}=e;const{style:i}=l,[s,u]=(0,r.useState)(null==i?void 0:i.replace(/\D/g,"")),m=(0,n.useAnchor)({editableContentElement:c.current,value:t,settings:y});return(0,r.createElement)(v.Popover,{placement:"bottom",focusOnMount:!1,anchor:m,className:"block-editor-format-toolbar__image-popover"},(0,r.createElement)("form",{className:"block-editor-format-toolbar__image-container-content",onSubmit:e=>{const n=t.replacements.slice();n[t.start]={type:b,attributes:{...l,style:s?`width: ${s}px;`:""}},a({...t,replacements:n}),e.preventDefault()}},(0,r.createElement)(v.TextControl,{className:"block-editor-format-toolbar__image-container-value",type:"number",label:(0,o.__)("Width"),value:s,min:1,onChange:e=>u(e)}),(0,r.createElement)(v.Button,{icon:d,label:(0,o.__)("Apply"),type:"submit"})))}var k=(0,r.createElement)(l.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,r.createElement)(l.Path,{d:"M12.5 5L10 19h1.9l2.5-14z"}));const C="core/italic",x=(0,o.__)("Italic"),_={name:C,title:x,tagName:"em",className:null,edit(e){let{isActive:t,value:o,onChange:l,onFocus:c}=e;function i(){l((0,n.toggleFormat)(o,{type:C,title:x}))}return(0,r.createElement)(r.Fragment,null,(0,r.createElement)(a.RichTextShortcut,{type:"primary",character:"i",onUse:i}),(0,r.createElement)(a.RichTextToolbarButton,{name:"italic",icon:k,title:x,onClick:function(){l((0,n.toggleFormat)(o,{type:C})),c()},isActive:t,shortcutType:"primary",shortcutCharacter:"i"}),(0,r.createElement)(a.__unstableRichTextInputEvent,{inputType:"formatItalic",onInput:i}))}};var T=window.wp.url,S=window.wp.htmlEntities;var F=(0,r.createElement)(l.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,r.createElement)(l.Path,{d:"M15.6 7.3h-.7l1.6-3.5-.9-.4-3.9 8.5H9v1.5h2l-1.3 2.8H8.4c-2 0-3.7-1.7-3.7-3.7s1.7-3.7 3.7-3.7H10V7.3H8.4c-2.9 0-5.2 2.3-5.2 5.2 0 2.9 2.3 5.2 5.2 5.2H9l-1.4 3.2.9.4 5.7-12.5h1.4c2 0 3.7 1.7 3.7 3.7s-1.7 3.7-3.7 3.7H14v1.5h1.6c2.9 0 5.2-2.3 5.2-5.2 0-2.9-2.4-5.2-5.2-5.2z"}));var A=(0,r.createElement)(l.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,r.createElement)(l.Path,{d:"M15.6 7.2H14v1.5h1.6c2 0 3.7 1.7 3.7 3.7s-1.7 3.7-3.7 3.7H14v1.5h1.6c2.8 0 5.2-2.3 5.2-5.2 0-2.9-2.3-5.2-5.2-5.2zM4.7 12.4c0-2 1.7-3.7 3.7-3.7H10V7.2H8.4c-2.9 0-5.2 2.3-5.2 5.2 0 2.9 2.3 5.2 5.2 5.2H10v-1.5H8.4c-2 0-3.7-1.7-3.7-3.7zm4.6.9h5.3v-1.5H9.3v1.5z"})),N=window.wp.a11y,R=window.wp.data;function P(e){if(!e)return!1;const t=e.trim();if(!t)return!1;if(/^\S+:/.test(t)){const e=(0,T.getProtocol)(t);if(!(0,T.isValidProtocol)(e))return!1;if(e.startsWith("http")&&!/^https?:\/\/[^\/\s]/i.test(t))return!1;const n=(0,T.getAuthority)(t);if(!(0,T.isValidAuthority)(n))return!1;const r=(0,T.getPath)(t);if(r&&!(0,T.isValidPath)(r))return!1;const o=(0,T.getQueryString)(t);if(o&&!(0,T.isValidQueryString)(o))return!1;const a=(0,T.getFragment)(t);if(a&&!(0,T.isValidFragment)(a))return!1}return!(t.startsWith("#")&&!(0,T.isValidFragment)(t))}function V(e,t){var n,r,o;let a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.start,l=arguments.length>3&&void 0!==arguments[3]?arguments[3]:e.end;const c={start:null,end:null},{formats:i}=e;let s,u;if(null==i||!i.length)return c;const m=i.slice(),h=null===(n=m[a])||void 0===n?void 0:n.find((e=>{let{type:n}=e;return n===t.type})),p=null===(r=m[l])||void 0===r?void 0:r.find((e=>{let{type:n}=e;return n===t.type})),g=null===(o=m[l-1])||void 0===o?void 0:o.find((e=>{let{type:n}=e;return n===t.type}));if(h)s=h,u=a;else if(p)s=p,u=l;else{if(!g)return c;s=g,u=l-1}const v=m[u].indexOf(s),d=[m,u,s,v];return a=B(...d),l=H(...d),a=a<0?0:a,{start:a,end:l}}function M(e,t,n,r,o){let a=t;const l={forwards:1,backwards:-1}[o]||1,c=-1*l;for(;e[a]&&e[a][r]===n;)a+=l;return a+=c,a}const z=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return function(){for(var t=arguments.length,r=new Array(t),o=0;o<t;o++)r[o]=arguments[o];return e(...r,...n)}},B=z(M,"backwards"),H=z(M,"forwards"),L=new WeakMap;let I=-1;function j(e){return`link-control-instance-${e}`}var U=function(e){if(e)return L.has(e)?j(L.get(e)):(I+=1,L.set(e,I),j(I))};var G=(0,v.withSpokenMessages)((function(e){let{isActive:t,activeAttributes:l,addingLink:c,value:i,onChange:s,speak:u,stopAddingLink:m,contentRef:h}=e;const p=function(e,t){let r=e.start,o=e.end;if(t){const t=V(e,{type:"core/link"});r=t.start,o=t.end+1}return(0,n.slice)(e,r,o)}(i,t),g=p.text,[d,w]=(0,r.useState)(),{createPageEntity:b,userCanCreatePages:f}=(0,R.useSelect)((e=>{const{getSettings:t}=e(a.store),n=t();return{createPageEntity:n.__experimentalCreatePageEntity,userCanCreatePages:n.__experimentalUserCanCreatePages}}),[]),y={url:l.url,type:l.type,id:l.id,opensInNewTab:"_blank"===l.target,title:g,...d},E=(0,n.useAnchor)({editableContentElement:h.current,value:i,settings:$}),k=U(E),C=(0,r.useRef)(!!c&&"firstElement");return(0,r.createElement)(v.Popover,{anchor:E,focusOnMount:C.current,onClose:m,placement:"bottom",shift:!0},(0,r.createElement)(a.__experimentalLinkControl,{key:k,value:y,onChange:function(e){e={...d,...e};const r=y.opensInNewTab!==e.opensInNewTab&&y.url===e.url,a=r&&void 0===e.url;if(w(a?e:void 0),a)return;const l=(0,T.prependHTTP)(e.url),c=function(e){let{url:t,type:n,id:r,opensInNewWindow:o}=e;const a={type:"core/link",attributes:{url:t}};return n&&(a.attributes.type=n),r&&(a.attributes.id=r),o&&(a.attributes.target="_blank",a.attributes.rel="noreferrer noopener"),a}({url:l,type:e.type,id:void 0!==e.id&&null!==e.id?String(e.id):void 0,opensInNewWindow:e.opensInNewTab}),h=e.title||l;if((0,n.isCollapsed)(i)&&!t){const e=(0,n.applyFormat)((0,n.create)({text:h}),c,0,h.length);s((0,n.insert)(i,e))}else{let e;if(h===g)e=(0,n.applyFormat)(i,c);else{e=(0,n.create)({text:h}),e=(0,n.applyFormat)(e,c,0,h.length);const t=V(i,{type:"core/link"}),[r,o]=(0,n.split)(i,t.start,t.start),a=(0,n.replace)(o,g,e);e=(0,n.concat)(r,a)}e.start=e.end,e.activeFormats=[],s(e)}r||m(),P(l)?u(t?(0,o.__)("Link edited."):(0,o.__)("Link inserted."),"assertive"):u((0,o.__)("Warning: the link has been inserted but may have errors. Please test it."),"assertive")},onRemove:function(){const e=(0,n.removeFormat)(i,"core/link");s(e),m(),u((0,o.__)("Link removed."),"assertive")},forceIsEditingLink:c,hasRichPreviews:!0,createSuggestion:b&&async function(e){const t=await b({title:e,status:"draft"});return{id:t.id,type:t.type,title:t.title.rendered,url:t.link,kind:"post-type"}},withCreateSuggestion:f,createSuggestionButtonText:function(e){return(0,r.createInterpolateElement)((0,o.sprintf)((0,o.__)("Create Page: <mark>%s</mark>"),e),{mark:(0,r.createElement)("mark",null)})},hasTextControl:!0}))}));const O="core/link",W=(0,o.__)("Link");const $={name:O,title:W,tagName:"a",className:null,attributes:{url:"href",type:"data-type",id:"data-id",target:"target"},__unstablePasteRule(e,t){let{html:r,plainText:o}=t;if((0,n.isCollapsed)(e))return e;const a=(r||o).replace(/<[^>]+>/g,"").trim();return(0,T.isURL)(a)?(window.console.log("Created link:\n\n",a),(0,n.applyFormat)(e,{type:O,attributes:{url:(0,S.decodeEntities)(a)}})):e},edit:function(e){let{isActive:t,activeAttributes:l,value:c,onChange:i,onFocus:s,contentRef:u}=e;const[m,h]=(0,r.useState)(!1);function p(){const e=(0,n.getTextContent)((0,n.slice)(c));e&&(0,T.isURL)(e)&&P(e)?i((0,n.applyFormat)(c,{type:O,attributes:{url:e}})):e&&(0,T.isEmail)(e)?i((0,n.applyFormat)(c,{type:O,attributes:{url:`mailto:${e}`}})):h(!0)}function g(){i((0,n.removeFormat)(c,O)),(0,N.speak)((0,o.__)("Link removed."),"assertive")}return(0,r.createElement)(r.Fragment,null,(0,r.createElement)(a.RichTextShortcut,{type:"primary",character:"k",onUse:p}),(0,r.createElement)(a.RichTextShortcut,{type:"primaryShift",character:"k",onUse:g}),t&&(0,r.createElement)(a.RichTextToolbarButton,{name:"link",icon:F,title:(0,o.__)("Unlink"),onClick:g,isActive:t,shortcutType:"primaryShift",shortcutCharacter:"k"}),!t&&(0,r.createElement)(a.RichTextToolbarButton,{name:"link",icon:A,title:W,onClick:p,isActive:t,shortcutType:"primary",shortcutCharacter:"k"}),(m||t)&&(0,r.createElement)(G,{addingLink:m,stopAddingLink:function(){h(!1),s()},isActive:t,activeAttributes:l,value:c,onChange:i,contentRef:u}))}};var D=(0,r.createElement)(l.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,r.createElement)(l.Path,{d:"M9.1 9v-.5c0-.6.2-1.1.7-1.4.5-.3 1.2-.5 2-.5.7 0 1.4.1 2.1.3.7.2 1.4.5 2.1.9l.2-1.9c-.6-.3-1.2-.5-1.9-.7-.8-.1-1.6-.2-2.4-.2-1.5 0-2.7.3-3.6 1-.8.7-1.2 1.5-1.2 2.6V9h2zM20 12H4v1h8.3c.3.1.6.2.8.3.5.2.9.5 1.1.8.3.3.4.7.4 1.2 0 .7-.2 1.1-.8 1.5-.5.3-1.2.5-2.1.5-.8 0-1.6-.1-2.4-.3-.8-.2-1.5-.5-2.2-.8L7 18.1c.5.2 1.2.4 2 .6.8.2 1.6.3 2.4.3 1.7 0 3-.3 3.9-1 .9-.7 1.3-1.6 1.3-2.8 0-.9-.2-1.7-.7-2.2H20v-1z"}));const Q="core/strikethrough",K=(0,o.__)("Strikethrough"),q={name:Q,title:K,tagName:"s",className:null,edit(e){let{isActive:t,value:o,onChange:l,onFocus:c}=e;function i(){l((0,n.toggleFormat)(o,{type:Q,title:K})),c()}return(0,r.createElement)(r.Fragment,null,(0,r.createElement)(a.RichTextShortcut,{type:"access",character:"d",onUse:i}),(0,r.createElement)(a.RichTextToolbarButton,{icon:D,title:K,onClick:i,isActive:t,role:"menuitemcheckbox"}))}},J="core/underline",X=(0,o.__)("Underline"),Y={name:J,title:X,tagName:"span",className:null,attributes:{style:"style"},edit(e){let{value:t,onChange:o}=e;const l=()=>{o((0,n.toggleFormat)(t,{type:J,attributes:{style:"text-decoration: underline;"},title:X}))};return(0,r.createElement)(r.Fragment,null,(0,r.createElement)(a.RichTextShortcut,{type:"primary",character:"u",onUse:l}),(0,r.createElement)(a.__unstableRichTextInputEvent,{inputType:"formatUnderline",onInput:l}))}};var Z=function(e){let{icon:t,size:n=24,...o}=e;return(0,r.cloneElement)(t,{width:n,height:n,...o})};var ee=(0,r.createElement)(l.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,r.createElement)(l.Path,{d:"M12.9 6h-2l-4 11h1.9l1.1-3h4.2l1.1 3h1.9L12.9 6zm-2.5 6.5l1.5-4.9 1.7 4.9h-3.2z"}));var te=(0,r.createElement)(l.SVG,{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},(0,r.createElement)(l.Path,{d:"M17.2 10.9c-.5-1-1.2-2.1-2.1-3.2-.6-.9-1.3-1.7-2.1-2.6L12 4l-1 1.1c-.6.9-1.3 1.7-2 2.6-.8 1.2-1.5 2.3-2 3.2-.6 1.2-1 2.2-1 3 0 3.4 2.7 6.1 6.1 6.1s6.1-2.7 6.1-6.1c0-.8-.3-1.8-1-3zm-5.1 7.6c-2.5 0-4.6-2.1-4.6-4.6 0-.3.1-1 .8-2.3.5-.9 1.1-1.9 2-3.1.7-.9 1.3-1.7 1.8-2.3.7.8 1.3 1.6 1.8 2.3.8 1.1 1.5 2.2 2 3.1.7 1.3.8 2 .8 2.3 0 2.5-2.1 4.6-4.6 4.6z"}));function ne(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return e.split(";").reduce(((e,t)=>{if(t){const[n,r]=t.split(":");"color"===n&&(e.color=r),"background-color"===n&&r!==ce&&(e.backgroundColor=r)}return e}),{})}function re(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=arguments.length>1?arguments[1]:void 0;return e.split(" ").reduce(((e,n)=>{if(n.startsWith("has-")&&n.endsWith("-color")){const r=n.replace(/^has-/,"").replace(/-color$/,""),o=(0,a.getColorObjectByAttributeValues)(t,r);e.color=o.color}return e}),{})}function oe(e,t,r){const o=(0,n.getActiveFormat)(e,t);return o?{...ne(o.attributes.style),...re(o.attributes.class,r)}:{}}function ae(e){let{name:t,property:o,value:l,onChange:c}=e;const i=(0,R.useSelect)((e=>{var t;const{getSettings:n}=e(a.store);return null!==(t=n().colors)&&void 0!==t?t:[]}),[]),s=(0,r.useCallback)((e=>{c(function(e,t,r,o){const{color:l,backgroundColor:c}={...oe(e,t,r),...o};if(!l&&!c)return(0,n.removeFormat)(e,t);const i=[],s=[],u={};if(c?i.push(["background-color",c].join(":")):i.push(["background-color",ce].join(":")),l){const e=(0,a.getColorObjectByColorValue)(r,l);e?s.push((0,a.getColorClassName)("color",e.slug)):i.push(["color",l].join(":"))}return i.length&&(u.style=i.join(";")),s.length&&(u.class=s.join(" ")),(0,n.applyFormat)(e,{type:t,attributes:u})}(l,t,i,{[o]:e}))}),[i,c,o]),u=(0,r.useMemo)((()=>oe(l,t,i)),[t,l,i]);return(0,r.createElement)(a.ColorPalette,{value:u[o],onChange:s})}function le(e){let{name:t,value:l,onChange:c,onClose:i,contentRef:s}=e;const u=(0,a.useCachedTruthy)((0,n.useAnchor)({editableContentElement:s.current,value:l,settings:he}));return(0,r.createElement)(v.Popover,{onClose:i,className:"components-inline-color-popover",anchor:u},(0,r.createElement)(v.TabPanel,{tabs:[{name:"color",title:(0,o.__)("Text")},{name:"backgroundColor",title:(0,o.__)("Background")}]},(e=>(0,r.createElement)(ae,{name:t,property:e.name,value:l,onChange:c}))))}const ce="rgba(0, 0, 0, 0)",ie="core/text-color",se=(0,o.__)("Highlight"),ue=[];function me(e,t){const{ownerDocument:n}=e,{defaultView:r}=n,o=r.getComputedStyle(e).getPropertyValue(t);return"background-color"===t&&o===ce&&e.parentElement?me(e.parentElement,t):o}const he={name:ie,title:se,tagName:"mark",className:"has-inline-color",attributes:{style:"style",class:"class"},__unstableFilterAttributeValue(e,t){if("style"!==e)return t;if(t&&t.includes("background-color"))return t;const n=["background-color",ce].join(":");return t?[n,t].join(";"):n},edit:function(e){let{value:t,onChange:o,isActive:l,activeAttributes:c,contentRef:i}=e;const s=(0,a.useSetting)("color.custom"),u=(0,a.useSetting)("color.palette")||ue,[m,h]=(0,r.useState)(!1),p=(0,r.useCallback)((()=>h(!0)),[h]),g=(0,r.useCallback)((()=>h(!1)),[h]),v=(0,r.useMemo)((()=>function(e,t){let{color:n,backgroundColor:r}=t;if(n||r)return{color:n||me(e,"color"),backgroundColor:r===ce?me(e,"background-color"):r}}(i.current,oe(t,ie,u))),[t,u]),d=u.length||!s;return d||l?(0,r.createElement)(r.Fragment,null,(0,r.createElement)(a.RichTextToolbarButton,{className:"format-library-text-color-button",isActive:l,icon:(0,r.createElement)(Z,{icon:Object.keys(c).length?ee:te,style:v}),title:se,onClick:d?p:()=>o((0,n.removeFormat)(t,ie)),role:"menuitemcheckbox"}),m&&(0,r.createElement)(le,{name:ie,onClose:g,activeAttributes:c,value:t,onChange:o,contentRef:i})):null}};var pe=(0,r.createElement)(l.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,r.createElement)(l.Path,{d:"M16.9 18.3l.8-1.2c.4-.6.7-1.2.9-1.6.2-.4.3-.8.3-1.2 0-.3-.1-.7-.2-1-.1-.3-.4-.5-.6-.7-.3-.2-.6-.3-1-.3s-.8.1-1.1.2c-.3.1-.7.3-1 .6l.2 1.3c.3-.3.5-.5.8-.6s.6-.2.9-.2c.3 0 .5.1.7.2.2.2.2.4.2.7 0 .3-.1.5-.2.8-.1.3-.4.7-.8 1.3L15 19.4h4.3v-1.2h-2.4zM14.1 7.2h-2L9.5 11 6.9 7.2h-2l3.6 5.3L4.7 18h2l2.7-4 2.7 4h2l-3.8-5.5 3.8-5.3z"}));const ge="core/subscript",ve=(0,o.__)("Subscript"),de={name:ge,title:ve,tagName:"sub",className:null,edit(e){let{isActive:t,value:o,onChange:l,onFocus:c}=e;return(0,r.createElement)(a.RichTextToolbarButton,{icon:pe,title:ve,onClick:function(){l((0,n.toggleFormat)(o,{type:ge,title:ve})),c()},isActive:t,role:"menuitemcheckbox"})}};var we=(0,r.createElement)(l.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,r.createElement)(l.Path,{d:"M16.9 10.3l.8-1.3c.4-.6.7-1.2.9-1.6.2-.4.3-.8.3-1.2 0-.3-.1-.7-.2-1-.2-.2-.4-.4-.7-.6-.3-.2-.6-.3-1-.3s-.8.1-1.1.2c-.3.1-.7.3-1 .6l.1 1.3c.3-.3.5-.5.8-.6s.6-.2.9-.2c.3 0 .5.1.7.2.2.2.2.4.2.7 0 .3-.1.5-.2.8-.1.3-.4.7-.8 1.3l-1.8 2.8h4.3v-1.2h-2.2zm-2.8-3.1h-2L9.5 11 6.9 7.2h-2l3.6 5.3L4.7 18h2l2.7-4 2.7 4h2l-3.8-5.5 3.8-5.3z"}));const be="core/superscript",fe=(0,o.__)("Superscript"),ye={name:be,title:fe,tagName:"sup",className:null,edit(e){let{isActive:t,value:o,onChange:l,onFocus:c}=e;return(0,r.createElement)(a.RichTextToolbarButton,{icon:we,title:fe,onClick:function(){l((0,n.toggleFormat)(o,{type:be,title:fe})),c()},isActive:t,role:"menuitemcheckbox"})}};var Ee=(0,r.createElement)(l.SVG,{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},(0,r.createElement)(l.Path,{d:"M19 6.5H5c-1.1 0-2 .9-2 2v7c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-7c0-1.1-.9-2-2-2zm.5 9c0 .3-.2.5-.5.5H5c-.3 0-.5-.2-.5-.5v-7c0-.3.2-.5.5-.5h14c.3 0 .5.2.5.5v7zM8 12.8h8v-1.5H8v1.5z"}));const ke="core/keyboard",Ce=(0,o.__)("Keyboard input"),xe={name:ke,title:Ce,tagName:"kbd",className:null,edit(e){let{isActive:t,value:o,onChange:l,onFocus:c}=e;return(0,r.createElement)(a.RichTextToolbarButton,{icon:Ee,title:Ce,onClick:function(){l((0,n.toggleFormat)(o,{type:ke,title:Ce})),c()},isActive:t,role:"menuitemcheckbox"})}};var _e=(0,r.createElement)(l.SVG,{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24"},(0,r.createElement)(l.Path,{d:"M12 4.75a7.25 7.25 0 100 14.5 7.25 7.25 0 000-14.5zM3.25 12a8.75 8.75 0 1117.5 0 8.75 8.75 0 01-17.5 0zM12 8.75a1.5 1.5 0 01.167 2.99c-.465.052-.917.44-.917 1.01V14h1.5v-.845A3 3 0 109 10.25h1.5a1.5 1.5 0 011.5-1.5zM11.25 15v1.5h1.5V15h-1.5z"}));const Te="core/unknown",Se=(0,o.__)("Clear Unknown Formatting");[u,g,y,_,$,q,Y,he,de,ye,xe,{name:Te,title:Se,tagName:"*",className:null,edit(e){let{isActive:t,value:o,onChange:l,onFocus:c}=e;const i=(0,n.slice)(o).formats.some((e=>e.some((e=>e.type===Te))));return t||i?(0,r.createElement)(a.RichTextToolbarButton,{name:"unknown",icon:_e,title:Se,onClick:function(){l((0,n.removeFormat)(o,Te)),c()},isActive:!0}):null}}].forEach((e=>{let{name:t,...r}=e;return(0,n.registerFormatType)(t,r)})),(window.wp=window.wp||{}).formatLibrary=t}(); dom-ready.min.js 0000666 00000000762 15123355174 0007564 0 ustar 00 /*! This file is auto-generated */
!function(){"use strict";var e={d:function(t,n){for(var o in n)e.o(n,o)&&!e.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:n[o]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}},t={};function n(e){"undefined"!=typeof document&&("complete"!==document.readyState&&"interactive"!==document.readyState?document.addEventListener("DOMContentLoaded",e):e())}e.d(t,{default:function(){return n}}),(window.wp=window.wp||{}).domReady=t.default}(); block-editor.js 0000666 00011463752 15123355174 0007515 0 ustar 00 /******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 480:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var callBound = __webpack_require__(5304);
var $byteLength = callBound('ArrayBuffer.prototype.byteLength', true);
var isArrayBuffer = __webpack_require__(4602);
/** @type {import('.')} */
module.exports = function byteLength(ab) {
if (!isArrayBuffer(ab)) {
return NaN;
}
return $byteLength ? $byteLength(ab) : ab.byteLength;
}; // in node < 0.11, byteLength is an own nonconfigurable property
/***/ }),
/***/ 5304:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(3803);
var callBind = __webpack_require__(6427);
var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));
module.exports = function callBoundIntrinsic(name, allowMissing) {
var intrinsic = GetIntrinsic(name, !!allowMissing);
if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
return callBind(intrinsic);
}
return intrinsic;
};
/***/ }),
/***/ 6427:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var bind = __webpack_require__(7870);
var GetIntrinsic = __webpack_require__(3803);
var setFunctionLength = __webpack_require__(4521);
var $TypeError = __webpack_require__(1642);
var $apply = GetIntrinsic('%Function.prototype.apply%');
var $call = GetIntrinsic('%Function.prototype.call%');
var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
var $defineProperty = __webpack_require__(8918);
var $max = GetIntrinsic('%Math.max%');
module.exports = function callBind(originalFunction) {
if (typeof originalFunction !== 'function') {
throw new $TypeError('a function is required');
}
var func = $reflectApply(bind, $call, arguments);
return setFunctionLength(
func,
1 + $max(0, originalFunction.length - (arguments.length - 1)),
true
);
};
var applyBind = function applyBind() {
return $reflectApply(bind, $apply, arguments);
};
if ($defineProperty) {
$defineProperty(module.exports, 'apply', { value: applyBind });
} else {
module.exports.apply = applyBind;
}
/***/ }),
/***/ 3303:
/***/ (function(module) {
"use strict";
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var toStr = Object.prototype.toString;
var max = Math.max;
var funcType = '[object Function]';
var concatty = function concatty(a, b) {
var arr = [];
for (var i = 0; i < a.length; i += 1) {
arr[i] = a[i];
}
for (var j = 0; j < b.length; j += 1) {
arr[j + a.length] = b[j];
}
return arr;
};
var slicy = function slicy(arrLike, offset) {
var arr = [];
for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
arr[j] = arrLike[i];
}
return arr;
};
var joiny = function (arr, joiner) {
var str = '';
for (var i = 0; i < arr.length; i += 1) {
str += arr[i];
if (i + 1 < arr.length) {
str += joiner;
}
}
return str;
};
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slicy(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
concatty(args, arguments)
);
if (Object(result) === result) {
return result;
}
return this;
}
return target.apply(
that,
concatty(args, arguments)
);
};
var boundLength = max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs[i] = '$' + i;
}
bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
/***/ }),
/***/ 7870:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(3303);
module.exports = Function.prototype.bind || implementation;
/***/ }),
/***/ 3803:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var undefined;
var $Error = __webpack_require__(6716);
var $EvalError = __webpack_require__(6788);
var $RangeError = __webpack_require__(9204);
var $ReferenceError = __webpack_require__(9908);
var $SyntaxError = __webpack_require__(6724);
var $TypeError = __webpack_require__(1642);
var $URIError = __webpack_require__(1451);
var $Function = Function;
// eslint-disable-next-line consistent-return
var getEvalledConstructor = function (expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
} catch (e) {}
};
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () {
throw new $TypeError();
};
var ThrowTypeError = $gOPD
? (function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}())
: throwTypeError;
var hasSymbols = __webpack_require__(8040)();
var hasProto = __webpack_require__(1856)();
var getProto = Object.getPrototypeOf || (
hasProto
? function (x) { return x.__proto__; } // eslint-disable-line no-proto
: null
);
var needsEval = {};
var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array);
var INTRINSICS = {
__proto__: null,
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
'%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined,
'%AsyncFromSyncIteratorPrototype%': undefined,
'%AsyncFunction%': needsEval,
'%AsyncGenerator%': needsEval,
'%AsyncGeneratorFunction%': needsEval,
'%AsyncIteratorPrototype%': needsEval,
'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,
'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,
'%Boolean%': Boolean,
'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
'%Date%': Date,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': $Error,
'%eval%': eval, // eslint-disable-line no-eval
'%EvalError%': $EvalError,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
'%Function%': $Function,
'%GeneratorFunction%': needsEval,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined,
'%JSON%': typeof JSON === 'object' ? JSON : undefined,
'%Map%': typeof Map === 'undefined' ? undefined : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()),
'%Math%': Math,
'%Number%': Number,
'%Object%': Object,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
'%RangeError%': $RangeError,
'%ReferenceError%': $ReferenceError,
'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
'%RegExp%': RegExp,
'%Set%': typeof Set === 'undefined' ? undefined : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()),
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined,
'%Symbol%': hasSymbols ? Symbol : undefined,
'%SyntaxError%': $SyntaxError,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypeError%': $TypeError,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
'%URIError%': $URIError,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
};
if (getProto) {
try {
null.error; // eslint-disable-line no-unused-expressions
} catch (e) {
// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
var errorProto = getProto(getProto(e));
INTRINSICS['%Error.prototype%'] = errorProto;
}
}
var doEval = function doEval(name) {
var value;
if (name === '%AsyncFunction%') {
value = getEvalledConstructor('async function () {}');
} else if (name === '%GeneratorFunction%') {
value = getEvalledConstructor('function* () {}');
} else if (name === '%AsyncGeneratorFunction%') {
value = getEvalledConstructor('async function* () {}');
} else if (name === '%AsyncGenerator%') {
var fn = doEval('%AsyncGeneratorFunction%');
if (fn) {
value = fn.prototype;
}
} else if (name === '%AsyncIteratorPrototype%') {
var gen = doEval('%AsyncGenerator%');
if (gen && getProto) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name] = value;
return value;
};
var LEGACY_ALIASES = {
__proto__: null,
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
'%ArrayPrototype%': ['Array', 'prototype'],
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
'%BooleanPrototype%': ['Boolean', 'prototype'],
'%DataViewPrototype%': ['DataView', 'prototype'],
'%DatePrototype%': ['Date', 'prototype'],
'%ErrorPrototype%': ['Error', 'prototype'],
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
'%FunctionPrototype%': ['Function', 'prototype'],
'%Generator%': ['GeneratorFunction', 'prototype'],
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
'%JSONParse%': ['JSON', 'parse'],
'%JSONStringify%': ['JSON', 'stringify'],
'%MapPrototype%': ['Map', 'prototype'],
'%NumberPrototype%': ['Number', 'prototype'],
'%ObjectPrototype%': ['Object', 'prototype'],
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
'%PromisePrototype%': ['Promise', 'prototype'],
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
'%Promise_all%': ['Promise', 'all'],
'%Promise_reject%': ['Promise', 'reject'],
'%Promise_resolve%': ['Promise', 'resolve'],
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
'%RegExpPrototype%': ['RegExp', 'prototype'],
'%SetPrototype%': ['Set', 'prototype'],
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
'%StringPrototype%': ['String', 'prototype'],
'%SymbolPrototype%': ['Symbol', 'prototype'],
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
'%URIErrorPrototype%': ['URIError', 'prototype'],
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
'%WeakSetPrototype%': ['WeakSet', 'prototype']
};
var bind = __webpack_require__(7870);
var hasOwn = __webpack_require__(9429);
var $concat = bind.call(Function.call, Array.prototype.concat);
var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
var $replace = bind.call(Function.call, String.prototype.replace);
var $strSlice = bind.call(Function.call, String.prototype.slice);
var $exec = bind.call(Function.call, RegExp.prototype.exec);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
var first = $strSlice(string, 0, 1);
var last = $strSlice(string, -1);
if (first === '%' && last !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
} else if (last === '%' && first !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
}
var result = [];
$replace(string, rePropName, function (match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
var intrinsicName = name;
var alias;
if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
alias = LEGACY_ALIASES[intrinsicName];
intrinsicName = '%' + alias[0] + '%';
}
if (hasOwn(INTRINSICS, intrinsicName)) {
var value = INTRINSICS[intrinsicName];
if (value === needsEval) {
value = doEval(intrinsicName);
}
if (typeof value === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return {
alias: alias,
name: intrinsicName,
value: value
};
}
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
};
module.exports = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new $TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new $TypeError('"allowMissing" argument must be a boolean');
}
if ($exec(/^%?[^%]*%?$/, name) === null) {
throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
}
var parts = stringToPath(name);
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
var intrinsicRealName = intrinsic.name;
var value = intrinsic.value;
var skipFurtherCaching = false;
var alias = intrinsic.alias;
if (alias) {
intrinsicBaseName = alias[0];
$spliceApply(parts, $concat([0, 1], alias));
}
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
var part = parts[i];
var first = $strSlice(part, 0, 1);
var last = $strSlice(part, -1);
if (
(
(first === '"' || first === "'" || first === '`')
|| (last === '"' || last === "'" || last === '`')
)
&& first !== last
) {
throw new $SyntaxError('property names with quotes must have matching quotes');
}
if (part === 'constructor' || !isOwn) {
skipFurtherCaching = true;
}
intrinsicBaseName += '.' + part;
intrinsicRealName = '%' + intrinsicBaseName + '%';
if (hasOwn(INTRINSICS, intrinsicRealName)) {
value = INTRINSICS[intrinsicRealName];
} else if (value != null) {
if (!(part in value)) {
if (!allowMissing) {
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
}
return void undefined;
}
if ($gOPD && (i + 1) >= parts.length) {
var desc = $gOPD(value, part);
isOwn = !!desc;
// By convention, when a data property is converted to an accessor
// property to emulate a data property that does not suffer from
// the override mistake, that accessor's getter is marked with
// an `originalValue` property. Here, when we detect this, we
// uphold the illusion by pretending to see that original data
// property, i.e., returning the value rather than the getter
// itself.
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
value = desc.get;
} else {
value = value[part];
}
} else {
isOwn = hasOwn(value, part);
value = value[part];
}
if (isOwn && !skipFurtherCaching) {
INTRINSICS[intrinsicRealName] = value;
}
}
}
return value;
};
/***/ }),
/***/ 8040:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = __webpack_require__(9063);
module.exports = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return hasSymbolSham();
};
/***/ }),
/***/ 9063:
/***/ (function(module) {
"use strict";
/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
/***/ }),
/***/ 6411:
/***/ (function(module, exports) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
autosize 4.0.4
license: MIT
http://www.jacklmoore.com/autosize
*/
(function (global, factory) {
if (true) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [module, exports], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else { var mod; }
})(this, function (module, exports) {
'use strict';
var map = typeof Map === "function" ? new Map() : function () {
var keys = [];
var values = [];
return {
has: function has(key) {
return keys.indexOf(key) > -1;
},
get: function get(key) {
return values[keys.indexOf(key)];
},
set: function set(key, value) {
if (keys.indexOf(key) === -1) {
keys.push(key);
values.push(value);
}
},
delete: function _delete(key) {
var index = keys.indexOf(key);
if (index > -1) {
keys.splice(index, 1);
values.splice(index, 1);
}
}
};
}();
var createEvent = function createEvent(name) {
return new Event(name, { bubbles: true });
};
try {
new Event('test');
} catch (e) {
// IE does not support `new Event()`
createEvent = function createEvent(name) {
var evt = document.createEvent('Event');
evt.initEvent(name, true, false);
return evt;
};
}
function assign(ta) {
if (!ta || !ta.nodeName || ta.nodeName !== 'TEXTAREA' || map.has(ta)) return;
var heightOffset = null;
var clientWidth = null;
var cachedHeight = null;
function init() {
var style = window.getComputedStyle(ta, null);
if (style.resize === 'vertical') {
ta.style.resize = 'none';
} else if (style.resize === 'both') {
ta.style.resize = 'horizontal';
}
if (style.boxSizing === 'content-box') {
heightOffset = -(parseFloat(style.paddingTop) + parseFloat(style.paddingBottom));
} else {
heightOffset = parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth);
}
// Fix when a textarea is not on document body and heightOffset is Not a Number
if (isNaN(heightOffset)) {
heightOffset = 0;
}
update();
}
function changeOverflow(value) {
{
// Chrome/Safari-specific fix:
// When the textarea y-overflow is hidden, Chrome/Safari do not reflow the text to account for the space
// made available by removing the scrollbar. The following forces the necessary text reflow.
var width = ta.style.width;
ta.style.width = '0px';
// Force reflow:
/* jshint ignore:start */
ta.offsetWidth;
/* jshint ignore:end */
ta.style.width = width;
}
ta.style.overflowY = value;
}
function getParentOverflows(el) {
var arr = [];
while (el && el.parentNode && el.parentNode instanceof Element) {
if (el.parentNode.scrollTop) {
arr.push({
node: el.parentNode,
scrollTop: el.parentNode.scrollTop
});
}
el = el.parentNode;
}
return arr;
}
function resize() {
if (ta.scrollHeight === 0) {
// If the scrollHeight is 0, then the element probably has display:none or is detached from the DOM.
return;
}
var overflows = getParentOverflows(ta);
var docTop = document.documentElement && document.documentElement.scrollTop; // Needed for Mobile IE (ticket #240)
ta.style.height = '';
ta.style.height = ta.scrollHeight + heightOffset + 'px';
// used to check if an update is actually necessary on window.resize
clientWidth = ta.clientWidth;
// prevents scroll-position jumping
overflows.forEach(function (el) {
el.node.scrollTop = el.scrollTop;
});
if (docTop) {
document.documentElement.scrollTop = docTop;
}
}
function update() {
resize();
var styleHeight = Math.round(parseFloat(ta.style.height));
var computed = window.getComputedStyle(ta, null);
// Using offsetHeight as a replacement for computed.height in IE, because IE does not account use of border-box
var actualHeight = computed.boxSizing === 'content-box' ? Math.round(parseFloat(computed.height)) : ta.offsetHeight;
// The actual height not matching the style height (set via the resize method) indicates that
// the max-height has been exceeded, in which case the overflow should be allowed.
if (actualHeight < styleHeight) {
if (computed.overflowY === 'hidden') {
changeOverflow('scroll');
resize();
actualHeight = computed.boxSizing === 'content-box' ? Math.round(parseFloat(window.getComputedStyle(ta, null).height)) : ta.offsetHeight;
}
} else {
// Normally keep overflow set to hidden, to avoid flash of scrollbar as the textarea expands.
if (computed.overflowY !== 'hidden') {
changeOverflow('hidden');
resize();
actualHeight = computed.boxSizing === 'content-box' ? Math.round(parseFloat(window.getComputedStyle(ta, null).height)) : ta.offsetHeight;
}
}
if (cachedHeight !== actualHeight) {
cachedHeight = actualHeight;
var evt = createEvent('autosize:resized');
try {
ta.dispatchEvent(evt);
} catch (err) {
// Firefox will throw an error on dispatchEvent for a detached element
// https://bugzilla.mozilla.org/show_bug.cgi?id=889376
}
}
}
var pageResize = function pageResize() {
if (ta.clientWidth !== clientWidth) {
update();
}
};
var destroy = function (style) {
window.removeEventListener('resize', pageResize, false);
ta.removeEventListener('input', update, false);
ta.removeEventListener('keyup', update, false);
ta.removeEventListener('autosize:destroy', destroy, false);
ta.removeEventListener('autosize:update', update, false);
Object.keys(style).forEach(function (key) {
ta.style[key] = style[key];
});
map.delete(ta);
}.bind(ta, {
height: ta.style.height,
resize: ta.style.resize,
overflowY: ta.style.overflowY,
overflowX: ta.style.overflowX,
wordWrap: ta.style.wordWrap
});
ta.addEventListener('autosize:destroy', destroy, false);
// IE9 does not fire onpropertychange or oninput for deletions,
// so binding to onkeyup to catch most of those events.
// There is no way that I know of to detect something like 'cut' in IE9.
if ('onpropertychange' in ta && 'oninput' in ta) {
ta.addEventListener('keyup', update, false);
}
window.addEventListener('resize', pageResize, false);
ta.addEventListener('input', update, false);
ta.addEventListener('autosize:update', update, false);
ta.style.overflowX = 'hidden';
ta.style.wordWrap = 'break-word';
map.set(ta, {
destroy: destroy,
update: update
});
init();
}
function destroy(ta) {
var methods = map.get(ta);
if (methods) {
methods.destroy();
}
}
function update(ta) {
var methods = map.get(ta);
if (methods) {
methods.update();
}
}
var autosize = null;
// Do nothing in Node.js environment and IE8 (or lower)
if (typeof window === 'undefined' || typeof window.getComputedStyle !== 'function') {
autosize = function autosize(el) {
return el;
};
autosize.destroy = function (el) {
return el;
};
autosize.update = function (el) {
return el;
};
} else {
autosize = function autosize(el, options) {
if (el) {
Array.prototype.forEach.call(el.length ? el : [el], function (x) {
return assign(x, options);
});
}
return el;
};
autosize.destroy = function (el) {
if (el) {
Array.prototype.forEach.call(el.length ? el : [el], destroy);
}
return el;
};
autosize.update = function (el) {
if (el) {
Array.prototype.forEach.call(el.length ? el : [el], update);
}
return el;
};
}
exports.default = autosize;
module.exports = exports['default'];
});
/***/ }),
/***/ 4827:
/***/ (function(module) {
// This code has been refactored for 140 bytes
// You can see the original here: https://github.com/twolfson/computedStyle/blob/04cd1da2e30fa45844f95f5cb1ac898e9b9ef050/lib/computedStyle.js
var computedStyle = function (el, prop, getComputedStyle) {
getComputedStyle = window.getComputedStyle;
// In one fell swoop
return (
// If we have getComputedStyle
getComputedStyle ?
// Query it
// TODO: From CSS-Query notes, we might need (node, null) for FF
getComputedStyle(el) :
// Otherwise, we are in IE and use currentStyle
el.currentStyle
)[
// Switch to camelCase for CSSOM
// DEV: Grabbed from jQuery
// https://github.com/jquery/jquery/blob/1.9-stable/src/css.js#L191-L194
// https://github.com/jquery/jquery/blob/1.9-stable/src/core.js#L593-L597
prop.replace(/-(\w)/gi, function (word, letter) {
return letter.toUpperCase();
})
];
};
module.exports = computedStyle;
/***/ }),
/***/ 2656:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $defineProperty = __webpack_require__(8918);
var $SyntaxError = __webpack_require__(6724);
var $TypeError = __webpack_require__(1642);
var gopd = __webpack_require__(3828);
/** @type {import('.')} */
module.exports = function defineDataProperty(
obj,
property,
value
) {
if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) {
throw new $TypeError('`obj` must be an object or a function`');
}
if (typeof property !== 'string' && typeof property !== 'symbol') {
throw new $TypeError('`property` must be a string or a symbol`');
}
if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) {
throw new $TypeError('`nonEnumerable`, if provided, must be a boolean or null');
}
if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) {
throw new $TypeError('`nonWritable`, if provided, must be a boolean or null');
}
if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) {
throw new $TypeError('`nonConfigurable`, if provided, must be a boolean or null');
}
if (arguments.length > 6 && typeof arguments[6] !== 'boolean') {
throw new $TypeError('`loose`, if provided, must be a boolean');
}
var nonEnumerable = arguments.length > 3 ? arguments[3] : null;
var nonWritable = arguments.length > 4 ? arguments[4] : null;
var nonConfigurable = arguments.length > 5 ? arguments[5] : null;
var loose = arguments.length > 6 ? arguments[6] : false;
/* @type {false | TypedPropertyDescriptor<unknown>} */
var desc = !!gopd && gopd(obj, property);
if ($defineProperty) {
$defineProperty(obj, property, {
configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable,
enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable,
value: value,
writable: nonWritable === null && desc ? desc.writable : !nonWritable
});
} else if (loose || (!nonEnumerable && !nonWritable && !nonConfigurable)) {
// must fall back to [[Set]], and was not explicitly asked to make non-enumerable, non-writable, or non-configurable
obj[property] = value; // eslint-disable-line no-param-reassign
} else {
throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.');
}
};
/***/ }),
/***/ 1198:
/***/ (function(__unused_webpack_module, exports) {
"use strict";
/*istanbul ignore start*/
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = Diff;
/*istanbul ignore end*/
function Diff() {}
Diff.prototype = {
/*istanbul ignore start*/
/*istanbul ignore end*/
diff: function diff(oldString, newString) {
/*istanbul ignore start*/
var
/*istanbul ignore end*/
options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var callback = options.callback;
if (typeof options === 'function') {
callback = options;
options = {};
}
this.options = options;
var self = this;
function done(value) {
if (callback) {
setTimeout(function () {
callback(undefined, value);
}, 0);
return true;
} else {
return value;
}
} // Allow subclasses to massage the input prior to running
oldString = this.castInput(oldString);
newString = this.castInput(newString);
oldString = this.removeEmpty(this.tokenize(oldString));
newString = this.removeEmpty(this.tokenize(newString));
var newLen = newString.length,
oldLen = oldString.length;
var editLength = 1;
var maxEditLength = newLen + oldLen;
var bestPath = [{
newPos: -1,
components: []
}]; // Seed editLength = 0, i.e. the content starts with the same values
var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
// Identity per the equality and tokenizer
return done([{
value: this.join(newString),
count: newString.length
}]);
} // Main worker method. checks all permutations of a given edit length for acceptance.
function execEditLength() {
for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
var basePath =
/*istanbul ignore start*/
void 0
/*istanbul ignore end*/
;
var addPath = bestPath[diagonalPath - 1],
removePath = bestPath[diagonalPath + 1],
_oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
if (addPath) {
// No one else is going to attempt to use this value, clear it
bestPath[diagonalPath - 1] = undefined;
}
var canAdd = addPath && addPath.newPos + 1 < newLen,
canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
if (!canAdd && !canRemove) {
// If this path is a terminal then prune
bestPath[diagonalPath] = undefined;
continue;
} // Select the diagonal that we want to branch from. We select the prior
// path whose position in the new string is the farthest from the origin
// and does not pass the bounds of the diff graph
if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
basePath = clonePath(removePath);
self.pushComponent(basePath.components, undefined, true);
} else {
basePath = addPath; // No need to clone, we've pulled it from the list
basePath.newPos++;
self.pushComponent(basePath.components, true, undefined);
}
_oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done
if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
} else {
// Otherwise track this path as a potential candidate and continue.
bestPath[diagonalPath] = basePath;
}
}
editLength++;
} // Performs the length of edit iteration. Is a bit fugly as this has to support the
// sync and async mode which is never fun. Loops over execEditLength until a value
// is produced.
if (callback) {
(function exec() {
setTimeout(function () {
// This should not happen, but we want to be safe.
/* istanbul ignore next */
if (editLength > maxEditLength) {
return callback();
}
if (!execEditLength()) {
exec();
}
}, 0);
})();
} else {
while (editLength <= maxEditLength) {
var ret = execEditLength();
if (ret) {
return ret;
}
}
}
},
/*istanbul ignore start*/
/*istanbul ignore end*/
pushComponent: function pushComponent(components, added, removed) {
var last = components[components.length - 1];
if (last && last.added === added && last.removed === removed) {
// We need to clone here as the component clone operation is just
// as shallow array clone
components[components.length - 1] = {
count: last.count + 1,
added: added,
removed: removed
};
} else {
components.push({
count: 1,
added: added,
removed: removed
});
}
},
/*istanbul ignore start*/
/*istanbul ignore end*/
extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
var newLen = newString.length,
oldLen = oldString.length,
newPos = basePath.newPos,
oldPos = newPos - diagonalPath,
commonCount = 0;
while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
newPos++;
oldPos++;
commonCount++;
}
if (commonCount) {
basePath.components.push({
count: commonCount
});
}
basePath.newPos = newPos;
return oldPos;
},
/*istanbul ignore start*/
/*istanbul ignore end*/
equals: function equals(left, right) {
if (this.options.comparator) {
return this.options.comparator(left, right);
} else {
return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
}
},
/*istanbul ignore start*/
/*istanbul ignore end*/
removeEmpty: function removeEmpty(array) {
var ret = [];
for (var i = 0; i < array.length; i++) {
if (array[i]) {
ret.push(array[i]);
}
}
return ret;
},
/*istanbul ignore start*/
/*istanbul ignore end*/
castInput: function castInput(value) {
return value;
},
/*istanbul ignore start*/
/*istanbul ignore end*/
tokenize: function tokenize(value) {
return value.split('');
},
/*istanbul ignore start*/
/*istanbul ignore end*/
join: function join(chars) {
return chars.join('');
}
};
function buildValues(diff, components, newString, oldString, useLongestToken) {
var componentPos = 0,
componentLen = components.length,
newPos = 0,
oldPos = 0;
for (; componentPos < componentLen; componentPos++) {
var component = components[componentPos];
if (!component.removed) {
if (!component.added && useLongestToken) {
var value = newString.slice(newPos, newPos + component.count);
value = value.map(function (value, i) {
var oldValue = oldString[oldPos + i];
return oldValue.length > value.length ? oldValue : value;
});
component.value = diff.join(value);
} else {
component.value = diff.join(newString.slice(newPos, newPos + component.count));
}
newPos += component.count; // Common case
if (!component.added) {
oldPos += component.count;
}
} else {
component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
oldPos += component.count; // Reverse add and remove so removes are output first to match common convention
// The diffing algorithm is tied to add then remove output and this is the simplest
// route to get the desired output with minimal overhead.
if (componentPos && components[componentPos - 1].added) {
var tmp = components[componentPos - 1];
components[componentPos - 1] = components[componentPos];
components[componentPos] = tmp;
}
}
} // Special case handle for when one terminal is ignored (i.e. whitespace).
// For this case we merge the terminal into the prior string and drop the change.
// This is only available for string mode.
var lastComponent = components[componentLen - 1];
if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
components[componentLen - 2].value += lastComponent.value;
components.pop();
}
return components;
}
function clonePath(path) {
return {
newPos: path.newPos,
components: path.components.slice(0)
};
}
/***/ }),
/***/ 1973:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __webpack_unused_export__;
/*istanbul ignore start*/
__webpack_unused_export__ = ({
value: true
});
exports.Kx = diffChars;
__webpack_unused_export__ = void 0;
/*istanbul ignore end*/
var
/*istanbul ignore start*/
_base = _interopRequireDefault(__webpack_require__(1198))
/*istanbul ignore end*/
;
/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/*istanbul ignore end*/
var characterDiff = new
/*istanbul ignore start*/
_base
/*istanbul ignore end*/
.
/*istanbul ignore start*/
default
/*istanbul ignore end*/
();
/*istanbul ignore start*/
__webpack_unused_export__ = characterDiff;
/*istanbul ignore end*/
function diffChars(oldStr, newStr, options) {
return characterDiff.diff(oldStr, newStr, options);
}
/***/ }),
/***/ 1345:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var util = __webpack_require__(5022);
function scrollIntoView(elem, container, config) {
config = config || {};
// document 归一化到 window
if (container.nodeType === 9) {
container = util.getWindow(container);
}
var allowHorizontalScroll = config.allowHorizontalScroll;
var onlyScrollIfNeeded = config.onlyScrollIfNeeded;
var alignWithTop = config.alignWithTop;
var alignWithLeft = config.alignWithLeft;
var offsetTop = config.offsetTop || 0;
var offsetLeft = config.offsetLeft || 0;
var offsetBottom = config.offsetBottom || 0;
var offsetRight = config.offsetRight || 0;
allowHorizontalScroll = allowHorizontalScroll === undefined ? true : allowHorizontalScroll;
var isWin = util.isWindow(container);
var elemOffset = util.offset(elem);
var eh = util.outerHeight(elem);
var ew = util.outerWidth(elem);
var containerOffset = undefined;
var ch = undefined;
var cw = undefined;
var containerScroll = undefined;
var diffTop = undefined;
var diffBottom = undefined;
var win = undefined;
var winScroll = undefined;
var ww = undefined;
var wh = undefined;
if (isWin) {
win = container;
wh = util.height(win);
ww = util.width(win);
winScroll = {
left: util.scrollLeft(win),
top: util.scrollTop(win)
};
// elem 相对 container 可视视窗的距离
diffTop = {
left: elemOffset.left - winScroll.left - offsetLeft,
top: elemOffset.top - winScroll.top - offsetTop
};
diffBottom = {
left: elemOffset.left + ew - (winScroll.left + ww) + offsetRight,
top: elemOffset.top + eh - (winScroll.top + wh) + offsetBottom
};
containerScroll = winScroll;
} else {
containerOffset = util.offset(container);
ch = container.clientHeight;
cw = container.clientWidth;
containerScroll = {
left: container.scrollLeft,
top: container.scrollTop
};
// elem 相对 container 可视视窗的距离
// 注意边框, offset 是边框到根节点
diffTop = {
left: elemOffset.left - (containerOffset.left + (parseFloat(util.css(container, 'borderLeftWidth')) || 0)) - offsetLeft,
top: elemOffset.top - (containerOffset.top + (parseFloat(util.css(container, 'borderTopWidth')) || 0)) - offsetTop
};
diffBottom = {
left: elemOffset.left + ew - (containerOffset.left + cw + (parseFloat(util.css(container, 'borderRightWidth')) || 0)) + offsetRight,
top: elemOffset.top + eh - (containerOffset.top + ch + (parseFloat(util.css(container, 'borderBottomWidth')) || 0)) + offsetBottom
};
}
if (diffTop.top < 0 || diffBottom.top > 0) {
// 强制向上
if (alignWithTop === true) {
util.scrollTop(container, containerScroll.top + diffTop.top);
} else if (alignWithTop === false) {
util.scrollTop(container, containerScroll.top + diffBottom.top);
} else {
// 自动调整
if (diffTop.top < 0) {
util.scrollTop(container, containerScroll.top + diffTop.top);
} else {
util.scrollTop(container, containerScroll.top + diffBottom.top);
}
}
} else {
if (!onlyScrollIfNeeded) {
alignWithTop = alignWithTop === undefined ? true : !!alignWithTop;
if (alignWithTop) {
util.scrollTop(container, containerScroll.top + diffTop.top);
} else {
util.scrollTop(container, containerScroll.top + diffBottom.top);
}
}
}
if (allowHorizontalScroll) {
if (diffTop.left < 0 || diffBottom.left > 0) {
// 强制向上
if (alignWithLeft === true) {
util.scrollLeft(container, containerScroll.left + diffTop.left);
} else if (alignWithLeft === false) {
util.scrollLeft(container, containerScroll.left + diffBottom.left);
} else {
// 自动调整
if (diffTop.left < 0) {
util.scrollLeft(container, containerScroll.left + diffTop.left);
} else {
util.scrollLeft(container, containerScroll.left + diffBottom.left);
}
}
} else {
if (!onlyScrollIfNeeded) {
alignWithLeft = alignWithLeft === undefined ? true : !!alignWithLeft;
if (alignWithLeft) {
util.scrollLeft(container, containerScroll.left + diffTop.left);
} else {
util.scrollLeft(container, containerScroll.left + diffBottom.left);
}
}
}
}
}
module.exports = scrollIntoView;
/***/ }),
/***/ 5425:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(1345);
/***/ }),
/***/ 5022:
/***/ (function(module) {
"use strict";
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
var RE_NUM = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source;
function getClientPosition(elem) {
var box = undefined;
var x = undefined;
var y = undefined;
var doc = elem.ownerDocument;
var body = doc.body;
var docElem = doc && doc.documentElement;
// 根据 GBS 最新数据,A-Grade Browsers 都已支持 getBoundingClientRect 方法,不用再考虑传统的实现方式
box = elem.getBoundingClientRect();
// 注:jQuery 还考虑减去 docElem.clientLeft/clientTop
// 但测试发现,这样反而会导致当 html 和 body 有边距/边框样式时,获取的值不正确
// 此外,ie6 会忽略 html 的 margin 值,幸运地是没有谁会去设置 html 的 margin
x = box.left;
y = box.top;
// In IE, most of the time, 2 extra pixels are added to the top and left
// due to the implicit 2-pixel inset border. In IE6/7 quirks mode and
// IE6 standards mode, this border can be overridden by setting the
// document element's border to zero -- thus, we cannot rely on the
// offset always being 2 pixels.
// In quirks mode, the offset can be determined by querying the body's
// clientLeft/clientTop, but in standards mode, it is found by querying
// the document element's clientLeft/clientTop. Since we already called
// getClientBoundingRect we have already forced a reflow, so it is not
// too expensive just to query them all.
// ie 下应该减去窗口的边框吧,毕竟默认 absolute 都是相对窗口定位的
// 窗口边框标准是设 documentElement ,quirks 时设置 body
// 最好禁止在 body 和 html 上边框 ,但 ie < 9 html 默认有 2px ,减去
// 但是非 ie 不可能设置窗口边框,body html 也不是窗口 ,ie 可以通过 html,body 设置
// 标准 ie 下 docElem.clientTop 就是 border-top
// ie7 html 即窗口边框改变不了。永远为 2
// 但标准 firefox/chrome/ie9 下 docElem.clientTop 是窗口边框,即使设了 border-top 也为 0
x -= docElem.clientLeft || body.clientLeft || 0;
y -= docElem.clientTop || body.clientTop || 0;
return {
left: x,
top: y
};
}
function getScroll(w, top) {
var ret = w['page' + (top ? 'Y' : 'X') + 'Offset'];
var method = 'scroll' + (top ? 'Top' : 'Left');
if (typeof ret !== 'number') {
var d = w.document;
// ie6,7,8 standard mode
ret = d.documentElement[method];
if (typeof ret !== 'number') {
// quirks mode
ret = d.body[method];
}
}
return ret;
}
function getScrollLeft(w) {
return getScroll(w);
}
function getScrollTop(w) {
return getScroll(w, true);
}
function getOffset(el) {
var pos = getClientPosition(el);
var doc = el.ownerDocument;
var w = doc.defaultView || doc.parentWindow;
pos.left += getScrollLeft(w);
pos.top += getScrollTop(w);
return pos;
}
function _getComputedStyle(elem, name, computedStyle_) {
var val = '';
var d = elem.ownerDocument;
var computedStyle = computedStyle_ || d.defaultView.getComputedStyle(elem, null);
// https://github.com/kissyteam/kissy/issues/61
if (computedStyle) {
val = computedStyle.getPropertyValue(name) || computedStyle[name];
}
return val;
}
var _RE_NUM_NO_PX = new RegExp('^(' + RE_NUM + ')(?!px)[a-z%]+$', 'i');
var RE_POS = /^(top|right|bottom|left)$/;
var CURRENT_STYLE = 'currentStyle';
var RUNTIME_STYLE = 'runtimeStyle';
var LEFT = 'left';
var PX = 'px';
function _getComputedStyleIE(elem, name) {
// currentStyle maybe null
// http://msdn.microsoft.com/en-us/library/ms535231.aspx
var ret = elem[CURRENT_STYLE] && elem[CURRENT_STYLE][name];
// 当 width/height 设置为百分比时,通过 pixelLeft 方式转换的 width/height 值
// 一开始就处理了! CUSTOM_STYLE.height,CUSTOM_STYLE.width ,cssHook 解决@2011-08-19
// 在 ie 下不对,需要直接用 offset 方式
// borderWidth 等值也有问题,但考虑到 borderWidth 设为百分比的概率很小,这里就不考虑了
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// exclude left right for relativity
if (_RE_NUM_NO_PX.test(ret) && !RE_POS.test(name)) {
// Remember the original values
var style = elem.style;
var left = style[LEFT];
var rsLeft = elem[RUNTIME_STYLE][LEFT];
// prevent flashing of content
elem[RUNTIME_STYLE][LEFT] = elem[CURRENT_STYLE][LEFT];
// Put in the new values to get a computed value out
style[LEFT] = name === 'fontSize' ? '1em' : ret || 0;
ret = style.pixelLeft + PX;
// Revert the changed values
style[LEFT] = left;
elem[RUNTIME_STYLE][LEFT] = rsLeft;
}
return ret === '' ? 'auto' : ret;
}
var getComputedStyleX = undefined;
if (typeof window !== 'undefined') {
getComputedStyleX = window.getComputedStyle ? _getComputedStyle : _getComputedStyleIE;
}
function each(arr, fn) {
for (var i = 0; i < arr.length; i++) {
fn(arr[i]);
}
}
function isBorderBoxFn(elem) {
return getComputedStyleX(elem, 'boxSizing') === 'border-box';
}
var BOX_MODELS = ['margin', 'border', 'padding'];
var CONTENT_INDEX = -1;
var PADDING_INDEX = 2;
var BORDER_INDEX = 1;
var MARGIN_INDEX = 0;
function swap(elem, options, callback) {
var old = {};
var style = elem.style;
var name = undefined;
// Remember the old values, and insert the new ones
for (name in options) {
if (options.hasOwnProperty(name)) {
old[name] = style[name];
style[name] = options[name];
}
}
callback.call(elem);
// Revert the old values
for (name in options) {
if (options.hasOwnProperty(name)) {
style[name] = old[name];
}
}
}
function getPBMWidth(elem, props, which) {
var value = 0;
var prop = undefined;
var j = undefined;
var i = undefined;
for (j = 0; j < props.length; j++) {
prop = props[j];
if (prop) {
for (i = 0; i < which.length; i++) {
var cssProp = undefined;
if (prop === 'border') {
cssProp = prop + which[i] + 'Width';
} else {
cssProp = prop + which[i];
}
value += parseFloat(getComputedStyleX(elem, cssProp)) || 0;
}
}
}
return value;
}
/**
* A crude way of determining if an object is a window
* @member util
*/
function isWindow(obj) {
// must use == for ie8
/* eslint eqeqeq:0 */
return obj != null && obj == obj.window;
}
var domUtils = {};
each(['Width', 'Height'], function (name) {
domUtils['doc' + name] = function (refWin) {
var d = refWin.document;
return Math.max(
// firefox chrome documentElement.scrollHeight< body.scrollHeight
// ie standard mode : documentElement.scrollHeight> body.scrollHeight
d.documentElement['scroll' + name],
// quirks : documentElement.scrollHeight 最大等于可视窗口多一点?
d.body['scroll' + name], domUtils['viewport' + name](d));
};
domUtils['viewport' + name] = function (win) {
// pc browser includes scrollbar in window.innerWidth
var prop = 'client' + name;
var doc = win.document;
var body = doc.body;
var documentElement = doc.documentElement;
var documentElementProp = documentElement[prop];
// 标准模式取 documentElement
// backcompat 取 body
return doc.compatMode === 'CSS1Compat' && documentElementProp || body && body[prop] || documentElementProp;
};
});
/*
得到元素的大小信息
@param elem
@param name
@param {String} [extra] 'padding' : (css width) + padding
'border' : (css width) + padding + border
'margin' : (css width) + padding + border + margin
*/
function getWH(elem, name, extra) {
if (isWindow(elem)) {
return name === 'width' ? domUtils.viewportWidth(elem) : domUtils.viewportHeight(elem);
} else if (elem.nodeType === 9) {
return name === 'width' ? domUtils.docWidth(elem) : domUtils.docHeight(elem);
}
var which = name === 'width' ? ['Left', 'Right'] : ['Top', 'Bottom'];
var borderBoxValue = name === 'width' ? elem.offsetWidth : elem.offsetHeight;
var computedStyle = getComputedStyleX(elem);
var isBorderBox = isBorderBoxFn(elem, computedStyle);
var cssBoxValue = 0;
if (borderBoxValue == null || borderBoxValue <= 0) {
borderBoxValue = undefined;
// Fall back to computed then un computed css if necessary
cssBoxValue = getComputedStyleX(elem, name);
if (cssBoxValue == null || Number(cssBoxValue) < 0) {
cssBoxValue = elem.style[name] || 0;
}
// Normalize '', auto, and prepare for extra
cssBoxValue = parseFloat(cssBoxValue) || 0;
}
if (extra === undefined) {
extra = isBorderBox ? BORDER_INDEX : CONTENT_INDEX;
}
var borderBoxValueOrIsBorderBox = borderBoxValue !== undefined || isBorderBox;
var val = borderBoxValue || cssBoxValue;
if (extra === CONTENT_INDEX) {
if (borderBoxValueOrIsBorderBox) {
return val - getPBMWidth(elem, ['border', 'padding'], which, computedStyle);
}
return cssBoxValue;
}
if (borderBoxValueOrIsBorderBox) {
var padding = extra === PADDING_INDEX ? -getPBMWidth(elem, ['border'], which, computedStyle) : getPBMWidth(elem, ['margin'], which, computedStyle);
return val + (extra === BORDER_INDEX ? 0 : padding);
}
return cssBoxValue + getPBMWidth(elem, BOX_MODELS.slice(extra), which, computedStyle);
}
var cssShow = {
position: 'absolute',
visibility: 'hidden',
display: 'block'
};
// fix #119 : https://github.com/kissyteam/kissy/issues/119
function getWHIgnoreDisplay(elem) {
var val = undefined;
var args = arguments;
// in case elem is window
// elem.offsetWidth === undefined
if (elem.offsetWidth !== 0) {
val = getWH.apply(undefined, args);
} else {
swap(elem, cssShow, function () {
val = getWH.apply(undefined, args);
});
}
return val;
}
function css(el, name, v) {
var value = v;
if ((typeof name === 'undefined' ? 'undefined' : _typeof(name)) === 'object') {
for (var i in name) {
if (name.hasOwnProperty(i)) {
css(el, i, name[i]);
}
}
return undefined;
}
if (typeof value !== 'undefined') {
if (typeof value === 'number') {
value += 'px';
}
el.style[name] = value;
return undefined;
}
return getComputedStyleX(el, name);
}
each(['width', 'height'], function (name) {
var first = name.charAt(0).toUpperCase() + name.slice(1);
domUtils['outer' + first] = function (el, includeMargin) {
return el && getWHIgnoreDisplay(el, name, includeMargin ? MARGIN_INDEX : BORDER_INDEX);
};
var which = name === 'width' ? ['Left', 'Right'] : ['Top', 'Bottom'];
domUtils[name] = function (elem, val) {
if (val !== undefined) {
if (elem) {
var computedStyle = getComputedStyleX(elem);
var isBorderBox = isBorderBoxFn(elem);
if (isBorderBox) {
val += getPBMWidth(elem, ['padding', 'border'], which, computedStyle);
}
return css(elem, name, val);
}
return undefined;
}
return elem && getWHIgnoreDisplay(elem, name, CONTENT_INDEX);
};
});
// 设置 elem 相对 elem.ownerDocument 的坐标
function setOffset(elem, offset) {
// set position first, in-case top/left are set even on static elem
if (css(elem, 'position') === 'static') {
elem.style.position = 'relative';
}
var old = getOffset(elem);
var ret = {};
var current = undefined;
var key = undefined;
for (key in offset) {
if (offset.hasOwnProperty(key)) {
current = parseFloat(css(elem, key)) || 0;
ret[key] = current + offset[key] - old[key];
}
}
css(elem, ret);
}
module.exports = _extends({
getWindow: function getWindow(node) {
var doc = node.ownerDocument || node;
return doc.defaultView || doc.parentWindow;
},
offset: function offset(el, value) {
if (typeof value !== 'undefined') {
setOffset(el, value);
} else {
return getOffset(el);
}
},
isWindow: isWindow,
each: each,
css: css,
clone: function clone(obj) {
var ret = {};
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
ret[i] = obj[i];
}
}
var overflow = obj.overflow;
if (overflow) {
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
ret.overflow[i] = obj.overflow[i];
}
}
}
return ret;
},
scrollLeft: function scrollLeft(w, v) {
if (isWindow(w)) {
if (v === undefined) {
return getScrollLeft(w);
}
window.scrollTo(v, getScrollTop(w));
} else {
if (v === undefined) {
return w.scrollLeft;
}
w.scrollLeft = v;
}
},
scrollTop: function scrollTop(w, v) {
if (isWindow(w)) {
if (v === undefined) {
return getScrollTop(w);
}
window.scrollTo(getScrollLeft(w), v);
} else {
if (v === undefined) {
return w.scrollTop;
}
w.scrollTop = v;
}
},
viewportWidth: 0,
viewportHeight: 0
}, domUtils);
/***/ }),
/***/ 8918:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(292);
/** @type {import('.')} */
var $defineProperty = GetIntrinsic('%Object.defineProperty%', true) || false;
if ($defineProperty) {
try {
$defineProperty({}, 'a', { value: 1 });
} catch (e) {
// IE 8 has a broken defineProperty
$defineProperty = false;
}
}
module.exports = $defineProperty;
/***/ }),
/***/ 3592:
/***/ (function(module) {
"use strict";
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var toStr = Object.prototype.toString;
var max = Math.max;
var funcType = '[object Function]';
var concatty = function concatty(a, b) {
var arr = [];
for (var i = 0; i < a.length; i += 1) {
arr[i] = a[i];
}
for (var j = 0; j < b.length; j += 1) {
arr[j + a.length] = b[j];
}
return arr;
};
var slicy = function slicy(arrLike, offset) {
var arr = [];
for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
arr[j] = arrLike[i];
}
return arr;
};
var joiny = function (arr, joiner) {
var str = '';
for (var i = 0; i < arr.length; i += 1) {
str += arr[i];
if (i + 1 < arr.length) {
str += joiner;
}
}
return str;
};
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slicy(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
concatty(args, arguments)
);
if (Object(result) === result) {
return result;
}
return this;
}
return target.apply(
that,
concatty(args, arguments)
);
};
var boundLength = max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs[i] = '$' + i;
}
bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
/***/ }),
/***/ 5903:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(3592);
module.exports = Function.prototype.bind || implementation;
/***/ }),
/***/ 292:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var undefined;
var $Error = __webpack_require__(6716);
var $EvalError = __webpack_require__(6788);
var $RangeError = __webpack_require__(9204);
var $ReferenceError = __webpack_require__(9908);
var $SyntaxError = __webpack_require__(6724);
var $TypeError = __webpack_require__(1642);
var $URIError = __webpack_require__(1451);
var $Function = Function;
// eslint-disable-next-line consistent-return
var getEvalledConstructor = function (expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
} catch (e) {}
};
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () {
throw new $TypeError();
};
var ThrowTypeError = $gOPD
? (function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}())
: throwTypeError;
var hasSymbols = __webpack_require__(4482)();
var hasProto = __webpack_require__(1856)();
var getProto = Object.getPrototypeOf || (
hasProto
? function (x) { return x.__proto__; } // eslint-disable-line no-proto
: null
);
var needsEval = {};
var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array);
var INTRINSICS = {
__proto__: null,
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
'%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined,
'%AsyncFromSyncIteratorPrototype%': undefined,
'%AsyncFunction%': needsEval,
'%AsyncGenerator%': needsEval,
'%AsyncGeneratorFunction%': needsEval,
'%AsyncIteratorPrototype%': needsEval,
'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,
'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,
'%Boolean%': Boolean,
'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
'%Date%': Date,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': $Error,
'%eval%': eval, // eslint-disable-line no-eval
'%EvalError%': $EvalError,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
'%Function%': $Function,
'%GeneratorFunction%': needsEval,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined,
'%JSON%': typeof JSON === 'object' ? JSON : undefined,
'%Map%': typeof Map === 'undefined' ? undefined : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()),
'%Math%': Math,
'%Number%': Number,
'%Object%': Object,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
'%RangeError%': $RangeError,
'%ReferenceError%': $ReferenceError,
'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
'%RegExp%': RegExp,
'%Set%': typeof Set === 'undefined' ? undefined : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()),
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined,
'%Symbol%': hasSymbols ? Symbol : undefined,
'%SyntaxError%': $SyntaxError,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypeError%': $TypeError,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
'%URIError%': $URIError,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
};
if (getProto) {
try {
null.error; // eslint-disable-line no-unused-expressions
} catch (e) {
// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
var errorProto = getProto(getProto(e));
INTRINSICS['%Error.prototype%'] = errorProto;
}
}
var doEval = function doEval(name) {
var value;
if (name === '%AsyncFunction%') {
value = getEvalledConstructor('async function () {}');
} else if (name === '%GeneratorFunction%') {
value = getEvalledConstructor('function* () {}');
} else if (name === '%AsyncGeneratorFunction%') {
value = getEvalledConstructor('async function* () {}');
} else if (name === '%AsyncGenerator%') {
var fn = doEval('%AsyncGeneratorFunction%');
if (fn) {
value = fn.prototype;
}
} else if (name === '%AsyncIteratorPrototype%') {
var gen = doEval('%AsyncGenerator%');
if (gen && getProto) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name] = value;
return value;
};
var LEGACY_ALIASES = {
__proto__: null,
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
'%ArrayPrototype%': ['Array', 'prototype'],
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
'%BooleanPrototype%': ['Boolean', 'prototype'],
'%DataViewPrototype%': ['DataView', 'prototype'],
'%DatePrototype%': ['Date', 'prototype'],
'%ErrorPrototype%': ['Error', 'prototype'],
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
'%FunctionPrototype%': ['Function', 'prototype'],
'%Generator%': ['GeneratorFunction', 'prototype'],
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
'%JSONParse%': ['JSON', 'parse'],
'%JSONStringify%': ['JSON', 'stringify'],
'%MapPrototype%': ['Map', 'prototype'],
'%NumberPrototype%': ['Number', 'prototype'],
'%ObjectPrototype%': ['Object', 'prototype'],
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
'%PromisePrototype%': ['Promise', 'prototype'],
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
'%Promise_all%': ['Promise', 'all'],
'%Promise_reject%': ['Promise', 'reject'],
'%Promise_resolve%': ['Promise', 'resolve'],
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
'%RegExpPrototype%': ['RegExp', 'prototype'],
'%SetPrototype%': ['Set', 'prototype'],
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
'%StringPrototype%': ['String', 'prototype'],
'%SymbolPrototype%': ['Symbol', 'prototype'],
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
'%URIErrorPrototype%': ['URIError', 'prototype'],
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
'%WeakSetPrototype%': ['WeakSet', 'prototype']
};
var bind = __webpack_require__(5903);
var hasOwn = __webpack_require__(9429);
var $concat = bind.call(Function.call, Array.prototype.concat);
var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
var $replace = bind.call(Function.call, String.prototype.replace);
var $strSlice = bind.call(Function.call, String.prototype.slice);
var $exec = bind.call(Function.call, RegExp.prototype.exec);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
var first = $strSlice(string, 0, 1);
var last = $strSlice(string, -1);
if (first === '%' && last !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
} else if (last === '%' && first !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
}
var result = [];
$replace(string, rePropName, function (match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
var intrinsicName = name;
var alias;
if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
alias = LEGACY_ALIASES[intrinsicName];
intrinsicName = '%' + alias[0] + '%';
}
if (hasOwn(INTRINSICS, intrinsicName)) {
var value = INTRINSICS[intrinsicName];
if (value === needsEval) {
value = doEval(intrinsicName);
}
if (typeof value === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return {
alias: alias,
name: intrinsicName,
value: value
};
}
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
};
module.exports = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new $TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new $TypeError('"allowMissing" argument must be a boolean');
}
if ($exec(/^%?[^%]*%?$/, name) === null) {
throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
}
var parts = stringToPath(name);
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
var intrinsicRealName = intrinsic.name;
var value = intrinsic.value;
var skipFurtherCaching = false;
var alias = intrinsic.alias;
if (alias) {
intrinsicBaseName = alias[0];
$spliceApply(parts, $concat([0, 1], alias));
}
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
var part = parts[i];
var first = $strSlice(part, 0, 1);
var last = $strSlice(part, -1);
if (
(
(first === '"' || first === "'" || first === '`')
|| (last === '"' || last === "'" || last === '`')
)
&& first !== last
) {
throw new $SyntaxError('property names with quotes must have matching quotes');
}
if (part === 'constructor' || !isOwn) {
skipFurtherCaching = true;
}
intrinsicBaseName += '.' + part;
intrinsicRealName = '%' + intrinsicBaseName + '%';
if (hasOwn(INTRINSICS, intrinsicRealName)) {
value = INTRINSICS[intrinsicRealName];
} else if (value != null) {
if (!(part in value)) {
if (!allowMissing) {
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
}
return void undefined;
}
if ($gOPD && (i + 1) >= parts.length) {
var desc = $gOPD(value, part);
isOwn = !!desc;
// By convention, when a data property is converted to an accessor
// property to emulate a data property that does not suffer from
// the override mistake, that accessor's getter is marked with
// an `originalValue` property. Here, when we detect this, we
// uphold the illusion by pretending to see that original data
// property, i.e., returning the value rather than the getter
// itself.
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
value = desc.get;
} else {
value = value[part];
}
} else {
isOwn = hasOwn(value, part);
value = value[part];
}
if (isOwn && !skipFurtherCaching) {
INTRINSICS[intrinsicRealName] = value;
}
}
}
return value;
};
/***/ }),
/***/ 4482:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = __webpack_require__(7457);
module.exports = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return hasSymbolSham();
};
/***/ }),
/***/ 7457:
/***/ (function(module) {
"use strict";
/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
/***/ }),
/***/ 6788:
/***/ (function(module) {
"use strict";
/** @type {import('./eval')} */
module.exports = EvalError;
/***/ }),
/***/ 6716:
/***/ (function(module) {
"use strict";
/** @type {import('.')} */
module.exports = Error;
/***/ }),
/***/ 9204:
/***/ (function(module) {
"use strict";
/** @type {import('./range')} */
module.exports = RangeError;
/***/ }),
/***/ 9908:
/***/ (function(module) {
"use strict";
/** @type {import('./ref')} */
module.exports = ReferenceError;
/***/ }),
/***/ 6724:
/***/ (function(module) {
"use strict";
/** @type {import('./syntax')} */
module.exports = SyntaxError;
/***/ }),
/***/ 1642:
/***/ (function(module) {
"use strict";
/** @type {import('./type')} */
module.exports = TypeError;
/***/ }),
/***/ 1451:
/***/ (function(module) {
"use strict";
/** @type {import('./uri')} */
module.exports = URIError;
/***/ }),
/***/ 7998:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $TypeError = __webpack_require__(1642);
/** @type {import('./RequireObjectCoercible')} */
module.exports = function RequireObjectCoercible(value) {
if (value == null) {
throw new $TypeError((arguments.length > 0 && arguments[1]) || ('Cannot call method on ' + value));
}
return value;
};
/***/ }),
/***/ 5249:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol';
var isPrimitive = __webpack_require__(3777);
var isCallable = __webpack_require__(5443);
var isDate = __webpack_require__(8659);
var isSymbol = __webpack_require__(3082);
var ordinaryToPrimitive = function OrdinaryToPrimitive(O, hint) {
if (typeof O === 'undefined' || O === null) {
throw new TypeError('Cannot call method on ' + O);
}
if (typeof hint !== 'string' || (hint !== 'number' && hint !== 'string')) {
throw new TypeError('hint must be "string" or "number"');
}
var methodNames = hint === 'string' ? ['toString', 'valueOf'] : ['valueOf', 'toString'];
var method, result, i;
for (i = 0; i < methodNames.length; ++i) {
method = O[methodNames[i]];
if (isCallable(method)) {
result = method.call(O);
if (isPrimitive(result)) {
return result;
}
}
}
throw new TypeError('No default value');
};
var GetMethod = function GetMethod(O, P) {
var func = O[P];
if (func !== null && typeof func !== 'undefined') {
if (!isCallable(func)) {
throw new TypeError(func + ' returned for property ' + P + ' of object ' + O + ' is not a function');
}
return func;
}
return void 0;
};
// http://www.ecma-international.org/ecma-262/6.0/#sec-toprimitive
module.exports = function ToPrimitive(input) {
if (isPrimitive(input)) {
return input;
}
var hint = 'default';
if (arguments.length > 1) {
if (arguments[1] === String) {
hint = 'string';
} else if (arguments[1] === Number) {
hint = 'number';
}
}
var exoticToPrim;
if (hasSymbols) {
if (Symbol.toPrimitive) {
exoticToPrim = GetMethod(input, Symbol.toPrimitive);
} else if (isSymbol(input)) {
exoticToPrim = Symbol.prototype.valueOf;
}
}
if (typeof exoticToPrim !== 'undefined') {
var result = exoticToPrim.call(input, hint);
if (isPrimitive(result)) {
return result;
}
throw new TypeError('unable to convert exotic object to primitive');
}
if (hint === 'default' && (isDate(input) || isSymbol(input))) {
hint = 'string';
}
return ordinaryToPrimitive(input, hint === 'default' ? 'number' : hint);
};
/***/ }),
/***/ 3777:
/***/ (function(module) {
"use strict";
module.exports = function isPrimitive(value) {
return value === null || (typeof value !== 'function' && typeof value !== 'object');
};
/***/ }),
/***/ 5619:
/***/ (function(module) {
"use strict";
// do not edit .js files directly - edit src/index.jst
var envHasBigInt64Array = typeof BigInt64Array !== 'undefined';
module.exports = function equal(a, b) {
if (a === b) return true;
if (a && b && typeof a == 'object' && typeof b == 'object') {
if (a.constructor !== b.constructor) return false;
var length, i, keys;
if (Array.isArray(a)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (!equal(a[i], b[i])) return false;
return true;
}
if ((a instanceof Map) && (b instanceof Map)) {
if (a.size !== b.size) return false;
for (i of a.entries())
if (!b.has(i[0])) return false;
for (i of a.entries())
if (!equal(i[1], b.get(i[0]))) return false;
return true;
}
if ((a instanceof Set) && (b instanceof Set)) {
if (a.size !== b.size) return false;
for (i of a.entries())
if (!b.has(i[0])) return false;
return true;
}
if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (a[i] !== b[i]) return false;
return true;
}
if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) return false;
for (i = length; i-- !== 0;)
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
for (i = length; i-- !== 0;) {
var key = keys[i];
if (!equal(a[key], b[key])) return false;
}
return true;
}
// true if both NaN, false otherwise
return a!==a && b!==b;
};
/***/ }),
/***/ 4843:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isCallable = __webpack_require__(5443);
var toStr = Object.prototype.toString;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var forEachArray = function forEachArray(array, iterator, receiver) {
for (var i = 0, len = array.length; i < len; i++) {
if (hasOwnProperty.call(array, i)) {
if (receiver == null) {
iterator(array[i], i, array);
} else {
iterator.call(receiver, array[i], i, array);
}
}
}
};
var forEachString = function forEachString(string, iterator, receiver) {
for (var i = 0, len = string.length; i < len; i++) {
// no such thing as a sparse string.
if (receiver == null) {
iterator(string.charAt(i), i, string);
} else {
iterator.call(receiver, string.charAt(i), i, string);
}
}
};
var forEachObject = function forEachObject(object, iterator, receiver) {
for (var k in object) {
if (hasOwnProperty.call(object, k)) {
if (receiver == null) {
iterator(object[k], k, object);
} else {
iterator.call(receiver, object[k], k, object);
}
}
}
};
var forEach = function forEach(list, iterator, thisArg) {
if (!isCallable(iterator)) {
throw new TypeError('iterator must be a function');
}
var receiver;
if (arguments.length >= 3) {
receiver = thisArg;
}
if (toStr.call(list) === '[object Array]') {
forEachArray(list, iterator, receiver);
} else if (typeof list === 'string') {
forEachString(list, iterator, receiver);
} else {
forEachObject(list, iterator, receiver);
}
};
module.exports = forEach;
/***/ }),
/***/ 3828:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(2473);
var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);
if ($gOPD) {
try {
$gOPD([], 'length');
} catch (e) {
// IE 8 has a broken gOPD
$gOPD = null;
}
}
module.exports = $gOPD;
/***/ }),
/***/ 8819:
/***/ (function(module) {
"use strict";
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var toStr = Object.prototype.toString;
var max = Math.max;
var funcType = '[object Function]';
var concatty = function concatty(a, b) {
var arr = [];
for (var i = 0; i < a.length; i += 1) {
arr[i] = a[i];
}
for (var j = 0; j < b.length; j += 1) {
arr[j + a.length] = b[j];
}
return arr;
};
var slicy = function slicy(arrLike, offset) {
var arr = [];
for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
arr[j] = arrLike[i];
}
return arr;
};
var joiny = function (arr, joiner) {
var str = '';
for (var i = 0; i < arr.length; i += 1) {
str += arr[i];
if (i + 1 < arr.length) {
str += joiner;
}
}
return str;
};
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slicy(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
concatty(args, arguments)
);
if (Object(result) === result) {
return result;
}
return this;
}
return target.apply(
that,
concatty(args, arguments)
);
};
var boundLength = max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs[i] = '$' + i;
}
bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
/***/ }),
/***/ 8729:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(8819);
module.exports = Function.prototype.bind || implementation;
/***/ }),
/***/ 2473:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var undefined;
var $Error = __webpack_require__(6716);
var $EvalError = __webpack_require__(6788);
var $RangeError = __webpack_require__(9204);
var $ReferenceError = __webpack_require__(9908);
var $SyntaxError = __webpack_require__(6724);
var $TypeError = __webpack_require__(1642);
var $URIError = __webpack_require__(1451);
var $Function = Function;
// eslint-disable-next-line consistent-return
var getEvalledConstructor = function (expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
} catch (e) {}
};
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () {
throw new $TypeError();
};
var ThrowTypeError = $gOPD
? (function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}())
: throwTypeError;
var hasSymbols = __webpack_require__(5810)();
var hasProto = __webpack_require__(1856)();
var getProto = Object.getPrototypeOf || (
hasProto
? function (x) { return x.__proto__; } // eslint-disable-line no-proto
: null
);
var needsEval = {};
var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array);
var INTRINSICS = {
__proto__: null,
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
'%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined,
'%AsyncFromSyncIteratorPrototype%': undefined,
'%AsyncFunction%': needsEval,
'%AsyncGenerator%': needsEval,
'%AsyncGeneratorFunction%': needsEval,
'%AsyncIteratorPrototype%': needsEval,
'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,
'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,
'%Boolean%': Boolean,
'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
'%Date%': Date,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': $Error,
'%eval%': eval, // eslint-disable-line no-eval
'%EvalError%': $EvalError,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
'%Function%': $Function,
'%GeneratorFunction%': needsEval,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined,
'%JSON%': typeof JSON === 'object' ? JSON : undefined,
'%Map%': typeof Map === 'undefined' ? undefined : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()),
'%Math%': Math,
'%Number%': Number,
'%Object%': Object,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
'%RangeError%': $RangeError,
'%ReferenceError%': $ReferenceError,
'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
'%RegExp%': RegExp,
'%Set%': typeof Set === 'undefined' ? undefined : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()),
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined,
'%Symbol%': hasSymbols ? Symbol : undefined,
'%SyntaxError%': $SyntaxError,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypeError%': $TypeError,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
'%URIError%': $URIError,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
};
if (getProto) {
try {
null.error; // eslint-disable-line no-unused-expressions
} catch (e) {
// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
var errorProto = getProto(getProto(e));
INTRINSICS['%Error.prototype%'] = errorProto;
}
}
var doEval = function doEval(name) {
var value;
if (name === '%AsyncFunction%') {
value = getEvalledConstructor('async function () {}');
} else if (name === '%GeneratorFunction%') {
value = getEvalledConstructor('function* () {}');
} else if (name === '%AsyncGeneratorFunction%') {
value = getEvalledConstructor('async function* () {}');
} else if (name === '%AsyncGenerator%') {
var fn = doEval('%AsyncGeneratorFunction%');
if (fn) {
value = fn.prototype;
}
} else if (name === '%AsyncIteratorPrototype%') {
var gen = doEval('%AsyncGenerator%');
if (gen && getProto) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name] = value;
return value;
};
var LEGACY_ALIASES = {
__proto__: null,
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
'%ArrayPrototype%': ['Array', 'prototype'],
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
'%BooleanPrototype%': ['Boolean', 'prototype'],
'%DataViewPrototype%': ['DataView', 'prototype'],
'%DatePrototype%': ['Date', 'prototype'],
'%ErrorPrototype%': ['Error', 'prototype'],
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
'%FunctionPrototype%': ['Function', 'prototype'],
'%Generator%': ['GeneratorFunction', 'prototype'],
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
'%JSONParse%': ['JSON', 'parse'],
'%JSONStringify%': ['JSON', 'stringify'],
'%MapPrototype%': ['Map', 'prototype'],
'%NumberPrototype%': ['Number', 'prototype'],
'%ObjectPrototype%': ['Object', 'prototype'],
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
'%PromisePrototype%': ['Promise', 'prototype'],
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
'%Promise_all%': ['Promise', 'all'],
'%Promise_reject%': ['Promise', 'reject'],
'%Promise_resolve%': ['Promise', 'resolve'],
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
'%RegExpPrototype%': ['RegExp', 'prototype'],
'%SetPrototype%': ['Set', 'prototype'],
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
'%StringPrototype%': ['String', 'prototype'],
'%SymbolPrototype%': ['Symbol', 'prototype'],
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
'%URIErrorPrototype%': ['URIError', 'prototype'],
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
'%WeakSetPrototype%': ['WeakSet', 'prototype']
};
var bind = __webpack_require__(8729);
var hasOwn = __webpack_require__(9429);
var $concat = bind.call(Function.call, Array.prototype.concat);
var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
var $replace = bind.call(Function.call, String.prototype.replace);
var $strSlice = bind.call(Function.call, String.prototype.slice);
var $exec = bind.call(Function.call, RegExp.prototype.exec);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
var first = $strSlice(string, 0, 1);
var last = $strSlice(string, -1);
if (first === '%' && last !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
} else if (last === '%' && first !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
}
var result = [];
$replace(string, rePropName, function (match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
var intrinsicName = name;
var alias;
if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
alias = LEGACY_ALIASES[intrinsicName];
intrinsicName = '%' + alias[0] + '%';
}
if (hasOwn(INTRINSICS, intrinsicName)) {
var value = INTRINSICS[intrinsicName];
if (value === needsEval) {
value = doEval(intrinsicName);
}
if (typeof value === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return {
alias: alias,
name: intrinsicName,
value: value
};
}
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
};
module.exports = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new $TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new $TypeError('"allowMissing" argument must be a boolean');
}
if ($exec(/^%?[^%]*%?$/, name) === null) {
throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
}
var parts = stringToPath(name);
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
var intrinsicRealName = intrinsic.name;
var value = intrinsic.value;
var skipFurtherCaching = false;
var alias = intrinsic.alias;
if (alias) {
intrinsicBaseName = alias[0];
$spliceApply(parts, $concat([0, 1], alias));
}
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
var part = parts[i];
var first = $strSlice(part, 0, 1);
var last = $strSlice(part, -1);
if (
(
(first === '"' || first === "'" || first === '`')
|| (last === '"' || last === "'" || last === '`')
)
&& first !== last
) {
throw new $SyntaxError('property names with quotes must have matching quotes');
}
if (part === 'constructor' || !isOwn) {
skipFurtherCaching = true;
}
intrinsicBaseName += '.' + part;
intrinsicRealName = '%' + intrinsicBaseName + '%';
if (hasOwn(INTRINSICS, intrinsicRealName)) {
value = INTRINSICS[intrinsicRealName];
} else if (value != null) {
if (!(part in value)) {
if (!allowMissing) {
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
}
return void undefined;
}
if ($gOPD && (i + 1) >= parts.length) {
var desc = $gOPD(value, part);
isOwn = !!desc;
// By convention, when a data property is converted to an accessor
// property to emulate a data property that does not suffer from
// the override mistake, that accessor's getter is marked with
// an `originalValue` property. Here, when we detect this, we
// uphold the illusion by pretending to see that original data
// property, i.e., returning the value rather than the getter
// itself.
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
value = desc.get;
} else {
value = value[part];
}
} else {
isOwn = hasOwn(value, part);
value = value[part];
}
if (isOwn && !skipFurtherCaching) {
INTRINSICS[intrinsicRealName] = value;
}
}
}
return value;
};
/***/ }),
/***/ 5810:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = __webpack_require__(1759);
module.exports = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return hasSymbolSham();
};
/***/ }),
/***/ 1759:
/***/ (function(module) {
"use strict";
/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
/***/ }),
/***/ 8198:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $defineProperty = __webpack_require__(8918);
var hasPropertyDescriptors = function hasPropertyDescriptors() {
return !!$defineProperty;
};
hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() {
// node v0.6 has a bug where array lengths can be Set but not Defined
if (!$defineProperty) {
return null;
}
try {
return $defineProperty([], 'length', { value: 1 }).length !== 1;
} catch (e) {
// In Firefox 4-22, defining length on an array throws an exception.
return true;
}
};
module.exports = hasPropertyDescriptors;
/***/ }),
/***/ 1856:
/***/ (function(module) {
"use strict";
var test = {
__proto__: null,
foo: {}
};
var $Object = Object;
/** @type {import('.')} */
module.exports = function hasProto() {
// @ts-expect-error: TS errors on an inherited property for some reason
return { __proto__: test }.foo === test.foo
&& !(test instanceof $Object);
};
/***/ }),
/***/ 9905:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var origSymbol = __webpack_require__.g.Symbol;
var hasSymbolSham = __webpack_require__(5682);
module.exports = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return hasSymbolSham();
};
/***/ }),
/***/ 5682:
/***/ (function(module) {
"use strict";
/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
/***/ }),
/***/ 81:
/***/ (function(module) {
"use strict";
/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
/***/ }),
/***/ 4111:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var hasSymbols = __webpack_require__(81);
/** @type {import('.')} */
module.exports = function hasToStringTagShams() {
return hasSymbols() && !!Symbol.toStringTag;
};
/***/ }),
/***/ 9429:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var call = Function.prototype.call;
var $hasOwn = Object.prototype.hasOwnProperty;
var bind = __webpack_require__(766);
/** @type {import('.')} */
module.exports = bind.call(call, $hasOwn);
/***/ }),
/***/ 2075:
/***/ (function(module) {
"use strict";
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var toStr = Object.prototype.toString;
var max = Math.max;
var funcType = '[object Function]';
var concatty = function concatty(a, b) {
var arr = [];
for (var i = 0; i < a.length; i += 1) {
arr[i] = a[i];
}
for (var j = 0; j < b.length; j += 1) {
arr[j + a.length] = b[j];
}
return arr;
};
var slicy = function slicy(arrLike, offset) {
var arr = [];
for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
arr[j] = arrLike[i];
}
return arr;
};
var joiny = function (arr, joiner) {
var str = '';
for (var i = 0; i < arr.length; i += 1) {
str += arr[i];
if (i + 1 < arr.length) {
str += joiner;
}
}
return str;
};
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slicy(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
concatty(args, arguments)
);
if (Object(result) === result) {
return result;
}
return this;
}
return target.apply(
that,
concatty(args, arguments)
);
};
var boundLength = max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs[i] = '$' + i;
}
bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
/***/ }),
/***/ 766:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(2075);
module.exports = Function.prototype.bind || implementation;
/***/ }),
/***/ 8575:
/***/ (function(module) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
})
}
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
}
/***/ }),
/***/ 4602:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var callBind = __webpack_require__(4374);
var callBound = __webpack_require__(7442);
var GetIntrinsic = __webpack_require__(3767);
var $ArrayBuffer = GetIntrinsic('%ArrayBuffer%', true);
/** @type {undefined | ((receiver: ArrayBuffer) => number) | ((receiver: unknown) => never)} */
var $byteLength = callBound('ArrayBuffer.prototype.byteLength', true);
var $toString = callBound('Object.prototype.toString');
// in node 0.10, ArrayBuffers have no prototype methods, but have an own slot-checking `slice` method
var abSlice = !!$ArrayBuffer && !$byteLength && new $ArrayBuffer(0).slice;
var $abSlice = !!abSlice && callBind(abSlice);
/** @type {import('.')} */
module.exports = $byteLength || $abSlice
? function isArrayBuffer(obj) {
if (!obj || typeof obj !== 'object') {
return false;
}
try {
if ($byteLength) {
// @ts-expect-error no idea why TS can't handle the overload
$byteLength(obj);
} else {
// @ts-expect-error TS chooses not to type-narrow inside a closure
$abSlice(obj, 0);
}
return true;
} catch (e) {
return false;
}
}
: $ArrayBuffer
// in node 0.8, ArrayBuffers have no prototype or own methods, but also no Symbol.toStringTag
? function isArrayBuffer(obj) {
return $toString(obj) === '[object ArrayBuffer]';
}
: function isArrayBuffer(obj) { // eslint-disable-line no-unused-vars
return false;
};
/***/ }),
/***/ 7442:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(3767);
var callBind = __webpack_require__(4374);
var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));
module.exports = function callBoundIntrinsic(name, allowMissing) {
var intrinsic = GetIntrinsic(name, !!allowMissing);
if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
return callBind(intrinsic);
}
return intrinsic;
};
/***/ }),
/***/ 4374:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var bind = __webpack_require__(7410);
var GetIntrinsic = __webpack_require__(3767);
var setFunctionLength = __webpack_require__(4521);
var $TypeError = __webpack_require__(1642);
var $apply = GetIntrinsic('%Function.prototype.apply%');
var $call = GetIntrinsic('%Function.prototype.call%');
var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
var $defineProperty = __webpack_require__(8918);
var $max = GetIntrinsic('%Math.max%');
module.exports = function callBind(originalFunction) {
if (typeof originalFunction !== 'function') {
throw new $TypeError('a function is required');
}
var func = $reflectApply(bind, $call, arguments);
return setFunctionLength(
func,
1 + $max(0, originalFunction.length - (arguments.length - 1)),
true
);
};
var applyBind = function applyBind() {
return $reflectApply(bind, $apply, arguments);
};
if ($defineProperty) {
$defineProperty(module.exports, 'apply', { value: applyBind });
} else {
module.exports.apply = applyBind;
}
/***/ }),
/***/ 1818:
/***/ (function(module) {
"use strict";
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var toStr = Object.prototype.toString;
var max = Math.max;
var funcType = '[object Function]';
var concatty = function concatty(a, b) {
var arr = [];
for (var i = 0; i < a.length; i += 1) {
arr[i] = a[i];
}
for (var j = 0; j < b.length; j += 1) {
arr[j + a.length] = b[j];
}
return arr;
};
var slicy = function slicy(arrLike, offset) {
var arr = [];
for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
arr[j] = arrLike[i];
}
return arr;
};
var joiny = function (arr, joiner) {
var str = '';
for (var i = 0; i < arr.length; i += 1) {
str += arr[i];
if (i + 1 < arr.length) {
str += joiner;
}
}
return str;
};
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slicy(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
concatty(args, arguments)
);
if (Object(result) === result) {
return result;
}
return this;
}
return target.apply(
that,
concatty(args, arguments)
);
};
var boundLength = max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs[i] = '$' + i;
}
bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
/***/ }),
/***/ 7410:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(1818);
module.exports = Function.prototype.bind || implementation;
/***/ }),
/***/ 3767:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var undefined;
var $Error = __webpack_require__(6716);
var $EvalError = __webpack_require__(6788);
var $RangeError = __webpack_require__(9204);
var $ReferenceError = __webpack_require__(9908);
var $SyntaxError = __webpack_require__(6724);
var $TypeError = __webpack_require__(1642);
var $URIError = __webpack_require__(1451);
var $Function = Function;
// eslint-disable-next-line consistent-return
var getEvalledConstructor = function (expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
} catch (e) {}
};
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () {
throw new $TypeError();
};
var ThrowTypeError = $gOPD
? (function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}())
: throwTypeError;
var hasSymbols = __webpack_require__(6945)();
var hasProto = __webpack_require__(1856)();
var getProto = Object.getPrototypeOf || (
hasProto
? function (x) { return x.__proto__; } // eslint-disable-line no-proto
: null
);
var needsEval = {};
var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array);
var INTRINSICS = {
__proto__: null,
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
'%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined,
'%AsyncFromSyncIteratorPrototype%': undefined,
'%AsyncFunction%': needsEval,
'%AsyncGenerator%': needsEval,
'%AsyncGeneratorFunction%': needsEval,
'%AsyncIteratorPrototype%': needsEval,
'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,
'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,
'%Boolean%': Boolean,
'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
'%Date%': Date,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': $Error,
'%eval%': eval, // eslint-disable-line no-eval
'%EvalError%': $EvalError,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
'%Function%': $Function,
'%GeneratorFunction%': needsEval,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined,
'%JSON%': typeof JSON === 'object' ? JSON : undefined,
'%Map%': typeof Map === 'undefined' ? undefined : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()),
'%Math%': Math,
'%Number%': Number,
'%Object%': Object,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
'%RangeError%': $RangeError,
'%ReferenceError%': $ReferenceError,
'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
'%RegExp%': RegExp,
'%Set%': typeof Set === 'undefined' ? undefined : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()),
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined,
'%Symbol%': hasSymbols ? Symbol : undefined,
'%SyntaxError%': $SyntaxError,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypeError%': $TypeError,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
'%URIError%': $URIError,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
};
if (getProto) {
try {
null.error; // eslint-disable-line no-unused-expressions
} catch (e) {
// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
var errorProto = getProto(getProto(e));
INTRINSICS['%Error.prototype%'] = errorProto;
}
}
var doEval = function doEval(name) {
var value;
if (name === '%AsyncFunction%') {
value = getEvalledConstructor('async function () {}');
} else if (name === '%GeneratorFunction%') {
value = getEvalledConstructor('function* () {}');
} else if (name === '%AsyncGeneratorFunction%') {
value = getEvalledConstructor('async function* () {}');
} else if (name === '%AsyncGenerator%') {
var fn = doEval('%AsyncGeneratorFunction%');
if (fn) {
value = fn.prototype;
}
} else if (name === '%AsyncIteratorPrototype%') {
var gen = doEval('%AsyncGenerator%');
if (gen && getProto) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name] = value;
return value;
};
var LEGACY_ALIASES = {
__proto__: null,
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
'%ArrayPrototype%': ['Array', 'prototype'],
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
'%BooleanPrototype%': ['Boolean', 'prototype'],
'%DataViewPrototype%': ['DataView', 'prototype'],
'%DatePrototype%': ['Date', 'prototype'],
'%ErrorPrototype%': ['Error', 'prototype'],
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
'%FunctionPrototype%': ['Function', 'prototype'],
'%Generator%': ['GeneratorFunction', 'prototype'],
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
'%JSONParse%': ['JSON', 'parse'],
'%JSONStringify%': ['JSON', 'stringify'],
'%MapPrototype%': ['Map', 'prototype'],
'%NumberPrototype%': ['Number', 'prototype'],
'%ObjectPrototype%': ['Object', 'prototype'],
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
'%PromisePrototype%': ['Promise', 'prototype'],
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
'%Promise_all%': ['Promise', 'all'],
'%Promise_reject%': ['Promise', 'reject'],
'%Promise_resolve%': ['Promise', 'resolve'],
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
'%RegExpPrototype%': ['RegExp', 'prototype'],
'%SetPrototype%': ['Set', 'prototype'],
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
'%StringPrototype%': ['String', 'prototype'],
'%SymbolPrototype%': ['Symbol', 'prototype'],
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
'%URIErrorPrototype%': ['URIError', 'prototype'],
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
'%WeakSetPrototype%': ['WeakSet', 'prototype']
};
var bind = __webpack_require__(7410);
var hasOwn = __webpack_require__(9429);
var $concat = bind.call(Function.call, Array.prototype.concat);
var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
var $replace = bind.call(Function.call, String.prototype.replace);
var $strSlice = bind.call(Function.call, String.prototype.slice);
var $exec = bind.call(Function.call, RegExp.prototype.exec);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
var first = $strSlice(string, 0, 1);
var last = $strSlice(string, -1);
if (first === '%' && last !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
} else if (last === '%' && first !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
}
var result = [];
$replace(string, rePropName, function (match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
var intrinsicName = name;
var alias;
if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
alias = LEGACY_ALIASES[intrinsicName];
intrinsicName = '%' + alias[0] + '%';
}
if (hasOwn(INTRINSICS, intrinsicName)) {
var value = INTRINSICS[intrinsicName];
if (value === needsEval) {
value = doEval(intrinsicName);
}
if (typeof value === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return {
alias: alias,
name: intrinsicName,
value: value
};
}
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
};
module.exports = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new $TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new $TypeError('"allowMissing" argument must be a boolean');
}
if ($exec(/^%?[^%]*%?$/, name) === null) {
throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
}
var parts = stringToPath(name);
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
var intrinsicRealName = intrinsic.name;
var value = intrinsic.value;
var skipFurtherCaching = false;
var alias = intrinsic.alias;
if (alias) {
intrinsicBaseName = alias[0];
$spliceApply(parts, $concat([0, 1], alias));
}
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
var part = parts[i];
var first = $strSlice(part, 0, 1);
var last = $strSlice(part, -1);
if (
(
(first === '"' || first === "'" || first === '`')
|| (last === '"' || last === "'" || last === '`')
)
&& first !== last
) {
throw new $SyntaxError('property names with quotes must have matching quotes');
}
if (part === 'constructor' || !isOwn) {
skipFurtherCaching = true;
}
intrinsicBaseName += '.' + part;
intrinsicRealName = '%' + intrinsicBaseName + '%';
if (hasOwn(INTRINSICS, intrinsicRealName)) {
value = INTRINSICS[intrinsicRealName];
} else if (value != null) {
if (!(part in value)) {
if (!allowMissing) {
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
}
return void undefined;
}
if ($gOPD && (i + 1) >= parts.length) {
var desc = $gOPD(value, part);
isOwn = !!desc;
// By convention, when a data property is converted to an accessor
// property to emulate a data property that does not suffer from
// the override mistake, that accessor's getter is marked with
// an `originalValue` property. Here, when we detect this, we
// uphold the illusion by pretending to see that original data
// property, i.e., returning the value rather than the getter
// itself.
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
value = desc.get;
} else {
value = value[part];
}
} else {
isOwn = hasOwn(value, part);
value = value[part];
}
if (isOwn && !skipFurtherCaching) {
INTRINSICS[intrinsicRealName] = value;
}
}
}
return value;
};
/***/ }),
/***/ 6945:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = __webpack_require__(6992);
module.exports = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return hasSymbolSham();
};
/***/ }),
/***/ 6992:
/***/ (function(module) {
"use strict";
/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
/***/ }),
/***/ 5443:
/***/ (function(module) {
"use strict";
var fnToStr = Function.prototype.toString;
var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply;
var badArrayLike;
var isCallableMarker;
if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') {
try {
badArrayLike = Object.defineProperty({}, 'length', {
get: function () {
throw isCallableMarker;
}
});
isCallableMarker = {};
// eslint-disable-next-line no-throw-literal
reflectApply(function () { throw 42; }, null, badArrayLike);
} catch (_) {
if (_ !== isCallableMarker) {
reflectApply = null;
}
}
} else {
reflectApply = null;
}
var constructorRegex = /^\s*class\b/;
var isES6ClassFn = function isES6ClassFunction(value) {
try {
var fnStr = fnToStr.call(value);
return constructorRegex.test(fnStr);
} catch (e) {
return false; // not a function
}
};
var tryFunctionObject = function tryFunctionToStr(value) {
try {
if (isES6ClassFn(value)) { return false; }
fnToStr.call(value);
return true;
} catch (e) {
return false;
}
};
var toStr = Object.prototype.toString;
var fnClass = '[object Function]';
var genClass = '[object GeneratorFunction]';
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
module.exports = reflectApply
? function isCallable(value) {
if (!value) { return false; }
if (typeof value !== 'function' && typeof value !== 'object') { return false; }
if (typeof value === 'function' && !value.prototype) { return true; }
try {
reflectApply(value, null, badArrayLike);
} catch (e) {
if (e !== isCallableMarker) { return false; }
}
return !isES6ClassFn(value);
}
: function isCallable(value) {
if (!value) { return false; }
if (typeof value !== 'function' && typeof value !== 'object') { return false; }
if (typeof value === 'function' && !value.prototype) { return true; }
if (hasToStringTag) { return tryFunctionObject(value); }
if (isES6ClassFn(value)) { return false; }
var strClass = toStr.call(value);
return strClass === fnClass || strClass === genClass;
};
/***/ }),
/***/ 8659:
/***/ (function(module) {
"use strict";
var getDay = Date.prototype.getDay;
var tryDateObject = function tryDateGetDayCall(value) {
try {
getDay.call(value);
return true;
} catch (e) {
return false;
}
};
var toStr = Object.prototype.toString;
var dateClass = '[object Date]';
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
module.exports = function isDateObject(value) {
if (typeof value !== 'object' || value === null) {
return false;
}
return hasToStringTag ? tryDateObject(value) : toStr.call(value) === dateClass;
};
/***/ }),
/***/ 5604:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var callBound = __webpack_require__(6131);
var $byteLength = callBound('SharedArrayBuffer.prototype.byteLength', true);
/** @type {import('.')} */
module.exports = $byteLength
? function isSharedArrayBuffer(obj) {
if (!obj || typeof obj !== 'object') {
return false;
}
try {
$byteLength(obj);
return true;
} catch (e) {
return false;
}
}
: function isSharedArrayBuffer(obj) { // eslint-disable-line no-unused-vars
return false;
};
/***/ }),
/***/ 6131:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(6254);
var callBind = __webpack_require__(7679);
var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));
module.exports = function callBoundIntrinsic(name, allowMissing) {
var intrinsic = GetIntrinsic(name, !!allowMissing);
if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
return callBind(intrinsic);
}
return intrinsic;
};
/***/ }),
/***/ 7679:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var bind = __webpack_require__(578);
var GetIntrinsic = __webpack_require__(6254);
var setFunctionLength = __webpack_require__(4521);
var $TypeError = __webpack_require__(1642);
var $apply = GetIntrinsic('%Function.prototype.apply%');
var $call = GetIntrinsic('%Function.prototype.call%');
var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
var $defineProperty = __webpack_require__(8918);
var $max = GetIntrinsic('%Math.max%');
module.exports = function callBind(originalFunction) {
if (typeof originalFunction !== 'function') {
throw new $TypeError('a function is required');
}
var func = $reflectApply(bind, $call, arguments);
return setFunctionLength(
func,
1 + $max(0, originalFunction.length - (arguments.length - 1)),
true
);
};
var applyBind = function applyBind() {
return $reflectApply(bind, $apply, arguments);
};
if ($defineProperty) {
$defineProperty(module.exports, 'apply', { value: applyBind });
} else {
module.exports.apply = applyBind;
}
/***/ }),
/***/ 901:
/***/ (function(module) {
"use strict";
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var toStr = Object.prototype.toString;
var max = Math.max;
var funcType = '[object Function]';
var concatty = function concatty(a, b) {
var arr = [];
for (var i = 0; i < a.length; i += 1) {
arr[i] = a[i];
}
for (var j = 0; j < b.length; j += 1) {
arr[j + a.length] = b[j];
}
return arr;
};
var slicy = function slicy(arrLike, offset) {
var arr = [];
for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
arr[j] = arrLike[i];
}
return arr;
};
var joiny = function (arr, joiner) {
var str = '';
for (var i = 0; i < arr.length; i += 1) {
str += arr[i];
if (i + 1 < arr.length) {
str += joiner;
}
}
return str;
};
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slicy(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
concatty(args, arguments)
);
if (Object(result) === result) {
return result;
}
return this;
}
return target.apply(
that,
concatty(args, arguments)
);
};
var boundLength = max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs[i] = '$' + i;
}
bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
/***/ }),
/***/ 578:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(901);
module.exports = Function.prototype.bind || implementation;
/***/ }),
/***/ 6254:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var undefined;
var $Error = __webpack_require__(6716);
var $EvalError = __webpack_require__(6788);
var $RangeError = __webpack_require__(9204);
var $ReferenceError = __webpack_require__(9908);
var $SyntaxError = __webpack_require__(6724);
var $TypeError = __webpack_require__(1642);
var $URIError = __webpack_require__(1451);
var $Function = Function;
// eslint-disable-next-line consistent-return
var getEvalledConstructor = function (expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
} catch (e) {}
};
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () {
throw new $TypeError();
};
var ThrowTypeError = $gOPD
? (function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}())
: throwTypeError;
var hasSymbols = __webpack_require__(2665)();
var hasProto = __webpack_require__(1856)();
var getProto = Object.getPrototypeOf || (
hasProto
? function (x) { return x.__proto__; } // eslint-disable-line no-proto
: null
);
var needsEval = {};
var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array);
var INTRINSICS = {
__proto__: null,
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
'%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined,
'%AsyncFromSyncIteratorPrototype%': undefined,
'%AsyncFunction%': needsEval,
'%AsyncGenerator%': needsEval,
'%AsyncGeneratorFunction%': needsEval,
'%AsyncIteratorPrototype%': needsEval,
'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,
'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,
'%Boolean%': Boolean,
'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
'%Date%': Date,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': $Error,
'%eval%': eval, // eslint-disable-line no-eval
'%EvalError%': $EvalError,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
'%Function%': $Function,
'%GeneratorFunction%': needsEval,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined,
'%JSON%': typeof JSON === 'object' ? JSON : undefined,
'%Map%': typeof Map === 'undefined' ? undefined : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()),
'%Math%': Math,
'%Number%': Number,
'%Object%': Object,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
'%RangeError%': $RangeError,
'%ReferenceError%': $ReferenceError,
'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
'%RegExp%': RegExp,
'%Set%': typeof Set === 'undefined' ? undefined : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()),
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined,
'%Symbol%': hasSymbols ? Symbol : undefined,
'%SyntaxError%': $SyntaxError,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypeError%': $TypeError,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
'%URIError%': $URIError,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
};
if (getProto) {
try {
null.error; // eslint-disable-line no-unused-expressions
} catch (e) {
// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
var errorProto = getProto(getProto(e));
INTRINSICS['%Error.prototype%'] = errorProto;
}
}
var doEval = function doEval(name) {
var value;
if (name === '%AsyncFunction%') {
value = getEvalledConstructor('async function () {}');
} else if (name === '%GeneratorFunction%') {
value = getEvalledConstructor('function* () {}');
} else if (name === '%AsyncGeneratorFunction%') {
value = getEvalledConstructor('async function* () {}');
} else if (name === '%AsyncGenerator%') {
var fn = doEval('%AsyncGeneratorFunction%');
if (fn) {
value = fn.prototype;
}
} else if (name === '%AsyncIteratorPrototype%') {
var gen = doEval('%AsyncGenerator%');
if (gen && getProto) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name] = value;
return value;
};
var LEGACY_ALIASES = {
__proto__: null,
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
'%ArrayPrototype%': ['Array', 'prototype'],
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
'%BooleanPrototype%': ['Boolean', 'prototype'],
'%DataViewPrototype%': ['DataView', 'prototype'],
'%DatePrototype%': ['Date', 'prototype'],
'%ErrorPrototype%': ['Error', 'prototype'],
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
'%FunctionPrototype%': ['Function', 'prototype'],
'%Generator%': ['GeneratorFunction', 'prototype'],
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
'%JSONParse%': ['JSON', 'parse'],
'%JSONStringify%': ['JSON', 'stringify'],
'%MapPrototype%': ['Map', 'prototype'],
'%NumberPrototype%': ['Number', 'prototype'],
'%ObjectPrototype%': ['Object', 'prototype'],
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
'%PromisePrototype%': ['Promise', 'prototype'],
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
'%Promise_all%': ['Promise', 'all'],
'%Promise_reject%': ['Promise', 'reject'],
'%Promise_resolve%': ['Promise', 'resolve'],
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
'%RegExpPrototype%': ['RegExp', 'prototype'],
'%SetPrototype%': ['Set', 'prototype'],
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
'%StringPrototype%': ['String', 'prototype'],
'%SymbolPrototype%': ['Symbol', 'prototype'],
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
'%URIErrorPrototype%': ['URIError', 'prototype'],
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
'%WeakSetPrototype%': ['WeakSet', 'prototype']
};
var bind = __webpack_require__(578);
var hasOwn = __webpack_require__(9429);
var $concat = bind.call(Function.call, Array.prototype.concat);
var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
var $replace = bind.call(Function.call, String.prototype.replace);
var $strSlice = bind.call(Function.call, String.prototype.slice);
var $exec = bind.call(Function.call, RegExp.prototype.exec);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
var first = $strSlice(string, 0, 1);
var last = $strSlice(string, -1);
if (first === '%' && last !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
} else if (last === '%' && first !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
}
var result = [];
$replace(string, rePropName, function (match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
var intrinsicName = name;
var alias;
if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
alias = LEGACY_ALIASES[intrinsicName];
intrinsicName = '%' + alias[0] + '%';
}
if (hasOwn(INTRINSICS, intrinsicName)) {
var value = INTRINSICS[intrinsicName];
if (value === needsEval) {
value = doEval(intrinsicName);
}
if (typeof value === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return {
alias: alias,
name: intrinsicName,
value: value
};
}
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
};
module.exports = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new $TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new $TypeError('"allowMissing" argument must be a boolean');
}
if ($exec(/^%?[^%]*%?$/, name) === null) {
throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
}
var parts = stringToPath(name);
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
var intrinsicRealName = intrinsic.name;
var value = intrinsic.value;
var skipFurtherCaching = false;
var alias = intrinsic.alias;
if (alias) {
intrinsicBaseName = alias[0];
$spliceApply(parts, $concat([0, 1], alias));
}
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
var part = parts[i];
var first = $strSlice(part, 0, 1);
var last = $strSlice(part, -1);
if (
(
(first === '"' || first === "'" || first === '`')
|| (last === '"' || last === "'" || last === '`')
)
&& first !== last
) {
throw new $SyntaxError('property names with quotes must have matching quotes');
}
if (part === 'constructor' || !isOwn) {
skipFurtherCaching = true;
}
intrinsicBaseName += '.' + part;
intrinsicRealName = '%' + intrinsicBaseName + '%';
if (hasOwn(INTRINSICS, intrinsicRealName)) {
value = INTRINSICS[intrinsicRealName];
} else if (value != null) {
if (!(part in value)) {
if (!allowMissing) {
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
}
return void undefined;
}
if ($gOPD && (i + 1) >= parts.length) {
var desc = $gOPD(value, part);
isOwn = !!desc;
// By convention, when a data property is converted to an accessor
// property to emulate a data property that does not suffer from
// the override mistake, that accessor's getter is marked with
// an `originalValue` property. Here, when we detect this, we
// uphold the illusion by pretending to see that original data
// property, i.e., returning the value rather than the getter
// itself.
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
value = desc.get;
} else {
value = value[part];
}
} else {
isOwn = hasOwn(value, part);
value = value[part];
}
if (isOwn && !skipFurtherCaching) {
INTRINSICS[intrinsicRealName] = value;
}
}
}
return value;
};
/***/ }),
/***/ 2665:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = __webpack_require__(2408);
module.exports = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return hasSymbolSham();
};
/***/ }),
/***/ 2408:
/***/ (function(module) {
"use strict";
/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
/***/ }),
/***/ 3082:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var toStr = Object.prototype.toString;
var hasSymbols = __webpack_require__(9905)();
if (hasSymbols) {
var symToStr = Symbol.prototype.toString;
var symStringRegex = /^Symbol\(.*\)$/;
var isSymbolObject = function isRealSymbolObject(value) {
if (typeof value.valueOf() !== 'symbol') {
return false;
}
return symStringRegex.test(symToStr.call(value));
};
module.exports = function isSymbol(value) {
if (typeof value === 'symbol') {
return true;
}
if (toStr.call(value) !== '[object Symbol]') {
return false;
}
try {
return isSymbolObject(value);
} catch (e) {
return false;
}
};
} else {
module.exports = function isSymbol(value) {
// this environment does not support Symbols.
return false && 0;
};
}
/***/ }),
/***/ 2527:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var whichTypedArray = __webpack_require__(4010);
/** @type {import('.')} */
module.exports = function isTypedArray(value) {
return !!whichTypedArray(value);
};
/***/ }),
/***/ 9894:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
// Load in dependencies
var computedStyle = __webpack_require__(4827);
/**
* Calculate the `line-height` of a given node
* @param {HTMLElement} node Element to calculate line height of. Must be in the DOM.
* @returns {Number} `line-height` of the element in pixels
*/
function lineHeight(node) {
// Grab the line-height via style
var lnHeightStr = computedStyle(node, 'line-height');
var lnHeight = parseFloat(lnHeightStr, 10);
// If the lineHeight did not contain a unit (i.e. it was numeric), convert it to ems (e.g. '2.3' === '2.3em')
if (lnHeightStr === lnHeight + '') {
// Save the old lineHeight style and update the em unit to the element
var _lnHeightStyle = node.style.lineHeight;
node.style.lineHeight = lnHeightStr + 'em';
// Calculate the em based height
lnHeightStr = computedStyle(node, 'line-height');
lnHeight = parseFloat(lnHeightStr, 10);
// Revert the lineHeight style
if (_lnHeightStyle) {
node.style.lineHeight = _lnHeightStyle;
} else {
delete node.style.lineHeight;
}
}
// If the lineHeight is in `pt`, convert it to pixels (4px for 3pt)
// DEV: `em` units are converted to `pt` in IE6
// Conversion ratio from https://developer.mozilla.org/en-US/docs/Web/CSS/length
if (lnHeightStr.indexOf('pt') !== -1) {
lnHeight *= 4;
lnHeight /= 3;
// Otherwise, if the lineHeight is in `mm`, convert it to pixels (96px for 25.4mm)
} else if (lnHeightStr.indexOf('mm') !== -1) {
lnHeight *= 96;
lnHeight /= 25.4;
// Otherwise, if the lineHeight is in `cm`, convert it to pixels (96px for 2.54cm)
} else if (lnHeightStr.indexOf('cm') !== -1) {
lnHeight *= 96;
lnHeight /= 2.54;
// Otherwise, if the lineHeight is in `in`, convert it to pixels (96px for 1in)
} else if (lnHeightStr.indexOf('in') !== -1) {
lnHeight *= 96;
// Otherwise, if the lineHeight is in `pc`, convert it to pixels (12pt for 1pc)
} else if (lnHeightStr.indexOf('pc') !== -1) {
lnHeight *= 16;
}
// Continue our computation
lnHeight = Math.round(lnHeight);
// If the line-height is "normal", calculate by font-size
if (lnHeightStr === 'normal') {
// Create a temporary node
var nodeName = node.nodeName;
var _node = document.createElement(nodeName);
_node.innerHTML = ' ';
// If we have a text area, reset it to only 1 row
// https://github.com/twolfson/line-height/issues/4
if (nodeName.toUpperCase() === 'TEXTAREA') {
_node.setAttribute('rows', '1');
}
// Set the font-size of the element
var fontSizeStr = computedStyle(node, 'font-size');
_node.style.fontSize = fontSizeStr;
// Remove default padding/border which can affect offset height
// https://github.com/twolfson/line-height/issues/4
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight
_node.style.padding = '0px';
_node.style.border = '0px';
// Append it to the body
var body = document.body;
body.appendChild(_node);
// Assume the line height of the element is the height
var height = _node.offsetHeight;
lnHeight = height;
// Remove our child from the DOM
body.removeChild(_node);
}
// Return the calculated height
return lnHeight;
}
// Export lineHeight
module.exports = lineHeight;
/***/ }),
/***/ 7970:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
module.exports = __webpack_require__(195);
/***/ }),
/***/ 3110:
/***/ (function(module) {
"use strict";
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ExecutionEnvironment
*/
/*jslint evil: true */
var canUseDOM = !!(
typeof window !== 'undefined' &&
window.document &&
window.document.createElement
);
/**
* Simple, lightweight module assisting with the detection and context of
* Worker. Helps avoid circular dependencies and allows code to reason about
* whether or not they are in a Worker, even if they never include the main
* `ReactWorker` dependency.
*/
var ExecutionEnvironment = {
canUseDOM: canUseDOM,
canUseWorkers: typeof Worker !== 'undefined',
canUseEventListeners:
canUseDOM && !!(window.addEventListener || window.attachEvent),
canUseViewport: canUseDOM && !!window.screen,
isInWorker: !canUseDOM // For now, this is true - might change in the future.
};
module.exports = ExecutionEnvironment;
/***/ }),
/***/ 3812:
/***/ (function(module) {
/**
* Copyright 2004-present Facebook. All Rights Reserved.
*
* @providesModule UserAgent_DEPRECATED
*/
/**
* Provides entirely client-side User Agent and OS detection. You should prefer
* the non-deprecated UserAgent module when possible, which exposes our
* authoritative server-side PHP-based detection to the client.
*
* Usage is straightforward:
*
* if (UserAgent_DEPRECATED.ie()) {
* // IE
* }
*
* You can also do version checks:
*
* if (UserAgent_DEPRECATED.ie() >= 7) {
* // IE7 or better
* }
*
* The browser functions will return NaN if the browser does not match, so
* you can also do version compares the other way:
*
* if (UserAgent_DEPRECATED.ie() < 7) {
* // IE6 or worse
* }
*
* Note that the version is a float and may include a minor version number,
* so you should always use range operators to perform comparisons, not
* strict equality.
*
* **Note:** You should **strongly** prefer capability detection to browser
* version detection where it's reasonable:
*
* http://www.quirksmode.org/js/support.html
*
* Further, we have a large number of mature wrapper functions and classes
* which abstract away many browser irregularities. Check the documentation,
* grep for things, or ask on javascript@lists.facebook.com before writing yet
* another copy of "event || window.event".
*
*/
var _populated = false;
// Browsers
var _ie, _firefox, _opera, _webkit, _chrome;
// Actual IE browser for compatibility mode
var _ie_real_version;
// Platforms
var _osx, _windows, _linux, _android;
// Architectures
var _win64;
// Devices
var _iphone, _ipad, _native;
var _mobile;
function _populate() {
if (_populated) {
return;
}
_populated = true;
// To work around buggy JS libraries that can't handle multi-digit
// version numbers, Opera 10's user agent string claims it's Opera
// 9, then later includes a Version/X.Y field:
//
// Opera/9.80 (foo) Presto/2.2.15 Version/10.10
var uas = navigator.userAgent;
var agent = /(?:MSIE.(\d+\.\d+))|(?:(?:Firefox|GranParadiso|Iceweasel).(\d+\.\d+))|(?:Opera(?:.+Version.|.)(\d+\.\d+))|(?:AppleWebKit.(\d+(?:\.\d+)?))|(?:Trident\/\d+\.\d+.*rv:(\d+\.\d+))/.exec(uas);
var os = /(Mac OS X)|(Windows)|(Linux)/.exec(uas);
_iphone = /\b(iPhone|iP[ao]d)/.exec(uas);
_ipad = /\b(iP[ao]d)/.exec(uas);
_android = /Android/i.exec(uas);
_native = /FBAN\/\w+;/i.exec(uas);
_mobile = /Mobile/i.exec(uas);
// Note that the IE team blog would have you believe you should be checking
// for 'Win64; x64'. But MSDN then reveals that you can actually be coming
// from either x64 or ia64; so ultimately, you should just check for Win64
// as in indicator of whether you're in 64-bit IE. 32-bit IE on 64-bit
// Windows will send 'WOW64' instead.
_win64 = !!(/Win64/.exec(uas));
if (agent) {
_ie = agent[1] ? parseFloat(agent[1]) : (
agent[5] ? parseFloat(agent[5]) : NaN);
// IE compatibility mode
if (_ie && document && document.documentMode) {
_ie = document.documentMode;
}
// grab the "true" ie version from the trident token if available
var trident = /(?:Trident\/(\d+.\d+))/.exec(uas);
_ie_real_version = trident ? parseFloat(trident[1]) + 4 : _ie;
_firefox = agent[2] ? parseFloat(agent[2]) : NaN;
_opera = agent[3] ? parseFloat(agent[3]) : NaN;
_webkit = agent[4] ? parseFloat(agent[4]) : NaN;
if (_webkit) {
// We do not add the regexp to the above test, because it will always
// match 'safari' only since 'AppleWebKit' appears before 'Chrome' in
// the userAgent string.
agent = /(?:Chrome\/(\d+\.\d+))/.exec(uas);
_chrome = agent && agent[1] ? parseFloat(agent[1]) : NaN;
} else {
_chrome = NaN;
}
} else {
_ie = _firefox = _opera = _chrome = _webkit = NaN;
}
if (os) {
if (os[1]) {
// Detect OS X version. If no version number matches, set _osx to true.
// Version examples: 10, 10_6_1, 10.7
// Parses version number as a float, taking only first two sets of
// digits. If only one set of digits is found, returns just the major
// version number.
var ver = /(?:Mac OS X (\d+(?:[._]\d+)?))/.exec(uas);
_osx = ver ? parseFloat(ver[1].replace('_', '.')) : true;
} else {
_osx = false;
}
_windows = !!os[2];
_linux = !!os[3];
} else {
_osx = _windows = _linux = false;
}
}
var UserAgent_DEPRECATED = {
/**
* Check if the UA is Internet Explorer.
*
*
* @return float|NaN Version number (if match) or NaN.
*/
ie: function() {
return _populate() || _ie;
},
/**
* Check if we're in Internet Explorer compatibility mode.
*
* @return bool true if in compatibility mode, false if
* not compatibility mode or not ie
*/
ieCompatibilityMode: function() {
return _populate() || (_ie_real_version > _ie);
},
/**
* Whether the browser is 64-bit IE. Really, this is kind of weak sauce; we
* only need this because Skype can't handle 64-bit IE yet. We need to remove
* this when we don't need it -- tracked by #601957.
*/
ie64: function() {
return UserAgent_DEPRECATED.ie() && _win64;
},
/**
* Check if the UA is Firefox.
*
*
* @return float|NaN Version number (if match) or NaN.
*/
firefox: function() {
return _populate() || _firefox;
},
/**
* Check if the UA is Opera.
*
*
* @return float|NaN Version number (if match) or NaN.
*/
opera: function() {
return _populate() || _opera;
},
/**
* Check if the UA is WebKit.
*
*
* @return float|NaN Version number (if match) or NaN.
*/
webkit: function() {
return _populate() || _webkit;
},
/**
* For Push
* WILL BE REMOVED VERY SOON. Use UserAgent_DEPRECATED.webkit
*/
safari: function() {
return UserAgent_DEPRECATED.webkit();
},
/**
* Check if the UA is a Chrome browser.
*
*
* @return float|NaN Version number (if match) or NaN.
*/
chrome : function() {
return _populate() || _chrome;
},
/**
* Check if the user is running Windows.
*
* @return bool `true' if the user's OS is Windows.
*/
windows: function() {
return _populate() || _windows;
},
/**
* Check if the user is running Mac OS X.
*
* @return float|bool Returns a float if a version number is detected,
* otherwise true/false.
*/
osx: function() {
return _populate() || _osx;
},
/**
* Check if the user is running Linux.
*
* @return bool `true' if the user's OS is some flavor of Linux.
*/
linux: function() {
return _populate() || _linux;
},
/**
* Check if the user is running on an iPhone or iPod platform.
*
* @return bool `true' if the user is running some flavor of the
* iPhone OS.
*/
iphone: function() {
return _populate() || _iphone;
},
mobile: function() {
return _populate() || (_iphone || _ipad || _android || _mobile);
},
nativeApp: function() {
// webviews inside of the native apps
return _populate() || _native;
},
android: function() {
return _populate() || _android;
},
ipad: function() {
return _populate() || _ipad;
}
};
module.exports = UserAgent_DEPRECATED;
/***/ }),
/***/ 7939:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule isEventSupported
*/
var ExecutionEnvironment = __webpack_require__(3110);
var useHasFeature;
if (ExecutionEnvironment.canUseDOM) {
useHasFeature =
document.implementation &&
document.implementation.hasFeature &&
// always returns true in newer browsers as per the standard.
// @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature
document.implementation.hasFeature('', '') !== true;
}
/**
* Checks if an event is supported in the current execution environment.
*
* NOTE: This will not work correctly for non-generic events such as `change`,
* `reset`, `load`, `error`, and `select`.
*
* Borrows from Modernizr.
*
* @param {string} eventNameSuffix Event name, e.g. "click".
* @param {?boolean} capture Check if the capture phase is supported.
* @return {boolean} True if the event is supported.
* @internal
* @license Modernizr 3.0.0pre (Custom Build) | MIT
*/
function isEventSupported(eventNameSuffix, capture) {
if (!ExecutionEnvironment.canUseDOM ||
capture && !('addEventListener' in document)) {
return false;
}
var eventName = 'on' + eventNameSuffix;
var isSupported = eventName in document;
if (!isSupported) {
var element = document.createElement('div');
element.setAttribute(eventName, 'return;');
isSupported = typeof element[eventName] === 'function';
}
if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') {
// This is the only way to test support for the `wheel` event in IE9+.
isSupported = document.implementation.hasFeature('Events.wheel', '3.0');
}
return isSupported;
}
module.exports = isEventSupported;
/***/ }),
/***/ 195:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule normalizeWheel
* @typechecks
*/
var UserAgent_DEPRECATED = __webpack_require__(3812);
var isEventSupported = __webpack_require__(7939);
// Reasonable defaults
var PIXEL_STEP = 10;
var LINE_HEIGHT = 40;
var PAGE_HEIGHT = 800;
/**
* Mouse wheel (and 2-finger trackpad) support on the web sucks. It is
* complicated, thus this doc is long and (hopefully) detailed enough to answer
* your questions.
*
* If you need to react to the mouse wheel in a predictable way, this code is
* like your bestest friend. * hugs *
*
* As of today, there are 4 DOM event types you can listen to:
*
* 'wheel' -- Chrome(31+), FF(17+), IE(9+)
* 'mousewheel' -- Chrome, IE(6+), Opera, Safari
* 'MozMousePixelScroll' -- FF(3.5 only!) (2010-2013) -- don't bother!
* 'DOMMouseScroll' -- FF(0.9.7+) since 2003
*
* So what to do? The is the best:
*
* normalizeWheel.getEventType();
*
* In your event callback, use this code to get sane interpretation of the
* deltas. This code will return an object with properties:
*
* spinX -- normalized spin speed (use for zoom) - x plane
* spinY -- " - y plane
* pixelX -- normalized distance (to pixels) - x plane
* pixelY -- " - y plane
*
* Wheel values are provided by the browser assuming you are using the wheel to
* scroll a web page by a number of lines or pixels (or pages). Values can vary
* significantly on different platforms and browsers, forgetting that you can
* scroll at different speeds. Some devices (like trackpads) emit more events
* at smaller increments with fine granularity, and some emit massive jumps with
* linear speed or acceleration.
*
* This code does its best to normalize the deltas for you:
*
* - spin is trying to normalize how far the wheel was spun (or trackpad
* dragged). This is super useful for zoom support where you want to
* throw away the chunky scroll steps on the PC and make those equal to
* the slow and smooth tiny steps on the Mac. Key data: This code tries to
* resolve a single slow step on a wheel to 1.
*
* - pixel is normalizing the desired scroll delta in pixel units. You'll
* get the crazy differences between browsers, but at least it'll be in
* pixels!
*
* - positive value indicates scrolling DOWN/RIGHT, negative UP/LEFT. This
* should translate to positive value zooming IN, negative zooming OUT.
* This matches the newer 'wheel' event.
*
* Why are there spinX, spinY (or pixels)?
*
* - spinX is a 2-finger side drag on the trackpad, and a shift + wheel turn
* with a mouse. It results in side-scrolling in the browser by default.
*
* - spinY is what you expect -- it's the classic axis of a mouse wheel.
*
* - I dropped spinZ/pixelZ. It is supported by the DOM 3 'wheel' event and
* probably is by browsers in conjunction with fancy 3D controllers .. but
* you know.
*
* Implementation info:
*
* Examples of 'wheel' event if you scroll slowly (down) by one step with an
* average mouse:
*
* OS X + Chrome (mouse) - 4 pixel delta (wheelDelta -120)
* OS X + Safari (mouse) - N/A pixel delta (wheelDelta -12)
* OS X + Firefox (mouse) - 0.1 line delta (wheelDelta N/A)
* Win8 + Chrome (mouse) - 100 pixel delta (wheelDelta -120)
* Win8 + Firefox (mouse) - 3 line delta (wheelDelta -120)
*
* On the trackpad:
*
* OS X + Chrome (trackpad) - 2 pixel delta (wheelDelta -6)
* OS X + Firefox (trackpad) - 1 pixel delta (wheelDelta N/A)
*
* On other/older browsers.. it's more complicated as there can be multiple and
* also missing delta values.
*
* The 'wheel' event is more standard:
*
* http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents
*
* The basics is that it includes a unit, deltaMode (pixels, lines, pages), and
* deltaX, deltaY and deltaZ. Some browsers provide other values to maintain
* backward compatibility with older events. Those other values help us
* better normalize spin speed. Example of what the browsers provide:
*
* | event.wheelDelta | event.detail
* ------------------+------------------+--------------
* Safari v5/OS X | -120 | 0
* Safari v5/Win7 | -120 | 0
* Chrome v17/OS X | -120 | 0
* Chrome v17/Win7 | -120 | 0
* IE9/Win7 | -120 | undefined
* Firefox v4/OS X | undefined | 1
* Firefox v4/Win7 | undefined | 3
*
*/
function normalizeWheel(/*object*/ event) /*object*/ {
var sX = 0, sY = 0, // spinX, spinY
pX = 0, pY = 0; // pixelX, pixelY
// Legacy
if ('detail' in event) { sY = event.detail; }
if ('wheelDelta' in event) { sY = -event.wheelDelta / 120; }
if ('wheelDeltaY' in event) { sY = -event.wheelDeltaY / 120; }
if ('wheelDeltaX' in event) { sX = -event.wheelDeltaX / 120; }
// side scrolling on FF with DOMMouseScroll
if ( 'axis' in event && event.axis === event.HORIZONTAL_AXIS ) {
sX = sY;
sY = 0;
}
pX = sX * PIXEL_STEP;
pY = sY * PIXEL_STEP;
if ('deltaY' in event) { pY = event.deltaY; }
if ('deltaX' in event) { pX = event.deltaX; }
if ((pX || pY) && event.deltaMode) {
if (event.deltaMode == 1) { // delta in LINE units
pX *= LINE_HEIGHT;
pY *= LINE_HEIGHT;
} else { // delta in PAGE units
pX *= PAGE_HEIGHT;
pY *= PAGE_HEIGHT;
}
}
// Fall-back if spin cannot be determined
if (pX && !sX) { sX = (pX < 1) ? -1 : 1; }
if (pY && !sY) { sY = (pY < 1) ? -1 : 1; }
return { spinX : sX,
spinY : sY,
pixelX : pX,
pixelY : pY };
}
/**
* The best combination if you prefer spinX + spinY normalization. It favors
* the older DOMMouseScroll for Firefox, as FF does not include wheelDelta with
* 'wheel' event, making spin speed determination impossible.
*/
normalizeWheel.getEventType = function() /*string*/ {
return (UserAgent_DEPRECATED.firefox())
? 'DOMMouseScroll'
: (isEventSupported('wheel'))
? 'wheel'
: 'mousewheel';
};
module.exports = normalizeWheel;
/***/ }),
/***/ 8383:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var keysShim;
if (!Object.keys) {
// modified from https://github.com/es-shims/es5-shim
var has = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var isArgs = __webpack_require__(4418); // eslint-disable-line global-require
var isEnumerable = Object.prototype.propertyIsEnumerable;
var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
var dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
var equalsConstructorPrototype = function (o) {
var ctor = o.constructor;
return ctor && ctor.prototype === o;
};
var excludedKeys = {
$applicationCache: true,
$console: true,
$external: true,
$frame: true,
$frameElement: true,
$frames: true,
$innerHeight: true,
$innerWidth: true,
$onmozfullscreenchange: true,
$onmozfullscreenerror: true,
$outerHeight: true,
$outerWidth: true,
$pageXOffset: true,
$pageYOffset: true,
$parent: true,
$scrollLeft: true,
$scrollTop: true,
$scrollX: true,
$scrollY: true,
$self: true,
$webkitIndexedDB: true,
$webkitStorageInfo: true,
$window: true
};
var hasAutomationEqualityBug = (function () {
/* global window */
if (typeof window === 'undefined') { return false; }
for (var k in window) {
try {
if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
try {
equalsConstructorPrototype(window[k]);
} catch (e) {
return true;
}
}
} catch (e) {
return true;
}
}
return false;
}());
var equalsConstructorPrototypeIfNotBuggy = function (o) {
/* global window */
if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
return equalsConstructorPrototype(o);
}
try {
return equalsConstructorPrototype(o);
} catch (e) {
return false;
}
};
keysShim = function keys(object) {
var isObject = object !== null && typeof object === 'object';
var isFunction = toStr.call(object) === '[object Function]';
var isArguments = isArgs(object);
var isString = isObject && toStr.call(object) === '[object String]';
var theKeys = [];
if (!isObject && !isFunction && !isArguments) {
throw new TypeError('Object.keys called on a non-object');
}
var skipProto = hasProtoEnumBug && isFunction;
if (isString && object.length > 0 && !has.call(object, 0)) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i));
}
}
if (isArguments && object.length > 0) {
for (var j = 0; j < object.length; ++j) {
theKeys.push(String(j));
}
} else {
for (var name in object) {
if (!(skipProto && name === 'prototype') && has.call(object, name)) {
theKeys.push(String(name));
}
}
}
if (hasDontEnumBug) {
var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
for (var k = 0; k < dontEnums.length; ++k) {
if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
theKeys.push(dontEnums[k]);
}
}
}
return theKeys;
};
}
module.exports = keysShim;
/***/ }),
/***/ 806:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var slice = Array.prototype.slice;
var isArgs = __webpack_require__(4418);
var origKeys = Object.keys;
var keysShim = origKeys ? function keys(o) { return origKeys(o); } : __webpack_require__(8383);
var originalKeys = Object.keys;
keysShim.shim = function shimObjectKeys() {
if (Object.keys) {
var keysWorksWithArguments = (function () {
// Safari 5.0 bug
var args = Object.keys(arguments);
return args && args.length === arguments.length;
}(1, 2));
if (!keysWorksWithArguments) {
Object.keys = function keys(object) { // eslint-disable-line func-name-matching
if (isArgs(object)) {
return originalKeys(slice.call(object));
}
return originalKeys(object);
};
}
} else {
Object.keys = keysShim;
}
return Object.keys || keysShim;
};
module.exports = keysShim;
/***/ }),
/***/ 4418:
/***/ (function(module) {
"use strict";
var toStr = Object.prototype.toString;
module.exports = function isArguments(value) {
var str = toStr.call(value);
var isArgs = str === '[object Arguments]';
if (!isArgs) {
isArgs = str !== '[object Array]' &&
value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
toStr.call(value.callee) === '[object Function]';
}
return isArgs;
};
/***/ }),
/***/ 131:
/***/ (function(module) {
"use strict";
/** @type {import('.')} */
module.exports = [
'Float32Array',
'Float64Array',
'Int8Array',
'Int16Array',
'Int32Array',
'Uint8Array',
'Uint8ClampedArray',
'Uint16Array',
'Uint32Array',
'BigInt64Array',
'BigUint64Array'
];
/***/ }),
/***/ 5372:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = __webpack_require__(9567);
function emptyFunction() {}
function emptyFunctionWithReset() {}
emptyFunctionWithReset.resetWarningCache = emptyFunction;
module.exports = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
if (secret === ReactPropTypesSecret) {
// It is still safe when called from React.
return;
}
var err = new Error(
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use PropTypes.checkPropTypes() to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
err.name = 'Invariant Violation';
throw err;
};
shim.isRequired = shim;
function getShim() {
return shim;
};
// Important!
// Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
var ReactPropTypes = {
array: shim,
bigint: shim,
bool: shim,
func: shim,
number: shim,
object: shim,
string: shim,
symbol: shim,
any: shim,
arrayOf: getShim,
element: shim,
elementType: shim,
instanceOf: getShim,
node: shim,
objectOf: getShim,
oneOf: getShim,
oneOfType: getShim,
shape: getShim,
exact: getShim,
checkPropTypes: emptyFunctionWithReset,
resetWarningCache: emptyFunction
};
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
/***/ }),
/***/ 2652:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
if (false) { var throwOnDirectAccess, ReactIs; } else {
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
module.exports = __webpack_require__(5372)();
}
/***/ }),
/***/ 9567:
/***/ (function(module) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
module.exports = ReactPropTypesSecret;
/***/ }),
/***/ 5438:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (this && this.__assign) || Object.assign || function(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;
};
var __rest = (this && this.__rest) || function (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)
t[p[i]] = s[p[i]];
return t;
};
exports.__esModule = true;
var React = __webpack_require__(9196);
var PropTypes = __webpack_require__(2652);
var autosize = __webpack_require__(6411);
var _getLineHeight = __webpack_require__(9894);
var getLineHeight = _getLineHeight;
var RESIZED = "autosize:resized";
/**
* A light replacement for built-in textarea component
* which automaticaly adjusts its height to match the content
*/
var TextareaAutosizeClass = /** @class */ (function (_super) {
__extends(TextareaAutosizeClass, _super);
function TextareaAutosizeClass() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.state = {
lineHeight: null
};
_this.textarea = null;
_this.onResize = function (e) {
if (_this.props.onResize) {
_this.props.onResize(e);
}
};
_this.updateLineHeight = function () {
if (_this.textarea) {
_this.setState({
lineHeight: getLineHeight(_this.textarea)
});
}
};
_this.onChange = function (e) {
var onChange = _this.props.onChange;
_this.currentValue = e.currentTarget.value;
onChange && onChange(e);
};
return _this;
}
TextareaAutosizeClass.prototype.componentDidMount = function () {
var _this = this;
var _a = this.props, maxRows = _a.maxRows, async = _a.async;
if (typeof maxRows === "number") {
this.updateLineHeight();
}
if (typeof maxRows === "number" || async) {
/*
the defer is needed to:
- force "autosize" to activate the scrollbar when this.props.maxRows is passed
- support StyledComponents (see #71)
*/
setTimeout(function () { return _this.textarea && autosize(_this.textarea); });
}
else {
this.textarea && autosize(this.textarea);
}
if (this.textarea) {
this.textarea.addEventListener(RESIZED, this.onResize);
}
};
TextareaAutosizeClass.prototype.componentWillUnmount = function () {
if (this.textarea) {
this.textarea.removeEventListener(RESIZED, this.onResize);
autosize.destroy(this.textarea);
}
};
TextareaAutosizeClass.prototype.render = function () {
var _this = this;
var _a = this, _b = _a.props, onResize = _b.onResize, maxRows = _b.maxRows, onChange = _b.onChange, style = _b.style, innerRef = _b.innerRef, children = _b.children, props = __rest(_b, ["onResize", "maxRows", "onChange", "style", "innerRef", "children"]), lineHeight = _a.state.lineHeight;
var maxHeight = maxRows && lineHeight ? lineHeight * maxRows : null;
return (React.createElement("textarea", __assign({}, props, { onChange: this.onChange, style: maxHeight ? __assign({}, style, { maxHeight: maxHeight }) : style, ref: function (element) {
_this.textarea = element;
if (typeof _this.props.innerRef === 'function') {
_this.props.innerRef(element);
}
else if (_this.props.innerRef) {
_this.props.innerRef.current = element;
}
} }), children));
};
TextareaAutosizeClass.prototype.componentDidUpdate = function () {
this.textarea && autosize.update(this.textarea);
};
TextareaAutosizeClass.defaultProps = {
rows: 1,
async: false
};
TextareaAutosizeClass.propTypes = {
rows: PropTypes.number,
maxRows: PropTypes.number,
onResize: PropTypes.func,
innerRef: PropTypes.any,
async: PropTypes.bool
};
return TextareaAutosizeClass;
}(React.Component));
exports.TextareaAutosize = React.forwardRef(function (props, ref) {
return React.createElement(TextareaAutosizeClass, __assign({}, props, { innerRef: ref }));
});
/***/ }),
/***/ 773:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __webpack_unused_export__;
__webpack_unused_export__ = true;
var TextareaAutosize_1 = __webpack_require__(5438);
exports.Z = TextareaAutosize_1.TextareaAutosize;
/***/ }),
/***/ 4793:
/***/ (function(module) {
var characterMap = {
"À": "A",
"Á": "A",
"Â": "A",
"Ã": "A",
"Ä": "A",
"Å": "A",
"Ấ": "A",
"Ắ": "A",
"Ẳ": "A",
"Ẵ": "A",
"Ặ": "A",
"Æ": "AE",
"Ầ": "A",
"Ằ": "A",
"Ȃ": "A",
"Ç": "C",
"Ḉ": "C",
"È": "E",
"É": "E",
"Ê": "E",
"Ë": "E",
"Ế": "E",
"Ḗ": "E",
"Ề": "E",
"Ḕ": "E",
"Ḝ": "E",
"Ȇ": "E",
"Ì": "I",
"Í": "I",
"Î": "I",
"Ï": "I",
"Ḯ": "I",
"Ȋ": "I",
"Ð": "D",
"Ñ": "N",
"Ò": "O",
"Ó": "O",
"Ô": "O",
"Õ": "O",
"Ö": "O",
"Ø": "O",
"Ố": "O",
"Ṍ": "O",
"Ṓ": "O",
"Ȏ": "O",
"Ù": "U",
"Ú": "U",
"Û": "U",
"Ü": "U",
"Ý": "Y",
"à": "a",
"á": "a",
"â": "a",
"ã": "a",
"ä": "a",
"å": "a",
"ấ": "a",
"ắ": "a",
"ẳ": "a",
"ẵ": "a",
"ặ": "a",
"æ": "ae",
"ầ": "a",
"ằ": "a",
"ȃ": "a",
"ç": "c",
"ḉ": "c",
"è": "e",
"é": "e",
"ê": "e",
"ë": "e",
"ế": "e",
"ḗ": "e",
"ề": "e",
"ḕ": "e",
"ḝ": "e",
"ȇ": "e",
"ì": "i",
"í": "i",
"î": "i",
"ï": "i",
"ḯ": "i",
"ȋ": "i",
"ð": "d",
"ñ": "n",
"ò": "o",
"ó": "o",
"ô": "o",
"õ": "o",
"ö": "o",
"ø": "o",
"ố": "o",
"ṍ": "o",
"ṓ": "o",
"ȏ": "o",
"ù": "u",
"ú": "u",
"û": "u",
"ü": "u",
"ý": "y",
"ÿ": "y",
"Ā": "A",
"ā": "a",
"Ă": "A",
"ă": "a",
"Ą": "A",
"ą": "a",
"Ć": "C",
"ć": "c",
"Ĉ": "C",
"ĉ": "c",
"Ċ": "C",
"ċ": "c",
"Č": "C",
"č": "c",
"C̆": "C",
"c̆": "c",
"Ď": "D",
"ď": "d",
"Đ": "D",
"đ": "d",
"Ē": "E",
"ē": "e",
"Ĕ": "E",
"ĕ": "e",
"Ė": "E",
"ė": "e",
"Ę": "E",
"ę": "e",
"Ě": "E",
"ě": "e",
"Ĝ": "G",
"Ǵ": "G",
"ĝ": "g",
"ǵ": "g",
"Ğ": "G",
"ğ": "g",
"Ġ": "G",
"ġ": "g",
"Ģ": "G",
"ģ": "g",
"Ĥ": "H",
"ĥ": "h",
"Ħ": "H",
"ħ": "h",
"Ḫ": "H",
"ḫ": "h",
"Ĩ": "I",
"ĩ": "i",
"Ī": "I",
"ī": "i",
"Ĭ": "I",
"ĭ": "i",
"Į": "I",
"į": "i",
"İ": "I",
"ı": "i",
"IJ": "IJ",
"ij": "ij",
"Ĵ": "J",
"ĵ": "j",
"Ķ": "K",
"ķ": "k",
"Ḱ": "K",
"ḱ": "k",
"K̆": "K",
"k̆": "k",
"Ĺ": "L",
"ĺ": "l",
"Ļ": "L",
"ļ": "l",
"Ľ": "L",
"ľ": "l",
"Ŀ": "L",
"ŀ": "l",
"Ł": "l",
"ł": "l",
"Ḿ": "M",
"ḿ": "m",
"M̆": "M",
"m̆": "m",
"Ń": "N",
"ń": "n",
"Ņ": "N",
"ņ": "n",
"Ň": "N",
"ň": "n",
"ʼn": "n",
"N̆": "N",
"n̆": "n",
"Ō": "O",
"ō": "o",
"Ŏ": "O",
"ŏ": "o",
"Ő": "O",
"ő": "o",
"Œ": "OE",
"œ": "oe",
"P̆": "P",
"p̆": "p",
"Ŕ": "R",
"ŕ": "r",
"Ŗ": "R",
"ŗ": "r",
"Ř": "R",
"ř": "r",
"R̆": "R",
"r̆": "r",
"Ȓ": "R",
"ȓ": "r",
"Ś": "S",
"ś": "s",
"Ŝ": "S",
"ŝ": "s",
"Ş": "S",
"Ș": "S",
"ș": "s",
"ş": "s",
"Š": "S",
"š": "s",
"ß": "ss",
"Ţ": "T",
"ţ": "t",
"ț": "t",
"Ț": "T",
"Ť": "T",
"ť": "t",
"Ŧ": "T",
"ŧ": "t",
"T̆": "T",
"t̆": "t",
"Ũ": "U",
"ũ": "u",
"Ū": "U",
"ū": "u",
"Ŭ": "U",
"ŭ": "u",
"Ů": "U",
"ů": "u",
"Ű": "U",
"ű": "u",
"Ų": "U",
"ų": "u",
"Ȗ": "U",
"ȗ": "u",
"V̆": "V",
"v̆": "v",
"Ŵ": "W",
"ŵ": "w",
"Ẃ": "W",
"ẃ": "w",
"X̆": "X",
"x̆": "x",
"Ŷ": "Y",
"ŷ": "y",
"Ÿ": "Y",
"Y̆": "Y",
"y̆": "y",
"Ź": "Z",
"ź": "z",
"Ż": "Z",
"ż": "z",
"Ž": "Z",
"ž": "z",
"ſ": "s",
"ƒ": "f",
"Ơ": "O",
"ơ": "o",
"Ư": "U",
"ư": "u",
"Ǎ": "A",
"ǎ": "a",
"Ǐ": "I",
"ǐ": "i",
"Ǒ": "O",
"ǒ": "o",
"Ǔ": "U",
"ǔ": "u",
"Ǖ": "U",
"ǖ": "u",
"Ǘ": "U",
"ǘ": "u",
"Ǚ": "U",
"ǚ": "u",
"Ǜ": "U",
"ǜ": "u",
"Ứ": "U",
"ứ": "u",
"Ṹ": "U",
"ṹ": "u",
"Ǻ": "A",
"ǻ": "a",
"Ǽ": "AE",
"ǽ": "ae",
"Ǿ": "O",
"ǿ": "o",
"Þ": "TH",
"þ": "th",
"Ṕ": "P",
"ṕ": "p",
"Ṥ": "S",
"ṥ": "s",
"X́": "X",
"x́": "x",
"Ѓ": "Г",
"ѓ": "г",
"Ќ": "К",
"ќ": "к",
"A̋": "A",
"a̋": "a",
"E̋": "E",
"e̋": "e",
"I̋": "I",
"i̋": "i",
"Ǹ": "N",
"ǹ": "n",
"Ồ": "O",
"ồ": "o",
"Ṑ": "O",
"ṑ": "o",
"Ừ": "U",
"ừ": "u",
"Ẁ": "W",
"ẁ": "w",
"Ỳ": "Y",
"ỳ": "y",
"Ȁ": "A",
"ȁ": "a",
"Ȅ": "E",
"ȅ": "e",
"Ȉ": "I",
"ȉ": "i",
"Ȍ": "O",
"ȍ": "o",
"Ȑ": "R",
"ȑ": "r",
"Ȕ": "U",
"ȕ": "u",
"B̌": "B",
"b̌": "b",
"Č̣": "C",
"č̣": "c",
"Ê̌": "E",
"ê̌": "e",
"F̌": "F",
"f̌": "f",
"Ǧ": "G",
"ǧ": "g",
"Ȟ": "H",
"ȟ": "h",
"J̌": "J",
"ǰ": "j",
"Ǩ": "K",
"ǩ": "k",
"M̌": "M",
"m̌": "m",
"P̌": "P",
"p̌": "p",
"Q̌": "Q",
"q̌": "q",
"Ř̩": "R",
"ř̩": "r",
"Ṧ": "S",
"ṧ": "s",
"V̌": "V",
"v̌": "v",
"W̌": "W",
"w̌": "w",
"X̌": "X",
"x̌": "x",
"Y̌": "Y",
"y̌": "y",
"A̧": "A",
"a̧": "a",
"B̧": "B",
"b̧": "b",
"Ḑ": "D",
"ḑ": "d",
"Ȩ": "E",
"ȩ": "e",
"Ɛ̧": "E",
"ɛ̧": "e",
"Ḩ": "H",
"ḩ": "h",
"I̧": "I",
"i̧": "i",
"Ɨ̧": "I",
"ɨ̧": "i",
"M̧": "M",
"m̧": "m",
"O̧": "O",
"o̧": "o",
"Q̧": "Q",
"q̧": "q",
"U̧": "U",
"u̧": "u",
"X̧": "X",
"x̧": "x",
"Z̧": "Z",
"z̧": "z",
"й":"и",
"Й":"И",
"ё":"е",
"Ё":"Е",
};
var chars = Object.keys(characterMap).join('|');
var allAccents = new RegExp(chars, 'g');
var firstAccent = new RegExp(chars, '');
function matcher(match) {
return characterMap[match];
}
var removeAccents = function(string) {
return string.replace(allAccents, matcher);
};
var hasAccents = function(string) {
return !!string.match(firstAccent);
};
module.exports = removeAccents;
module.exports.has = hasAccents;
module.exports.remove = removeAccents;
/***/ }),
/***/ 3002:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(8024);
var $concat = GetIntrinsic('%Array.prototype.concat%');
var callBind = __webpack_require__(9386);
var callBound = __webpack_require__(3315);
var $slice = callBound('Array.prototype.slice');
var hasSymbols = __webpack_require__(1489)();
var isConcatSpreadable = hasSymbols && Symbol.isConcatSpreadable;
/** @type {never[]} */ var empty = [];
var $concatApply = isConcatSpreadable ? callBind.apply($concat, empty) : null;
// eslint-disable-next-line no-extra-parens
var isArray = isConcatSpreadable ? /** @type {(value: unknown) => value is unknown[]} */ (__webpack_require__(9277)) : null;
/** @type {import('.')} */
module.exports = isConcatSpreadable
// eslint-disable-next-line no-unused-vars
? function safeArrayConcat(item) {
for (var i = 0; i < arguments.length; i += 1) {
/** @type {typeof item} */ var arg = arguments[i];
// @ts-expect-error ts(2538) see https://github.com/microsoft/TypeScript/issues/9998#issuecomment-1890787975; works if `const`
if (arg && typeof arg === 'object' && typeof arg[isConcatSpreadable] === 'boolean') {
// @ts-expect-error ts(7015) TS doesn't yet support Symbol indexing
if (!empty[isConcatSpreadable]) {
// @ts-expect-error ts(7015) TS doesn't yet support Symbol indexing
empty[isConcatSpreadable] = true;
}
// @ts-expect-error ts(2721) ts(18047) not sure why TS can't figure out this can't be null
var arr = isArray(arg) ? $slice(arg) : [arg];
// @ts-expect-error ts(7015) TS can't handle expandos on an array
arr[isConcatSpreadable] = true; // shadow the property. TODO: use [[Define]]
arguments[i] = arr;
}
}
// @ts-expect-error ts(2345) https://github.com/microsoft/TypeScript/issues/57164 TS doesn't understand that apply can take an arguments object
return $concatApply(arguments);
}
: callBind($concat, empty);
/***/ }),
/***/ 3315:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(8024);
var callBind = __webpack_require__(9386);
var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));
module.exports = function callBoundIntrinsic(name, allowMissing) {
var intrinsic = GetIntrinsic(name, !!allowMissing);
if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
return callBind(intrinsic);
}
return intrinsic;
};
/***/ }),
/***/ 9386:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var bind = __webpack_require__(5127);
var GetIntrinsic = __webpack_require__(8024);
var setFunctionLength = __webpack_require__(4521);
var $TypeError = __webpack_require__(1642);
var $apply = GetIntrinsic('%Function.prototype.apply%');
var $call = GetIntrinsic('%Function.prototype.call%');
var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
var $defineProperty = __webpack_require__(8918);
var $max = GetIntrinsic('%Math.max%');
module.exports = function callBind(originalFunction) {
if (typeof originalFunction !== 'function') {
throw new $TypeError('a function is required');
}
var func = $reflectApply(bind, $call, arguments);
return setFunctionLength(
func,
1 + $max(0, originalFunction.length - (arguments.length - 1)),
true
);
};
var applyBind = function applyBind() {
return $reflectApply(bind, $apply, arguments);
};
if ($defineProperty) {
$defineProperty(module.exports, 'apply', { value: applyBind });
} else {
module.exports.apply = applyBind;
}
/***/ }),
/***/ 6850:
/***/ (function(module) {
"use strict";
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var toStr = Object.prototype.toString;
var max = Math.max;
var funcType = '[object Function]';
var concatty = function concatty(a, b) {
var arr = [];
for (var i = 0; i < a.length; i += 1) {
arr[i] = a[i];
}
for (var j = 0; j < b.length; j += 1) {
arr[j + a.length] = b[j];
}
return arr;
};
var slicy = function slicy(arrLike, offset) {
var arr = [];
for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
arr[j] = arrLike[i];
}
return arr;
};
var joiny = function (arr, joiner) {
var str = '';
for (var i = 0; i < arr.length; i += 1) {
str += arr[i];
if (i + 1 < arr.length) {
str += joiner;
}
}
return str;
};
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slicy(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
concatty(args, arguments)
);
if (Object(result) === result) {
return result;
}
return this;
}
return target.apply(
that,
concatty(args, arguments)
);
};
var boundLength = max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs[i] = '$' + i;
}
bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
/***/ }),
/***/ 5127:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(6850);
module.exports = Function.prototype.bind || implementation;
/***/ }),
/***/ 8024:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var undefined;
var $Error = __webpack_require__(6716);
var $EvalError = __webpack_require__(6788);
var $RangeError = __webpack_require__(9204);
var $ReferenceError = __webpack_require__(9908);
var $SyntaxError = __webpack_require__(6724);
var $TypeError = __webpack_require__(1642);
var $URIError = __webpack_require__(1451);
var $Function = Function;
// eslint-disable-next-line consistent-return
var getEvalledConstructor = function (expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
} catch (e) {}
};
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () {
throw new $TypeError();
};
var ThrowTypeError = $gOPD
? (function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}())
: throwTypeError;
var hasSymbols = __webpack_require__(330)();
var hasProto = __webpack_require__(1856)();
var getProto = Object.getPrototypeOf || (
hasProto
? function (x) { return x.__proto__; } // eslint-disable-line no-proto
: null
);
var needsEval = {};
var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array);
var INTRINSICS = {
__proto__: null,
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
'%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined,
'%AsyncFromSyncIteratorPrototype%': undefined,
'%AsyncFunction%': needsEval,
'%AsyncGenerator%': needsEval,
'%AsyncGeneratorFunction%': needsEval,
'%AsyncIteratorPrototype%': needsEval,
'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,
'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,
'%Boolean%': Boolean,
'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
'%Date%': Date,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': $Error,
'%eval%': eval, // eslint-disable-line no-eval
'%EvalError%': $EvalError,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
'%Function%': $Function,
'%GeneratorFunction%': needsEval,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined,
'%JSON%': typeof JSON === 'object' ? JSON : undefined,
'%Map%': typeof Map === 'undefined' ? undefined : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()),
'%Math%': Math,
'%Number%': Number,
'%Object%': Object,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
'%RangeError%': $RangeError,
'%ReferenceError%': $ReferenceError,
'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
'%RegExp%': RegExp,
'%Set%': typeof Set === 'undefined' ? undefined : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()),
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined,
'%Symbol%': hasSymbols ? Symbol : undefined,
'%SyntaxError%': $SyntaxError,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypeError%': $TypeError,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
'%URIError%': $URIError,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
};
if (getProto) {
try {
null.error; // eslint-disable-line no-unused-expressions
} catch (e) {
// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
var errorProto = getProto(getProto(e));
INTRINSICS['%Error.prototype%'] = errorProto;
}
}
var doEval = function doEval(name) {
var value;
if (name === '%AsyncFunction%') {
value = getEvalledConstructor('async function () {}');
} else if (name === '%GeneratorFunction%') {
value = getEvalledConstructor('function* () {}');
} else if (name === '%AsyncGeneratorFunction%') {
value = getEvalledConstructor('async function* () {}');
} else if (name === '%AsyncGenerator%') {
var fn = doEval('%AsyncGeneratorFunction%');
if (fn) {
value = fn.prototype;
}
} else if (name === '%AsyncIteratorPrototype%') {
var gen = doEval('%AsyncGenerator%');
if (gen && getProto) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name] = value;
return value;
};
var LEGACY_ALIASES = {
__proto__: null,
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
'%ArrayPrototype%': ['Array', 'prototype'],
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
'%BooleanPrototype%': ['Boolean', 'prototype'],
'%DataViewPrototype%': ['DataView', 'prototype'],
'%DatePrototype%': ['Date', 'prototype'],
'%ErrorPrototype%': ['Error', 'prototype'],
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
'%FunctionPrototype%': ['Function', 'prototype'],
'%Generator%': ['GeneratorFunction', 'prototype'],
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
'%JSONParse%': ['JSON', 'parse'],
'%JSONStringify%': ['JSON', 'stringify'],
'%MapPrototype%': ['Map', 'prototype'],
'%NumberPrototype%': ['Number', 'prototype'],
'%ObjectPrototype%': ['Object', 'prototype'],
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
'%PromisePrototype%': ['Promise', 'prototype'],
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
'%Promise_all%': ['Promise', 'all'],
'%Promise_reject%': ['Promise', 'reject'],
'%Promise_resolve%': ['Promise', 'resolve'],
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
'%RegExpPrototype%': ['RegExp', 'prototype'],
'%SetPrototype%': ['Set', 'prototype'],
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
'%StringPrototype%': ['String', 'prototype'],
'%SymbolPrototype%': ['Symbol', 'prototype'],
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
'%URIErrorPrototype%': ['URIError', 'prototype'],
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
'%WeakSetPrototype%': ['WeakSet', 'prototype']
};
var bind = __webpack_require__(5127);
var hasOwn = __webpack_require__(9429);
var $concat = bind.call(Function.call, Array.prototype.concat);
var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
var $replace = bind.call(Function.call, String.prototype.replace);
var $strSlice = bind.call(Function.call, String.prototype.slice);
var $exec = bind.call(Function.call, RegExp.prototype.exec);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
var first = $strSlice(string, 0, 1);
var last = $strSlice(string, -1);
if (first === '%' && last !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
} else if (last === '%' && first !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
}
var result = [];
$replace(string, rePropName, function (match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
var intrinsicName = name;
var alias;
if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
alias = LEGACY_ALIASES[intrinsicName];
intrinsicName = '%' + alias[0] + '%';
}
if (hasOwn(INTRINSICS, intrinsicName)) {
var value = INTRINSICS[intrinsicName];
if (value === needsEval) {
value = doEval(intrinsicName);
}
if (typeof value === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return {
alias: alias,
name: intrinsicName,
value: value
};
}
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
};
module.exports = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new $TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new $TypeError('"allowMissing" argument must be a boolean');
}
if ($exec(/^%?[^%]*%?$/, name) === null) {
throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
}
var parts = stringToPath(name);
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
var intrinsicRealName = intrinsic.name;
var value = intrinsic.value;
var skipFurtherCaching = false;
var alias = intrinsic.alias;
if (alias) {
intrinsicBaseName = alias[0];
$spliceApply(parts, $concat([0, 1], alias));
}
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
var part = parts[i];
var first = $strSlice(part, 0, 1);
var last = $strSlice(part, -1);
if (
(
(first === '"' || first === "'" || first === '`')
|| (last === '"' || last === "'" || last === '`')
)
&& first !== last
) {
throw new $SyntaxError('property names with quotes must have matching quotes');
}
if (part === 'constructor' || !isOwn) {
skipFurtherCaching = true;
}
intrinsicBaseName += '.' + part;
intrinsicRealName = '%' + intrinsicBaseName + '%';
if (hasOwn(INTRINSICS, intrinsicRealName)) {
value = INTRINSICS[intrinsicRealName];
} else if (value != null) {
if (!(part in value)) {
if (!allowMissing) {
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
}
return void undefined;
}
if ($gOPD && (i + 1) >= parts.length) {
var desc = $gOPD(value, part);
isOwn = !!desc;
// By convention, when a data property is converted to an accessor
// property to emulate a data property that does not suffer from
// the override mistake, that accessor's getter is marked with
// an `originalValue` property. Here, when we detect this, we
// uphold the illusion by pretending to see that original data
// property, i.e., returning the value rather than the getter
// itself.
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
value = desc.get;
} else {
value = value[part];
}
} else {
isOwn = hasOwn(value, part);
value = value[part];
}
if (isOwn && !skipFurtherCaching) {
INTRINSICS[intrinsicRealName] = value;
}
}
}
return value;
};
/***/ }),
/***/ 330:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = __webpack_require__(1489);
module.exports = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return hasSymbolSham();
};
/***/ }),
/***/ 1489:
/***/ (function(module) {
"use strict";
/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
/***/ }),
/***/ 9277:
/***/ (function(module) {
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
/***/ }),
/***/ 1312:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var callBound = __webpack_require__(2137);
var isRegex = __webpack_require__(6073);
var $exec = callBound('RegExp.prototype.exec');
var $TypeError = __webpack_require__(1642);
module.exports = function regexTester(regex) {
if (!isRegex(regex)) {
throw new $TypeError('`regex` must be a RegExp');
}
return function test(s) {
return $exec(regex, s) !== null;
};
};
/***/ }),
/***/ 2137:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(5273);
var callBind = __webpack_require__(381);
var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));
module.exports = function callBoundIntrinsic(name, allowMissing) {
var intrinsic = GetIntrinsic(name, !!allowMissing);
if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
return callBind(intrinsic);
}
return intrinsic;
};
/***/ }),
/***/ 381:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var bind = __webpack_require__(3331);
var GetIntrinsic = __webpack_require__(5273);
var setFunctionLength = __webpack_require__(4521);
var $TypeError = __webpack_require__(1642);
var $apply = GetIntrinsic('%Function.prototype.apply%');
var $call = GetIntrinsic('%Function.prototype.call%');
var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
var $defineProperty = __webpack_require__(8918);
var $max = GetIntrinsic('%Math.max%');
module.exports = function callBind(originalFunction) {
if (typeof originalFunction !== 'function') {
throw new $TypeError('a function is required');
}
var func = $reflectApply(bind, $call, arguments);
return setFunctionLength(
func,
1 + $max(0, originalFunction.length - (arguments.length - 1)),
true
);
};
var applyBind = function applyBind() {
return $reflectApply(bind, $apply, arguments);
};
if ($defineProperty) {
$defineProperty(module.exports, 'apply', { value: applyBind });
} else {
module.exports.apply = applyBind;
}
/***/ }),
/***/ 7780:
/***/ (function(module) {
"use strict";
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var toStr = Object.prototype.toString;
var max = Math.max;
var funcType = '[object Function]';
var concatty = function concatty(a, b) {
var arr = [];
for (var i = 0; i < a.length; i += 1) {
arr[i] = a[i];
}
for (var j = 0; j < b.length; j += 1) {
arr[j + a.length] = b[j];
}
return arr;
};
var slicy = function slicy(arrLike, offset) {
var arr = [];
for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
arr[j] = arrLike[i];
}
return arr;
};
var joiny = function (arr, joiner) {
var str = '';
for (var i = 0; i < arr.length; i += 1) {
str += arr[i];
if (i + 1 < arr.length) {
str += joiner;
}
}
return str;
};
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slicy(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
concatty(args, arguments)
);
if (Object(result) === result) {
return result;
}
return this;
}
return target.apply(
that,
concatty(args, arguments)
);
};
var boundLength = max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs[i] = '$' + i;
}
bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
/***/ }),
/***/ 3331:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(7780);
module.exports = Function.prototype.bind || implementation;
/***/ }),
/***/ 5273:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var undefined;
var $Error = __webpack_require__(6716);
var $EvalError = __webpack_require__(6788);
var $RangeError = __webpack_require__(9204);
var $ReferenceError = __webpack_require__(9908);
var $SyntaxError = __webpack_require__(6724);
var $TypeError = __webpack_require__(1642);
var $URIError = __webpack_require__(1451);
var $Function = Function;
// eslint-disable-next-line consistent-return
var getEvalledConstructor = function (expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
} catch (e) {}
};
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () {
throw new $TypeError();
};
var ThrowTypeError = $gOPD
? (function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}())
: throwTypeError;
var hasSymbols = __webpack_require__(6339)();
var hasProto = __webpack_require__(1856)();
var getProto = Object.getPrototypeOf || (
hasProto
? function (x) { return x.__proto__; } // eslint-disable-line no-proto
: null
);
var needsEval = {};
var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array);
var INTRINSICS = {
__proto__: null,
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
'%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined,
'%AsyncFromSyncIteratorPrototype%': undefined,
'%AsyncFunction%': needsEval,
'%AsyncGenerator%': needsEval,
'%AsyncGeneratorFunction%': needsEval,
'%AsyncIteratorPrototype%': needsEval,
'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,
'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,
'%Boolean%': Boolean,
'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
'%Date%': Date,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': $Error,
'%eval%': eval, // eslint-disable-line no-eval
'%EvalError%': $EvalError,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
'%Function%': $Function,
'%GeneratorFunction%': needsEval,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined,
'%JSON%': typeof JSON === 'object' ? JSON : undefined,
'%Map%': typeof Map === 'undefined' ? undefined : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()),
'%Math%': Math,
'%Number%': Number,
'%Object%': Object,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
'%RangeError%': $RangeError,
'%ReferenceError%': $ReferenceError,
'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
'%RegExp%': RegExp,
'%Set%': typeof Set === 'undefined' ? undefined : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()),
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined,
'%Symbol%': hasSymbols ? Symbol : undefined,
'%SyntaxError%': $SyntaxError,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypeError%': $TypeError,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
'%URIError%': $URIError,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
};
if (getProto) {
try {
null.error; // eslint-disable-line no-unused-expressions
} catch (e) {
// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
var errorProto = getProto(getProto(e));
INTRINSICS['%Error.prototype%'] = errorProto;
}
}
var doEval = function doEval(name) {
var value;
if (name === '%AsyncFunction%') {
value = getEvalledConstructor('async function () {}');
} else if (name === '%GeneratorFunction%') {
value = getEvalledConstructor('function* () {}');
} else if (name === '%AsyncGeneratorFunction%') {
value = getEvalledConstructor('async function* () {}');
} else if (name === '%AsyncGenerator%') {
var fn = doEval('%AsyncGeneratorFunction%');
if (fn) {
value = fn.prototype;
}
} else if (name === '%AsyncIteratorPrototype%') {
var gen = doEval('%AsyncGenerator%');
if (gen && getProto) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name] = value;
return value;
};
var LEGACY_ALIASES = {
__proto__: null,
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
'%ArrayPrototype%': ['Array', 'prototype'],
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
'%BooleanPrototype%': ['Boolean', 'prototype'],
'%DataViewPrototype%': ['DataView', 'prototype'],
'%DatePrototype%': ['Date', 'prototype'],
'%ErrorPrototype%': ['Error', 'prototype'],
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
'%FunctionPrototype%': ['Function', 'prototype'],
'%Generator%': ['GeneratorFunction', 'prototype'],
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
'%JSONParse%': ['JSON', 'parse'],
'%JSONStringify%': ['JSON', 'stringify'],
'%MapPrototype%': ['Map', 'prototype'],
'%NumberPrototype%': ['Number', 'prototype'],
'%ObjectPrototype%': ['Object', 'prototype'],
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
'%PromisePrototype%': ['Promise', 'prototype'],
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
'%Promise_all%': ['Promise', 'all'],
'%Promise_reject%': ['Promise', 'reject'],
'%Promise_resolve%': ['Promise', 'resolve'],
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
'%RegExpPrototype%': ['RegExp', 'prototype'],
'%SetPrototype%': ['Set', 'prototype'],
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
'%StringPrototype%': ['String', 'prototype'],
'%SymbolPrototype%': ['Symbol', 'prototype'],
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
'%URIErrorPrototype%': ['URIError', 'prototype'],
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
'%WeakSetPrototype%': ['WeakSet', 'prototype']
};
var bind = __webpack_require__(3331);
var hasOwn = __webpack_require__(9429);
var $concat = bind.call(Function.call, Array.prototype.concat);
var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
var $replace = bind.call(Function.call, String.prototype.replace);
var $strSlice = bind.call(Function.call, String.prototype.slice);
var $exec = bind.call(Function.call, RegExp.prototype.exec);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
var first = $strSlice(string, 0, 1);
var last = $strSlice(string, -1);
if (first === '%' && last !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
} else if (last === '%' && first !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
}
var result = [];
$replace(string, rePropName, function (match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
var intrinsicName = name;
var alias;
if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
alias = LEGACY_ALIASES[intrinsicName];
intrinsicName = '%' + alias[0] + '%';
}
if (hasOwn(INTRINSICS, intrinsicName)) {
var value = INTRINSICS[intrinsicName];
if (value === needsEval) {
value = doEval(intrinsicName);
}
if (typeof value === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return {
alias: alias,
name: intrinsicName,
value: value
};
}
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
};
module.exports = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new $TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new $TypeError('"allowMissing" argument must be a boolean');
}
if ($exec(/^%?[^%]*%?$/, name) === null) {
throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
}
var parts = stringToPath(name);
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
var intrinsicRealName = intrinsic.name;
var value = intrinsic.value;
var skipFurtherCaching = false;
var alias = intrinsic.alias;
if (alias) {
intrinsicBaseName = alias[0];
$spliceApply(parts, $concat([0, 1], alias));
}
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
var part = parts[i];
var first = $strSlice(part, 0, 1);
var last = $strSlice(part, -1);
if (
(
(first === '"' || first === "'" || first === '`')
|| (last === '"' || last === "'" || last === '`')
)
&& first !== last
) {
throw new $SyntaxError('property names with quotes must have matching quotes');
}
if (part === 'constructor' || !isOwn) {
skipFurtherCaching = true;
}
intrinsicBaseName += '.' + part;
intrinsicRealName = '%' + intrinsicBaseName + '%';
if (hasOwn(INTRINSICS, intrinsicRealName)) {
value = INTRINSICS[intrinsicRealName];
} else if (value != null) {
if (!(part in value)) {
if (!allowMissing) {
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
}
return void undefined;
}
if ($gOPD && (i + 1) >= parts.length) {
var desc = $gOPD(value, part);
isOwn = !!desc;
// By convention, when a data property is converted to an accessor
// property to emulate a data property that does not suffer from
// the override mistake, that accessor's getter is marked with
// an `originalValue` property. Here, when we detect this, we
// uphold the illusion by pretending to see that original data
// property, i.e., returning the value rather than the getter
// itself.
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
value = desc.get;
} else {
value = value[part];
}
} else {
isOwn = hasOwn(value, part);
value = value[part];
}
if (isOwn && !skipFurtherCaching) {
INTRINSICS[intrinsicRealName] = value;
}
}
}
return value;
};
/***/ }),
/***/ 6339:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = __webpack_require__(6789);
module.exports = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return hasSymbolSham();
};
/***/ }),
/***/ 6789:
/***/ (function(module) {
"use strict";
/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
/***/ }),
/***/ 6073:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var callBound = __webpack_require__(2137);
var hasToStringTag = __webpack_require__(4111)();
var has;
var $exec;
var isRegexMarker;
var badStringifier;
if (hasToStringTag) {
has = callBound('Object.prototype.hasOwnProperty');
$exec = callBound('RegExp.prototype.exec');
isRegexMarker = {};
var throwRegexMarker = function () {
throw isRegexMarker;
};
badStringifier = {
toString: throwRegexMarker,
valueOf: throwRegexMarker
};
if (typeof Symbol.toPrimitive === 'symbol') {
badStringifier[Symbol.toPrimitive] = throwRegexMarker;
}
}
var $toString = callBound('Object.prototype.toString');
var gOPD = Object.getOwnPropertyDescriptor;
var regexClass = '[object RegExp]';
module.exports = hasToStringTag
// eslint-disable-next-line consistent-return
? function isRegex(value) {
if (!value || typeof value !== 'object') {
return false;
}
var descriptor = gOPD(value, 'lastIndex');
var hasLastIndexDataProperty = descriptor && has(descriptor, 'value');
if (!hasLastIndexDataProperty) {
return false;
}
try {
$exec(value, badStringifier);
} catch (e) {
return e === isRegexMarker;
}
}
: function isRegex(value) {
// In older browsers, typeof regex incorrectly returns 'function'
if (!value || (typeof value !== 'object' && typeof value !== 'function')) {
return false;
}
return $toString(value) === regexClass;
};
/***/ }),
/***/ 4521:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(1757);
var define = __webpack_require__(2656);
var hasDescriptors = __webpack_require__(8198)();
var gOPD = __webpack_require__(3828);
var $TypeError = __webpack_require__(1642);
var $floor = GetIntrinsic('%Math.floor%');
/** @type {import('.')} */
module.exports = function setFunctionLength(fn, length) {
if (typeof fn !== 'function') {
throw new $TypeError('`fn` is not a function');
}
if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) {
throw new $TypeError('`length` must be a positive 32-bit integer');
}
var loose = arguments.length > 2 && !!arguments[2];
var functionLengthIsConfigurable = true;
var functionLengthIsWritable = true;
if ('length' in fn && gOPD) {
var desc = gOPD(fn, 'length');
if (desc && !desc.configurable) {
functionLengthIsConfigurable = false;
}
if (desc && !desc.writable) {
functionLengthIsWritable = false;
}
}
if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) {
if (hasDescriptors) {
define(/** @type {Parameters<define>[0]} */ (fn), 'length', length, true, true);
} else {
define(/** @type {Parameters<define>[0]} */ (fn), 'length', length);
}
}
return fn;
};
/***/ }),
/***/ 5371:
/***/ (function(module) {
"use strict";
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var toStr = Object.prototype.toString;
var max = Math.max;
var funcType = '[object Function]';
var concatty = function concatty(a, b) {
var arr = [];
for (var i = 0; i < a.length; i += 1) {
arr[i] = a[i];
}
for (var j = 0; j < b.length; j += 1) {
arr[j + a.length] = b[j];
}
return arr;
};
var slicy = function slicy(arrLike, offset) {
var arr = [];
for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
arr[j] = arrLike[i];
}
return arr;
};
var joiny = function (arr, joiner) {
var str = '';
for (var i = 0; i < arr.length; i += 1) {
str += arr[i];
if (i + 1 < arr.length) {
str += joiner;
}
}
return str;
};
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slicy(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
concatty(args, arguments)
);
if (Object(result) === result) {
return result;
}
return this;
}
return target.apply(
that,
concatty(args, arguments)
);
};
var boundLength = max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs[i] = '$' + i;
}
bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
/***/ }),
/***/ 9015:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(5371);
module.exports = Function.prototype.bind || implementation;
/***/ }),
/***/ 1757:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var undefined;
var $Error = __webpack_require__(6716);
var $EvalError = __webpack_require__(6788);
var $RangeError = __webpack_require__(9204);
var $ReferenceError = __webpack_require__(9908);
var $SyntaxError = __webpack_require__(6724);
var $TypeError = __webpack_require__(1642);
var $URIError = __webpack_require__(1451);
var $Function = Function;
// eslint-disable-next-line consistent-return
var getEvalledConstructor = function (expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
} catch (e) {}
};
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () {
throw new $TypeError();
};
var ThrowTypeError = $gOPD
? (function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}())
: throwTypeError;
var hasSymbols = __webpack_require__(1207)();
var hasProto = __webpack_require__(1856)();
var getProto = Object.getPrototypeOf || (
hasProto
? function (x) { return x.__proto__; } // eslint-disable-line no-proto
: null
);
var needsEval = {};
var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array);
var INTRINSICS = {
__proto__: null,
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
'%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined,
'%AsyncFromSyncIteratorPrototype%': undefined,
'%AsyncFunction%': needsEval,
'%AsyncGenerator%': needsEval,
'%AsyncGeneratorFunction%': needsEval,
'%AsyncIteratorPrototype%': needsEval,
'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,
'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,
'%Boolean%': Boolean,
'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
'%Date%': Date,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': $Error,
'%eval%': eval, // eslint-disable-line no-eval
'%EvalError%': $EvalError,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
'%Function%': $Function,
'%GeneratorFunction%': needsEval,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined,
'%JSON%': typeof JSON === 'object' ? JSON : undefined,
'%Map%': typeof Map === 'undefined' ? undefined : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()),
'%Math%': Math,
'%Number%': Number,
'%Object%': Object,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
'%RangeError%': $RangeError,
'%ReferenceError%': $ReferenceError,
'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
'%RegExp%': RegExp,
'%Set%': typeof Set === 'undefined' ? undefined : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()),
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined,
'%Symbol%': hasSymbols ? Symbol : undefined,
'%SyntaxError%': $SyntaxError,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypeError%': $TypeError,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
'%URIError%': $URIError,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
};
if (getProto) {
try {
null.error; // eslint-disable-line no-unused-expressions
} catch (e) {
// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
var errorProto = getProto(getProto(e));
INTRINSICS['%Error.prototype%'] = errorProto;
}
}
var doEval = function doEval(name) {
var value;
if (name === '%AsyncFunction%') {
value = getEvalledConstructor('async function () {}');
} else if (name === '%GeneratorFunction%') {
value = getEvalledConstructor('function* () {}');
} else if (name === '%AsyncGeneratorFunction%') {
value = getEvalledConstructor('async function* () {}');
} else if (name === '%AsyncGenerator%') {
var fn = doEval('%AsyncGeneratorFunction%');
if (fn) {
value = fn.prototype;
}
} else if (name === '%AsyncIteratorPrototype%') {
var gen = doEval('%AsyncGenerator%');
if (gen && getProto) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name] = value;
return value;
};
var LEGACY_ALIASES = {
__proto__: null,
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
'%ArrayPrototype%': ['Array', 'prototype'],
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
'%BooleanPrototype%': ['Boolean', 'prototype'],
'%DataViewPrototype%': ['DataView', 'prototype'],
'%DatePrototype%': ['Date', 'prototype'],
'%ErrorPrototype%': ['Error', 'prototype'],
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
'%FunctionPrototype%': ['Function', 'prototype'],
'%Generator%': ['GeneratorFunction', 'prototype'],
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
'%JSONParse%': ['JSON', 'parse'],
'%JSONStringify%': ['JSON', 'stringify'],
'%MapPrototype%': ['Map', 'prototype'],
'%NumberPrototype%': ['Number', 'prototype'],
'%ObjectPrototype%': ['Object', 'prototype'],
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
'%PromisePrototype%': ['Promise', 'prototype'],
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
'%Promise_all%': ['Promise', 'all'],
'%Promise_reject%': ['Promise', 'reject'],
'%Promise_resolve%': ['Promise', 'resolve'],
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
'%RegExpPrototype%': ['RegExp', 'prototype'],
'%SetPrototype%': ['Set', 'prototype'],
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
'%StringPrototype%': ['String', 'prototype'],
'%SymbolPrototype%': ['Symbol', 'prototype'],
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
'%URIErrorPrototype%': ['URIError', 'prototype'],
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
'%WeakSetPrototype%': ['WeakSet', 'prototype']
};
var bind = __webpack_require__(9015);
var hasOwn = __webpack_require__(9429);
var $concat = bind.call(Function.call, Array.prototype.concat);
var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
var $replace = bind.call(Function.call, String.prototype.replace);
var $strSlice = bind.call(Function.call, String.prototype.slice);
var $exec = bind.call(Function.call, RegExp.prototype.exec);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
var first = $strSlice(string, 0, 1);
var last = $strSlice(string, -1);
if (first === '%' && last !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
} else if (last === '%' && first !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
}
var result = [];
$replace(string, rePropName, function (match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
var intrinsicName = name;
var alias;
if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
alias = LEGACY_ALIASES[intrinsicName];
intrinsicName = '%' + alias[0] + '%';
}
if (hasOwn(INTRINSICS, intrinsicName)) {
var value = INTRINSICS[intrinsicName];
if (value === needsEval) {
value = doEval(intrinsicName);
}
if (typeof value === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return {
alias: alias,
name: intrinsicName,
value: value
};
}
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
};
module.exports = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new $TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new $TypeError('"allowMissing" argument must be a boolean');
}
if ($exec(/^%?[^%]*%?$/, name) === null) {
throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
}
var parts = stringToPath(name);
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
var intrinsicRealName = intrinsic.name;
var value = intrinsic.value;
var skipFurtherCaching = false;
var alias = intrinsic.alias;
if (alias) {
intrinsicBaseName = alias[0];
$spliceApply(parts, $concat([0, 1], alias));
}
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
var part = parts[i];
var first = $strSlice(part, 0, 1);
var last = $strSlice(part, -1);
if (
(
(first === '"' || first === "'" || first === '`')
|| (last === '"' || last === "'" || last === '`')
)
&& first !== last
) {
throw new $SyntaxError('property names with quotes must have matching quotes');
}
if (part === 'constructor' || !isOwn) {
skipFurtherCaching = true;
}
intrinsicBaseName += '.' + part;
intrinsicRealName = '%' + intrinsicBaseName + '%';
if (hasOwn(INTRINSICS, intrinsicRealName)) {
value = INTRINSICS[intrinsicRealName];
} else if (value != null) {
if (!(part in value)) {
if (!allowMissing) {
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
}
return void undefined;
}
if ($gOPD && (i + 1) >= parts.length) {
var desc = $gOPD(value, part);
isOwn = !!desc;
// By convention, when a data property is converted to an accessor
// property to emulate a data property that does not suffer from
// the override mistake, that accessor's getter is marked with
// an `originalValue` property. Here, when we detect this, we
// uphold the illusion by pretending to see that original data
// property, i.e., returning the value rather than the getter
// itself.
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
value = desc.get;
} else {
value = value[part];
}
} else {
isOwn = hasOwn(value, part);
value = value[part];
}
if (isOwn && !skipFurtherCaching) {
INTRINSICS[intrinsicRealName] = value;
}
}
}
return value;
};
/***/ }),
/***/ 1207:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = __webpack_require__(2326);
module.exports = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return hasSymbolSham();
};
/***/ }),
/***/ 2326:
/***/ (function(module) {
"use strict";
/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
/***/ }),
/***/ 5467:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var RequireObjectCoercible = __webpack_require__(7998);
var ToString = __webpack_require__(6245);
var callBound = __webpack_require__(6907);
var $replace = callBound('String.prototype.replace');
var mvsIsWS = (/^\s$/).test('\u180E');
/* eslint-disable no-control-regex */
var leftWhitespace = mvsIsWS
? /^[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+/
: /^[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+/;
var rightWhitespace = mvsIsWS
? /[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+$/
: /[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+$/;
/* eslint-enable no-control-regex */
module.exports = function trim() {
var S = ToString(RequireObjectCoercible(this));
return $replace($replace(S, leftWhitespace, ''), rightWhitespace, '');
};
/***/ }),
/***/ 4113:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var callBind = __webpack_require__(7618);
var define = __webpack_require__(5213);
var RequireObjectCoercible = __webpack_require__(7998);
var implementation = __webpack_require__(5467);
var getPolyfill = __webpack_require__(5626);
var shim = __webpack_require__(1029);
var bound = callBind(getPolyfill());
var boundMethod = function trim(receiver) {
RequireObjectCoercible(receiver);
return bound(receiver);
};
define(boundMethod, {
getPolyfill: getPolyfill,
implementation: implementation,
shim: shim
});
module.exports = boundMethod;
/***/ }),
/***/ 6907:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(5037);
var callBind = __webpack_require__(7618);
var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));
module.exports = function callBoundIntrinsic(name, allowMissing) {
var intrinsic = GetIntrinsic(name, !!allowMissing);
if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
return callBind(intrinsic);
}
return intrinsic;
};
/***/ }),
/***/ 7618:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var bind = __webpack_require__(1769);
var GetIntrinsic = __webpack_require__(5037);
var setFunctionLength = __webpack_require__(4521);
var $TypeError = __webpack_require__(1642);
var $apply = GetIntrinsic('%Function.prototype.apply%');
var $call = GetIntrinsic('%Function.prototype.call%');
var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
var $defineProperty = __webpack_require__(8918);
var $max = GetIntrinsic('%Math.max%');
module.exports = function callBind(originalFunction) {
if (typeof originalFunction !== 'function') {
throw new $TypeError('a function is required');
}
var func = $reflectApply(bind, $call, arguments);
return setFunctionLength(
func,
1 + $max(0, originalFunction.length - (arguments.length - 1)),
true
);
};
var applyBind = function applyBind() {
return $reflectApply(bind, $apply, arguments);
};
if ($defineProperty) {
$defineProperty(module.exports, 'apply', { value: applyBind });
} else {
module.exports.apply = applyBind;
}
/***/ }),
/***/ 5213:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var keys = __webpack_require__(806);
var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';
var toStr = Object.prototype.toString;
var concat = Array.prototype.concat;
var defineDataProperty = __webpack_require__(2656);
var isFunction = function (fn) {
return typeof fn === 'function' && toStr.call(fn) === '[object Function]';
};
var supportsDescriptors = __webpack_require__(8198)();
var defineProperty = function (object, name, value, predicate) {
if (name in object) {
if (predicate === true) {
if (object[name] === value) {
return;
}
} else if (!isFunction(predicate) || !predicate()) {
return;
}
}
if (supportsDescriptors) {
defineDataProperty(object, name, value, true);
} else {
defineDataProperty(object, name, value);
}
};
var defineProperties = function (object, map) {
var predicates = arguments.length > 2 ? arguments[2] : {};
var props = keys(map);
if (hasSymbols) {
props = concat.call(props, Object.getOwnPropertySymbols(map));
}
for (var i = 0; i < props.length; i += 1) {
defineProperty(object, props[i], map[props[i]], predicates[props[i]]);
}
};
defineProperties.supportsDescriptors = !!supportsDescriptors;
module.exports = defineProperties;
/***/ }),
/***/ 1032:
/***/ (function(module) {
"use strict";
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var toStr = Object.prototype.toString;
var max = Math.max;
var funcType = '[object Function]';
var concatty = function concatty(a, b) {
var arr = [];
for (var i = 0; i < a.length; i += 1) {
arr[i] = a[i];
}
for (var j = 0; j < b.length; j += 1) {
arr[j + a.length] = b[j];
}
return arr;
};
var slicy = function slicy(arrLike, offset) {
var arr = [];
for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
arr[j] = arrLike[i];
}
return arr;
};
var joiny = function (arr, joiner) {
var str = '';
for (var i = 0; i < arr.length; i += 1) {
str += arr[i];
if (i + 1 < arr.length) {
str += joiner;
}
}
return str;
};
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slicy(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
concatty(args, arguments)
);
if (Object(result) === result) {
return result;
}
return this;
}
return target.apply(
that,
concatty(args, arguments)
);
};
var boundLength = max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs[i] = '$' + i;
}
bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
/***/ }),
/***/ 1769:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(1032);
module.exports = Function.prototype.bind || implementation;
/***/ }),
/***/ 5037:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var undefined;
var $Error = __webpack_require__(6716);
var $EvalError = __webpack_require__(6788);
var $RangeError = __webpack_require__(9204);
var $ReferenceError = __webpack_require__(9908);
var $SyntaxError = __webpack_require__(6724);
var $TypeError = __webpack_require__(1642);
var $URIError = __webpack_require__(1451);
var $Function = Function;
// eslint-disable-next-line consistent-return
var getEvalledConstructor = function (expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
} catch (e) {}
};
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () {
throw new $TypeError();
};
var ThrowTypeError = $gOPD
? (function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}())
: throwTypeError;
var hasSymbols = __webpack_require__(5570)();
var hasProto = __webpack_require__(1856)();
var getProto = Object.getPrototypeOf || (
hasProto
? function (x) { return x.__proto__; } // eslint-disable-line no-proto
: null
);
var needsEval = {};
var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array);
var INTRINSICS = {
__proto__: null,
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
'%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined,
'%AsyncFromSyncIteratorPrototype%': undefined,
'%AsyncFunction%': needsEval,
'%AsyncGenerator%': needsEval,
'%AsyncGeneratorFunction%': needsEval,
'%AsyncIteratorPrototype%': needsEval,
'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,
'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,
'%Boolean%': Boolean,
'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
'%Date%': Date,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': $Error,
'%eval%': eval, // eslint-disable-line no-eval
'%EvalError%': $EvalError,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
'%Function%': $Function,
'%GeneratorFunction%': needsEval,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined,
'%JSON%': typeof JSON === 'object' ? JSON : undefined,
'%Map%': typeof Map === 'undefined' ? undefined : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()),
'%Math%': Math,
'%Number%': Number,
'%Object%': Object,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
'%RangeError%': $RangeError,
'%ReferenceError%': $ReferenceError,
'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
'%RegExp%': RegExp,
'%Set%': typeof Set === 'undefined' ? undefined : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()),
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined,
'%Symbol%': hasSymbols ? Symbol : undefined,
'%SyntaxError%': $SyntaxError,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypeError%': $TypeError,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
'%URIError%': $URIError,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
};
if (getProto) {
try {
null.error; // eslint-disable-line no-unused-expressions
} catch (e) {
// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
var errorProto = getProto(getProto(e));
INTRINSICS['%Error.prototype%'] = errorProto;
}
}
var doEval = function doEval(name) {
var value;
if (name === '%AsyncFunction%') {
value = getEvalledConstructor('async function () {}');
} else if (name === '%GeneratorFunction%') {
value = getEvalledConstructor('function* () {}');
} else if (name === '%AsyncGeneratorFunction%') {
value = getEvalledConstructor('async function* () {}');
} else if (name === '%AsyncGenerator%') {
var fn = doEval('%AsyncGeneratorFunction%');
if (fn) {
value = fn.prototype;
}
} else if (name === '%AsyncIteratorPrototype%') {
var gen = doEval('%AsyncGenerator%');
if (gen && getProto) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name] = value;
return value;
};
var LEGACY_ALIASES = {
__proto__: null,
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
'%ArrayPrototype%': ['Array', 'prototype'],
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
'%BooleanPrototype%': ['Boolean', 'prototype'],
'%DataViewPrototype%': ['DataView', 'prototype'],
'%DatePrototype%': ['Date', 'prototype'],
'%ErrorPrototype%': ['Error', 'prototype'],
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
'%FunctionPrototype%': ['Function', 'prototype'],
'%Generator%': ['GeneratorFunction', 'prototype'],
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
'%JSONParse%': ['JSON', 'parse'],
'%JSONStringify%': ['JSON', 'stringify'],
'%MapPrototype%': ['Map', 'prototype'],
'%NumberPrototype%': ['Number', 'prototype'],
'%ObjectPrototype%': ['Object', 'prototype'],
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
'%PromisePrototype%': ['Promise', 'prototype'],
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
'%Promise_all%': ['Promise', 'all'],
'%Promise_reject%': ['Promise', 'reject'],
'%Promise_resolve%': ['Promise', 'resolve'],
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
'%RegExpPrototype%': ['RegExp', 'prototype'],
'%SetPrototype%': ['Set', 'prototype'],
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
'%StringPrototype%': ['String', 'prototype'],
'%SymbolPrototype%': ['Symbol', 'prototype'],
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
'%URIErrorPrototype%': ['URIError', 'prototype'],
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
'%WeakSetPrototype%': ['WeakSet', 'prototype']
};
var bind = __webpack_require__(1769);
var hasOwn = __webpack_require__(9429);
var $concat = bind.call(Function.call, Array.prototype.concat);
var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
var $replace = bind.call(Function.call, String.prototype.replace);
var $strSlice = bind.call(Function.call, String.prototype.slice);
var $exec = bind.call(Function.call, RegExp.prototype.exec);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
var first = $strSlice(string, 0, 1);
var last = $strSlice(string, -1);
if (first === '%' && last !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
} else if (last === '%' && first !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
}
var result = [];
$replace(string, rePropName, function (match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
var intrinsicName = name;
var alias;
if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
alias = LEGACY_ALIASES[intrinsicName];
intrinsicName = '%' + alias[0] + '%';
}
if (hasOwn(INTRINSICS, intrinsicName)) {
var value = INTRINSICS[intrinsicName];
if (value === needsEval) {
value = doEval(intrinsicName);
}
if (typeof value === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return {
alias: alias,
name: intrinsicName,
value: value
};
}
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
};
module.exports = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new $TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new $TypeError('"allowMissing" argument must be a boolean');
}
if ($exec(/^%?[^%]*%?$/, name) === null) {
throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
}
var parts = stringToPath(name);
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
var intrinsicRealName = intrinsic.name;
var value = intrinsic.value;
var skipFurtherCaching = false;
var alias = intrinsic.alias;
if (alias) {
intrinsicBaseName = alias[0];
$spliceApply(parts, $concat([0, 1], alias));
}
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
var part = parts[i];
var first = $strSlice(part, 0, 1);
var last = $strSlice(part, -1);
if (
(
(first === '"' || first === "'" || first === '`')
|| (last === '"' || last === "'" || last === '`')
)
&& first !== last
) {
throw new $SyntaxError('property names with quotes must have matching quotes');
}
if (part === 'constructor' || !isOwn) {
skipFurtherCaching = true;
}
intrinsicBaseName += '.' + part;
intrinsicRealName = '%' + intrinsicBaseName + '%';
if (hasOwn(INTRINSICS, intrinsicRealName)) {
value = INTRINSICS[intrinsicRealName];
} else if (value != null) {
if (!(part in value)) {
if (!allowMissing) {
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
}
return void undefined;
}
if ($gOPD && (i + 1) >= parts.length) {
var desc = $gOPD(value, part);
isOwn = !!desc;
// By convention, when a data property is converted to an accessor
// property to emulate a data property that does not suffer from
// the override mistake, that accessor's getter is marked with
// an `originalValue` property. Here, when we detect this, we
// uphold the illusion by pretending to see that original data
// property, i.e., returning the value rather than the getter
// itself.
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
value = desc.get;
} else {
value = value[part];
}
} else {
isOwn = hasOwn(value, part);
value = value[part];
}
if (isOwn && !skipFurtherCaching) {
INTRINSICS[intrinsicRealName] = value;
}
}
}
return value;
};
/***/ }),
/***/ 5570:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = __webpack_require__(5889);
module.exports = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return hasSymbolSham();
};
/***/ }),
/***/ 5889:
/***/ (function(module) {
"use strict";
/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
/***/ }),
/***/ 5626:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(5467);
var zeroWidthSpace = '\u200b';
var mongolianVowelSeparator = '\u180E';
module.exports = function getPolyfill() {
if (
String.prototype.trim
&& zeroWidthSpace.trim() === zeroWidthSpace
&& mongolianVowelSeparator.trim() === mongolianVowelSeparator
&& ('_' + mongolianVowelSeparator).trim() === ('_' + mongolianVowelSeparator)
&& (mongolianVowelSeparator + '_').trim() === (mongolianVowelSeparator + '_')
) {
return String.prototype.trim;
}
return implementation;
};
/***/ }),
/***/ 1029:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var define = __webpack_require__(5213);
var getPolyfill = __webpack_require__(5626);
module.exports = function shimStringTrim() {
var polyfill = getPolyfill();
define(String.prototype, { trim: polyfill }, {
trim: function testTrim() {
return String.prototype.trim !== polyfill;
}
});
return polyfill;
};
/***/ }),
/***/ 3124:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var whichTypedArray = __webpack_require__(4010);
var taSlice = __webpack_require__(1140);
var gopd = __webpack_require__(3828);
// TODO: use call-bind, is-date, is-regex, is-string, is-boolean-object, is-number-object
function toS(obj) { return Object.prototype.toString.call(obj); }
function isDate(obj) { return toS(obj) === '[object Date]'; }
function isRegExp(obj) { return toS(obj) === '[object RegExp]'; }
function isError(obj) { return toS(obj) === '[object Error]'; }
function isBoolean(obj) { return toS(obj) === '[object Boolean]'; }
function isNumber(obj) { return toS(obj) === '[object Number]'; }
function isString(obj) { return toS(obj) === '[object String]'; }
// TODO: use isarray
var isArray = Array.isArray || function isArray(xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
// TODO: use for-each?
function forEach(xs, fn) {
if (xs.forEach) { return xs.forEach(fn); }
for (var i = 0; i < xs.length; i++) {
fn(xs[i], i, xs);
}
return void undefined;
}
// TODO: use object-keys
var objectKeys = Object.keys || function keys(obj) {
var res = [];
for (var key in obj) { res.push(key); } // eslint-disable-line no-restricted-syntax
return res;
};
var propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
var getOwnPropertySymbols = Object.getOwnPropertySymbols; // eslint-disable-line id-length
// TODO: use reflect.ownkeys and filter out non-enumerables
function ownEnumerableKeys(obj) {
var res = objectKeys(obj);
// Include enumerable symbol properties.
if (getOwnPropertySymbols) {
var symbols = getOwnPropertySymbols(obj);
for (var i = 0; i < symbols.length; i++) {
if (propertyIsEnumerable.call(obj, symbols[i])) {
res.push(symbols[i]);
}
}
}
return res;
}
// TODO: use object.hasown
var hasOwnProperty = Object.prototype.hasOwnProperty || function (obj, key) {
return key in obj;
};
function isWritable(object, key) {
if (typeof gopd !== 'function') {
return true;
}
return !gopd(object, key).writable;
}
function copy(src, options) {
if (typeof src === 'object' && src !== null) {
var dst;
if (isArray(src)) {
dst = [];
} else if (isDate(src)) {
dst = new Date(src.getTime ? src.getTime() : src);
} else if (isRegExp(src)) {
dst = new RegExp(src);
} else if (isError(src)) {
dst = { message: src.message };
} else if (isBoolean(src) || isNumber(src) || isString(src)) {
dst = Object(src);
} else {
var ta = whichTypedArray(src);
if (ta) {
return taSlice(src);
} else if (Object.create && Object.getPrototypeOf) {
dst = Object.create(Object.getPrototypeOf(src));
} else if (src.constructor === Object) {
dst = {};
} else {
var proto = (src.constructor && src.constructor.prototype)
|| src.__proto__
|| {};
var T = function T() {}; // eslint-disable-line func-style, func-name-matching
T.prototype = proto;
dst = new T();
}
}
var iteratorFunction = options.includeSymbols ? ownEnumerableKeys : objectKeys;
forEach(iteratorFunction(src), function (key) {
dst[key] = src[key];
});
return dst;
}
return src;
}
/** @type {TraverseOptions} */
var emptyNull = { __proto__: null };
function walk(root, cb) {
var path = [];
var parents = [];
var alive = true;
var options = arguments.length > 2 ? arguments[2] : emptyNull;
var iteratorFunction = options.includeSymbols ? ownEnumerableKeys : objectKeys;
var immutable = !!options.immutable;
return (function walker(node_) {
var node = immutable ? copy(node_, options) : node_;
var modifiers = {};
var keepGoing = true;
var state = {
node: node,
node_: node_,
path: [].concat(path),
parent: parents[parents.length - 1],
parents: parents,
key: path[path.length - 1],
isRoot: path.length === 0,
level: path.length,
circular: null,
update: function (x, stopHere) {
if (!state.isRoot) {
state.parent.node[state.key] = x;
}
state.node = x;
if (stopHere) { keepGoing = false; }
},
delete: function (stopHere) {
delete state.parent.node[state.key];
if (stopHere) { keepGoing = false; }
},
remove: function (stopHere) {
if (isArray(state.parent.node)) {
state.parent.node.splice(state.key, 1);
} else {
delete state.parent.node[state.key];
}
if (stopHere) { keepGoing = false; }
},
keys: null,
before: function (f) { modifiers.before = f; },
after: function (f) { modifiers.after = f; },
pre: function (f) { modifiers.pre = f; },
post: function (f) { modifiers.post = f; },
stop: function () { alive = false; },
block: function () { keepGoing = false; },
};
if (!alive) { return state; }
function updateState() {
if (typeof state.node === 'object' && state.node !== null) {
if (!state.keys || state.node_ !== state.node) {
state.keys = iteratorFunction(state.node);
}
state.isLeaf = state.keys.length === 0;
for (var i = 0; i < parents.length; i++) {
if (parents[i].node_ === node_) {
state.circular = parents[i];
break; // eslint-disable-line no-restricted-syntax
}
}
} else {
state.isLeaf = true;
state.keys = null;
}
state.notLeaf = !state.isLeaf;
state.notRoot = !state.isRoot;
}
updateState();
// use return values to update if defined
var ret = cb.call(state, state.node);
if (ret !== undefined && state.update) { state.update(ret); }
if (modifiers.before) { modifiers.before.call(state, state.node); }
if (!keepGoing) { return state; }
if (
typeof state.node === 'object'
&& state.node !== null
&& !state.circular
) {
parents.push(state);
updateState();
forEach(state.keys, function (key, i) {
path.push(key);
if (modifiers.pre) { modifiers.pre.call(state, state.node[key], key); }
var child = walker(state.node[key]);
if (
immutable
&& hasOwnProperty.call(state.node, key)
&& !isWritable(state.node, key)
) {
state.node[key] = child.node;
}
child.isLast = i === state.keys.length - 1;
child.isFirst = i === 0;
if (modifiers.post) { modifiers.post.call(state, child); }
path.pop();
});
parents.pop();
}
if (modifiers.after) { modifiers.after.call(state, state.node); }
return state;
}(root)).node;
}
/** @typedef {{ immutable?: boolean, includeSymbols?: boolean }} TraverseOptions */
/**
* A traverse constructor
* @param {object} obj - the object to traverse
* @param {TraverseOptions | undefined} [options] - options for the traverse
* @constructor
*/
function Traverse(obj) {
/** @type {TraverseOptions} */
this.options = arguments.length > 1 ? arguments[1] : emptyNull;
this.value = obj;
}
/** @type {(ps: PropertyKey[]) => Traverse['value']} */
Traverse.prototype.get = function (ps) {
var node = this.value;
for (var i = 0; node && i < ps.length; i++) {
var key = ps[i];
if (
!hasOwnProperty.call(node, key)
|| (!this.options.includeSymbols && typeof key === 'symbol')
) {
return void undefined;
}
node = node[key];
}
return node;
};
/** @type {(ps: PropertyKey[]) => boolean} */
Traverse.prototype.has = function (ps) {
var node = this.value;
for (var i = 0; node && i < ps.length; i++) {
var key = ps[i];
if (!hasOwnProperty.call(node, key) || (!this.options.includeSymbols && typeof key === 'symbol')) {
return false;
}
node = node[key];
}
return true;
};
Traverse.prototype.set = function (ps, value) {
var node = this.value;
for (var i = 0; i < ps.length - 1; i++) {
var key = ps[i];
if (!hasOwnProperty.call(node, key)) { node[key] = {}; }
node = node[key];
}
node[ps[i]] = value;
return value;
};
Traverse.prototype.map = function (cb) {
return walk(this.value, cb, { __proto__: null, immutable: true, includeSymbols: !!this.options.includeSymbols });
};
Traverse.prototype.forEach = function (cb) {
this.value = walk(this.value, cb, this.options);
return this.value;
};
Traverse.prototype.reduce = function (cb, init) {
var skip = arguments.length === 1;
var acc = skip ? this.value : init;
this.forEach(function (x) {
if (!this.isRoot || !skip) {
acc = cb.call(this, acc, x);
}
});
return acc;
};
Traverse.prototype.paths = function () {
var acc = [];
this.forEach(function () {
acc.push(this.path);
});
return acc;
};
Traverse.prototype.nodes = function () {
var acc = [];
this.forEach(function () {
acc.push(this.node);
});
return acc;
};
Traverse.prototype.clone = function () {
var parents = [];
var nodes = [];
var options = this.options;
if (whichTypedArray(this.value)) {
return taSlice(this.value);
}
return (function clone(src) {
for (var i = 0; i < parents.length; i++) {
if (parents[i] === src) {
return nodes[i];
}
}
if (typeof src === 'object' && src !== null) {
var dst = copy(src, options);
parents.push(src);
nodes.push(dst);
var iteratorFunction = options.includeSymbols ? ownEnumerableKeys : objectKeys;
forEach(iteratorFunction(src), function (key) {
dst[key] = clone(src[key]);
});
parents.pop();
nodes.pop();
return dst;
}
return src;
}(this.value));
};
/** @type {(obj: object, options?: TraverseOptions) => Traverse} */
function traverse(obj) {
var options = arguments.length > 1 ? arguments[1] : emptyNull;
return new Traverse(obj, options);
}
// TODO: replace with object.assign?
forEach(ownEnumerableKeys(Traverse.prototype), function (key) {
traverse[key] = function (obj) {
var args = [].slice.call(arguments, 1);
var t = new Traverse(obj);
return t[key].apply(t, args);
};
});
module.exports = traverse;
/***/ }),
/***/ 6740:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $TypeError = __webpack_require__(1642);
var callBound = __webpack_require__(6798);
var $typedArrayBuffer = callBound('TypedArray.prototype.buffer', true);
var isTypedArray = __webpack_require__(2527);
/** @type {import('.')} */
// node <= 0.10, < 0.11.4 has a nonconfigurable own property instead of a prototype getter
module.exports = $typedArrayBuffer || function typedArrayBuffer(x) {
if (!isTypedArray(x)) {
throw new $TypeError('Not a Typed Array');
}
return x.buffer;
};
/***/ }),
/***/ 6798:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(1634);
var callBind = __webpack_require__(8388);
var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));
module.exports = function callBoundIntrinsic(name, allowMissing) {
var intrinsic = GetIntrinsic(name, !!allowMissing);
if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
return callBind(intrinsic);
}
return intrinsic;
};
/***/ }),
/***/ 8388:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var bind = __webpack_require__(7715);
var GetIntrinsic = __webpack_require__(1634);
var setFunctionLength = __webpack_require__(4521);
var $TypeError = __webpack_require__(1642);
var $apply = GetIntrinsic('%Function.prototype.apply%');
var $call = GetIntrinsic('%Function.prototype.call%');
var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
var $defineProperty = __webpack_require__(8918);
var $max = GetIntrinsic('%Math.max%');
module.exports = function callBind(originalFunction) {
if (typeof originalFunction !== 'function') {
throw new $TypeError('a function is required');
}
var func = $reflectApply(bind, $call, arguments);
return setFunctionLength(
func,
1 + $max(0, originalFunction.length - (arguments.length - 1)),
true
);
};
var applyBind = function applyBind() {
return $reflectApply(bind, $apply, arguments);
};
if ($defineProperty) {
$defineProperty(module.exports, 'apply', { value: applyBind });
} else {
module.exports.apply = applyBind;
}
/***/ }),
/***/ 9003:
/***/ (function(module) {
"use strict";
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var toStr = Object.prototype.toString;
var max = Math.max;
var funcType = '[object Function]';
var concatty = function concatty(a, b) {
var arr = [];
for (var i = 0; i < a.length; i += 1) {
arr[i] = a[i];
}
for (var j = 0; j < b.length; j += 1) {
arr[j + a.length] = b[j];
}
return arr;
};
var slicy = function slicy(arrLike, offset) {
var arr = [];
for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
arr[j] = arrLike[i];
}
return arr;
};
var joiny = function (arr, joiner) {
var str = '';
for (var i = 0; i < arr.length; i += 1) {
str += arr[i];
if (i + 1 < arr.length) {
str += joiner;
}
}
return str;
};
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slicy(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
concatty(args, arguments)
);
if (Object(result) === result) {
return result;
}
return this;
}
return target.apply(
that,
concatty(args, arguments)
);
};
var boundLength = max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs[i] = '$' + i;
}
bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
/***/ }),
/***/ 7715:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(9003);
module.exports = Function.prototype.bind || implementation;
/***/ }),
/***/ 1634:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var undefined;
var $Error = __webpack_require__(6716);
var $EvalError = __webpack_require__(6788);
var $RangeError = __webpack_require__(9204);
var $ReferenceError = __webpack_require__(9908);
var $SyntaxError = __webpack_require__(6724);
var $TypeError = __webpack_require__(1642);
var $URIError = __webpack_require__(1451);
var $Function = Function;
// eslint-disable-next-line consistent-return
var getEvalledConstructor = function (expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
} catch (e) {}
};
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () {
throw new $TypeError();
};
var ThrowTypeError = $gOPD
? (function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}())
: throwTypeError;
var hasSymbols = __webpack_require__(263)();
var hasProto = __webpack_require__(1856)();
var getProto = Object.getPrototypeOf || (
hasProto
? function (x) { return x.__proto__; } // eslint-disable-line no-proto
: null
);
var needsEval = {};
var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array);
var INTRINSICS = {
__proto__: null,
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
'%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined,
'%AsyncFromSyncIteratorPrototype%': undefined,
'%AsyncFunction%': needsEval,
'%AsyncGenerator%': needsEval,
'%AsyncGeneratorFunction%': needsEval,
'%AsyncIteratorPrototype%': needsEval,
'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,
'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,
'%Boolean%': Boolean,
'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
'%Date%': Date,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': $Error,
'%eval%': eval, // eslint-disable-line no-eval
'%EvalError%': $EvalError,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
'%Function%': $Function,
'%GeneratorFunction%': needsEval,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined,
'%JSON%': typeof JSON === 'object' ? JSON : undefined,
'%Map%': typeof Map === 'undefined' ? undefined : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()),
'%Math%': Math,
'%Number%': Number,
'%Object%': Object,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
'%RangeError%': $RangeError,
'%ReferenceError%': $ReferenceError,
'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
'%RegExp%': RegExp,
'%Set%': typeof Set === 'undefined' ? undefined : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()),
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined,
'%Symbol%': hasSymbols ? Symbol : undefined,
'%SyntaxError%': $SyntaxError,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypeError%': $TypeError,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
'%URIError%': $URIError,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
};
if (getProto) {
try {
null.error; // eslint-disable-line no-unused-expressions
} catch (e) {
// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
var errorProto = getProto(getProto(e));
INTRINSICS['%Error.prototype%'] = errorProto;
}
}
var doEval = function doEval(name) {
var value;
if (name === '%AsyncFunction%') {
value = getEvalledConstructor('async function () {}');
} else if (name === '%GeneratorFunction%') {
value = getEvalledConstructor('function* () {}');
} else if (name === '%AsyncGeneratorFunction%') {
value = getEvalledConstructor('async function* () {}');
} else if (name === '%AsyncGenerator%') {
var fn = doEval('%AsyncGeneratorFunction%');
if (fn) {
value = fn.prototype;
}
} else if (name === '%AsyncIteratorPrototype%') {
var gen = doEval('%AsyncGenerator%');
if (gen && getProto) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name] = value;
return value;
};
var LEGACY_ALIASES = {
__proto__: null,
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
'%ArrayPrototype%': ['Array', 'prototype'],
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
'%BooleanPrototype%': ['Boolean', 'prototype'],
'%DataViewPrototype%': ['DataView', 'prototype'],
'%DatePrototype%': ['Date', 'prototype'],
'%ErrorPrototype%': ['Error', 'prototype'],
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
'%FunctionPrototype%': ['Function', 'prototype'],
'%Generator%': ['GeneratorFunction', 'prototype'],
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
'%JSONParse%': ['JSON', 'parse'],
'%JSONStringify%': ['JSON', 'stringify'],
'%MapPrototype%': ['Map', 'prototype'],
'%NumberPrototype%': ['Number', 'prototype'],
'%ObjectPrototype%': ['Object', 'prototype'],
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
'%PromisePrototype%': ['Promise', 'prototype'],
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
'%Promise_all%': ['Promise', 'all'],
'%Promise_reject%': ['Promise', 'reject'],
'%Promise_resolve%': ['Promise', 'resolve'],
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
'%RegExpPrototype%': ['RegExp', 'prototype'],
'%SetPrototype%': ['Set', 'prototype'],
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
'%StringPrototype%': ['String', 'prototype'],
'%SymbolPrototype%': ['Symbol', 'prototype'],
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
'%URIErrorPrototype%': ['URIError', 'prototype'],
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
'%WeakSetPrototype%': ['WeakSet', 'prototype']
};
var bind = __webpack_require__(7715);
var hasOwn = __webpack_require__(9429);
var $concat = bind.call(Function.call, Array.prototype.concat);
var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
var $replace = bind.call(Function.call, String.prototype.replace);
var $strSlice = bind.call(Function.call, String.prototype.slice);
var $exec = bind.call(Function.call, RegExp.prototype.exec);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
var first = $strSlice(string, 0, 1);
var last = $strSlice(string, -1);
if (first === '%' && last !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
} else if (last === '%' && first !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
}
var result = [];
$replace(string, rePropName, function (match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
var intrinsicName = name;
var alias;
if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
alias = LEGACY_ALIASES[intrinsicName];
intrinsicName = '%' + alias[0] + '%';
}
if (hasOwn(INTRINSICS, intrinsicName)) {
var value = INTRINSICS[intrinsicName];
if (value === needsEval) {
value = doEval(intrinsicName);
}
if (typeof value === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return {
alias: alias,
name: intrinsicName,
value: value
};
}
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
};
module.exports = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new $TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new $TypeError('"allowMissing" argument must be a boolean');
}
if ($exec(/^%?[^%]*%?$/, name) === null) {
throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
}
var parts = stringToPath(name);
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
var intrinsicRealName = intrinsic.name;
var value = intrinsic.value;
var skipFurtherCaching = false;
var alias = intrinsic.alias;
if (alias) {
intrinsicBaseName = alias[0];
$spliceApply(parts, $concat([0, 1], alias));
}
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
var part = parts[i];
var first = $strSlice(part, 0, 1);
var last = $strSlice(part, -1);
if (
(
(first === '"' || first === "'" || first === '`')
|| (last === '"' || last === "'" || last === '`')
)
&& first !== last
) {
throw new $SyntaxError('property names with quotes must have matching quotes');
}
if (part === 'constructor' || !isOwn) {
skipFurtherCaching = true;
}
intrinsicBaseName += '.' + part;
intrinsicRealName = '%' + intrinsicBaseName + '%';
if (hasOwn(INTRINSICS, intrinsicRealName)) {
value = INTRINSICS[intrinsicRealName];
} else if (value != null) {
if (!(part in value)) {
if (!allowMissing) {
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
}
return void undefined;
}
if ($gOPD && (i + 1) >= parts.length) {
var desc = $gOPD(value, part);
isOwn = !!desc;
// By convention, when a data property is converted to an accessor
// property to emulate a data property that does not suffer from
// the override mistake, that accessor's getter is marked with
// an `originalValue` property. Here, when we detect this, we
// uphold the illusion by pretending to see that original data
// property, i.e., returning the value rather than the getter
// itself.
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
value = desc.get;
} else {
value = value[part];
}
} else {
isOwn = hasOwn(value, part);
value = value[part];
}
if (isOwn && !skipFurtherCaching) {
INTRINSICS[intrinsicRealName] = value;
}
}
}
return value;
};
/***/ }),
/***/ 263:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = __webpack_require__(9184);
module.exports = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return hasSymbolSham();
};
/***/ }),
/***/ 9184:
/***/ (function(module) {
"use strict";
/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
/***/ }),
/***/ 7046:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var forEach = __webpack_require__(4843);
var callBind = __webpack_require__(2526);
var typedArrays = __webpack_require__(4343)();
/** @typedef {Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array} TypedArray */
/** @typedef {(x: TypedArray) => number} ByteOffsetGetter */
/** @type {Object.<typeof typedArrays, ByteOffsetGetter>} */
var getters = {};
var hasProto = __webpack_require__(1856)();
var gOPD = __webpack_require__(3828);
var oDP = Object.defineProperty;
if (gOPD) {
/** @type {ByteOffsetGetter} */
var getByteOffset = function (x) {
return x.byteOffset;
};
forEach(typedArrays, function (typedArray) {
// In Safari 7, Typed Array constructors are typeof object
if (typeof __webpack_require__.g[typedArray] === 'function' || typeof __webpack_require__.g[typedArray] === 'object') {
var Proto = __webpack_require__.g[typedArray].prototype;
// @ts-expect-error TS can't guarantee the callback is invoked sync
var descriptor = gOPD(Proto, 'byteOffset');
if (!descriptor && hasProto) {
// @ts-expect-error hush, TS, every object has a dunder proto
var superProto = Proto.__proto__; // eslint-disable-line no-proto
// @ts-expect-error TS can't guarantee the callback is invoked sync
descriptor = gOPD(superProto, 'byteOffset');
}
// Opera 12.16 has a magic byteOffset data property on instances AND on Proto
if (descriptor && descriptor.get) {
getters[typedArray] = callBind(descriptor.get);
} else if (oDP) {
// this is likely an engine where instances have a magic byteOffset data property
var arr = new __webpack_require__.g[typedArray](2);
// @ts-expect-error TS can't guarantee the callback is invoked sync
descriptor = gOPD(arr, 'byteOffset');
if (descriptor && descriptor.configurable) {
oDP(arr, 'length', { value: 3 });
}
if (arr.length === 2) {
getters[typedArray] = getByteOffset;
}
}
}
});
}
/** @type {ByteOffsetGetter} */
var tryTypedArrays = function tryAllTypedArrays(value) {
/** @type {number} */ var foundOffset;
forEach(getters, /** @type {(getter: ByteOffsetGetter) => void} */ function (getter) {
if (typeof foundOffset !== 'number') {
try {
var offset = getter(value);
if (typeof offset === 'number') {
foundOffset = offset;
}
} catch (e) {}
}
});
// @ts-expect-error TS can't guarantee the callback is invoked sync
return foundOffset;
};
var isTypedArray = __webpack_require__(2527);
/** @type {import('.')} */
module.exports = function typedArrayByteOffset(value) {
if (!isTypedArray(value)) {
return false;
}
return tryTypedArrays(value);
};
/***/ }),
/***/ 2526:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var bind = __webpack_require__(1530);
var GetIntrinsic = __webpack_require__(3699);
var setFunctionLength = __webpack_require__(4521);
var $TypeError = __webpack_require__(1642);
var $apply = GetIntrinsic('%Function.prototype.apply%');
var $call = GetIntrinsic('%Function.prototype.call%');
var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
var $defineProperty = __webpack_require__(8918);
var $max = GetIntrinsic('%Math.max%');
module.exports = function callBind(originalFunction) {
if (typeof originalFunction !== 'function') {
throw new $TypeError('a function is required');
}
var func = $reflectApply(bind, $call, arguments);
return setFunctionLength(
func,
1 + $max(0, originalFunction.length - (arguments.length - 1)),
true
);
};
var applyBind = function applyBind() {
return $reflectApply(bind, $apply, arguments);
};
if ($defineProperty) {
$defineProperty(module.exports, 'apply', { value: applyBind });
} else {
module.exports.apply = applyBind;
}
/***/ }),
/***/ 1609:
/***/ (function(module) {
"use strict";
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var toStr = Object.prototype.toString;
var max = Math.max;
var funcType = '[object Function]';
var concatty = function concatty(a, b) {
var arr = [];
for (var i = 0; i < a.length; i += 1) {
arr[i] = a[i];
}
for (var j = 0; j < b.length; j += 1) {
arr[j + a.length] = b[j];
}
return arr;
};
var slicy = function slicy(arrLike, offset) {
var arr = [];
for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
arr[j] = arrLike[i];
}
return arr;
};
var joiny = function (arr, joiner) {
var str = '';
for (var i = 0; i < arr.length; i += 1) {
str += arr[i];
if (i + 1 < arr.length) {
str += joiner;
}
}
return str;
};
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slicy(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
concatty(args, arguments)
);
if (Object(result) === result) {
return result;
}
return this;
}
return target.apply(
that,
concatty(args, arguments)
);
};
var boundLength = max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs[i] = '$' + i;
}
bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
/***/ }),
/***/ 1530:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(1609);
module.exports = Function.prototype.bind || implementation;
/***/ }),
/***/ 3699:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var undefined;
var $Error = __webpack_require__(6716);
var $EvalError = __webpack_require__(6788);
var $RangeError = __webpack_require__(9204);
var $ReferenceError = __webpack_require__(9908);
var $SyntaxError = __webpack_require__(6724);
var $TypeError = __webpack_require__(1642);
var $URIError = __webpack_require__(1451);
var $Function = Function;
// eslint-disable-next-line consistent-return
var getEvalledConstructor = function (expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
} catch (e) {}
};
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () {
throw new $TypeError();
};
var ThrowTypeError = $gOPD
? (function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}())
: throwTypeError;
var hasSymbols = __webpack_require__(5162)();
var hasProto = __webpack_require__(1856)();
var getProto = Object.getPrototypeOf || (
hasProto
? function (x) { return x.__proto__; } // eslint-disable-line no-proto
: null
);
var needsEval = {};
var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array);
var INTRINSICS = {
__proto__: null,
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
'%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined,
'%AsyncFromSyncIteratorPrototype%': undefined,
'%AsyncFunction%': needsEval,
'%AsyncGenerator%': needsEval,
'%AsyncGeneratorFunction%': needsEval,
'%AsyncIteratorPrototype%': needsEval,
'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,
'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,
'%Boolean%': Boolean,
'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
'%Date%': Date,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': $Error,
'%eval%': eval, // eslint-disable-line no-eval
'%EvalError%': $EvalError,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
'%Function%': $Function,
'%GeneratorFunction%': needsEval,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined,
'%JSON%': typeof JSON === 'object' ? JSON : undefined,
'%Map%': typeof Map === 'undefined' ? undefined : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()),
'%Math%': Math,
'%Number%': Number,
'%Object%': Object,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
'%RangeError%': $RangeError,
'%ReferenceError%': $ReferenceError,
'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
'%RegExp%': RegExp,
'%Set%': typeof Set === 'undefined' ? undefined : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()),
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined,
'%Symbol%': hasSymbols ? Symbol : undefined,
'%SyntaxError%': $SyntaxError,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypeError%': $TypeError,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
'%URIError%': $URIError,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
};
if (getProto) {
try {
null.error; // eslint-disable-line no-unused-expressions
} catch (e) {
// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
var errorProto = getProto(getProto(e));
INTRINSICS['%Error.prototype%'] = errorProto;
}
}
var doEval = function doEval(name) {
var value;
if (name === '%AsyncFunction%') {
value = getEvalledConstructor('async function () {}');
} else if (name === '%GeneratorFunction%') {
value = getEvalledConstructor('function* () {}');
} else if (name === '%AsyncGeneratorFunction%') {
value = getEvalledConstructor('async function* () {}');
} else if (name === '%AsyncGenerator%') {
var fn = doEval('%AsyncGeneratorFunction%');
if (fn) {
value = fn.prototype;
}
} else if (name === '%AsyncIteratorPrototype%') {
var gen = doEval('%AsyncGenerator%');
if (gen && getProto) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name] = value;
return value;
};
var LEGACY_ALIASES = {
__proto__: null,
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
'%ArrayPrototype%': ['Array', 'prototype'],
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
'%BooleanPrototype%': ['Boolean', 'prototype'],
'%DataViewPrototype%': ['DataView', 'prototype'],
'%DatePrototype%': ['Date', 'prototype'],
'%ErrorPrototype%': ['Error', 'prototype'],
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
'%FunctionPrototype%': ['Function', 'prototype'],
'%Generator%': ['GeneratorFunction', 'prototype'],
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
'%JSONParse%': ['JSON', 'parse'],
'%JSONStringify%': ['JSON', 'stringify'],
'%MapPrototype%': ['Map', 'prototype'],
'%NumberPrototype%': ['Number', 'prototype'],
'%ObjectPrototype%': ['Object', 'prototype'],
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
'%PromisePrototype%': ['Promise', 'prototype'],
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
'%Promise_all%': ['Promise', 'all'],
'%Promise_reject%': ['Promise', 'reject'],
'%Promise_resolve%': ['Promise', 'resolve'],
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
'%RegExpPrototype%': ['RegExp', 'prototype'],
'%SetPrototype%': ['Set', 'prototype'],
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
'%StringPrototype%': ['String', 'prototype'],
'%SymbolPrototype%': ['Symbol', 'prototype'],
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
'%URIErrorPrototype%': ['URIError', 'prototype'],
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
'%WeakSetPrototype%': ['WeakSet', 'prototype']
};
var bind = __webpack_require__(1530);
var hasOwn = __webpack_require__(9429);
var $concat = bind.call(Function.call, Array.prototype.concat);
var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
var $replace = bind.call(Function.call, String.prototype.replace);
var $strSlice = bind.call(Function.call, String.prototype.slice);
var $exec = bind.call(Function.call, RegExp.prototype.exec);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
var first = $strSlice(string, 0, 1);
var last = $strSlice(string, -1);
if (first === '%' && last !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
} else if (last === '%' && first !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
}
var result = [];
$replace(string, rePropName, function (match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
var intrinsicName = name;
var alias;
if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
alias = LEGACY_ALIASES[intrinsicName];
intrinsicName = '%' + alias[0] + '%';
}
if (hasOwn(INTRINSICS, intrinsicName)) {
var value = INTRINSICS[intrinsicName];
if (value === needsEval) {
value = doEval(intrinsicName);
}
if (typeof value === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return {
alias: alias,
name: intrinsicName,
value: value
};
}
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
};
module.exports = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new $TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new $TypeError('"allowMissing" argument must be a boolean');
}
if ($exec(/^%?[^%]*%?$/, name) === null) {
throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
}
var parts = stringToPath(name);
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
var intrinsicRealName = intrinsic.name;
var value = intrinsic.value;
var skipFurtherCaching = false;
var alias = intrinsic.alias;
if (alias) {
intrinsicBaseName = alias[0];
$spliceApply(parts, $concat([0, 1], alias));
}
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
var part = parts[i];
var first = $strSlice(part, 0, 1);
var last = $strSlice(part, -1);
if (
(
(first === '"' || first === "'" || first === '`')
|| (last === '"' || last === "'" || last === '`')
)
&& first !== last
) {
throw new $SyntaxError('property names with quotes must have matching quotes');
}
if (part === 'constructor' || !isOwn) {
skipFurtherCaching = true;
}
intrinsicBaseName += '.' + part;
intrinsicRealName = '%' + intrinsicBaseName + '%';
if (hasOwn(INTRINSICS, intrinsicRealName)) {
value = INTRINSICS[intrinsicRealName];
} else if (value != null) {
if (!(part in value)) {
if (!allowMissing) {
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
}
return void undefined;
}
if ($gOPD && (i + 1) >= parts.length) {
var desc = $gOPD(value, part);
isOwn = !!desc;
// By convention, when a data property is converted to an accessor
// property to emulate a data property that does not suffer from
// the override mistake, that accessor's getter is marked with
// an `originalValue` property. Here, when we detect this, we
// uphold the illusion by pretending to see that original data
// property, i.e., returning the value rather than the getter
// itself.
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
value = desc.get;
} else {
value = value[part];
}
} else {
isOwn = hasOwn(value, part);
value = value[part];
}
if (isOwn && !skipFurtherCaching) {
INTRINSICS[intrinsicRealName] = value;
}
}
}
return value;
};
/***/ }),
/***/ 5162:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = __webpack_require__(3903);
module.exports = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return hasSymbolSham();
};
/***/ }),
/***/ 3903:
/***/ (function(module) {
"use strict";
/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
/***/ }),
/***/ 8150:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
// / <reference types="node" />
var callBind = __webpack_require__(4888);
var forEach = __webpack_require__(4843);
var gOPD = __webpack_require__(3828);
var hasProto = __webpack_require__(1856)();
var isTypedArray = __webpack_require__(2527);
var typedArrays = __webpack_require__(131);
/** @typedef {(value: import('.').TypedArray) => number} TypedArrayLengthGetter */
/** @typedef {{ [k in `$${import('.').TypedArrayName}` | '__proto__']: k extends '__proto__' ? null : TypedArrayLengthGetter }} Cache */
/** @type {Cache} */
// @ts-expect-error TS doesn't seem to have a "will eventually satisfy" type
var getters = { __proto__: null };
var oDP = Object.defineProperty;
if (gOPD) {
var getLength = /** @type {TypedArrayLengthGetter} */ function (x) {
return x.length;
};
forEach(typedArrays, /** @type {(typedArray: import('.').TypedArrayName) => void} */ function (typedArray) {
var TA = __webpack_require__.g[typedArray];
// In Safari 7, Typed Array constructors are typeof object
if (typeof TA === 'function' || typeof TA === 'object') {
var Proto = TA.prototype;
// @ts-expect-error TS doesn't narrow types inside callbacks, which is weird
var descriptor = gOPD(Proto, 'length');
if (!descriptor && hasProto) {
var superProto = Proto.__proto__; // eslint-disable-line no-proto
// @ts-expect-error TS doesn't narrow types inside callbacks, which is weird
descriptor = gOPD(superProto, 'length');
}
// Opera 12.16 has a magic length data property on instances AND on Proto
if (descriptor && descriptor.get) {
// eslint-disable-next-line no-extra-parens
getters[/** @type {`$${import('.').TypedArrayName}`} */ ('$' + typedArray)] = callBind(descriptor.get);
} else if (oDP) {
// this is likely an engine where instances have a magic length data property
var arr = new __webpack_require__.g[typedArray](2);
// @ts-expect-error TS doesn't narrow types inside callbacks, which is weird
descriptor = gOPD(arr, 'length');
if (descriptor && descriptor.configurable) {
oDP(arr, 'length', { value: 3 });
}
if (arr.length === 2) {
// eslint-disable-next-line no-extra-parens
getters[/** @type {`$${import('.').TypedArrayName}`} */ ('$' + typedArray)] = getLength;
}
}
}
});
}
/** @type {TypedArrayLengthGetter} */
var tryTypedArrays = function tryAllTypedArrays(value) {
/** @type {number} */ var foundLength;
// @ts-expect-error not sure why this won't work
forEach(getters, /** @type {(getter: TypedArrayLengthGetter) => void} */ function (getter) {
if (typeof foundLength !== 'number') {
try {
var length = getter(value);
if (typeof length === 'number') {
foundLength = length;
}
} catch (e) {}
}
});
// @ts-expect-error TS can't guarantee the above callback is invoked sync
return foundLength;
};
/** @type {import('.')} */
module.exports = function typedArrayLength(value) {
if (!isTypedArray(value)) {
return false;
}
return tryTypedArrays(value);
};
/***/ }),
/***/ 4888:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var bind = __webpack_require__(3576);
var GetIntrinsic = __webpack_require__(8031);
var setFunctionLength = __webpack_require__(4521);
var $TypeError = __webpack_require__(1642);
var $apply = GetIntrinsic('%Function.prototype.apply%');
var $call = GetIntrinsic('%Function.prototype.call%');
var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
var $defineProperty = __webpack_require__(8918);
var $max = GetIntrinsic('%Math.max%');
module.exports = function callBind(originalFunction) {
if (typeof originalFunction !== 'function') {
throw new $TypeError('a function is required');
}
var func = $reflectApply(bind, $call, arguments);
return setFunctionLength(
func,
1 + $max(0, originalFunction.length - (arguments.length - 1)),
true
);
};
var applyBind = function applyBind() {
return $reflectApply(bind, $apply, arguments);
};
if ($defineProperty) {
$defineProperty(module.exports, 'apply', { value: applyBind });
} else {
module.exports.apply = applyBind;
}
/***/ }),
/***/ 7380:
/***/ (function(module) {
"use strict";
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var toStr = Object.prototype.toString;
var max = Math.max;
var funcType = '[object Function]';
var concatty = function concatty(a, b) {
var arr = [];
for (var i = 0; i < a.length; i += 1) {
arr[i] = a[i];
}
for (var j = 0; j < b.length; j += 1) {
arr[j + a.length] = b[j];
}
return arr;
};
var slicy = function slicy(arrLike, offset) {
var arr = [];
for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
arr[j] = arrLike[i];
}
return arr;
};
var joiny = function (arr, joiner) {
var str = '';
for (var i = 0; i < arr.length; i += 1) {
str += arr[i];
if (i + 1 < arr.length) {
str += joiner;
}
}
return str;
};
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slicy(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
concatty(args, arguments)
);
if (Object(result) === result) {
return result;
}
return this;
}
return target.apply(
that,
concatty(args, arguments)
);
};
var boundLength = max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs[i] = '$' + i;
}
bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
/***/ }),
/***/ 3576:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(7380);
module.exports = Function.prototype.bind || implementation;
/***/ }),
/***/ 8031:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var undefined;
var $Error = __webpack_require__(6716);
var $EvalError = __webpack_require__(6788);
var $RangeError = __webpack_require__(9204);
var $ReferenceError = __webpack_require__(9908);
var $SyntaxError = __webpack_require__(6724);
var $TypeError = __webpack_require__(1642);
var $URIError = __webpack_require__(1451);
var $Function = Function;
// eslint-disable-next-line consistent-return
var getEvalledConstructor = function (expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
} catch (e) {}
};
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () {
throw new $TypeError();
};
var ThrowTypeError = $gOPD
? (function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}())
: throwTypeError;
var hasSymbols = __webpack_require__(307)();
var hasProto = __webpack_require__(1856)();
var getProto = Object.getPrototypeOf || (
hasProto
? function (x) { return x.__proto__; } // eslint-disable-line no-proto
: null
);
var needsEval = {};
var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array);
var INTRINSICS = {
__proto__: null,
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
'%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined,
'%AsyncFromSyncIteratorPrototype%': undefined,
'%AsyncFunction%': needsEval,
'%AsyncGenerator%': needsEval,
'%AsyncGeneratorFunction%': needsEval,
'%AsyncIteratorPrototype%': needsEval,
'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,
'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,
'%Boolean%': Boolean,
'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
'%Date%': Date,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': $Error,
'%eval%': eval, // eslint-disable-line no-eval
'%EvalError%': $EvalError,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
'%Function%': $Function,
'%GeneratorFunction%': needsEval,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined,
'%JSON%': typeof JSON === 'object' ? JSON : undefined,
'%Map%': typeof Map === 'undefined' ? undefined : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()),
'%Math%': Math,
'%Number%': Number,
'%Object%': Object,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
'%RangeError%': $RangeError,
'%ReferenceError%': $ReferenceError,
'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
'%RegExp%': RegExp,
'%Set%': typeof Set === 'undefined' ? undefined : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()),
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined,
'%Symbol%': hasSymbols ? Symbol : undefined,
'%SyntaxError%': $SyntaxError,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypeError%': $TypeError,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
'%URIError%': $URIError,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
};
if (getProto) {
try {
null.error; // eslint-disable-line no-unused-expressions
} catch (e) {
// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
var errorProto = getProto(getProto(e));
INTRINSICS['%Error.prototype%'] = errorProto;
}
}
var doEval = function doEval(name) {
var value;
if (name === '%AsyncFunction%') {
value = getEvalledConstructor('async function () {}');
} else if (name === '%GeneratorFunction%') {
value = getEvalledConstructor('function* () {}');
} else if (name === '%AsyncGeneratorFunction%') {
value = getEvalledConstructor('async function* () {}');
} else if (name === '%AsyncGenerator%') {
var fn = doEval('%AsyncGeneratorFunction%');
if (fn) {
value = fn.prototype;
}
} else if (name === '%AsyncIteratorPrototype%') {
var gen = doEval('%AsyncGenerator%');
if (gen && getProto) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name] = value;
return value;
};
var LEGACY_ALIASES = {
__proto__: null,
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
'%ArrayPrototype%': ['Array', 'prototype'],
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
'%BooleanPrototype%': ['Boolean', 'prototype'],
'%DataViewPrototype%': ['DataView', 'prototype'],
'%DatePrototype%': ['Date', 'prototype'],
'%ErrorPrototype%': ['Error', 'prototype'],
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
'%FunctionPrototype%': ['Function', 'prototype'],
'%Generator%': ['GeneratorFunction', 'prototype'],
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
'%JSONParse%': ['JSON', 'parse'],
'%JSONStringify%': ['JSON', 'stringify'],
'%MapPrototype%': ['Map', 'prototype'],
'%NumberPrototype%': ['Number', 'prototype'],
'%ObjectPrototype%': ['Object', 'prototype'],
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
'%PromisePrototype%': ['Promise', 'prototype'],
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
'%Promise_all%': ['Promise', 'all'],
'%Promise_reject%': ['Promise', 'reject'],
'%Promise_resolve%': ['Promise', 'resolve'],
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
'%RegExpPrototype%': ['RegExp', 'prototype'],
'%SetPrototype%': ['Set', 'prototype'],
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
'%StringPrototype%': ['String', 'prototype'],
'%SymbolPrototype%': ['Symbol', 'prototype'],
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
'%URIErrorPrototype%': ['URIError', 'prototype'],
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
'%WeakSetPrototype%': ['WeakSet', 'prototype']
};
var bind = __webpack_require__(3576);
var hasOwn = __webpack_require__(9429);
var $concat = bind.call(Function.call, Array.prototype.concat);
var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
var $replace = bind.call(Function.call, String.prototype.replace);
var $strSlice = bind.call(Function.call, String.prototype.slice);
var $exec = bind.call(Function.call, RegExp.prototype.exec);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
var first = $strSlice(string, 0, 1);
var last = $strSlice(string, -1);
if (first === '%' && last !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
} else if (last === '%' && first !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
}
var result = [];
$replace(string, rePropName, function (match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
var intrinsicName = name;
var alias;
if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
alias = LEGACY_ALIASES[intrinsicName];
intrinsicName = '%' + alias[0] + '%';
}
if (hasOwn(INTRINSICS, intrinsicName)) {
var value = INTRINSICS[intrinsicName];
if (value === needsEval) {
value = doEval(intrinsicName);
}
if (typeof value === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return {
alias: alias,
name: intrinsicName,
value: value
};
}
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
};
module.exports = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new $TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new $TypeError('"allowMissing" argument must be a boolean');
}
if ($exec(/^%?[^%]*%?$/, name) === null) {
throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
}
var parts = stringToPath(name);
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
var intrinsicRealName = intrinsic.name;
var value = intrinsic.value;
var skipFurtherCaching = false;
var alias = intrinsic.alias;
if (alias) {
intrinsicBaseName = alias[0];
$spliceApply(parts, $concat([0, 1], alias));
}
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
var part = parts[i];
var first = $strSlice(part, 0, 1);
var last = $strSlice(part, -1);
if (
(
(first === '"' || first === "'" || first === '`')
|| (last === '"' || last === "'" || last === '`')
)
&& first !== last
) {
throw new $SyntaxError('property names with quotes must have matching quotes');
}
if (part === 'constructor' || !isOwn) {
skipFurtherCaching = true;
}
intrinsicBaseName += '.' + part;
intrinsicRealName = '%' + intrinsicBaseName + '%';
if (hasOwn(INTRINSICS, intrinsicRealName)) {
value = INTRINSICS[intrinsicRealName];
} else if (value != null) {
if (!(part in value)) {
if (!allowMissing) {
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
}
return void undefined;
}
if ($gOPD && (i + 1) >= parts.length) {
var desc = $gOPD(value, part);
isOwn = !!desc;
// By convention, when a data property is converted to an accessor
// property to emulate a data property that does not suffer from
// the override mistake, that accessor's getter is marked with
// an `originalValue` property. Here, when we detect this, we
// uphold the illusion by pretending to see that original data
// property, i.e., returning the value rather than the getter
// itself.
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
value = desc.get;
} else {
value = value[part];
}
} else {
isOwn = hasOwn(value, part);
value = value[part];
}
if (isOwn && !skipFurtherCaching) {
INTRINSICS[intrinsicRealName] = value;
}
}
}
return value;
};
/***/ }),
/***/ 307:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = __webpack_require__(1766);
module.exports = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return hasSymbolSham();
};
/***/ }),
/***/ 1766:
/***/ (function(module) {
"use strict";
/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
/***/ }),
/***/ 4073:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $TypeError = __webpack_require__(1642);
var Get = __webpack_require__(3675);
var GetValueFromBuffer = __webpack_require__(9661);
var IsDetachedBuffer = __webpack_require__(1320);
var max = __webpack_require__(1367);
var min = __webpack_require__(2967);
var Set = __webpack_require__(8055);
var SetValueInBuffer = __webpack_require__(3383);
var ToIntegerOrInfinity = __webpack_require__(2897);
var ToString = __webpack_require__(7249);
var TypedArrayElementSize = __webpack_require__(9149);
var TypedArrayElementType = __webpack_require__(1586);
var TypedArraySpeciesCreate = __webpack_require__(817);
var ValidateTypedArray = __webpack_require__(3842);
var typedArrayBuffer = __webpack_require__(6740);
var typedArrayByteOffset = __webpack_require__(7046);
// https://tc39.es/ecma262/#sec-%typedarray%.prototype.slice
module.exports = function slice(start, end) {
var O = this; // step 1
ValidateTypedArray(O, 'SEQ-CST'); // step 2
// 3. Let len be O.[[ArrayLength]].
var len = O.length; // steps 3
var relativeStart = ToIntegerOrInfinity(start); // step 4
var k;
if (relativeStart === -Infinity) {
k = 0; // step 5
} else if (relativeStart < 0) {
k = max(len + relativeStart, 0); // step 6
} else {
k = min(relativeStart, len); // step 7
}
var relativeEnd = typeof end === 'undefined' ? len : ToIntegerOrInfinity(end); // step 8
var final;
if (relativeEnd === -Infinity) {
final = 0; // step 9
} else if (relativeEnd < 0) {
final = max(len + relativeEnd, 0); // step 10
} else {
final = min(relativeEnd, len); // step 11
}
var count = max(final - k, 0); // step 12
var A = TypedArraySpeciesCreate(O, [count]); // step 13
if (count > 0) { // step 14
if (IsDetachedBuffer(typedArrayBuffer(O))) {
throw new $TypeError('Cannot use a Typed Array with an underlying ArrayBuffer that is detached'); // step 14.a
}
var srcType = TypedArrayElementType(O); // step 14.b
var targetType = TypedArrayElementType(A); // step 14.c
if (srcType === targetType) { // step 14.d
// 1. NOTE: The transfer must be performed in a manner that preserves the bit-level encoding of the source data.
var srcBuffer = typedArrayBuffer(O); // step 14.d.ii
var targetBuffer = typedArrayBuffer(A); // step 14.d.iii
var elementSize = TypedArrayElementSize(O); // step 14.d.iv
var srcByteOffset = typedArrayByteOffset(O); // step 14.d.v
var srcByteIndex = (k * elementSize) + srcByteOffset; // step 14.d.vi
var targetByteIndex = typedArrayByteOffset(A); // step 14.d.vii
var limit = targetByteIndex + (count * elementSize); // step 14.d.viii
while (targetByteIndex < limit) { // step 14.d.ix
var value = GetValueFromBuffer(srcBuffer, srcByteIndex, 'UINT8', true, 'UNORDERED'); // step 14.d.ix.1
SetValueInBuffer(targetBuffer, targetByteIndex, 'UINT8', value, true, 'UNORDERED'); // step 14.d.ix.2
srcByteIndex += 1; // step 14.d.ix.3
targetByteIndex += 1; // step 14.d.ix.4
}
} else { // step 14.e
var n = 0; // step 14.e.i
while (k < final) { // step 14.e.ii
var Pk = ToString(k); // step 14.e.ii.1
var kValue = Get(O, Pk); // step 14.e.ii.2
Set(A, ToString(n), kValue, true); // step 14.e.ii.3
k += 1; // step 14.e.ii.4
n += 1; // step 14.e.ii.5
}
}
}
return A; // step 15
};
/***/ }),
/***/ 1140:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var define = __webpack_require__(6776);
var callBind = __webpack_require__(8374);
var implementation = __webpack_require__(4073);
var getPolyfill = __webpack_require__(5046);
var shim = __webpack_require__(8564);
var bound = callBind(getPolyfill());
define(bound, {
getPolyfill: getPolyfill,
implementation: implementation,
shim: shim
});
module.exports = bound;
/***/ }),
/***/ 1154:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var callBind = __webpack_require__(8374);
var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));
module.exports = function callBoundIntrinsic(name, allowMissing) {
var intrinsic = GetIntrinsic(name, !!allowMissing);
if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
return callBind(intrinsic);
}
return intrinsic;
};
/***/ }),
/***/ 8374:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var bind = __webpack_require__(8474);
var GetIntrinsic = __webpack_require__(682);
var setFunctionLength = __webpack_require__(4521);
var $TypeError = __webpack_require__(1642);
var $apply = GetIntrinsic('%Function.prototype.apply%');
var $call = GetIntrinsic('%Function.prototype.call%');
var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
var $defineProperty = __webpack_require__(8918);
var $max = GetIntrinsic('%Math.max%');
module.exports = function callBind(originalFunction) {
if (typeof originalFunction !== 'function') {
throw new $TypeError('a function is required');
}
var func = $reflectApply(bind, $call, arguments);
return setFunctionLength(
func,
1 + $max(0, originalFunction.length - (arguments.length - 1)),
true
);
};
var applyBind = function applyBind() {
return $reflectApply(bind, $apply, arguments);
};
if ($defineProperty) {
$defineProperty(module.exports, 'apply', { value: applyBind });
} else {
module.exports.apply = applyBind;
}
/***/ }),
/***/ 6776:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var keys = __webpack_require__(806);
var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';
var toStr = Object.prototype.toString;
var concat = Array.prototype.concat;
var defineDataProperty = __webpack_require__(2656);
var isFunction = function (fn) {
return typeof fn === 'function' && toStr.call(fn) === '[object Function]';
};
var supportsDescriptors = __webpack_require__(8198)();
var defineProperty = function (object, name, value, predicate) {
if (name in object) {
if (predicate === true) {
if (object[name] === value) {
return;
}
} else if (!isFunction(predicate) || !predicate()) {
return;
}
}
if (supportsDescriptors) {
defineDataProperty(object, name, value, true);
} else {
defineDataProperty(object, name, value);
}
};
var defineProperties = function (object, map) {
var predicates = arguments.length > 2 ? arguments[2] : {};
var props = keys(map);
if (hasSymbols) {
props = concat.call(props, Object.getOwnPropertySymbols(map));
}
for (var i = 0; i < props.length; i += 1) {
defineProperty(object, props[i], map[props[i]], predicates[props[i]]);
}
};
defineProperties.supportsDescriptors = !!supportsDescriptors;
module.exports = defineProperties;
/***/ }),
/***/ 2855:
/***/ (function(module) {
"use strict";
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var toStr = Object.prototype.toString;
var max = Math.max;
var funcType = '[object Function]';
var concatty = function concatty(a, b) {
var arr = [];
for (var i = 0; i < a.length; i += 1) {
arr[i] = a[i];
}
for (var j = 0; j < b.length; j += 1) {
arr[j + a.length] = b[j];
}
return arr;
};
var slicy = function slicy(arrLike, offset) {
var arr = [];
for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
arr[j] = arrLike[i];
}
return arr;
};
var joiny = function (arr, joiner) {
var str = '';
for (var i = 0; i < arr.length; i += 1) {
str += arr[i];
if (i + 1 < arr.length) {
str += joiner;
}
}
return str;
};
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slicy(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
concatty(args, arguments)
);
if (Object(result) === result) {
return result;
}
return this;
}
return target.apply(
that,
concatty(args, arguments)
);
};
var boundLength = max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs[i] = '$' + i;
}
bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
/***/ }),
/***/ 8474:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(2855);
module.exports = Function.prototype.bind || implementation;
/***/ }),
/***/ 682:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var undefined;
var $Error = __webpack_require__(6716);
var $EvalError = __webpack_require__(6788);
var $RangeError = __webpack_require__(9204);
var $ReferenceError = __webpack_require__(9908);
var $SyntaxError = __webpack_require__(6724);
var $TypeError = __webpack_require__(1642);
var $URIError = __webpack_require__(1451);
var $Function = Function;
// eslint-disable-next-line consistent-return
var getEvalledConstructor = function (expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
} catch (e) {}
};
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () {
throw new $TypeError();
};
var ThrowTypeError = $gOPD
? (function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}())
: throwTypeError;
var hasSymbols = __webpack_require__(5314)();
var hasProto = __webpack_require__(1856)();
var getProto = Object.getPrototypeOf || (
hasProto
? function (x) { return x.__proto__; } // eslint-disable-line no-proto
: null
);
var needsEval = {};
var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array);
var INTRINSICS = {
__proto__: null,
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
'%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined,
'%AsyncFromSyncIteratorPrototype%': undefined,
'%AsyncFunction%': needsEval,
'%AsyncGenerator%': needsEval,
'%AsyncGeneratorFunction%': needsEval,
'%AsyncIteratorPrototype%': needsEval,
'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,
'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,
'%Boolean%': Boolean,
'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
'%Date%': Date,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': $Error,
'%eval%': eval, // eslint-disable-line no-eval
'%EvalError%': $EvalError,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
'%Function%': $Function,
'%GeneratorFunction%': needsEval,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined,
'%JSON%': typeof JSON === 'object' ? JSON : undefined,
'%Map%': typeof Map === 'undefined' ? undefined : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()),
'%Math%': Math,
'%Number%': Number,
'%Object%': Object,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
'%RangeError%': $RangeError,
'%ReferenceError%': $ReferenceError,
'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
'%RegExp%': RegExp,
'%Set%': typeof Set === 'undefined' ? undefined : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()),
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined,
'%Symbol%': hasSymbols ? Symbol : undefined,
'%SyntaxError%': $SyntaxError,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypeError%': $TypeError,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
'%URIError%': $URIError,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
};
if (getProto) {
try {
null.error; // eslint-disable-line no-unused-expressions
} catch (e) {
// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
var errorProto = getProto(getProto(e));
INTRINSICS['%Error.prototype%'] = errorProto;
}
}
var doEval = function doEval(name) {
var value;
if (name === '%AsyncFunction%') {
value = getEvalledConstructor('async function () {}');
} else if (name === '%GeneratorFunction%') {
value = getEvalledConstructor('function* () {}');
} else if (name === '%AsyncGeneratorFunction%') {
value = getEvalledConstructor('async function* () {}');
} else if (name === '%AsyncGenerator%') {
var fn = doEval('%AsyncGeneratorFunction%');
if (fn) {
value = fn.prototype;
}
} else if (name === '%AsyncIteratorPrototype%') {
var gen = doEval('%AsyncGenerator%');
if (gen && getProto) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name] = value;
return value;
};
var LEGACY_ALIASES = {
__proto__: null,
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
'%ArrayPrototype%': ['Array', 'prototype'],
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
'%BooleanPrototype%': ['Boolean', 'prototype'],
'%DataViewPrototype%': ['DataView', 'prototype'],
'%DatePrototype%': ['Date', 'prototype'],
'%ErrorPrototype%': ['Error', 'prototype'],
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
'%FunctionPrototype%': ['Function', 'prototype'],
'%Generator%': ['GeneratorFunction', 'prototype'],
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
'%JSONParse%': ['JSON', 'parse'],
'%JSONStringify%': ['JSON', 'stringify'],
'%MapPrototype%': ['Map', 'prototype'],
'%NumberPrototype%': ['Number', 'prototype'],
'%ObjectPrototype%': ['Object', 'prototype'],
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
'%PromisePrototype%': ['Promise', 'prototype'],
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
'%Promise_all%': ['Promise', 'all'],
'%Promise_reject%': ['Promise', 'reject'],
'%Promise_resolve%': ['Promise', 'resolve'],
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
'%RegExpPrototype%': ['RegExp', 'prototype'],
'%SetPrototype%': ['Set', 'prototype'],
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
'%StringPrototype%': ['String', 'prototype'],
'%SymbolPrototype%': ['Symbol', 'prototype'],
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
'%URIErrorPrototype%': ['URIError', 'prototype'],
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
'%WeakSetPrototype%': ['WeakSet', 'prototype']
};
var bind = __webpack_require__(8474);
var hasOwn = __webpack_require__(9429);
var $concat = bind.call(Function.call, Array.prototype.concat);
var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
var $replace = bind.call(Function.call, String.prototype.replace);
var $strSlice = bind.call(Function.call, String.prototype.slice);
var $exec = bind.call(Function.call, RegExp.prototype.exec);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
var first = $strSlice(string, 0, 1);
var last = $strSlice(string, -1);
if (first === '%' && last !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
} else if (last === '%' && first !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
}
var result = [];
$replace(string, rePropName, function (match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
var intrinsicName = name;
var alias;
if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
alias = LEGACY_ALIASES[intrinsicName];
intrinsicName = '%' + alias[0] + '%';
}
if (hasOwn(INTRINSICS, intrinsicName)) {
var value = INTRINSICS[intrinsicName];
if (value === needsEval) {
value = doEval(intrinsicName);
}
if (typeof value === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return {
alias: alias,
name: intrinsicName,
value: value
};
}
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
};
module.exports = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new $TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new $TypeError('"allowMissing" argument must be a boolean');
}
if ($exec(/^%?[^%]*%?$/, name) === null) {
throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
}
var parts = stringToPath(name);
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
var intrinsicRealName = intrinsic.name;
var value = intrinsic.value;
var skipFurtherCaching = false;
var alias = intrinsic.alias;
if (alias) {
intrinsicBaseName = alias[0];
$spliceApply(parts, $concat([0, 1], alias));
}
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
var part = parts[i];
var first = $strSlice(part, 0, 1);
var last = $strSlice(part, -1);
if (
(
(first === '"' || first === "'" || first === '`')
|| (last === '"' || last === "'" || last === '`')
)
&& first !== last
) {
throw new $SyntaxError('property names with quotes must have matching quotes');
}
if (part === 'constructor' || !isOwn) {
skipFurtherCaching = true;
}
intrinsicBaseName += '.' + part;
intrinsicRealName = '%' + intrinsicBaseName + '%';
if (hasOwn(INTRINSICS, intrinsicRealName)) {
value = INTRINSICS[intrinsicRealName];
} else if (value != null) {
if (!(part in value)) {
if (!allowMissing) {
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
}
return void undefined;
}
if ($gOPD && (i + 1) >= parts.length) {
var desc = $gOPD(value, part);
isOwn = !!desc;
// By convention, when a data property is converted to an accessor
// property to emulate a data property that does not suffer from
// the override mistake, that accessor's getter is marked with
// an `originalValue` property. Here, when we detect this, we
// uphold the illusion by pretending to see that original data
// property, i.e., returning the value rather than the getter
// itself.
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
value = desc.get;
} else {
value = value[part];
}
} else {
isOwn = hasOwn(value, part);
value = value[part];
}
if (isOwn && !skipFurtherCaching) {
INTRINSICS[intrinsicRealName] = value;
}
}
}
return value;
};
/***/ }),
/***/ 5314:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = __webpack_require__(6188);
module.exports = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return hasSymbolSham();
};
/***/ }),
/***/ 6188:
/***/ (function(module) {
"use strict";
/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
/***/ }),
/***/ 6841:
/***/ (function(module) {
"use strict";
var fnToStr = Function.prototype.toString;
var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply;
var badArrayLike;
var isCallableMarker;
if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') {
try {
badArrayLike = Object.defineProperty({}, 'length', {
get: function () {
throw isCallableMarker;
}
});
isCallableMarker = {};
// eslint-disable-next-line no-throw-literal
reflectApply(function () { throw 42; }, null, badArrayLike);
} catch (_) {
if (_ !== isCallableMarker) {
reflectApply = null;
}
}
} else {
reflectApply = null;
}
var constructorRegex = /^\s*class\b/;
var isES6ClassFn = function isES6ClassFunction(value) {
try {
var fnStr = fnToStr.call(value);
return constructorRegex.test(fnStr);
} catch (e) {
return false; // not a function
}
};
var tryFunctionObject = function tryFunctionToStr(value) {
try {
if (isES6ClassFn(value)) { return false; }
fnToStr.call(value);
return true;
} catch (e) {
return false;
}
};
var toStr = Object.prototype.toString;
var objectClass = '[object Object]';
var fnClass = '[object Function]';
var genClass = '[object GeneratorFunction]';
var ddaClass = '[object HTMLAllCollection]'; // IE 11
var ddaClass2 = '[object HTML document.all class]';
var ddaClass3 = '[object HTMLCollection]'; // IE 9-10
var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag; // better: use `has-tostringtag`
var isIE68 = !(0 in [,]); // eslint-disable-line no-sparse-arrays, comma-spacing
var isDDA = function isDocumentDotAll() { return false; };
if (typeof document === 'object') {
// Firefox 3 canonicalizes DDA to undefined when it's not accessed directly
var all = document.all;
if (toStr.call(all) === toStr.call(document.all)) {
isDDA = function isDocumentDotAll(value) {
/* globals document: false */
// in IE 6-8, typeof document.all is "object" and it's truthy
if ((isIE68 || !value) && (typeof value === 'undefined' || typeof value === 'object')) {
try {
var str = toStr.call(value);
return (
str === ddaClass
|| str === ddaClass2
|| str === ddaClass3 // opera 12.16
|| str === objectClass // IE 6-8
) && value('') == null; // eslint-disable-line eqeqeq
} catch (e) { /**/ }
}
return false;
};
}
}
module.exports = reflectApply
? function isCallable(value) {
if (isDDA(value)) { return true; }
if (!value) { return false; }
if (typeof value !== 'function' && typeof value !== 'object') { return false; }
try {
reflectApply(value, null, badArrayLike);
} catch (e) {
if (e !== isCallableMarker) { return false; }
}
return !isES6ClassFn(value) && tryFunctionObject(value);
}
: function isCallable(value) {
if (isDDA(value)) { return true; }
if (!value) { return false; }
if (typeof value !== 'function' && typeof value !== 'object') { return false; }
if (hasToStringTag) { return tryFunctionObject(value); }
if (isES6ClassFn(value)) { return false; }
var strClass = toStr.call(value);
if (strClass !== fnClass && strClass !== genClass && !(/^\[object HTML/).test(strClass)) { return false; }
return tryFunctionObject(value);
};
/***/ }),
/***/ 5726:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var hasMap = typeof Map === 'function' && Map.prototype;
var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;
var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;
var mapForEach = hasMap && Map.prototype.forEach;
var hasSet = typeof Set === 'function' && Set.prototype;
var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null;
var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null;
var setForEach = hasSet && Set.prototype.forEach;
var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype;
var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null;
var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype;
var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;
var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype;
var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null;
var booleanValueOf = Boolean.prototype.valueOf;
var objectToString = Object.prototype.toString;
var functionToString = Function.prototype.toString;
var $match = String.prototype.match;
var $slice = String.prototype.slice;
var $replace = String.prototype.replace;
var $toUpperCase = String.prototype.toUpperCase;
var $toLowerCase = String.prototype.toLowerCase;
var $test = RegExp.prototype.test;
var $concat = Array.prototype.concat;
var $join = Array.prototype.join;
var $arrSlice = Array.prototype.slice;
var $floor = Math.floor;
var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null;
var gOPS = Object.getOwnPropertySymbols;
var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null;
var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object';
// ie, `has-tostringtag/shams
var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol')
? Symbol.toStringTag
: null;
var isEnumerable = Object.prototype.propertyIsEnumerable;
var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || (
[].__proto__ === Array.prototype // eslint-disable-line no-proto
? function (O) {
return O.__proto__; // eslint-disable-line no-proto
}
: null
);
function addNumericSeparator(num, str) {
if (
num === Infinity
|| num === -Infinity
|| num !== num
|| (num && num > -1000 && num < 1000)
|| $test.call(/e/, str)
) {
return str;
}
var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;
if (typeof num === 'number') {
var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num)
if (int !== num) {
var intStr = String(int);
var dec = $slice.call(str, intStr.length + 1);
return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, '');
}
}
return $replace.call(str, sepRegex, '$&_');
}
var utilInspect = __webpack_require__(5794);
var inspectCustom = utilInspect.custom;
var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null;
module.exports = function inspect_(obj, options, depth, seen) {
var opts = options || {};
if (has(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) {
throw new TypeError('option "quoteStyle" must be "single" or "double"');
}
if (
has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number'
? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity
: opts.maxStringLength !== null
)
) {
throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');
}
var customInspect = has(opts, 'customInspect') ? opts.customInspect : true;
if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') {
throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`');
}
if (
has(opts, 'indent')
&& opts.indent !== null
&& opts.indent !== '\t'
&& !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)
) {
throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');
}
if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') {
throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');
}
var numericSeparator = opts.numericSeparator;
if (typeof obj === 'undefined') {
return 'undefined';
}
if (obj === null) {
return 'null';
}
if (typeof obj === 'boolean') {
return obj ? 'true' : 'false';
}
if (typeof obj === 'string') {
return inspectString(obj, opts);
}
if (typeof obj === 'number') {
if (obj === 0) {
return Infinity / obj > 0 ? '0' : '-0';
}
var str = String(obj);
return numericSeparator ? addNumericSeparator(obj, str) : str;
}
if (typeof obj === 'bigint') {
var bigIntStr = String(obj) + 'n';
return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr;
}
var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth;
if (typeof depth === 'undefined') { depth = 0; }
if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') {
return isArray(obj) ? '[Array]' : '[Object]';
}
var indent = getIndent(opts, depth);
if (typeof seen === 'undefined') {
seen = [];
} else if (indexOf(seen, obj) >= 0) {
return '[Circular]';
}
function inspect(value, from, noIndent) {
if (from) {
seen = $arrSlice.call(seen);
seen.push(from);
}
if (noIndent) {
var newOpts = {
depth: opts.depth
};
if (has(opts, 'quoteStyle')) {
newOpts.quoteStyle = opts.quoteStyle;
}
return inspect_(value, newOpts, depth + 1, seen);
}
return inspect_(value, opts, depth + 1, seen);
}
if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable
var name = nameOf(obj);
var keys = arrObjKeys(obj, inspect);
return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : '');
}
if (isSymbol(obj)) {
var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj);
return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString;
}
if (isElement(obj)) {
var s = '<' + $toLowerCase.call(String(obj.nodeName));
var attrs = obj.attributes || [];
for (var i = 0; i < attrs.length; i++) {
s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts);
}
s += '>';
if (obj.childNodes && obj.childNodes.length) { s += '...'; }
s += '</' + $toLowerCase.call(String(obj.nodeName)) + '>';
return s;
}
if (isArray(obj)) {
if (obj.length === 0) { return '[]'; }
var xs = arrObjKeys(obj, inspect);
if (indent && !singleLineValues(xs)) {
return '[' + indentedJoin(xs, indent) + ']';
}
return '[ ' + $join.call(xs, ', ') + ' ]';
}
if (isError(obj)) {
var parts = arrObjKeys(obj, inspect);
if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) {
return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }';
}
if (parts.length === 0) { return '[' + String(obj) + ']'; }
return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }';
}
if (typeof obj === 'object' && customInspect) {
if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) {
return utilInspect(obj, { depth: maxDepth - depth });
} else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') {
return obj.inspect();
}
}
if (isMap(obj)) {
var mapParts = [];
if (mapForEach) {
mapForEach.call(obj, function (value, key) {
mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj));
});
}
return collectionOf('Map', mapSize.call(obj), mapParts, indent);
}
if (isSet(obj)) {
var setParts = [];
if (setForEach) {
setForEach.call(obj, function (value) {
setParts.push(inspect(value, obj));
});
}
return collectionOf('Set', setSize.call(obj), setParts, indent);
}
if (isWeakMap(obj)) {
return weakCollectionOf('WeakMap');
}
if (isWeakSet(obj)) {
return weakCollectionOf('WeakSet');
}
if (isWeakRef(obj)) {
return weakCollectionOf('WeakRef');
}
if (isNumber(obj)) {
return markBoxed(inspect(Number(obj)));
}
if (isBigInt(obj)) {
return markBoxed(inspect(bigIntValueOf.call(obj)));
}
if (isBoolean(obj)) {
return markBoxed(booleanValueOf.call(obj));
}
if (isString(obj)) {
return markBoxed(inspect(String(obj)));
}
// note: in IE 8, sometimes `global !== window` but both are the prototypes of each other
/* eslint-env browser */
if (typeof window !== 'undefined' && obj === window) {
return '{ [object Window] }';
}
if (
(typeof globalThis !== 'undefined' && obj === globalThis)
|| (typeof __webpack_require__.g !== 'undefined' && obj === __webpack_require__.g)
) {
return '{ [object globalThis] }';
}
if (!isDate(obj) && !isRegExp(obj)) {
var ys = arrObjKeys(obj, inspect);
var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object;
var protoTag = obj instanceof Object ? '' : 'null prototype';
var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : '';
var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : '';
var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : '');
if (ys.length === 0) { return tag + '{}'; }
if (indent) {
return tag + '{' + indentedJoin(ys, indent) + '}';
}
return tag + '{ ' + $join.call(ys, ', ') + ' }';
}
return String(obj);
};
function wrapQuotes(s, defaultStyle, opts) {
var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'";
return quoteChar + s + quoteChar;
}
function quote(s) {
return $replace.call(String(s), /"/g, '"');
}
function isArray(obj) { return toStr(obj) === '[object Array]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isDate(obj) { return toStr(obj) === '[object Date]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isRegExp(obj) { return toStr(obj) === '[object RegExp]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isError(obj) { return toStr(obj) === '[object Error]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isString(obj) { return toStr(obj) === '[object String]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isNumber(obj) { return toStr(obj) === '[object Number]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives
function isSymbol(obj) {
if (hasShammedSymbols) {
return obj && typeof obj === 'object' && obj instanceof Symbol;
}
if (typeof obj === 'symbol') {
return true;
}
if (!obj || typeof obj !== 'object' || !symToString) {
return false;
}
try {
symToString.call(obj);
return true;
} catch (e) {}
return false;
}
function isBigInt(obj) {
if (!obj || typeof obj !== 'object' || !bigIntValueOf) {
return false;
}
try {
bigIntValueOf.call(obj);
return true;
} catch (e) {}
return false;
}
var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; };
function has(obj, key) {
return hasOwn.call(obj, key);
}
function toStr(obj) {
return objectToString.call(obj);
}
function nameOf(f) {
if (f.name) { return f.name; }
var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/);
if (m) { return m[1]; }
return null;
}
function indexOf(xs, x) {
if (xs.indexOf) { return xs.indexOf(x); }
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) { return i; }
}
return -1;
}
function isMap(x) {
if (!mapSize || !x || typeof x !== 'object') {
return false;
}
try {
mapSize.call(x);
try {
setSize.call(x);
} catch (s) {
return true;
}
return x instanceof Map; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isWeakMap(x) {
if (!weakMapHas || !x || typeof x !== 'object') {
return false;
}
try {
weakMapHas.call(x, weakMapHas);
try {
weakSetHas.call(x, weakSetHas);
} catch (s) {
return true;
}
return x instanceof WeakMap; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isWeakRef(x) {
if (!weakRefDeref || !x || typeof x !== 'object') {
return false;
}
try {
weakRefDeref.call(x);
return true;
} catch (e) {}
return false;
}
function isSet(x) {
if (!setSize || !x || typeof x !== 'object') {
return false;
}
try {
setSize.call(x);
try {
mapSize.call(x);
} catch (m) {
return true;
}
return x instanceof Set; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isWeakSet(x) {
if (!weakSetHas || !x || typeof x !== 'object') {
return false;
}
try {
weakSetHas.call(x, weakSetHas);
try {
weakMapHas.call(x, weakMapHas);
} catch (s) {
return true;
}
return x instanceof WeakSet; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isElement(x) {
if (!x || typeof x !== 'object') { return false; }
if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) {
return true;
}
return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function';
}
function inspectString(str, opts) {
if (str.length > opts.maxStringLength) {
var remaining = str.length - opts.maxStringLength;
var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : '');
return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer;
}
// eslint-disable-next-line no-control-regex
var s = $replace.call($replace.call(str, /(['\\])/g, '\\$1'), /[\x00-\x1f]/g, lowbyte);
return wrapQuotes(s, 'single', opts);
}
function lowbyte(c) {
var n = c.charCodeAt(0);
var x = {
8: 'b',
9: 't',
10: 'n',
12: 'f',
13: 'r'
}[n];
if (x) { return '\\' + x; }
return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16));
}
function markBoxed(str) {
return 'Object(' + str + ')';
}
function weakCollectionOf(type) {
return type + ' { ? }';
}
function collectionOf(type, size, entries, indent) {
var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', ');
return type + ' (' + size + ') {' + joinedEntries + '}';
}
function singleLineValues(xs) {
for (var i = 0; i < xs.length; i++) {
if (indexOf(xs[i], '\n') >= 0) {
return false;
}
}
return true;
}
function getIndent(opts, depth) {
var baseIndent;
if (opts.indent === '\t') {
baseIndent = '\t';
} else if (typeof opts.indent === 'number' && opts.indent > 0) {
baseIndent = $join.call(Array(opts.indent + 1), ' ');
} else {
return null;
}
return {
base: baseIndent,
prev: $join.call(Array(depth + 1), baseIndent)
};
}
function indentedJoin(xs, indent) {
if (xs.length === 0) { return ''; }
var lineJoiner = '\n' + indent.prev + indent.base;
return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev;
}
function arrObjKeys(obj, inspect) {
var isArr = isArray(obj);
var xs = [];
if (isArr) {
xs.length = obj.length;
for (var i = 0; i < obj.length; i++) {
xs[i] = has(obj, i) ? inspect(obj[i], obj) : '';
}
}
var syms = typeof gOPS === 'function' ? gOPS(obj) : [];
var symMap;
if (hasShammedSymbols) {
symMap = {};
for (var k = 0; k < syms.length; k++) {
symMap['$' + syms[k]] = syms[k];
}
}
for (var key in obj) { // eslint-disable-line no-restricted-syntax
if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue
if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue
if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) {
// this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section
continue; // eslint-disable-line no-restricted-syntax, no-continue
} else if ($test.call(/[^\w$]/, key)) {
xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj));
} else {
xs.push(key + ': ' + inspect(obj[key], obj));
}
}
if (typeof gOPS === 'function') {
for (var j = 0; j < syms.length; j++) {
if (isEnumerable.call(obj, syms[j])) {
xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj));
}
}
}
return xs;
}
/***/ }),
/***/ 5046:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(4073);
module.exports = function getPolyfill() {
return (typeof Uint8Array === 'function' && Uint8Array.prototype.slice) || implementation;
};
/***/ }),
/***/ 8564:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var define = __webpack_require__(6776);
var getProto = __webpack_require__(9495);
var getPolyfill = __webpack_require__(5046);
module.exports = function shimTypedArraySlice() {
if (typeof Uint8Array === 'function') {
var polyfill = getPolyfill();
var proto = getProto(Uint8Array.prototype);
define(
proto,
{ slice: polyfill },
{ slice: function () { return proto.slice !== polyfill; } }
);
}
return polyfill;
};
/***/ }),
/***/ 4010:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var forEach = __webpack_require__(4843);
var availableTypedArrays = __webpack_require__(4343);
var callBind = __webpack_require__(4899);
var callBound = __webpack_require__(7120);
var gOPD = __webpack_require__(3828);
/** @type {(O: object) => string} */
var $toString = callBound('Object.prototype.toString');
var hasToStringTag = __webpack_require__(4111)();
var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis;
var typedArrays = availableTypedArrays();
var $slice = callBound('String.prototype.slice');
var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof');
/** @type {<T = unknown>(array: readonly T[], value: unknown) => number} */
var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) {
for (var i = 0; i < array.length; i += 1) {
if (array[i] === value) {
return i;
}
}
return -1;
};
/** @typedef {(receiver: import('.').TypedArray) => string | typeof Uint8Array.prototype.slice.call | typeof Uint8Array.prototype.set.call} Getter */
/** @type {{ [k in `\$${import('.').TypedArrayName}`]?: Getter } & { __proto__: null }} */
var cache = { __proto__: null };
if (hasToStringTag && gOPD && getPrototypeOf) {
forEach(typedArrays, function (typedArray) {
var arr = new g[typedArray]();
if (Symbol.toStringTag in arr) {
var proto = getPrototypeOf(arr);
// @ts-expect-error TS won't narrow inside a closure
var descriptor = gOPD(proto, Symbol.toStringTag);
if (!descriptor) {
var superProto = getPrototypeOf(proto);
// @ts-expect-error TS won't narrow inside a closure
descriptor = gOPD(superProto, Symbol.toStringTag);
}
// @ts-expect-error TODO: fix
cache['$' + typedArray] = callBind(descriptor.get);
}
});
} else {
forEach(typedArrays, function (typedArray) {
var arr = new g[typedArray]();
var fn = arr.slice || arr.set;
if (fn) {
// @ts-expect-error TODO: fix
cache['$' + typedArray] = callBind(fn);
}
});
}
/** @type {(value: object) => false | import('.').TypedArrayName} */
var tryTypedArrays = function tryAllTypedArrays(value) {
/** @type {ReturnType<typeof tryAllTypedArrays>} */ var found = false;
forEach(
// eslint-disable-next-line no-extra-parens
/** @type {Record<`\$${TypedArrayName}`, Getter>} */ /** @type {any} */ (cache),
/** @type {(getter: Getter, name: `\$${import('.').TypedArrayName}`) => void} */
function (getter, typedArray) {
if (!found) {
try {
// @ts-expect-error TODO: fix
if ('$' + getter(value) === typedArray) {
found = $slice(typedArray, 1);
}
} catch (e) { /**/ }
}
}
);
return found;
};
/** @type {(value: object) => false | import('.').TypedArrayName} */
var trySlices = function tryAllSlices(value) {
/** @type {ReturnType<typeof tryAllSlices>} */ var found = false;
forEach(
// eslint-disable-next-line no-extra-parens
/** @type {Record<`\$${TypedArrayName}`, Getter>} */ /** @type {any} */ (cache),
/** @type {(getter: typeof cache, name: `\$${import('.').TypedArrayName}`) => void} */ function (getter, name) {
if (!found) {
try {
// @ts-expect-error TODO: fix
getter(value);
found = $slice(name, 1);
} catch (e) { /**/ }
}
}
);
return found;
};
/** @type {import('.')} */
module.exports = function whichTypedArray(value) {
if (!value || typeof value !== 'object') { return false; }
if (!hasToStringTag) {
/** @type {string} */
var tag = $slice($toString(value), 8, -1);
if ($indexOf(typedArrays, tag) > -1) {
return tag;
}
if (tag !== 'Object') {
return false;
}
// node < 0.6 hits here on real Typed Arrays
return trySlices(value);
}
if (!gOPD) { return null; } // unknown engine
return tryTypedArrays(value);
};
/***/ }),
/***/ 7120:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(6883);
var callBind = __webpack_require__(4899);
var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));
module.exports = function callBoundIntrinsic(name, allowMissing) {
var intrinsic = GetIntrinsic(name, !!allowMissing);
if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
return callBind(intrinsic);
}
return intrinsic;
};
/***/ }),
/***/ 4899:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var bind = __webpack_require__(7961);
var GetIntrinsic = __webpack_require__(6883);
var setFunctionLength = __webpack_require__(4521);
var $TypeError = __webpack_require__(1642);
var $apply = GetIntrinsic('%Function.prototype.apply%');
var $call = GetIntrinsic('%Function.prototype.call%');
var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
var $defineProperty = __webpack_require__(8918);
var $max = GetIntrinsic('%Math.max%');
module.exports = function callBind(originalFunction) {
if (typeof originalFunction !== 'function') {
throw new $TypeError('a function is required');
}
var func = $reflectApply(bind, $call, arguments);
return setFunctionLength(
func,
1 + $max(0, originalFunction.length - (arguments.length - 1)),
true
);
};
var applyBind = function applyBind() {
return $reflectApply(bind, $apply, arguments);
};
if ($defineProperty) {
$defineProperty(module.exports, 'apply', { value: applyBind });
} else {
module.exports.apply = applyBind;
}
/***/ }),
/***/ 7562:
/***/ (function(module) {
"use strict";
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var toStr = Object.prototype.toString;
var max = Math.max;
var funcType = '[object Function]';
var concatty = function concatty(a, b) {
var arr = [];
for (var i = 0; i < a.length; i += 1) {
arr[i] = a[i];
}
for (var j = 0; j < b.length; j += 1) {
arr[j + a.length] = b[j];
}
return arr;
};
var slicy = function slicy(arrLike, offset) {
var arr = [];
for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
arr[j] = arrLike[i];
}
return arr;
};
var joiny = function (arr, joiner) {
var str = '';
for (var i = 0; i < arr.length; i += 1) {
str += arr[i];
if (i + 1 < arr.length) {
str += joiner;
}
}
return str;
};
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slicy(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
concatty(args, arguments)
);
if (Object(result) === result) {
return result;
}
return this;
}
return target.apply(
that,
concatty(args, arguments)
);
};
var boundLength = max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs[i] = '$' + i;
}
bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
/***/ }),
/***/ 7961:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(7562);
module.exports = Function.prototype.bind || implementation;
/***/ }),
/***/ 6883:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var undefined;
var $Error = __webpack_require__(6716);
var $EvalError = __webpack_require__(6788);
var $RangeError = __webpack_require__(9204);
var $ReferenceError = __webpack_require__(9908);
var $SyntaxError = __webpack_require__(6724);
var $TypeError = __webpack_require__(1642);
var $URIError = __webpack_require__(1451);
var $Function = Function;
// eslint-disable-next-line consistent-return
var getEvalledConstructor = function (expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
} catch (e) {}
};
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () {
throw new $TypeError();
};
var ThrowTypeError = $gOPD
? (function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}())
: throwTypeError;
var hasSymbols = __webpack_require__(8861)();
var hasProto = __webpack_require__(1856)();
var getProto = Object.getPrototypeOf || (
hasProto
? function (x) { return x.__proto__; } // eslint-disable-line no-proto
: null
);
var needsEval = {};
var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array);
var INTRINSICS = {
__proto__: null,
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
'%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined,
'%AsyncFromSyncIteratorPrototype%': undefined,
'%AsyncFunction%': needsEval,
'%AsyncGenerator%': needsEval,
'%AsyncGeneratorFunction%': needsEval,
'%AsyncIteratorPrototype%': needsEval,
'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,
'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,
'%Boolean%': Boolean,
'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
'%Date%': Date,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': $Error,
'%eval%': eval, // eslint-disable-line no-eval
'%EvalError%': $EvalError,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
'%Function%': $Function,
'%GeneratorFunction%': needsEval,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined,
'%JSON%': typeof JSON === 'object' ? JSON : undefined,
'%Map%': typeof Map === 'undefined' ? undefined : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()),
'%Math%': Math,
'%Number%': Number,
'%Object%': Object,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
'%RangeError%': $RangeError,
'%ReferenceError%': $ReferenceError,
'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
'%RegExp%': RegExp,
'%Set%': typeof Set === 'undefined' ? undefined : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()),
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined,
'%Symbol%': hasSymbols ? Symbol : undefined,
'%SyntaxError%': $SyntaxError,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypeError%': $TypeError,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
'%URIError%': $URIError,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
};
if (getProto) {
try {
null.error; // eslint-disable-line no-unused-expressions
} catch (e) {
// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
var errorProto = getProto(getProto(e));
INTRINSICS['%Error.prototype%'] = errorProto;
}
}
var doEval = function doEval(name) {
var value;
if (name === '%AsyncFunction%') {
value = getEvalledConstructor('async function () {}');
} else if (name === '%GeneratorFunction%') {
value = getEvalledConstructor('function* () {}');
} else if (name === '%AsyncGeneratorFunction%') {
value = getEvalledConstructor('async function* () {}');
} else if (name === '%AsyncGenerator%') {
var fn = doEval('%AsyncGeneratorFunction%');
if (fn) {
value = fn.prototype;
}
} else if (name === '%AsyncIteratorPrototype%') {
var gen = doEval('%AsyncGenerator%');
if (gen && getProto) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name] = value;
return value;
};
var LEGACY_ALIASES = {
__proto__: null,
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
'%ArrayPrototype%': ['Array', 'prototype'],
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
'%BooleanPrototype%': ['Boolean', 'prototype'],
'%DataViewPrototype%': ['DataView', 'prototype'],
'%DatePrototype%': ['Date', 'prototype'],
'%ErrorPrototype%': ['Error', 'prototype'],
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
'%FunctionPrototype%': ['Function', 'prototype'],
'%Generator%': ['GeneratorFunction', 'prototype'],
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
'%JSONParse%': ['JSON', 'parse'],
'%JSONStringify%': ['JSON', 'stringify'],
'%MapPrototype%': ['Map', 'prototype'],
'%NumberPrototype%': ['Number', 'prototype'],
'%ObjectPrototype%': ['Object', 'prototype'],
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
'%PromisePrototype%': ['Promise', 'prototype'],
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
'%Promise_all%': ['Promise', 'all'],
'%Promise_reject%': ['Promise', 'reject'],
'%Promise_resolve%': ['Promise', 'resolve'],
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
'%RegExpPrototype%': ['RegExp', 'prototype'],
'%SetPrototype%': ['Set', 'prototype'],
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
'%StringPrototype%': ['String', 'prototype'],
'%SymbolPrototype%': ['Symbol', 'prototype'],
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
'%URIErrorPrototype%': ['URIError', 'prototype'],
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
'%WeakSetPrototype%': ['WeakSet', 'prototype']
};
var bind = __webpack_require__(7961);
var hasOwn = __webpack_require__(9429);
var $concat = bind.call(Function.call, Array.prototype.concat);
var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
var $replace = bind.call(Function.call, String.prototype.replace);
var $strSlice = bind.call(Function.call, String.prototype.slice);
var $exec = bind.call(Function.call, RegExp.prototype.exec);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
var first = $strSlice(string, 0, 1);
var last = $strSlice(string, -1);
if (first === '%' && last !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
} else if (last === '%' && first !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
}
var result = [];
$replace(string, rePropName, function (match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
var intrinsicName = name;
var alias;
if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
alias = LEGACY_ALIASES[intrinsicName];
intrinsicName = '%' + alias[0] + '%';
}
if (hasOwn(INTRINSICS, intrinsicName)) {
var value = INTRINSICS[intrinsicName];
if (value === needsEval) {
value = doEval(intrinsicName);
}
if (typeof value === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return {
alias: alias,
name: intrinsicName,
value: value
};
}
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
};
module.exports = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new $TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new $TypeError('"allowMissing" argument must be a boolean');
}
if ($exec(/^%?[^%]*%?$/, name) === null) {
throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
}
var parts = stringToPath(name);
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
var intrinsicRealName = intrinsic.name;
var value = intrinsic.value;
var skipFurtherCaching = false;
var alias = intrinsic.alias;
if (alias) {
intrinsicBaseName = alias[0];
$spliceApply(parts, $concat([0, 1], alias));
}
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
var part = parts[i];
var first = $strSlice(part, 0, 1);
var last = $strSlice(part, -1);
if (
(
(first === '"' || first === "'" || first === '`')
|| (last === '"' || last === "'" || last === '`')
)
&& first !== last
) {
throw new $SyntaxError('property names with quotes must have matching quotes');
}
if (part === 'constructor' || !isOwn) {
skipFurtherCaching = true;
}
intrinsicBaseName += '.' + part;
intrinsicRealName = '%' + intrinsicBaseName + '%';
if (hasOwn(INTRINSICS, intrinsicRealName)) {
value = INTRINSICS[intrinsicRealName];
} else if (value != null) {
if (!(part in value)) {
if (!allowMissing) {
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
}
return void undefined;
}
if ($gOPD && (i + 1) >= parts.length) {
var desc = $gOPD(value, part);
isOwn = !!desc;
// By convention, when a data property is converted to an accessor
// property to emulate a data property that does not suffer from
// the override mistake, that accessor's getter is marked with
// an `originalValue` property. Here, when we detect this, we
// uphold the illusion by pretending to see that original data
// property, i.e., returning the value rather than the getter
// itself.
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
value = desc.get;
} else {
value = value[part];
}
} else {
isOwn = hasOwn(value, part);
value = value[part];
}
if (isOwn && !skipFurtherCaching) {
INTRINSICS[intrinsicRealName] = value;
}
}
}
return value;
};
/***/ }),
/***/ 8861:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = __webpack_require__(704);
module.exports = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return hasSymbolSham();
};
/***/ }),
/***/ 704:
/***/ (function(module) {
"use strict";
/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
/***/ }),
/***/ 9196:
/***/ (function(module) {
"use strict";
module.exports = window["React"];
/***/ }),
/***/ 5794:
/***/ (function() {
/* (ignored) */
/***/ }),
/***/ 4343:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var possibleNames = __webpack_require__(131);
var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis;
/** @type {import('.')} */
module.exports = function availableTypedArrays() {
var /** @type {ReturnType<typeof availableTypedArrays>} */ out = [];
for (var i = 0; i < possibleNames.length; i++) {
if (typeof g[possibleNames[i]] === 'function') {
// @ts-expect-error
out[out.length] = possibleNames[i];
}
}
return out;
};
/***/ }),
/***/ 7153:
/***/ (function(module, exports) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2018 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
'use strict';
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = '';
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
classes = appendClass(classes, parseValue(arg));
}
}
return classes;
}
function parseValue (arg) {
if (typeof arg === 'string' || typeof arg === 'number') {
return arg;
}
if (typeof arg !== 'object') {
return '';
}
if (Array.isArray(arg)) {
return classNames.apply(null, arg);
}
if (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes('[native code]')) {
return arg.toString();
}
var classes = '';
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes = appendClass(classes, key);
}
}
return classes;
}
function appendClass (value, newClass) {
if (!newClass) {
return value;
}
if (value) {
return value + ' ' + newClass;
}
return value + newClass;
}
if ( true && module.exports) {
classNames.default = classNames;
module.exports = classNames;
} else if (true) {
// register as 'classnames', consistent with npm package name
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () {
return classNames;
}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
}());
/***/ }),
/***/ 6245:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(5037);
var $String = GetIntrinsic('%String%');
var $TypeError = __webpack_require__(1642);
// https://262.ecma-international.org/6.0/#sec-tostring
module.exports = function ToString(argument) {
if (typeof argument === 'symbol') {
throw new $TypeError('Cannot convert a Symbol value to a string');
}
return $String(argument);
};
/***/ }),
/***/ 2981:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $TypeError = __webpack_require__(1642);
// https://tc39.es/ecma262/#sec-arraybufferbytelength
var IsDetachedBuffer = __webpack_require__(1320);
var isArrayBuffer = __webpack_require__(4602);
var isSharedArrayBuffer = __webpack_require__(5604);
var arrayBufferByteLength = __webpack_require__(480);
var isGrowable = false; // TODO: support this
module.exports = function ArrayBufferByteLength(arrayBuffer, order) {
var isSAB = isSharedArrayBuffer(arrayBuffer);
if (!isArrayBuffer(arrayBuffer) && !isSAB) {
throw new $TypeError('Assertion failed: `arrayBuffer` must be an ArrayBuffer or a SharedArrayBuffer');
}
if (order !== 'SEQ-CST' && order !== 'UNORDERED') {
throw new $TypeError('Assertion failed: `order` must be ~SEQ-CST~ or ~UNORDERED~');
}
// 1. If IsSharedArrayBuffer(arrayBuffer) is true and arrayBuffer has an [[ArrayBufferByteLengthData]] internal slot, then
// TODO: see if IsFixedLengthArrayBuffer can be used here in the spec instead
if (isSAB && isGrowable) { // step 1
// a. Let bufferByteLengthBlock be arrayBuffer.[[ArrayBufferByteLengthData]].
// b. Let rawLength be GetRawBytesFromSharedBlock(bufferByteLengthBlock, 0, BIGUINT64, true, order).
// c. Let isLittleEndian be the value of the [[LittleEndian]] field of the surrounding agent's Agent Record.
// d. Return ℝ(RawBytesToNumeric(BIGUINT64, rawLength, isLittleEndian)).
}
if (IsDetachedBuffer(arrayBuffer)) {
throw new $TypeError('Assertion failed: `arrayBuffer` must not be detached'); // step 2
}
return arrayBufferByteLength(arrayBuffer);
};
/***/ }),
/***/ 6548:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var $BigInt = GetIntrinsic('%BigInt%', true);
var $RangeError = __webpack_require__(9204);
var $TypeError = __webpack_require__(1642);
var zero = $BigInt && $BigInt(0);
// https://262.ecma-international.org/11.0/#sec-numeric-types-bigint-remainder
module.exports = function BigIntRemainder(n, d) {
if (typeof n !== 'bigint' || typeof d !== 'bigint') {
throw new $TypeError('Assertion failed: `n` and `d` arguments must be BigInts');
}
if (d === zero) {
throw new $RangeError('Division by zero');
}
if (n === zero) {
return zero;
}
// shortcut for the actual spec mechanics
return n % d;
};
/***/ }),
/***/ 9002:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $TypeError = __webpack_require__(1642);
var isPropertyDescriptor = __webpack_require__(6862);
var DefineOwnProperty = __webpack_require__(208);
var FromPropertyDescriptor = __webpack_require__(8367);
var IsDataDescriptor = __webpack_require__(4065);
var IsPropertyKey = __webpack_require__(9762);
var SameValue = __webpack_require__(3392);
var ToPropertyDescriptor = __webpack_require__(8110);
var Type = __webpack_require__(9655);
// https://262.ecma-international.org/6.0/#sec-definepropertyorthrow
module.exports = function DefinePropertyOrThrow(O, P, desc) {
if (Type(O) !== 'Object') {
throw new $TypeError('Assertion failed: Type(O) is not Object');
}
if (!IsPropertyKey(P)) {
throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true');
}
var Desc = isPropertyDescriptor(desc) ? desc : ToPropertyDescriptor(desc);
if (!isPropertyDescriptor(Desc)) {
throw new $TypeError('Assertion failed: Desc is not a valid Property Descriptor');
}
return DefineOwnProperty(
IsDataDescriptor,
SameValue,
FromPropertyDescriptor,
O,
P,
Desc
);
};
/***/ }),
/***/ 8367:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $TypeError = __webpack_require__(1642);
var isPropertyDescriptor = __webpack_require__(6862);
var fromPropertyDescriptor = __webpack_require__(2646);
// https://262.ecma-international.org/6.0/#sec-frompropertydescriptor
module.exports = function FromPropertyDescriptor(Desc) {
if (typeof Desc !== 'undefined' && !isPropertyDescriptor(Desc)) {
throw new $TypeError('Assertion failed: `Desc` must be a Property Descriptor');
}
return fromPropertyDescriptor(Desc);
};
/***/ }),
/***/ 3675:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $TypeError = __webpack_require__(1642);
var inspect = __webpack_require__(5726);
var IsPropertyKey = __webpack_require__(9762);
var Type = __webpack_require__(9655);
// https://262.ecma-international.org/6.0/#sec-get-o-p
module.exports = function Get(O, P) {
// 7.3.1.1
if (Type(O) !== 'Object') {
throw new $TypeError('Assertion failed: Type(O) is not Object');
}
// 7.3.1.2
if (!IsPropertyKey(P)) {
throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true, got ' + inspect(P));
}
// 7.3.1.3
return O[P];
};
/***/ }),
/***/ 9661:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var $SyntaxError = __webpack_require__(6724);
var $TypeError = __webpack_require__(1642);
var $Uint8Array = GetIntrinsic('%Uint8Array%', true);
var callBound = __webpack_require__(1154);
var $slice = callBound('Array.prototype.slice');
var isInteger = __webpack_require__(6156);
var IsDetachedBuffer = __webpack_require__(1320);
var RawBytesToNumeric = __webpack_require__(9219);
var isArrayBuffer = __webpack_require__(4602);
var isSharedArrayBuffer = __webpack_require__(5604);
var safeConcat = __webpack_require__(3002);
var tableTAO = __webpack_require__(2170);
var defaultEndianness = __webpack_require__(2142);
// https://262.ecma-international.org/15.0/#sec-getvaluefrombuffer
module.exports = function GetValueFromBuffer(arrayBuffer, byteIndex, type, isTypedArray, order) {
var isSAB = isSharedArrayBuffer(arrayBuffer);
if (!isArrayBuffer(arrayBuffer) && !isSAB) {
throw new $TypeError('Assertion failed: `arrayBuffer` must be an ArrayBuffer or a SharedArrayBuffer');
}
if (!isInteger(byteIndex)) {
throw new $TypeError('Assertion failed: `byteIndex` must be an integer');
}
if (typeof type !== 'string' || typeof tableTAO.size['$' + type] !== 'number') {
throw new $TypeError('Assertion failed: `type` must be a Typed Array element type');
}
if (typeof isTypedArray !== 'boolean') {
throw new $TypeError('Assertion failed: `isTypedArray` must be a boolean');
}
if (order !== 'SEQ-CST' && order !== 'UNORDERED') {
throw new $TypeError('Assertion failed: `order` must be either `SEQ-CST` or `UNORDERED`');
}
if (arguments.length > 5 && typeof arguments[5] !== 'boolean') {
throw new $TypeError('Assertion failed: `isLittleEndian` must be a boolean, if present');
}
if (IsDetachedBuffer(arrayBuffer)) {
throw new $TypeError('Assertion failed: `arrayBuffer` is detached'); // step 1
}
// 2. Assert: There are sufficient bytes in arrayBuffer starting at byteIndex to represent a value of type.
if (byteIndex < 0) {
throw new $TypeError('Assertion failed: `byteIndex` must be non-negative'); // step 3
}
// 4. Let block be arrayBuffer.[[ArrayBufferData]].
var elementSize = tableTAO.size['$' + type]; // step 5
if (!elementSize) {
throw new $TypeError('Assertion failed: `type` must be one of "INT8", "UINT8", "UINT8C", "INT16", "UINT16", "INT32", "UINT32", "BIGINT64", "BIGUINT64", "FLOAT32", or "FLOAT64"');
}
var rawValue;
if (isSAB) { // step 6
/*
a. Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent Record.
b. Let eventList be the [[EventList]] field of the element in execution.[[EventLists]] whose [[AgentSignifier]] is AgentSignifier().
c. If isTypedArray is true and type is "Int8", "Uint8", "Int16", "Uint16", "Int32", or "Uint32", let noTear be true; otherwise let noTear be false.
d. Let rawValue be a List of length elementSize of nondeterministically chosen byte values.
e. NOTE: In implementations, rawValue is the result of a non-atomic or atomic read instruction on the underlying hardware. The nondeterminism is a semantic prescription of the memory model to describe observable behaviour of hardware with weak consistency.
f. Let readEvent be ReadSharedMemory{ [[Order]]: order, [[NoTear]]: noTear, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize }.
g. Append readEvent to eventList.
h. Append Chosen Value Record { [[Event]]: readEvent, [[ChosenValue]]: rawValue } to execution.[[ChosenValues]].
*/
throw new $SyntaxError('SharedArrayBuffer is not supported by this implementation');
} else {
// 7. Let rawValue be a List of elementSize containing, in order, the elementSize sequence of bytes starting with block[byteIndex].
rawValue = $slice(new $Uint8Array(arrayBuffer, byteIndex), 0, elementSize); // step 6
}
// 8. If isLittleEndian is not present, set isLittleEndian to either true or false. The choice is implementation dependent and should be the alternative that is most efficient for the implementation. An implementation must use the same value each time this step is executed and the same value must be used for the corresponding step in the SetValueInBuffer abstract operation.
var isLittleEndian = arguments.length > 5 ? arguments[5] : defaultEndianness === 'little'; // step 8
var bytes = isLittleEndian
? $slice(safeConcat([0, 0, 0, 0, 0, 0, 0, 0], rawValue), -elementSize)
: $slice(safeConcat(rawValue, [0, 0, 0, 0, 0, 0, 0, 0]), 0, elementSize);
return RawBytesToNumeric(type, bytes, isLittleEndian);
};
/***/ }),
/***/ 5584:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $TypeError = __webpack_require__(1642);
var hasOwn = __webpack_require__(9429);
var IsPropertyKey = __webpack_require__(9762);
var Type = __webpack_require__(9655);
// https://262.ecma-international.org/6.0/#sec-hasownproperty
module.exports = function HasOwnProperty(O, P) {
if (Type(O) !== 'Object') {
throw new $TypeError('Assertion failed: `O` must be an Object');
}
if (!IsPropertyKey(P)) {
throw new $TypeError('Assertion failed: `P` must be a Property Key');
}
return hasOwn(O, P);
};
/***/ }),
/***/ 2985:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
// https://262.ecma-international.org/6.0/#sec-isarray
module.exports = __webpack_require__(692);
/***/ }),
/***/ 4734:
/***/ (function(module) {
"use strict";
// https://262.ecma-international.org/15.0/#sec-isbigintelementtype
module.exports = function IsBigIntElementType(type) {
return type === 'BIGUINT64' || type === 'BIGINT64';
};
/***/ }),
/***/ 3071:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
// http://262.ecma-international.org/5.1/#sec-9.11
module.exports = __webpack_require__(6841);
/***/ }),
/***/ 7010:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(4342);
var $construct = GetIntrinsic('%Reflect.construct%', true);
var DefinePropertyOrThrow = __webpack_require__(9002);
try {
DefinePropertyOrThrow({}, '', { '[[Get]]': function () {} });
} catch (e) {
// Accessor properties aren't supported
DefinePropertyOrThrow = null;
}
// https://262.ecma-international.org/6.0/#sec-isconstructor
if (DefinePropertyOrThrow && $construct) {
var isConstructorMarker = {};
var badArrayLike = {};
DefinePropertyOrThrow(badArrayLike, 'length', {
'[[Get]]': function () {
throw isConstructorMarker;
},
'[[Enumerable]]': true
});
module.exports = function IsConstructor(argument) {
try {
// `Reflect.construct` invokes `IsConstructor(target)` before `Get(args, 'length')`:
$construct(argument, badArrayLike);
} catch (err) {
return err === isConstructorMarker;
}
};
} else {
module.exports = function IsConstructor(argument) {
// unfortunately there's no way to truly check this without try/catch `new argument` in old environments
return typeof argument === 'function' && !!argument.prototype;
};
}
/***/ }),
/***/ 4065:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $TypeError = __webpack_require__(1642);
var hasOwn = __webpack_require__(9429);
var isPropertyDescriptor = __webpack_require__(6862);
// https://262.ecma-international.org/5.1/#sec-8.10.2
module.exports = function IsDataDescriptor(Desc) {
if (typeof Desc === 'undefined') {
return false;
}
if (!isPropertyDescriptor(Desc)) {
throw new $TypeError('Assertion failed: `Desc` must be a Property Descriptor');
}
if (!hasOwn(Desc, '[[Value]]') && !hasOwn(Desc, '[[Writable]]')) {
return false;
}
return true;
};
/***/ }),
/***/ 1320:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $TypeError = __webpack_require__(1642);
var $byteLength = __webpack_require__(480);
var availableTypedArrays = __webpack_require__(4343)();
var callBound = __webpack_require__(1154);
var isArrayBuffer = __webpack_require__(4602);
var isSharedArrayBuffer = __webpack_require__(5604);
var $sabByteLength = callBound('SharedArrayBuffer.prototype.byteLength', true);
// https://262.ecma-international.org/8.0/#sec-isdetachedbuffer
module.exports = function IsDetachedBuffer(arrayBuffer) {
var isSAB = isSharedArrayBuffer(arrayBuffer);
if (!isArrayBuffer(arrayBuffer) && !isSAB) {
throw new $TypeError('Assertion failed: `arrayBuffer` must be an Object with an [[ArrayBufferData]] internal slot');
}
if ((isSAB ? $sabByteLength : $byteLength)(arrayBuffer) === 0) {
try {
new __webpack_require__.g[availableTypedArrays[0]](arrayBuffer); // eslint-disable-line no-new
} catch (error) {
return !!error && error.name === 'TypeError';
}
}
return false;
};
/***/ }),
/***/ 9442:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $TypeError = __webpack_require__(1642);
var callBound = __webpack_require__(1154);
var $arrayBufferResizable = callBound('%ArrayBuffer.prototype.resizable%', true);
var $sharedArrayGrowable = callBound('%SharedArrayBuffer.prototype.growable%', true);
var isArrayBuffer = __webpack_require__(4602);
var isSharedArrayBuffer = __webpack_require__(5604);
// https://262.ecma-international.org/15.0/#sec-isfixedlengtharraybuffer
module.exports = function IsFixedLengthArrayBuffer(arrayBuffer) {
var isAB = isArrayBuffer(arrayBuffer);
var isSAB = isSharedArrayBuffer(arrayBuffer);
if (!isAB && !isSAB) {
throw new $TypeError('Assertion failed: `arrayBuffer` must be an ArrayBuffer or SharedArrayBuffer');
}
if (isAB && $arrayBufferResizable) {
return !$arrayBufferResizable(arrayBuffer); // step 1
}
if (isSAB && $sharedArrayGrowable) {
return !$sharedArrayGrowable(arrayBuffer); // step 1
}
return true; // step 2
};
/***/ }),
/***/ 9762:
/***/ (function(module) {
"use strict";
// https://262.ecma-international.org/6.0/#sec-ispropertykey
module.exports = function IsPropertyKey(argument) {
return typeof argument === 'string' || typeof argument === 'symbol';
};
/***/ }),
/***/ 9954:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $TypeError = __webpack_require__(1642);
var IsDetachedBuffer = __webpack_require__(1320);
var TypedArrayElementSize = __webpack_require__(9149);
var isTypedArrayWithBufferWitnessRecord = __webpack_require__(359);
var typedArrayBuffer = __webpack_require__(6740);
var typedArrayByteOffset = __webpack_require__(7046);
var typedArrayLength = __webpack_require__(8150);
// https://tc39.es/ecma262/#sec-istypedarrayoutofbounds
module.exports = function IsTypedArrayOutOfBounds(taRecord) {
if (!isTypedArrayWithBufferWitnessRecord(taRecord)) {
throw new $TypeError('Assertion failed: `taRecord` must be a TypedArray With Buffer Witness Record');
}
var O = taRecord['[[Object]]']; // step 1
var bufferByteLength = taRecord['[[CachedBufferByteLength]]']; // step 2
if (IsDetachedBuffer(typedArrayBuffer(O)) && bufferByteLength !== 'DETACHED') {
throw new $TypeError('Assertion failed: typed array is detached only if the byte length is ~DETACHED~'); // step 3
}
if (bufferByteLength === 'DETACHED') {
return true; // step 4
}
var byteOffsetStart = typedArrayByteOffset(O); // step 5
var byteOffsetEnd;
var length = typedArrayLength(O);
// TODO: probably use package for array length
// seems to apply when TA is backed by a resizable/growable AB
if (length === 'AUTO') { // step 6
byteOffsetEnd = bufferByteLength; // step 6.a
} else {
var elementSize = TypedArrayElementSize(O); // step 7.a
byteOffsetEnd = byteOffsetStart + (length * elementSize); // step 7.b
}
if (byteOffsetStart > bufferByteLength || byteOffsetEnd > bufferByteLength) {
return true; // step 8
}
// 9. NOTE: 0-length TypedArrays are not considered out-of-bounds.
return false; // step 10
};
/***/ }),
/***/ 7551:
/***/ (function(module) {
"use strict";
// https://262.ecma-international.org/15.0/#sec-isunsignedelementtype
module.exports = function IsUnsignedElementType(type) {
return type === 'UINT8'
|| type === 'UINT8C'
|| type === 'UINT16'
|| type === 'UINT32'
|| type === 'BIGUINT64';
};
/***/ }),
/***/ 6005:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $TypeError = __webpack_require__(1642);
var ArrayBufferByteLength = __webpack_require__(2981);
var IsDetachedBuffer = __webpack_require__(1320);
var isTypedArray = __webpack_require__(2527);
var typedArrayBuffer = __webpack_require__(6740);
// https://tc39.es/ecma262/#sec-maketypedarraywithbufferwitnessrecord
module.exports = function MakeTypedArrayWithBufferWitnessRecord(obj, order) {
if (!isTypedArray(obj)) {
throw new $TypeError('Assertion failed: `obj` must be a Typed Array');
}
if (order !== 'SEQ-CST' && order !== 'UNORDERED') {
throw new $TypeError('Assertion failed: `order` must be ~SEQ-CST~ or ~UNORDERED~');
}
var buffer = typedArrayBuffer(obj); // step 1
var byteLength = IsDetachedBuffer(buffer) ? 'DETACHED' : ArrayBufferByteLength(buffer, order); // steps 2 - 3
return { '[[Object]]': obj, '[[CachedBufferByteLength]]': byteLength }; // step 4
};
/***/ }),
/***/ 4604:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $TypeError = __webpack_require__(1642);
var hasOwnProperty = __webpack_require__(5584);
var ToBigInt64 = __webpack_require__(1242);
var ToBigUint64 = __webpack_require__(2947);
var ToInt16 = __webpack_require__(3181);
var ToInt32 = __webpack_require__(2587);
var ToInt8 = __webpack_require__(5562);
var ToUint16 = __webpack_require__(5465);
var ToUint32 = __webpack_require__(5964);
var ToUint8 = __webpack_require__(9496);
var ToUint8Clamp = __webpack_require__(6550);
var valueToFloat32Bytes = __webpack_require__(3647);
var valueToFloat64Bytes = __webpack_require__(7511);
var integerToNBytes = __webpack_require__(1520);
var keys = __webpack_require__(806);
// https://262.ecma-international.org/15.0/#table-the-typedarray-constructors
var TypeToSizes = {
__proto__: null,
INT8: 1,
UINT8: 1,
UINT8C: 1,
INT16: 2,
UINT16: 2,
INT32: 4,
UINT32: 4,
BIGINT64: 8,
BIGUINT64: 8,
FLOAT32: 4,
FLOAT64: 8
};
var TypeToAO = {
__proto__: null,
INT8: ToInt8,
UINT8: ToUint8,
UINT8C: ToUint8Clamp,
INT16: ToInt16,
UINT16: ToUint16,
INT32: ToInt32,
UINT32: ToUint32,
BIGINT64: ToBigInt64,
BIGUINT64: ToBigUint64
};
// https://262.ecma-international.org/15.0/#sec-numerictorawbytes
module.exports = function NumericToRawBytes(type, value, isLittleEndian) {
if (typeof type !== 'string' || !hasOwnProperty(TypeToSizes, type)) {
throw new $TypeError('Assertion failed: `type` must be a TypedArray element type: ' + keys(TypeToSizes));
}
if (typeof value !== 'number' && typeof value !== 'bigint') {
throw new $TypeError('Assertion failed: `value` must be a Number or a BigInt');
}
if (typeof isLittleEndian !== 'boolean') {
throw new $TypeError('Assertion failed: `isLittleEndian` must be a Boolean');
}
if (type === 'FLOAT32') { // step 1
return valueToFloat32Bytes(value, isLittleEndian);
} else if (type === 'FLOAT64') { // step 2
return valueToFloat64Bytes(value, isLittleEndian);
} // step 3
var n = TypeToSizes[type]; // step 3.a
var convOp = TypeToAO[type]; // step 3.b
var intValue = convOp(value); // step 3.c
return integerToNBytes(intValue, n, isLittleEndian); // step 3.d, 3.e, 4
};
/***/ }),
/***/ 9219:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var callBound = __webpack_require__(1154);
var $RangeError = __webpack_require__(9204);
var $SyntaxError = __webpack_require__(6724);
var $TypeError = __webpack_require__(1642);
var $BigInt = GetIntrinsic('%BigInt%', true);
var hasOwnProperty = __webpack_require__(5584);
var IsArray = __webpack_require__(2985);
var IsBigIntElementType = __webpack_require__(4734);
var IsUnsignedElementType = __webpack_require__(7551);
var bytesAsFloat32 = __webpack_require__(8727);
var bytesAsFloat64 = __webpack_require__(7604);
var bytesAsInteger = __webpack_require__(2367);
var every = __webpack_require__(8172);
var isByteValue = __webpack_require__(1824);
var $reverse = callBound('Array.prototype.reverse');
var $slice = callBound('Array.prototype.slice');
var keys = __webpack_require__(806);
// https://262.ecma-international.org/15.0/#table-the-typedarray-constructors
var TypeToSizes = {
__proto__: null,
INT8: 1,
UINT8: 1,
UINT8C: 1,
INT16: 2,
UINT16: 2,
INT32: 4,
UINT32: 4,
BIGINT64: 8,
BIGUINT64: 8,
FLOAT32: 4,
FLOAT64: 8
};
// https://262.ecma-international.org/15.0/#sec-rawbytestonumeric
module.exports = function RawBytesToNumeric(type, rawBytes, isLittleEndian) {
if (!hasOwnProperty(TypeToSizes, type)) {
throw new $TypeError('Assertion failed: `type` must be a TypedArray element type: ' + keys(TypeToSizes));
}
if (!IsArray(rawBytes) || !every(rawBytes, isByteValue)) {
throw new $TypeError('Assertion failed: `rawBytes` must be an Array of bytes');
}
if (typeof isLittleEndian !== 'boolean') {
throw new $TypeError('Assertion failed: `isLittleEndian` must be a Boolean');
}
var elementSize = TypeToSizes[type]; // step 1
if (rawBytes.length !== elementSize) {
// this assertion is not in the spec, but it'd be an editorial error if it were ever violated
throw new $RangeError('Assertion failed: `rawBytes` must have a length of ' + elementSize + ' for type ' + type);
}
var isBigInt = IsBigIntElementType(type);
if (isBigInt && !$BigInt) {
throw new $SyntaxError('this environment does not support BigInts');
}
// eslint-disable-next-line no-param-reassign
rawBytes = $slice(rawBytes, 0, elementSize);
if (!isLittleEndian) {
$reverse(rawBytes); // step 2
}
if (type === 'FLOAT32') { // step 3
return bytesAsFloat32(rawBytes);
}
if (type === 'FLOAT64') { // step 4
return bytesAsFloat64(rawBytes);
}
return bytesAsInteger(rawBytes, elementSize, IsUnsignedElementType(type), isBigInt);
};
/***/ }),
/***/ 3392:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $isNaN = __webpack_require__(9404);
// http://262.ecma-international.org/5.1/#sec-9.12
module.exports = function SameValue(x, y) {
if (x === y) { // 0 === -0, but they are not identical.
if (x === 0) { return 1 / x === 1 / y; }
return true;
}
return $isNaN(x) && $isNaN(y);
};
/***/ }),
/***/ 8055:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $TypeError = __webpack_require__(1642);
var IsPropertyKey = __webpack_require__(9762);
var SameValue = __webpack_require__(3392);
var Type = __webpack_require__(9655);
// IE 9 does not throw in strict mode when writability/configurability/extensibility is violated
var noThrowOnStrictViolation = (function () {
try {
delete [].length;
return true;
} catch (e) {
return false;
}
}());
// https://262.ecma-international.org/6.0/#sec-set-o-p-v-throw
module.exports = function Set(O, P, V, Throw) {
if (Type(O) !== 'Object') {
throw new $TypeError('Assertion failed: `O` must be an Object');
}
if (!IsPropertyKey(P)) {
throw new $TypeError('Assertion failed: `P` must be a Property Key');
}
if (typeof Throw !== 'boolean') {
throw new $TypeError('Assertion failed: `Throw` must be a Boolean');
}
if (Throw) {
O[P] = V; // eslint-disable-line no-param-reassign
if (noThrowOnStrictViolation && !SameValue(O[P], V)) {
throw new $TypeError('Attempted to assign to readonly property.');
}
return true;
}
try {
O[P] = V; // eslint-disable-line no-param-reassign
return noThrowOnStrictViolation ? SameValue(O[P], V) : true;
} catch (e) {
return false;
}
};
/***/ }),
/***/ 3383:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var $SyntaxError = __webpack_require__(6724);
var $TypeError = __webpack_require__(1642);
var $Uint8Array = GetIntrinsic('%Uint8Array%', true);
var isInteger = __webpack_require__(6156);
var IsBigIntElementType = __webpack_require__(4734);
var IsDetachedBuffer = __webpack_require__(1320);
var NumericToRawBytes = __webpack_require__(4604);
var isArrayBuffer = __webpack_require__(4602);
var isSharedArrayBuffer = __webpack_require__(5604);
var has = __webpack_require__(9429);
var tableTAO = __webpack_require__(2170);
var defaultEndianness = __webpack_require__(2142);
var forEach = __webpack_require__(9065);
// https://262.ecma-international.org/15.0/#sec-setvalueinbuffer
/* eslint max-params: 0 */
module.exports = function SetValueInBuffer(arrayBuffer, byteIndex, type, value, isTypedArray, order) {
var isSAB = isSharedArrayBuffer(arrayBuffer);
if (!isArrayBuffer(arrayBuffer) && !isSAB) {
throw new $TypeError('Assertion failed: `arrayBuffer` must be an ArrayBuffer or a SharedArrayBuffer');
}
if (!isInteger(byteIndex) || byteIndex < 0) {
throw new $TypeError('Assertion failed: `byteIndex` must be a non-negative integer');
}
if (typeof type !== 'string' || !has(tableTAO.size, '$' + type)) {
throw new $TypeError('Assertion failed: `type` must be a Typed Array Element Type');
}
if (typeof value !== 'number' && typeof value !== 'bigint') {
throw new $TypeError('Assertion failed: `value` must be a Number or a BigInt');
}
if (typeof isTypedArray !== 'boolean') {
throw new $TypeError('Assertion failed: `isTypedArray` must be a boolean');
}
if (order !== 'SEQ-CST' && order !== 'UNORDERED' && order !== 'INIT') {
throw new $TypeError('Assertion failed: `order` must be `"SEQ-CST"`, `"UNORDERED"`, or `"INIT"`');
}
if (arguments.length > 6 && typeof arguments[6] !== 'boolean') {
throw new $TypeError('Assertion failed: `isLittleEndian` must be a boolean, if present');
}
if (IsDetachedBuffer(arrayBuffer)) {
throw new $TypeError('Assertion failed: ArrayBuffer is detached'); // step 1
}
// 2. Assert: There are sufficient bytes in arrayBuffer starting at byteIndex to represent a value of type.
if (IsBigIntElementType(type) ? typeof value !== 'bigint' : typeof value !== 'number') { // step 3
throw new $TypeError('Assertion failed: `value` must be a BigInt if type is ~BIGINT64~ or ~BIGUINT64~, otherwise a Number');
}
// 4. Let block be arrayBuffer’s [[ArrayBufferData]] internal slot.
var elementSize = tableTAO.size['$' + type]; // step 5
// 6. If isLittleEndian is not present, set isLittleEndian to either true or false. The choice is implementation dependent and should be the alternative that is most efficient for the implementation. An implementation must use the same value each time this step is executed and the same value must be used for the corresponding step in the GetValueFromBuffer abstract operation.
var isLittleEndian = arguments.length > 6 ? arguments[6] : defaultEndianness === 'little'; // step 6
var rawBytes = NumericToRawBytes(type, value, isLittleEndian); // step 7
if (isSAB) { // step 8
/*
Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent Record.
Let eventList be the [[EventList]] field of the element in execution.[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier().
If isTypedArray is true and IsNoTearConfiguration(type, order) is true, let noTear be true; otherwise let noTear be false.
Append WriteSharedMemory { [[Order]]: order, [[NoTear]]: noTear, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize, [[Payload]]: rawBytes } to eventList.
*/
throw new $SyntaxError('SharedArrayBuffer is not supported by this implementation');
} else {
// 9. Store the individual bytes of rawBytes into block, in order, starting at block[byteIndex].
var arr = new $Uint8Array(arrayBuffer, byteIndex, elementSize);
forEach(rawBytes, function (rawByte, i) {
arr[i] = rawByte;
});
}
// 10. Return NormalCompletion(undefined).
};
/***/ }),
/***/ 5994:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var $species = GetIntrinsic('%Symbol.species%', true);
var $TypeError = __webpack_require__(1642);
var IsConstructor = __webpack_require__(7010);
var Type = __webpack_require__(9655);
// https://262.ecma-international.org/6.0/#sec-speciesconstructor
module.exports = function SpeciesConstructor(O, defaultConstructor) {
if (Type(O) !== 'Object') {
throw new $TypeError('Assertion failed: Type(O) is not Object');
}
var C = O.constructor;
if (typeof C === 'undefined') {
return defaultConstructor;
}
if (Type(C) !== 'Object') {
throw new $TypeError('O.constructor is not an Object');
}
var S = $species ? C[$species] : void 0;
if (S == null) {
return defaultConstructor;
}
if (IsConstructor(S)) {
return S;
}
throw new $TypeError('no constructor found');
};
/***/ }),
/***/ 907:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var $BigInt = GetIntrinsic('%BigInt%', true);
var $TypeError = __webpack_require__(1642);
var $SyntaxError = __webpack_require__(6724);
// https://262.ecma-international.org/14.0/#sec-stringtobigint
module.exports = function StringToBigInt(argument) {
if (typeof argument !== 'string') {
throw new $TypeError('`argument` must be a string');
}
if (!$BigInt) {
throw new $SyntaxError('BigInts are not supported in this environment');
}
try {
return $BigInt(argument);
} catch (e) {
return void undefined;
}
};
/***/ }),
/***/ 4967:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var $Number = GetIntrinsic('%Number%');
var $RegExp = GetIntrinsic('%RegExp%');
var $TypeError = __webpack_require__(1642);
var $parseInteger = GetIntrinsic('%parseInt%');
var callBound = __webpack_require__(1154);
var regexTester = __webpack_require__(1312);
var $strSlice = callBound('String.prototype.slice');
var isBinary = regexTester(/^0b[01]+$/i);
var isOctal = regexTester(/^0o[0-7]+$/i);
var isInvalidHexLiteral = regexTester(/^[-+]0x[0-9a-f]+$/i);
var nonWS = ['\u0085', '\u200b', '\ufffe'].join('');
var nonWSregex = new $RegExp('[' + nonWS + ']', 'g');
var hasNonWS = regexTester(nonWSregex);
var $trim = __webpack_require__(4113);
// https://262.ecma-international.org/13.0/#sec-stringtonumber
module.exports = function StringToNumber(argument) {
if (typeof argument !== 'string') {
throw new $TypeError('Assertion failed: `argument` is not a String');
}
if (isBinary(argument)) {
return $Number($parseInteger($strSlice(argument, 2), 2));
}
if (isOctal(argument)) {
return $Number($parseInteger($strSlice(argument, 2), 8));
}
if (hasNonWS(argument) || isInvalidHexLiteral(argument)) {
return NaN;
}
var trimmed = $trim(argument);
if (trimmed !== argument) {
return StringToNumber(trimmed);
}
return $Number(argument);
};
/***/ }),
/***/ 9752:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var $BigInt = GetIntrinsic('%BigInt%', true);
var $Number = GetIntrinsic('%Number%');
var $TypeError = __webpack_require__(1642);
var $SyntaxError = __webpack_require__(6724);
var StringToBigInt = __webpack_require__(907);
var ToPrimitive = __webpack_require__(210);
// https://262.ecma-international.org/13.0/#sec-tobigint
module.exports = function ToBigInt(argument) {
if (!$BigInt) {
throw new $SyntaxError('BigInts are not supported in this environment');
}
var prim = ToPrimitive(argument, $Number);
if (prim == null) {
throw new $TypeError('Cannot convert null or undefined to a BigInt');
}
if (typeof prim === 'boolean') {
return prim ? $BigInt(1) : $BigInt(0);
}
if (typeof prim === 'number') {
throw new $TypeError('Cannot convert a Number value to a BigInt');
}
if (typeof prim === 'string') {
var n = StringToBigInt(prim);
if (typeof n === 'undefined') {
throw new $TypeError('Failed to parse String to BigInt');
}
return n;
}
if (typeof prim === 'symbol') {
throw new $TypeError('Cannot convert a Symbol value to a BigInt');
}
if (typeof prim !== 'bigint') {
throw new $SyntaxError('Assertion failed: unknown primitive type');
}
return prim;
};
/***/ }),
/***/ 1242:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var $BigInt = GetIntrinsic('%BigInt%', true);
var $pow = GetIntrinsic('%Math.pow%');
var ToBigInt = __webpack_require__(9752);
var BigIntRemainder = __webpack_require__(6548);
var modBigInt = __webpack_require__(8626);
// BigInt(2**63), but node v10.4-v10.8 have a bug where you can't `BigInt(x)` anything larger than MAX_SAFE_INTEGER
var twoSixtyThree = $BigInt && (BigInt($pow(2, 32)) * BigInt($pow(2, 31)));
// BigInt(2**64), but node v10.4-v10.8 have a bug where you can't `BigInt(x)` anything larger than MAX_SAFE_INTEGER
var twoSixtyFour = $BigInt && (BigInt($pow(2, 32)) * BigInt($pow(2, 32)));
// https://262.ecma-international.org/11.0/#sec-tobigint64
module.exports = function ToBigInt64(argument) {
var n = ToBigInt(argument);
var int64bit = modBigInt(BigIntRemainder, n, twoSixtyFour);
return int64bit >= twoSixtyThree ? int64bit - twoSixtyFour : int64bit;
};
/***/ }),
/***/ 2947:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var $BigInt = GetIntrinsic('%BigInt%', true);
var $pow = GetIntrinsic('%Math.pow%');
var ToBigInt = __webpack_require__(9752);
var BigIntRemainder = __webpack_require__(6548);
var modBigInt = __webpack_require__(8626);
// BigInt(2**64), but node v10.4-v10.8 have a bug where you can't `BigInt(x)` anything larger than MAX_SAFE_INTEGER
var twoSixtyFour = $BigInt && (BigInt($pow(2, 32)) * BigInt($pow(2, 32)));
// https://262.ecma-international.org/11.0/#sec-tobiguint64
module.exports = function ToBigUint64(argument) {
var n = ToBigInt(argument);
var int64bit = modBigInt(BigIntRemainder, n, twoSixtyFour);
return int64bit;
};
/***/ }),
/***/ 6440:
/***/ (function(module) {
"use strict";
// http://262.ecma-international.org/5.1/#sec-9.2
module.exports = function ToBoolean(value) { return !!value; };
/***/ }),
/***/ 3181:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var modulo = __webpack_require__(8457);
var ToNumber = __webpack_require__(3438);
var truncate = __webpack_require__(736);
var isFinite = __webpack_require__(7991);
// https://262.ecma-international.org/14.0/#sec-toint16
var two16 = 0x10000; // Math.pow(2, 16);
module.exports = function ToInt16(argument) {
var number = ToNumber(argument);
if (!isFinite(number) || number === 0) {
return 0;
}
var int = truncate(number);
var int16bit = modulo(int, two16);
return int16bit >= 0x8000 ? int16bit - two16 : int16bit;
};
/***/ }),
/***/ 2587:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var modulo = __webpack_require__(8457);
var ToNumber = __webpack_require__(3438);
var truncate = __webpack_require__(736);
var isFinite = __webpack_require__(7991);
// https://262.ecma-international.org/14.0/#sec-toint32
var two31 = 0x80000000; // Math.pow(2, 31);
var two32 = 0x100000000; // Math.pow(2, 32);
module.exports = function ToInt32(argument) {
var number = ToNumber(argument);
if (!isFinite(number) || number === 0) {
return 0;
}
var int = truncate(number);
var int32bit = modulo(int, two32);
var result = int32bit >= two31 ? int32bit - two32 : int32bit;
return result === 0 ? 0 : result; // in the spec, these are math values, so we filter out -0 here
};
/***/ }),
/***/ 5562:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var modulo = __webpack_require__(8457);
var ToNumber = __webpack_require__(3438);
var truncate = __webpack_require__(736);
var isFinite = __webpack_require__(7991);
// https://262.ecma-international.org/14.0/#sec-toint8
module.exports = function ToInt8(argument) {
var number = ToNumber(argument);
if (!isFinite(number) || number === 0) {
return 0;
}
var int = truncate(number);
var int8bit = modulo(int, 0x100);
return int8bit >= 0x80 ? int8bit - 0x100 : int8bit;
};
/***/ }),
/***/ 2897:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var ToNumber = __webpack_require__(3438);
var truncate = __webpack_require__(736);
var $isNaN = __webpack_require__(9404);
var $isFinite = __webpack_require__(7991);
// https://262.ecma-international.org/14.0/#sec-tointegerorinfinity
module.exports = function ToIntegerOrInfinity(value) {
var number = ToNumber(value);
if ($isNaN(number) || number === 0) { return 0; }
if (!$isFinite(number)) { return number; }
return truncate(number);
};
/***/ }),
/***/ 3438:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var $TypeError = __webpack_require__(1642);
var $Number = GetIntrinsic('%Number%');
var isPrimitive = __webpack_require__(4968);
var ToPrimitive = __webpack_require__(210);
var StringToNumber = __webpack_require__(4967);
// https://262.ecma-international.org/13.0/#sec-tonumber
module.exports = function ToNumber(argument) {
var value = isPrimitive(argument) ? argument : ToPrimitive(argument, $Number);
if (typeof value === 'symbol') {
throw new $TypeError('Cannot convert a Symbol value to a number');
}
if (typeof value === 'bigint') {
throw new $TypeError('Conversion from \'BigInt\' to \'number\' is not allowed.');
}
if (typeof value === 'string') {
return StringToNumber(value);
}
return $Number(value);
};
/***/ }),
/***/ 210:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var toPrimitive = __webpack_require__(5249);
// https://262.ecma-international.org/6.0/#sec-toprimitive
module.exports = function ToPrimitive(input) {
if (arguments.length > 1) {
return toPrimitive(input, arguments[1]);
}
return toPrimitive(input);
};
/***/ }),
/***/ 8110:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var hasOwn = __webpack_require__(9429);
var $TypeError = __webpack_require__(1642);
var Type = __webpack_require__(9655);
var ToBoolean = __webpack_require__(6440);
var IsCallable = __webpack_require__(3071);
// https://262.ecma-international.org/5.1/#sec-8.10.5
module.exports = function ToPropertyDescriptor(Obj) {
if (Type(Obj) !== 'Object') {
throw new $TypeError('ToPropertyDescriptor requires an object');
}
var desc = {};
if (hasOwn(Obj, 'enumerable')) {
desc['[[Enumerable]]'] = ToBoolean(Obj.enumerable);
}
if (hasOwn(Obj, 'configurable')) {
desc['[[Configurable]]'] = ToBoolean(Obj.configurable);
}
if (hasOwn(Obj, 'value')) {
desc['[[Value]]'] = Obj.value;
}
if (hasOwn(Obj, 'writable')) {
desc['[[Writable]]'] = ToBoolean(Obj.writable);
}
if (hasOwn(Obj, 'get')) {
var getter = Obj.get;
if (typeof getter !== 'undefined' && !IsCallable(getter)) {
throw new $TypeError('getter must be a function');
}
desc['[[Get]]'] = getter;
}
if (hasOwn(Obj, 'set')) {
var setter = Obj.set;
if (typeof setter !== 'undefined' && !IsCallable(setter)) {
throw new $TypeError('setter must be a function');
}
desc['[[Set]]'] = setter;
}
if ((hasOwn(desc, '[[Get]]') || hasOwn(desc, '[[Set]]')) && (hasOwn(desc, '[[Value]]') || hasOwn(desc, '[[Writable]]'))) {
throw new $TypeError('Invalid property descriptor. Cannot both specify accessors and a value or writable attribute');
}
return desc;
};
/***/ }),
/***/ 7249:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var $String = GetIntrinsic('%String%');
var $TypeError = __webpack_require__(1642);
// https://262.ecma-international.org/6.0/#sec-tostring
module.exports = function ToString(argument) {
if (typeof argument === 'symbol') {
throw new $TypeError('Cannot convert a Symbol value to a string');
}
return $String(argument);
};
/***/ }),
/***/ 5465:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var modulo = __webpack_require__(8457);
var ToNumber = __webpack_require__(3438);
var truncate = __webpack_require__(736);
var isFinite = __webpack_require__(7991);
// https://262.ecma-international.org/14.0/#sec-touint16
var two16 = 0x10000; // Math.pow(2, 16)
module.exports = function ToUint16(argument) {
var number = ToNumber(argument);
if (!isFinite(number) || number === 0) {
return 0;
}
var int = truncate(number);
var int16bit = modulo(int, two16);
return int16bit === 0 ? 0 : int16bit; // in the spec, these are math values, so we filter out -0 here
};
/***/ }),
/***/ 5964:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var modulo = __webpack_require__(8457);
var ToNumber = __webpack_require__(3438);
var truncate = __webpack_require__(736);
var isFinite = __webpack_require__(7991);
// https://262.ecma-international.org/14.0/#sec-touint32
var two32 = 0x100000000; // Math.pow(2, 32);
module.exports = function ToUint32(argument) {
var number = ToNumber(argument);
if (!isFinite(number) || number === 0) {
return 0;
}
var int = truncate(number);
var int32bit = modulo(int, two32);
return int32bit === 0 ? 0 : int32bit; // in the spec, these are math values, so we filter out -0 here
};
/***/ }),
/***/ 9496:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isFinite = __webpack_require__(7991);
var modulo = __webpack_require__(8457);
var ToNumber = __webpack_require__(3438);
var truncate = __webpack_require__(736);
// https://262.ecma-international.org/14.0/#sec-touint8
module.exports = function ToUint8(argument) {
var number = ToNumber(argument);
if (!isFinite(number) || number === 0) {
return 0;
}
var int = truncate(number);
var int8bit = modulo(int, 0x100);
return int8bit;
};
/***/ }),
/***/ 6550:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var clamp = __webpack_require__(3832);
var ToNumber = __webpack_require__(3438);
var floor = __webpack_require__(3473);
var $isNaN = __webpack_require__(9404);
// https://262.ecma-international.org/15.0/#sec-touint8clamp
module.exports = function ToUint8Clamp(argument) {
var number = ToNumber(argument); // step 1
if ($isNaN(number)) { return 0; } // step 2
var clamped = clamp(number, 0, 255); // step 4
var f = floor(clamped); // step 5
if (clamped < (f + 0.5)) { return f; } // step 6
if (clamped > (f + 0.5)) { return f + 1; } // step 7
return f % 2 === 0 ? f : f + 1; // step 8
};
/***/ }),
/***/ 9655:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var ES5Type = __webpack_require__(1528);
// https://262.ecma-international.org/11.0/#sec-ecmascript-data-types-and-values
module.exports = function Type(x) {
if (typeof x === 'symbol') {
return 'Symbol';
}
if (typeof x === 'bigint') {
return 'BigInt';
}
return ES5Type(x);
};
/***/ }),
/***/ 7265:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $SyntaxError = __webpack_require__(6724);
var $TypeError = __webpack_require__(1642);
var IsArray = __webpack_require__(2985);
var IsConstructor = __webpack_require__(7010);
var IsTypedArrayOutOfBounds = __webpack_require__(9954);
var TypedArrayLength = __webpack_require__(8921);
var ValidateTypedArray = __webpack_require__(3842);
var availableTypedArrays = __webpack_require__(4343)();
// https://262.ecma-international.org/15.0/#typedarraycreatefromconstructor
module.exports = function TypedArrayCreateFromConstructor(constructor, argumentList) {
if (!IsConstructor(constructor)) {
throw new $TypeError('Assertion failed: `constructor` must be a constructor');
}
if (!IsArray(argumentList)) {
throw new $TypeError('Assertion failed: `argumentList` must be a List');
}
if (availableTypedArrays.length === 0) {
throw new $SyntaxError('Assertion failed: Typed Arrays are not supported in this environment');
}
// var newTypedArray = Construct(constructor, argumentList); // step 1
var newTypedArray;
if (argumentList.length === 0) {
newTypedArray = new constructor();
} else if (argumentList.length === 1) {
newTypedArray = new constructor(argumentList[0]);
} else if (argumentList.length === 2) {
newTypedArray = new constructor(argumentList[0], argumentList[1]);
} else {
newTypedArray = new constructor(argumentList[0], argumentList[1], argumentList[2]);
}
var taRecord = ValidateTypedArray(newTypedArray, 'SEQ-CST'); // step 2
if (argumentList.length === 1 && typeof argumentList[0] === 'number') { // step 3
if (IsTypedArrayOutOfBounds(taRecord)) {
throw new $TypeError('new Typed Array is out of bounds'); // step 3.a
}
var length = TypedArrayLength(taRecord); // step 3.b
if (length < argumentList[0]) {
throw new $TypeError('`argumentList[0]` must be <= `newTypedArray.length`'); // step 3.c
}
}
return newTypedArray; // step 4
};
/***/ }),
/***/ 9149:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $SyntaxError = __webpack_require__(6724);
var $TypeError = __webpack_require__(1642);
var isInteger = __webpack_require__(6156);
var whichTypedArray = __webpack_require__(4010);
// https://262.ecma-international.org/13.0/#sec-typedarrayelementsize
var tableTAO = __webpack_require__(2170);
module.exports = function TypedArrayElementSize(O) {
var type = whichTypedArray(O);
if (type === false) {
throw new $TypeError('Assertion failed: `O` must be a TypedArray');
}
var size = tableTAO.size['$' + tableTAO.name['$' + type]];
if (!isInteger(size) || size < 0) {
throw new $SyntaxError('Assertion failed: Unknown TypedArray type `' + type + '`');
}
return size;
};
/***/ }),
/***/ 1586:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $SyntaxError = __webpack_require__(6724);
var $TypeError = __webpack_require__(1642);
var whichTypedArray = __webpack_require__(4010);
// https://262.ecma-international.org/15.0/#sec-typedarrayelementtype
var tableTAO = __webpack_require__(2170);
module.exports = function TypedArrayElementType(O) {
var type = whichTypedArray(O);
if (type === false) {
throw new $TypeError('Assertion failed: `O` must be a TypedArray');
}
var result = tableTAO.name['$' + type];
if (typeof result !== 'string') {
throw new $SyntaxError('Assertion failed: Unknown TypedArray type `' + type + '`');
}
return result;
};
/***/ }),
/***/ 8921:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $TypeError = __webpack_require__(1642);
var floor = __webpack_require__(3473);
var IsFixedLengthArrayBuffer = __webpack_require__(9442);
var IsTypedArrayOutOfBounds = __webpack_require__(9954);
var TypedArrayElementSize = __webpack_require__(9149);
var isTypedArrayWithBufferWitnessRecord = __webpack_require__(359);
var typedArrayBuffer = __webpack_require__(6740);
var typedArrayByteOffset = __webpack_require__(7046);
var typedArrayLength = __webpack_require__(8150);
// http://www.ecma-international.org/ecma-262/15.0/#sec-typedarraylength
module.exports = function TypedArrayLength(taRecord) {
if (!isTypedArrayWithBufferWitnessRecord(taRecord)) {
throw new $TypeError('Assertion failed: `taRecord` must be a TypedArray With Buffer Witness Record');
}
if (IsTypedArrayOutOfBounds(taRecord)) {
throw new $TypeError('Assertion failed: `taRecord` is out of bounds'); // step 1
}
var O = taRecord['[[Object]]']; // step 2
var length = typedArrayLength(O);
if (length !== 'AUTO') {
return length; // step 3
}
if (IsFixedLengthArrayBuffer(typedArrayBuffer(O))) {
throw new $TypeError('Assertion failed: array buffer is not fixed length'); // step 4
}
var byteOffset = typedArrayByteOffset(O); // step 5
var elementSize = TypedArrayElementSize(O); // step 6
var byteLength = taRecord['[[CachedBufferByteLength]]']; // step 7
if (byteLength === 'DETACHED') {
throw new $TypeError('Assertion failed: typed array is detached'); // step 8
}
return floor((byteLength - byteOffset) / elementSize); // step 9
};
/***/ }),
/***/ 817:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $SyntaxError = __webpack_require__(6724);
var $TypeError = __webpack_require__(1642);
var whichTypedArray = __webpack_require__(4010);
var availableTypedArrays = __webpack_require__(4343)();
var IsArray = __webpack_require__(2985);
var SpeciesConstructor = __webpack_require__(5994);
var TypedArrayCreateFromConstructor = __webpack_require__(7265);
var getConstructor = __webpack_require__(9660);
// https://262.ecma-international.org/15.0/#typedarray-species-create
module.exports = function TypedArraySpeciesCreate(exemplar, argumentList) {
if (availableTypedArrays.length === 0) {
throw new $SyntaxError('Assertion failed: Typed Arrays are not supported in this environment');
}
var kind = whichTypedArray(exemplar);
if (!kind) {
throw new $TypeError('Assertion failed: exemplar must be a TypedArray'); // step 1
}
if (!IsArray(argumentList)) {
throw new $TypeError('Assertion failed: `argumentList` must be a List'); // step 1
}
var defaultConstructor = getConstructor(kind); // step 2
if (typeof defaultConstructor !== 'function') {
throw new $SyntaxError('Assertion failed: `constructor` of `exemplar` (' + kind + ') must exist. Please report this!');
}
var constructor = SpeciesConstructor(exemplar, defaultConstructor); // step 3
return TypedArrayCreateFromConstructor(constructor, argumentList); // step 4
};
/***/ }),
/***/ 3842:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $TypeError = __webpack_require__(1642);
var IsTypedArrayOutOfBounds = __webpack_require__(9954);
var MakeTypedArrayWithBufferWitnessRecord = __webpack_require__(6005);
var Type = __webpack_require__(9655);
var isTypedArray = __webpack_require__(2527);
// https://262.ecma-international.org/15.0/#sec-validatetypedarray
module.exports = function ValidateTypedArray(O, order) {
if (order !== 'SEQ-CST' && order !== 'UNORDERED') {
throw new $TypeError('Assertion failed: `order` must be ~SEQ-CST~ or ~UNORDERED~');
}
if (Type(O) !== 'Object') {
throw new $TypeError('Assertion failed: `O` must be an Object'); // step 1
}
if (!isTypedArray(O)) {
throw new $TypeError('Assertion failed: `O` must be a Typed Array'); // steps 1 - 2
}
var taRecord = MakeTypedArrayWithBufferWitnessRecord(O, order); // step 3
if (IsTypedArrayOutOfBounds(taRecord)) {
throw new $TypeError('`O` must be in-bounds and backed by a non-detached buffer'); // step 4
}
return taRecord; // step 5
};
/***/ }),
/***/ 3832:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var $TypeError = __webpack_require__(1642);
var max = GetIntrinsic('%Math.max%');
var min = GetIntrinsic('%Math.min%');
// https://262.ecma-international.org/12.0/#clamping
module.exports = function clamp(x, lower, upper) {
if (typeof x !== 'number' || typeof lower !== 'number' || typeof upper !== 'number' || !(lower <= upper)) {
throw new $TypeError('Assertion failed: all three arguments must be MVs, and `lower` must be `<= upper`');
}
return min(max(lower, x), upper);
};
/***/ }),
/***/ 3473:
/***/ (function(module) {
"use strict";
// var modulo = require('./modulo');
var $floor = Math.floor;
// http://262.ecma-international.org/11.0/#eqn-floor
module.exports = function floor(x) {
// return x - modulo(x, 1);
if (typeof x === 'bigint') {
return x;
}
return $floor(x);
};
/***/ }),
/***/ 1367:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
// https://262.ecma-international.org/6.0/#sec-algorithm-conventions
module.exports = GetIntrinsic('%Math.max%');
/***/ }),
/***/ 2967:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
// https://262.ecma-international.org/6.0/#sec-algorithm-conventions
module.exports = GetIntrinsic('%Math.min%');
/***/ }),
/***/ 8457:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var mod = __webpack_require__(2076);
// https://262.ecma-international.org/5.1/#sec-5.2
module.exports = function modulo(x, y) {
return mod(x, y);
};
/***/ }),
/***/ 2170:
/***/ (function(module) {
"use strict";
// https://262.ecma-international.org/15.0/#table-the-typedarray-constructors
module.exports = {
__proto__: null,
name: {
__proto__: null,
$Int8Array: 'INT8',
$Uint8Array: 'UINT8',
$Uint8ClampedArray: 'UINT8C',
$Int16Array: 'INT16',
$Uint16Array: 'UINT16',
$Int32Array: 'INT32',
$Uint32Array: 'UINT32',
$BigInt64Array: 'BIGINT64',
$BigUint64Array: 'BIGUINT64',
$Float32Array: 'FLOAT32',
$Float64Array: 'FLOAT64'
},
size: {
__proto__: null,
$INT8: 1,
$UINT8: 1,
$UINT8C: 1,
$INT16: 2,
$UINT16: 2,
$INT32: 4,
$UINT32: 4,
$BIGINT64: 8,
$BIGUINT64: 8,
$FLOAT32: 4,
$FLOAT64: 8
}
};
/***/ }),
/***/ 736:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var floor = __webpack_require__(3473);
var $TypeError = __webpack_require__(1642);
// https://262.ecma-international.org/14.0/#eqn-truncate
module.exports = function truncate(x) {
if (typeof x !== 'number' && typeof x !== 'bigint') {
throw new $TypeError('argument must be a Number or a BigInt');
}
var result = x < 0 ? -floor(-x) : floor(x);
return result === 0 ? 0 : result; // in the spec, these are math values, so we filter out -0 here
};
/***/ }),
/***/ 1528:
/***/ (function(module) {
"use strict";
// https://262.ecma-international.org/5.1/#sec-8
module.exports = function Type(x) {
if (x === null) {
return 'Null';
}
if (typeof x === 'undefined') {
return 'Undefined';
}
if (typeof x === 'function' || typeof x === 'object') {
return 'Object';
}
if (typeof x === 'number') {
return 'Number';
}
if (typeof x === 'boolean') {
return 'Boolean';
}
if (typeof x === 'string') {
return 'String';
}
};
/***/ }),
/***/ 4342:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
// TODO: remove, semver-major
module.exports = __webpack_require__(682);
/***/ }),
/***/ 208:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var hasPropertyDescriptors = __webpack_require__(8198);
var $defineProperty = __webpack_require__(8918);
var hasArrayLengthDefineBug = hasPropertyDescriptors.hasArrayLengthDefineBug();
// eslint-disable-next-line global-require
var isArray = hasArrayLengthDefineBug && __webpack_require__(692);
var callBound = __webpack_require__(1154);
var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable');
// eslint-disable-next-line max-params
module.exports = function DefineOwnProperty(IsDataDescriptor, SameValue, FromPropertyDescriptor, O, P, desc) {
if (!$defineProperty) {
if (!IsDataDescriptor(desc)) {
// ES3 does not support getters/setters
return false;
}
if (!desc['[[Configurable]]'] || !desc['[[Writable]]']) {
return false;
}
// fallback for ES3
if (P in O && $isEnumerable(O, P) !== !!desc['[[Enumerable]]']) {
// a non-enumerable existing property
return false;
}
// property does not exist at all, or exists but is enumerable
var V = desc['[[Value]]'];
// eslint-disable-next-line no-param-reassign
O[P] = V; // will use [[Define]]
return SameValue(O[P], V);
}
if (
hasArrayLengthDefineBug
&& P === 'length'
&& '[[Value]]' in desc
&& isArray(O)
&& O.length !== desc['[[Value]]']
) {
// eslint-disable-next-line no-param-reassign
O.length = desc['[[Value]]'];
return O.length === desc['[[Value]]'];
}
$defineProperty(O, P, FromPropertyDescriptor(desc));
return true;
};
/***/ }),
/***/ 692:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var $Array = GetIntrinsic('%Array%');
// eslint-disable-next-line global-require
var toStr = !$Array.isArray && __webpack_require__(1154)('Object.prototype.toString');
module.exports = $Array.isArray || function IsArray(argument) {
return toStr(argument) === '[object Array]';
};
/***/ }),
/***/ 8727:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var $pow = GetIntrinsic('%Math.pow%');
module.exports = function bytesAsFloat32(rawBytes) {
// return new $Float32Array(new $Uint8Array(rawBytes).buffer)[0];
/*
Let value be the byte elements of rawBytes concatenated and interpreted as a little-endian bit string encoding of an IEEE 754-2008 binary32 value.
If value is an IEEE 754-2008 binary32 NaN value, return the NaN Number value.
Return the Number value that corresponds to value.
*/
var sign = rawBytes[3] & 0x80 ? -1 : 1; // Check the sign bit
var exponent = ((rawBytes[3] & 0x7F) << 1)
| (rawBytes[2] >> 7); // Combine bits for exponent
var mantissa = ((rawBytes[2] & 0x7F) << 16)
| (rawBytes[1] << 8)
| rawBytes[0]; // Combine bits for mantissa
if (exponent === 0 && mantissa === 0) {
return sign === 1 ? 0 : -0;
}
if (exponent === 0xFF && mantissa === 0) {
return sign === 1 ? Infinity : -Infinity;
}
if (exponent === 0xFF && mantissa !== 0) {
return NaN;
}
exponent -= 127; // subtract the bias
if (exponent === -127) {
return sign * mantissa * $pow(2, -126 - 23);
}
return sign * (1 + (mantissa * $pow(2, -23))) * $pow(2, exponent);
};
/***/ }),
/***/ 7604:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var $pow = GetIntrinsic('%Math.pow%');
module.exports = function bytesAsFloat64(rawBytes) {
// return new $Float64Array(new $Uint8Array(rawBytes).buffer)[0];
/*
Let value be the byte elements of rawBytes concatenated and interpreted as a little-endian bit string encoding of an IEEE 754-2008 binary64 value.
If value is an IEEE 754-2008 binary64 NaN value, return the NaN Number value.
Return the Number value that corresponds to value.
*/
var sign = rawBytes[7] & 0x80 ? -1 : 1; // first bit
var exponent = ((rawBytes[7] & 0x7F) << 4) // 7 bits from index 7
| ((rawBytes[6] & 0xF0) >> 4); // 4 bits from index 6
var mantissa = ((rawBytes[6] & 0x0F) * 0x1000000000000) // 4 bits from index 6
+ (rawBytes[5] * 0x10000000000) // 8 bits from index 5
+ (rawBytes[4] * 0x100000000) // 8 bits from index 4
+ (rawBytes[3] * 0x1000000) // 8 bits from index 3
+ (rawBytes[2] * 0x10000) // 8 bits from index 2
+ (rawBytes[1] * 0x100) // 8 bits from index 1
+ rawBytes[0]; // 8 bits from index 0
if (exponent === 0 && mantissa === 0) {
return sign * 0;
}
if (exponent === 0x7FF && mantissa !== 0) {
return NaN;
}
if (exponent === 0x7FF && mantissa === 0) {
return sign * Infinity;
}
exponent -= 1023; // subtract the bias
// Handle subnormal numbers
if (exponent === -1023) {
return sign * mantissa * 5e-324; // $pow(2, -1022 - 52)
}
return sign * (1 + (mantissa / 0x10000000000000)) * $pow(2, exponent);
};
/***/ }),
/***/ 2367:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var $pow = GetIntrinsic('%Math.pow%');
var $Number = GetIntrinsic('%Number%');
var $BigInt = GetIntrinsic('%BigInt%', true);
module.exports = function bytesAsInteger(rawBytes, elementSize, isUnsigned, isBigInt) {
var Z = isBigInt ? $BigInt : $Number;
// this is common to both branches
var intValue = Z(0);
for (var i = 0; i < rawBytes.length; i++) {
intValue += Z(rawBytes[i] * $pow(2, 8 * i));
}
/*
Let intValue be the byte elements of rawBytes concatenated and interpreted as a bit string encoding of an unsigned little-endian binary number.
*/
if (!isUnsigned) { // steps 5-6
// Let intValue be the byte elements of rawBytes concatenated and interpreted as a bit string encoding of a binary little-endian 2's complement number of bit length elementSize × 8.
var bitLength = elementSize * 8;
if (rawBytes[elementSize - 1] & 0x80) {
intValue -= Z($pow(2, bitLength));
}
}
return intValue; // step 7
};
/***/ }),
/***/ 2142:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var $Uint8Array = GetIntrinsic('%Uint8Array%', true);
var $Uint32Array = GetIntrinsic('%Uint32Array%', true);
var typedArrayBuffer = __webpack_require__(6740);
var uInt32 = $Uint32Array && new $Uint32Array([0x12345678]);
var uInt8 = uInt32 && new $Uint8Array(typedArrayBuffer(uInt32));
module.exports = uInt8
? uInt8[0] === 0x78
? 'little'
: uInt8[0] === 0x12
? 'big'
: uInt8[0] === 0x34
? 'mixed' // https://developer.mozilla.org/en-US/docs/Glossary/Endianness
: 'unknown' // ???
: 'indeterminate'; // no way to know
/***/ }),
/***/ 8172:
/***/ (function(module) {
"use strict";
module.exports = function every(array, predicate) {
for (var i = 0; i < array.length; i += 1) {
if (!predicate(array[i], i, array)) {
return false;
}
}
return true;
};
/***/ }),
/***/ 9065:
/***/ (function(module) {
"use strict";
module.exports = function forEach(array, callback) {
for (var i = 0; i < array.length; i += 1) {
callback(array[i], i, array); // eslint-disable-line callback-return
}
};
/***/ }),
/***/ 1211:
/***/ (function(module) {
"use strict";
var MAX_ITER = 1075; // 1023+52 (subnormals) => BIAS+NUM_SIGNFICAND_BITS-1
var maxBits = 54; // only 53 bits for fraction
module.exports = function fractionToBitString(x) {
var str = '';
if (x === 0) {
return str;
}
var j = MAX_ITER;
var y;
// Each time we multiply by 2 and find a ones digit, add a '1'; otherwise, add a '0'..
for (var i = 0; i < MAX_ITER; i += 1) {
y = x * 2;
if (y >= 1) {
x = y - 1; // eslint-disable-line no-param-reassign
str += '1';
if (j === MAX_ITER) {
j = i; // first 1
}
} else {
x = y; // eslint-disable-line no-param-reassign
str += '0';
}
// Stop when we have no more decimals to process or in the event we found a fraction which cannot be represented in a finite number of bits...
if (y === 1 || i - j > maxBits) {
return str;
}
}
return str;
};
/***/ }),
/***/ 2646:
/***/ (function(module) {
"use strict";
module.exports = function fromPropertyDescriptor(Desc) {
if (typeof Desc === 'undefined') {
return Desc;
}
var obj = {};
if ('[[Value]]' in Desc) {
obj.value = Desc['[[Value]]'];
}
if ('[[Writable]]' in Desc) {
obj.writable = !!Desc['[[Writable]]'];
}
if ('[[Get]]' in Desc) {
obj.get = Desc['[[Get]]'];
}
if ('[[Set]]' in Desc) {
obj.set = Desc['[[Set]]'];
}
if ('[[Enumerable]]' in Desc) {
obj.enumerable = !!Desc['[[Enumerable]]'];
}
if ('[[Configurable]]' in Desc) {
obj.configurable = !!Desc['[[Configurable]]'];
}
return obj;
};
/***/ }),
/***/ 9495:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var originalGetProto = GetIntrinsic('%Object.getPrototypeOf%', true);
var hasProto = __webpack_require__(1856)();
module.exports = originalGetProto || (
hasProto
? function (O) {
return O.__proto__; // eslint-disable-line no-proto
}
: null
);
/***/ }),
/***/ 20:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var $floor = GetIntrinsic('%Math.floor%');
// https://runestone.academy/ns/books/published/pythonds/BasicDS/ConvertingDecimalNumberstoBinaryNumbers.html#:~:text=The%20Divide%20by%202%20algorithm,have%20a%20remainder%20of%200
module.exports = function intToBinaryString(x) {
var str = '';
var y;
while (x > 0) {
y = x / 2;
x = $floor(y); // eslint-disable-line no-param-reassign
if (y === x) {
str = '0' + str;
} else {
str = '1' + str;
}
}
return str;
};
/***/ }),
/***/ 1520:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var $Number = GetIntrinsic('%Number%');
var $BigInt = GetIntrinsic('%BigInt%', true);
module.exports = function integerToNBytes(intValue, n, isLittleEndian) {
var Z = typeof intValue === 'bigint' ? $BigInt : $Number;
/*
if (intValue >= 0) { // step 3.d
// Let rawBytes be a List containing the n-byte binary encoding of intValue. If isLittleEndian is false, the bytes are ordered in big endian order. Otherwise, the bytes are ordered in little endian order.
} else { // step 3.e
// Let rawBytes be a List containing the n-byte binary 2's complement encoding of intValue. If isLittleEndian is false, the bytes are ordered in big endian order. Otherwise, the bytes are ordered in little endian order.
}
*/
if (intValue < 0) {
intValue >>>= 0; // eslint-disable-line no-param-reassign
}
var rawBytes = [];
for (var i = 0; i < n; i++) {
rawBytes[isLittleEndian ? i : n - 1 - i] = $Number(intValue & Z(0xFF));
intValue >>= Z(8); // eslint-disable-line no-param-reassign
}
return rawBytes; // step 4
};
/***/ }),
/***/ 1824:
/***/ (function(module) {
"use strict";
module.exports = function isByteValue(value) {
return typeof value === 'number' && value >= 0 && value <= 255 && (value | 0) === value;
};
/***/ }),
/***/ 7991:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $isNaN = __webpack_require__(9404);
module.exports = function (x) { return (typeof x === 'number' || typeof x === 'bigint') && !$isNaN(x) && x !== Infinity && x !== -Infinity; };
/***/ }),
/***/ 6156:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var $abs = GetIntrinsic('%Math.abs%');
var $floor = GetIntrinsic('%Math.floor%');
var $isNaN = __webpack_require__(9404);
var $isFinite = __webpack_require__(7991);
module.exports = function isInteger(argument) {
if (typeof argument !== 'number' || $isNaN(argument) || !$isFinite(argument)) {
return false;
}
var absValue = $abs(argument);
return $floor(absValue) === absValue;
};
/***/ }),
/***/ 9404:
/***/ (function(module) {
"use strict";
module.exports = Number.isNaN || function isNaN(a) {
return a !== a;
};
/***/ }),
/***/ 2745:
/***/ (function(module) {
"use strict";
module.exports = function isNegativeZero(x) {
return x === 0 && 1 / x === 1 / -0;
};
/***/ }),
/***/ 4968:
/***/ (function(module) {
"use strict";
module.exports = function isPrimitive(value) {
return value === null || (typeof value !== 'function' && typeof value !== 'object');
};
/***/ }),
/***/ 2076:
/***/ (function(module) {
"use strict";
var $floor = Math.floor;
module.exports = function mod(number, modulo) {
var remain = number % modulo;
return $floor(remain >= 0 ? remain : remain + modulo);
};
/***/ }),
/***/ 8626:
/***/ (function(module) {
"use strict";
module.exports = function bigIntMod(BigIntRemainder, bigint, modulo) {
var remain = BigIntRemainder(bigint, modulo);
return remain >= 0 ? remain : remain + modulo;
};
/***/ }),
/***/ 6862:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var $TypeError = __webpack_require__(1642);
var hasOwn = __webpack_require__(9429);
var allowed = {
__proto__: null,
'[[Configurable]]': true,
'[[Enumerable]]': true,
'[[Get]]': true,
'[[Set]]': true,
'[[Value]]': true,
'[[Writable]]': true
};
// https://262.ecma-international.org/6.0/#sec-property-descriptor-specification-type
module.exports = function isPropertyDescriptor(Desc) {
if (!Desc || typeof Desc !== 'object') {
return false;
}
for (var key in Desc) { // eslint-disable-line
if (hasOwn(Desc, key) && !allowed[key]) {
return false;
}
}
var isData = hasOwn(Desc, '[[Value]]') || hasOwn(Desc, '[[Writable]]');
var IsAccessor = hasOwn(Desc, '[[Get]]') || hasOwn(Desc, '[[Set]]');
if (isData && IsAccessor) {
throw new $TypeError('Property Descriptors may not be both accessor and data descriptors');
}
return true;
};
/***/ }),
/***/ 359:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var hasOwn = __webpack_require__(9429);
var isTypedArray = __webpack_require__(2527);
var isInteger = __webpack_require__(6156);
module.exports = function isTypedArrayWithBufferWitnessRecord(value) {
return !!value
&& typeof value === 'object'
&& hasOwn(value, '[[Object]]')
&& hasOwn(value, '[[CachedBufferByteLength]]')
&& (
(isInteger(value['[[CachedBufferByteLength]]']) && value['[[CachedBufferByteLength]]'] >= 0)
|| value['[[CachedBufferByteLength]]'] === 'DETACHED'
)
&& isTypedArray(value['[[Object]]']);
};
/***/ }),
/***/ 9660:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var constructors = {
__proto__: null,
$Int8Array: GetIntrinsic('%Int8Array%', true),
$Uint8Array: GetIntrinsic('%Uint8Array%', true),
$Uint8ClampedArray: GetIntrinsic('%Uint8ClampedArray%', true),
$Int16Array: GetIntrinsic('%Int16Array%', true),
$Uint16Array: GetIntrinsic('%Uint16Array%', true),
$Int32Array: GetIntrinsic('%Int32Array%', true),
$Uint32Array: GetIntrinsic('%Uint32Array%', true),
$BigInt64Array: GetIntrinsic('%BigInt64Array%', true),
$BigUint64Array: GetIntrinsic('%BigUint64Array%', true),
$Float32Array: GetIntrinsic('%Float32Array%', true),
$Float64Array: GetIntrinsic('%Float64Array%', true)
};
module.exports = function getConstructor(kind) {
return constructors['$' + kind];
};
/***/ }),
/***/ 3647:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var $abs = GetIntrinsic('%Math.abs%');
var $floor = GetIntrinsic('%Math.floor%');
var $pow = GetIntrinsic('%Math.pow%');
var isFinite = __webpack_require__(7991);
var isNaN = __webpack_require__(9404);
var isNegativeZero = __webpack_require__(2745);
var maxFiniteFloat32 = 3.4028234663852886e+38; // roughly 2 ** 128 - 1
module.exports = function valueToFloat32Bytes(value, isLittleEndian) {
if (isNaN(value)) {
return isLittleEndian ? [0, 0, 192, 127] : [127, 192, 0, 0]; // hardcoded
}
var leastSig;
if (value === 0) {
leastSig = isNegativeZero(value) ? 0x80 : 0;
return isLittleEndian ? [0, 0, 0, leastSig] : [leastSig, 0, 0, 0];
}
if ($abs(value) > maxFiniteFloat32 || !isFinite(value)) {
leastSig = value < 0 ? 255 : 127;
return isLittleEndian ? [0, 0, 128, leastSig] : [leastSig, 128, 0, 0];
}
var sign = value < 0 ? 1 : 0;
value = $abs(value); // eslint-disable-line no-param-reassign
var exponent = 0;
while (value >= 2) {
exponent += 1;
value /= 2; // eslint-disable-line no-param-reassign
}
while (value < 1) {
exponent -= 1;
value *= 2; // eslint-disable-line no-param-reassign
}
var mantissa = value - 1;
mantissa *= $pow(2, 23) + 0.5;
mantissa = $floor(mantissa);
exponent += 127;
exponent <<= 23;
var result = (sign << 31)
| exponent
| mantissa;
var byte0 = result & 255;
result >>= 8;
var byte1 = result & 255;
result >>= 8;
var byte2 = result & 255;
result >>= 8;
var byte3 = result & 255;
if (isLittleEndian) {
return [byte0, byte1, byte2, byte3];
}
return [byte3, byte2, byte1, byte0];
};
/***/ }),
/***/ 7511:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(682);
var $parseInt = GetIntrinsic('%parseInt%');
var $abs = GetIntrinsic('%Math.abs%');
var $floor = GetIntrinsic('%Math.floor%');
var callBound = __webpack_require__(1154);
var $strIndexOf = callBound('String.prototype.indexOf');
var $strSlice = callBound('String.prototype.slice');
var fractionToBitString = __webpack_require__(1211);
var intToBinString = __webpack_require__(20);
var isNegativeZero = __webpack_require__(2745);
var float64bias = 1023;
var elevenOnes = '11111111111';
var elevenZeroes = '00000000000';
var fiftyOneZeroes = elevenZeroes + elevenZeroes + elevenZeroes + elevenZeroes + '0000000';
// IEEE 754-1985
module.exports = function valueToFloat64Bytes(value, isLittleEndian) {
var signBit = value < 0 || isNegativeZero(value) ? '1' : '0';
var exponentBits;
var significandBits;
if (isNaN(value)) {
exponentBits = elevenOnes;
significandBits = '1' + fiftyOneZeroes;
} else if (!isFinite(value)) {
exponentBits = elevenOnes;
significandBits = '0' + fiftyOneZeroes;
} else if (value === 0) {
exponentBits = elevenZeroes;
significandBits = '0' + fiftyOneZeroes;
} else {
value = $abs(value); // eslint-disable-line no-param-reassign
// Isolate the integer part (digits before the decimal):
var integerPart = $floor(value);
var intBinString = intToBinString(integerPart); // bit string for integer part
var fracBinString = fractionToBitString(value - integerPart); // bit string for fractional part
var numberOfBits;
// find exponent needed to normalize integer+fractional parts
if (intBinString) {
exponentBits = intBinString.length - 1; // move the decimal to the left
} else {
var first1 = $strIndexOf(fracBinString, '1');
if (first1 > -1) {
numberOfBits = first1 + 1;
}
exponentBits = -numberOfBits; // move the decimal to the right
}
significandBits = intBinString + fracBinString;
if (exponentBits < 0) {
// subnormals
if (exponentBits <= -float64bias) {
numberOfBits = float64bias - 1; // limit number of removed bits
}
significandBits = $strSlice(significandBits, numberOfBits); // remove all leading 0s and the first 1 for normal values; for subnormals, remove up to `float64bias - 1` leading bits
} else {
significandBits = $strSlice(significandBits, 1); // remove the leading '1' (implicit/hidden bit)
}
exponentBits = $strSlice(elevenZeroes + intToBinString(exponentBits + float64bias), -11); // Convert the exponent to a bit string
significandBits = $strSlice(significandBits + fiftyOneZeroes + '0', 0, 52); // fill in any trailing zeros and ensure we have only 52 fraction bits
}
var bits = signBit + exponentBits + significandBits;
var rawBytes = [];
for (var i = 0; i < 8; i++) {
var targetIndex = isLittleEndian ? 8 - i - 1 : i;
rawBytes[targetIndex] = $parseInt($strSlice(bits, i * 8, (i + 1) * 8), 2);
}
return rawBytes;
};
/***/ })
/******/ });
/************************************************************************/
/******/ // 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].call(module.exports, 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/global */
/******/ !function() {
/******/ __webpack_require__.g = (function() {
/******/ if (typeof globalThis === 'object') return globalThis;
/******/ try {
/******/ return this || new Function('return this')();
/******/ } catch (e) {
/******/ if (typeof window === 'object') return window;
/******/ }
/******/ })();
/******/ }();
/******/
/******/ /* 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 in strict mode.
!function() {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"AlignmentControl": function() { return /* reexport */ AlignmentControl; },
"AlignmentToolbar": function() { return /* reexport */ AlignmentToolbar; },
"Autocomplete": function() { return /* reexport */ autocomplete; },
"BlockAlignmentControl": function() { return /* reexport */ BlockAlignmentControl; },
"BlockAlignmentToolbar": function() { return /* reexport */ BlockAlignmentToolbar; },
"BlockBreadcrumb": function() { return /* reexport */ block_breadcrumb; },
"BlockColorsStyleSelector": function() { return /* reexport */ color_style_selector; },
"BlockContextProvider": function() { return /* reexport */ BlockContextProvider; },
"BlockControls": function() { return /* reexport */ block_controls; },
"BlockEdit": function() { return /* reexport */ BlockEdit; },
"BlockEditorKeyboardShortcuts": function() { return /* reexport */ keyboard_shortcuts; },
"BlockEditorProvider": function() { return /* reexport */ provider; },
"BlockFormatControls": function() { return /* reexport */ BlockFormatControls; },
"BlockIcon": function() { return /* reexport */ block_icon; },
"BlockInspector": function() { return /* reexport */ block_inspector; },
"BlockList": function() { return /* reexport */ BlockList; },
"BlockMover": function() { return /* reexport */ block_mover; },
"BlockNavigationDropdown": function() { return /* reexport */ dropdown; },
"BlockPreview": function() { return /* reexport */ block_preview; },
"BlockSelectionClearer": function() { return /* reexport */ BlockSelectionClearer; },
"BlockSettingsMenu": function() { return /* reexport */ block_settings_menu; },
"BlockSettingsMenuControls": function() { return /* reexport */ block_settings_menu_controls; },
"BlockStyles": function() { return /* reexport */ block_styles; },
"BlockTitle": function() { return /* reexport */ BlockTitle; },
"BlockToolbar": function() { return /* reexport */ block_toolbar; },
"BlockTools": function() { return /* reexport */ BlockTools; },
"BlockVerticalAlignmentControl": function() { return /* reexport */ BlockVerticalAlignmentControl; },
"BlockVerticalAlignmentToolbar": function() { return /* reexport */ BlockVerticalAlignmentToolbar; },
"ButtonBlockAppender": function() { return /* reexport */ button_block_appender; },
"ButtonBlockerAppender": function() { return /* reexport */ ButtonBlockerAppender; },
"ColorPalette": function() { return /* reexport */ color_palette; },
"ColorPaletteControl": function() { return /* reexport */ ColorPaletteControl; },
"ContrastChecker": function() { return /* reexport */ contrast_checker; },
"CopyHandler": function() { return /* reexport */ copy_handler; },
"DefaultBlockAppender": function() { return /* reexport */ default_block_appender; },
"FontSizePicker": function() { return /* reexport */ font_size_picker; },
"HeightControl": function() { return /* reexport */ HeightControl; },
"InnerBlocks": function() { return /* reexport */ inner_blocks; },
"Inserter": function() { return /* reexport */ inserter; },
"InspectorAdvancedControls": function() { return /* reexport */ InspectorAdvancedControls; },
"InspectorControls": function() { return /* reexport */ inspector_controls; },
"JustifyContentControl": function() { return /* reexport */ JustifyContentControl; },
"JustifyToolbar": function() { return /* reexport */ JustifyToolbar; },
"LineHeightControl": function() { return /* reexport */ line_height_control; },
"MediaPlaceholder": function() { return /* reexport */ media_placeholder; },
"MediaReplaceFlow": function() { return /* reexport */ media_replace_flow; },
"MediaUpload": function() { return /* reexport */ media_upload; },
"MediaUploadCheck": function() { return /* reexport */ check; },
"MultiSelectScrollIntoView": function() { return /* reexport */ MultiSelectScrollIntoView; },
"NavigableToolbar": function() { return /* reexport */ navigable_toolbar; },
"ObserveTyping": function() { return /* reexport */ observe_typing; },
"PanelColorSettings": function() { return /* reexport */ panel_color_settings; },
"PlainText": function() { return /* reexport */ plain_text; },
"RichText": function() { return /* reexport */ rich_text; },
"RichTextShortcut": function() { return /* reexport */ RichTextShortcut; },
"RichTextToolbarButton": function() { return /* reexport */ RichTextToolbarButton; },
"SETTINGS_DEFAULTS": function() { return /* reexport */ SETTINGS_DEFAULTS; },
"SkipToSelectedBlock": function() { return /* reexport */ skip_to_selected_block; },
"ToolSelector": function() { return /* reexport */ tool_selector; },
"Typewriter": function() { return /* reexport */ typewriter; },
"URLInput": function() { return /* reexport */ url_input; },
"URLInputButton": function() { return /* reexport */ url_input_button; },
"URLPopover": function() { return /* reexport */ url_popover; },
"Warning": function() { return /* reexport */ warning; },
"WritingFlow": function() { return /* reexport */ writing_flow; },
"__experimentalBlockAlignmentMatrixControl": function() { return /* reexport */ block_alignment_matrix_control; },
"__experimentalBlockFullHeightAligmentControl": function() { return /* reexport */ block_full_height_alignment_control; },
"__experimentalBlockPatternSetup": function() { return /* reexport */ block_pattern_setup; },
"__experimentalBlockPatternsList": function() { return /* reexport */ block_patterns_list; },
"__experimentalBlockVariationPicker": function() { return /* reexport */ block_variation_picker; },
"__experimentalBlockVariationTransforms": function() { return /* reexport */ block_variation_transforms; },
"__experimentalBorderRadiusControl": function() { return /* reexport */ BorderRadiusControl; },
"__experimentalColorGradientControl": function() { return /* reexport */ control; },
"__experimentalColorGradientSettingsDropdown": function() { return /* reexport */ ColorGradientSettingsDropdown; },
"__experimentalDateFormatPicker": function() { return /* reexport */ DateFormatPicker; },
"__experimentalDuotoneControl": function() { return /* reexport */ duotone_control; },
"__experimentalFontAppearanceControl": function() { return /* reexport */ FontAppearanceControl; },
"__experimentalFontFamilyControl": function() { return /* reexport */ FontFamilyControl; },
"__experimentalGetBorderClassesAndStyles": function() { return /* reexport */ getBorderClassesAndStyles; },
"__experimentalGetColorClassesAndStyles": function() { return /* reexport */ getColorClassesAndStyles; },
"__experimentalGetElementClassName": function() { return /* reexport */ __experimentalGetElementClassName; },
"__experimentalGetGapCSSValue": function() { return /* reexport */ getGapCSSValue; },
"__experimentalGetGradientClass": function() { return /* reexport */ __experimentalGetGradientClass; },
"__experimentalGetGradientObjectByGradientValue": function() { return /* reexport */ __experimentalGetGradientObjectByGradientValue; },
"__experimentalGetMatchingVariation": function() { return /* reexport */ __experimentalGetMatchingVariation; },
"__experimentalGetSpacingClassesAndStyles": function() { return /* reexport */ getSpacingClassesAndStyles; },
"__experimentalImageEditor": function() { return /* reexport */ ImageEditor; },
"__experimentalImageSizeControl": function() { return /* reexport */ ImageSizeControl; },
"__experimentalImageURLInputUI": function() { return /* reexport */ ImageURLInputUI; },
"__experimentalInspectorPopoverHeader": function() { return /* reexport */ InspectorPopoverHeader; },
"__experimentalLayoutStyle": function() { return /* reexport */ LayoutStyle; },
"__experimentalLetterSpacingControl": function() { return /* reexport */ LetterSpacingControl; },
"__experimentalLibrary": function() { return /* reexport */ library; },
"__experimentalLinkControl": function() { return /* reexport */ link_control; },
"__experimentalLinkControlSearchInput": function() { return /* reexport */ search_input; },
"__experimentalLinkControlSearchItem": function() { return /* reexport */ search_item; },
"__experimentalLinkControlSearchResults": function() { return /* reexport */ LinkControlSearchResults; },
"__experimentalListView": function() { return /* reexport */ components_list_view; },
"__experimentalPanelColorGradientSettings": function() { return /* reexport */ panel_color_gradient_settings; },
"__experimentalPreviewOptions": function() { return /* reexport */ PreviewOptions; },
"__experimentalPublishDateTimePicker": function() { return /* reexport */ publish_date_time_picker; },
"__experimentalRecursionProvider": function() { return /* reexport */ RecursionProvider; },
"__experimentalResponsiveBlockControl": function() { return /* reexport */ responsive_block_control; },
"__experimentalSpacingSizesControl": function() { return /* reexport */ SpacingSizesControl; },
"__experimentalTextDecorationControl": function() { return /* reexport */ TextDecorationControl; },
"__experimentalTextTransformControl": function() { return /* reexport */ TextTransformControl; },
"__experimentalUnitControl": function() { return /* reexport */ UnitControl; },
"__experimentalUseBlockOverlayActive": function() { return /* reexport */ useBlockOverlayActive; },
"__experimentalUseBlockPreview": function() { return /* reexport */ useBlockPreview; },
"__experimentalUseBorderProps": function() { return /* reexport */ useBorderProps; },
"__experimentalUseColorProps": function() { return /* reexport */ useColorProps; },
"__experimentalUseCustomSides": function() { return /* reexport */ useCustomSides; },
"__experimentalUseGradient": function() { return /* reexport */ __experimentalUseGradient; },
"__experimentalUseHasRecursion": function() { return /* reexport */ useHasRecursion; },
"__experimentalUseMultipleOriginColorsAndGradients": function() { return /* reexport */ useMultipleOriginColorsAndGradients; },
"__experimentalUseResizeCanvas": function() { return /* reexport */ useResizeCanvas; },
"__experimentaluseLayoutClasses": function() { return /* reexport */ useLayoutClasses; },
"__experimentaluseLayoutStyles": function() { return /* reexport */ useLayoutStyles; },
"__unstableBlockNameContext": function() { return /* reexport */ block_name_context; },
"__unstableBlockSettingsMenuFirstItem": function() { return /* reexport */ block_settings_menu_first_item; },
"__unstableBlockToolbarLastItem": function() { return /* reexport */ block_toolbar_last_item; },
"__unstableDuotoneFilter": function() { return /* reexport */ DuotoneFilter; },
"__unstableDuotoneStylesheet": function() { return /* reexport */ DuotoneStylesheet; },
"__unstableDuotoneUnsetStylesheet": function() { return /* reexport */ DuotoneUnsetStylesheet; },
"__unstableEditorStyles": function() { return /* reexport */ EditorStyles; },
"__unstableGetValuesFromColors": function() { return /* reexport */ getValuesFromColors; },
"__unstableIframe": function() { return /* reexport */ iframe; },
"__unstableInserterMenuExtension": function() { return /* reexport */ inserter_menu_extension; },
"__unstablePresetDuotoneFilter": function() { return /* reexport */ PresetDuotoneFilter; },
"__unstableRichTextInputEvent": function() { return /* reexport */ __unstableRichTextInputEvent; },
"__unstableUseBlockSelectionClearer": function() { return /* reexport */ useBlockSelectionClearer; },
"__unstableUseClipboardHandler": function() { return /* reexport */ useClipboardHandler; },
"__unstableUseMouseMoveTypingReset": function() { return /* reexport */ useMouseMoveTypingReset; },
"__unstableUseTypewriter": function() { return /* reexport */ useTypewriter; },
"__unstableUseTypingObserver": function() { return /* reexport */ useTypingObserver; },
"createCustomColorsHOC": function() { return /* reexport */ createCustomColorsHOC; },
"getColorClassName": function() { return /* reexport */ getColorClassName; },
"getColorObjectByAttributeValues": function() { return /* reexport */ getColorObjectByAttributeValues; },
"getColorObjectByColorValue": function() { return /* reexport */ getColorObjectByColorValue; },
"getComputedFluidTypographyValue": function() { return /* reexport */ getComputedFluidTypographyValue; },
"getFontSize": function() { return /* reexport */ getFontSize; },
"getFontSizeClass": function() { return /* reexport */ getFontSizeClass; },
"getFontSizeObjectByValue": function() { return /* reexport */ getFontSizeObjectByValue; },
"getGradientSlugByValue": function() { return /* reexport */ getGradientSlugByValue; },
"getGradientValueBySlug": function() { return /* reexport */ getGradientValueBySlug; },
"getPxFromCssUnit": function() { return /* reexport */ parse_css_unit_to_px; },
"getTypographyClassesAndStyles": function() { return /* reexport */ getTypographyClassesAndStyles; },
"privateApis": function() { return /* reexport */ privateApis; },
"store": function() { return /* reexport */ store; },
"storeConfig": function() { return /* reexport */ storeConfig; },
"transformStyles": function() { return /* reexport */ transform_styles; },
"useBlockDisplayInformation": function() { return /* reexport */ useBlockDisplayInformation; },
"useBlockEditContext": function() { return /* reexport */ useBlockEditContext; },
"useBlockProps": function() { return /* reexport */ useBlockProps; },
"useCachedTruthy": function() { return /* reexport */ useCachedTruthy; },
"useInnerBlocksProps": function() { return /* reexport */ useInnerBlocksProps; },
"useSetting": function() { return /* reexport */ useSetting; },
"withColorContext": function() { return /* reexport */ with_color_context; },
"withColors": function() { return /* reexport */ withColors; },
"withFontSizes": function() { return /* reexport */ with_font_sizes; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/block-editor/build-module/store/selectors.js
var selectors_namespaceObject = {};
__webpack_require__.r(selectors_namespaceObject);
__webpack_require__.d(selectors_namespaceObject, {
"__experimentalGetActiveBlockIdByBlockNames": function() { return __experimentalGetActiveBlockIdByBlockNames; },
"__experimentalGetAllowedBlocks": function() { return __experimentalGetAllowedBlocks; },
"__experimentalGetAllowedPatterns": function() { return __experimentalGetAllowedPatterns; },
"__experimentalGetBlockListSettingsForBlocks": function() { return __experimentalGetBlockListSettingsForBlocks; },
"__experimentalGetDirectInsertBlock": function() { return __experimentalGetDirectInsertBlock; },
"__experimentalGetGlobalBlocksByName": function() { return __experimentalGetGlobalBlocksByName; },
"__experimentalGetLastBlockAttributeChanges": function() { return __experimentalGetLastBlockAttributeChanges; },
"__experimentalGetParsedPattern": function() { return __experimentalGetParsedPattern; },
"__experimentalGetPatternTransformItems": function() { return __experimentalGetPatternTransformItems; },
"__experimentalGetPatternsByBlockTypes": function() { return __experimentalGetPatternsByBlockTypes; },
"__experimentalGetReusableBlockTitle": function() { return __experimentalGetReusableBlockTitle; },
"__unstableGetBlockWithoutInnerBlocks": function() { return __unstableGetBlockWithoutInnerBlocks; },
"__unstableGetClientIdWithClientIdsTree": function() { return __unstableGetClientIdWithClientIdsTree; },
"__unstableGetClientIdsTree": function() { return __unstableGetClientIdsTree; },
"__unstableGetContentLockingParent": function() { return __unstableGetContentLockingParent; },
"__unstableGetEditorMode": function() { return __unstableGetEditorMode; },
"__unstableGetSelectedBlocksWithPartialSelection": function() { return __unstableGetSelectedBlocksWithPartialSelection; },
"__unstableGetTemporarilyEditingAsBlocks": function() { return __unstableGetTemporarilyEditingAsBlocks; },
"__unstableGetVisibleBlocks": function() { return __unstableGetVisibleBlocks; },
"__unstableHasActiveBlockOverlayActive": function() { return __unstableHasActiveBlockOverlayActive; },
"__unstableIsFullySelected": function() { return __unstableIsFullySelected; },
"__unstableIsLastBlockChangeIgnored": function() { return __unstableIsLastBlockChangeIgnored; },
"__unstableIsSelectionCollapsed": function() { return __unstableIsSelectionCollapsed; },
"__unstableIsSelectionMergeable": function() { return __unstableIsSelectionMergeable; },
"__unstableIsWithinBlockOverlay": function() { return __unstableIsWithinBlockOverlay; },
"__unstableSelectionHasUnmergeableBlock": function() { return __unstableSelectionHasUnmergeableBlock; },
"areInnerBlocksControlled": function() { return areInnerBlocksControlled; },
"canEditBlock": function() { return canEditBlock; },
"canInsertBlockType": function() { return canInsertBlockType; },
"canInsertBlocks": function() { return canInsertBlocks; },
"canLockBlockType": function() { return canLockBlockType; },
"canMoveBlock": function() { return canMoveBlock; },
"canMoveBlocks": function() { return canMoveBlocks; },
"canRemoveBlock": function() { return canRemoveBlock; },
"canRemoveBlocks": function() { return canRemoveBlocks; },
"didAutomaticChange": function() { return didAutomaticChange; },
"getAdjacentBlockClientId": function() { return getAdjacentBlockClientId; },
"getAllowedBlocks": function() { return getAllowedBlocks; },
"getBlock": function() { return getBlock; },
"getBlockAttributes": function() { return getBlockAttributes; },
"getBlockCount": function() { return getBlockCount; },
"getBlockHierarchyRootClientId": function() { return getBlockHierarchyRootClientId; },
"getBlockIndex": function() { return getBlockIndex; },
"getBlockInsertionPoint": function() { return getBlockInsertionPoint; },
"getBlockListSettings": function() { return getBlockListSettings; },
"getBlockMode": function() { return getBlockMode; },
"getBlockName": function() { return getBlockName; },
"getBlockNamesByClientId": function() { return getBlockNamesByClientId; },
"getBlockOrder": function() { return getBlockOrder; },
"getBlockParents": function() { return getBlockParents; },
"getBlockParentsByBlockName": function() { return getBlockParentsByBlockName; },
"getBlockRootClientId": function() { return getBlockRootClientId; },
"getBlockSelectionEnd": function() { return getBlockSelectionEnd; },
"getBlockSelectionStart": function() { return getBlockSelectionStart; },
"getBlockTransformItems": function() { return getBlockTransformItems; },
"getBlocks": function() { return getBlocks; },
"getBlocksByClientId": function() { return getBlocksByClientId; },
"getClientIdsOfDescendants": function() { return getClientIdsOfDescendants; },
"getClientIdsWithDescendants": function() { return getClientIdsWithDescendants; },
"getDraggedBlockClientIds": function() { return getDraggedBlockClientIds; },
"getFirstMultiSelectedBlockClientId": function() { return getFirstMultiSelectedBlockClientId; },
"getGlobalBlockCount": function() { return getGlobalBlockCount; },
"getInserterItems": function() { return getInserterItems; },
"getLastMultiSelectedBlockClientId": function() { return getLastMultiSelectedBlockClientId; },
"getLowestCommonAncestorWithSelectedBlock": function() { return getLowestCommonAncestorWithSelectedBlock; },
"getMultiSelectedBlockClientIds": function() { return getMultiSelectedBlockClientIds; },
"getMultiSelectedBlocks": function() { return getMultiSelectedBlocks; },
"getMultiSelectedBlocksEndClientId": function() { return getMultiSelectedBlocksEndClientId; },
"getMultiSelectedBlocksStartClientId": function() { return getMultiSelectedBlocksStartClientId; },
"getNextBlockClientId": function() { return getNextBlockClientId; },
"getPatternsByBlockTypes": function() { return getPatternsByBlockTypes; },
"getPreviousBlockClientId": function() { return getPreviousBlockClientId; },
"getSelectedBlock": function() { return getSelectedBlock; },
"getSelectedBlockClientId": function() { return getSelectedBlockClientId; },
"getSelectedBlockClientIds": function() { return getSelectedBlockClientIds; },
"getSelectedBlockCount": function() { return getSelectedBlockCount; },
"getSelectedBlocksInitialCaretPosition": function() { return getSelectedBlocksInitialCaretPosition; },
"getSelectionEnd": function() { return getSelectionEnd; },
"getSelectionStart": function() { return getSelectionStart; },
"getSettings": function() { return getSettings; },
"getTemplate": function() { return getTemplate; },
"getTemplateLock": function() { return getTemplateLock; },
"hasBlockMovingClientId": function() { return selectors_hasBlockMovingClientId; },
"hasInserterItems": function() { return hasInserterItems; },
"hasMultiSelection": function() { return hasMultiSelection; },
"hasSelectedBlock": function() { return hasSelectedBlock; },
"hasSelectedInnerBlock": function() { return hasSelectedInnerBlock; },
"isAncestorBeingDragged": function() { return isAncestorBeingDragged; },
"isAncestorMultiSelected": function() { return isAncestorMultiSelected; },
"isBlockBeingDragged": function() { return isBlockBeingDragged; },
"isBlockHighlighted": function() { return isBlockHighlighted; },
"isBlockInsertionPointVisible": function() { return isBlockInsertionPointVisible; },
"isBlockMultiSelected": function() { return isBlockMultiSelected; },
"isBlockSelected": function() { return isBlockSelected; },
"isBlockValid": function() { return isBlockValid; },
"isBlockVisible": function() { return isBlockVisible; },
"isBlockWithinSelection": function() { return isBlockWithinSelection; },
"isCaretWithinFormattedText": function() { return isCaretWithinFormattedText; },
"isDraggingBlocks": function() { return isDraggingBlocks; },
"isFirstMultiSelectedBlock": function() { return isFirstMultiSelectedBlock; },
"isLastBlockChangePersistent": function() { return isLastBlockChangePersistent; },
"isMultiSelecting": function() { return selectors_isMultiSelecting; },
"isNavigationMode": function() { return isNavigationMode; },
"isSelectionEnabled": function() { return selectors_isSelectionEnabled; },
"isTyping": function() { return selectors_isTyping; },
"isValidTemplate": function() { return isValidTemplate; },
"wasBlockJustInserted": function() { return wasBlockJustInserted; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/block-editor/build-module/store/private-actions.js
var private_actions_namespaceObject = {};
__webpack_require__.r(private_actions_namespaceObject);
__webpack_require__.d(private_actions_namespaceObject, {
"__experimentalUpdateSettings": function() { return __experimentalUpdateSettings; },
"hideBlockInterface": function() { return hideBlockInterface; },
"showBlockInterface": function() { return showBlockInterface; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/block-editor/build-module/store/private-selectors.js
var private_selectors_namespaceObject = {};
__webpack_require__.r(private_selectors_namespaceObject);
__webpack_require__.d(private_selectors_namespaceObject, {
"getLastInsertedBlocksClientIds": function() { return getLastInsertedBlocksClientIds; },
"isBlockInterfaceHidden": function() { return private_selectors_isBlockInterfaceHidden; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/block-editor/build-module/store/actions.js
var actions_namespaceObject = {};
__webpack_require__.r(actions_namespaceObject);
__webpack_require__.d(actions_namespaceObject, {
"__unstableDeleteSelection": function() { return __unstableDeleteSelection; },
"__unstableExpandSelection": function() { return __unstableExpandSelection; },
"__unstableMarkAutomaticChange": function() { return __unstableMarkAutomaticChange; },
"__unstableMarkLastChangeAsPersistent": function() { return __unstableMarkLastChangeAsPersistent; },
"__unstableMarkNextChangeAsNotPersistent": function() { return __unstableMarkNextChangeAsNotPersistent; },
"__unstableSaveReusableBlock": function() { return __unstableSaveReusableBlock; },
"__unstableSetEditorMode": function() { return __unstableSetEditorMode; },
"__unstableSetTemporarilyEditingAsBlocks": function() { return __unstableSetTemporarilyEditingAsBlocks; },
"__unstableSplitSelection": function() { return __unstableSplitSelection; },
"clearSelectedBlock": function() { return clearSelectedBlock; },
"duplicateBlocks": function() { return duplicateBlocks; },
"enterFormattedText": function() { return enterFormattedText; },
"exitFormattedText": function() { return exitFormattedText; },
"flashBlock": function() { return flashBlock; },
"hideInsertionPoint": function() { return hideInsertionPoint; },
"insertAfterBlock": function() { return insertAfterBlock; },
"insertBeforeBlock": function() { return insertBeforeBlock; },
"insertBlock": function() { return insertBlock; },
"insertBlocks": function() { return insertBlocks; },
"insertDefaultBlock": function() { return insertDefaultBlock; },
"mergeBlocks": function() { return mergeBlocks; },
"moveBlockToPosition": function() { return moveBlockToPosition; },
"moveBlocksDown": function() { return moveBlocksDown; },
"moveBlocksToPosition": function() { return moveBlocksToPosition; },
"moveBlocksUp": function() { return moveBlocksUp; },
"multiSelect": function() { return multiSelect; },
"receiveBlocks": function() { return receiveBlocks; },
"removeBlock": function() { return removeBlock; },
"removeBlocks": function() { return removeBlocks; },
"replaceBlock": function() { return replaceBlock; },
"replaceBlocks": function() { return replaceBlocks; },
"replaceInnerBlocks": function() { return replaceInnerBlocks; },
"resetBlocks": function() { return resetBlocks; },
"resetSelection": function() { return resetSelection; },
"selectBlock": function() { return selectBlock; },
"selectNextBlock": function() { return selectNextBlock; },
"selectPreviousBlock": function() { return selectPreviousBlock; },
"selectionChange": function() { return selectionChange; },
"setBlockMovingClientId": function() { return setBlockMovingClientId; },
"setBlockVisibility": function() { return setBlockVisibility; },
"setHasControlledInnerBlocks": function() { return setHasControlledInnerBlocks; },
"setNavigationMode": function() { return setNavigationMode; },
"setTemplateValidity": function() { return setTemplateValidity; },
"showInsertionPoint": function() { return showInsertionPoint; },
"startDraggingBlocks": function() { return startDraggingBlocks; },
"startMultiSelect": function() { return startMultiSelect; },
"startTyping": function() { return startTyping; },
"stopDraggingBlocks": function() { return stopDraggingBlocks; },
"stopMultiSelect": function() { return stopMultiSelect; },
"stopTyping": function() { return stopTyping; },
"synchronizeTemplate": function() { return synchronizeTemplate; },
"toggleBlockHighlight": function() { return toggleBlockHighlight; },
"toggleBlockMode": function() { return toggleBlockMode; },
"toggleSelection": function() { return toggleSelection; },
"updateBlock": function() { return updateBlock; },
"updateBlockAttributes": function() { return updateBlockAttributes; },
"updateBlockListSettings": function() { return updateBlockListSettings; },
"updateSettings": function() { return updateSettings; },
"validateBlocksToTemplate": function() { return validateBlocksToTemplate; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/block-editor/build-module/components/global-styles/index.js
var global_styles_namespaceObject = {};
__webpack_require__.r(global_styles_namespaceObject);
__webpack_require__.d(global_styles_namespaceObject, {
"GlobalStylesContext": function() { return GlobalStylesContext; },
"useGlobalSetting": function() { return useGlobalSetting; },
"useGlobalStyle": function() { return useGlobalStyle; },
"useGlobalStylesOutput": function() { return useGlobalStylesOutput; },
"useGlobalStylesReset": function() { return useGlobalStylesReset; }
});
;// CONCATENATED MODULE: external ["wp","blocks"]
var external_wp_blocks_namespaceObject = window["wp"]["blocks"];
;// CONCATENATED MODULE: external ["wp","hooks"]
var external_wp_hooks_namespaceObject = window["wp"]["hooks"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/compat.js
/**
* WordPress dependencies
*/
function migrateLightBlockWrapper(settings) {
const {
apiVersion = 1
} = settings;
if (apiVersion < 2 && (0,external_wp_blocks_namespaceObject.hasBlockSupport)(settings, 'lightBlockWrapper', false)) {
settings.apiVersion = 2;
}
return settings;
}
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'core/compat/migrateLightBlockWrapper', migrateLightBlockWrapper);
;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/extends.js
function _extends() {
return _extends = Object.assign ? Object.assign.bind() : function (n) {
for (var e = 1; e < arguments.length; e++) {
var t = arguments[e];
for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
}
return n;
}, _extends.apply(null, arguments);
}
;// CONCATENATED MODULE: external ["wp","element"]
var external_wp_element_namespaceObject = window["wp"]["element"];
// EXTERNAL MODULE: ./node_modules/classnames/index.js
var classnames = __webpack_require__(7153);
var classnames_default = /*#__PURE__*/__webpack_require__.n(classnames);
;// CONCATENATED MODULE: external ["wp","compose"]
var external_wp_compose_namespaceObject = window["wp"]["compose"];
;// CONCATENATED MODULE: external ["wp","data"]
var external_wp_data_namespaceObject = window["wp"]["data"];
;// CONCATENATED MODULE: external "lodash"
var external_lodash_namespaceObject = window["lodash"];
;// CONCATENATED MODULE: external ["wp","components"]
var external_wp_components_namespaceObject = window["wp"]["components"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-controls/groups.js
/**
* WordPress dependencies
*/
const BlockControlsDefault = (0,external_wp_components_namespaceObject.createSlotFill)('BlockControls');
const BlockControlsBlock = (0,external_wp_components_namespaceObject.createSlotFill)('BlockControlsBlock');
const BlockControlsInline = (0,external_wp_components_namespaceObject.createSlotFill)('BlockFormatControls');
const BlockControlsOther = (0,external_wp_components_namespaceObject.createSlotFill)('BlockControlsOther');
const BlockControlsParent = (0,external_wp_components_namespaceObject.createSlotFill)('BlockControlsParent');
const groups = {
default: BlockControlsDefault,
block: BlockControlsBlock,
inline: BlockControlsInline,
other: BlockControlsOther,
parent: BlockControlsParent
};
/* harmony default export */ var block_controls_groups = (groups);
// EXTERNAL MODULE: ./node_modules/fast-deep-equal/es6/index.js
var es6 = __webpack_require__(5619);
var es6_default = /*#__PURE__*/__webpack_require__.n(es6);
;// CONCATENATED MODULE: external ["wp","i18n"]
var external_wp_i18n_namespaceObject = window["wp"]["i18n"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/store/defaults.js
/**
* WordPress dependencies
*/
const PREFERENCES_DEFAULTS = {
insertUsage: {}
};
/**
* The default editor settings
*
* @typedef {Object} SETTINGS_DEFAULT
* @property {boolean} alignWide Enable/Disable Wide/Full Alignments
* @property {boolean} supportsLayout Enable/disable layouts support in container blocks.
* @property {boolean} imageEditing Image Editing settings set to false to disable.
* @property {Array} imageSizes Available image sizes
* @property {number} maxWidth Max width to constraint resizing
* @property {boolean|Array} allowedBlockTypes Allowed block types
* @property {boolean} hasFixedToolbar Whether or not the editor toolbar is fixed
* @property {boolean} focusMode Whether the focus mode is enabled or not
* @property {Array} styles Editor Styles
* @property {boolean} keepCaretInsideBlock Whether caret should move between blocks in edit mode
* @property {string} bodyPlaceholder Empty post placeholder
* @property {string} titlePlaceholder Empty title placeholder
* @property {boolean} canLockBlocks Whether the user can manage Block Lock state
* @property {boolean} codeEditingEnabled Whether or not the user can switch to the code editor
* @property {boolean} generateAnchors Enable/Disable auto anchor generation for Heading blocks
* @property {boolean} enableOpenverseMediaCategory Enable/Disable the Openverse media category in the inserter.
* @property {boolean} clearBlockSelection Whether the block editor should clear selection on mousedown when a block is not clicked.
* @property {boolean} __experimentalCanUserUseUnfilteredHTML Whether the user should be able to use unfiltered HTML or the HTML should be filtered e.g., to remove elements considered insecure like iframes.
* @property {boolean} __experimentalBlockDirectory Whether the user has enabled the Block Directory
* @property {Array} __experimentalBlockPatterns Array of objects representing the block patterns
* @property {Array} __experimentalBlockPatternCategories Array of objects representing the block pattern categories
* @property {boolean} __unstableGalleryWithImageBlocks Whether the user has enabled the refactored gallery block which uses InnerBlocks
*/
const SETTINGS_DEFAULTS = {
alignWide: false,
supportsLayout: true,
// colors setting is not used anymore now defaults are passed from theme.json on the server and core has its own defaults.
// The setting is only kept for backward compatibility purposes.
colors: [{
name: (0,external_wp_i18n_namespaceObject.__)('Black'),
slug: 'black',
color: '#000000'
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Cyan bluish gray'),
slug: 'cyan-bluish-gray',
color: '#abb8c3'
}, {
name: (0,external_wp_i18n_namespaceObject.__)('White'),
slug: 'white',
color: '#ffffff'
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Pale pink'),
slug: 'pale-pink',
color: '#f78da7'
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Vivid red'),
slug: 'vivid-red',
color: '#cf2e2e'
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Luminous vivid orange'),
slug: 'luminous-vivid-orange',
color: '#ff6900'
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Luminous vivid amber'),
slug: 'luminous-vivid-amber',
color: '#fcb900'
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Light green cyan'),
slug: 'light-green-cyan',
color: '#7bdcb5'
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Vivid green cyan'),
slug: 'vivid-green-cyan',
color: '#00d084'
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Pale cyan blue'),
slug: 'pale-cyan-blue',
color: '#8ed1fc'
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Vivid cyan blue'),
slug: 'vivid-cyan-blue',
color: '#0693e3'
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Vivid purple'),
slug: 'vivid-purple',
color: '#9b51e0'
}],
// fontSizes setting is not used anymore now defaults are passed from theme.json on the server and core has its own defaults.
// The setting is only kept for backward compatibility purposes.
fontSizes: [{
name: (0,external_wp_i18n_namespaceObject._x)('Small', 'font size name'),
size: 13,
slug: 'small'
}, {
name: (0,external_wp_i18n_namespaceObject._x)('Normal', 'font size name'),
size: 16,
slug: 'normal'
}, {
name: (0,external_wp_i18n_namespaceObject._x)('Medium', 'font size name'),
size: 20,
slug: 'medium'
}, {
name: (0,external_wp_i18n_namespaceObject._x)('Large', 'font size name'),
size: 36,
slug: 'large'
}, {
name: (0,external_wp_i18n_namespaceObject._x)('Huge', 'font size name'),
size: 42,
slug: 'huge'
}],
// Image default size slug.
imageDefaultSize: 'large',
imageSizes: [{
slug: 'thumbnail',
name: (0,external_wp_i18n_namespaceObject.__)('Thumbnail')
}, {
slug: 'medium',
name: (0,external_wp_i18n_namespaceObject.__)('Medium')
}, {
slug: 'large',
name: (0,external_wp_i18n_namespaceObject.__)('Large')
}, {
slug: 'full',
name: (0,external_wp_i18n_namespaceObject.__)('Full Size')
}],
// Allow plugin to disable Image Editor if need be.
imageEditing: true,
// This is current max width of the block inner area
// It's used to constraint image resizing and this value could be overridden later by themes
maxWidth: 580,
// Allowed block types for the editor, defaulting to true (all supported).
allowedBlockTypes: true,
// Maximum upload size in bytes allowed for the site.
maxUploadFileSize: 0,
// List of allowed mime types and file extensions.
allowedMimeTypes: null,
// Allows to disable block locking interface.
canLockBlocks: true,
// Allows to disable Openverse media category in the inserter.
enableOpenverseMediaCategory: true,
clearBlockSelection: true,
__experimentalCanUserUseUnfilteredHTML: false,
__experimentalBlockDirectory: false,
__mobileEnablePageTemplates: false,
__experimentalBlockPatterns: [],
__experimentalBlockPatternCategories: [],
__unstableGalleryWithImageBlocks: false,
__unstableIsPreviewMode: false,
// These settings will be completely revamped in the future.
// The goal is to evolve this into an API which will instruct
// the block inspector to animate transitions between what it
// displays based on the relationship between the selected block
// and its parent, and only enable it if the parent is controlling
// its children blocks.
blockInspectorAnimation: {
animationParent: 'core/navigation',
'core/navigation': {
enterDirection: 'leftToRight'
},
'core/navigation-submenu': {
enterDirection: 'rightToLeft'
},
'core/navigation-link': {
enterDirection: 'rightToLeft'
},
'core/search': {
enterDirection: 'rightToLeft'
},
'core/social-links': {
enterDirection: 'rightToLeft'
},
'core/page-list': {
enterDirection: 'rightToLeft'
},
'core/spacer': {
enterDirection: 'rightToLeft'
},
'core/home-link': {
enterDirection: 'rightToLeft'
},
'core/site-title': {
enterDirection: 'rightToLeft'
},
'core/site-logo': {
enterDirection: 'rightToLeft'
}
},
generateAnchors: false,
// gradients setting is not used anymore now defaults are passed from theme.json on the server and core has its own defaults.
// The setting is only kept for backward compatibility purposes.
gradients: [{
name: (0,external_wp_i18n_namespaceObject.__)('Vivid cyan blue to vivid purple'),
gradient: 'linear-gradient(135deg,rgba(6,147,227,1) 0%,rgb(155,81,224) 100%)',
slug: 'vivid-cyan-blue-to-vivid-purple'
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Light green cyan to vivid green cyan'),
gradient: 'linear-gradient(135deg,rgb(122,220,180) 0%,rgb(0,208,130) 100%)',
slug: 'light-green-cyan-to-vivid-green-cyan'
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Luminous vivid amber to luminous vivid orange'),
gradient: 'linear-gradient(135deg,rgba(252,185,0,1) 0%,rgba(255,105,0,1) 100%)',
slug: 'luminous-vivid-amber-to-luminous-vivid-orange'
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Luminous vivid orange to vivid red'),
gradient: 'linear-gradient(135deg,rgba(255,105,0,1) 0%,rgb(207,46,46) 100%)',
slug: 'luminous-vivid-orange-to-vivid-red'
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Very light gray to cyan bluish gray'),
gradient: 'linear-gradient(135deg,rgb(238,238,238) 0%,rgb(169,184,195) 100%)',
slug: 'very-light-gray-to-cyan-bluish-gray'
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Cool to warm spectrum'),
gradient: 'linear-gradient(135deg,rgb(74,234,220) 0%,rgb(151,120,209) 20%,rgb(207,42,186) 40%,rgb(238,44,130) 60%,rgb(251,105,98) 80%,rgb(254,248,76) 100%)',
slug: 'cool-to-warm-spectrum'
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Blush light purple'),
gradient: 'linear-gradient(135deg,rgb(255,206,236) 0%,rgb(152,150,240) 100%)',
slug: 'blush-light-purple'
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Blush bordeaux'),
gradient: 'linear-gradient(135deg,rgb(254,205,165) 0%,rgb(254,45,45) 50%,rgb(107,0,62) 100%)',
slug: 'blush-bordeaux'
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Luminous dusk'),
gradient: 'linear-gradient(135deg,rgb(255,203,112) 0%,rgb(199,81,192) 50%,rgb(65,88,208) 100%)',
slug: 'luminous-dusk'
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Pale ocean'),
gradient: 'linear-gradient(135deg,rgb(255,245,203) 0%,rgb(182,227,212) 50%,rgb(51,167,181) 100%)',
slug: 'pale-ocean'
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Electric grass'),
gradient: 'linear-gradient(135deg,rgb(202,248,128) 0%,rgb(113,206,126) 100%)',
slug: 'electric-grass'
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Midnight'),
gradient: 'linear-gradient(135deg,rgb(2,3,129) 0%,rgb(40,116,252) 100%)',
slug: 'midnight'
}],
__unstableResolvedAssets: {
styles: [],
scripts: []
}
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/store/array.js
/**
* Insert one or multiple elements into a given position of an array.
*
* @param {Array} array Source array.
* @param {*} elements Elements to insert.
* @param {number} index Insert Position.
*
* @return {Array} Result.
*/
function insertAt(array, elements, index) {
return [...array.slice(0, index), ...(Array.isArray(elements) ? elements : [elements]), ...array.slice(index)];
}
/**
* Moves an element in an array.
*
* @param {Array} array Source array.
* @param {number} from Source index.
* @param {number} to Destination index.
* @param {number} count Number of elements to move.
*
* @return {Array} Result.
*/
function moveTo(array, from, to) {
let count = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1;
const withoutMovedElements = [...array];
withoutMovedElements.splice(from, count);
return insertAt(withoutMovedElements, array.slice(from, from + count), to);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/store/reducer.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const identity = x => x;
/**
* Given an array of blocks, returns an object where each key is a nesting
* context, the value of which is an array of block client IDs existing within
* that nesting context.
*
* @param {Array} blocks Blocks to map.
* @param {?string} rootClientId Assumed root client ID.
*
* @return {Object} Block order map object.
*/
function mapBlockOrder(blocks) {
let rootClientId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
const result = new Map();
const current = [];
result.set(rootClientId, current);
blocks.forEach(block => {
const {
clientId,
innerBlocks
} = block;
current.push(clientId);
mapBlockOrder(innerBlocks, clientId).forEach((order, subClientId) => {
result.set(subClientId, order);
});
});
return result;
}
/**
* Given an array of blocks, returns an object where each key contains
* the clientId of the block and the value is the parent of the block.
*
* @param {Array} blocks Blocks to map.
* @param {?string} rootClientId Assumed root client ID.
*
* @return {Object} Block order map object.
*/
function mapBlockParents(blocks) {
let rootClientId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
const result = [];
const stack = [[rootClientId, blocks]];
while (stack.length) {
const [parent, currentBlocks] = stack.shift();
currentBlocks.forEach(_ref => {
let {
innerBlocks,
...block
} = _ref;
result.push([block.clientId, parent]);
if (innerBlocks !== null && innerBlocks !== void 0 && innerBlocks.length) {
stack.push([block.clientId, innerBlocks]);
}
});
}
return result;
}
/**
* Helper method to iterate through all blocks, recursing into inner blocks,
* applying a transformation function to each one.
* Returns a flattened object with the transformed blocks.
*
* @param {Array} blocks Blocks to flatten.
* @param {Function} transform Transforming function to be applied to each block.
*
* @return {Array} Flattened object.
*/
function flattenBlocks(blocks) {
let transform = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : identity;
const result = [];
const stack = [...blocks];
while (stack.length) {
const {
innerBlocks,
...block
} = stack.shift();
stack.push(...innerBlocks);
result.push([block.clientId, transform(block)]);
}
return result;
}
function getFlattenedClientIds(blocks) {
const result = {};
const stack = [...blocks];
while (stack.length) {
const {
innerBlocks,
...block
} = stack.shift();
stack.push(...innerBlocks);
result[block.clientId] = true;
}
return result;
}
/**
* Given an array of blocks, returns an object containing all blocks, without
* attributes, recursing into inner blocks. Keys correspond to the block client
* ID, the value of which is the attributes object.
*
* @param {Array} blocks Blocks to flatten.
*
* @return {Array} Flattened block attributes object.
*/
function getFlattenedBlocksWithoutAttributes(blocks) {
return flattenBlocks(blocks, block => {
const {
attributes,
...restBlock
} = block;
return restBlock;
});
}
/**
* Given an array of blocks, returns an object containing all block attributes,
* recursing into inner blocks. Keys correspond to the block client ID, the
* value of which is the attributes object.
*
* @param {Array} blocks Blocks to flatten.
*
* @return {Array} Flattened block attributes object.
*/
function getFlattenedBlockAttributes(blocks) {
return flattenBlocks(blocks, block => block.attributes);
}
/**
* Returns true if the two object arguments have the same keys, or false
* otherwise.
*
* @param {Object} a First object.
* @param {Object} b Second object.
*
* @return {boolean} Whether the two objects have the same keys.
*/
function hasSameKeys(a, b) {
return es6_default()(Object.keys(a), Object.keys(b));
}
/**
* Returns true if, given the currently dispatching action and the previously
* dispatched action, the two actions are updating the same block attribute, or
* false otherwise.
*
* @param {Object} action Currently dispatching action.
* @param {Object} lastAction Previously dispatched action.
*
* @return {boolean} Whether actions are updating the same block attribute.
*/
function isUpdatingSameBlockAttribute(action, lastAction) {
return action.type === 'UPDATE_BLOCK_ATTRIBUTES' && lastAction !== undefined && lastAction.type === 'UPDATE_BLOCK_ATTRIBUTES' && es6_default()(action.clientIds, lastAction.clientIds) && hasSameKeys(action.attributes, lastAction.attributes);
}
function updateBlockTreeForBlocks(state, blocks) {
const treeToUpdate = state.tree;
const stack = [...blocks];
const flattenedBlocks = [...blocks];
while (stack.length) {
const block = stack.shift();
stack.push(...block.innerBlocks);
flattenedBlocks.push(...block.innerBlocks);
} // Create objects before mutating them, that way it's always defined.
for (const block of flattenedBlocks) {
treeToUpdate.set(block.clientId, {});
}
for (const block of flattenedBlocks) {
treeToUpdate.set(block.clientId, Object.assign(treeToUpdate.get(block.clientId), { ...state.byClientId.get(block.clientId),
attributes: state.attributes.get(block.clientId),
innerBlocks: block.innerBlocks.map(subBlock => treeToUpdate.get(subBlock.clientId))
}));
}
}
function updateParentInnerBlocksInTree(state, updatedClientIds) {
let updateChildrenOfUpdatedClientIds = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
const treeToUpdate = state.tree;
const uncontrolledParents = new Set([]);
const controlledParents = new Set();
for (const clientId of updatedClientIds) {
let current = updateChildrenOfUpdatedClientIds ? clientId : state.parents.get(clientId);
do {
if (state.controlledInnerBlocks[current]) {
// Should stop on controlled blocks.
// If we reach a controlled parent, break out of the loop.
controlledParents.add(current);
break;
} else {
// Else continue traversing up through parents.
uncontrolledParents.add(current);
current = state.parents.get(current);
}
} while (current !== undefined);
} // To make sure the order of assignments doesn't matter,
// we first create empty objects and mutates the inner blocks later.
for (const clientId of uncontrolledParents) {
treeToUpdate.set(clientId, { ...treeToUpdate.get(clientId)
});
}
for (const clientId of uncontrolledParents) {
treeToUpdate.get(clientId).innerBlocks = (state.order.get(clientId) || []).map(subClientId => treeToUpdate.get(subClientId));
} // Controlled parent blocks, need a dedicated key for their inner blocks
// to be used when doing getBlocks( controlledBlockClientId ).
for (const clientId of controlledParents) {
treeToUpdate.set('controlled||' + clientId, {
innerBlocks: (state.order.get(clientId) || []).map(subClientId => treeToUpdate.get(subClientId))
});
}
}
/**
* Higher-order reducer intended to compute full block objects key for each block in the post.
* This is a denormalization to optimize the performance of the getBlock selectors and avoid
* recomputing the block objects and avoid heavy memoization.
*
* @param {Function} reducer Original reducer function.
*
* @return {Function} Enhanced reducer function.
*/
const withBlockTree = reducer => function () {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
const newState = reducer(state, action);
if (newState === state) {
return state;
}
newState.tree = state.tree ? state.tree : new Map();
switch (action.type) {
case 'RECEIVE_BLOCKS':
case 'INSERT_BLOCKS':
{
newState.tree = new Map(newState.tree);
updateBlockTreeForBlocks(newState, action.blocks);
updateParentInnerBlocksInTree(newState, action.rootClientId ? [action.rootClientId] : [''], true);
break;
}
case 'UPDATE_BLOCK':
newState.tree = new Map(newState.tree);
newState.tree.set(action.clientId, { ...newState.tree.get(action.clientId),
...newState.byClientId.get(action.clientId),
attributes: newState.attributes.get(action.clientId)
});
updateParentInnerBlocksInTree(newState, [action.clientId], false);
break;
case 'UPDATE_BLOCK_ATTRIBUTES':
{
newState.tree = new Map(newState.tree);
action.clientIds.forEach(clientId => {
newState.tree.set(clientId, { ...newState.tree.get(clientId),
attributes: newState.attributes.get(clientId)
});
});
updateParentInnerBlocksInTree(newState, action.clientIds, false);
break;
}
case 'REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN':
{
const inserterClientIds = getFlattenedClientIds(action.blocks);
newState.tree = new Map(newState.tree);
action.replacedClientIds.concat( // Controlled inner blocks are only removed
// if the block doesn't move to another position
// otherwise their content will be lost.
action.replacedClientIds.filter(clientId => !inserterClientIds[clientId]).map(clientId => 'controlled||' + clientId)).forEach(key => {
newState.tree.delete(key);
});
updateBlockTreeForBlocks(newState, action.blocks);
updateParentInnerBlocksInTree(newState, action.blocks.map(b => b.clientId), false); // If there are no replaced blocks, it means we're removing blocks so we need to update their parent.
const parentsOfRemovedBlocks = [];
for (const clientId of action.clientIds) {
if (state.parents.get(clientId) !== undefined && (state.parents.get(clientId) === '' || newState.byClientId.get(state.parents.get(clientId)))) {
parentsOfRemovedBlocks.push(state.parents.get(clientId));
}
}
updateParentInnerBlocksInTree(newState, parentsOfRemovedBlocks, true);
break;
}
case 'REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN':
const parentsOfRemovedBlocks = [];
for (const clientId of action.clientIds) {
if (state.parents.get(clientId) !== undefined && (state.parents.get(clientId) === '' || newState.byClientId.get(state.parents.get(clientId)))) {
parentsOfRemovedBlocks.push(state.parents.get(clientId));
}
}
newState.tree = new Map(newState.tree);
action.removedClientIds.concat(action.removedClientIds.map(clientId => 'controlled||' + clientId)).forEach(key => {
newState.tree.delete(key);
});
updateParentInnerBlocksInTree(newState, parentsOfRemovedBlocks, true);
break;
case 'MOVE_BLOCKS_TO_POSITION':
{
const updatedBlockUids = [];
if (action.fromRootClientId) {
updatedBlockUids.push(action.fromRootClientId);
} else {
updatedBlockUids.push('');
}
if (action.toRootClientId) {
updatedBlockUids.push(action.toRootClientId);
}
newState.tree = new Map(newState.tree);
updateParentInnerBlocksInTree(newState, updatedBlockUids, true);
break;
}
case 'MOVE_BLOCKS_UP':
case 'MOVE_BLOCKS_DOWN':
{
const updatedBlockUids = [action.rootClientId ? action.rootClientId : ''];
newState.tree = new Map(newState.tree);
updateParentInnerBlocksInTree(newState, updatedBlockUids, true);
break;
}
case 'SAVE_REUSABLE_BLOCK_SUCCESS':
{
const updatedBlockUids = [];
newState.attributes.forEach((attributes, clientId) => {
if (newState.byClientId.get(clientId).name === 'core/block' && attributes.ref === action.updatedId) {
updatedBlockUids.push(clientId);
}
});
newState.tree = new Map(newState.tree);
updatedBlockUids.forEach(clientId => {
newState.tree.set(clientId, { ...newState.byClientId.get(clientId),
attributes: newState.attributes.get(clientId),
innerBlocks: newState.tree.get(clientId).innerBlocks
});
});
updateParentInnerBlocksInTree(newState, updatedBlockUids, false);
}
}
return newState;
};
/**
* Higher-order reducer intended to augment the blocks reducer, assigning an
* `isPersistentChange` property value corresponding to whether a change in
* state can be considered as persistent. All changes are considered persistent
* except when updating the same block attribute as in the previous action.
*
* @param {Function} reducer Original reducer function.
*
* @return {Function} Enhanced reducer function.
*/
function withPersistentBlockChange(reducer) {
let lastAction;
let markNextChangeAsNotPersistent = false;
return (state, action) => {
let nextState = reducer(state, action);
const isExplicitPersistentChange = action.type === 'MARK_LAST_CHANGE_AS_PERSISTENT' || markNextChangeAsNotPersistent; // Defer to previous state value (or default) unless changing or
// explicitly marking as persistent.
if (state === nextState && !isExplicitPersistentChange) {
var _state$isPersistentCh;
markNextChangeAsNotPersistent = action.type === 'MARK_NEXT_CHANGE_AS_NOT_PERSISTENT';
const nextIsPersistentChange = (_state$isPersistentCh = state === null || state === void 0 ? void 0 : state.isPersistentChange) !== null && _state$isPersistentCh !== void 0 ? _state$isPersistentCh : true;
if (state.isPersistentChange === nextIsPersistentChange) {
return state;
}
return { ...nextState,
isPersistentChange: nextIsPersistentChange
};
}
nextState = { ...nextState,
isPersistentChange: isExplicitPersistentChange ? !markNextChangeAsNotPersistent : !isUpdatingSameBlockAttribute(action, lastAction)
}; // In comparing against the previous action, consider only those which
// would have qualified as one which would have been ignored or not
// have resulted in a changed state.
lastAction = action;
markNextChangeAsNotPersistent = action.type === 'MARK_NEXT_CHANGE_AS_NOT_PERSISTENT';
return nextState;
};
}
/**
* Higher-order reducer intended to augment the blocks reducer, assigning an
* `isIgnoredChange` property value corresponding to whether a change in state
* can be considered as ignored. A change is considered ignored when the result
* of an action not incurred by direct user interaction.
*
* @param {Function} reducer Original reducer function.
*
* @return {Function} Enhanced reducer function.
*/
function withIgnoredBlockChange(reducer) {
/**
* Set of action types for which a blocks state change should be ignored.
*
* @type {Set}
*/
const IGNORED_ACTION_TYPES = new Set(['RECEIVE_BLOCKS']);
return (state, action) => {
const nextState = reducer(state, action);
if (nextState !== state) {
nextState.isIgnoredChange = IGNORED_ACTION_TYPES.has(action.type);
}
return nextState;
};
}
/**
* Higher-order reducer targeting the combined blocks reducer, augmenting
* block client IDs in remove action to include cascade of inner blocks.
*
* @param {Function} reducer Original reducer function.
*
* @return {Function} Enhanced reducer function.
*/
const withInnerBlocksRemoveCascade = reducer => (state, action) => {
// Gets all children which need to be removed.
const getAllChildren = clientIds => {
let result = clientIds;
for (let i = 0; i < result.length; i++) {
if (!state.order.get(result[i]) || action.keepControlledInnerBlocks && action.keepControlledInnerBlocks[result[i]]) {
continue;
}
if (result === clientIds) {
result = [...result];
}
result.push(...state.order.get(result[i]));
}
return result;
};
if (state) {
switch (action.type) {
case 'REMOVE_BLOCKS':
action = { ...action,
type: 'REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN',
removedClientIds: getAllChildren(action.clientIds)
};
break;
case 'REPLACE_BLOCKS':
action = { ...action,
type: 'REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN',
replacedClientIds: getAllChildren(action.clientIds)
};
break;
}
}
return reducer(state, action);
};
/**
* Higher-order reducer which targets the combined blocks reducer and handles
* the `RESET_BLOCKS` action. When dispatched, this action will replace all
* blocks that exist in the post, leaving blocks that exist only in state (e.g.
* reusable blocks and blocks controlled by inner blocks controllers) alone.
*
* @param {Function} reducer Original reducer function.
*
* @return {Function} Enhanced reducer function.
*/
const withBlockReset = reducer => (state, action) => {
if (action.type === 'RESET_BLOCKS') {
const newState = { ...state,
byClientId: new Map(getFlattenedBlocksWithoutAttributes(action.blocks)),
attributes: new Map(getFlattenedBlockAttributes(action.blocks)),
order: mapBlockOrder(action.blocks),
parents: new Map(mapBlockParents(action.blocks)),
controlledInnerBlocks: {}
};
newState.tree = new Map(state === null || state === void 0 ? void 0 : state.tree);
updateBlockTreeForBlocks(newState, action.blocks);
newState.tree.set('', {
innerBlocks: action.blocks.map(subBlock => newState.tree.get(subBlock.clientId))
});
return newState;
}
return reducer(state, action);
};
/**
* Higher-order reducer which targets the combined blocks reducer and handles
* the `REPLACE_INNER_BLOCKS` action. When dispatched, this action the state
* should become equivalent to the execution of a `REMOVE_BLOCKS` action
* containing all the child's of the root block followed by the execution of
* `INSERT_BLOCKS` with the new blocks.
*
* @param {Function} reducer Original reducer function.
*
* @return {Function} Enhanced reducer function.
*/
const withReplaceInnerBlocks = reducer => (state, action) => {
if (action.type !== 'REPLACE_INNER_BLOCKS') {
return reducer(state, action);
} // Finds every nested inner block controller. We must check the action blocks
// and not just the block parent state because some inner block controllers
// should be deleted if specified, whereas others should not be deleted. If
// a controlled should not be deleted, then we need to avoid deleting its
// inner blocks from the block state because its inner blocks will not be
// attached to the block in the action.
const nestedControllers = {};
if (Object.keys(state.controlledInnerBlocks).length) {
const stack = [...action.blocks];
while (stack.length) {
const {
innerBlocks,
...block
} = stack.shift();
stack.push(...innerBlocks);
if (!!state.controlledInnerBlocks[block.clientId]) {
nestedControllers[block.clientId] = true;
}
}
} // The `keepControlledInnerBlocks` prop will keep the inner blocks of the
// marked block in the block state so that they can be reattached to the
// marked block when we re-insert everything a few lines below.
let stateAfterBlocksRemoval = state;
if (state.order.get(action.rootClientId)) {
stateAfterBlocksRemoval = reducer(stateAfterBlocksRemoval, {
type: 'REMOVE_BLOCKS',
keepControlledInnerBlocks: nestedControllers,
clientIds: state.order.get(action.rootClientId)
});
}
let stateAfterInsert = stateAfterBlocksRemoval;
if (action.blocks.length) {
stateAfterInsert = reducer(stateAfterInsert, { ...action,
type: 'INSERT_BLOCKS',
index: 0
}); // We need to re-attach the controlled inner blocks to the blocks tree and
// preserve their block order. Otherwise, an inner block controller's blocks
// will be deleted entirely from its entity.
const stateAfterInsertOrder = new Map(stateAfterInsert.order);
Object.keys(nestedControllers).forEach(key => {
if (state.order.get(key)) {
stateAfterInsertOrder.set(key, state.order.get(key));
}
});
stateAfterInsert.order = stateAfterInsertOrder;
stateAfterInsert.tree = new Map(stateAfterInsert.tree);
Object.keys(nestedControllers).forEach(_key => {
const key = `controlled||${_key}`;
if (state.tree.has(key)) {
stateAfterInsert.tree.set(key, state.tree.get(key));
}
});
}
return stateAfterInsert;
};
/**
* Higher-order reducer which targets the combined blocks reducer and handles
* the `SAVE_REUSABLE_BLOCK_SUCCESS` action. This action can't be handled by
* regular reducers and needs a higher-order reducer since it needs access to
* both `byClientId` and `attributes` simultaneously.
*
* @param {Function} reducer Original reducer function.
*
* @return {Function} Enhanced reducer function.
*/
const withSaveReusableBlock = reducer => (state, action) => {
if (state && action.type === 'SAVE_REUSABLE_BLOCK_SUCCESS') {
const {
id,
updatedId
} = action; // If a temporary reusable block is saved, we swap the temporary id with the final one.
if (id === updatedId) {
return state;
}
state = { ...state
};
state.attributes = new Map(state.attributes);
state.attributes.forEach((attributes, clientId) => {
const {
name
} = state.byClientId.get(clientId);
if (name === 'core/block' && attributes.ref === id) {
state.attributes.set(clientId, { ...attributes,
ref: updatedId
});
}
});
}
return reducer(state, action);
};
/**
* Higher-order reducer which removes blocks from state when switching parent block controlled state.
*
* @param {Function} reducer Original reducer function.
*
* @return {Function} Enhanced reducer function.
*/
const withResetControlledBlocks = reducer => (state, action) => {
if (action.type === 'SET_HAS_CONTROLLED_INNER_BLOCKS') {
// when switching a block from controlled to uncontrolled or inverse,
// we need to remove its content first.
const tempState = reducer(state, {
type: 'REPLACE_INNER_BLOCKS',
rootClientId: action.clientId,
blocks: []
});
return reducer(tempState, action);
}
return reducer(state, action);
};
/**
* Reducer returning the blocks state.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
const blocks = (0,external_wp_compose_namespaceObject.pipe)(external_wp_data_namespaceObject.combineReducers, withSaveReusableBlock, // Needs to be before withBlockCache.
withBlockTree, // Needs to be before withInnerBlocksRemoveCascade.
withInnerBlocksRemoveCascade, withReplaceInnerBlocks, // Needs to be after withInnerBlocksRemoveCascade.
withBlockReset, withPersistentBlockChange, withIgnoredBlockChange, withResetControlledBlocks)({
// The state is using a Map instead of a plain object for performance reasons.
// You can run the "./test/performance.js" unit test to check the impact
// code changes can have on this reducer.
byClientId() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Map();
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'RECEIVE_BLOCKS':
case 'INSERT_BLOCKS':
{
const newState = new Map(state);
getFlattenedBlocksWithoutAttributes(action.blocks).forEach(_ref2 => {
let [key, value] = _ref2;
newState.set(key, value);
});
return newState;
}
case 'UPDATE_BLOCK':
{
// Ignore updates if block isn't known.
if (!state.has(action.clientId)) {
return state;
} // Do nothing if only attributes change.
const {
attributes,
...changes
} = action.updates;
if (Object.values(changes).length === 0) {
return state;
}
const newState = new Map(state);
newState.set(action.clientId, { ...state.get(action.clientId),
...changes
});
return newState;
}
case 'REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN':
{
if (!action.blocks) {
return state;
}
const newState = new Map(state);
action.replacedClientIds.forEach(clientId => {
newState.delete(clientId);
});
getFlattenedBlocksWithoutAttributes(action.blocks).forEach(_ref3 => {
let [key, value] = _ref3;
newState.set(key, value);
});
return newState;
}
case 'REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN':
{
const newState = new Map(state);
action.removedClientIds.forEach(clientId => {
newState.delete(clientId);
});
return newState;
}
}
return state;
},
// The state is using a Map instead of a plain object for performance reasons.
// You can run the "./test/performance.js" unit test to check the impact
// code changes can have on this reducer.
attributes() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Map();
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'RECEIVE_BLOCKS':
case 'INSERT_BLOCKS':
{
const newState = new Map(state);
getFlattenedBlockAttributes(action.blocks).forEach(_ref4 => {
let [key, value] = _ref4;
newState.set(key, value);
});
return newState;
}
case 'UPDATE_BLOCK':
{
// Ignore updates if block isn't known or there are no attribute changes.
if (!state.get(action.clientId) || !action.updates.attributes) {
return state;
}
const newState = new Map(state);
newState.set(action.clientId, { ...state.get(action.clientId),
...action.updates.attributes
});
return newState;
}
case 'UPDATE_BLOCK_ATTRIBUTES':
{
// Avoid a state change if none of the block IDs are known.
if (action.clientIds.every(id => !state.get(id))) {
return state;
}
let hasChange = false;
const newState = new Map(state);
for (const clientId of action.clientIds) {
var _action$attributes;
const updatedAttributeEntries = Object.entries(action.uniqueByBlock ? action.attributes[clientId] : (_action$attributes = action.attributes) !== null && _action$attributes !== void 0 ? _action$attributes : {});
if (updatedAttributeEntries.length === 0) {
continue;
}
let hasUpdatedAttributes = false;
const existingAttributes = state.get(clientId);
const newAttributes = {};
updatedAttributeEntries.forEach(_ref5 => {
let [key, value] = _ref5;
if (existingAttributes[key] !== value) {
hasUpdatedAttributes = true;
newAttributes[key] = value;
}
});
hasChange = hasChange || hasUpdatedAttributes;
if (hasUpdatedAttributes) {
newState.set(clientId, { ...existingAttributes,
...newAttributes
});
}
}
return hasChange ? newState : state;
}
case 'REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN':
{
if (!action.blocks) {
return state;
}
const newState = new Map(state);
action.replacedClientIds.forEach(clientId => {
newState.delete(clientId);
});
getFlattenedBlockAttributes(action.blocks).forEach(_ref6 => {
let [key, value] = _ref6;
newState.set(key, value);
});
return newState;
}
case 'REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN':
{
const newState = new Map(state);
action.removedClientIds.forEach(clientId => {
newState.delete(clientId);
});
return newState;
}
}
return state;
},
// The state is using a Map instead of a plain object for performance reasons.
// You can run the "./test/performance.js" unit test to check the impact
// code changes can have on this reducer.
order() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Map();
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'RECEIVE_BLOCKS':
{
var _state$get;
const blockOrder = mapBlockOrder(action.blocks);
const newState = new Map(state);
blockOrder.forEach((order, clientId) => {
if (clientId !== '') {
newState.set(clientId, order);
}
});
newState.set('', ((_state$get = state.get('')) !== null && _state$get !== void 0 ? _state$get : []).concat(blockOrder['']));
return newState;
}
case 'INSERT_BLOCKS':
{
const {
rootClientId = ''
} = action;
const subState = state.get(rootClientId) || [];
const mappedBlocks = mapBlockOrder(action.blocks, rootClientId);
const {
index = subState.length
} = action;
const newState = new Map(state);
mappedBlocks.forEach((order, clientId) => {
newState.set(clientId, order);
});
newState.set(rootClientId, insertAt(subState, mappedBlocks.get(rootClientId), index));
return newState;
}
case 'MOVE_BLOCKS_TO_POSITION':
{
var _state$get$filter, _state$get2;
const {
fromRootClientId = '',
toRootClientId = '',
clientIds
} = action;
const {
index = state.get(toRootClientId).length
} = action; // Moving inside the same parent block.
if (fromRootClientId === toRootClientId) {
const subState = state.get(toRootClientId);
const fromIndex = subState.indexOf(clientIds[0]);
const newState = new Map(state);
newState.set(toRootClientId, moveTo(state.get(toRootClientId), fromIndex, index, clientIds.length));
return newState;
} // Moving from a parent block to another.
const newState = new Map(state);
newState.set(fromRootClientId, (_state$get$filter = (_state$get2 = state.get(fromRootClientId)) === null || _state$get2 === void 0 ? void 0 : _state$get2.filter(id => !clientIds.includes(id))) !== null && _state$get$filter !== void 0 ? _state$get$filter : []);
newState.set(toRootClientId, insertAt(state.get(toRootClientId), clientIds, index));
return newState;
}
case 'MOVE_BLOCKS_UP':
{
const {
clientIds,
rootClientId = ''
} = action;
const firstClientId = clientIds[0];
const subState = state.get(rootClientId);
if (!subState.length || firstClientId === subState[0]) {
return state;
}
const firstIndex = subState.indexOf(firstClientId);
const newState = new Map(state);
newState.set(rootClientId, moveTo(subState, firstIndex, firstIndex - 1, clientIds.length));
return newState;
}
case 'MOVE_BLOCKS_DOWN':
{
const {
clientIds,
rootClientId = ''
} = action;
const firstClientId = clientIds[0];
const lastClientId = clientIds[clientIds.length - 1];
const subState = state.get(rootClientId);
if (!subState.length || lastClientId === subState[subState.length - 1]) {
return state;
}
const firstIndex = subState.indexOf(firstClientId);
const newState = new Map(state);
newState.set(rootClientId, moveTo(subState, firstIndex, firstIndex + 1, clientIds.length));
return newState;
}
case 'REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN':
{
const {
clientIds
} = action;
if (!action.blocks) {
return state;
}
const mappedBlocks = mapBlockOrder(action.blocks);
const newState = new Map(state);
action.replacedClientIds.forEach(clientId => {
newState.delete(clientId);
});
mappedBlocks.forEach((order, clientId) => {
if (clientId !== '') {
newState.set(clientId, order);
}
});
newState.forEach((order, clientId) => {
const newSubOrder = Object.values(order).reduce((result, subClientId) => {
if (subClientId === clientIds[0]) {
return [...result, ...mappedBlocks.get('')];
}
if (clientIds.indexOf(subClientId) === -1) {
result.push(subClientId);
}
return result;
}, []);
newState.set(clientId, newSubOrder);
});
return newState;
}
case 'REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN':
{
const newState = new Map(state); // Remove inner block ordering for removed blocks.
action.removedClientIds.forEach(clientId => {
newState.delete(clientId);
});
newState.forEach((order, clientId) => {
var _order$filter;
const newSubOrder = (_order$filter = order === null || order === void 0 ? void 0 : order.filter(id => !action.removedClientIds.includes(id))) !== null && _order$filter !== void 0 ? _order$filter : [];
if (newSubOrder.length !== order.length) {
newState.set(clientId, newSubOrder);
}
});
return newState;
}
}
return state;
},
// While technically redundant data as the inverse of `order`, it serves as
// an optimization for the selectors which derive the ancestry of a block.
parents() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Map();
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'RECEIVE_BLOCKS':
{
const newState = new Map(state);
mapBlockParents(action.blocks).forEach(_ref7 => {
let [key, value] = _ref7;
newState.set(key, value);
});
return newState;
}
case 'INSERT_BLOCKS':
{
const newState = new Map(state);
mapBlockParents(action.blocks, action.rootClientId || '').forEach(_ref8 => {
let [key, value] = _ref8;
newState.set(key, value);
});
return newState;
}
case 'MOVE_BLOCKS_TO_POSITION':
{
const newState = new Map(state);
action.clientIds.forEach(id => {
newState.set(id, action.toRootClientId || '');
});
return newState;
}
case 'REPLACE_BLOCKS_AUGMENTED_WITH_CHILDREN':
{
const newState = new Map(state);
action.replacedClientIds.forEach(clientId => {
newState.delete(clientId);
});
mapBlockParents(action.blocks, state.get(action.clientIds[0])).forEach(_ref9 => {
let [key, value] = _ref9;
newState.set(key, value);
});
return newState;
}
case 'REMOVE_BLOCKS_AUGMENTED_WITH_CHILDREN':
{
const newState = new Map(state);
action.removedClientIds.forEach(clientId => {
newState.delete(clientId);
});
return newState;
}
}
return state;
},
controlledInnerBlocks() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let {
type,
clientId,
hasControlledInnerBlocks
} = arguments.length > 1 ? arguments[1] : undefined;
if (type === 'SET_HAS_CONTROLLED_INNER_BLOCKS') {
return { ...state,
[clientId]: hasControlledInnerBlocks
};
}
return state;
}
});
/**
* Reducer returning visibility status of block interface.
*
* @param {boolean} state Current state.
* @param {Object} action Dispatched action.
*
* @return {boolean} Updated state.
*/
function isBlockInterfaceHidden() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'HIDE_BLOCK_INTERFACE':
return true;
case 'SHOW_BLOCK_INTERFACE':
return false;
}
return state;
}
/**
* Reducer returning typing state.
*
* @param {boolean} state Current state.
* @param {Object} action Dispatched action.
*
* @return {boolean} Updated state.
*/
function isTyping() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'START_TYPING':
return true;
case 'STOP_TYPING':
return false;
}
return state;
}
/**
* Reducer returning dragged block client id.
*
* @param {string[]} state Current state.
* @param {Object} action Dispatched action.
*
* @return {string[]} Updated state.
*/
function draggedBlocks() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'START_DRAGGING_BLOCKS':
return action.clientIds;
case 'STOP_DRAGGING_BLOCKS':
return [];
}
return state;
}
/**
* Reducer tracking the visible blocks.
*
* @param {Record<string,boolean>} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Record<string,boolean>} Block visibility.
*/
function blockVisibility() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
if (action.type === 'SET_BLOCK_VISIBILITY') {
return { ...state,
...action.updates
};
}
return state;
}
/**
* Internal helper reducer for selectionStart and selectionEnd. Can hold a block
* selection, represented by an object with property clientId.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
function selectionHelper() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'CLEAR_SELECTED_BLOCK':
{
if (state.clientId) {
return {};
}
return state;
}
case 'SELECT_BLOCK':
if (action.clientId === state.clientId) {
return state;
}
return {
clientId: action.clientId
};
case 'REPLACE_INNER_BLOCKS':
case 'INSERT_BLOCKS':
{
if (!action.updateSelection || !action.blocks.length) {
return state;
}
return {
clientId: action.blocks[0].clientId
};
}
case 'REMOVE_BLOCKS':
if (!action.clientIds || !action.clientIds.length || action.clientIds.indexOf(state.clientId) === -1) {
return state;
}
return {};
case 'REPLACE_BLOCKS':
{
if (action.clientIds.indexOf(state.clientId) === -1) {
return state;
}
const blockToSelect = action.blocks[action.indexToSelect] || action.blocks[action.blocks.length - 1];
if (!blockToSelect) {
return {};
}
if (blockToSelect.clientId === state.clientId) {
return state;
}
return {
clientId: blockToSelect.clientId
};
}
}
return state;
}
/**
* Reducer returning the selection state.
*
* @param {boolean} state Current state.
* @param {Object} action Dispatched action.
*
* @return {boolean} Updated state.
*/
function selection() {
var _state$selectionStart, _state$selectionEnd, _state$selectionStart2, _state$selectionEnd2;
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'SELECTION_CHANGE':
if (action.clientId) {
return {
selectionStart: {
clientId: action.clientId,
attributeKey: action.attributeKey,
offset: action.startOffset
},
selectionEnd: {
clientId: action.clientId,
attributeKey: action.attributeKey,
offset: action.endOffset
}
};
}
return {
selectionStart: action.start || state.selectionStart,
selectionEnd: action.end || state.selectionEnd
};
case 'RESET_SELECTION':
const {
selectionStart,
selectionEnd
} = action;
return {
selectionStart,
selectionEnd
};
case 'MULTI_SELECT':
const {
start,
end
} = action;
if (start === ((_state$selectionStart = state.selectionStart) === null || _state$selectionStart === void 0 ? void 0 : _state$selectionStart.clientId) && end === ((_state$selectionEnd = state.selectionEnd) === null || _state$selectionEnd === void 0 ? void 0 : _state$selectionEnd.clientId)) {
return state;
}
return {
selectionStart: {
clientId: start
},
selectionEnd: {
clientId: end
}
};
case 'RESET_BLOCKS':
const startClientId = state === null || state === void 0 ? void 0 : (_state$selectionStart2 = state.selectionStart) === null || _state$selectionStart2 === void 0 ? void 0 : _state$selectionStart2.clientId;
const endClientId = state === null || state === void 0 ? void 0 : (_state$selectionEnd2 = state.selectionEnd) === null || _state$selectionEnd2 === void 0 ? void 0 : _state$selectionEnd2.clientId; // Do nothing if there's no selected block.
if (!startClientId && !endClientId) {
return state;
} // If the start of the selection won't exist after reset, remove selection.
if (!action.blocks.some(block => block.clientId === startClientId)) {
return {
selectionStart: {},
selectionEnd: {}
};
} // If the end of the selection won't exist after reset, collapse selection.
if (!action.blocks.some(block => block.clientId === endClientId)) {
return { ...state,
selectionEnd: state.selectionStart
};
}
}
return {
selectionStart: selectionHelper(state.selectionStart, action),
selectionEnd: selectionHelper(state.selectionEnd, action)
};
}
/**
* Reducer returning whether the user is multi-selecting.
*
* @param {boolean} state Current state.
* @param {Object} action Dispatched action.
*
* @return {boolean} Updated state.
*/
function isMultiSelecting() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'START_MULTI_SELECT':
return true;
case 'STOP_MULTI_SELECT':
return false;
}
return state;
}
/**
* Reducer returning whether selection is enabled.
*
* @param {boolean} state Current state.
* @param {Object} action Dispatched action.
*
* @return {boolean} Updated state.
*/
function isSelectionEnabled() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'TOGGLE_SELECTION':
return action.isSelectionEnabled;
}
return state;
}
/**
* Reducer returning the initial block selection.
*
* Currently this in only used to restore the selection after block deletion and
* pasting new content.This reducer should eventually be removed in favour of setting
* selection directly.
*
* @param {boolean} state Current state.
* @param {Object} action Dispatched action.
*
* @return {number|null} Initial position: 0, -1 or null.
*/
function initialPosition() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
let action = arguments.length > 1 ? arguments[1] : undefined;
if (action.type === 'REPLACE_BLOCKS' && action.initialPosition !== undefined) {
return action.initialPosition;
} else if (['MULTI_SELECT', 'SELECT_BLOCK', 'RESET_SELECTION', 'INSERT_BLOCKS', 'REPLACE_INNER_BLOCKS'].includes(action.type)) {
return action.initialPosition;
}
return state;
}
function blocksMode() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
if (action.type === 'TOGGLE_BLOCK_MODE') {
const {
clientId
} = action;
return { ...state,
[clientId]: state[clientId] && state[clientId] === 'html' ? 'visual' : 'html'
};
}
return state;
}
/**
* Reducer returning the block insertion point visibility, either null if there
* is not an explicit insertion point assigned, or an object of its `index` and
* `rootClientId`.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
function insertionPoint() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'SHOW_INSERTION_POINT':
{
const {
rootClientId,
index,
__unstableWithInserter,
operation
} = action;
const nextState = {
rootClientId,
index,
__unstableWithInserter,
operation
}; // Bail out updates if the states are the same.
return es6_default()(state, nextState) ? state : nextState;
}
case 'HIDE_INSERTION_POINT':
return null;
}
return state;
}
/**
* Reducer returning whether the post blocks match the defined template or not.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {boolean} Updated state.
*/
function template() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
isValid: true
};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'SET_TEMPLATE_VALIDITY':
return { ...state,
isValid: action.isValid
};
}
return state;
}
/**
* Reducer returning the editor setting.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
function settings() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : SETTINGS_DEFAULTS;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'UPDATE_SETTINGS':
return { ...state,
...action.settings
};
}
return state;
}
/**
* Reducer returning the user preferences.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {string} Updated state.
*/
function preferences() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : PREFERENCES_DEFAULTS;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'INSERT_BLOCKS':
case 'REPLACE_BLOCKS':
return action.blocks.reduce((prevState, block) => {
const {
attributes,
name: blockName
} = block;
const match = (0,external_wp_data_namespaceObject.select)(external_wp_blocks_namespaceObject.store).getActiveBlockVariation(blockName, attributes); // If a block variation match is found change the name to be the same with the
// one that is used for block variations in the Inserter (`getItemFromVariation`).
let id = match !== null && match !== void 0 && match.name ? `${blockName}/${match.name}` : blockName;
const insert = {
name: id
};
if (blockName === 'core/block') {
insert.ref = attributes.ref;
id += '/' + attributes.ref;
}
return { ...prevState,
insertUsage: { ...prevState.insertUsage,
[id]: {
time: action.time,
count: prevState.insertUsage[id] ? prevState.insertUsage[id].count + 1 : 1,
insert
}
}
};
}, state);
}
return state;
}
/**
* Reducer returning an object where each key is a block client ID, its value
* representing the settings for its nested blocks.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
const blockListSettings = function () {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
// Even if the replaced blocks have the same client ID, our logic
// should correct the state.
case 'REPLACE_BLOCKS':
case 'REMOVE_BLOCKS':
{
return Object.fromEntries(Object.entries(state).filter(_ref10 => {
let [id] = _ref10;
return !action.clientIds.includes(id);
}));
}
case 'UPDATE_BLOCK_LIST_SETTINGS':
{
const {
clientId
} = action;
if (!action.settings) {
if (state.hasOwnProperty(clientId)) {
const {
[clientId]: removedBlock,
...restBlocks
} = state;
return restBlocks;
}
return state;
}
if (es6_default()(state[clientId], action.settings)) {
return state;
}
return { ...state,
[clientId]: action.settings
};
}
}
return state;
};
/**
* Reducer returning which mode is enabled.
*
* @param {string} state Current state.
* @param {Object} action Dispatched action.
*
* @return {string} Updated state.
*/
function editorMode() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'edit';
let action = arguments.length > 1 ? arguments[1] : undefined;
// Let inserting block in navigation mode always trigger Edit mode.
if (action.type === 'INSERT_BLOCKS' && state === 'navigation') {
return 'edit';
}
if (action.type === 'SET_EDITOR_MODE') {
return action.mode;
}
return state;
}
/**
* Reducer returning whether the block moving mode is enabled or not.
*
* @param {string|null} state Current state.
* @param {Object} action Dispatched action.
*
* @return {string|null} Updated state.
*/
function hasBlockMovingClientId() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
let action = arguments.length > 1 ? arguments[1] : undefined;
if (action.type === 'SET_BLOCK_MOVING_MODE') {
return action.hasBlockMovingClientId;
}
if (action.type === 'SET_EDITOR_MODE') {
return null;
}
return state;
}
/**
* Reducer return an updated state representing the most recent block attribute
* update. The state is structured as an object where the keys represent the
* client IDs of blocks, the values a subset of attributes from the most recent
* block update. The state is always reset to null if the last action is
* anything other than an attributes update.
*
* @param {Object<string,Object>} state Current state.
* @param {Object} action Action object.
*
* @return {[string,Object]} Updated state.
*/
function lastBlockAttributesChange() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'UPDATE_BLOCK':
if (!action.updates.attributes) {
break;
}
return {
[action.clientId]: action.updates.attributes
};
case 'UPDATE_BLOCK_ATTRIBUTES':
return action.clientIds.reduce((accumulator, id) => ({ ...accumulator,
[id]: action.uniqueByBlock ? action.attributes[id] : action.attributes
}), {});
}
return state;
}
/**
* Reducer returning automatic change state.
*
* @param {?string} state Current state.
* @param {Object} action Dispatched action.
*
* @return {string | undefined} Updated state.
*/
function automaticChangeStatus(state, action) {
switch (action.type) {
case 'MARK_AUTOMATIC_CHANGE':
return 'pending';
case 'MARK_AUTOMATIC_CHANGE_FINAL':
if (state === 'pending') {
return 'final';
}
return;
case 'SELECTION_CHANGE':
// As long as the state is not final, ignore any selection changes.
if (state !== 'final') {
return state;
}
return;
// Undoing an automatic change should still be possible after mouse
// move or after visibility change.
case 'SET_BLOCK_VISIBILITY':
case 'START_TYPING':
case 'STOP_TYPING':
case 'UPDATE_BLOCK_LIST_SETTINGS':
return state;
} // TODO: This is a source of bug, as each time there's a change in timing,
// or a new action is added, this could break.
// Reset the state by default (for any action not handled).
}
/**
* Reducer returning current highlighted block.
*
* @param {boolean} state Current highlighted block.
* @param {Object} action Dispatched action.
*
* @return {string} Updated state.
*/
function highlightedBlock(state, action) {
switch (action.type) {
case 'TOGGLE_BLOCK_HIGHLIGHT':
const {
clientId,
isHighlighted
} = action;
if (isHighlighted) {
return clientId;
} else if (state === clientId) {
return null;
}
return state;
case 'SELECT_BLOCK':
if (action.clientId !== state) {
return null;
}
}
return state;
}
/**
* Reducer returning the block insertion event list state.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
function lastBlockInserted() {
var _action$meta;
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'INSERT_BLOCKS':
case 'REPLACE_BLOCKS':
case 'REPLACE_INNER_BLOCKS':
if (!action.blocks.length) {
return state;
}
const clientIds = action.blocks.map(block => {
return block.clientId;
});
const source = (_action$meta = action.meta) === null || _action$meta === void 0 ? void 0 : _action$meta.source;
return {
clientIds,
source
};
case 'RESET_BLOCKS':
return {};
}
return state;
}
/**
* Reducer returning the block that is eding temporarily edited as blocks.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
function temporarilyEditingAsBlocks() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
let action = arguments.length > 1 ? arguments[1] : undefined;
if (action.type === 'SET_TEMPORARILY_EDITING_AS_BLOCKS') {
return action.temporarilyEditingAsBlocks;
}
return state;
}
/* harmony default export */ var reducer = ((0,external_wp_data_namespaceObject.combineReducers)({
blocks,
isTyping,
isBlockInterfaceHidden,
draggedBlocks,
selection,
isMultiSelecting,
isSelectionEnabled,
initialPosition,
blocksMode,
blockListSettings,
insertionPoint,
template,
settings,
preferences,
lastBlockAttributesChange,
editorMode,
hasBlockMovingClientId,
automaticChangeStatus,
highlightedBlock,
lastBlockInserted,
temporarilyEditingAsBlocks,
blockVisibility
}));
;// CONCATENATED MODULE: ./node_modules/rememo/rememo.js
/** @typedef {(...args: any[]) => *[]} GetDependants */
/** @typedef {() => void} Clear */
/**
* @typedef {{
* getDependants: GetDependants,
* clear: Clear
* }} EnhancedSelector
*/
/**
* Internal cache entry.
*
* @typedef CacheNode
*
* @property {?CacheNode|undefined} [prev] Previous node.
* @property {?CacheNode|undefined} [next] Next node.
* @property {*[]} args Function arguments for cache entry.
* @property {*} val Function result.
*/
/**
* @typedef Cache
*
* @property {Clear} clear Function to clear cache.
* @property {boolean} [isUniqueByDependants] Whether dependants are valid in
* considering cache uniqueness. A cache is unique if dependents are all arrays
* or objects.
* @property {CacheNode?} [head] Cache head.
* @property {*[]} [lastDependants] Dependants from previous invocation.
*/
/**
* Arbitrary value used as key for referencing cache object in WeakMap tree.
*
* @type {{}}
*/
var LEAF_KEY = {};
/**
* Returns the first argument as the sole entry in an array.
*
* @template T
*
* @param {T} value Value to return.
*
* @return {[T]} Value returned as entry in array.
*/
function arrayOf(value) {
return [value];
}
/**
* Returns true if the value passed is object-like, or false otherwise. A value
* is object-like if it can support property assignment, e.g. object or array.
*
* @param {*} value Value to test.
*
* @return {boolean} Whether value is object-like.
*/
function isObjectLike(value) {
return !!value && 'object' === typeof value;
}
/**
* Creates and returns a new cache object.
*
* @return {Cache} Cache object.
*/
function createCache() {
/** @type {Cache} */
var cache = {
clear: function () {
cache.head = null;
},
};
return cache;
}
/**
* Returns true if entries within the two arrays are strictly equal by
* reference from a starting index.
*
* @param {*[]} a First array.
* @param {*[]} b Second array.
* @param {number} fromIndex Index from which to start comparison.
*
* @return {boolean} Whether arrays are shallowly equal.
*/
function isShallowEqual(a, b, fromIndex) {
var i;
if (a.length !== b.length) {
return false;
}
for (i = fromIndex; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
/**
* Returns a memoized selector function. The getDependants function argument is
* called before the memoized selector and is expected to return an immutable
* reference or array of references on which the selector depends for computing
* its own return value. The memoize cache is preserved only as long as those
* dependant references remain the same. If getDependants returns a different
* reference(s), the cache is cleared and the selector value regenerated.
*
* @template {(...args: *[]) => *} S
*
* @param {S} selector Selector function.
* @param {GetDependants=} getDependants Dependant getter returning an array of
* references used in cache bust consideration.
*/
/* harmony default export */ function rememo(selector, getDependants) {
/** @type {WeakMap<*,*>} */
var rootCache;
/** @type {GetDependants} */
var normalizedGetDependants = getDependants ? getDependants : arrayOf;
/**
* Returns the cache for a given dependants array. When possible, a WeakMap
* will be used to create a unique cache for each set of dependants. This
* is feasible due to the nature of WeakMap in allowing garbage collection
* to occur on entries where the key object is no longer referenced. Since
* WeakMap requires the key to be an object, this is only possible when the
* dependant is object-like. The root cache is created as a hierarchy where
* each top-level key is the first entry in a dependants set, the value a
* WeakMap where each key is the next dependant, and so on. This continues
* so long as the dependants are object-like. If no dependants are object-
* like, then the cache is shared across all invocations.
*
* @see isObjectLike
*
* @param {*[]} dependants Selector dependants.
*
* @return {Cache} Cache object.
*/
function getCache(dependants) {
var caches = rootCache,
isUniqueByDependants = true,
i,
dependant,
map,
cache;
for (i = 0; i < dependants.length; i++) {
dependant = dependants[i];
// Can only compose WeakMap from object-like key.
if (!isObjectLike(dependant)) {
isUniqueByDependants = false;
break;
}
// Does current segment of cache already have a WeakMap?
if (caches.has(dependant)) {
// Traverse into nested WeakMap.
caches = caches.get(dependant);
} else {
// Create, set, and traverse into a new one.
map = new WeakMap();
caches.set(dependant, map);
caches = map;
}
}
// We use an arbitrary (but consistent) object as key for the last item
// in the WeakMap to serve as our running cache.
if (!caches.has(LEAF_KEY)) {
cache = createCache();
cache.isUniqueByDependants = isUniqueByDependants;
caches.set(LEAF_KEY, cache);
}
return caches.get(LEAF_KEY);
}
/**
* Resets root memoization cache.
*/
function clear() {
rootCache = new WeakMap();
}
/* eslint-disable jsdoc/check-param-names */
/**
* The augmented selector call, considering first whether dependants have
* changed before passing it to underlying memoize function.
*
* @param {*} source Source object for derivation.
* @param {...*} extraArgs Additional arguments to pass to selector.
*
* @return {*} Selector result.
*/
/* eslint-enable jsdoc/check-param-names */
function callSelector(/* source, ...extraArgs */) {
var len = arguments.length,
cache,
node,
i,
args,
dependants;
// Create copy of arguments (avoid leaking deoptimization).
args = new Array(len);
for (i = 0; i < len; i++) {
args[i] = arguments[i];
}
dependants = normalizedGetDependants.apply(null, args);
cache = getCache(dependants);
// If not guaranteed uniqueness by dependants (primitive type), shallow
// compare against last dependants and, if references have changed,
// destroy cache to recalculate result.
if (!cache.isUniqueByDependants) {
if (
cache.lastDependants &&
!isShallowEqual(dependants, cache.lastDependants, 0)
) {
cache.clear();
}
cache.lastDependants = dependants;
}
node = cache.head;
while (node) {
// Check whether node arguments match arguments
if (!isShallowEqual(node.args, args, 1)) {
node = node.next;
continue;
}
// At this point we can assume we've found a match
// Surface matched node to head if not already
if (node !== cache.head) {
// Adjust siblings to point to each other.
/** @type {CacheNode} */ (node.prev).next = node.next;
if (node.next) {
node.next.prev = node.prev;
}
node.next = cache.head;
node.prev = null;
/** @type {CacheNode} */ (cache.head).prev = node;
cache.head = node;
}
// Return immediately
return node.val;
}
// No cached value found. Continue to insertion phase:
node = /** @type {CacheNode} */ ({
// Generate the result from original function
val: selector.apply(null, args),
});
// Avoid including the source object in the cache.
args[0] = null;
node.args = args;
// Don't need to check whether node is already head, since it would
// have been returned above already if it was
// Shift existing head down list
if (cache.head) {
cache.head.prev = node;
node.next = cache.head;
}
cache.head = node;
return node.val;
}
callSelector.getDependants = normalizedGetDependants;
callSelector.clear = clear;
clear();
return /** @type {S & EnhancedSelector} */ (callSelector);
}
;// 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: external ["wp","richText"]
var external_wp_richText_namespaceObject = window["wp"]["richText"];
;// CONCATENATED MODULE: external ["wp","deprecated"]
var external_wp_deprecated_namespaceObject = window["wp"]["deprecated"];
var external_wp_deprecated_default = /*#__PURE__*/__webpack_require__.n(external_wp_deprecated_namespaceObject);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/store/utils.js
/**
* Helper function that maps attribute definition properties to the
* ones used by RichText utils like `create, toHTMLString, etc..`.
*
* @param {Object} attributeDefinition A block's attribute definition object.
* @return {Object} The mapped object.
*/
function mapRichTextSettings(attributeDefinition) {
const {
multiline: multilineTag,
__unstableMultilineWrapperTags: multilineWrapperTags,
__unstablePreserveWhiteSpace: preserveWhiteSpace
} = attributeDefinition;
return {
multilineTag,
multilineWrapperTags,
preserveWhiteSpace
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/utils/sorting.js
/**
* Recursive stable sorting comparator function.
*
* @param {string|Function} field Field to sort by.
* @param {Array} items Items to sort.
* @param {string} order Order, 'asc' or 'desc'.
* @return {Function} Comparison function to be used in a `.sort()`.
*/
const comparator = (field, items, order) => {
return (a, b) => {
let cmpA, cmpB;
if (typeof field === 'function') {
cmpA = field(a);
cmpB = field(b);
} else {
cmpA = a[field];
cmpB = b[field];
}
if (cmpA > cmpB) {
return order === 'asc' ? 1 : -1;
} else if (cmpB > cmpA) {
return order === 'asc' ? -1 : 1;
}
const orderA = items.findIndex(item => item === a);
const orderB = items.findIndex(item => item === b); // Stable sort: maintaining original array order
if (orderA > orderB) {
return 1;
} else if (orderB > orderA) {
return -1;
}
return 0;
};
};
/**
* Order items by a certain key.
* Supports decorator functions that allow complex picking of a comparison field.
* Sorts in ascending order by default, but supports descending as well.
* Stable sort - maintains original order of equal items.
*
* @param {Array} items Items to order.
* @param {string|Function} field Field to order by.
* @param {string} order Sorting order, `asc` or `desc`.
* @return {Array} Sorted items.
*/
function orderBy(items, field) {
let order = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'asc';
return items.concat().sort(comparator(field, items, order));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/store/selectors.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* A block selection object.
*
* @typedef {Object} WPBlockSelection
*
* @property {string} clientId A block client ID.
* @property {string} attributeKey A block attribute key.
* @property {number} offset An attribute value offset, based on the rich
* text value. See `wp.richText.create`.
*/
// Module constants.
const MILLISECONDS_PER_HOUR = 3600 * 1000;
const MILLISECONDS_PER_DAY = 24 * 3600 * 1000;
const MILLISECONDS_PER_WEEK = 7 * 24 * 3600 * 1000;
/**
* 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
* other pure component which performs `shouldComponentUpdate` check on props.
* This should be used as a last resort, since the normalized data should be
* maintained by the reducer result in state.
*
* @type {Array}
*/
const EMPTY_ARRAY = [];
/**
* Returns a block's name given its client ID, or null if no block exists with
* the client ID.
*
* @param {Object} state Editor state.
* @param {string} clientId Block client ID.
*
* @return {string} Block name.
*/
function getBlockName(state, clientId) {
const block = state.blocks.byClientId.get(clientId);
const socialLinkName = 'core/social-link';
if (external_wp_element_namespaceObject.Platform.OS !== 'web' && (block === null || block === void 0 ? void 0 : block.name) === socialLinkName) {
const attributes = state.blocks.attributes.get(clientId);
const {
service
} = attributes !== null && attributes !== void 0 ? attributes : {};
return service ? `${socialLinkName}-${service}` : socialLinkName;
}
return block ? block.name : null;
}
/**
* Returns whether a block is valid or not.
*
* @param {Object} state Editor state.
* @param {string} clientId Block client ID.
*
* @return {boolean} Is Valid.
*/
function isBlockValid(state, clientId) {
const block = state.blocks.byClientId.get(clientId);
return !!block && block.isValid;
}
/**
* Returns a block's attributes given its client ID, or null if no block exists with
* the client ID.
*
* @param {Object} state Editor state.
* @param {string} clientId Block client ID.
*
* @return {Object?} Block attributes.
*/
function getBlockAttributes(state, clientId) {
const block = state.blocks.byClientId.get(clientId);
if (!block) {
return null;
}
return state.blocks.attributes.get(clientId);
}
/**
* Returns a block given its client ID. This is a parsed copy of the block,
* containing its `blockName`, `clientId`, and current `attributes` state. This
* is not the block's registration settings, which must be retrieved from the
* blocks module registration store.
*
* getBlock recurses through its inner blocks until all its children blocks have
* been retrieved. Note that getBlock will not return the child inner blocks of
* an inner block controller. This is because an inner block controller syncs
* itself with its own entity, and should therefore not be included with the
* blocks of a different entity. For example, say you call `getBlocks( TP )` to
* get the blocks of a template part. If another template part is a child of TP,
* then the nested template part's child blocks will not be returned. This way,
* the template block itself is considered part of the parent, but the children
* are not.
*
* @param {Object} state Editor state.
* @param {string} clientId Block client ID.
*
* @return {Object} Parsed block object.
*/
function getBlock(state, clientId) {
if (!state.blocks.byClientId.has(clientId)) {
return null;
}
return state.blocks.tree.get(clientId);
}
const __unstableGetBlockWithoutInnerBlocks = rememo((state, clientId) => {
if (!state.blocks.byClientId.has(clientId)) {
return null;
}
return { ...state.blocks.byClientId.get(clientId),
attributes: getBlockAttributes(state, clientId)
};
}, (state, clientId) => [state.blocks.byClientId.get(clientId), state.blocks.attributes.get(clientId)]);
/**
* Returns all block objects for the current post being edited as an array in
* the order they appear in the post. Note that this will exclude child blocks
* of nested inner block controllers.
*
* @param {Object} state Editor state.
* @param {?string} rootClientId Optional root client ID of block list.
*
* @return {Object[]} Post blocks.
*/
function getBlocks(state, rootClientId) {
var _state$blocks$tree$ge;
const treeKey = !rootClientId || !areInnerBlocksControlled(state, rootClientId) ? rootClientId || '' : 'controlled||' + rootClientId;
return ((_state$blocks$tree$ge = state.blocks.tree.get(treeKey)) === null || _state$blocks$tree$ge === void 0 ? void 0 : _state$blocks$tree$ge.innerBlocks) || EMPTY_ARRAY;
}
/**
* Returns a stripped down block object containing only its client ID,
* and its inner blocks' client IDs.
*
* @param {Object} state Editor state.
* @param {string} clientId Client ID of the block to get.
*
* @return {Object} Client IDs of the post blocks.
*/
const __unstableGetClientIdWithClientIdsTree = rememo((state, clientId) => ({
clientId,
innerBlocks: __unstableGetClientIdsTree(state, clientId)
}), state => [state.blocks.order]);
/**
* Returns the block tree represented in the block-editor store from the
* given root, consisting of stripped down block objects containing only
* their client IDs, and their inner blocks' client IDs.
*
* @param {Object} state Editor state.
* @param {?string} rootClientId Optional root client ID of block list.
*
* @return {Object[]} Client IDs of the post blocks.
*/
const __unstableGetClientIdsTree = rememo(function (state) {
let rootClientId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
return getBlockOrder(state, rootClientId).map(clientId => __unstableGetClientIdWithClientIdsTree(state, clientId));
}, state => [state.blocks.order]);
/**
* Returns an array containing the clientIds of all descendants of the blocks
* given. Returned ids are ordered first by the order of the ids given, then
* by the order that they appear in the editor.
*
* @param {Object} state Global application state.
* @param {Array} clientIds Array of blocks to inspect.
*
* @return {Array} ids of descendants.
*/
const getClientIdsOfDescendants = rememo((state, clientIds) => {
const collectedIds = [];
for (const givenId of clientIds) {
for (const descendantId of getBlockOrder(state, givenId)) {
collectedIds.push(descendantId, ...getClientIdsOfDescendants(state, [descendantId]));
}
}
return collectedIds;
}, state => [state.blocks.order]);
/**
* Returns an array containing the clientIds of the top-level blocks and
* their descendants of any depth (for nested blocks). Ids are returned
* in the same order that they appear in the editor.
*
* @param {Object} state Global application state.
*
* @return {Array} ids of top-level and descendant blocks.
*/
const getClientIdsWithDescendants = rememo(state => {
const collectedIds = [];
for (const topLevelId of getBlockOrder(state)) {
collectedIds.push(topLevelId, ...getClientIdsOfDescendants(state, [topLevelId]));
}
return collectedIds;
}, state => [state.blocks.order]);
/**
* Returns the total number of blocks, or the total number of blocks with a specific name in a post.
* The number returned includes nested blocks.
*
* @param {Object} state Global application state.
* @param {?string} blockName Optional block name, if specified only blocks of that type will be counted.
*
* @return {number} Number of blocks in the post, or number of blocks with name equal to blockName.
*/
const getGlobalBlockCount = rememo((state, blockName) => {
const clientIds = getClientIdsWithDescendants(state);
if (!blockName) {
return clientIds.length;
}
return clientIds.reduce((accumulator, clientId) => {
const block = state.blocks.byClientId.get(clientId);
return block.name === blockName ? accumulator + 1 : accumulator;
}, 0);
}, state => [state.blocks.order, state.blocks.byClientId]);
/**
* Returns all global blocks that match a blockName. Results include nested blocks.
*
* @param {Object} state Global application state.
* @param {?string} blockName Optional block name, if not specified, returns an empty array.
*
* @return {Array} Array of clientIds of blocks with name equal to blockName.
*/
const __experimentalGetGlobalBlocksByName = rememo((state, blockName) => {
if (!blockName) {
return EMPTY_ARRAY;
}
const clientIds = getClientIdsWithDescendants(state);
const foundBlocks = clientIds.filter(clientId => {
const block = state.blocks.byClientId.get(clientId);
return block.name === blockName;
});
return foundBlocks.length > 0 ? foundBlocks : EMPTY_ARRAY;
}, state => [state.blocks.order, state.blocks.byClientId]);
/**
* Given an array of block client IDs, returns the corresponding array of block
* objects.
*
* @param {Object} state Editor state.
* @param {string[]} clientIds Client IDs for which blocks are to be returned.
*
* @return {WPBlock[]} Block objects.
*/
const getBlocksByClientId = rememo((state, clientIds) => (Array.isArray(clientIds) ? clientIds : [clientIds]).map(clientId => getBlock(state, clientId)), (state, clientIds) => (Array.isArray(clientIds) ? clientIds : [clientIds]).map(clientId => state.blocks.tree.get(clientId)));
/**
* Given an array of block client IDs, returns the corresponding array of block
* names.
*
* @param {Object} state Editor state.
* @param {string[]} clientIds Client IDs for which block names are to be returned.
*
* @return {string[]} Block names.
*/
const getBlockNamesByClientId = rememo((state, clientIds) => getBlocksByClientId(state, clientIds).filter(Boolean).map(block => block.name), (state, clientIds) => getBlocksByClientId(state, clientIds));
/**
* Returns the number of blocks currently present in the post.
*
* @param {Object} state Editor state.
* @param {?string} rootClientId Optional root client ID of block list.
*
* @return {number} Number of blocks in the post.
*/
function getBlockCount(state, rootClientId) {
return getBlockOrder(state, rootClientId).length;
}
/**
* Returns the current selection start block client ID, attribute key and text
* offset.
*
* @param {Object} state Block editor state.
*
* @return {WPBlockSelection} Selection start information.
*/
function getSelectionStart(state) {
return state.selection.selectionStart;
}
/**
* Returns the current selection end block client ID, attribute key and text
* offset.
*
* @param {Object} state Block editor state.
*
* @return {WPBlockSelection} Selection end information.
*/
function getSelectionEnd(state) {
return state.selection.selectionEnd;
}
/**
* Returns the current block selection start. This value may be null, and it
* may represent either a singular block selection or multi-selection start.
* A selection is singular if its start and end match.
*
* @param {Object} state Global application state.
*
* @return {?string} Client ID of block selection start.
*/
function getBlockSelectionStart(state) {
return state.selection.selectionStart.clientId;
}
/**
* Returns the current block selection end. This value may be null, and it
* may represent either a singular block selection or multi-selection end.
* A selection is singular if its start and end match.
*
* @param {Object} state Global application state.
*
* @return {?string} Client ID of block selection end.
*/
function getBlockSelectionEnd(state) {
return state.selection.selectionEnd.clientId;
}
/**
* Returns the number of blocks currently selected in the post.
*
* @param {Object} state Global application state.
*
* @return {number} Number of blocks selected in the post.
*/
function getSelectedBlockCount(state) {
const multiSelectedBlockCount = getMultiSelectedBlockClientIds(state).length;
if (multiSelectedBlockCount) {
return multiSelectedBlockCount;
}
return state.selection.selectionStart.clientId ? 1 : 0;
}
/**
* Returns true if there is a single selected block, or false otherwise.
*
* @param {Object} state Editor state.
*
* @return {boolean} Whether a single block is selected.
*/
function hasSelectedBlock(state) {
const {
selectionStart,
selectionEnd
} = state.selection;
return !!selectionStart.clientId && selectionStart.clientId === selectionEnd.clientId;
}
/**
* Returns the currently selected block client ID, or null if there is no
* selected block.
*
* @param {Object} state Editor state.
*
* @return {?string} Selected block client ID.
*/
function getSelectedBlockClientId(state) {
const {
selectionStart,
selectionEnd
} = state.selection;
const {
clientId
} = selectionStart;
if (!clientId || clientId !== selectionEnd.clientId) {
return null;
}
return clientId;
}
/**
* Returns the currently selected block, or null if there is no selected block.
*
* @param {Object} state Global application state.
*
* @return {?Object} Selected block.
*/
function getSelectedBlock(state) {
const clientId = getSelectedBlockClientId(state);
return clientId ? getBlock(state, clientId) : null;
}
/**
* Given a block client ID, returns the root block from which the block is
* nested, an empty string for top-level blocks, or null if the block does not
* exist.
*
* @param {Object} state Editor state.
* @param {string} clientId Block from which to find root client ID.
*
* @return {?string} Root client ID, if exists
*/
function getBlockRootClientId(state, clientId) {
return state.blocks.parents.has(clientId) ? state.blocks.parents.get(clientId) : null;
}
/**
* Given a block client ID, returns the list of all its parents from top to bottom.
*
* @param {Object} state Editor state.
* @param {string} clientId Block from which to find root client ID.
* @param {boolean} ascending Order results from bottom to top (true) or top to bottom (false).
*
* @return {Array} ClientIDs of the parent blocks.
*/
const getBlockParents = rememo(function (state, clientId) {
let ascending = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
const parents = [];
let current = clientId;
while (!!state.blocks.parents.get(current)) {
current = state.blocks.parents.get(current);
parents.push(current);
}
return ascending ? parents : parents.reverse();
}, state => [state.blocks.parents]);
/**
* Given a block client ID and a block name, returns the list of all its parents
* from top to bottom, filtered by the given name(s). For example, if passed
* 'core/group' as the blockName, it will only return parents which are group
* blocks. If passed `[ 'core/group', 'core/cover']`, as the blockName, it will
* return parents which are group blocks and parents which are cover blocks.
*
* @param {Object} state Editor state.
* @param {string} clientId Block from which to find root client ID.
* @param {string|string[]} blockName Block name(s) to filter.
* @param {boolean} ascending Order results from bottom to top (true) or top to bottom (false).
*
* @return {Array} ClientIDs of the parent blocks.
*/
const getBlockParentsByBlockName = rememo(function (state, clientId, blockName) {
let ascending = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
const parents = getBlockParents(state, clientId, ascending);
return parents.map(id => ({
id,
name: getBlockName(state, id)
})).filter(_ref => {
let {
name
} = _ref;
if (Array.isArray(blockName)) {
return blockName.includes(name);
}
return name === blockName;
}).map(_ref2 => {
let {
id
} = _ref2;
return id;
});
}, state => [state.blocks.parents]);
/**
* Given a block client ID, returns the root of the hierarchy from which the block is nested, return the block itself for root level blocks.
*
* @param {Object} state Editor state.
* @param {string} clientId Block from which to find root client ID.
*
* @return {string} Root client ID
*/
function getBlockHierarchyRootClientId(state, clientId) {
let current = clientId;
let parent;
do {
parent = current;
current = state.blocks.parents.get(current);
} while (current);
return parent;
}
/**
* Given a block client ID, returns the lowest common ancestor with selected client ID.
*
* @param {Object} state Editor state.
* @param {string} clientId Block from which to find common ancestor client ID.
*
* @return {string} Common ancestor client ID or undefined
*/
function getLowestCommonAncestorWithSelectedBlock(state, clientId) {
const selectedId = getSelectedBlockClientId(state);
const clientParents = [...getBlockParents(state, clientId), clientId];
const selectedParents = [...getBlockParents(state, selectedId), selectedId];
let lowestCommonAncestor;
const maxDepth = Math.min(clientParents.length, selectedParents.length);
for (let index = 0; index < maxDepth; index++) {
if (clientParents[index] === selectedParents[index]) {
lowestCommonAncestor = clientParents[index];
} else {
break;
}
}
return lowestCommonAncestor;
}
/**
* Returns the client ID of the block adjacent one at the given reference
* startClientId and modifier directionality. Defaults start startClientId to
* the selected block, and direction as next block. Returns null if there is no
* adjacent block.
*
* @param {Object} state Editor state.
* @param {?string} startClientId Optional client ID of block from which to
* search.
* @param {?number} modifier Directionality multiplier (1 next, -1
* previous).
*
* @return {?string} Return the client ID of the block, or null if none exists.
*/
function getAdjacentBlockClientId(state, startClientId) {
let modifier = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
// Default to selected block.
if (startClientId === undefined) {
startClientId = getSelectedBlockClientId(state);
} // Try multi-selection starting at extent based on modifier.
if (startClientId === undefined) {
if (modifier < 0) {
startClientId = getFirstMultiSelectedBlockClientId(state);
} else {
startClientId = getLastMultiSelectedBlockClientId(state);
}
} // Validate working start client ID.
if (!startClientId) {
return null;
} // Retrieve start block root client ID, being careful to allow the falsey
// empty string top-level root by explicitly testing against null.
const rootClientId = getBlockRootClientId(state, startClientId);
if (rootClientId === null) {
return null;
}
const {
order
} = state.blocks;
const orderSet = order.get(rootClientId);
const index = orderSet.indexOf(startClientId);
const nextIndex = index + 1 * modifier; // Block was first in set and we're attempting to get previous.
if (nextIndex < 0) {
return null;
} // Block was last in set and we're attempting to get next.
if (nextIndex === orderSet.length) {
return null;
} // Assume incremented index is within the set.
return orderSet[nextIndex];
}
/**
* Returns the previous block's client ID from the given reference start ID.
* Defaults start to the selected block. Returns null if there is no previous
* block.
*
* @param {Object} state Editor state.
* @param {?string} startClientId Optional client ID of block from which to
* search.
*
* @return {?string} Adjacent block's client ID, or null if none exists.
*/
function getPreviousBlockClientId(state, startClientId) {
return getAdjacentBlockClientId(state, startClientId, -1);
}
/**
* Returns the next block's client ID from the given reference start ID.
* Defaults start to the selected block. Returns null if there is no next
* block.
*
* @param {Object} state Editor state.
* @param {?string} startClientId Optional client ID of block from which to
* search.
*
* @return {?string} Adjacent block's client ID, or null if none exists.
*/
function getNextBlockClientId(state, startClientId) {
return getAdjacentBlockClientId(state, startClientId, 1);
}
/* eslint-disable jsdoc/valid-types */
/**
* Returns the initial caret position for the selected block.
* This position is to used to position the caret properly when the selected block changes.
* If the current block is not a RichText, having initial position set to 0 means "focus block"
*
* @param {Object} state Global application state.
*
* @return {0|-1|null} Initial position.
*/
function getSelectedBlocksInitialCaretPosition(state) {
/* eslint-enable jsdoc/valid-types */
return state.initialPosition;
}
/**
* Returns the current selection set of block client IDs (multiselection or single selection).
*
* @param {Object} state Editor state.
*
* @return {Array} Multi-selected block client IDs.
*/
const getSelectedBlockClientIds = rememo(state => {
const {
selectionStart,
selectionEnd
} = state.selection;
if (!selectionStart.clientId || !selectionEnd.clientId) {
return EMPTY_ARRAY;
}
if (selectionStart.clientId === selectionEnd.clientId) {
return [selectionStart.clientId];
} // Retrieve root client ID to aid in retrieving relevant nested block
// order, being careful to allow the falsey empty string top-level root
// by explicitly testing against null.
const rootClientId = getBlockRootClientId(state, selectionStart.clientId);
if (rootClientId === null) {
return EMPTY_ARRAY;
}
const blockOrder = getBlockOrder(state, rootClientId);
const startIndex = blockOrder.indexOf(selectionStart.clientId);
const endIndex = blockOrder.indexOf(selectionEnd.clientId);
if (startIndex > endIndex) {
return blockOrder.slice(endIndex, startIndex + 1);
}
return blockOrder.slice(startIndex, endIndex + 1);
}, state => [state.blocks.order, state.selection.selectionStart.clientId, state.selection.selectionEnd.clientId]);
/**
* Returns the current multi-selection set of block client IDs, or an empty
* array if there is no multi-selection.
*
* @param {Object} state Editor state.
*
* @return {Array} Multi-selected block client IDs.
*/
function getMultiSelectedBlockClientIds(state) {
const {
selectionStart,
selectionEnd
} = state.selection;
if (selectionStart.clientId === selectionEnd.clientId) {
return EMPTY_ARRAY;
}
return getSelectedBlockClientIds(state);
}
/**
* Returns the current multi-selection set of blocks, or an empty array if
* there is no multi-selection.
*
* @param {Object} state Editor state.
*
* @return {Array} Multi-selected block objects.
*/
const getMultiSelectedBlocks = rememo(state => {
const multiSelectedBlockClientIds = getMultiSelectedBlockClientIds(state);
if (!multiSelectedBlockClientIds.length) {
return EMPTY_ARRAY;
}
return multiSelectedBlockClientIds.map(clientId => getBlock(state, clientId));
}, state => [...getSelectedBlockClientIds.getDependants(state), state.blocks.byClientId, state.blocks.order, state.blocks.attributes]);
/**
* Returns the client ID of the first block in the multi-selection set, or null
* if there is no multi-selection.
*
* @param {Object} state Editor state.
*
* @return {?string} First block client ID in the multi-selection set.
*/
function getFirstMultiSelectedBlockClientId(state) {
return getMultiSelectedBlockClientIds(state)[0] || null;
}
/**
* Returns the client ID of the last block in the multi-selection set, or null
* if there is no multi-selection.
*
* @param {Object} state Editor state.
*
* @return {?string} Last block client ID in the multi-selection set.
*/
function getLastMultiSelectedBlockClientId(state) {
const selectedClientIds = getMultiSelectedBlockClientIds(state);
return selectedClientIds[selectedClientIds.length - 1] || null;
}
/**
* Returns true if a multi-selection exists, and the block corresponding to the
* specified client ID is the first block of the multi-selection set, or false
* otherwise.
*
* @param {Object} state Editor state.
* @param {string} clientId Block client ID.
*
* @return {boolean} Whether block is first in multi-selection.
*/
function isFirstMultiSelectedBlock(state, clientId) {
return getFirstMultiSelectedBlockClientId(state) === clientId;
}
/**
* Returns true if the client ID occurs within the block multi-selection, or
* false otherwise.
*
* @param {Object} state Editor state.
* @param {string} clientId Block client ID.
*
* @return {boolean} Whether block is in multi-selection set.
*/
function isBlockMultiSelected(state, clientId) {
return getMultiSelectedBlockClientIds(state).indexOf(clientId) !== -1;
}
/**
* Returns true if an ancestor of the block is multi-selected, or false
* otherwise.
*
* @param {Object} state Editor state.
* @param {string} clientId Block client ID.
*
* @return {boolean} Whether an ancestor of the block is in multi-selection
* set.
*/
const isAncestorMultiSelected = rememo((state, clientId) => {
let ancestorClientId = clientId;
let isMultiSelected = false;
while (ancestorClientId && !isMultiSelected) {
ancestorClientId = getBlockRootClientId(state, ancestorClientId);
isMultiSelected = isBlockMultiSelected(state, ancestorClientId);
}
return isMultiSelected;
}, state => [state.blocks.order, state.selection.selectionStart.clientId, state.selection.selectionEnd.clientId]);
/**
* Returns the client ID of the block which begins the multi-selection set, or
* null if there is no multi-selection.
*
* This is not necessarily the first client ID in the selection.
*
* @see getFirstMultiSelectedBlockClientId
*
* @param {Object} state Editor state.
*
* @return {?string} Client ID of block beginning multi-selection.
*/
function getMultiSelectedBlocksStartClientId(state) {
const {
selectionStart,
selectionEnd
} = state.selection;
if (selectionStart.clientId === selectionEnd.clientId) {
return null;
}
return selectionStart.clientId || null;
}
/**
* Returns the client ID of the block which ends the multi-selection set, or
* null if there is no multi-selection.
*
* This is not necessarily the last client ID in the selection.
*
* @see getLastMultiSelectedBlockClientId
*
* @param {Object} state Editor state.
*
* @return {?string} Client ID of block ending multi-selection.
*/
function getMultiSelectedBlocksEndClientId(state) {
const {
selectionStart,
selectionEnd
} = state.selection;
if (selectionStart.clientId === selectionEnd.clientId) {
return null;
}
return selectionEnd.clientId || null;
}
/**
* Returns true if the selection is not partial.
*
* @param {Object} state Editor state.
*
* @return {boolean} Whether the selection is mergeable.
*/
function __unstableIsFullySelected(state) {
const selectionAnchor = getSelectionStart(state);
const selectionFocus = getSelectionEnd(state);
return !selectionAnchor.attributeKey && !selectionFocus.attributeKey && typeof selectionAnchor.offset === 'undefined' && typeof selectionFocus.offset === 'undefined';
}
/**
* Returns true if the selection is collapsed.
*
* @param {Object} state Editor state.
*
* @return {boolean} Whether the selection is collapsed.
*/
function __unstableIsSelectionCollapsed(state) {
const selectionAnchor = getSelectionStart(state);
const selectionFocus = getSelectionEnd(state);
return !!selectionAnchor && !!selectionFocus && selectionAnchor.clientId === selectionFocus.clientId && selectionAnchor.attributeKey === selectionFocus.attributeKey && selectionAnchor.offset === selectionFocus.offset;
}
function __unstableSelectionHasUnmergeableBlock(state) {
return getSelectedBlockClientIds(state).some(clientId => {
const blockName = getBlockName(state, clientId);
const blockType = (0,external_wp_blocks_namespaceObject.getBlockType)(blockName);
return !blockType.merge;
});
}
/**
* Check whether the selection is mergeable.
*
* @param {Object} state Editor state.
* @param {boolean} isForward Whether to merge forwards.
*
* @return {boolean} Whether the selection is mergeable.
*/
function __unstableIsSelectionMergeable(state, isForward) {
const selectionAnchor = getSelectionStart(state);
const selectionFocus = getSelectionEnd(state); // It's not mergeable if the start and end are within the same block.
if (selectionAnchor.clientId === selectionFocus.clientId) return false; // It's not mergeable if there's no rich text selection.
if (!selectionAnchor.attributeKey || !selectionFocus.attributeKey || typeof selectionAnchor.offset === 'undefined' || typeof selectionFocus.offset === 'undefined') return false;
const anchorRootClientId = getBlockRootClientId(state, selectionAnchor.clientId);
const focusRootClientId = getBlockRootClientId(state, selectionFocus.clientId); // It's not mergeable if the selection doesn't start and end in the same
// block list. Maybe in the future it should be allowed.
if (anchorRootClientId !== focusRootClientId) {
return false;
}
const blockOrder = getBlockOrder(state, anchorRootClientId);
const anchorIndex = blockOrder.indexOf(selectionAnchor.clientId);
const focusIndex = blockOrder.indexOf(selectionFocus.clientId); // Reassign selection start and end based on order.
let selectionStart, selectionEnd;
if (anchorIndex > focusIndex) {
selectionStart = selectionFocus;
selectionEnd = selectionAnchor;
} else {
selectionStart = selectionAnchor;
selectionEnd = selectionFocus;
}
const targetBlockClientId = isForward ? selectionEnd.clientId : selectionStart.clientId;
const blockToMergeClientId = isForward ? selectionStart.clientId : selectionEnd.clientId;
const targetBlockName = getBlockName(state, targetBlockClientId);
const targetBlockType = (0,external_wp_blocks_namespaceObject.getBlockType)(targetBlockName);
if (!targetBlockType.merge) return false;
const blockToMerge = getBlock(state, blockToMergeClientId); // It's mergeable if the blocks are of the same type.
if (blockToMerge.name === targetBlockName) return true; // If the blocks are of a different type, try to transform the block being
// merged into the same type of block.
const blocksToMerge = (0,external_wp_blocks_namespaceObject.switchToBlockType)(blockToMerge, targetBlockName);
return blocksToMerge && blocksToMerge.length;
}
/**
* Get partial selected blocks with their content updated
* based on the selection.
*
* @param {Object} state Editor state.
*
* @return {Object[]} Updated partial selected blocks.
*/
const __unstableGetSelectedBlocksWithPartialSelection = state => {
const selectionAnchor = getSelectionStart(state);
const selectionFocus = getSelectionEnd(state);
if (selectionAnchor.clientId === selectionFocus.clientId) {
return EMPTY_ARRAY;
} // Can't split if the selection is not set.
if (!selectionAnchor.attributeKey || !selectionFocus.attributeKey || typeof selectionAnchor.offset === 'undefined' || typeof selectionFocus.offset === 'undefined') {
return EMPTY_ARRAY;
}
const anchorRootClientId = getBlockRootClientId(state, selectionAnchor.clientId);
const focusRootClientId = getBlockRootClientId(state, selectionFocus.clientId); // It's not splittable if the selection doesn't start and end in the same
// block list. Maybe in the future it should be allowed.
if (anchorRootClientId !== focusRootClientId) {
return EMPTY_ARRAY;
}
const blockOrder = getBlockOrder(state, anchorRootClientId);
const anchorIndex = blockOrder.indexOf(selectionAnchor.clientId);
const focusIndex = blockOrder.indexOf(selectionFocus.clientId); // Reassign selection start and end based on order.
const [selectionStart, selectionEnd] = anchorIndex > focusIndex ? [selectionFocus, selectionAnchor] : [selectionAnchor, selectionFocus];
const blockA = getBlock(state, selectionStart.clientId);
const blockAType = (0,external_wp_blocks_namespaceObject.getBlockType)(blockA.name);
const blockB = getBlock(state, selectionEnd.clientId);
const blockBType = (0,external_wp_blocks_namespaceObject.getBlockType)(blockB.name);
const htmlA = blockA.attributes[selectionStart.attributeKey];
const htmlB = blockB.attributes[selectionEnd.attributeKey];
const attributeDefinitionA = blockAType.attributes[selectionStart.attributeKey];
const attributeDefinitionB = blockBType.attributes[selectionEnd.attributeKey];
let valueA = (0,external_wp_richText_namespaceObject.create)({
html: htmlA,
...mapRichTextSettings(attributeDefinitionA)
});
let valueB = (0,external_wp_richText_namespaceObject.create)({
html: htmlB,
...mapRichTextSettings(attributeDefinitionB)
});
valueA = (0,external_wp_richText_namespaceObject.remove)(valueA, 0, selectionStart.offset);
valueB = (0,external_wp_richText_namespaceObject.remove)(valueB, selectionEnd.offset, valueB.text.length);
return [{ ...blockA,
attributes: { ...blockA.attributes,
[selectionStart.attributeKey]: (0,external_wp_richText_namespaceObject.toHTMLString)({
value: valueA,
...mapRichTextSettings(attributeDefinitionA)
})
}
}, { ...blockB,
attributes: { ...blockB.attributes,
[selectionEnd.attributeKey]: (0,external_wp_richText_namespaceObject.toHTMLString)({
value: valueB,
...mapRichTextSettings(attributeDefinitionB)
})
}
}];
};
/**
* Returns an array containing all block client IDs in the editor in the order
* they appear. Optionally accepts a root client ID of the block list for which
* the order should be returned, defaulting to the top-level block order.
*
* @param {Object} state Editor state.
* @param {?string} rootClientId Optional root client ID of block list.
*
* @return {Array} Ordered client IDs of editor blocks.
*/
function getBlockOrder(state, rootClientId) {
return state.blocks.order.get(rootClientId || '') || EMPTY_ARRAY;
}
/**
* Returns the index at which the block corresponding to the specified client
* ID occurs within the block order, or `-1` if the block does not exist.
*
* @param {Object} state Editor state.
* @param {string} clientId Block client ID.
*
* @return {number} Index at which block exists in order.
*/
function getBlockIndex(state, clientId) {
const rootClientId = getBlockRootClientId(state, clientId);
return getBlockOrder(state, rootClientId).indexOf(clientId);
}
/**
* Returns true if the block corresponding to the specified client ID is
* currently selected and no multi-selection exists, or false otherwise.
*
* @param {Object} state Editor state.
* @param {string} clientId Block client ID.
*
* @return {boolean} Whether block is selected and multi-selection exists.
*/
function isBlockSelected(state, clientId) {
const {
selectionStart,
selectionEnd
} = state.selection;
if (selectionStart.clientId !== selectionEnd.clientId) {
return false;
}
return selectionStart.clientId === clientId;
}
/**
* Returns true if one of the block's inner blocks is selected.
*
* @param {Object} state Editor state.
* @param {string} clientId Block client ID.
* @param {boolean} deep Perform a deep check.
*
* @return {boolean} Whether the block as an inner block selected
*/
function hasSelectedInnerBlock(state, clientId) {
let deep = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
return getBlockOrder(state, clientId).some(innerClientId => isBlockSelected(state, innerClientId) || isBlockMultiSelected(state, innerClientId) || deep && hasSelectedInnerBlock(state, innerClientId, deep));
}
/**
* Returns true if the block corresponding to the specified client ID is
* currently selected but isn't the last of the selected blocks. Here "last"
* refers to the block sequence in the document, _not_ the sequence of
* multi-selection, which is why `state.selectionEnd` isn't used.
*
* @param {Object} state Editor state.
* @param {string} clientId Block client ID.
*
* @return {boolean} Whether block is selected and not the last in the
* selection.
*/
function isBlockWithinSelection(state, clientId) {
if (!clientId) {
return false;
}
const clientIds = getMultiSelectedBlockClientIds(state);
const index = clientIds.indexOf(clientId);
return index > -1 && index < clientIds.length - 1;
}
/**
* Returns true if a multi-selection has been made, or false otherwise.
*
* @param {Object} state Editor state.
*
* @return {boolean} Whether multi-selection has been made.
*/
function hasMultiSelection(state) {
const {
selectionStart,
selectionEnd
} = state.selection;
return selectionStart.clientId !== selectionEnd.clientId;
}
/**
* Whether in the process of multi-selecting or not. This flag is only true
* while the multi-selection is being selected (by mouse move), and is false
* once the multi-selection has been settled.
*
* @see hasMultiSelection
*
* @param {Object} state Global application state.
*
* @return {boolean} True if multi-selecting, false if not.
*/
function selectors_isMultiSelecting(state) {
return state.isMultiSelecting;
}
/**
* Selector that returns if multi-selection is enabled or not.
*
* @param {Object} state Global application state.
*
* @return {boolean} True if it should be possible to multi-select blocks, false if multi-selection is disabled.
*/
function selectors_isSelectionEnabled(state) {
return state.isSelectionEnabled;
}
/**
* Returns the block's editing mode, defaulting to "visual" if not explicitly
* assigned.
*
* @param {Object} state Editor state.
* @param {string} clientId Block client ID.
*
* @return {Object} Block editing mode.
*/
function getBlockMode(state, clientId) {
return state.blocksMode[clientId] || 'visual';
}
/**
* Returns true if the user is typing, or false otherwise.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether user is typing.
*/
function selectors_isTyping(state) {
return state.isTyping;
}
/**
* Returns true if the user is dragging blocks, or false otherwise.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether user is dragging blocks.
*/
function isDraggingBlocks(state) {
return !!state.draggedBlocks.length;
}
/**
* Returns the client ids of any blocks being directly dragged.
*
* This does not include children of a parent being dragged.
*
* @param {Object} state Global application state.
*
* @return {string[]} Array of dragged block client ids.
*/
function getDraggedBlockClientIds(state) {
return state.draggedBlocks;
}
/**
* Returns whether the block is being dragged.
*
* Only returns true if the block is being directly dragged,
* not if the block is a child of a parent being dragged.
* See `isAncestorBeingDragged` for child blocks.
*
* @param {Object} state Global application state.
* @param {string} clientId Client id for block to check.
*
* @return {boolean} Whether the block is being dragged.
*/
function isBlockBeingDragged(state, clientId) {
return state.draggedBlocks.includes(clientId);
}
/**
* Returns whether a parent/ancestor of the block is being dragged.
*
* @param {Object} state Global application state.
* @param {string} clientId Client id for block to check.
*
* @return {boolean} Whether the block's ancestor is being dragged.
*/
function isAncestorBeingDragged(state, clientId) {
// Return early if no blocks are being dragged rather than
// the more expensive check for parents.
if (!isDraggingBlocks(state)) {
return false;
}
const parents = getBlockParents(state, clientId);
return parents.some(parentClientId => isBlockBeingDragged(state, parentClientId));
}
/**
* Returns true if the caret is within formatted text, or false otherwise.
*
* @deprecated
*
* @return {boolean} Whether the caret is within formatted text.
*/
function isCaretWithinFormattedText() {
external_wp_deprecated_default()('wp.data.select( "core/block-editor" ).isCaretWithinFormattedText', {
since: '6.1',
version: '6.3'
});
return false;
}
/**
* Returns the insertion point, the index at which the new inserted block would
* be placed. Defaults to the last index.
*
* @param {Object} state Editor state.
*
* @return {Object} Insertion point object with `rootClientId`, `index`.
*/
const getBlockInsertionPoint = rememo(state => {
let rootClientId, index;
const {
insertionPoint,
selection: {
selectionEnd
}
} = state;
if (insertionPoint !== null) {
return insertionPoint;
}
const {
clientId
} = selectionEnd;
if (clientId) {
rootClientId = getBlockRootClientId(state, clientId) || undefined;
index = getBlockIndex(state, selectionEnd.clientId) + 1;
} else {
index = getBlockOrder(state).length;
}
return {
rootClientId,
index
};
}, state => [state.insertionPoint, state.selection.selectionEnd.clientId, state.blocks.parents, state.blocks.order]);
/**
* Returns true if we should show the block insertion point.
*
* @param {Object} state Global application state.
*
* @return {?boolean} Whether the insertion point is visible or not.
*/
function isBlockInsertionPointVisible(state) {
return state.insertionPoint !== null;
}
/**
* Returns whether the blocks matches the template or not.
*
* @param {boolean} state
* @return {?boolean} Whether the template is valid or not.
*/
function isValidTemplate(state) {
return state.template.isValid;
}
/**
* Returns the defined block template
*
* @param {boolean} state
*
* @return {?Array} Block Template.
*/
function getTemplate(state) {
return state.settings.template;
}
/**
* Returns the defined block template lock. Optionally accepts a root block
* client ID as context, otherwise defaulting to the global context.
*
* @param {Object} state Editor state.
* @param {?string} rootClientId Optional block root client ID.
*
* @return {string|false} Block Template Lock
*/
function getTemplateLock(state, rootClientId) {
var _getBlockListSettings, _getBlockListSettings2;
if (!rootClientId) {
var _state$settings$templ;
return (_state$settings$templ = state.settings.templateLock) !== null && _state$settings$templ !== void 0 ? _state$settings$templ : false;
}
return (_getBlockListSettings = (_getBlockListSettings2 = getBlockListSettings(state, rootClientId)) === null || _getBlockListSettings2 === void 0 ? void 0 : _getBlockListSettings2.templateLock) !== null && _getBlockListSettings !== void 0 ? _getBlockListSettings : false;
}
const checkAllowList = function (list, item) {
let defaultResult = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
if (typeof list === 'boolean') {
return list;
}
if (Array.isArray(list)) {
// TODO: when there is a canonical way to detect that we are editing a post
// the following check should be changed to something like:
// if ( list.includes( 'core/post-content' ) && getEditorMode() === 'post-content' && item === null )
if (list.includes('core/post-content') && item === null) {
return true;
}
return list.includes(item);
}
return defaultResult;
};
/**
* Determines if the given block type is allowed to be inserted into the block list.
* This function is not exported and not memoized because using a memoized selector
* inside another memoized selector is just a waste of time.
*
* @param {Object} state Editor state.
* @param {string|Object} blockName The block type object, e.g., the response
* from the block directory; or a string name of
* an installed block type, e.g.' core/paragraph'.
* @param {?string} rootClientId Optional root client ID of block list.
*
* @return {boolean} Whether the given block type is allowed to be inserted.
*/
const canInsertBlockTypeUnmemoized = function (state, blockName) {
let rootClientId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
let blockType;
if (blockName && 'object' === typeof blockName) {
blockType = blockName;
blockName = blockType.name;
} else {
blockType = (0,external_wp_blocks_namespaceObject.getBlockType)(blockName);
}
if (!blockType) {
return false;
}
const {
allowedBlockTypes
} = getSettings(state);
const isBlockAllowedInEditor = checkAllowList(allowedBlockTypes, blockName, true);
if (!isBlockAllowedInEditor) {
return false;
}
const isLocked = !!getTemplateLock(state, rootClientId);
if (isLocked) {
return false;
}
const parentBlockListSettings = getBlockListSettings(state, rootClientId); // The parent block doesn't have settings indicating it doesn't support
// inner blocks, return false.
if (rootClientId && parentBlockListSettings === undefined) {
return false;
}
const parentAllowedBlocks = parentBlockListSettings === null || parentBlockListSettings === void 0 ? void 0 : parentBlockListSettings.allowedBlocks;
const hasParentAllowedBlock = checkAllowList(parentAllowedBlocks, blockName);
const blockAllowedParentBlocks = blockType.parent;
const parentName = getBlockName(state, rootClientId);
const hasBlockAllowedParent = checkAllowList(blockAllowedParentBlocks, parentName);
let hasBlockAllowedAncestor = true;
const blockAllowedAncestorBlocks = blockType.ancestor;
if (blockAllowedAncestorBlocks) {
const ancestors = [rootClientId, ...getBlockParents(state, rootClientId)];
hasBlockAllowedAncestor = ancestors.some(ancestorClientId => checkAllowList(blockAllowedAncestorBlocks, getBlockName(state, ancestorClientId)));
}
const canInsert = hasBlockAllowedAncestor && (hasParentAllowedBlock === null && hasBlockAllowedParent === null || hasParentAllowedBlock === true || hasBlockAllowedParent === true);
if (!canInsert) {
return canInsert;
}
/**
* This filter is an ad-hoc solution to prevent adding template parts inside post content.
* Conceptually, having a filter inside a selector is bad pattern so this code will be
* replaced by a declarative API that doesn't the following drawbacks:
*
* Filters are not reactive: Upon switching between "template mode" and non "template mode",
* the filter and selector won't necessarily be executed again. For now, it doesn't matter much
* because you can't switch between the two modes while the inserter stays open.
*
* Filters are global: Once they're defined, they will affect all editor instances and all registries.
* An ideal API would only affect specific editor instances.
*/
return (0,external_wp_hooks_namespaceObject.applyFilters)('blockEditor.__unstableCanInsertBlockType', canInsert, blockType, rootClientId, {
// Pass bound selectors of the current registry. If we're in a nested
// context, the data will differ from the one selected from the root
// registry.
getBlock: getBlock.bind(null, state),
getBlockParentsByBlockName: getBlockParentsByBlockName.bind(null, state)
});
};
/**
* Determines if the given block type is allowed to be inserted into the block list.
*
* @param {Object} state Editor state.
* @param {string} blockName The name of the block type, e.g.' core/paragraph'.
* @param {?string} rootClientId Optional root client ID of block list.
*
* @return {boolean} Whether the given block type is allowed to be inserted.
*/
const canInsertBlockType = rememo(canInsertBlockTypeUnmemoized, (state, blockName, rootClientId) => [state.blockListSettings[rootClientId], state.blocks.byClientId.get(rootClientId), state.settings.allowedBlockTypes, state.settings.templateLock]);
/**
* Determines if the given blocks are allowed to be inserted into the block
* list.
*
* @param {Object} state Editor state.
* @param {string} clientIds The block client IDs to be inserted.
* @param {?string} rootClientId Optional root client ID of block list.
*
* @return {boolean} Whether the given blocks are allowed to be inserted.
*/
function canInsertBlocks(state, clientIds) {
let rootClientId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
return clientIds.every(id => canInsertBlockType(state, getBlockName(state, id), rootClientId));
}
/**
* Determines if the given block is allowed to be deleted.
*
* @param {Object} state Editor state.
* @param {string} clientId The block client Id.
* @param {?string} rootClientId Optional root client ID of block list.
*
* @return {boolean} Whether the given block is allowed to be removed.
*/
function canRemoveBlock(state, clientId) {
let rootClientId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
const attributes = getBlockAttributes(state, clientId); // attributes can be null if the block is already deleted.
if (attributes === null) {
return true;
}
const {
lock
} = attributes;
const parentIsLocked = !!getTemplateLock(state, rootClientId); // If we don't have a lock on the blockType level, we defer to the parent templateLock.
if (lock === undefined || (lock === null || lock === void 0 ? void 0 : lock.remove) === undefined) {
return !parentIsLocked;
} // When remove is true, it means we cannot remove it.
return !(lock !== null && lock !== void 0 && lock.remove);
}
/**
* Determines if the given blocks are allowed to be removed.
*
* @param {Object} state Editor state.
* @param {string} clientIds The block client IDs to be removed.
* @param {?string} rootClientId Optional root client ID of block list.
*
* @return {boolean} Whether the given blocks are allowed to be removed.
*/
function canRemoveBlocks(state, clientIds) {
let rootClientId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
return clientIds.every(clientId => canRemoveBlock(state, clientId, rootClientId));
}
/**
* Determines if the given block is allowed to be moved.
*
* @param {Object} state Editor state.
* @param {string} clientId The block client Id.
* @param {?string} rootClientId Optional root client ID of block list.
*
* @return {boolean | undefined} Whether the given block is allowed to be moved.
*/
function canMoveBlock(state, clientId) {
let rootClientId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
const attributes = getBlockAttributes(state, clientId);
if (attributes === null) {
return;
}
const {
lock
} = attributes;
const parentIsLocked = getTemplateLock(state, rootClientId) === 'all'; // If we don't have a lock on the blockType level, we defer to the parent templateLock.
if (lock === undefined || (lock === null || lock === void 0 ? void 0 : lock.move) === undefined) {
return !parentIsLocked;
} // When move is true, it means we cannot move it.
return !(lock !== null && lock !== void 0 && lock.move);
}
/**
* Determines if the given blocks are allowed to be moved.
*
* @param {Object} state Editor state.
* @param {string} clientIds The block client IDs to be moved.
* @param {?string} rootClientId Optional root client ID of block list.
*
* @return {boolean} Whether the given blocks are allowed to be moved.
*/
function canMoveBlocks(state, clientIds) {
let rootClientId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
return clientIds.every(clientId => canMoveBlock(state, clientId, rootClientId));
}
/**
* Determines if the given block is allowed to be edited.
*
* @param {Object} state Editor state.
* @param {string} clientId The block client Id.
*
* @return {boolean} Whether the given block is allowed to be edited.
*/
function canEditBlock(state, clientId) {
const attributes = getBlockAttributes(state, clientId);
if (attributes === null) {
return true;
}
const {
lock
} = attributes; // When the edit is true, we cannot edit the block.
return !(lock !== null && lock !== void 0 && lock.edit);
}
/**
* Determines if the given block type can be locked/unlocked by a user.
*
* @param {Object} state Editor state.
* @param {(string|Object)} nameOrType Block name or type object.
*
* @return {boolean} Whether a given block type can be locked/unlocked.
*/
function canLockBlockType(state, nameOrType) {
var _state$settings;
if (!(0,external_wp_blocks_namespaceObject.hasBlockSupport)(nameOrType, 'lock', true)) {
return false;
} // Use block editor settings as the default value.
return !!((_state$settings = state.settings) !== null && _state$settings !== void 0 && _state$settings.canLockBlocks);
}
/**
* Returns information about how recently and frequently a block has been inserted.
*
* @param {Object} state Global application state.
* @param {string} id A string which identifies the insert, e.g. 'core/block/12'
*
* @return {?{ time: number, count: number }} An object containing `time` which is when the last
* insert occurred as a UNIX epoch, and `count` which is
* the number of inserts that have occurred.
*/
function getInsertUsage(state, id) {
var _state$preferences$in, _state$preferences$in2;
return (_state$preferences$in = (_state$preferences$in2 = state.preferences.insertUsage) === null || _state$preferences$in2 === void 0 ? void 0 : _state$preferences$in2[id]) !== null && _state$preferences$in !== void 0 ? _state$preferences$in : null;
}
/**
* Returns whether we can show a block type in the inserter
*
* @param {Object} state Global State
* @param {Object} blockType BlockType
* @param {?string} rootClientId Optional root client ID of block list.
*
* @return {boolean} Whether the given block type is allowed to be shown in the inserter.
*/
const canIncludeBlockTypeInInserter = (state, blockType, rootClientId) => {
if (!(0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockType, 'inserter', true)) {
return false;
}
return canInsertBlockTypeUnmemoized(state, blockType.name, rootClientId);
};
/**
* Return a function to be used to tranform a block variation to an inserter item
*
* @param {Object} state Global State
* @param {Object} item Denormalized inserter item
* @return {Function} Function to transform a block variation to inserter item
*/
const getItemFromVariation = (state, item) => variation => {
const variationId = `${item.id}/${variation.name}`;
const {
time,
count = 0
} = getInsertUsage(state, variationId) || {};
return { ...item,
id: variationId,
icon: variation.icon || item.icon,
title: variation.title || item.title,
description: variation.description || item.description,
category: variation.category || item.category,
// If `example` is explicitly undefined for the variation, the preview will not be shown.
example: variation.hasOwnProperty('example') ? variation.example : item.example,
initialAttributes: { ...item.initialAttributes,
...variation.attributes
},
innerBlocks: variation.innerBlocks,
keywords: variation.keywords || item.keywords,
frecency: calculateFrecency(time, count)
};
};
/**
* Returns the calculated frecency.
*
* 'frecency' is a heuristic (https://en.wikipedia.org/wiki/Frecency)
* that combines block usage frequenty and recency.
*
* @param {number} time When the last insert occurred as a UNIX epoch
* @param {number} count The number of inserts that have occurred.
*
* @return {number} The calculated frecency.
*/
const calculateFrecency = (time, count) => {
if (!time) {
return count;
} // The selector is cached, which means Date.now() is the last time that the
// relevant state changed. This suits our needs.
const duration = Date.now() - time;
switch (true) {
case duration < MILLISECONDS_PER_HOUR:
return count * 4;
case duration < MILLISECONDS_PER_DAY:
return count * 2;
case duration < MILLISECONDS_PER_WEEK:
return count / 2;
default:
return count / 4;
}
};
/**
* Returns a function that accepts a block type and builds an item to be shown
* in a specific context. It's used for building items for Inserter and available
* block Transfroms list.
*
* @param {Object} state Editor state.
* @param {Object} options Options object for handling the building of a block type.
* @param {string} options.buildScope The scope for which the item is going to be used.
* @return {Function} Function returns an item to be shown in a specific context (Inserter|Transforms list).
*/
const buildBlockTypeItem = (state, _ref3) => {
let {
buildScope = 'inserter'
} = _ref3;
return blockType => {
const id = blockType.name;
let isDisabled = false;
if (!(0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockType.name, 'multiple', true)) {
isDisabled = getBlocksByClientId(state, getClientIdsWithDescendants(state)).some(_ref4 => {
let {
name
} = _ref4;
return name === blockType.name;
});
}
const {
time,
count = 0
} = getInsertUsage(state, id) || {};
const blockItemBase = {
id,
name: blockType.name,
title: blockType.title,
icon: blockType.icon,
isDisabled,
frecency: calculateFrecency(time, count)
};
if (buildScope === 'transform') return blockItemBase;
const inserterVariations = (0,external_wp_blocks_namespaceObject.getBlockVariations)(blockType.name, 'inserter');
return { ...blockItemBase,
initialAttributes: {},
description: blockType.description,
category: blockType.category,
keywords: blockType.keywords,
variations: inserterVariations,
example: blockType.example,
utility: 1 // Deprecated.
};
};
};
/**
* Determines the items that appear in the inserter. Includes both static
* items (e.g. a regular block type) and dynamic items (e.g. a reusable block).
*
* Each item object contains what's necessary to display a button in the
* inserter and handle its selection.
*
* The 'frecency' property is a heuristic (https://en.wikipedia.org/wiki/Frecency)
* that combines block usage frequenty and recency.
*
* Items are returned ordered descendingly by their 'utility' and 'frecency'.
*
* @param {Object} state Editor state.
* @param {?string} rootClientId Optional root client ID of block list.
*
* @return {WPEditorInserterItem[]} Items that appear in inserter.
*
* @typedef {Object} WPEditorInserterItem
* @property {string} id Unique identifier for the item.
* @property {string} name The type of block to create.
* @property {Object} initialAttributes Attributes to pass to the newly created block.
* @property {string} title Title of the item, as it appears in the inserter.
* @property {string} icon Dashicon for the item, as it appears in the inserter.
* @property {string} category Block category that the item is associated with.
* @property {string[]} keywords Keywords that can be searched to find this item.
* @property {boolean} isDisabled Whether or not the user should be prevented from inserting
* this item.
* @property {number} frecency Heuristic that combines frequency and recency.
*/
const getInserterItems = rememo(function (state) {
let rootClientId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
const buildBlockTypeInserterItem = buildBlockTypeItem(state, {
buildScope: 'inserter'
});
/*
* Matches block comment delimiters amid serialized content.
*
* @see `tokenizer` in `@wordpress/block-serialization-default-parser`
* package
*
* blockParserTokenizer differs from the original tokenizer in the
* following ways:
*
* - removed global flag (/g)
* - prepended ^\s*
*
*/
const blockParserTokenizer = /^\s*<!--\s+(\/)?wp:([a-z][a-z0-9_-]*\/)?([a-z][a-z0-9_-]*)\s+({(?:(?=([^}]+|}+(?=})|(?!}\s+\/?-->)[^])*)\5|[^]*?)}\s+)?(\/)?-->/;
const buildReusableBlockInserterItem = reusableBlock => {
let icon = library_symbol;
/*
* Instead of always displaying a generic "symbol" icon for every
* reusable block, try to use an icon that represents the first
* outermost block contained in the reusable block. This requires
* scanning the serialized form of the reusable block to find its
* first block delimiter, then looking up the corresponding block
* type, if available.
*/
if (external_wp_element_namespaceObject.Platform.OS === 'web') {
const content = typeof reusableBlock.content.raw === 'string' ? reusableBlock.content.raw : reusableBlock.content;
const rawBlockMatch = content.match(blockParserTokenizer);
if (rawBlockMatch) {
const [,, namespace = 'core/', blockName] = rawBlockMatch;
const referencedBlockType = (0,external_wp_blocks_namespaceObject.getBlockType)(namespace + blockName);
if (referencedBlockType) {
icon = referencedBlockType.icon;
}
}
}
const id = `core/block/${reusableBlock.id}`;
const {
time,
count = 0
} = getInsertUsage(state, id) || {};
const frecency = calculateFrecency(time, count);
return {
id,
name: 'core/block',
initialAttributes: {
ref: reusableBlock.id
},
title: reusableBlock.title.raw,
icon,
category: 'reusable',
keywords: [],
isDisabled: false,
utility: 1,
// Deprecated.
frecency
};
};
const blockTypeInserterItems = (0,external_wp_blocks_namespaceObject.getBlockTypes)().filter(blockType => canIncludeBlockTypeInInserter(state, blockType, rootClientId)).map(buildBlockTypeInserterItem);
const reusableBlockInserterItems = canInsertBlockTypeUnmemoized(state, 'core/block', rootClientId) ? getReusableBlocks(state).map(buildReusableBlockInserterItem) : [];
const items = blockTypeInserterItems.reduce((accumulator, item) => {
const {
variations = []
} = item; // Exclude any block type item that is to be replaced by a default variation.
if (!variations.some(_ref5 => {
let {
isDefault
} = _ref5;
return isDefault;
})) {
accumulator.push(item);
}
if (variations.length) {
const variationMapper = getItemFromVariation(state, item);
accumulator.push(...variations.map(variationMapper));
}
return accumulator;
}, []); // Ensure core blocks are prioritized in the returned results,
// because third party blocks can be registered earlier than
// the core blocks (usually by using the `init` action),
// thus affecting the display order.
// We don't sort reusable blocks as they are handled differently.
const groupByType = (blocks, block) => {
const {
core,
noncore
} = blocks;
const type = block.name.startsWith('core/') ? core : noncore;
type.push(block);
return blocks;
};
const {
core: coreItems,
noncore: nonCoreItems
} = items.reduce(groupByType, {
core: [],
noncore: []
});
const sortedBlockTypes = [...coreItems, ...nonCoreItems];
return [...sortedBlockTypes, ...reusableBlockInserterItems];
}, (state, rootClientId) => [state.blockListSettings[rootClientId], state.blocks.byClientId, state.blocks.order, state.preferences.insertUsage, state.settings.allowedBlockTypes, state.settings.templateLock, getReusableBlocks(state), (0,external_wp_blocks_namespaceObject.getBlockTypes)()]);
/**
* Determines the items that appear in the available block transforms list.
*
* Each item object contains what's necessary to display a menu item in the
* transform list and handle its selection.
*
* The 'frecency' property is a heuristic (https://en.wikipedia.org/wiki/Frecency)
* that combines block usage frequenty and recency.
*
* Items are returned ordered descendingly by their 'frecency'.
*
* @param {Object} state Editor state.
* @param {Object|Object[]} blocks Block object or array objects.
* @param {?string} rootClientId Optional root client ID of block list.
*
* @return {WPEditorTransformItem[]} Items that appear in inserter.
*
* @typedef {Object} WPEditorTransformItem
* @property {string} id Unique identifier for the item.
* @property {string} name The type of block to create.
* @property {string} title Title of the item, as it appears in the inserter.
* @property {string} icon Dashicon for the item, as it appears in the inserter.
* @property {boolean} isDisabled Whether or not the user should be prevented from inserting
* this item.
* @property {number} frecency Heuristic that combines frequency and recency.
*/
const getBlockTransformItems = rememo(function (state, blocks) {
var _itemsByName$sourceBl;
let rootClientId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
const normalizedBlocks = Array.isArray(blocks) ? blocks : [blocks];
const [sourceBlock] = normalizedBlocks;
const buildBlockTypeTransformItem = buildBlockTypeItem(state, {
buildScope: 'transform'
});
const blockTypeTransformItems = (0,external_wp_blocks_namespaceObject.getBlockTypes)().filter(blockType => canIncludeBlockTypeInInserter(state, blockType, rootClientId)).map(buildBlockTypeTransformItem);
const itemsByName = Object.fromEntries(Object.entries(blockTypeTransformItems).map(_ref6 => {
let [, value] = _ref6;
return [value.name, value];
})); // Consider unwraping the highest priority.
itemsByName['*'] = {
frecency: +Infinity,
id: '*',
isDisabled: false,
name: '*',
title: (0,external_wp_i18n_namespaceObject.__)('Unwrap'),
icon: (_itemsByName$sourceBl = itemsByName[sourceBlock === null || sourceBlock === void 0 ? void 0 : sourceBlock.name]) === null || _itemsByName$sourceBl === void 0 ? void 0 : _itemsByName$sourceBl.icon
};
const possibleTransforms = (0,external_wp_blocks_namespaceObject.getPossibleBlockTransformations)(normalizedBlocks).reduce((accumulator, block) => {
if (block === '*') {
accumulator.push(itemsByName['*']);
} else if (itemsByName[block === null || block === void 0 ? void 0 : block.name]) {
accumulator.push(itemsByName[block.name]);
}
return accumulator;
}, []);
return orderBy(possibleTransforms, block => itemsByName[block.name].frecency, 'desc');
}, (state, blocks, rootClientId) => [state.blockListSettings[rootClientId], state.blocks.byClientId, state.preferences.insertUsage, state.settings.allowedBlockTypes, state.settings.templateLock, (0,external_wp_blocks_namespaceObject.getBlockTypes)()]);
/**
* Determines whether there are items to show in the inserter.
*
* @param {Object} state Editor state.
* @param {?string} rootClientId Optional root client ID of block list.
*
* @return {boolean} Items that appear in inserter.
*/
const hasInserterItems = rememo(function (state) {
let rootClientId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
const hasBlockType = (0,external_wp_blocks_namespaceObject.getBlockTypes)().some(blockType => canIncludeBlockTypeInInserter(state, blockType, rootClientId));
if (hasBlockType) {
return true;
}
const hasReusableBlock = canInsertBlockTypeUnmemoized(state, 'core/block', rootClientId) && getReusableBlocks(state).length > 0;
return hasReusableBlock;
}, (state, rootClientId) => [state.blockListSettings[rootClientId], state.blocks.byClientId, state.settings.allowedBlockTypes, state.settings.templateLock, getReusableBlocks(state), (0,external_wp_blocks_namespaceObject.getBlockTypes)()]);
/**
* Returns the list of allowed inserter blocks for inner blocks children.
*
* @param {Object} state Editor state.
* @param {?string} rootClientId Optional root client ID of block list.
*
* @return {Array?} The list of allowed block types.
*/
const getAllowedBlocks = rememo(function (state) {
let rootClientId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
if (!rootClientId) {
return;
}
return (0,external_wp_blocks_namespaceObject.getBlockTypes)().filter(blockType => canIncludeBlockTypeInInserter(state, blockType, rootClientId));
}, (state, rootClientId) => [state.blockListSettings[rootClientId], state.blocks.byClientId, state.settings.allowedBlockTypes, state.settings.templateLock, (0,external_wp_blocks_namespaceObject.getBlockTypes)()]);
const __experimentalGetAllowedBlocks = rememo(function (state) {
let rootClientId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
external_wp_deprecated_default()('wp.data.select( "core/block-editor" ).__experimentalGetAllowedBlocks', {
alternative: 'wp.data.select( "core/block-editor" ).getAllowedBlocks',
since: '6.2',
version: '6.4'
});
return getAllowedBlocks(state, rootClientId);
}, (state, rootClientId) => [...getAllowedBlocks.getDependants(state, rootClientId)]);
/**
* Returns the block to be directly inserted by the block appender.
*
* @param {Object} state Editor state.
* @param {?string} rootClientId Optional root client ID of block list.
*
* @return {?WPDirectInsertBlock} The block type to be directly inserted.
*
* @typedef {Object} WPDirectInsertBlock
* @property {string} name The type of block.
* @property {?Object} attributes Attributes to pass to the newly created block.
* @property {?Array<string>} attributesToCopy Attributes to be copied from adjecent blocks when inserted.
*/
const __experimentalGetDirectInsertBlock = rememo(function (state) {
var _state$blockListSetti, _state$blockListSetti2;
let rootClientId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
if (!rootClientId) {
return;
}
const defaultBlock = (_state$blockListSetti = state.blockListSettings[rootClientId]) === null || _state$blockListSetti === void 0 ? void 0 : _state$blockListSetti.__experimentalDefaultBlock;
const directInsert = (_state$blockListSetti2 = state.blockListSettings[rootClientId]) === null || _state$blockListSetti2 === void 0 ? void 0 : _state$blockListSetti2.__experimentalDirectInsert;
if (!defaultBlock || !directInsert) {
return;
}
if (typeof directInsert === 'function') {
return directInsert(getBlock(state, rootClientId)) ? defaultBlock : null;
}
return defaultBlock;
}, (state, rootClientId) => [state.blockListSettings[rootClientId], state.blocks.tree.get(rootClientId)]);
const checkAllowListRecursive = (blocks, allowedBlockTypes) => {
if (typeof allowedBlockTypes === 'boolean') {
return allowedBlockTypes;
}
const blocksQueue = [...blocks];
while (blocksQueue.length > 0) {
var _block$innerBlocks;
const block = blocksQueue.shift();
const isAllowed = checkAllowList(allowedBlockTypes, block.name || block.blockName, true);
if (!isAllowed) {
return false;
}
(_block$innerBlocks = block.innerBlocks) === null || _block$innerBlocks === void 0 ? void 0 : _block$innerBlocks.forEach(innerBlock => {
blocksQueue.push(innerBlock);
});
}
return true;
};
const __experimentalGetParsedPattern = rememo((state, patternName) => {
const patterns = state.settings.__experimentalBlockPatterns;
const pattern = patterns.find(_ref7 => {
let {
name
} = _ref7;
return name === patternName;
});
if (!pattern) {
return null;
}
return { ...pattern,
blocks: (0,external_wp_blocks_namespaceObject.parse)(pattern.content, {
__unstableSkipMigrationLogs: true
})
};
}, state => [state.settings.__experimentalBlockPatterns]);
const getAllAllowedPatterns = rememo(state => {
const patterns = state.settings.__experimentalBlockPatterns;
const {
allowedBlockTypes
} = getSettings(state);
const parsedPatterns = patterns.filter(_ref8 => {
let {
inserter = true
} = _ref8;
return !!inserter;
}).map(_ref9 => {
let {
name
} = _ref9;
return __experimentalGetParsedPattern(state, name);
});
const allowedPatterns = parsedPatterns.filter(_ref10 => {
let {
blocks
} = _ref10;
return checkAllowListRecursive(blocks, allowedBlockTypes);
});
return allowedPatterns;
}, state => [state.settings.__experimentalBlockPatterns, state.settings.allowedBlockTypes]);
/**
* Returns the list of allowed patterns for inner blocks children.
*
* @param {Object} state Editor state.
* @param {?string} rootClientId Optional target root client ID.
*
* @return {Array?} The list of allowed patterns.
*/
const __experimentalGetAllowedPatterns = rememo(function (state) {
let rootClientId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
const availableParsedPatterns = getAllAllowedPatterns(state);
const patternsAllowed = availableParsedPatterns.filter(_ref11 => {
let {
blocks
} = _ref11;
return blocks.every(_ref12 => {
let {
name
} = _ref12;
return canInsertBlockType(state, name, rootClientId);
});
});
return patternsAllowed;
}, (state, rootClientId) => [state.settings.__experimentalBlockPatterns, state.settings.allowedBlockTypes, state.settings.templateLock, state.blockListSettings[rootClientId], state.blocks.byClientId.get(rootClientId)]);
/**
* Returns the list of patterns based on their declared `blockTypes`
* and a block's name.
* Patterns can use `blockTypes` to integrate in work flows like
* suggesting appropriate patterns in a Placeholder state(during insertion)
* or blocks transformations.
*
* @param {Object} state Editor state.
* @param {string|string[]} blockNames Block's name or array of block names to find matching pattens.
* @param {?string} rootClientId Optional target root client ID.
*
* @return {Array} The list of matched block patterns based on declared `blockTypes` and block name.
*/
const getPatternsByBlockTypes = rememo(function (state, blockNames) {
let rootClientId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
if (!blockNames) return EMPTY_ARRAY;
const patterns = __experimentalGetAllowedPatterns(state, rootClientId);
const normalizedBlockNames = Array.isArray(blockNames) ? blockNames : [blockNames];
const filteredPatterns = patterns.filter(pattern => {
var _pattern$blockTypes, _pattern$blockTypes$s;
return pattern === null || pattern === void 0 ? void 0 : (_pattern$blockTypes = pattern.blockTypes) === null || _pattern$blockTypes === void 0 ? void 0 : (_pattern$blockTypes$s = _pattern$blockTypes.some) === null || _pattern$blockTypes$s === void 0 ? void 0 : _pattern$blockTypes$s.call(_pattern$blockTypes, blockName => normalizedBlockNames.includes(blockName));
});
if (filteredPatterns.length === 0) {
return EMPTY_ARRAY;
}
return filteredPatterns;
}, (state, blockNames, rootClientId) => [...__experimentalGetAllowedPatterns.getDependants(state, rootClientId)]);
const __experimentalGetPatternsByBlockTypes = rememo(function (state, blockNames) {
let rootClientId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
external_wp_deprecated_default()('wp.data.select( "core/block-editor" ).__experimentalGetPatternsByBlockTypes', {
alternative: 'wp.data.select( "core/block-editor" ).getPatternsByBlockTypes',
since: '6.2',
version: '6.4'
});
return getPatternsByBlockTypes(state, blockNames, rootClientId);
}, (state, blockNames, rootClientId) => [...__experimentalGetAllowedPatterns.getDependants(state, rootClientId)]);
/**
* Determines the items that appear in the available pattern transforms list.
*
* For now we only handle blocks without InnerBlocks and take into account
* the `__experimentalRole` property of blocks' attributes for the transformation.
*
* We return the first set of possible eligible block patterns,
* by checking the `blockTypes` property. We still have to recurse through
* block pattern's blocks and try to find matches from the selected blocks.
* Now this happens in the consumer to avoid heavy operations in the selector.
*
* @param {Object} state Editor state.
* @param {Object[]} blocks The selected blocks.
* @param {?string} rootClientId Optional root client ID of block list.
*
* @return {WPBlockPattern[]} Items that are eligible for a pattern transformation.
*/
const __experimentalGetPatternTransformItems = rememo(function (state, blocks) {
let rootClientId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
if (!blocks) return EMPTY_ARRAY;
/**
* For now we only handle blocks without InnerBlocks and take into account
* the `__experimentalRole` property of blocks' attributes for the transformation.
* Note that the blocks have been retrieved through `getBlock`, which doesn't
* return the inner blocks of an inner block controller, so we still need
* to check for this case too.
*/
if (blocks.some(_ref13 => {
let {
clientId,
innerBlocks
} = _ref13;
return innerBlocks.length || areInnerBlocksControlled(state, clientId);
})) {
return EMPTY_ARRAY;
} // Create a Set of the selected block names that is used in patterns filtering.
const selectedBlockNames = Array.from(new Set(blocks.map(_ref14 => {
let {
name
} = _ref14;
return name;
})));
/**
* Here we will return first set of possible eligible block patterns,
* by checking the `blockTypes` property. We still have to recurse through
* block pattern's blocks and try to find matches from the selected blocks.
* Now this happens in the consumer to avoid heavy operations in the selector.
*/
return getPatternsByBlockTypes(state, selectedBlockNames, rootClientId);
}, (state, blocks, rootClientId) => [...getPatternsByBlockTypes.getDependants(state, rootClientId)]);
/**
* Returns the Block List settings of a block, if any exist.
*
* @param {Object} state Editor state.
* @param {?string} clientId Block client ID.
*
* @return {?Object} Block settings of the block if set.
*/
function getBlockListSettings(state, clientId) {
return state.blockListSettings[clientId];
}
/**
* Returns the editor settings.
*
* @param {Object} state Editor state.
*
* @return {Object} The editor settings object.
*/
function getSettings(state) {
return state.settings;
}
/**
* Returns true if the most recent block change is be considered persistent, or
* false otherwise. A persistent change is one committed by BlockEditorProvider
* via its `onChange` callback, in addition to `onInput`.
*
* @param {Object} state Block editor state.
*
* @return {boolean} Whether the most recent block change was persistent.
*/
function isLastBlockChangePersistent(state) {
return state.blocks.isPersistentChange;
}
/**
* Returns the block list settings for an array of blocks, if any exist.
*
* @param {Object} state Editor state.
* @param {Array} clientIds Block client IDs.
*
* @return {Object} An object where the keys are client ids and the values are
* a block list setting object.
*/
const __experimentalGetBlockListSettingsForBlocks = rememo(function (state) {
let clientIds = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
return clientIds.reduce((blockListSettingsForBlocks, clientId) => {
if (!state.blockListSettings[clientId]) {
return blockListSettingsForBlocks;
}
return { ...blockListSettingsForBlocks,
[clientId]: state.blockListSettings[clientId]
};
}, {});
}, state => [state.blockListSettings]);
/**
* Returns the title of a given reusable block
*
* @param {Object} state Global application state.
* @param {number|string} ref The shared block's ID.
*
* @return {string} The reusable block saved title.
*/
const __experimentalGetReusableBlockTitle = rememo((state, ref) => {
var _reusableBlock$title;
const reusableBlock = getReusableBlocks(state).find(block => block.id === ref);
if (!reusableBlock) {
return null;
}
return (_reusableBlock$title = reusableBlock.title) === null || _reusableBlock$title === void 0 ? void 0 : _reusableBlock$title.raw;
}, state => [getReusableBlocks(state)]);
/**
* Returns true if the most recent block change is be considered ignored, or
* false otherwise. An ignored change is one not to be committed by
* BlockEditorProvider, neither via `onChange` nor `onInput`.
*
* @param {Object} state Block editor state.
*
* @return {boolean} Whether the most recent block change was ignored.
*/
function __unstableIsLastBlockChangeIgnored(state) {
// TODO: Removal Plan: Changes incurred by RECEIVE_BLOCKS should not be
// ignored if in-fact they result in a change in blocks state. The current
// need to ignore changes not a result of user interaction should be
// accounted for in the refactoring of reusable blocks as occurring within
// their own separate block editor / state (#7119).
return state.blocks.isIgnoredChange;
}
/**
* Returns the block attributes changed as a result of the last dispatched
* action.
*
* @param {Object} state Block editor state.
*
* @return {Object<string,Object>} Subsets of block attributes changed, keyed
* by block client ID.
*/
function __experimentalGetLastBlockAttributeChanges(state) {
return state.lastBlockAttributesChange;
}
/**
* Returns the available reusable blocks
*
* @param {Object} state Global application state.
*
* @return {Array} Reusable blocks
*/
function getReusableBlocks(state) {
var _state$settings$__exp, _state$settings2;
return (_state$settings$__exp = state === null || state === void 0 ? void 0 : (_state$settings2 = state.settings) === null || _state$settings2 === void 0 ? void 0 : _state$settings2.__experimentalReusableBlocks) !== null && _state$settings$__exp !== void 0 ? _state$settings$__exp : EMPTY_ARRAY;
}
/**
* Returns whether the navigation mode is enabled.
*
* @param {Object} state Editor state.
*
* @return {boolean} Is navigation mode enabled.
*/
function isNavigationMode(state) {
return state.editorMode === 'navigation';
}
/**
* Returns the current editor mode.
*
* @param {Object} state Editor state.
*
* @return {string} the editor mode.
*/
function __unstableGetEditorMode(state) {
return state.editorMode;
}
/**
* Returns whether block moving mode is enabled.
*
* @param {Object} state Editor state.
*
* @return {string} Client Id of moving block.
*/
function selectors_hasBlockMovingClientId(state) {
return state.hasBlockMovingClientId;
}
/**
* Returns true if the last change was an automatic change, false otherwise.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the last change was automatic.
*/
function didAutomaticChange(state) {
return !!state.automaticChangeStatus;
}
/**
* Returns true if the current highlighted block matches the block clientId.
*
* @param {Object} state Global application state.
* @param {string} clientId The block to check.
*
* @return {boolean} Whether the block is currently highlighted.
*/
function isBlockHighlighted(state, clientId) {
return state.highlightedBlock === clientId;
}
/**
* Checks if a given block has controlled inner blocks.
*
* @param {Object} state Global application state.
* @param {string} clientId The block to check.
*
* @return {boolean} True if the block has controlled inner blocks.
*/
function areInnerBlocksControlled(state, clientId) {
return !!state.blocks.controlledInnerBlocks[clientId];
}
/**
* Returns the clientId for the first 'active' block of a given array of block names.
* A block is 'active' if it (or a child) is the selected block.
* Returns the first match moving up the DOM from the selected block.
*
* @param {Object} state Global application state.
* @param {string[]} validBlocksNames The names of block types to check for.
*
* @return {string} The matching block's clientId.
*/
const __experimentalGetActiveBlockIdByBlockNames = rememo((state, validBlockNames) => {
if (!validBlockNames.length) {
return null;
} // Check if selected block is a valid entity area.
const selectedBlockClientId = getSelectedBlockClientId(state);
if (validBlockNames.includes(getBlockName(state, selectedBlockClientId))) {
return selectedBlockClientId;
} // Check if first selected block is a child of a valid entity area.
const multiSelectedBlockClientIds = getMultiSelectedBlockClientIds(state);
const entityAreaParents = getBlockParentsByBlockName(state, selectedBlockClientId || multiSelectedBlockClientIds[0], validBlockNames);
if (entityAreaParents) {
// Last parent closest/most interior.
return entityAreaParents[entityAreaParents.length - 1];
}
return null;
}, (state, validBlockNames) => [state.selection.selectionStart.clientId, state.selection.selectionEnd.clientId, validBlockNames]);
/**
* Tells if the block with the passed clientId was just inserted.
*
* @param {Object} state Global application state.
* @param {Object} clientId Client Id of the block.
* @param {?string} source Optional insertion source of the block.
* @return {boolean} True if the block matches the last block inserted from the specified source.
*/
function wasBlockJustInserted(state, clientId, source) {
var _lastBlockInserted$cl;
const {
lastBlockInserted
} = state;
return ((_lastBlockInserted$cl = lastBlockInserted.clientIds) === null || _lastBlockInserted$cl === void 0 ? void 0 : _lastBlockInserted$cl.includes(clientId)) && lastBlockInserted.source === source;
}
/**
* Tells if the block is visible on the canvas or not.
*
* @param {Object} state Global application state.
* @param {Object} clientId Client Id of the block.
* @return {boolean} True if the block is visible.
*/
function isBlockVisible(state, clientId) {
var _state$blockVisibilit, _state$blockVisibilit2;
return (_state$blockVisibilit = (_state$blockVisibilit2 = state.blockVisibility) === null || _state$blockVisibilit2 === void 0 ? void 0 : _state$blockVisibilit2[clientId]) !== null && _state$blockVisibilit !== void 0 ? _state$blockVisibilit : true;
}
/**
* Returns the list of all hidden blocks.
*
* @param {Object} state Global application state.
* @return {[string]} List of hidden blocks.
*/
const __unstableGetVisibleBlocks = rememo(state => {
return new Set(Object.keys(state.blockVisibility).filter(key => state.blockVisibility[key]));
}, state => [state.blockVisibility]);
/**
* DO-NOT-USE in production.
* This selector is created for internal/experimental only usage and may be
* removed anytime without any warning, causing breakage on any plugin or theme invoking it.
*/
const __unstableGetContentLockingParent = rememo((state, clientId) => {
let current = clientId;
let result;
while (state.blocks.parents.has(current)) {
current = state.blocks.parents.get(current);
if (current && getTemplateLock(state, current) === 'contentOnly') {
result = current;
}
}
return result;
}, state => [state.blocks.parents, state.blockListSettings]);
/**
* DO-NOT-USE in production.
* This selector is created for internal/experimental only usage and may be
* removed anytime without any warning, causing breakage on any plugin or theme invoking it.
*
* @param {Object} state Global application state.
*/
function __unstableGetTemporarilyEditingAsBlocks(state) {
return state.temporarilyEditingAsBlocks;
}
function __unstableHasActiveBlockOverlayActive(state, clientId) {
// If the block editing is locked, the block overlay is always active.
if (!canEditBlock(state, clientId)) {
return true;
}
const editorMode = __unstableGetEditorMode(state); // In zoom-out mode, the block overlay is always active for top level blocks.
if (editorMode === 'zoom-out' && clientId && !getBlockRootClientId(state, clientId)) {
return true;
} // In navigation mode, the block overlay is active when the block is not
// selected (and doesn't contain a selected child). The same behavior is
// also enabled in all modes for blocks that have controlled children
// (reusable block, template part, navigation), unless explicitly disabled
// with `supports.__experimentalDisableBlockOverlay`.
const blockSupportDisable = (0,external_wp_blocks_namespaceObject.hasBlockSupport)(getBlockName(state, clientId), '__experimentalDisableBlockOverlay', false);
const shouldEnableIfUnselected = editorMode === 'navigation' || (blockSupportDisable ? false : areInnerBlocksControlled(state, clientId));
return shouldEnableIfUnselected && !isBlockSelected(state, clientId) && !hasSelectedInnerBlock(state, clientId, true);
}
function __unstableIsWithinBlockOverlay(state, clientId) {
let parent = state.blocks.parents.get(clientId);
while (!!parent) {
if (__unstableHasActiveBlockOverlayActive(state, parent)) {
return true;
}
parent = state.blocks.parents.get(parent);
}
return false;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/store/private-actions.js
/**
* WordPress dependencies
*/
/**
* A list of private/experimental block editor settings that
* should not become a part of the WordPress public API.
* BlockEditorProvider will remove these settings from the
* settings object it receives.
*
* @see https://github.com/WordPress/gutenberg/pull/46131
*/
const privateSettings = ['inserterMediaCategories', 'blockInspectorAnimation'];
/**
* Action that updates the block editor settings and
* conditionally preserves the experimental ones.
*
* @param {Object} settings Updated settings
* @param {boolean} stripExperimentalSettings Whether to strip experimental settings.
* @return {Object} Action object
*/
function __experimentalUpdateSettings(settings) {
let stripExperimentalSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
let cleanSettings = settings; // There are no plugins in the mobile apps, so there is no
// need to strip the experimental settings:
if (stripExperimentalSettings && external_wp_element_namespaceObject.Platform.OS === 'web') {
cleanSettings = {};
for (const key in settings) {
if (!privateSettings.includes(key)) {
cleanSettings[key] = settings[key];
}
}
}
return {
type: 'UPDATE_SETTINGS',
settings: cleanSettings
};
}
/**
* Hides the block interface (eg. toolbar, outline, etc.)
*
* @return {Object} Action object.
*/
function hideBlockInterface() {
return {
type: 'HIDE_BLOCK_INTERFACE'
};
}
/**
* Shows the block interface (eg. toolbar, outline, etc.)
*
* @return {Object} Action object.
*/
function showBlockInterface() {
return {
type: 'SHOW_BLOCK_INTERFACE'
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/store/private-selectors.js
/**
* Returns true if the block interface is hidden, or false otherwise.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the block toolbar is hidden.
*/
function private_selectors_isBlockInterfaceHidden(state) {
return state.isBlockInterfaceHidden;
}
/**
* Gets the client ids of the last inserted blocks.
*
* @param {Object} state Global application state.
* @return {Array|undefined} Client Ids of the last inserted block(s).
*/
function getLastInsertedBlocksClientIds(state) {
var _state$lastBlockInser;
return state === null || state === void 0 ? void 0 : (_state$lastBlockInser = state.lastBlockInserted) === null || _state$lastBlockInser === void 0 ? void 0 : _state$lastBlockInser.clientIds;
}
;// CONCATENATED MODULE: external ["wp","a11y"]
var external_wp_a11y_namespaceObject = window["wp"]["a11y"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/utils/selection.js
/**
* A robust way to retain selection position through various
* transforms is to insert a special character at the position and
* then recover it.
*/
const START_OF_SELECTED_AREA = '\u0086';
/**
* Retrieve the block attribute that contains the selection position.
*
* @param {Object} blockAttributes Block attributes.
* @return {string|void} The name of the block attribute that was previously selected.
*/
function retrieveSelectedAttribute(blockAttributes) {
if (!blockAttributes) {
return;
}
return Object.keys(blockAttributes).find(name => {
const value = blockAttributes[name];
return typeof value === 'string' && value.indexOf(START_OF_SELECTED_AREA) !== -1;
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/store/actions.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/** @typedef {import('../components/use-on-block-drop/types').WPDropOperation} WPDropOperation */
const castArray = maybeArray => Array.isArray(maybeArray) ? maybeArray : [maybeArray];
/**
* Action which will insert a default block insert action if there
* are no other blocks at the root of the editor. This action should be used
* in actions which may result in no blocks remaining in the editor (removal,
* replacement, etc).
*/
const ensureDefaultBlock = () => _ref => {
let {
select,
dispatch
} = _ref;
// To avoid a focus loss when removing the last block, assure there is
// always a default block if the last of the blocks have been removed.
const count = select.getBlockCount();
if (count > 0) {
return;
} // If there's an custom appender, don't insert default block.
// We have to remember to manually move the focus elsewhere to
// prevent it from being lost though.
const {
__unstableHasCustomAppender
} = select.getSettings();
if (__unstableHasCustomAppender) {
return;
}
dispatch.insertDefaultBlock();
};
/**
* Action that resets blocks state to the specified array of blocks, taking precedence
* over any other content reflected as an edit in state.
*
* @param {Array} blocks Array of blocks.
*/
const resetBlocks = blocks => _ref2 => {
let {
dispatch
} = _ref2;
dispatch({
type: 'RESET_BLOCKS',
blocks
});
dispatch(validateBlocksToTemplate(blocks));
};
/**
* Block validity is a function of blocks state (at the point of a
* reset) and the template setting. As a compromise to its placement
* across distinct parts of state, it is implemented here as a side-
* effect of the block reset action.
*
* @param {Array} blocks Array of blocks.
*/
const validateBlocksToTemplate = blocks => _ref3 => {
let {
select,
dispatch
} = _ref3;
const template = select.getTemplate();
const templateLock = select.getTemplateLock(); // Unlocked templates are considered always valid because they act
// as default values only.
const isBlocksValidToTemplate = !template || templateLock !== 'all' || (0,external_wp_blocks_namespaceObject.doBlocksMatchTemplate)(blocks, template); // Update if validity has changed.
const isValidTemplate = select.isValidTemplate();
if (isBlocksValidToTemplate !== isValidTemplate) {
dispatch.setTemplateValidity(isBlocksValidToTemplate);
return isBlocksValidToTemplate;
}
};
/**
* A block selection object.
*
* @typedef {Object} WPBlockSelection
*
* @property {string} clientId A block client ID.
* @property {string} attributeKey A block attribute key.
* @property {number} offset An attribute value offset, based on the rich
* text value. See `wp.richText.create`.
*/
/**
* A selection object.
*
* @typedef {Object} WPSelection
*
* @property {WPBlockSelection} start The selection start.
* @property {WPBlockSelection} end The selection end.
*/
/* eslint-disable jsdoc/valid-types */
/**
* Returns an action object used in signalling that selection state should be
* reset to the specified selection.
*
* @param {WPBlockSelection} selectionStart The selection start.
* @param {WPBlockSelection} selectionEnd The selection end.
* @param {0|-1|null} initialPosition Initial block position.
*
* @return {Object} Action object.
*/
function resetSelection(selectionStart, selectionEnd, initialPosition) {
/* eslint-enable jsdoc/valid-types */
return {
type: 'RESET_SELECTION',
selectionStart,
selectionEnd,
initialPosition
};
}
/**
* Returns an action object used in signalling that blocks have been received.
* Unlike resetBlocks, these should be appended to the existing known set, not
* replacing.
*
* @deprecated
*
* @param {Object[]} blocks Array of block objects.
*
* @return {Object} Action object.
*/
function receiveBlocks(blocks) {
external_wp_deprecated_default()('wp.data.dispatch( "core/block-editor" ).receiveBlocks', {
since: '5.9',
alternative: 'resetBlocks or insertBlocks'
});
return {
type: 'RECEIVE_BLOCKS',
blocks
};
}
/**
* Action that updates attributes of multiple blocks with the specified client IDs.
*
* @param {string|string[]} clientIds Block client IDs.
* @param {Object} attributes Block attributes to be merged. Should be keyed by clientIds if
* uniqueByBlock is true.
* @param {boolean} uniqueByBlock true if each block in clientIds array has a unique set of attributes
* @return {Object} Action object.
*/
function updateBlockAttributes(clientIds, attributes) {
let uniqueByBlock = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
return {
type: 'UPDATE_BLOCK_ATTRIBUTES',
clientIds: castArray(clientIds),
attributes,
uniqueByBlock
};
}
/**
* Action that updates the block with the specified client ID.
*
* @param {string} clientId Block client ID.
* @param {Object} updates Block attributes to be merged.
*
* @return {Object} Action object.
*/
function updateBlock(clientId, updates) {
return {
type: 'UPDATE_BLOCK',
clientId,
updates
};
}
/* eslint-disable jsdoc/valid-types */
/**
* Returns an action object used in signalling that the block with the
* specified client ID has been selected, optionally accepting a position
* value reflecting its selection directionality. An initialPosition of -1
* reflects a reverse selection.
*
* @param {string} clientId Block client ID.
* @param {0|-1|null} initialPosition Optional initial position. Pass as -1 to
* reflect reverse selection.
*
* @return {Object} Action object.
*/
function selectBlock(clientId) {
let initialPosition = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
/* eslint-enable jsdoc/valid-types */
return {
type: 'SELECT_BLOCK',
initialPosition,
clientId
};
}
/**
* Yields action objects used in signalling that the block preceding the given
* clientId (or optionally, its first parent from bottom to top)
* should be selected.
*
* @param {string} clientId Block client ID.
* @param {boolean} fallbackToParent If true, select the first parent if there is no previous block.
*/
const selectPreviousBlock = function (clientId) {
let fallbackToParent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
return _ref4 => {
let {
select,
dispatch
} = _ref4;
const previousBlockClientId = select.getPreviousBlockClientId(clientId);
if (previousBlockClientId) {
dispatch.selectBlock(previousBlockClientId, -1);
} else if (fallbackToParent) {
const firstParentClientId = select.getBlockRootClientId(clientId);
if (firstParentClientId) {
dispatch.selectBlock(firstParentClientId, -1);
}
}
};
};
/**
* Yields action objects used in signalling that the block following the given
* clientId should be selected.
*
* @param {string} clientId Block client ID.
*/
const selectNextBlock = clientId => _ref5 => {
let {
select,
dispatch
} = _ref5;
const nextBlockClientId = select.getNextBlockClientId(clientId);
if (nextBlockClientId) {
dispatch.selectBlock(nextBlockClientId);
}
};
/**
* Action that starts block multi-selection.
*
* @return {Object} Action object.
*/
function startMultiSelect() {
return {
type: 'START_MULTI_SELECT'
};
}
/**
* Action that stops block multi-selection.
*
* @return {Object} Action object.
*/
function stopMultiSelect() {
return {
type: 'STOP_MULTI_SELECT'
};
}
/**
* Action that changes block multi-selection.
*
* @param {string} start First block of the multi selection.
* @param {string} end Last block of the multiselection.
* @param {number|null} __experimentalInitialPosition Optional initial position. Pass as null to skip focus within editor canvas.
*/
const multiSelect = function (start, end) {
let __experimentalInitialPosition = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
return _ref6 => {
let {
select,
dispatch
} = _ref6;
const startBlockRootClientId = select.getBlockRootClientId(start);
const endBlockRootClientId = select.getBlockRootClientId(end); // Only allow block multi-selections at the same level.
if (startBlockRootClientId !== endBlockRootClientId) {
return;
}
dispatch({
type: 'MULTI_SELECT',
start,
end,
initialPosition: __experimentalInitialPosition
});
const blockCount = select.getSelectedBlockCount();
(0,external_wp_a11y_namespaceObject.speak)((0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: number of selected blocks */
(0,external_wp_i18n_namespaceObject._n)('%s block selected.', '%s blocks selected.', blockCount), blockCount), 'assertive');
};
};
/**
* Action that clears the block selection.
*
* @return {Object} Action object.
*/
function clearSelectedBlock() {
return {
type: 'CLEAR_SELECTED_BLOCK'
};
}
/**
* Action that enables or disables block selection.
*
* @param {boolean} [isSelectionEnabled=true] Whether block selection should
* be enabled.
*
* @return {Object} Action object.
*/
function toggleSelection() {
let isSelectionEnabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
return {
type: 'TOGGLE_SELECTION',
isSelectionEnabled
};
}
function getBlocksWithDefaultStylesApplied(blocks, blockEditorSettings) {
var _blockEditorSettings$, _blockEditorSettings$2;
const preferredStyleVariations = (_blockEditorSettings$ = blockEditorSettings === null || blockEditorSettings === void 0 ? void 0 : (_blockEditorSettings$2 = blockEditorSettings.__experimentalPreferredStyleVariations) === null || _blockEditorSettings$2 === void 0 ? void 0 : _blockEditorSettings$2.value) !== null && _blockEditorSettings$ !== void 0 ? _blockEditorSettings$ : {};
return blocks.map(block => {
var _block$attributes;
const blockName = block.name;
if (!(0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockName, 'defaultStylePicker', true)) {
return block;
}
if (!preferredStyleVariations[blockName]) {
return block;
}
const className = (_block$attributes = block.attributes) === null || _block$attributes === void 0 ? void 0 : _block$attributes.className;
if (className !== null && className !== void 0 && className.includes('is-style-')) {
return block;
}
const {
attributes = {}
} = block;
const blockStyle = preferredStyleVariations[blockName];
return { ...block,
attributes: { ...attributes,
className: `${className || ''} is-style-${blockStyle}`.trim()
}
};
});
}
/* eslint-disable jsdoc/valid-types */
/**
* Action that replaces given blocks with one or more replacement blocks.
*
* @param {(string|string[])} clientIds Block client ID(s) to replace.
* @param {(Object|Object[])} blocks Replacement block(s).
* @param {number} indexToSelect Index of replacement block to select.
* @param {0|-1|null} initialPosition Index of caret after in the selected block after the operation.
* @param {?Object} meta Optional Meta values to be passed to the action object.
*
* @return {Object} Action object.
*/
const replaceBlocks = function (clientIds, blocks, indexToSelect) {
let initialPosition = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
let meta = arguments.length > 4 ? arguments[4] : undefined;
return _ref7 => {
let {
select,
dispatch
} = _ref7;
/* eslint-enable jsdoc/valid-types */
clientIds = castArray(clientIds);
blocks = getBlocksWithDefaultStylesApplied(castArray(blocks), select.getSettings());
const rootClientId = select.getBlockRootClientId(clientIds[0]); // Replace is valid if the new blocks can be inserted in the root block.
for (let index = 0; index < blocks.length; index++) {
const block = blocks[index];
const canInsertBlock = select.canInsertBlockType(block.name, rootClientId);
if (!canInsertBlock) {
return;
}
}
dispatch({
type: 'REPLACE_BLOCKS',
clientIds,
blocks,
time: Date.now(),
indexToSelect,
initialPosition,
meta
});
dispatch(ensureDefaultBlock());
};
};
/**
* Action that replaces a single block with one or more replacement blocks.
*
* @param {(string|string[])} clientId Block client ID to replace.
* @param {(Object|Object[])} block Replacement block(s).
*
* @return {Object} Action object.
*/
function replaceBlock(clientId, block) {
return replaceBlocks(clientId, block);
}
/**
* Higher-order action creator which, given the action type to dispatch creates
* an action creator for managing block movement.
*
* @param {string} type Action type to dispatch.
*
* @return {Function} Action creator.
*/
const createOnMove = type => (clientIds, rootClientId) => _ref8 => {
let {
select,
dispatch
} = _ref8;
// If one of the blocks is locked or the parent is locked, we cannot move any block.
const canMoveBlocks = select.canMoveBlocks(clientIds, rootClientId);
if (!canMoveBlocks) {
return;
}
dispatch({
type,
clientIds: castArray(clientIds),
rootClientId
});
};
const moveBlocksDown = createOnMove('MOVE_BLOCKS_DOWN');
const moveBlocksUp = createOnMove('MOVE_BLOCKS_UP');
/**
* Action that moves given blocks to a new position.
*
* @param {?string} clientIds The client IDs of the blocks.
* @param {?string} fromRootClientId Root client ID source.
* @param {?string} toRootClientId Root client ID destination.
* @param {number} index The index to move the blocks to.
*/
const moveBlocksToPosition = function (clientIds) {
let fromRootClientId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
let toRootClientId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
let index = arguments.length > 3 ? arguments[3] : undefined;
return _ref9 => {
let {
select,
dispatch
} = _ref9;
const canMoveBlocks = select.canMoveBlocks(clientIds, fromRootClientId); // If one of the blocks is locked or the parent is locked, we cannot move any block.
if (!canMoveBlocks) {
return;
} // If moving inside the same root block the move is always possible.
if (fromRootClientId !== toRootClientId) {
const canRemoveBlocks = select.canRemoveBlocks(clientIds, fromRootClientId); // If we're moving to another block, it means we're deleting blocks from
// the original block, so we need to check if removing is possible.
if (!canRemoveBlocks) {
return;
}
const canInsertBlocks = select.canInsertBlocks(clientIds, toRootClientId); // If moving to other parent block, the move is possible if we can insert a block of the same type inside the new parent block.
if (!canInsertBlocks) {
return;
}
}
dispatch({
type: 'MOVE_BLOCKS_TO_POSITION',
fromRootClientId,
toRootClientId,
clientIds,
index
});
};
};
/**
* Action that moves given block to a new position.
*
* @param {?string} clientId The client ID of the block.
* @param {?string} fromRootClientId Root client ID source.
* @param {?string} toRootClientId Root client ID destination.
* @param {number} index The index to move the block to.
*/
function moveBlockToPosition(clientId) {
let fromRootClientId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
let toRootClientId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
let index = arguments.length > 3 ? arguments[3] : undefined;
return moveBlocksToPosition([clientId], fromRootClientId, toRootClientId, index);
}
/**
* Action that inserts a single block, optionally at a specific index respective a root block list.
*
* @param {Object} block Block object to insert.
* @param {?number} index Index at which block should be inserted.
* @param {?string} rootClientId Optional root client ID of block list on which to insert.
* @param {?boolean} updateSelection If true block selection will be updated. If false, block selection will not change. Defaults to true.
* @param {?Object} meta Optional Meta values to be passed to the action object.
*
* @return {Object} Action object.
*/
function insertBlock(block, index, rootClientId, updateSelection, meta) {
return insertBlocks([block], index, rootClientId, updateSelection, 0, meta);
}
/* eslint-disable jsdoc/valid-types */
/**
* Action that inserts an array of blocks, optionally at a specific index respective a root block list.
*
* @param {Object[]} blocks Block objects to insert.
* @param {?number} index Index at which block should be inserted.
* @param {?string} rootClientId Optional root client ID of block list on which to insert.
* @param {?boolean} updateSelection If true block selection will be updated. If false, block selection will not change. Defaults to true.
* @param {0|-1|null} initialPosition Initial focus position. Setting it to null prevent focusing the inserted block.
* @param {?Object} meta Optional Meta values to be passed to the action object.
* @return {Object} Action object.
*/
const insertBlocks = function (blocks, index, rootClientId) {
let updateSelection = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
let initialPosition = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
let meta = arguments.length > 5 ? arguments[5] : undefined;
return _ref10 => {
let {
select,
dispatch
} = _ref10;
/* eslint-enable jsdoc/valid-types */
if (initialPosition !== null && typeof initialPosition === 'object') {
meta = initialPosition;
initialPosition = 0;
external_wp_deprecated_default()("meta argument in wp.data.dispatch('core/block-editor')", {
since: '5.8',
hint: 'The meta argument is now the 6th argument of the function'
});
}
blocks = getBlocksWithDefaultStylesApplied(castArray(blocks), select.getSettings());
const allowedBlocks = [];
for (const block of blocks) {
const isValid = select.canInsertBlockType(block.name, rootClientId);
if (isValid) {
allowedBlocks.push(block);
}
}
if (allowedBlocks.length) {
dispatch({
type: 'INSERT_BLOCKS',
blocks: allowedBlocks,
index,
rootClientId,
time: Date.now(),
updateSelection,
initialPosition: updateSelection ? initialPosition : null,
meta
});
}
};
};
/**
* Action that shows the insertion point.
*
* @param {?string} rootClientId Optional root client ID of block list on
* which to insert.
* @param {?number} index Index at which block should be inserted.
* @param {?Object} __unstableOptions Additional options.
* @property {boolean} __unstableWithInserter Whether or not to show an inserter button.
* @property {WPDropOperation} operation The operation to perform when applied,
* either 'insert' or 'replace' for now.
*
* @return {Object} Action object.
*/
function showInsertionPoint(rootClientId, index) {
let __unstableOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
const {
__unstableWithInserter,
operation
} = __unstableOptions;
return {
type: 'SHOW_INSERTION_POINT',
rootClientId,
index,
__unstableWithInserter,
operation
};
}
/**
* Action that hides the insertion point.
*/
const hideInsertionPoint = () => _ref11 => {
let {
select,
dispatch
} = _ref11;
if (!select.isBlockInsertionPointVisible()) {
return;
}
dispatch({
type: 'HIDE_INSERTION_POINT'
});
};
/**
* Action that resets the template validity.
*
* @param {boolean} isValid template validity flag.
*
* @return {Object} Action object.
*/
function setTemplateValidity(isValid) {
return {
type: 'SET_TEMPLATE_VALIDITY',
isValid
};
}
/**
* Action that synchronizes the template with the list of blocks.
*
* @return {Object} Action object.
*/
const synchronizeTemplate = () => _ref12 => {
let {
select,
dispatch
} = _ref12;
dispatch({
type: 'SYNCHRONIZE_TEMPLATE'
});
const blocks = select.getBlocks();
const template = select.getTemplate();
const updatedBlockList = (0,external_wp_blocks_namespaceObject.synchronizeBlocksWithTemplate)(blocks, template);
dispatch.resetBlocks(updatedBlockList);
};
/**
* Delete the current selection.
*
* @param {boolean} isForward
*/
const __unstableDeleteSelection = isForward => _ref13 => {
let {
registry,
select,
dispatch
} = _ref13;
const selectionAnchor = select.getSelectionStart();
const selectionFocus = select.getSelectionEnd();
if (selectionAnchor.clientId === selectionFocus.clientId) return; // It's not mergeable if there's no rich text selection.
if (!selectionAnchor.attributeKey || !selectionFocus.attributeKey || typeof selectionAnchor.offset === 'undefined' || typeof selectionFocus.offset === 'undefined') return false;
const anchorRootClientId = select.getBlockRootClientId(selectionAnchor.clientId);
const focusRootClientId = select.getBlockRootClientId(selectionFocus.clientId); // It's not mergeable if the selection doesn't start and end in the same
// block list. Maybe in the future it should be allowed.
if (anchorRootClientId !== focusRootClientId) {
return;
}
const blockOrder = select.getBlockOrder(anchorRootClientId);
const anchorIndex = blockOrder.indexOf(selectionAnchor.clientId);
const focusIndex = blockOrder.indexOf(selectionFocus.clientId); // Reassign selection start and end based on order.
let selectionStart, selectionEnd;
if (anchorIndex > focusIndex) {
selectionStart = selectionFocus;
selectionEnd = selectionAnchor;
} else {
selectionStart = selectionAnchor;
selectionEnd = selectionFocus;
}
const targetSelection = isForward ? selectionEnd : selectionStart;
const targetBlock = select.getBlock(targetSelection.clientId);
const targetBlockType = (0,external_wp_blocks_namespaceObject.getBlockType)(targetBlock.name);
if (!targetBlockType.merge) {
return;
}
const selectionA = selectionStart;
const selectionB = selectionEnd;
const blockA = select.getBlock(selectionA.clientId);
const blockAType = (0,external_wp_blocks_namespaceObject.getBlockType)(blockA.name);
const blockB = select.getBlock(selectionB.clientId);
const blockBType = (0,external_wp_blocks_namespaceObject.getBlockType)(blockB.name);
const htmlA = blockA.attributes[selectionA.attributeKey];
const htmlB = blockB.attributes[selectionB.attributeKey];
const attributeDefinitionA = blockAType.attributes[selectionA.attributeKey];
const attributeDefinitionB = blockBType.attributes[selectionB.attributeKey];
let valueA = (0,external_wp_richText_namespaceObject.create)({
html: htmlA,
...mapRichTextSettings(attributeDefinitionA)
});
let valueB = (0,external_wp_richText_namespaceObject.create)({
html: htmlB,
...mapRichTextSettings(attributeDefinitionB)
});
valueA = (0,external_wp_richText_namespaceObject.remove)(valueA, selectionA.offset, valueA.text.length);
valueB = (0,external_wp_richText_namespaceObject.insert)(valueB, START_OF_SELECTED_AREA, 0, selectionB.offset); // Clone the blocks so we don't manipulate the original.
const cloneA = (0,external_wp_blocks_namespaceObject.cloneBlock)(blockA, {
[selectionA.attributeKey]: (0,external_wp_richText_namespaceObject.toHTMLString)({
value: valueA,
...mapRichTextSettings(attributeDefinitionA)
})
});
const cloneB = (0,external_wp_blocks_namespaceObject.cloneBlock)(blockB, {
[selectionB.attributeKey]: (0,external_wp_richText_namespaceObject.toHTMLString)({
value: valueB,
...mapRichTextSettings(attributeDefinitionB)
})
});
const followingBlock = isForward ? cloneA : cloneB; // We can only merge blocks with similar types
// thus, we transform the block to merge first
const blocksWithTheSameType = blockA.name === blockB.name ? [followingBlock] : (0,external_wp_blocks_namespaceObject.switchToBlockType)(followingBlock, targetBlockType.name); // If the block types can not match, do nothing
if (!blocksWithTheSameType || !blocksWithTheSameType.length) {
return;
}
let updatedAttributes;
if (isForward) {
const blockToMerge = blocksWithTheSameType.pop();
updatedAttributes = targetBlockType.merge(blockToMerge.attributes, cloneB.attributes);
} else {
const blockToMerge = blocksWithTheSameType.shift();
updatedAttributes = targetBlockType.merge(cloneA.attributes, blockToMerge.attributes);
}
const newAttributeKey = retrieveSelectedAttribute(updatedAttributes);
const convertedHtml = updatedAttributes[newAttributeKey];
const convertedValue = (0,external_wp_richText_namespaceObject.create)({
html: convertedHtml,
...mapRichTextSettings(targetBlockType.attributes[newAttributeKey])
});
const newOffset = convertedValue.text.indexOf(START_OF_SELECTED_AREA);
const newValue = (0,external_wp_richText_namespaceObject.remove)(convertedValue, newOffset, newOffset + 1);
const newHtml = (0,external_wp_richText_namespaceObject.toHTMLString)({
value: newValue,
...mapRichTextSettings(targetBlockType.attributes[newAttributeKey])
});
updatedAttributes[newAttributeKey] = newHtml;
const selectedBlockClientIds = select.getSelectedBlockClientIds();
const replacement = [...(isForward ? blocksWithTheSameType : []), { // Preserve the original client ID.
...targetBlock,
attributes: { ...targetBlock.attributes,
...updatedAttributes
}
}, ...(isForward ? [] : blocksWithTheSameType)];
registry.batch(() => {
dispatch.selectionChange(targetBlock.clientId, newAttributeKey, newOffset, newOffset);
dispatch.replaceBlocks(selectedBlockClientIds, replacement, 0, // If we don't pass the `indexToSelect` it will default to the last block.
select.getSelectedBlocksInitialCaretPosition());
});
};
/**
* Split the current selection.
*/
const __unstableSplitSelection = () => _ref14 => {
let {
select,
dispatch
} = _ref14;
const selectionAnchor = select.getSelectionStart();
const selectionFocus = select.getSelectionEnd();
if (selectionAnchor.clientId === selectionFocus.clientId) return; // Can't split if the selection is not set.
if (!selectionAnchor.attributeKey || !selectionFocus.attributeKey || typeof selectionAnchor.offset === 'undefined' || typeof selectionFocus.offset === 'undefined') return;
const anchorRootClientId = select.getBlockRootClientId(selectionAnchor.clientId);
const focusRootClientId = select.getBlockRootClientId(selectionFocus.clientId); // It's not splittable if the selection doesn't start and end in the same
// block list. Maybe in the future it should be allowed.
if (anchorRootClientId !== focusRootClientId) {
return;
}
const blockOrder = select.getBlockOrder(anchorRootClientId);
const anchorIndex = blockOrder.indexOf(selectionAnchor.clientId);
const focusIndex = blockOrder.indexOf(selectionFocus.clientId); // Reassign selection start and end based on order.
let selectionStart, selectionEnd;
if (anchorIndex > focusIndex) {
selectionStart = selectionFocus;
selectionEnd = selectionAnchor;
} else {
selectionStart = selectionAnchor;
selectionEnd = selectionFocus;
}
const selectionA = selectionStart;
const selectionB = selectionEnd;
const blockA = select.getBlock(selectionA.clientId);
const blockAType = (0,external_wp_blocks_namespaceObject.getBlockType)(blockA.name);
const blockB = select.getBlock(selectionB.clientId);
const blockBType = (0,external_wp_blocks_namespaceObject.getBlockType)(blockB.name);
const htmlA = blockA.attributes[selectionA.attributeKey];
const htmlB = blockB.attributes[selectionB.attributeKey];
const attributeDefinitionA = blockAType.attributes[selectionA.attributeKey];
const attributeDefinitionB = blockBType.attributes[selectionB.attributeKey];
let valueA = (0,external_wp_richText_namespaceObject.create)({
html: htmlA,
...mapRichTextSettings(attributeDefinitionA)
});
let valueB = (0,external_wp_richText_namespaceObject.create)({
html: htmlB,
...mapRichTextSettings(attributeDefinitionB)
});
valueA = (0,external_wp_richText_namespaceObject.remove)(valueA, selectionA.offset, valueA.text.length);
valueB = (0,external_wp_richText_namespaceObject.remove)(valueB, 0, selectionB.offset);
dispatch.replaceBlocks(select.getSelectedBlockClientIds(), [{ // Preserve the original client ID.
...blockA,
attributes: { ...blockA.attributes,
[selectionA.attributeKey]: (0,external_wp_richText_namespaceObject.toHTMLString)({
value: valueA,
...mapRichTextSettings(attributeDefinitionA)
})
}
}, (0,external_wp_blocks_namespaceObject.createBlock)((0,external_wp_blocks_namespaceObject.getDefaultBlockName)()), { // Preserve the original client ID.
...blockB,
attributes: { ...blockB.attributes,
[selectionB.attributeKey]: (0,external_wp_richText_namespaceObject.toHTMLString)({
value: valueB,
...mapRichTextSettings(attributeDefinitionB)
})
}
}], 1, // If we don't pass the `indexToSelect` it will default to the last block.
select.getSelectedBlocksInitialCaretPosition());
};
/**
* Expand the selection to cover the entire blocks, removing partial selection.
*/
const __unstableExpandSelection = () => _ref15 => {
let {
select,
dispatch
} = _ref15;
const selectionAnchor = select.getSelectionStart();
const selectionFocus = select.getSelectionEnd();
dispatch.selectionChange({
start: {
clientId: selectionAnchor.clientId
},
end: {
clientId: selectionFocus.clientId
}
});
};
/**
* Action that merges two blocks.
*
* @param {string} firstBlockClientId Client ID of the first block to merge.
* @param {string} secondBlockClientId Client ID of the second block to merge.
*/
const mergeBlocks = (firstBlockClientId, secondBlockClientId) => _ref16 => {
let {
registry,
select,
dispatch
} = _ref16;
const blocks = [firstBlockClientId, secondBlockClientId];
dispatch({
type: 'MERGE_BLOCKS',
blocks
});
const [clientIdA, clientIdB] = blocks;
const blockA = select.getBlock(clientIdA);
const blockAType = (0,external_wp_blocks_namespaceObject.getBlockType)(blockA.name);
if (!blockAType) return;
const blockB = select.getBlock(clientIdB);
if (blockAType && !blockAType.merge) {
// If there's no merge function defined, attempt merging inner
// blocks.
const blocksWithTheSameType = (0,external_wp_blocks_namespaceObject.switchToBlockType)(blockB, blockAType.name); // Only focus the previous block if it's not mergeable.
if ((blocksWithTheSameType === null || blocksWithTheSameType === void 0 ? void 0 : blocksWithTheSameType.length) !== 1) {
dispatch.selectBlock(blockA.clientId);
return;
}
const [blockWithSameType] = blocksWithTheSameType;
if (blockWithSameType.innerBlocks.length < 1) {
dispatch.selectBlock(blockA.clientId);
return;
}
registry.batch(() => {
dispatch.insertBlocks(blockWithSameType.innerBlocks, undefined, clientIdA);
dispatch.removeBlock(clientIdB);
dispatch.selectBlock(blockWithSameType.innerBlocks[0].clientId);
});
return;
}
const blockBType = (0,external_wp_blocks_namespaceObject.getBlockType)(blockB.name);
const {
clientId,
attributeKey,
offset
} = select.getSelectionStart();
const selectedBlockType = clientId === clientIdA ? blockAType : blockBType;
const attributeDefinition = selectedBlockType.attributes[attributeKey];
const canRestoreTextSelection = (clientId === clientIdA || clientId === clientIdB) && attributeKey !== undefined && offset !== undefined && // We cannot restore text selection if the RichText identifier
// is not a defined block attribute key. This can be the case if the
// fallback intance ID is used to store selection (and no RichText
// identifier is set), or when the identifier is wrong.
!!attributeDefinition;
if (!attributeDefinition) {
if (typeof attributeKey === 'number') {
window.console.error(`RichText needs an identifier prop that is the block attribute key of the attribute it controls. Its type is expected to be a string, but was ${typeof attributeKey}`);
} else {
window.console.error('The RichText identifier prop does not match any attributes defined by the block.');
}
} // Clone the blocks so we don't insert the character in a "live" block.
const cloneA = (0,external_wp_blocks_namespaceObject.cloneBlock)(blockA);
const cloneB = (0,external_wp_blocks_namespaceObject.cloneBlock)(blockB);
if (canRestoreTextSelection) {
const selectedBlock = clientId === clientIdA ? cloneA : cloneB;
const html = selectedBlock.attributes[attributeKey];
const value = (0,external_wp_richText_namespaceObject.insert)((0,external_wp_richText_namespaceObject.create)({
html,
...mapRichTextSettings(attributeDefinition)
}), START_OF_SELECTED_AREA, offset, offset);
selectedBlock.attributes[attributeKey] = (0,external_wp_richText_namespaceObject.toHTMLString)({
value,
...mapRichTextSettings(attributeDefinition)
});
} // We can only merge blocks with similar types
// thus, we transform the block to merge first.
const blocksWithTheSameType = blockA.name === blockB.name ? [cloneB] : (0,external_wp_blocks_namespaceObject.switchToBlockType)(cloneB, blockA.name); // If the block types can not match, do nothing.
if (!blocksWithTheSameType || !blocksWithTheSameType.length) {
return;
} // Calling the merge to update the attributes and remove the block to be merged.
const updatedAttributes = blockAType.merge(cloneA.attributes, blocksWithTheSameType[0].attributes);
if (canRestoreTextSelection) {
const newAttributeKey = retrieveSelectedAttribute(updatedAttributes);
const convertedHtml = updatedAttributes[newAttributeKey];
const convertedValue = (0,external_wp_richText_namespaceObject.create)({
html: convertedHtml,
...mapRichTextSettings(blockAType.attributes[newAttributeKey])
});
const newOffset = convertedValue.text.indexOf(START_OF_SELECTED_AREA);
const newValue = (0,external_wp_richText_namespaceObject.remove)(convertedValue, newOffset, newOffset + 1);
const newHtml = (0,external_wp_richText_namespaceObject.toHTMLString)({
value: newValue,
...mapRichTextSettings(blockAType.attributes[newAttributeKey])
});
updatedAttributes[newAttributeKey] = newHtml;
dispatch.selectionChange(blockA.clientId, newAttributeKey, newOffset, newOffset);
}
dispatch.replaceBlocks([blockA.clientId, blockB.clientId], [{ ...blockA,
attributes: { ...blockA.attributes,
...updatedAttributes
}
}, ...blocksWithTheSameType.slice(1)], 0 // If we don't pass the `indexToSelect` it will default to the last block.
);
};
/**
* Yields action objects used in signalling that the blocks corresponding to
* the set of specified client IDs are to be removed.
*
* @param {string|string[]} clientIds Client IDs of blocks to remove.
* @param {boolean} selectPrevious True if the previous block
* or the immediate parent
* (if no previous block exists)
* should be selected
* when a block is removed.
*/
const removeBlocks = function (clientIds) {
let selectPrevious = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
return _ref17 => {
let {
select,
dispatch
} = _ref17;
if (!clientIds || !clientIds.length) {
return;
}
clientIds = castArray(clientIds);
const rootClientId = select.getBlockRootClientId(clientIds[0]);
const canRemoveBlocks = select.canRemoveBlocks(clientIds, rootClientId);
if (!canRemoveBlocks) {
return;
}
if (selectPrevious) {
dispatch.selectPreviousBlock(clientIds[0], selectPrevious);
}
dispatch({
type: 'REMOVE_BLOCKS',
clientIds
}); // To avoid a focus loss when removing the last block, assure there is
// always a default block if the last of the blocks have been removed.
dispatch(ensureDefaultBlock());
};
};
/**
* Returns an action object used in signalling that the block with the
* specified client ID is to be removed.
*
* @param {string} clientId Client ID of block to remove.
* @param {boolean} selectPrevious True if the previous block should be
* selected when a block is removed.
*
* @return {Object} Action object.
*/
function removeBlock(clientId, selectPrevious) {
return removeBlocks([clientId], selectPrevious);
}
/* eslint-disable jsdoc/valid-types */
/**
* Returns an action object used in signalling that the inner blocks with the
* specified client ID should be replaced.
*
* @param {string} rootClientId Client ID of the block whose InnerBlocks will re replaced.
* @param {Object[]} blocks Block objects to insert as new InnerBlocks
* @param {?boolean} updateSelection If true block selection will be updated. If false, block selection will not change. Defaults to false.
* @param {0|-1|null} initialPosition Initial block position.
* @return {Object} Action object.
*/
function replaceInnerBlocks(rootClientId, blocks) {
let updateSelection = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
let initialPosition = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
/* eslint-enable jsdoc/valid-types */
return {
type: 'REPLACE_INNER_BLOCKS',
rootClientId,
blocks,
updateSelection,
initialPosition: updateSelection ? initialPosition : null,
time: Date.now()
};
}
/**
* Returns an action object used to toggle the block editing mode between
* visual and HTML modes.
*
* @param {string} clientId Block client ID.
*
* @return {Object} Action object.
*/
function toggleBlockMode(clientId) {
return {
type: 'TOGGLE_BLOCK_MODE',
clientId
};
}
/**
* Returns an action object used in signalling that the user has begun to type.
*
* @return {Object} Action object.
*/
function startTyping() {
return {
type: 'START_TYPING'
};
}
/**
* Returns an action object used in signalling that the user has stopped typing.
*
* @return {Object} Action object.
*/
function stopTyping() {
return {
type: 'STOP_TYPING'
};
}
/**
* Returns an action object used in signalling that the user has begun to drag blocks.
*
* @param {string[]} clientIds An array of client ids being dragged
*
* @return {Object} Action object.
*/
function startDraggingBlocks() {
let clientIds = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
return {
type: 'START_DRAGGING_BLOCKS',
clientIds
};
}
/**
* Returns an action object used in signalling that the user has stopped dragging blocks.
*
* @return {Object} Action object.
*/
function stopDraggingBlocks() {
return {
type: 'STOP_DRAGGING_BLOCKS'
};
}
/**
* Returns an action object used in signalling that the caret has entered formatted text.
*
* @deprecated
*
* @return {Object} Action object.
*/
function enterFormattedText() {
external_wp_deprecated_default()('wp.data.dispatch( "core/block-editor" ).enterFormattedText', {
since: '6.1',
version: '6.3'
});
return {
type: 'DO_NOTHING'
};
}
/**
* Returns an action object used in signalling that the user caret has exited formatted text.
*
* @deprecated
*
* @return {Object} Action object.
*/
function exitFormattedText() {
external_wp_deprecated_default()('wp.data.dispatch( "core/block-editor" ).exitFormattedText', {
since: '6.1',
version: '6.3'
});
return {
type: 'DO_NOTHING'
};
}
/**
* Action that changes the position of the user caret.
*
* @param {string|WPSelection} clientId The selected block client ID.
* @param {string} attributeKey The selected block attribute key.
* @param {number} startOffset The start offset.
* @param {number} endOffset The end offset.
*
* @return {Object} Action object.
*/
function selectionChange(clientId, attributeKey, startOffset, endOffset) {
if (typeof clientId === 'string') {
return {
type: 'SELECTION_CHANGE',
clientId,
attributeKey,
startOffset,
endOffset
};
}
return {
type: 'SELECTION_CHANGE',
...clientId
};
}
/**
* Action that adds a new block of the default type to the block list.
*
* @param {?Object} attributes Optional attributes of the block to assign.
* @param {?string} rootClientId Optional root client ID of block list on which
* to append.
* @param {?number} index Optional index where to insert the default block.
*/
const insertDefaultBlock = (attributes, rootClientId, index) => _ref18 => {
let {
dispatch
} = _ref18;
// Abort if there is no default block type (if it has been unregistered).
const defaultBlockName = (0,external_wp_blocks_namespaceObject.getDefaultBlockName)();
if (!defaultBlockName) {
return;
}
const block = (0,external_wp_blocks_namespaceObject.createBlock)(defaultBlockName, attributes);
return dispatch.insertBlock(block, index, rootClientId);
};
/**
* Action that changes the nested settings of a given block.
*
* @param {string} clientId Client ID of the block whose nested setting are
* being received.
* @param {Object} settings Object with the new settings for the nested block.
*
* @return {Object} Action object
*/
function updateBlockListSettings(clientId, settings) {
return {
type: 'UPDATE_BLOCK_LIST_SETTINGS',
clientId,
settings
};
}
/**
* Action that updates the block editor settings.
*
* @param {Object} settings Updated settings
*
* @return {Object} Action object
*/
function updateSettings(settings) {
return __experimentalUpdateSettings(settings, true);
}
/**
* Action that signals that a temporary reusable block has been saved
* in order to switch its temporary id with the real id.
*
* @param {string} id Reusable block's id.
* @param {string} updatedId Updated block's id.
*
* @return {Object} Action object.
*/
function __unstableSaveReusableBlock(id, updatedId) {
return {
type: 'SAVE_REUSABLE_BLOCK_SUCCESS',
id,
updatedId
};
}
/**
* Action that marks the last block change explicitly as persistent.
*
* @return {Object} Action object.
*/
function __unstableMarkLastChangeAsPersistent() {
return {
type: 'MARK_LAST_CHANGE_AS_PERSISTENT'
};
}
/**
* Action that signals that the next block change should be marked explicitly as not persistent.
*
* @return {Object} Action object.
*/
function __unstableMarkNextChangeAsNotPersistent() {
return {
type: 'MARK_NEXT_CHANGE_AS_NOT_PERSISTENT'
};
}
/**
* Action that marks the last block change as an automatic change, meaning it was not
* performed by the user, and can be undone using the `Escape` and `Backspace` keys.
* This action must be called after the change was made, and any actions that are a
* consequence of it, so it is recommended to be called at the next idle period to ensure all
* selection changes have been recorded.
*/
const __unstableMarkAutomaticChange = () => _ref19 => {
let {
dispatch
} = _ref19;
dispatch({
type: 'MARK_AUTOMATIC_CHANGE'
});
const {
requestIdleCallback = cb => setTimeout(cb, 100)
} = window;
requestIdleCallback(() => {
dispatch({
type: 'MARK_AUTOMATIC_CHANGE_FINAL'
});
});
};
/**
* Action that enables or disables the navigation mode.
*
* @param {boolean} isNavigationMode Enable/Disable navigation mode.
*/
const setNavigationMode = function () {
let isNavigationMode = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
return _ref20 => {
let {
dispatch
} = _ref20;
dispatch.__unstableSetEditorMode(isNavigationMode ? 'navigation' : 'edit');
};
};
/**
* Action that sets the editor mode
*
* @param {string} mode Editor mode
*/
const __unstableSetEditorMode = mode => _ref21 => {
let {
dispatch,
select
} = _ref21;
// When switching to zoom-out mode, we need to select the root block
if (mode === 'zoom-out') {
const firstSelectedClientId = select.getBlockSelectionStart();
if (firstSelectedClientId) {
dispatch.selectBlock(select.getBlockHierarchyRootClientId(firstSelectedClientId));
}
}
dispatch({
type: 'SET_EDITOR_MODE',
mode
});
if (mode === 'navigation') {
(0,external_wp_a11y_namespaceObject.speak)((0,external_wp_i18n_namespaceObject.__)('You are currently in navigation mode. Navigate blocks using the Tab key and Arrow keys. Use Left and Right Arrow keys to move between nesting levels. To exit navigation mode and edit the selected block, press Enter.'));
} else if (mode === 'edit') {
(0,external_wp_a11y_namespaceObject.speak)((0,external_wp_i18n_namespaceObject.__)('You are currently in edit mode. To return to the navigation mode, press Escape.'));
} else if (mode === 'zoom-out') {
(0,external_wp_a11y_namespaceObject.speak)((0,external_wp_i18n_namespaceObject.__)('You are currently in zoom-out mode.'));
}
};
/**
* Action that enables or disables the block moving mode.
*
* @param {string|null} hasBlockMovingClientId Enable/Disable block moving mode.
*/
const setBlockMovingClientId = function () {
let hasBlockMovingClientId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
return _ref22 => {
let {
dispatch
} = _ref22;
dispatch({
type: 'SET_BLOCK_MOVING_MODE',
hasBlockMovingClientId
});
if (hasBlockMovingClientId) {
(0,external_wp_a11y_namespaceObject.speak)((0,external_wp_i18n_namespaceObject.__)('Use the Tab key and Arrow keys to choose new block location. Use Left and Right Arrow keys to move between nesting levels. Once location is selected press Enter or Space to move the block.'));
}
};
};
/**
* Action that duplicates a list of blocks.
*
* @param {string[]} clientIds
* @param {boolean} updateSelection
*/
const duplicateBlocks = function (clientIds) {
let updateSelection = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
return _ref23 => {
let {
select,
dispatch
} = _ref23;
if (!clientIds || !clientIds.length) {
return;
} // Return early if blocks don't exist.
const blocks = select.getBlocksByClientId(clientIds);
if (blocks.some(block => !block)) {
return;
} // Return early if blocks don't support multiple usage.
const blockNames = blocks.map(block => block.name);
if (blockNames.some(blockName => !(0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockName, 'multiple', true))) {
return;
}
const rootClientId = select.getBlockRootClientId(clientIds[0]);
const clientIdsArray = castArray(clientIds);
const lastSelectedIndex = select.getBlockIndex(clientIdsArray[clientIdsArray.length - 1]);
const clonedBlocks = blocks.map(block => (0,external_wp_blocks_namespaceObject.__experimentalCloneSanitizedBlock)(block));
dispatch.insertBlocks(clonedBlocks, lastSelectedIndex + 1, rootClientId, updateSelection);
if (clonedBlocks.length > 1 && updateSelection) {
dispatch.multiSelect(clonedBlocks[0].clientId, clonedBlocks[clonedBlocks.length - 1].clientId);
}
return clonedBlocks.map(block => block.clientId);
};
};
/**
* Action that inserts an empty block before a given block.
*
* @param {string} clientId
*/
const insertBeforeBlock = clientId => _ref24 => {
let {
select,
dispatch
} = _ref24;
if (!clientId) {
return;
}
const rootClientId = select.getBlockRootClientId(clientId);
const isLocked = select.getTemplateLock(rootClientId);
if (isLocked) {
return;
}
const firstSelectedIndex = select.getBlockIndex(clientId);
return dispatch.insertDefaultBlock({}, rootClientId, firstSelectedIndex);
};
/**
* Action that inserts an empty block after a given block.
*
* @param {string} clientId
*/
const insertAfterBlock = clientId => _ref25 => {
let {
select,
dispatch
} = _ref25;
if (!clientId) {
return;
}
const rootClientId = select.getBlockRootClientId(clientId);
const isLocked = select.getTemplateLock(rootClientId);
if (isLocked) {
return;
}
const firstSelectedIndex = select.getBlockIndex(clientId);
return dispatch.insertDefaultBlock({}, rootClientId, firstSelectedIndex + 1);
};
/**
* Action that toggles the highlighted block state.
*
* @param {string} clientId The block's clientId.
* @param {boolean} isHighlighted The highlight state.
*/
function toggleBlockHighlight(clientId, isHighlighted) {
return {
type: 'TOGGLE_BLOCK_HIGHLIGHT',
clientId,
isHighlighted
};
}
/**
* Action that "flashes" the block with a given `clientId` by rhythmically highlighting it.
*
* @param {string} clientId Target block client ID.
*/
const flashBlock = clientId => async _ref26 => {
let {
dispatch
} = _ref26;
dispatch(toggleBlockHighlight(clientId, true));
await new Promise(resolve => setTimeout(resolve, 150));
dispatch(toggleBlockHighlight(clientId, false));
};
/**
* Action that sets whether a block has controlled inner blocks.
*
* @param {string} clientId The block's clientId.
* @param {boolean} hasControlledInnerBlocks True if the block's inner blocks are controlled.
*/
function setHasControlledInnerBlocks(clientId, hasControlledInnerBlocks) {
return {
type: 'SET_HAS_CONTROLLED_INNER_BLOCKS',
hasControlledInnerBlocks,
clientId
};
}
/**
* Action that sets whether given blocks are visible on the canvas.
*
* @param {Record<string,boolean>} updates For each block's clientId, its new visibility setting.
*/
function setBlockVisibility(updates) {
return {
type: 'SET_BLOCK_VISIBILITY',
updates
};
}
/**
* Action that sets whether a block is being temporaritly edited as blocks.
*
* DO-NOT-USE in production.
* This action is created for internal/experimental only usage and may be
* removed anytime without any warning, causing breakage on any plugin or theme invoking it.
*
* @param {?string} temporarilyEditingAsBlocks The block's clientId being temporaritly edited as blocks.
*/
function __unstableSetTemporarilyEditingAsBlocks(temporarilyEditingAsBlocks) {
return {
type: 'SET_TEMPORARILY_EDITING_AS_BLOCKS',
temporarilyEditingAsBlocks
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/store/constants.js
const STORE_NAME = 'core/block-editor';
;// CONCATENATED MODULE: external ["wp","privateApis"]
var external_wp_privateApis_namespaceObject = window["wp"]["privateApis"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/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/block-editor');
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/store/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Block editor data store configuration.
*
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/data/README.md#registerStore
*/
const storeConfig = {
reducer: reducer,
selectors: selectors_namespaceObject,
actions: actions_namespaceObject
};
/**
* Store definition for the block editor namespace.
*
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/data/README.md#createReduxStore
*/
const store = (0,external_wp_data_namespaceObject.createReduxStore)(STORE_NAME, { ...storeConfig,
persist: ['preferences']
}); // We will be able to use the `register` function once we switch
// the "preferences" persistence to use the new preferences package.
const registeredStore = (0,external_wp_data_namespaceObject.registerStore)(STORE_NAME, { ...storeConfig,
persist: ['preferences']
});
unlock(registeredStore).registerPrivateActions(private_actions_namespaceObject);
unlock(registeredStore).registerPrivateSelectors(private_selectors_namespaceObject);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-edit/context.js
/**
* WordPress dependencies
*/
const DEFAULT_BLOCK_EDIT_CONTEXT = {
name: '',
isSelected: false
};
const Context = (0,external_wp_element_namespaceObject.createContext)(DEFAULT_BLOCK_EDIT_CONTEXT);
const {
Provider
} = Context;
/**
* A hook that returns the block edit context.
*
* @return {Object} Block edit context
*/
function useBlockEditContext() {
return (0,external_wp_element_namespaceObject.useContext)(Context);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/use-display-block-controls/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useDisplayBlockControls() {
const {
isSelected,
clientId,
name
} = useBlockEditContext();
return (0,external_wp_data_namespaceObject.useSelect)(select => {
if (isSelected) {
return true;
}
const {
getBlockName,
isFirstMultiSelectedBlock,
getMultiSelectedBlockClientIds
} = select(store);
if (isFirstMultiSelectedBlock(clientId)) {
return getMultiSelectedBlockClientIds().every(id => getBlockName(id) === name);
}
return false;
}, [clientId, isSelected, name]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-controls/hook.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useBlockControlsFill(group, shareWithChildBlocks) {
const isDisplayed = useDisplayBlockControls();
const {
clientId
} = useBlockEditContext();
const isParentDisplayed = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlockName,
hasSelectedInnerBlock
} = select(store);
const {
hasBlockSupport
} = select(external_wp_blocks_namespaceObject.store);
return shareWithChildBlocks && hasBlockSupport(getBlockName(clientId), '__experimentalExposeControlsToChildren', false) && hasSelectedInnerBlock(clientId);
}, [shareWithChildBlocks, clientId]);
if (isDisplayed) {
var _groups$group;
return (_groups$group = block_controls_groups[group]) === null || _groups$group === void 0 ? void 0 : _groups$group.Fill;
}
if (isParentDisplayed) {
return block_controls_groups.parent.Fill;
}
return null;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-controls/fill.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function BlockControlsFill(_ref) {
let {
group = 'default',
controls,
children,
__experimentalShareWithChildBlocks = false
} = _ref;
const Fill = useBlockControlsFill(group, __experimentalShareWithChildBlocks);
if (!Fill) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalStyleProvider, {
document: document
}, (0,external_wp_element_namespaceObject.createElement)(Fill, null, fillProps => {
// Children passed to BlockControlsFill will not have access to any
// React Context whose Provider is part of the BlockControlsSlot tree.
// So we re-create the Provider in this subtree.
const value = !(0,external_lodash_namespaceObject.isEmpty)(fillProps) ? fillProps : null;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToolbarContext.Provider, {
value: value
}, group === 'default' && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarGroup, {
controls: controls
}), children);
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-controls/slot.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function BlockControlsSlot(_ref) {
let {
group = 'default',
...props
} = _ref;
const accessibleToolbarState = (0,external_wp_element_namespaceObject.useContext)(external_wp_components_namespaceObject.__experimentalToolbarContext);
const Slot = block_controls_groups[group].Slot;
const fills = (0,external_wp_components_namespaceObject.__experimentalUseSlotFills)(Slot.__unstableName);
const hasFills = Boolean(fills && fills.length);
if (!hasFills) {
return null;
}
if (group === 'default') {
return (0,external_wp_element_namespaceObject.createElement)(Slot, _extends({}, props, {
bubblesVirtually: true,
fillProps: accessibleToolbarState
}));
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarGroup, null, (0,external_wp_element_namespaceObject.createElement)(Slot, _extends({}, props, {
bubblesVirtually: true,
fillProps: accessibleToolbarState
})));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-controls/index.js
/**
* Internal dependencies
*/
const BlockControls = BlockControlsFill;
BlockControls.Slot = BlockControlsSlot; // This is just here for backward compatibility.
const BlockFormatControls = props => {
return (0,external_wp_element_namespaceObject.createElement)(BlockControlsFill, _extends({
group: "inline"
}, props));
};
BlockFormatControls.Slot = props => {
return (0,external_wp_element_namespaceObject.createElement)(BlockControlsSlot, _extends({
group: "inline"
}, props));
};
/* harmony default export */ var block_controls = (BlockControls);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/justify-left.js
/**
* WordPress dependencies
*/
const justifyLeft = (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: "M9 9v6h11V9H9zM4 20h1.5V4H4v16z"
}));
/* harmony default export */ var justify_left = (justifyLeft);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/justify-center.js
/**
* WordPress dependencies
*/
const justifyCenter = (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: "M20 9h-7.2V4h-1.6v5H4v6h7.2v5h1.6v-5H20z"
}));
/* harmony default export */ var justify_center = (justifyCenter);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/justify-right.js
/**
* WordPress dependencies
*/
const justifyRight = (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: "M4 15h11V9H4v6zM18.5 4v16H20V4h-1.5z"
}));
/* harmony default export */ var justify_right = (justifyRight);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/justify-space-between.js
/**
* WordPress dependencies
*/
const justifySpaceBetween = (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: "M9 15h6V9H9v6zm-5 5h1.5V4H4v16zM18.5 4v16H20V4h-1.5z"
}));
/* harmony default export */ var justify_space_between = (justifySpaceBetween);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/justify-stretch.js
/**
* WordPress dependencies
*/
const justifyStretch = (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: "M4 4H5.5V20H4V4ZM7 10L17 10V14L7 14V10ZM20 4H18.5V20H20V4Z"
}));
/* harmony default export */ var justify_stretch = (justifyStretch);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/arrow-right.js
/**
* WordPress dependencies
*/
const arrowRight = (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: "m14.5 6.5-1 1 3.7 3.7H4v1.6h13.2l-3.7 3.7 1 1 5.6-5.5z"
}));
/* harmony default export */ var arrow_right = (arrowRight);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/arrow-down.js
/**
* WordPress dependencies
*/
const arrowDown = (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: "m16.5 13.5-3.7 3.7V4h-1.5v13.2l-3.8-3.7-1 1 5.5 5.6 5.5-5.6z"
}));
/* harmony default export */ var arrow_down = (arrowDown);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/layouts/utils.js
/**
* WordPress dependencies
*/
/**
* Utility to generate the proper CSS selector for layout styles.
*
* @param {string} selectors CSS selector, also supports multiple comma-separated selectors.
* @param {string} append The string to append.
*
* @return {string} - CSS selector.
*/
function appendSelectors(selectors) {
let append = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
// Ideally we shouldn't need the `.editor-styles-wrapper` increased specificity here
// The problem though is that we have a `.editor-styles-wrapper p { margin: reset; }` style
// it's used to reset the default margin added by wp-admin to paragraphs
// so we need this to be higher speficity otherwise, it won't be applied to paragraphs inside containers
// When the post editor is fully iframed, this extra classname could be removed.
return selectors.split(',').map(subselector => `.editor-styles-wrapper ${subselector}${append ? ` ${append}` : ''}`).join(',');
}
/**
* Get generated blockGap CSS rules based on layout definitions provided in theme.json
* Falsy values in the layout definition's spacingStyles rules will be swapped out
* with the provided `blockGapValue`.
*
* @param {string} selector The CSS selector to target for the generated rules.
* @param {Object} layoutDefinitions Layout definitions object from theme.json.
* @param {string} layoutType The layout type (e.g. `default` or `flex`).
* @param {string} blockGapValue The current blockGap value to be applied.
* @return {string} The generated CSS rules.
*/
function getBlockGapCSS(selector, layoutDefinitions, layoutType, blockGapValue) {
var _layoutDefinitions$la, _layoutDefinitions$la2;
let output = '';
if (layoutDefinitions !== null && layoutDefinitions !== void 0 && (_layoutDefinitions$la = layoutDefinitions[layoutType]) !== null && _layoutDefinitions$la !== void 0 && (_layoutDefinitions$la2 = _layoutDefinitions$la.spacingStyles) !== null && _layoutDefinitions$la2 !== void 0 && _layoutDefinitions$la2.length && blockGapValue) {
layoutDefinitions[layoutType].spacingStyles.forEach(gapStyle => {
output += `${appendSelectors(selector, gapStyle.selector.trim())} { `;
output += Object.entries(gapStyle.rules).map(_ref => {
let [cssProperty, value] = _ref;
return `${cssProperty}: ${value ? value : blockGapValue}`;
}).join('; ');
output += '; }';
});
}
return output;
}
/**
* Helper method to assign contextual info to clarify
* alignment settings.
*
* Besides checking if `contentSize` and `wideSize` have a
* value, we now show this information only if their values
* are not a `css var`. This needs to change when parsing
* css variables land.
*
* @see https://github.com/WordPress/gutenberg/pull/34710#issuecomment-918000752
*
* @param {Object} layout The layout object.
* @return {Object} An object with contextual info per alignment.
*/
function getAlignmentsInfo(layout) {
const {
contentSize,
wideSize,
type = 'default'
} = layout;
const alignmentInfo = {};
const sizeRegex = /^(?!0)\d+(px|em|rem|vw|vh|%)?$/i;
if (sizeRegex.test(contentSize) && type === 'constrained') {
// translators: %s: container size (i.e. 600px etc)
alignmentInfo.none = (0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('Max %s wide'), contentSize);
}
if (sizeRegex.test(wideSize)) {
// translators: %s: container size (i.e. 600px etc)
alignmentInfo.wide = (0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('Max %s wide'), wideSize);
}
return alignmentInfo;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/provider/block-refs-provider.js
/**
* WordPress dependencies
*/
const BlockRefs = (0,external_wp_element_namespaceObject.createContext)({
refs: new Map(),
callbacks: new Map()
});
function BlockRefsProvider(_ref) {
let {
children
} = _ref;
const value = (0,external_wp_element_namespaceObject.useMemo)(() => ({
refs: new Map(),
callbacks: new Map()
}), []);
return (0,external_wp_element_namespaceObject.createElement)(BlockRefs.Provider, {
value: value
}, children);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-list/use-block-props/use-block-refs.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/** @typedef {import('@wordpress/element').RefCallback} RefCallback */
/** @typedef {import('@wordpress/element').RefObject} RefObject */
/**
* Provides a ref to the BlockRefs context.
*
* @param {string} clientId The client ID of the element ref.
*
* @return {RefCallback} Ref callback.
*/
function useBlockRefProvider(clientId) {
const {
refs,
callbacks
} = (0,external_wp_element_namespaceObject.useContext)(BlockRefs);
const ref = (0,external_wp_element_namespaceObject.useRef)();
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
refs.set(ref, clientId);
return () => {
refs.delete(ref);
};
}, [clientId]);
return (0,external_wp_compose_namespaceObject.useRefEffect)(element => {
// Update the ref in the provider.
ref.current = element; // Call any update functions.
callbacks.forEach((id, setElement) => {
if (clientId === id) {
setElement(element);
}
});
}, [clientId]);
}
/**
* Gets a ref pointing to the current block element. Continues to return a
* stable ref even if the block client ID changes.
*
* @param {string} clientId The client ID to get a ref for.
*
* @return {RefObject} A ref containing the element.
*/
function useBlockRef(clientId) {
const {
refs
} = (0,external_wp_element_namespaceObject.useContext)(BlockRefs);
const freshClientId = (0,external_wp_element_namespaceObject.useRef)();
freshClientId.current = clientId; // Always return an object, even if no ref exists for a given client ID, so
// that `current` works at a later point.
return (0,external_wp_element_namespaceObject.useMemo)(() => ({
get current() {
let element = null; // Multiple refs may be created for a single block. Find the
// first that has an element set.
for (const [ref, id] of refs.entries()) {
if (id === freshClientId.current && ref.current) {
element = ref.current;
}
}
return element;
}
}), []);
}
/**
* Return the element for a given client ID. Updates whenever the element
* changes, becomes available, or disappears.
*
* @param {string} clientId The client ID to an element for.
*
* @return {Element|null} The block's wrapper element.
*/
function useBlockElement(clientId) {
const {
callbacks
} = (0,external_wp_element_namespaceObject.useContext)(BlockRefs);
const ref = useBlockRef(clientId);
const [element, setElement] = (0,external_wp_element_namespaceObject.useState)(null);
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
if (!clientId) {
return;
}
callbacks.set(setElement, clientId);
return () => {
callbacks.delete(setElement);
};
}, [clientId]);
return ref.current || element;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/spacing-sizes-control/utils.js
/**
* WordPress dependencies
*/
/**
* Checks is given value is a spacing preset.
*
* @param {string} value Value to check
*
* @return {boolean} Return true if value is string in format var:preset|spacing|.
*/
function isValueSpacingPreset(value) {
if (!(value !== null && value !== void 0 && value.includes)) {
return false;
}
return value === '0' || value.includes('var:preset|spacing|');
}
/**
* Converts a spacing preset into a custom value.
*
* @param {string} value Value to convert
* @param {Array} spacingSizes Array of the current spacing preset objects
*
* @return {string} Mapping of the spacing preset to its equivalent custom value.
*/
function getCustomValueFromPreset(value, spacingSizes) {
if (!isValueSpacingPreset(value)) {
return value;
}
const slug = getSpacingPresetSlug(value);
const spacingSize = spacingSizes.find(size => String(size.slug) === slug);
return spacingSize === null || spacingSize === void 0 ? void 0 : spacingSize.size;
}
/**
* Converts a custom value to preset value if one can be found.
*
* Returns value as-is if no match is found.
*
* @param {string} value Value to convert
* @param {Array} spacingSizes Array of the current spacing preset objects
*
* @return {string} The preset value if it can be found.
*/
function getPresetValueFromCustomValue(value, spacingSizes) {
// Return value as-is if it is already a preset;
if (isValueSpacingPreset(value)) {
return value;
}
const spacingMatch = spacingSizes.find(size => String(size.size) === String(value));
if (spacingMatch !== null && spacingMatch !== void 0 && spacingMatch.slug) {
return `var:preset|spacing|${spacingMatch.slug}`;
}
return value;
}
/**
* Converts a spacing preset into a custom value.
*
* @param {string} value Value to convert.
*
* @return {string | undefined} CSS var string for given spacing preset value.
*/
function getSpacingPresetCssVar(value) {
if (!value) {
return;
}
const slug = value.match(/var:preset\|spacing\|(.+)/);
if (!slug) {
return value;
}
return `var(--wp--preset--spacing--${slug[1]})`;
}
/**
* Returns the slug section of the given spacing preset string.
*
* @param {string} value Value to extract slug from.
*
* @return {string|undefined} The int value of the slug from given spacing preset.
*/
function getSpacingPresetSlug(value) {
if (!value) {
return;
}
if (value === '0' || value === 'default') {
return value;
}
const slug = value.match(/var:preset\|spacing\|(.+)/);
return slug ? slug[1] : undefined;
}
/**
* Converts spacing preset value into a Range component value .
*
* @param {string} presetValue Value to convert to Range value.
* @param {Array} spacingSizes Array of current spacing preset value objects.
*
* @return {number} The int value for use in Range control.
*/
function getSliderValueFromPreset(presetValue, spacingSizes) {
if (presetValue === undefined) {
return 0;
}
const slug = parseFloat(presetValue, 10) === 0 ? '0' : getSpacingPresetSlug(presetValue);
const sliderValue = spacingSizes.findIndex(spacingSize => {
return String(spacingSize.slug) === slug;
}); // Returning NaN rather than undefined as undefined makes range control thumb sit in center
return sliderValue !== -1 ? sliderValue : NaN;
}
const LABELS = {
all: (0,external_wp_i18n_namespaceObject.__)('All sides'),
top: (0,external_wp_i18n_namespaceObject.__)('Top'),
bottom: (0,external_wp_i18n_namespaceObject.__)('Bottom'),
left: (0,external_wp_i18n_namespaceObject.__)('Left'),
right: (0,external_wp_i18n_namespaceObject.__)('Right'),
mixed: (0,external_wp_i18n_namespaceObject.__)('Mixed'),
vertical: (0,external_wp_i18n_namespaceObject.__)('Vertical'),
horizontal: (0,external_wp_i18n_namespaceObject.__)('Horizontal')
};
const DEFAULT_VALUES = {
top: undefined,
right: undefined,
bottom: undefined,
left: undefined
};
const ALL_SIDES = ['top', 'right', 'bottom', 'left'];
/**
* Gets an items with the most occurrence within an array
* https://stackoverflow.com/a/20762713
*
* @param {Array<any>} arr Array of items to check.
* @return {any} The item with the most occurrences.
*/
function mode(arr) {
return arr.sort((a, b) => arr.filter(v => v === a).length - arr.filter(v => v === b).length).pop();
}
/**
* Gets the 'all' input value from values data.
*
* @param {Object} values Box spacing values
*
* @return {string} The most common value from all sides of box.
*/
function getAllRawValue() {
let values = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return mode(Object.values(values));
}
/**
* Checks to determine if values are mixed.
*
* @param {Object} values Box values.
* @param {Array} sides Sides that values relate to.
*
* @return {boolean} Whether values are mixed.
*/
function isValuesMixed() {
let values = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let sides = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ALL_SIDES;
return Object.values(values).length >= 1 && Object.values(values).length < sides.length || new Set(Object.values(values)).size > 1;
}
/**
* Checks to determine if values are defined.
*
* @param {Object} values Box values.
*
* @return {boolean} Whether values are defined.
*/
function isValuesDefined(values) {
if (values === undefined || values === null) {
return false;
}
return Object.values(values).filter(value => !!value).length > 0;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/settings.js
/**
* WordPress dependencies
*/
const settings_settings = (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: "M14.5 13.8c-1.1 0-2.1.7-2.4 1.8H4V17h8.1c.3 1 1.3 1.8 2.4 1.8s2.1-.7 2.4-1.8H20v-1.5h-3.1c-.3-1-1.3-1.7-2.4-1.7zM11.9 7c-.3-1-1.3-1.8-2.4-1.8S7.4 6 7.1 7H4v1.5h3.1c.3 1 1.3 1.8 2.4 1.8s2.1-.7 2.4-1.8H20V7h-8.1z"
}));
/* harmony default export */ var library_settings = (settings_settings);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/use-setting/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const blockedPaths = ['color', 'border', 'dimensions', 'typography', 'spacing'];
const deprecatedFlags = {
'color.palette': settings => settings.colors,
'color.gradients': settings => settings.gradients,
'color.custom': settings => settings.disableCustomColors === undefined ? undefined : !settings.disableCustomColors,
'color.customGradient': settings => settings.disableCustomGradients === undefined ? undefined : !settings.disableCustomGradients,
'typography.fontSizes': settings => settings.fontSizes,
'typography.customFontSize': settings => settings.disableCustomFontSizes === undefined ? undefined : !settings.disableCustomFontSizes,
'typography.lineHeight': settings => settings.enableCustomLineHeight,
'spacing.units': settings => {
if (settings.enableCustomUnits === undefined) {
return;
}
if (settings.enableCustomUnits === true) {
return ['px', 'em', 'rem', 'vh', 'vw', '%'];
}
return settings.enableCustomUnits;
},
'spacing.padding': settings => settings.enableCustomSpacing
};
const prefixedFlags = {
/*
* These were only available in the plugin
* and can be removed when the minimum WordPress version
* for the plugin is 5.9.
*/
'border.customColor': 'border.color',
'border.customStyle': 'border.style',
'border.customWidth': 'border.width',
'typography.customFontStyle': 'typography.fontStyle',
'typography.customFontWeight': 'typography.fontWeight',
'typography.customLetterSpacing': 'typography.letterSpacing',
'typography.customTextDecorations': 'typography.textDecoration',
'typography.customTextTransforms': 'typography.textTransform',
/*
* These were part of WordPress 5.8 and we need to keep them.
*/
'border.customRadius': 'border.radius',
'spacing.customMargin': 'spacing.margin',
'spacing.customPadding': 'spacing.padding',
'typography.customLineHeight': 'typography.lineHeight'
};
/**
* Remove `custom` prefixes for flags that did not land in 5.8.
*
* This provides continued support for `custom` prefixed properties. It will
* be removed once third party devs have had sufficient time to update themes,
* plugins, etc.
*
* @see https://github.com/WordPress/gutenberg/pull/34485
*
* @param {string} path Path to desired value in settings.
* @return {string} The value for defined setting.
*/
const removeCustomPrefixes = path => {
return prefixedFlags[path] || path;
};
/**
* Hook that retrieves the given setting for the block instance in use.
*
* It looks up the settings first in the block instance hierarchy.
* If none is found, it'll look it up in the block editor store.
*
* @param {string} path The path to the setting.
* @return {any} Returns the value defined for the setting.
* @example
* ```js
* const isEnabled = useSetting( 'typography.dropCap' );
* ```
*/
function useSetting(path) {
const {
name: blockName,
clientId
} = useBlockEditContext();
return (0,external_wp_data_namespaceObject.useSelect)(select => {
if (blockedPaths.includes(path)) {
// eslint-disable-next-line no-console
console.warn('Top level useSetting paths are disabled. Please use a subpath to query the information needed.');
return undefined;
} // 0. Allow third parties to filter the block's settings at runtime.
let result = (0,external_wp_hooks_namespaceObject.applyFilters)('blockEditor.useSetting.before', undefined, path, clientId, blockName);
if (undefined !== result) {
return result;
}
const normalizedPath = removeCustomPrefixes(path); // 1. Take settings from the block instance or its ancestors.
// Start from the current block and work our way up the ancestors.
const candidates = [clientId, ...select(store).getBlockParents(clientId,
/* ascending */
true)];
for (const candidateClientId of candidates) {
const candidateBlockName = select(store).getBlockName(candidateClientId);
if ((0,external_wp_blocks_namespaceObject.hasBlockSupport)(candidateBlockName, '__experimentalSettings', false)) {
var _get;
const candidateAtts = select(store).getBlockAttributes(candidateClientId);
result = (_get = (0,external_lodash_namespaceObject.get)(candidateAtts, `settings.blocks.${blockName}.${normalizedPath}`)) !== null && _get !== void 0 ? _get : (0,external_lodash_namespaceObject.get)(candidateAtts, `settings.${normalizedPath}`);
if (result !== undefined) {
// Stop the search for more distant ancestors and move on.
break;
}
}
} // 2. Fall back to the settings from the block editor store (__experimentalFeatures).
const settings = select(store).getSettings();
if (result === undefined) {
var _get2;
const defaultsPath = `__experimentalFeatures.${normalizedPath}`;
const blockPath = `__experimentalFeatures.blocks.${blockName}.${normalizedPath}`;
result = (_get2 = (0,external_lodash_namespaceObject.get)(settings, blockPath)) !== null && _get2 !== void 0 ? _get2 : (0,external_lodash_namespaceObject.get)(settings, defaultsPath);
} // Return if the setting was found in either the block instance or the store.
if (result !== undefined) {
if (external_wp_blocks_namespaceObject.__EXPERIMENTAL_PATHS_WITH_MERGE[normalizedPath]) {
var _ref, _result$custom;
return (_ref = (_result$custom = result.custom) !== null && _result$custom !== void 0 ? _result$custom : result.theme) !== null && _ref !== void 0 ? _ref : result.default;
}
return result;
} // 3. Otherwise, use deprecated settings.
const deprecatedSettingsValue = deprecatedFlags[normalizedPath] ? deprecatedFlags[normalizedPath](settings) : undefined;
if (deprecatedSettingsValue !== undefined) {
return deprecatedSettingsValue;
} // 4. Fallback for typography.dropCap:
// This is only necessary to support typography.dropCap.
// when __experimentalFeatures are not present (core without plugin).
// To remove when __experimentalFeatures are ported to core.
return normalizedPath === 'typography.dropCap' ? true : undefined;
}, [blockName, clientId, path]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/spacing-sizes-control/spacing-input-control.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const CUSTOM_VALUE_SETTINGS = {
px: {
max: 300,
steps: 1
},
'%': {
max: 100,
steps: 1
},
vw: {
max: 100,
steps: 1
},
vh: {
max: 100,
steps: 1
},
em: {
max: 10,
steps: 0.1
},
rm: {
max: 10,
steps: 0.1
}
};
function SpacingInputControl(_ref) {
var _CUSTOM_VALUE_SETTING, _CUSTOM_VALUE_SETTING2, _CUSTOM_VALUE_SETTING3, _CUSTOM_VALUE_SETTING4, _spacingSizes$current;
let {
spacingSizes,
value,
side,
onChange,
isMixed = false,
type,
minimumCustomValue,
onMouseOver,
onMouseOut
} = _ref;
// Treat value as a preset value if the passed in value matches the value of one of the spacingSizes.
value = getPresetValueFromCustomValue(value, spacingSizes);
let selectListSizes = spacingSizes;
const showRangeControl = spacingSizes.length <= 8;
const disableCustomSpacingSizes = (0,external_wp_data_namespaceObject.useSelect)(select => {
const editorSettings = select(store).getSettings();
return editorSettings === null || editorSettings === void 0 ? void 0 : editorSettings.disableCustomSpacingSizes;
});
const [showCustomValueControl, setShowCustomValueControl] = (0,external_wp_element_namespaceObject.useState)(!disableCustomSpacingSizes && value !== undefined && !isValueSpacingPreset(value));
const units = (0,external_wp_components_namespaceObject.__experimentalUseCustomUnits)({
availableUnits: useSetting('spacing.units') || ['px', 'em', 'rem']
});
let currentValue = null;
const showCustomValueInSelectList = !showRangeControl && !showCustomValueControl && value !== undefined && (!isValueSpacingPreset(value) || isValueSpacingPreset(value) && isMixed);
if (showCustomValueInSelectList) {
selectListSizes = [...spacingSizes, {
name: !isMixed ? // translators: A custom measurement, eg. a number followed by a unit like 12px.
(0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('Custom (%s)'), value) : (0,external_wp_i18n_namespaceObject.__)('Mixed'),
slug: 'custom',
size: value
}];
currentValue = selectListSizes.length - 1;
} else if (!isMixed) {
currentValue = !showCustomValueControl ? getSliderValueFromPreset(value, spacingSizes) : getCustomValueFromPreset(value, spacingSizes);
}
const selectedUnit = (0,external_wp_element_namespaceObject.useMemo)(() => (0,external_wp_components_namespaceObject.__experimentalParseQuantityAndUnitFromRawValue)(currentValue), [currentValue])[1] || units[0].value;
const setInitialValue = () => {
if (value === undefined) {
onChange('0');
}
};
const customTooltipContent = newValue => {
var _spacingSizes$newValu;
return value === undefined ? undefined : (_spacingSizes$newValu = spacingSizes[newValue]) === null || _spacingSizes$newValu === void 0 ? void 0 : _spacingSizes$newValu.name;
};
const customRangeValue = parseFloat(currentValue, 10);
const getNewCustomValue = newSize => {
const isNumeric = !isNaN(parseFloat(newSize));
const nextValue = isNumeric ? newSize : undefined;
return nextValue;
};
const getNewPresetValue = (newSize, controlType) => {
var _spacingSizes$newSize;
const size = parseInt(newSize, 10);
if (controlType === 'selectList') {
if (size === 0) {
return undefined;
}
if (size === 1) {
return '0';
}
} else if (size === 0) {
return '0';
}
return `var:preset|spacing|${(_spacingSizes$newSize = spacingSizes[newSize]) === null || _spacingSizes$newSize === void 0 ? void 0 : _spacingSizes$newSize.slug}`;
};
const handleCustomValueSliderChange = next => {
onChange([next, selectedUnit].join(''));
};
const allPlaceholder = isMixed ? (0,external_wp_i18n_namespaceObject.__)('Mixed') : null;
const currentValueHint = !isMixed ? customTooltipContent(currentValue) : (0,external_wp_i18n_namespaceObject.__)('Mixed');
const options = selectListSizes.map((size, index) => ({
key: index,
name: size.name
}));
const marks = spacingSizes.map((newValue, index) => ({
value: index,
label: undefined
}));
const ariaLabel = (0,external_wp_i18n_namespaceObject.sprintf)( // translators: 1: The side of the block being modified (top, bottom, left, etc.). 2. Type of spacing being modified (Padding, margin, etc)
(0,external_wp_i18n_namespaceObject.__)('%1$s %2$s'), LABELS[side], type === null || type === void 0 ? void 0 : type.toLowerCase());
const showHint = showRangeControl && !showCustomValueControl && currentValueHint !== undefined;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, side !== 'all' && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalHStack, {
className: "components-spacing-sizes-control__side-labels"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.BaseControl.VisualLabel, {
className: "components-spacing-sizes-control__side-label"
}, LABELS[side]), showHint && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.BaseControl.VisualLabel, {
className: "components-spacing-sizes-control__hint-single"
}, currentValueHint)), side === 'all' && showHint && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.BaseControl.VisualLabel, {
className: "components-spacing-sizes-control__hint-all"
}, currentValueHint), !disableCustomSpacingSizes && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
label: showCustomValueControl ? (0,external_wp_i18n_namespaceObject.__)('Use size preset') : (0,external_wp_i18n_namespaceObject.__)('Set custom size'),
icon: library_settings,
onClick: () => {
setShowCustomValueControl(!showCustomValueControl);
},
isPressed: showCustomValueControl,
isSmall: true,
className: classnames_default()({
'components-spacing-sizes-control__custom-toggle-all': side === 'all',
'components-spacing-sizes-control__custom-toggle-single': side !== 'all'
}),
iconSize: 24
}), showCustomValueControl && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalUnitControl, {
onMouseOver: onMouseOver,
onMouseOut: onMouseOut,
onFocus: onMouseOver,
onBlur: onMouseOut,
onChange: newSize => onChange(getNewCustomValue(newSize)),
value: currentValue,
units: units,
min: minimumCustomValue,
placeholder: allPlaceholder,
disableUnits: isMixed,
label: ariaLabel,
hideLabelFromVision: true,
className: "components-spacing-sizes-control__custom-value-input",
size: '__unstable-large'
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.RangeControl, {
onMouseOver: onMouseOver,
onMouseOut: onMouseOut,
onFocus: onMouseOver,
onBlur: onMouseOut,
value: customRangeValue,
min: 0,
max: (_CUSTOM_VALUE_SETTING = (_CUSTOM_VALUE_SETTING2 = CUSTOM_VALUE_SETTINGS[selectedUnit]) === null || _CUSTOM_VALUE_SETTING2 === void 0 ? void 0 : _CUSTOM_VALUE_SETTING2.max) !== null && _CUSTOM_VALUE_SETTING !== void 0 ? _CUSTOM_VALUE_SETTING : 10,
step: (_CUSTOM_VALUE_SETTING3 = (_CUSTOM_VALUE_SETTING4 = CUSTOM_VALUE_SETTINGS[selectedUnit]) === null || _CUSTOM_VALUE_SETTING4 === void 0 ? void 0 : _CUSTOM_VALUE_SETTING4.steps) !== null && _CUSTOM_VALUE_SETTING3 !== void 0 ? _CUSTOM_VALUE_SETTING3 : 0.1,
withInputField: false,
onChange: handleCustomValueSliderChange,
className: "components-spacing-sizes-control__custom-value-range",
__nextHasNoMarginBottom: true
})), showRangeControl && !showCustomValueControl && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.RangeControl, {
onMouseOver: onMouseOver,
onMouseOut: onMouseOut,
className: "components-spacing-sizes-control__range-control",
value: currentValue,
onChange: newSize => onChange(getNewPresetValue(newSize)),
onMouseDown: event => {
var _event$nativeEvent;
// If mouse down is near start of range set initial value to 0, which
// prevents the user have to drag right then left to get 0 setting.
if ((event === null || event === void 0 ? void 0 : (_event$nativeEvent = event.nativeEvent) === null || _event$nativeEvent === void 0 ? void 0 : _event$nativeEvent.offsetX) < 35) {
setInitialValue();
}
},
withInputField: false,
"aria-valuenow": currentValue,
"aria-valuetext": (_spacingSizes$current = spacingSizes[currentValue]) === null || _spacingSizes$current === void 0 ? void 0 : _spacingSizes$current.name,
renderTooltipContent: customTooltipContent,
min: 0,
max: spacingSizes.length - 1,
marks: marks,
label: ariaLabel,
hideLabelFromVision: true,
__nextHasNoMarginBottom: true,
onFocus: onMouseOver,
onBlur: onMouseOut
}), !showRangeControl && !showCustomValueControl && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.CustomSelectControl, {
className: "components-spacing-sizes-control__custom-select-control",
value: options.find(option => option.key === currentValue) || '' // passing undefined here causes a downshift controlled/uncontrolled warning
,
onChange: selection => {
onChange(getNewPresetValue(selection.selectedItem.key, 'selectList'));
},
options: options,
label: ariaLabel,
hideLabelFromVision: true,
__nextUnconstrainedWidth: true,
size: '__unstable-large',
onMouseOver: onMouseOver,
onMouseOut: onMouseOut,
onFocus: onMouseOver,
onBlur: onMouseOut
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/spacing-sizes-control/all-input-control.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function AllInputControl(_ref) {
let {
onChange,
values,
sides,
spacingSizes,
type,
minimumCustomValue,
onMouseOver,
onMouseOut
} = _ref;
const allValue = getAllRawValue(values);
const hasValues = isValuesDefined(values);
const isMixed = hasValues && isValuesMixed(values, sides);
const handleOnChange = next => {
const nextValues = (0,external_wp_components_namespaceObject.__experimentalApplyValueToSides)(values, next, sides);
onChange(nextValues);
};
return (0,external_wp_element_namespaceObject.createElement)(SpacingInputControl, {
value: allValue,
onChange: handleOnChange,
side: 'all',
spacingSizes: spacingSizes,
isMixed: isMixed,
type: type,
minimumCustomValue: minimumCustomValue,
onMouseOver: onMouseOver,
onMouseOut: onMouseOut
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/spacing-sizes-control/input-controls.js
/**
* Internal dependencies
*/
function BoxInputControls(_ref) {
let {
values,
sides,
onChange,
spacingSizes,
type,
minimumCustomValue,
onMouseOver,
onMouseOut
} = _ref;
// Filter sides if custom configuration provided, maintaining default order.
const filteredSides = sides !== null && sides !== void 0 && sides.length ? ALL_SIDES.filter(side => sides.includes(side)) : ALL_SIDES;
const createHandleOnChange = side => next => {
const nextValues = { ...values
};
nextValues[side] = next;
onChange(nextValues);
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, filteredSides.map(side => {
return (0,external_wp_element_namespaceObject.createElement)(SpacingInputControl, {
value: values[side],
label: LABELS[side],
key: `spacing-sizes-control-${side}`,
withInputField: false,
side: side,
onChange: createHandleOnChange(side),
spacingSizes: spacingSizes,
type: type,
minimumCustomValue: minimumCustomValue,
onMouseOver: onMouseOver,
onMouseOut: onMouseOut
});
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/spacing-sizes-control/axial-input-controls.js
/**
* Internal dependencies
*/
const groupedSides = ['vertical', 'horizontal'];
function AxialInputControls(_ref) {
let {
onChange,
values,
sides,
spacingSizes,
type,
minimumCustomValue,
onMouseOver,
onMouseOut
} = _ref;
const createHandleOnChange = side => next => {
if (!onChange) {
return;
}
const nextValues = { ...values
};
if (side === 'vertical') {
nextValues.top = next;
nextValues.bottom = next;
}
if (side === 'horizontal') {
nextValues.left = next;
nextValues.right = next;
}
onChange(nextValues);
}; // Filter sides if custom configuration provided, maintaining default order.
const filteredSides = sides !== null && sides !== void 0 && sides.length ? groupedSides.filter(side => sides.includes(side)) : groupedSides;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, filteredSides.map(side => {
const axisValue = side === 'vertical' ? values.top : values.left;
return (0,external_wp_element_namespaceObject.createElement)(SpacingInputControl, {
value: axisValue,
onChange: createHandleOnChange(side),
label: LABELS[side],
key: `spacing-sizes-control-${side}`,
withInputField: false,
side: side,
spacingSizes: spacingSizes,
type: type,
minimumCustomValue: minimumCustomValue,
onMouseOver: onMouseOver,
onMouseOut: onMouseOut
});
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/link.js
/**
* WordPress dependencies
*/
const link_link = (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: "M15.6 7.2H14v1.5h1.6c2 0 3.7 1.7 3.7 3.7s-1.7 3.7-3.7 3.7H14v1.5h1.6c2.8 0 5.2-2.3 5.2-5.2 0-2.9-2.3-5.2-5.2-5.2zM4.7 12.4c0-2 1.7-3.7 3.7-3.7H10V7.2H8.4c-2.9 0-5.2 2.3-5.2 5.2 0 2.9 2.3 5.2 5.2 5.2H10v-1.5H8.4c-2 0-3.7-1.7-3.7-3.7zm4.6.9h5.3v-1.5H9.3v1.5z"
}));
/* harmony default export */ var library_link = (link_link);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/link-off.js
/**
* WordPress dependencies
*/
const linkOff = (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: "M15.6 7.3h-.7l1.6-3.5-.9-.4-3.9 8.5H9v1.5h2l-1.3 2.8H8.4c-2 0-3.7-1.7-3.7-3.7s1.7-3.7 3.7-3.7H10V7.3H8.4c-2.9 0-5.2 2.3-5.2 5.2 0 2.9 2.3 5.2 5.2 5.2H9l-1.4 3.2.9.4 5.7-12.5h1.4c2 0 3.7 1.7 3.7 3.7s-1.7 3.7-3.7 3.7H14v1.5h1.6c2.9 0 5.2-2.3 5.2-5.2 0-2.9-2.4-5.2-5.2-5.2z"
}));
/* harmony default export */ var link_off = (linkOff);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/spacing-sizes-control/linked-button.js
/**
* WordPress dependencies
*/
function LinkedButton(_ref) {
let {
isLinked,
onClick
} = _ref;
const label = isLinked ? (0,external_wp_i18n_namespaceObject.__)('Unlink sides') : (0,external_wp_i18n_namespaceObject.__)('Link sides');
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Tooltip, {
text: label
}, (0,external_wp_element_namespaceObject.createElement)("span", {
className: "component-spacing-sizes-control__linked-button"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
isSmall: true,
icon: isLinked ? library_link : link_off,
iconSize: 24,
"aria-label": label,
onClick: onClick
})));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/spacing-sizes-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function SpacingSizesControl(_ref) {
let {
inputProps,
onChange,
label = (0,external_wp_i18n_namespaceObject.__)('Spacing Control'),
values,
sides,
splitOnAxis = false,
useSelect,
minimumCustomValue = 0,
onMouseOver,
onMouseOut
} = _ref;
const spacingSizes = [{
name: 0,
slug: '0',
size: 0
}, ...(useSetting('spacing.spacingSizes') || [])];
if (spacingSizes.length > 8) {
spacingSizes.unshift({
name: (0,external_wp_i18n_namespaceObject.__)('Default'),
slug: 'default',
size: undefined
});
}
const inputValues = values || DEFAULT_VALUES;
const hasInitialValue = isValuesDefined(values);
const hasOneSide = (sides === null || sides === void 0 ? void 0 : sides.length) === 1;
const [isLinked, setIsLinked] = (0,external_wp_element_namespaceObject.useState)(!hasInitialValue || !isValuesMixed(inputValues, sides) || hasOneSide);
const toggleLinked = () => {
setIsLinked(!isLinked);
};
const handleOnChange = nextValue => {
const newValues = { ...values,
...nextValue
};
onChange(newValues);
};
const inputControlProps = { ...inputProps,
onChange: handleOnChange,
isLinked,
sides,
values: inputValues,
spacingSizes,
useSelect,
type: label,
minimumCustomValue,
onMouseOver,
onMouseOut
};
return (0,external_wp_element_namespaceObject.createElement)("fieldset", {
className: classnames_default()('component-spacing-sizes-control', {
'is-unlinked': !isLinked
})
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.BaseControl.VisualLabel, {
as: "legend"
}, label), !hasOneSide && (0,external_wp_element_namespaceObject.createElement)(LinkedButton, {
onClick: toggleLinked,
isLinked: isLinked
}), isLinked && (0,external_wp_element_namespaceObject.createElement)(AllInputControl, _extends({
"aria-label": label
}, inputControlProps)), !isLinked && splitOnAxis && (0,external_wp_element_namespaceObject.createElement)(AxialInputControls, inputControlProps), !isLinked && !splitOnAxis && (0,external_wp_element_namespaceObject.createElement)(BoxInputControls, inputControlProps));
}
;// CONCATENATED MODULE: external ["wp","warning"]
var external_wp_warning_namespaceObject = window["wp"]["warning"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inspector-controls/groups.js
/**
* WordPress dependencies
*/
const InspectorControlsDefault = (0,external_wp_components_namespaceObject.createSlotFill)('InspectorControls');
const InspectorControlsAdvanced = (0,external_wp_components_namespaceObject.createSlotFill)('InspectorAdvancedControls');
const InspectorControlsBorder = (0,external_wp_components_namespaceObject.createSlotFill)('InspectorControlsBorder');
const InspectorControlsColor = (0,external_wp_components_namespaceObject.createSlotFill)('InspectorControlsColor');
const InspectorControlsDimensions = (0,external_wp_components_namespaceObject.createSlotFill)('InspectorControlsDimensions');
const InspectorControlsPosition = (0,external_wp_components_namespaceObject.createSlotFill)('InspectorControlsPosition');
const InspectorControlsTypography = (0,external_wp_components_namespaceObject.createSlotFill)('InspectorControlsTypography');
const InspectorControlsListView = (0,external_wp_components_namespaceObject.createSlotFill)('InspectorControlsListView');
const InspectorControlsStyles = (0,external_wp_components_namespaceObject.createSlotFill)('InspectorControlsStyles');
const groups_groups = {
default: InspectorControlsDefault,
advanced: InspectorControlsAdvanced,
border: InspectorControlsBorder,
color: InspectorControlsColor,
dimensions: InspectorControlsDimensions,
list: InspectorControlsListView,
settings: InspectorControlsDefault,
// Alias for default.
styles: InspectorControlsStyles,
typography: InspectorControlsTypography,
position: InspectorControlsPosition
};
/* harmony default export */ var inspector_controls_groups = (groups_groups);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inspector-controls/fill.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function InspectorControlsFill(_ref) {
var _groups$group;
let {
children,
group = 'default',
__experimentalGroup
} = _ref;
if (__experimentalGroup) {
external_wp_deprecated_default()('`__experimentalGroup` property in `InspectorControlsFill`', {
since: '6.2',
version: '6.4',
alternative: '`group`'
});
group = __experimentalGroup;
}
const isDisplayed = useDisplayBlockControls();
const Fill = (_groups$group = inspector_controls_groups[group]) === null || _groups$group === void 0 ? void 0 : _groups$group.Fill;
if (!Fill) {
typeof process !== "undefined" && process.env && "production" !== "production" ? 0 : void 0;
return null;
}
if (!isDisplayed) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalStyleProvider, {
document: document
}, (0,external_wp_element_namespaceObject.createElement)(Fill, null, fillProps => {
// Children passed to InspectorControlsFill will not have
// access to any React Context whose Provider is part of
// the InspectorControlsSlot tree. So we re-create the
// Provider in this subtree.
const value = !(0,external_lodash_namespaceObject.isEmpty)(fillProps) ? fillProps : null;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToolsPanelContext.Provider, {
value: value
}, children);
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/utils.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Removed falsy values from nested object.
*
* @param {*} object
* @return {*} Object cleaned from falsy values
*/
const utils_cleanEmptyObject = object => {
if (object === null || typeof object !== 'object' || Array.isArray(object)) {
return object;
}
const cleanedNestedObjects = Object.fromEntries(Object.entries((0,external_lodash_namespaceObject.mapValues)(object, utils_cleanEmptyObject)).filter(_ref => {
let [, value] = _ref;
return Boolean(value);
}));
return (0,external_lodash_namespaceObject.isEmpty)(cleanedNestedObjects) ? undefined : cleanedNestedObjects;
};
/**
* Converts a path to an array of its fragments.
* Supports strings, numbers and arrays:
*
* 'foo' => [ 'foo' ]
* 2 => [ '2' ]
* [ 'foo', 'bar' ] => [ 'foo', 'bar' ]
*
* @param {string|number|Array} path Path
* @return {Array} Normalized path.
*/
function normalizePath(path) {
if (Array.isArray(path)) {
return path;
} else if (typeof path === 'number') {
return [path.toString()];
}
return [path];
}
/**
* Clones an object.
* Non-object values are returned unchanged.
*
* @param {*} object Object to clone.
* @return {*} Cloned object, or original literal non-object value.
*/
function cloneObject(object) {
if (typeof object === 'object') {
return { ...Object.fromEntries(Object.entries(object).map(_ref2 => {
let [key, value] = _ref2;
return [key, cloneObject(value)];
}))
};
}
return object;
}
/**
* Perform an immutable set.
* Handles nullish initial values.
* Clones all nested objects in the specified object.
*
* @param {Object} object Object to set a value in.
* @param {number|string|Array} path Path in the object to modify.
* @param {*} value New value to set.
* @return {Object} Cloned object with the new value set.
*/
function immutableSet(object, path, value) {
const normalizedPath = normalizePath(path);
const newObject = object ? cloneObject(object) : {};
normalizedPath.reduce((acc, key, i) => {
if (acc[key] === undefined) {
acc[key] = {};
}
if (i === normalizedPath.length - 1) {
acc[key] = value;
}
return acc[key];
}, newObject);
return newObject;
}
function transformStyles(activeSupports, migrationPaths, result, source, index, results) {
var _source$;
// If there are no active supports return early.
if (Object.values(activeSupports !== null && activeSupports !== void 0 ? activeSupports : {}).every(isActive => !isActive)) {
return result;
} // If the condition verifies we are probably in the presence of a wrapping transform
// e.g: nesting paragraphs in a group or columns and in that case the styles should not be transformed.
if (results.length === 1 && result.innerBlocks.length === source.length) {
return result;
} // For cases where we have a transform from one block to multiple blocks
// or multiple blocks to one block we apply the styles of the first source block
// to the result(s).
let referenceBlockAttributes = (_source$ = source[0]) === null || _source$ === void 0 ? void 0 : _source$.attributes; // If we are in presence of transform between more than one block in the source
// that has more than one block in the result
// we apply the styles on source N to the result N,
// if source N does not exists we do nothing.
if (results.length > 1 && source.length > 1) {
if (source[index]) {
var _source$index;
referenceBlockAttributes = (_source$index = source[index]) === null || _source$index === void 0 ? void 0 : _source$index.attributes;
} else {
return result;
}
}
let returnBlock = result;
Object.entries(activeSupports).forEach(_ref3 => {
let [support, isActive] = _ref3;
if (isActive) {
migrationPaths[support].forEach(path => {
const styleValue = (0,external_lodash_namespaceObject.get)(referenceBlockAttributes, path);
if (styleValue) {
returnBlock = { ...returnBlock,
attributes: immutableSet(returnBlock.attributes, path, styleValue)
};
}
});
}
});
return returnBlock;
}
/**
* Check whether serialization of specific block support feature or set should
* be skipped.
*
* @param {string|Object} blockType Block name or block type object.
* @param {string} featureSet Name of block support feature set.
* @param {string} feature Name of the individual feature to check.
*
* @return {boolean} Whether serialization should occur.
*/
function shouldSkipSerialization(blockType, featureSet, feature) {
const support = (0,external_wp_blocks_namespaceObject.getBlockSupport)(blockType, featureSet);
const skipSerialization = support === null || support === void 0 ? void 0 : support.__experimentalSkipSerialization;
if (Array.isArray(skipSerialization)) {
return skipSerialization.includes(feature);
}
return skipSerialization;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inspector-controls/block-support-tools-panel.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function BlockSupportToolsPanel(_ref) {
let {
children,
group,
label
} = _ref;
const {
updateBlockAttributes
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const {
getBlockAttributes,
getMultiSelectedBlockClientIds,
getSelectedBlockClientId,
hasMultiSelection
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const panelId = getSelectedBlockClientId();
const resetAll = (0,external_wp_element_namespaceObject.useCallback)(function () {
let resetFilters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
const newAttributes = {};
const clientIds = hasMultiSelection() ? getMultiSelectedBlockClientIds() : [panelId];
clientIds.forEach(clientId => {
const {
style
} = getBlockAttributes(clientId);
let newBlockAttributes = {
style
};
resetFilters.forEach(resetFilter => {
newBlockAttributes = { ...newBlockAttributes,
...resetFilter(newBlockAttributes)
};
}); // Enforce a cleaned style object.
newBlockAttributes = { ...newBlockAttributes,
style: utils_cleanEmptyObject(newBlockAttributes.style)
};
newAttributes[clientId] = newBlockAttributes;
});
updateBlockAttributes(clientIds, newAttributes, true);
}, [utils_cleanEmptyObject, getBlockAttributes, getMultiSelectedBlockClientIds, hasMultiSelection, panelId, updateBlockAttributes]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToolsPanel, {
className: `${group}-block-support-panel`,
label: label,
resetAll: resetAll,
key: panelId,
panelId: panelId,
hasInnerWrapper: true,
shouldRenderPlaceholderItems: true // Required to maintain fills ordering.
,
__experimentalFirstVisibleItemClass: "first",
__experimentalLastVisibleItemClass: "last"
}, children);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inspector-controls/block-support-slot-container.js
/**
* WordPress dependencies
*/
function BlockSupportSlotContainer(_ref) {
let {
Slot,
...props
} = _ref;
const toolsPanelContext = (0,external_wp_element_namespaceObject.useContext)(external_wp_components_namespaceObject.__experimentalToolsPanelContext);
return (0,external_wp_element_namespaceObject.createElement)(Slot, _extends({}, props, {
fillProps: toolsPanelContext,
bubblesVirtually: true
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inspector-controls/slot.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function InspectorControlsSlot(_ref) {
var _groups$group;
let {
__experimentalGroup,
group = 'default',
label,
...props
} = _ref;
if (__experimentalGroup) {
external_wp_deprecated_default()('`__experimentalGroup` property in `InspectorControlsSlot`', {
since: '6.2',
version: '6.4',
alternative: '`group`'
});
group = __experimentalGroup;
}
const Slot = (_groups$group = inspector_controls_groups[group]) === null || _groups$group === void 0 ? void 0 : _groups$group.Slot;
const slot = (0,external_wp_components_namespaceObject.__experimentalUseSlot)(Slot === null || Slot === void 0 ? void 0 : Slot.__unstableName);
const fills = (0,external_wp_components_namespaceObject.__experimentalUseSlotFills)(Slot === null || Slot === void 0 ? void 0 : Slot.__unstableName);
if (!Slot || !slot) {
typeof process !== "undefined" && process.env && "production" !== "production" ? 0 : void 0;
return null;
}
const hasFills = Boolean(fills && fills.length);
if (!hasFills) {
return null;
}
if (label) {
return (0,external_wp_element_namespaceObject.createElement)(BlockSupportToolsPanel, {
group: group,
label: label
}, (0,external_wp_element_namespaceObject.createElement)(BlockSupportSlotContainer, _extends({}, props, {
Slot: Slot
})));
}
return (0,external_wp_element_namespaceObject.createElement)(Slot, _extends({}, props, {
bubblesVirtually: true
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inspector-controls/index.js
/**
* Internal dependencies
*/
const InspectorControls = InspectorControlsFill;
InspectorControls.Slot = InspectorControlsSlot; // This is just here for backward compatibility.
const InspectorAdvancedControls = props => {
return (0,external_wp_element_namespaceObject.createElement)(InspectorControlsFill, _extends({}, props, {
group: "advanced"
}));
};
InspectorAdvancedControls.Slot = props => {
return (0,external_wp_element_namespaceObject.createElement)(InspectorControlsSlot, _extends({}, props, {
group: "advanced"
}));
};
InspectorAdvancedControls.slotName = 'InspectorAdvancedControls';
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/inspector-controls/README.md
*/
/* harmony default export */ var inspector_controls = (InspectorControls);
;// CONCATENATED MODULE: external ["wp","isShallowEqual"]
var external_wp_isShallowEqual_namespaceObject = window["wp"]["isShallowEqual"];
var external_wp_isShallowEqual_default = /*#__PURE__*/__webpack_require__.n(external_wp_isShallowEqual_namespaceObject);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-popover/use-popover-scroll.js
/**
* WordPress dependencies
*/
/**
* Allow scrolling "through" popovers over the canvas. This is only called for
* as long as the pointer is over a popover. Do not use React events because it
* will bubble through portals.
*
* @param {Object} scrollableRef
*/
function usePopoverScroll(scrollableRef) {
return (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
if (!scrollableRef) {
return;
}
function onWheel(event) {
const {
deltaX,
deltaY
} = event;
scrollableRef.current.scrollBy(deltaX, deltaY);
} // Tell the browser that we do not call event.preventDefault
// See https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#improving_scrolling_performance_with_passive_listeners
const options = {
passive: true
};
node.addEventListener('wheel', onWheel, options);
return () => {
node.removeEventListener('wheel', onWheel, options);
};
}, [scrollableRef]);
}
/* harmony default export */ var use_popover_scroll = (usePopoverScroll);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-popover/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const MAX_POPOVER_RECOMPUTE_COUNTER = Number.MAX_SAFE_INTEGER;
function BlockPopover(_ref, ref) {
let {
clientId,
bottomClientId,
children,
__unstableRefreshSize,
__unstableCoverTarget = false,
__unstablePopoverSlot,
__unstableContentRef,
shift = true,
...props
} = _ref;
const selectedElement = useBlockElement(clientId);
const lastSelectedElement = useBlockElement(bottomClientId !== null && bottomClientId !== void 0 ? bottomClientId : clientId);
const mergedRefs = (0,external_wp_compose_namespaceObject.useMergeRefs)([ref, use_popover_scroll(__unstableContentRef)]);
const [popoverDimensionsRecomputeCounter, forceRecomputePopoverDimensions] = (0,external_wp_element_namespaceObject.useReducer)( // Module is there to make sure that the counter doesn't overflow.
s => (s + 1) % MAX_POPOVER_RECOMPUTE_COUNTER, 0); // When blocks are moved up/down, they are animated to their new position by
// updating the `transform` property manually (i.e. without using CSS
// transitions or animations). The animation, which can also scroll the block
// editor, can sometimes cause the position of the Popover to get out of sync.
// A MutationObserver is therefore used to make sure that changes to the
// selectedElement's attribute (i.e. `transform`) can be tracked and used to
// trigger the Popover to rerender.
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
if (!selectedElement) {
return;
}
const observer = new window.MutationObserver(forceRecomputePopoverDimensions);
observer.observe(selectedElement, {
attributes: true
});
return () => {
observer.disconnect();
};
}, [selectedElement]);
const style = (0,external_wp_element_namespaceObject.useMemo)(() => {
if ( // popoverDimensionsRecomputeCounter is by definition always equal or greater
// than 0. This check is only there to satisfy the correctness of the
// exhaustive-deps rule for the `useMemo` hook.
popoverDimensionsRecomputeCounter < 0 || !selectedElement || lastSelectedElement !== selectedElement) {
return {};
}
return {
position: 'absolute',
width: selectedElement.offsetWidth,
height: selectedElement.offsetHeight
};
}, [selectedElement, lastSelectedElement, __unstableRefreshSize, popoverDimensionsRecomputeCounter]);
const popoverAnchor = (0,external_wp_element_namespaceObject.useMemo)(() => {
if ( // popoverDimensionsRecomputeCounter is by definition always equal or greater
// than 0. This check is only there to satisfy the correctness of the
// exhaustive-deps rule for the `useMemo` hook.
popoverDimensionsRecomputeCounter < 0 || !selectedElement || bottomClientId && !lastSelectedElement) {
return undefined;
}
return {
getBoundingClientRect() {
var _lastSelectedBCR$left, _lastSelectedBCR$top, _lastSelectedBCR$righ, _lastSelectedBCR$bott;
const selectedBCR = selectedElement.getBoundingClientRect();
const lastSelectedBCR = lastSelectedElement === null || lastSelectedElement === void 0 ? void 0 : lastSelectedElement.getBoundingClientRect(); // Get the biggest rectangle that encompasses completely the currently
// selected element and the last selected element:
// - for top/left coordinates, use the smaller numbers
// - for the bottom/right coordinates, use the largest numbers
const left = Math.min(selectedBCR.left, (_lastSelectedBCR$left = lastSelectedBCR === null || lastSelectedBCR === void 0 ? void 0 : lastSelectedBCR.left) !== null && _lastSelectedBCR$left !== void 0 ? _lastSelectedBCR$left : Infinity);
const top = Math.min(selectedBCR.top, (_lastSelectedBCR$top = lastSelectedBCR === null || lastSelectedBCR === void 0 ? void 0 : lastSelectedBCR.top) !== null && _lastSelectedBCR$top !== void 0 ? _lastSelectedBCR$top : Infinity);
const right = Math.max(selectedBCR.right, (_lastSelectedBCR$righ = lastSelectedBCR.right) !== null && _lastSelectedBCR$righ !== void 0 ? _lastSelectedBCR$righ : -Infinity);
const bottom = Math.max(selectedBCR.bottom, (_lastSelectedBCR$bott = lastSelectedBCR.bottom) !== null && _lastSelectedBCR$bott !== void 0 ? _lastSelectedBCR$bott : -Infinity);
const width = right - left;
const height = bottom - top;
return new window.DOMRect(left, top, width, height);
},
ownerDocument: selectedElement.ownerDocument
};
}, [bottomClientId, lastSelectedElement, selectedElement, popoverDimensionsRecomputeCounter]);
if (!selectedElement || bottomClientId && !lastSelectedElement) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Popover, _extends({
ref: mergedRefs,
animate: false,
focusOnMount: false,
anchor: popoverAnchor // Render in the old slot if needed for backward compatibility,
// otherwise render in place (not in the default popover slot).
,
__unstableSlotName: __unstablePopoverSlot || null,
placement: "top-start",
resize: false,
flip: false,
shift: shift
}, props, {
className: classnames_default()('block-editor-block-popover', props.className),
variant: "unstyled"
}), __unstableCoverTarget && (0,external_wp_element_namespaceObject.createElement)("div", {
style: style
}, children), !__unstableCoverTarget && children);
}
/* harmony default export */ var block_popover = ((0,external_wp_element_namespaceObject.forwardRef)(BlockPopover));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/margin.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Determines if there is margin support.
*
* @param {string|Object} blockType Block name or Block Type object.
*
* @return {boolean} Whether there is support.
*/
function hasMarginSupport(blockType) {
const support = (0,external_wp_blocks_namespaceObject.getBlockSupport)(blockType, SPACING_SUPPORT_KEY);
return !!(true === support || support !== null && support !== void 0 && support.margin);
}
/**
* Checks if there is a current value in the margin block support attributes.
*
* @param {Object} props Block props.
* @return {boolean} Whether or not the block has a margin value set.
*/
function hasMarginValue(props) {
var _props$attributes$sty, _props$attributes$sty2;
return ((_props$attributes$sty = props.attributes.style) === null || _props$attributes$sty === void 0 ? void 0 : (_props$attributes$sty2 = _props$attributes$sty.spacing) === null || _props$attributes$sty2 === void 0 ? void 0 : _props$attributes$sty2.margin) !== undefined;
}
/**
* Resets the margin block support attributes. This can be used when disabling
* the margin support controls for a block via a `ToolsPanel`.
*
* @param {Object} props Block props.
* @param {Object} props.attributes Block's attributes.
* @param {Object} props.setAttributes Function to set block's attributes.
*/
function resetMargin(_ref) {
let {
attributes = {},
setAttributes
} = _ref;
const {
style
} = attributes;
setAttributes({
style: utils_cleanEmptyObject({ ...style,
spacing: { ...(style === null || style === void 0 ? void 0 : style.spacing),
margin: undefined
}
})
});
}
/**
* Custom hook that checks if margin settings have been disabled.
*
* @param {string} name The name of the block.
*
* @return {boolean} Whether margin setting is disabled.
*/
function useIsMarginDisabled() {
let {
name: blockName
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const isDisabled = !useSetting('spacing.margin');
const isInvalid = !useIsDimensionsSupportValid(blockName, 'margin');
return !hasMarginSupport(blockName) || isDisabled || isInvalid;
}
/**
* Inspector control panel containing the margin related configuration
*
* @param {Object} props Block props.
*
* @return {WPElement} Margin edit element.
*/
function MarginEdit(props) {
var _style$spacing, _style$spacing2;
const {
name: blockName,
attributes: {
style
},
setAttributes,
onMouseOver,
onMouseOut
} = props;
const spacingSizes = useSetting('spacing.spacingSizes');
const units = (0,external_wp_components_namespaceObject.__experimentalUseCustomUnits)({
availableUnits: useSetting('spacing.units') || ['%', 'px', 'em', 'rem', 'vw']
});
const sides = useCustomSides(blockName, 'margin');
const splitOnAxis = sides && sides.some(side => AXIAL_SIDES.includes(side));
if (useIsMarginDisabled(props)) {
return null;
}
const onChange = next => {
const newStyle = { ...style,
spacing: { ...(style === null || style === void 0 ? void 0 : style.spacing),
margin: next
}
};
setAttributes({
style: utils_cleanEmptyObject(newStyle)
});
};
return external_wp_element_namespaceObject.Platform.select({
web: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (!spacingSizes || (spacingSizes === null || spacingSizes === void 0 ? void 0 : spacingSizes.length) === 0) && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalBoxControl, {
values: style === null || style === void 0 ? void 0 : (_style$spacing = style.spacing) === null || _style$spacing === void 0 ? void 0 : _style$spacing.margin,
onChange: onChange,
label: (0,external_wp_i18n_namespaceObject.__)('Margin'),
sides: sides,
units: units,
allowReset: false,
splitOnAxis: splitOnAxis,
onMouseOver: onMouseOver,
onMouseOut: onMouseOut
}), (spacingSizes === null || spacingSizes === void 0 ? void 0 : spacingSizes.length) > 0 && (0,external_wp_element_namespaceObject.createElement)(SpacingSizesControl, {
values: style === null || style === void 0 ? void 0 : (_style$spacing2 = style.spacing) === null || _style$spacing2 === void 0 ? void 0 : _style$spacing2.margin,
onChange: onChange,
label: (0,external_wp_i18n_namespaceObject.__)('Margin'),
sides: sides,
units: units,
allowReset: false,
splitOnAxis: false,
onMouseOver: onMouseOver,
onMouseOut: onMouseOut
})),
native: null
});
}
function MarginVisualizer(_ref2) {
var _attributes$style, _attributes$style$spa;
let {
clientId,
attributes,
forceShow
} = _ref2;
const margin = attributes === null || attributes === void 0 ? void 0 : (_attributes$style = attributes.style) === null || _attributes$style === void 0 ? void 0 : (_attributes$style$spa = _attributes$style.spacing) === null || _attributes$style$spa === void 0 ? void 0 : _attributes$style$spa.margin;
const style = (0,external_wp_element_namespaceObject.useMemo)(() => {
const marginTop = margin !== null && margin !== void 0 && margin.top ? getSpacingPresetCssVar(margin === null || margin === void 0 ? void 0 : margin.top) : 0;
const marginRight = margin !== null && margin !== void 0 && margin.right ? getSpacingPresetCssVar(margin === null || margin === void 0 ? void 0 : margin.right) : 0;
const marginBottom = margin !== null && margin !== void 0 && margin.bottom ? getSpacingPresetCssVar(margin === null || margin === void 0 ? void 0 : margin.bottom) : 0;
const marginLeft = margin !== null && margin !== void 0 && margin.left ? getSpacingPresetCssVar(margin === null || margin === void 0 ? void 0 : margin.left) : 0;
return {
borderTopWidth: marginTop,
borderRightWidth: marginRight,
borderBottomWidth: marginBottom,
borderLeftWidth: marginLeft,
top: marginTop ? `calc(${marginTop} * -1)` : 0,
right: marginRight ? `calc(${marginRight} * -1)` : 0,
bottom: marginBottom ? `calc(${marginBottom} * -1)` : 0,
left: marginLeft ? `calc(${marginLeft} * -1)` : 0
};
}, [margin]);
const [isActive, setIsActive] = (0,external_wp_element_namespaceObject.useState)(false);
const valueRef = (0,external_wp_element_namespaceObject.useRef)(margin);
const timeoutRef = (0,external_wp_element_namespaceObject.useRef)();
const clearTimer = () => {
if (timeoutRef.current) {
window.clearTimeout(timeoutRef.current);
}
};
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (!external_wp_isShallowEqual_default()(margin, valueRef.current) && !forceShow) {
setIsActive(true);
valueRef.current = margin;
timeoutRef.current = setTimeout(() => {
setIsActive(false);
}, 400);
}
return () => {
setIsActive(false);
clearTimer();
};
}, [margin, forceShow]);
if (!isActive && !forceShow) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(block_popover, {
clientId: clientId,
__unstableCoverTarget: true,
__unstableRefreshSize: margin,
__unstablePopoverSlot: "block-toolbar",
shift: false
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor__padding-visualizer",
style: style
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/height-control/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const RANGE_CONTROL_CUSTOM_SETTINGS = {
px: {
max: 1000,
step: 1
},
'%': {
max: 100,
step: 1
},
vw: {
max: 100,
step: 1
},
vh: {
max: 100,
step: 1
},
em: {
max: 50,
step: 0.1
},
rem: {
max: 50,
step: 0.1
}
};
/**
* HeightControl renders a linked unit control and range control for adjusting the height of a block.
*
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/height-control/README.md
*
* @param {Object} props
* @param {?string} props.label A label for the control.
* @param {( value: string ) => void } props.onChange Called when the height changes.
* @param {string} props.value The current height value.
*
* @return {WPComponent} The component to be rendered.
*/
function HeightControl(_ref) {
var _units$, _RANGE_CONTROL_CUSTOM, _RANGE_CONTROL_CUSTOM2, _RANGE_CONTROL_CUSTOM3, _RANGE_CONTROL_CUSTOM4;
let {
label = (0,external_wp_i18n_namespaceObject.__)('Height'),
onChange,
value
} = _ref;
const customRangeValue = parseFloat(value);
const units = (0,external_wp_components_namespaceObject.__experimentalUseCustomUnits)({
availableUnits: useSetting('spacing.units') || ['%', 'px', 'em', 'rem', 'vh', 'vw']
});
const selectedUnit = (0,external_wp_element_namespaceObject.useMemo)(() => (0,external_wp_components_namespaceObject.__experimentalParseQuantityAndUnitFromRawValue)(value), [value])[1] || ((_units$ = units[0]) === null || _units$ === void 0 ? void 0 : _units$.value) || 'px';
const handleSliderChange = next => {
onChange([next, selectedUnit].join(''));
};
const handleUnitChange = newUnit => {
// Attempt to smooth over differences between currentUnit and newUnit.
// This should slightly improve the experience of switching between unit types.
const [currentValue, currentUnit] = (0,external_wp_components_namespaceObject.__experimentalParseQuantityAndUnitFromRawValue)(value);
if (['em', 'rem'].includes(newUnit) && currentUnit === 'px') {
// Convert pixel value to an approximate of the new unit, assuming a root size of 16px.
onChange((currentValue / 16).toFixed(2) + newUnit);
} else if (['em', 'rem'].includes(currentUnit) && newUnit === 'px') {
// Convert to pixel value assuming a root size of 16px.
onChange(Math.round(currentValue * 16) + newUnit);
} else if (['vh', 'vw', '%'].includes(newUnit) && currentValue > 100) {
// When converting to `vh`, `vw`, or `%` units, cap the new value at 100.
onChange(100 + newUnit);
}
};
return (0,external_wp_element_namespaceObject.createElement)("fieldset", {
className: "block-editor-height-control"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.BaseControl.VisualLabel, {
as: "legend"
}, label), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Flex, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexItem, {
isBlock: true
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalUnitControl, {
value: value,
units: units,
onChange: onChange,
onUnitChange: handleUnitChange,
min: 0,
size: '__unstable-large'
})), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexItem, {
isBlock: true
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalSpacer, {
marginX: 2,
marginBottom: 0
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.RangeControl, {
value: customRangeValue,
min: 0,
max: (_RANGE_CONTROL_CUSTOM = (_RANGE_CONTROL_CUSTOM2 = RANGE_CONTROL_CUSTOM_SETTINGS[selectedUnit]) === null || _RANGE_CONTROL_CUSTOM2 === void 0 ? void 0 : _RANGE_CONTROL_CUSTOM2.max) !== null && _RANGE_CONTROL_CUSTOM !== void 0 ? _RANGE_CONTROL_CUSTOM : 100,
step: (_RANGE_CONTROL_CUSTOM3 = (_RANGE_CONTROL_CUSTOM4 = RANGE_CONTROL_CUSTOM_SETTINGS[selectedUnit]) === null || _RANGE_CONTROL_CUSTOM4 === void 0 ? void 0 : _RANGE_CONTROL_CUSTOM4.step) !== null && _RANGE_CONTROL_CUSTOM3 !== void 0 ? _RANGE_CONTROL_CUSTOM3 : 0.1,
withInputField: false,
onChange: handleSliderChange,
__nextHasNoMarginBottom: true
})))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/min-height.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Determines if there is minHeight support.
*
* @param {string|Object} blockType Block name or Block Type object.
* @return {boolean} Whether there is support.
*/
function hasMinHeightSupport(blockType) {
const support = (0,external_wp_blocks_namespaceObject.getBlockSupport)(blockType, DIMENSIONS_SUPPORT_KEY);
return !!(true === support || support !== null && support !== void 0 && support.minHeight);
}
/**
* Checks if there is a current value in the minHeight block support attributes.
*
* @param {Object} props Block props.
* @return {boolean} Whether or not the block has a minHeight value set.
*/
function hasMinHeightValue(props) {
var _props$attributes$sty, _props$attributes$sty2;
return ((_props$attributes$sty = props.attributes.style) === null || _props$attributes$sty === void 0 ? void 0 : (_props$attributes$sty2 = _props$attributes$sty.dimensions) === null || _props$attributes$sty2 === void 0 ? void 0 : _props$attributes$sty2.minHeight) !== undefined;
}
/**
* Resets the minHeight block support attributes. This can be used when disabling
* the padding support controls for a block via a `ToolsPanel`.
*
* @param {Object} props Block props.
* @param {Object} props.attributes Block's attributes.
* @param {Object} props.setAttributes Function to set block's attributes.
*/
function resetMinHeight(_ref) {
let {
attributes = {},
setAttributes
} = _ref;
const {
style
} = attributes;
setAttributes({
style: utils_cleanEmptyObject({ ...style,
dimensions: { ...(style === null || style === void 0 ? void 0 : style.dimensions),
minHeight: undefined
}
})
});
}
/**
* Custom hook that checks if minHeight controls have been disabled.
*
* @param {string} name The name of the block.
* @return {boolean} Whether minHeight control is disabled.
*/
function useIsMinHeightDisabled() {
let {
name: blockName
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const isDisabled = !useSetting('dimensions.minHeight');
return !hasMinHeightSupport(blockName) || isDisabled;
}
/**
* Inspector control panel containing the minHeight related configuration.
*
* @param {Object} props Block props.
* @return {WPElement} Edit component for height.
*/
function MinHeightEdit(props) {
var _style$dimensions;
const {
attributes: {
style
},
setAttributes
} = props;
if (useIsMinHeightDisabled(props)) {
return null;
}
const onChange = next => {
const newStyle = { ...style,
dimensions: { ...(style === null || style === void 0 ? void 0 : style.dimensions),
minHeight: next
}
};
setAttributes({
style: utils_cleanEmptyObject(newStyle)
});
};
return (0,external_wp_element_namespaceObject.createElement)(HeightControl, {
label: (0,external_wp_i18n_namespaceObject.__)('Min. height'),
value: style === null || style === void 0 ? void 0 : (_style$dimensions = style.dimensions) === null || _style$dimensions === void 0 ? void 0 : _style$dimensions.minHeight,
onChange: onChange
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/padding.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Determines if there is padding support.
*
* @param {string|Object} blockType Block name or Block Type object.
*
* @return {boolean} Whether there is support.
*/
function hasPaddingSupport(blockType) {
const support = (0,external_wp_blocks_namespaceObject.getBlockSupport)(blockType, SPACING_SUPPORT_KEY);
return !!(true === support || support !== null && support !== void 0 && support.padding);
}
/**
* Checks if there is a current value in the padding block support attributes.
*
* @param {Object} props Block props.
* @return {boolean} Whether or not the block has a padding value set.
*/
function hasPaddingValue(props) {
var _props$attributes$sty, _props$attributes$sty2;
return ((_props$attributes$sty = props.attributes.style) === null || _props$attributes$sty === void 0 ? void 0 : (_props$attributes$sty2 = _props$attributes$sty.spacing) === null || _props$attributes$sty2 === void 0 ? void 0 : _props$attributes$sty2.padding) !== undefined;
}
/**
* Resets the padding block support attributes. This can be used when disabling
* the padding support controls for a block via a `ToolsPanel`.
*
* @param {Object} props Block props.
* @param {Object} props.attributes Block's attributes.
* @param {Object} props.setAttributes Function to set block's attributes.
*/
function resetPadding(_ref) {
let {
attributes = {},
setAttributes
} = _ref;
const {
style
} = attributes;
setAttributes({
style: utils_cleanEmptyObject({ ...style,
spacing: { ...(style === null || style === void 0 ? void 0 : style.spacing),
padding: undefined
}
})
});
}
/**
* Custom hook that checks if padding settings have been disabled.
*
* @param {string} name The name of the block.
*
* @return {boolean} Whether padding setting is disabled.
*/
function useIsPaddingDisabled() {
let {
name: blockName
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const isDisabled = !useSetting('spacing.padding');
const isInvalid = !useIsDimensionsSupportValid(blockName, 'padding');
return !hasPaddingSupport(blockName) || isDisabled || isInvalid;
}
/**
* Inspector control panel containing the padding related configuration
*
* @param {Object} props
*
* @return {WPElement} Padding edit element.
*/
function PaddingEdit(props) {
var _style$spacing, _style$spacing2;
const {
name: blockName,
attributes: {
style
},
setAttributes,
onMouseOver,
onMouseOut
} = props;
const spacingSizes = useSetting('spacing.spacingSizes');
const units = (0,external_wp_components_namespaceObject.__experimentalUseCustomUnits)({
availableUnits: useSetting('spacing.units') || ['%', 'px', 'em', 'rem', 'vw']
});
const sides = useCustomSides(blockName, 'padding');
const splitOnAxis = sides && sides.some(side => AXIAL_SIDES.includes(side));
if (useIsPaddingDisabled(props)) {
return null;
}
const onChange = next => {
const newStyle = { ...style,
spacing: { ...(style === null || style === void 0 ? void 0 : style.spacing),
padding: next
}
};
setAttributes({
style: utils_cleanEmptyObject(newStyle)
});
};
return external_wp_element_namespaceObject.Platform.select({
web: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (!spacingSizes || (spacingSizes === null || spacingSizes === void 0 ? void 0 : spacingSizes.length) === 0) && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalBoxControl, {
values: style === null || style === void 0 ? void 0 : (_style$spacing = style.spacing) === null || _style$spacing === void 0 ? void 0 : _style$spacing.padding,
onChange: onChange,
label: (0,external_wp_i18n_namespaceObject.__)('Padding'),
sides: sides,
units: units,
allowReset: false,
splitOnAxis: splitOnAxis,
onMouseOver: onMouseOver,
onMouseOut: onMouseOut
}), (spacingSizes === null || spacingSizes === void 0 ? void 0 : spacingSizes.length) > 0 && (0,external_wp_element_namespaceObject.createElement)(SpacingSizesControl, {
values: style === null || style === void 0 ? void 0 : (_style$spacing2 = style.spacing) === null || _style$spacing2 === void 0 ? void 0 : _style$spacing2.padding,
onChange: onChange,
label: (0,external_wp_i18n_namespaceObject.__)('Padding'),
sides: sides,
units: units,
allowReset: false,
splitOnAxis: splitOnAxis,
onMouseOver: onMouseOver,
onMouseOut: onMouseOut
})),
native: null
});
}
function PaddingVisualizer(_ref2) {
var _attributes$style, _attributes$style$spa;
let {
clientId,
attributes,
forceShow
} = _ref2;
const padding = attributes === null || attributes === void 0 ? void 0 : (_attributes$style = attributes.style) === null || _attributes$style === void 0 ? void 0 : (_attributes$style$spa = _attributes$style.spacing) === null || _attributes$style$spa === void 0 ? void 0 : _attributes$style$spa.padding;
const style = (0,external_wp_element_namespaceObject.useMemo)(() => {
return {
borderTopWidth: padding !== null && padding !== void 0 && padding.top ? getSpacingPresetCssVar(padding === null || padding === void 0 ? void 0 : padding.top) : 0,
borderRightWidth: padding !== null && padding !== void 0 && padding.right ? getSpacingPresetCssVar(padding === null || padding === void 0 ? void 0 : padding.right) : 0,
borderBottomWidth: padding !== null && padding !== void 0 && padding.bottom ? getSpacingPresetCssVar(padding === null || padding === void 0 ? void 0 : padding.bottom) : 0,
borderLeftWidth: padding !== null && padding !== void 0 && padding.left ? getSpacingPresetCssVar(padding === null || padding === void 0 ? void 0 : padding.left) : 0
};
}, [padding]);
const [isActive, setIsActive] = (0,external_wp_element_namespaceObject.useState)(false);
const valueRef = (0,external_wp_element_namespaceObject.useRef)(padding);
const timeoutRef = (0,external_wp_element_namespaceObject.useRef)();
const clearTimer = () => {
if (timeoutRef.current) {
window.clearTimeout(timeoutRef.current);
}
};
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (!external_wp_isShallowEqual_default()(padding, valueRef.current) && !forceShow) {
setIsActive(true);
valueRef.current = padding;
timeoutRef.current = setTimeout(() => {
setIsActive(false);
}, 400);
}
return () => {
setIsActive(false);
clearTimer();
};
}, [padding, forceShow]);
if (!isActive && !forceShow) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(block_popover, {
clientId: clientId,
__unstableCoverTarget: true,
__unstableRefreshSize: padding,
__unstablePopoverSlot: "block-toolbar",
shift: false
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor__padding-visualizer",
style: style
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/child-layout.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function helpText(selfStretch, parentLayout) {
const {
orientation = 'horizontal'
} = parentLayout;
if (selfStretch === 'fill') {
return (0,external_wp_i18n_namespaceObject.__)('Stretch to fill available space.');
}
if (selfStretch === 'fixed') {
if (orientation === 'horizontal') {
return (0,external_wp_i18n_namespaceObject.__)('Specify a fixed width.');
}
return (0,external_wp_i18n_namespaceObject.__)('Specify a fixed height.');
}
return (0,external_wp_i18n_namespaceObject.__)('Fit contents.');
}
/**
* Inspector controls containing the child layout related configuration.
*
* @param {Object} props Block props.
* @param {Object} props.attributes Block attributes.
* @param {Object} props.setAttributes Function to set block attributes.
* @param {Object} props.__unstableParentLayout
*
* @return {WPElement} child layout edit element.
*/
function ChildLayoutEdit(_ref) {
let {
attributes,
setAttributes,
__unstableParentLayout: parentLayout
} = _ref;
const {
style = {}
} = attributes;
const {
layout: childLayout = {}
} = style;
const {
selfStretch,
flexSize
} = childLayout;
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (selfStretch === 'fixed' && !flexSize) {
setAttributes({
style: { ...style,
layout: { ...childLayout,
selfStretch: 'fit'
}
}
});
}
}, []);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToggleGroupControl, {
__nextHasNoMarginBottom: true,
size: '__unstable-large',
label: childLayoutOrientation(parentLayout),
value: selfStretch || 'fit',
help: helpText(selfStretch, parentLayout),
onChange: value => {
const newFlexSize = value !== 'fixed' ? null : flexSize;
setAttributes({
style: { ...style,
layout: { ...childLayout,
selfStretch: value,
flexSize: newFlexSize
}
}
});
},
isBlock: true
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToggleGroupControlOption, {
key: 'fit',
value: 'fit',
label: (0,external_wp_i18n_namespaceObject.__)('Fit')
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToggleGroupControlOption, {
key: 'fill',
value: 'fill',
label: (0,external_wp_i18n_namespaceObject.__)('Fill')
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToggleGroupControlOption, {
key: 'fixed',
value: 'fixed',
label: (0,external_wp_i18n_namespaceObject.__)('Fixed')
})), selfStretch === 'fixed' && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalUnitControl, {
size: '__unstable-large',
onChange: value => {
setAttributes({
style: { ...style,
layout: { ...childLayout,
flexSize: value
}
}
});
},
value: flexSize
}));
}
/**
* Determines if there is child layout support.
*
* @param {Object} props Block Props object.
* @param {Object} props.__unstableParentLayout Parent layout.
*
* @return {boolean} Whether there is support.
*/
function hasChildLayoutSupport(_ref2) {
let {
__unstableParentLayout: parentLayout = {}
} = _ref2;
const {
type: parentLayoutType = 'default',
default: {
type: defaultParentLayoutType = 'default'
} = {},
allowSizingOnChildren = false
} = parentLayout;
const support = (defaultParentLayoutType === 'flex' || parentLayoutType === 'flex') && allowSizingOnChildren;
return support;
}
/**
* Checks if there is a current value in the child layout attributes.
*
* @param {Object} props Block props.
* @return {boolean} Whether or not the block has a child layout value set.
*/
function hasChildLayoutValue(props) {
var _props$attributes$sty;
return ((_props$attributes$sty = props.attributes.style) === null || _props$attributes$sty === void 0 ? void 0 : _props$attributes$sty.layout) !== undefined;
}
/**
* Resets the child layout attribute. This can be used when disabling
* child layout controls for a block via a progressive discovery panel.
*
* @param {Object} props Block props.
* @param {Object} props.attributes Block attributes.
* @param {Object} props.setAttributes Function to set block attributes.
*/
function resetChildLayout(_ref3) {
let {
attributes = {},
setAttributes
} = _ref3;
const {
style
} = attributes;
setAttributes({
style: { ...style,
layout: undefined
}
});
}
/**
* Custom hook that checks if child layout settings have been disabled.
*
* @param {Object} props Block props.
*
* @return {boolean} Whether the child layout setting is disabled.
*/
function useIsChildLayoutDisabled(props) {
const isDisabled = !useSetting('layout');
return !hasChildLayoutSupport(props) || isDisabled;
}
function childLayoutOrientation(parentLayout) {
const {
orientation = 'horizontal'
} = parentLayout;
return orientation === 'horizontal' ? (0,external_wp_i18n_namespaceObject.__)('Width') : (0,external_wp_i18n_namespaceObject.__)('Height');
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/dimensions.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const DIMENSIONS_SUPPORT_KEY = 'dimensions';
const SPACING_SUPPORT_KEY = 'spacing';
const dimensions_ALL_SIDES = ['top', 'right', 'bottom', 'left'];
const AXIAL_SIDES = ['vertical', 'horizontal'];
function useVisualizerMouseOver() {
const [isMouseOver, setIsMouseOver] = (0,external_wp_element_namespaceObject.useState)(false);
const {
hideBlockInterface,
showBlockInterface
} = unlock((0,external_wp_data_namespaceObject.useDispatch)(store));
const onMouseOver = e => {
e.stopPropagation();
hideBlockInterface();
setIsMouseOver(true);
};
const onMouseOut = e => {
e.stopPropagation();
showBlockInterface();
setIsMouseOver(false);
};
return {
isMouseOver,
onMouseOver,
onMouseOut
};
}
/**
* Inspector controls for dimensions support.
*
* @param {Object} props Block props.
*
* @return {WPElement} Inspector controls for dimensions and spacing support features.
*/
function DimensionsPanel(props) {
const isGapDisabled = useIsGapDisabled(props);
const isPaddingDisabled = useIsPaddingDisabled(props);
const isMarginDisabled = useIsMarginDisabled(props);
const isMinHeightDisabled = useIsMinHeightDisabled(props);
const isChildLayoutDisabled = useIsChildLayoutDisabled(props);
const isDisabled = useIsDimensionsDisabled(props);
const isSupported = hasDimensionsSupport(props);
const spacingSizes = useSetting('spacing.spacingSizes');
const paddingMouseOver = useVisualizerMouseOver();
const marginMouseOver = useVisualizerMouseOver();
if (isDisabled || !isSupported) {
return null;
}
const defaultDimensionsControls = (0,external_wp_blocks_namespaceObject.getBlockSupport)(props.name, [DIMENSIONS_SUPPORT_KEY, '__experimentalDefaultControls']);
const defaultSpacingControls = (0,external_wp_blocks_namespaceObject.getBlockSupport)(props.name, [SPACING_SUPPORT_KEY, '__experimentalDefaultControls']);
const createResetAllFilter = (attribute, featureSet) => newAttributes => {
var _newAttributes$style;
return { ...newAttributes,
style: { ...newAttributes.style,
[featureSet]: { ...((_newAttributes$style = newAttributes.style) === null || _newAttributes$style === void 0 ? void 0 : _newAttributes$style[featureSet]),
[attribute]: undefined
}
}
};
};
const spacingClassnames = classnames_default()({
'tools-panel-item-spacing': spacingSizes && spacingSizes.length > 0
});
const {
__unstableParentLayout: parentLayout
} = props;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(inspector_controls, {
group: "dimensions"
}, !isPaddingDisabled && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToolsPanelItem, {
className: spacingClassnames,
hasValue: () => hasPaddingValue(props),
label: (0,external_wp_i18n_namespaceObject.__)('Padding'),
onDeselect: () => resetPadding(props),
resetAllFilter: createResetAllFilter('padding', 'spacing'),
isShownByDefault: defaultSpacingControls === null || defaultSpacingControls === void 0 ? void 0 : defaultSpacingControls.padding,
panelId: props.clientId
}, (0,external_wp_element_namespaceObject.createElement)(PaddingEdit, _extends({
onMouseOver: paddingMouseOver.onMouseOver,
onMouseOut: paddingMouseOver.onMouseOut
}, props))), !isMarginDisabled && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToolsPanelItem, {
className: spacingClassnames,
hasValue: () => hasMarginValue(props),
label: (0,external_wp_i18n_namespaceObject.__)('Margin'),
onDeselect: () => resetMargin(props),
resetAllFilter: createResetAllFilter('margin', 'spacing'),
isShownByDefault: defaultSpacingControls === null || defaultSpacingControls === void 0 ? void 0 : defaultSpacingControls.margin,
panelId: props.clientId
}, (0,external_wp_element_namespaceObject.createElement)(MarginEdit, _extends({
onMouseOver: marginMouseOver.onMouseOver,
onMouseOut: marginMouseOver.onMouseOut
}, props))), !isGapDisabled && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToolsPanelItem, {
className: spacingClassnames,
hasValue: () => hasGapValue(props),
label: (0,external_wp_i18n_namespaceObject.__)('Block spacing'),
onDeselect: () => resetGap(props),
resetAllFilter: createResetAllFilter('blockGap', 'spacing'),
isShownByDefault: defaultSpacingControls === null || defaultSpacingControls === void 0 ? void 0 : defaultSpacingControls.blockGap,
panelId: props.clientId
}, (0,external_wp_element_namespaceObject.createElement)(GapEdit, props)), !isMinHeightDisabled && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToolsPanelItem, {
hasValue: () => hasMinHeightValue(props),
label: (0,external_wp_i18n_namespaceObject.__)('Min. height'),
onDeselect: () => resetMinHeight(props),
resetAllFilter: createResetAllFilter('minHeight', 'dimensions'),
isShownByDefault: defaultDimensionsControls === null || defaultDimensionsControls === void 0 ? void 0 : defaultDimensionsControls.minHeight,
panelId: props.clientId
}, (0,external_wp_element_namespaceObject.createElement)(MinHeightEdit, props)), !isChildLayoutDisabled && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalVStack, {
as: external_wp_components_namespaceObject.__experimentalToolsPanelItem,
spacing: 2,
hasValue: () => hasChildLayoutValue(props),
label: childLayoutOrientation(parentLayout),
onDeselect: () => resetChildLayout(props),
resetAllFilter: createResetAllFilter('selfStretch', 'layout'),
isShownByDefault: false,
panelId: props.clientId
}, (0,external_wp_element_namespaceObject.createElement)(ChildLayoutEdit, props))), !isPaddingDisabled && (0,external_wp_element_namespaceObject.createElement)(PaddingVisualizer, _extends({
forceShow: paddingMouseOver.isMouseOver
}, props)), !isMarginDisabled && (0,external_wp_element_namespaceObject.createElement)(MarginVisualizer, _extends({
forceShow: marginMouseOver.isMouseOver
}, props)));
}
/**
* Determine whether there is dimensions related block support.
*
* @param {Object} props Block props.
*
* @return {boolean} Whether there is support.
*/
function hasDimensionsSupport(props) {
if (external_wp_element_namespaceObject.Platform.OS !== 'web') {
return false;
}
const {
name: blockName
} = props;
return hasGapSupport(blockName) || hasMinHeightSupport(blockName) || hasPaddingSupport(blockName) || hasMarginSupport(blockName) || hasChildLayoutSupport(props);
}
/**
* Determines whether dimensions support has been disabled.
*
* @param {Object} props Block properties.
*
* @return {boolean} If spacing support is completely disabled.
*/
const useIsDimensionsDisabled = function () {
let props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const gapDisabled = useIsGapDisabled(props);
const minHeightDisabled = useIsMinHeightDisabled(props);
const paddingDisabled = useIsPaddingDisabled(props);
const marginDisabled = useIsMarginDisabled(props);
const childLayoutDisabled = useIsChildLayoutDisabled(props);
return gapDisabled && minHeightDisabled && paddingDisabled && marginDisabled && childLayoutDisabled;
};
/**
* Custom hook to retrieve which padding/margin/blockGap is supported
* e.g. top, right, bottom or left.
*
* Sides are opted into by default. It is only if a specific side is set to
* false that it is omitted.
*
* @param {string} blockName Block name.
* @param {string} feature The feature custom sides relate to e.g. padding or margins.
*
* @return {string[] | undefined} Strings representing the custom sides available.
*/
function useCustomSides(blockName, feature) {
var _support$feature;
const support = (0,external_wp_blocks_namespaceObject.getBlockSupport)(blockName, SPACING_SUPPORT_KEY); // Skip when setting is boolean as theme isn't setting arbitrary sides.
if (!support || typeof support[feature] === 'boolean') {
return;
} // Return if the setting is an array of sides (e.g. `[ 'top', 'bottom' ]`).
if (Array.isArray(support[feature])) {
return support[feature];
} // Finally, attempt to return `.sides` if the setting is an object.
if ((_support$feature = support[feature]) !== null && _support$feature !== void 0 && _support$feature.sides) {
return support[feature].sides;
}
}
/**
* Custom hook to determine whether the sides configured in the
* block support are valid. A dimension property cannot declare
* support for a mix of axial and individual sides.
*
* @param {string} blockName Block name.
* @param {string} feature The feature custom sides relate to e.g. padding or margins.
*
* @return {boolean} If the feature has a valid configuration of sides.
*/
function useIsDimensionsSupportValid(blockName, feature) {
const sides = useCustomSides(blockName, feature);
if (sides && sides.some(side => dimensions_ALL_SIDES.includes(side)) && sides.some(side => AXIAL_SIDES.includes(side))) {
// eslint-disable-next-line no-console
console.warn(`The ${feature} support for the "${blockName}" block can not be configured to support both axial and arbitrary sides.`);
return false;
}
return true;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/gap.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Determines if there is gap support.
*
* @param {string|Object} blockType Block name or Block Type object.
* @return {boolean} Whether there is support.
*/
function hasGapSupport(blockType) {
const support = (0,external_wp_blocks_namespaceObject.getBlockSupport)(blockType, SPACING_SUPPORT_KEY);
return !!(true === support || support !== null && support !== void 0 && support.blockGap);
}
/**
* Checks if there is a current value in the gap block support attributes.
*
* @param {Object} props Block props.
* @return {boolean} Whether or not the block has a gap value set.
*/
function hasGapValue(props) {
var _props$attributes$sty, _props$attributes$sty2;
return ((_props$attributes$sty = props.attributes.style) === null || _props$attributes$sty === void 0 ? void 0 : (_props$attributes$sty2 = _props$attributes$sty.spacing) === null || _props$attributes$sty2 === void 0 ? void 0 : _props$attributes$sty2.blockGap) !== undefined;
}
/**
* Returns a BoxControl object value from a given blockGap style value.
* The string check is for backwards compatibility before Gutenberg supported
* split gap values (row and column) and the value was a string n + unit.
*
* @param {string? | Object?} blockGapValue A block gap string or axial object value, e.g., '10px' or { top: '10px', left: '10px'}.
* @return {Object|null} A value to pass to the BoxControl component.
*/
function getGapBoxControlValueFromStyle(blockGapValue) {
if (!blockGapValue) {
return null;
}
const isValueString = typeof blockGapValue === 'string';
return {
top: isValueString ? blockGapValue : blockGapValue === null || blockGapValue === void 0 ? void 0 : blockGapValue.top,
left: isValueString ? blockGapValue : blockGapValue === null || blockGapValue === void 0 ? void 0 : blockGapValue.left
};
}
/**
* Returns a CSS value for the `gap` property from a given blockGap style.
*
* @param {string? | Object?} blockGapValue A block gap string or axial object value, e.g., '10px' or { top: '10px', left: '10px'}.
* @param {string?} defaultValue A default gap value.
* @return {string|null} The concatenated gap value (row and column).
*/
function getGapCSSValue(blockGapValue) {
let defaultValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '0';
const blockGapBoxControlValue = getGapBoxControlValueFromStyle(blockGapValue);
if (!blockGapBoxControlValue) {
return null;
}
const row = getSpacingPresetCssVar(blockGapBoxControlValue === null || blockGapBoxControlValue === void 0 ? void 0 : blockGapBoxControlValue.top) || defaultValue;
const column = getSpacingPresetCssVar(blockGapBoxControlValue === null || blockGapBoxControlValue === void 0 ? void 0 : blockGapBoxControlValue.left) || defaultValue;
return row === column ? row : `${row} ${column}`;
}
/**
* Resets the gap block support attribute. This can be used when disabling
* the gap support controls for a block via a progressive discovery panel.
*
* @param {Object} props Block props.
* @param {Object} props.attributes Block's attributes.
* @param {Object} props.setAttributes Function to set block's attributes.
*/
function resetGap(_ref) {
let {
attributes = {},
setAttributes
} = _ref;
const {
style
} = attributes;
setAttributes({
style: { ...style,
spacing: { ...(style === null || style === void 0 ? void 0 : style.spacing),
blockGap: undefined
}
}
});
}
/**
* Custom hook that checks if gap settings have been disabled.
*
* @param {string} name The name of the block.
* @return {boolean} Whether the gap setting is disabled.
*/
function useIsGapDisabled() {
let {
name: blockName
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const isDisabled = !useSetting('spacing.blockGap');
return !hasGapSupport(blockName) || isDisabled;
}
/**
* Inspector control panel containing the gap related configuration
*
* @param {Object} props
*
* @return {WPElement} Gap edit element.
*/
function GapEdit(props) {
var _style$spacing;
const {
clientId,
attributes: {
style
},
name: blockName,
setAttributes
} = props;
const spacingSizes = useSetting('spacing.spacingSizes');
const units = (0,external_wp_components_namespaceObject.__experimentalUseCustomUnits)({
availableUnits: useSetting('spacing.units') || ['%', 'px', 'em', 'rem', 'vw']
});
const sides = useCustomSides(blockName, 'blockGap');
const ref = useBlockRef(clientId);
if (useIsGapDisabled(props)) {
return null;
}
const splitOnAxis = sides && sides.some(side => AXIAL_SIDES.includes(side));
const onChange = next => {
var _window;
let blockGap = next; // If splitOnAxis activated we need to return a BoxControl object to the BoxControl component.
if (!!next && splitOnAxis) {
blockGap = { ...getGapBoxControlValueFromStyle(next)
};
} else if (next !== null && next !== void 0 && next.hasOwnProperty('top')) {
// If splitOnAxis is not enabled, treat the 'top' value as the shorthand gap value.
blockGap = next.top;
}
const newStyle = { ...style,
spacing: { ...(style === null || style === void 0 ? void 0 : style.spacing),
blockGap
}
};
setAttributes({
style: utils_cleanEmptyObject(newStyle)
}); // In Safari, changing the `gap` CSS value on its own will not trigger the layout
// to be recalculated / re-rendered. To force the updated gap to re-render, here
// we replace the block's node with itself.
const isSafari = ((_window = window) === null || _window === void 0 ? void 0 : _window.navigator.userAgent) && window.navigator.userAgent.includes('Safari') && !window.navigator.userAgent.includes('Chrome ') && !window.navigator.userAgent.includes('Chromium ');
if (ref.current && isSafari) {
var _ref$current$parentNo;
(_ref$current$parentNo = ref.current.parentNode) === null || _ref$current$parentNo === void 0 ? void 0 : _ref$current$parentNo.replaceChild(ref.current, ref.current);
}
};
const gapValue = getGapBoxControlValueFromStyle(style === null || style === void 0 ? void 0 : (_style$spacing = style.spacing) === null || _style$spacing === void 0 ? void 0 : _style$spacing.blockGap); // The BoxControl component expects a full complement of side values.
// Gap row and column values translate to top/bottom and left/right respectively.
const boxControlGapValue = splitOnAxis ? { ...gapValue,
right: gapValue === null || gapValue === void 0 ? void 0 : gapValue.left,
bottom: gapValue === null || gapValue === void 0 ? void 0 : gapValue.top
} : {
top: gapValue === null || gapValue === void 0 ? void 0 : gapValue.top
};
return external_wp_element_namespaceObject.Platform.select({
web: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (!spacingSizes || (spacingSizes === null || spacingSizes === void 0 ? void 0 : spacingSizes.length) === 0) && (splitOnAxis ? (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalBoxControl, {
label: (0,external_wp_i18n_namespaceObject.__)('Block spacing'),
min: 0,
onChange: onChange,
units: units,
sides: sides,
values: boxControlGapValue,
allowReset: false,
splitOnAxis: splitOnAxis
}) : (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalUnitControl, {
label: (0,external_wp_i18n_namespaceObject.__)('Block spacing'),
__unstableInputWidth: "80px",
min: 0,
onChange: onChange,
units: units // Default to `row` for combined values.
,
value: boxControlGapValue
})), (spacingSizes === null || spacingSizes === void 0 ? void 0 : spacingSizes.length) > 0 && (0,external_wp_element_namespaceObject.createElement)(SpacingSizesControl, {
values: boxControlGapValue,
onChange: onChange,
label: (0,external_wp_i18n_namespaceObject.__)('Block spacing'),
sides: splitOnAxis ? sides : ['top'] // Use 'top' as the shorthand property in non-axial configurations.
,
units: units,
allowReset: false,
splitOnAxis: splitOnAxis
})),
native: null
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-vertical-alignment-control/icons.js
/**
* WordPress dependencies
*/
const alignBottom = (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Path, {
d: "M15 4H9v11h6V4zM4 18.5V20h16v-1.5H4z"
}));
const alignCenter = (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Path, {
d: "M20 11h-5V4H9v7H4v1.5h5V20h6v-7.5h5z"
}));
const alignTop = (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Path, {
d: "M9 20h6V9H9v11zM4 4v1.5h16V4H4z"
}));
const alignStretch = (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Path, {
d: "M4 4L20 4L20 5.5L4 5.5L4 4ZM10 7L14 7L14 17L10 17L10 7ZM20 18.5L4 18.5L4 20L20 20L20 18.5Z"
}));
const spaceBetween = (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Path, {
d: "M7 4H17V8L7 8V4ZM7 16L17 16V20L7 20V16ZM20 11.25H4V12.75H20V11.25Z"
}));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-vertical-alignment-control/ui.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const BLOCK_ALIGNMENTS_CONTROLS = {
top: {
icon: alignTop,
title: (0,external_wp_i18n_namespaceObject._x)('Align top', 'Block vertical alignment setting')
},
center: {
icon: alignCenter,
title: (0,external_wp_i18n_namespaceObject._x)('Align middle', 'Block vertical alignment setting')
},
bottom: {
icon: alignBottom,
title: (0,external_wp_i18n_namespaceObject._x)('Align bottom', 'Block vertical alignment setting')
},
stretch: {
icon: alignStretch,
title: (0,external_wp_i18n_namespaceObject._x)('Stretch to fill', 'Block vertical alignment setting')
},
'space-between': {
icon: spaceBetween,
title: (0,external_wp_i18n_namespaceObject._x)('Space between', 'Block vertical alignment setting')
}
};
const DEFAULT_CONTROLS = ['top', 'center', 'bottom'];
const DEFAULT_CONTROL = 'top';
function BlockVerticalAlignmentUI(_ref) {
let {
value,
onChange,
controls = DEFAULT_CONTROLS,
isCollapsed = true,
isToolbar
} = _ref;
function applyOrUnset(align) {
return () => onChange(value === align ? undefined : align);
}
const activeAlignment = BLOCK_ALIGNMENTS_CONTROLS[value];
const defaultAlignmentControl = BLOCK_ALIGNMENTS_CONTROLS[DEFAULT_CONTROL];
const UIComponent = isToolbar ? external_wp_components_namespaceObject.ToolbarGroup : external_wp_components_namespaceObject.ToolbarDropdownMenu;
const extraProps = isToolbar ? {
isCollapsed
} : {
popoverProps: {
variant: 'toolbar'
}
};
return (0,external_wp_element_namespaceObject.createElement)(UIComponent, _extends({
icon: activeAlignment ? activeAlignment.icon : defaultAlignmentControl.icon,
label: (0,external_wp_i18n_namespaceObject._x)('Change vertical alignment', 'Block vertical alignment setting label'),
controls: controls.map(control => {
return { ...BLOCK_ALIGNMENTS_CONTROLS[control],
isActive: value === control,
role: isCollapsed ? 'menuitemradio' : undefined,
onClick: applyOrUnset(control)
};
})
}, extraProps));
}
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/block-vertical-alignment-toolbar/README.md
*/
/* harmony default export */ var ui = (BlockVerticalAlignmentUI);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-vertical-alignment-control/index.js
/**
* Internal dependencies
*/
const BlockVerticalAlignmentControl = props => {
return (0,external_wp_element_namespaceObject.createElement)(ui, _extends({}, props, {
isToolbar: false
}));
};
const BlockVerticalAlignmentToolbar = props => {
return (0,external_wp_element_namespaceObject.createElement)(ui, _extends({}, props, {
isToolbar: true
}));
};
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/block-vertical-alignment-control/README.md
*/
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/justify-content-control/ui.js
/**
* WordPress dependencies
*/
const icons = {
left: justify_left,
center: justify_center,
right: justify_right,
'space-between': justify_space_between,
stretch: justify_stretch
};
function JustifyContentUI(_ref) {
let {
allowedControls = ['left', 'center', 'right', 'space-between'],
isCollapsed = true,
onChange,
value,
popoverProps,
isToolbar
} = _ref;
// If the control is already selected we want a click
// again on the control to deselect the item, so we
// call onChange( undefined )
const handleClick = next => {
if (next === value) {
onChange(undefined);
} else {
onChange(next);
}
};
const icon = value ? icons[value] : icons.left;
const allControls = [{
name: 'left',
icon: justify_left,
title: (0,external_wp_i18n_namespaceObject.__)('Justify items left'),
isActive: 'left' === value,
onClick: () => handleClick('left')
}, {
name: 'center',
icon: justify_center,
title: (0,external_wp_i18n_namespaceObject.__)('Justify items center'),
isActive: 'center' === value,
onClick: () => handleClick('center')
}, {
name: 'right',
icon: justify_right,
title: (0,external_wp_i18n_namespaceObject.__)('Justify items right'),
isActive: 'right' === value,
onClick: () => handleClick('right')
}, {
name: 'space-between',
icon: justify_space_between,
title: (0,external_wp_i18n_namespaceObject.__)('Space between items'),
isActive: 'space-between' === value,
onClick: () => handleClick('space-between')
}, {
name: 'stretch',
icon: justify_stretch,
title: (0,external_wp_i18n_namespaceObject.__)('Stretch items'),
isActive: 'stretch' === value,
onClick: () => handleClick('stretch')
}];
const UIComponent = isToolbar ? external_wp_components_namespaceObject.ToolbarGroup : external_wp_components_namespaceObject.ToolbarDropdownMenu;
const extraProps = isToolbar ? {
isCollapsed
} : {};
return (0,external_wp_element_namespaceObject.createElement)(UIComponent, _extends({
icon: icon,
popoverProps: popoverProps,
label: (0,external_wp_i18n_namespaceObject.__)('Change items justification'),
controls: allControls.filter(elem => allowedControls.includes(elem.name))
}, extraProps));
}
/* harmony default export */ var justify_content_control_ui = (JustifyContentUI);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/justify-content-control/index.js
/**
* Internal dependencies
*/
const JustifyContentControl = props => {
return (0,external_wp_element_namespaceObject.createElement)(justify_content_control_ui, _extends({}, props, {
isToolbar: false
}));
};
const JustifyToolbar = props => {
return (0,external_wp_element_namespaceObject.createElement)(justify_content_control_ui, _extends({}, props, {
isToolbar: true
}));
};
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/justify-content-control/README.md
*/
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/layouts/flex.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
// Used with the default, horizontal flex orientation.
const justifyContentMap = {
left: 'flex-start',
right: 'flex-end',
center: 'center',
'space-between': 'space-between'
}; // Used with the vertical (column) flex orientation.
const alignItemsMap = {
left: 'flex-start',
right: 'flex-end',
center: 'center',
stretch: 'stretch'
};
const verticalAlignmentMap = {
top: 'flex-start',
center: 'center',
bottom: 'flex-end',
stretch: 'stretch',
'space-between': 'space-between'
};
const flexWrapOptions = ['wrap', 'nowrap'];
/* harmony default export */ var flex = ({
name: 'flex',
label: (0,external_wp_i18n_namespaceObject.__)('Flex'),
inspectorControls: function FlexLayoutInspectorControls(_ref) {
let {
layout = {},
onChange,
layoutBlockSupport = {}
} = _ref;
const {
allowOrientation = true
} = layoutBlockSupport;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Flex, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexItem, null, (0,external_wp_element_namespaceObject.createElement)(FlexLayoutJustifyContentControl, {
layout: layout,
onChange: onChange
})), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexItem, null, allowOrientation && (0,external_wp_element_namespaceObject.createElement)(OrientationControl, {
layout: layout,
onChange: onChange
}))), (0,external_wp_element_namespaceObject.createElement)(FlexWrapControl, {
layout: layout,
onChange: onChange
}));
},
toolBarControls: function FlexLayoutToolbarControls(_ref2) {
let {
layout = {},
onChange,
layoutBlockSupport
} = _ref2;
if (layoutBlockSupport !== null && layoutBlockSupport !== void 0 && layoutBlockSupport.allowSwitching) {
return null;
}
const {
allowVerticalAlignment = true
} = layoutBlockSupport;
return (0,external_wp_element_namespaceObject.createElement)(block_controls, {
group: "block",
__experimentalShareWithChildBlocks: true
}, (0,external_wp_element_namespaceObject.createElement)(FlexLayoutJustifyContentControl, {
layout: layout,
onChange: onChange,
isToolbar: true
}), allowVerticalAlignment && (0,external_wp_element_namespaceObject.createElement)(FlexLayoutVerticalAlignmentControl, {
layout: layout,
onChange: onChange,
isToolbar: true
}));
},
getLayoutStyle: function getLayoutStyle(_ref3) {
var _style$spacing, _style$spacing2;
let {
selector,
layout,
style,
blockName,
hasBlockGapSupport,
layoutDefinitions
} = _ref3;
const {
orientation = 'horizontal'
} = layout; // If a block's block.json skips serialization for spacing or spacing.blockGap,
// don't apply the user-defined value to the styles.
const blockGapValue = style !== null && style !== void 0 && (_style$spacing = style.spacing) !== null && _style$spacing !== void 0 && _style$spacing.blockGap && !shouldSkipSerialization(blockName, 'spacing', 'blockGap') ? getGapCSSValue(style === null || style === void 0 ? void 0 : (_style$spacing2 = style.spacing) === null || _style$spacing2 === void 0 ? void 0 : _style$spacing2.blockGap, '0.5em') : undefined;
const justifyContent = justifyContentMap[layout.justifyContent];
const flexWrap = flexWrapOptions.includes(layout.flexWrap) ? layout.flexWrap : 'wrap';
const verticalAlignment = verticalAlignmentMap[layout.verticalAlignment];
const alignItems = alignItemsMap[layout.justifyContent] || alignItemsMap.left;
let output = '';
const rules = [];
if (flexWrap && flexWrap !== 'wrap') {
rules.push(`flex-wrap: ${flexWrap}`);
}
if (orientation === 'horizontal') {
if (verticalAlignment) {
rules.push(`align-items: ${verticalAlignment}`);
}
if (justifyContent) {
rules.push(`justify-content: ${justifyContent}`);
}
} else {
if (verticalAlignment) {
rules.push(`justify-content: ${verticalAlignment}`);
}
rules.push('flex-direction: column');
rules.push(`align-items: ${alignItems}`);
}
if (rules.length) {
output = `${appendSelectors(selector)} {
${rules.join('; ')};
}`;
} // Output blockGap styles based on rules contained in layout definitions in theme.json.
if (hasBlockGapSupport && blockGapValue) {
output += getBlockGapCSS(selector, layoutDefinitions, 'flex', blockGapValue);
}
return output;
},
getOrientation(layout) {
const {
orientation = 'horizontal'
} = layout;
return orientation;
},
getAlignments() {
return [];
}
});
function FlexLayoutVerticalAlignmentControl(_ref4) {
let {
layout,
onChange,
isToolbar = false
} = _ref4;
const {
orientation = 'horizontal'
} = layout;
const defaultVerticalAlignment = orientation === 'horizontal' ? verticalAlignmentMap.center : verticalAlignmentMap.top;
const {
verticalAlignment = defaultVerticalAlignment
} = layout;
const onVerticalAlignmentChange = value => {
onChange({ ...layout,
verticalAlignment: value
});
};
if (isToolbar) {
return (0,external_wp_element_namespaceObject.createElement)(BlockVerticalAlignmentControl, {
onChange: onVerticalAlignmentChange,
value: verticalAlignment,
controls: orientation === 'horizontal' ? ['top', 'center', 'bottom', 'stretch'] : ['top', 'center', 'bottom', 'space-between']
});
}
const verticalAlignmentOptions = [{
value: 'flex-start',
label: (0,external_wp_i18n_namespaceObject.__)('Align items top')
}, {
value: 'center',
label: (0,external_wp_i18n_namespaceObject.__)('Align items center')
}, {
value: 'flex-end',
label: (0,external_wp_i18n_namespaceObject.__)('Align items bottom')
}];
return (0,external_wp_element_namespaceObject.createElement)("fieldset", {
className: "block-editor-hooks__flex-layout-vertical-alignment-control"
}, (0,external_wp_element_namespaceObject.createElement)("legend", null, (0,external_wp_i18n_namespaceObject.__)('Vertical alignment')), (0,external_wp_element_namespaceObject.createElement)("div", null, verticalAlignmentOptions.map((value, icon, label) => {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
key: value,
label: label,
icon: icon,
isPressed: verticalAlignment === value,
onClick: () => onVerticalAlignmentChange(value)
});
})));
}
function FlexLayoutJustifyContentControl(_ref5) {
let {
layout,
onChange,
isToolbar = false
} = _ref5;
const {
justifyContent = 'left',
orientation = 'horizontal'
} = layout;
const onJustificationChange = value => {
onChange({ ...layout,
justifyContent: value
});
};
const allowedControls = ['left', 'center', 'right'];
if (orientation === 'horizontal') {
allowedControls.push('space-between');
} else {
allowedControls.push('stretch');
}
if (isToolbar) {
return (0,external_wp_element_namespaceObject.createElement)(JustifyContentControl, {
allowedControls: allowedControls,
value: justifyContent,
onChange: onJustificationChange,
popoverProps: {
position: 'bottom right',
variant: 'toolbar'
}
});
}
const justificationOptions = [{
value: 'left',
icon: justify_left,
label: (0,external_wp_i18n_namespaceObject.__)('Justify items left')
}, {
value: 'center',
icon: justify_center,
label: (0,external_wp_i18n_namespaceObject.__)('Justify items center')
}, {
value: 'right',
icon: justify_right,
label: (0,external_wp_i18n_namespaceObject.__)('Justify items right')
}];
if (orientation === 'horizontal') {
justificationOptions.push({
value: 'space-between',
icon: justify_space_between,
label: (0,external_wp_i18n_namespaceObject.__)('Space between items')
});
} else {
justificationOptions.push({
value: 'stretch',
icon: justify_stretch,
label: (0,external_wp_i18n_namespaceObject.__)('Stretch items')
});
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToggleGroupControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Justification'),
value: justifyContent,
onChange: onJustificationChange,
className: "block-editor-hooks__flex-layout-justification-controls"
}, justificationOptions.map(_ref6 => {
let {
value,
icon,
label
} = _ref6;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToggleGroupControlOptionIcon, {
key: value,
value: value,
icon: icon,
label: label
});
}));
}
function FlexWrapControl(_ref7) {
let {
layout,
onChange
} = _ref7;
const {
flexWrap = 'wrap'
} = layout;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToggleControl, {
label: (0,external_wp_i18n_namespaceObject.__)('Allow to wrap to multiple lines'),
onChange: value => {
onChange({ ...layout,
flexWrap: value ? 'wrap' : 'nowrap'
});
},
checked: flexWrap === 'wrap'
});
}
function OrientationControl(_ref8) {
let {
layout,
onChange
} = _ref8;
const {
orientation = 'horizontal',
verticalAlignment,
justifyContent
} = layout;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToggleGroupControl, {
__nextHasNoMarginBottom: true,
className: "block-editor-hooks__flex-layout-orientation-controls",
label: (0,external_wp_i18n_namespaceObject.__)('Orientation'),
value: orientation,
onChange: value => {
// Make sure the vertical alignment and justification are compatible with the new orientation.
let newVerticalAlignment = verticalAlignment;
let newJustification = justifyContent;
if (value === 'horizontal') {
if (verticalAlignment === 'space-between') {
newVerticalAlignment = 'center';
}
if (justifyContent === 'stretch') {
newJustification = 'left';
}
} else {
if (verticalAlignment === 'stretch') {
newVerticalAlignment = 'top';
}
if (justifyContent === 'space-between') {
newJustification = 'left';
}
}
return onChange({ ...layout,
orientation: value,
verticalAlignment: newVerticalAlignment,
justifyContent: newJustification
});
}
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToggleGroupControlOptionIcon, {
icon: arrow_right,
value: 'horizontal',
label: (0,external_wp_i18n_namespaceObject.__)('Horizontal')
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToggleGroupControlOptionIcon, {
icon: arrow_down,
value: 'vertical',
label: (0,external_wp_i18n_namespaceObject.__)('Vertical')
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/layouts/flow.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/* harmony default export */ var flow = ({
name: 'default',
label: (0,external_wp_i18n_namespaceObject.__)('Flow'),
inspectorControls: function DefaultLayoutInspectorControls() {
return null;
},
toolBarControls: function DefaultLayoutToolbarControls() {
return null;
},
getLayoutStyle: function getLayoutStyle(_ref) {
var _style$spacing;
let {
selector,
style,
blockName,
hasBlockGapSupport,
layoutDefinitions
} = _ref;
const blockGapStyleValue = getGapCSSValue(style === null || style === void 0 ? void 0 : (_style$spacing = style.spacing) === null || _style$spacing === void 0 ? void 0 : _style$spacing.blockGap); // If a block's block.json skips serialization for spacing or
// spacing.blockGap, don't apply the user-defined value to the styles.
let blockGapValue = '';
if (!shouldSkipSerialization(blockName, 'spacing', 'blockGap')) {
// If an object is provided only use the 'top' value for this kind of gap.
if (blockGapStyleValue !== null && blockGapStyleValue !== void 0 && blockGapStyleValue.top) {
blockGapValue = getGapCSSValue(blockGapStyleValue === null || blockGapStyleValue === void 0 ? void 0 : blockGapStyleValue.top);
} else if (typeof blockGapStyleValue === 'string') {
blockGapValue = getGapCSSValue(blockGapStyleValue);
}
}
let output = ''; // Output blockGap styles based on rules contained in layout definitions in theme.json.
if (hasBlockGapSupport && blockGapValue) {
output += getBlockGapCSS(selector, layoutDefinitions, 'default', blockGapValue);
}
return output;
},
getOrientation() {
return 'vertical';
},
getAlignments(layout, isBlockBasedTheme) {
const alignmentInfo = getAlignmentsInfo(layout);
if (layout.alignments !== undefined) {
if (!layout.alignments.includes('none')) {
layout.alignments.unshift('none');
}
return layout.alignments.map(alignment => ({
name: alignment,
info: alignmentInfo[alignment]
}));
}
const alignments = [{
name: 'left'
}, {
name: 'center'
}, {
name: 'right'
}]; // This is for backwards compatibility with hybrid themes.
if (!isBlockBasedTheme) {
const {
contentSize,
wideSize
} = layout;
if (contentSize) {
alignments.unshift({
name: 'full'
});
}
if (wideSize) {
alignments.unshift({
name: 'wide',
info: alignmentInfo.wide
});
}
}
alignments.unshift({
name: 'none',
info: alignmentInfo.none
});
return alignments;
}
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/icon/index.js
/**
* WordPress dependencies
*/
/** @typedef {{icon: JSX.Element, size?: number} & import('@wordpress/primitives').SVGProps} IconProps */
/**
* Return an SVG icon.
*
* @param {IconProps} props icon is the SVG component to render
* size is a number specifiying the icon size in pixels
* Other props will be passed to wrapped SVG component
*
* @return {JSX.Element} Icon component
*/
function Icon(_ref) {
let {
icon,
size = 24,
...props
} = _ref;
return (0,external_wp_element_namespaceObject.cloneElement)(icon, {
width: size,
height: size,
...props
});
}
/* harmony default export */ var build_module_icon = (Icon);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/position-center.js
/**
* WordPress dependencies
*/
const positionCenter = (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: "M7 9v6h10V9H7zM5 19.8h14v-1.5H5v1.5zM5 4.3v1.5h14V4.3H5z"
}));
/* harmony default export */ var position_center = (positionCenter);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/stretch-wide.js
/**
* WordPress dependencies
*/
const stretchWide = (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: "M5 9v6h14V9H5zm11-4.8H8v1.5h8V4.2zM8 19.8h8v-1.5H8v1.5z"
}));
/* harmony default export */ var stretch_wide = (stretchWide);
;// CONCATENATED MODULE: external ["wp","styleEngine"]
var external_wp_styleEngine_namespaceObject = window["wp"]["styleEngine"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/layouts/constrained.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/* harmony default export */ var constrained = ({
name: 'constrained',
label: (0,external_wp_i18n_namespaceObject.__)('Constrained'),
inspectorControls: function DefaultLayoutInspectorControls(_ref) {
let {
layout,
onChange
} = _ref;
const {
wideSize,
contentSize,
justifyContent = 'center'
} = layout;
const onJustificationChange = value => {
onChange({ ...layout,
justifyContent: value
});
};
const justificationOptions = [{
value: 'left',
icon: justify_left,
label: (0,external_wp_i18n_namespaceObject.__)('Justify items left')
}, {
value: 'center',
icon: justify_center,
label: (0,external_wp_i18n_namespaceObject.__)('Justify items center')
}, {
value: 'right',
icon: justify_right,
label: (0,external_wp_i18n_namespaceObject.__)('Justify items right')
}];
const units = (0,external_wp_components_namespaceObject.__experimentalUseCustomUnits)({
availableUnits: useSetting('spacing.units') || ['%', 'px', 'em', 'rem', 'vw']
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-hooks__layout-controls"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-hooks__layout-controls-unit"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalUnitControl, {
className: "block-editor-hooks__layout-controls-unit-input",
label: (0,external_wp_i18n_namespaceObject.__)('Content'),
labelPosition: "top",
__unstableInputWidth: "80px",
value: contentSize || wideSize || '',
onChange: nextWidth => {
nextWidth = 0 > parseFloat(nextWidth) ? '0' : nextWidth;
onChange({ ...layout,
contentSize: nextWidth
});
},
units: units
}), (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: position_center
})), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-hooks__layout-controls-unit"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalUnitControl, {
className: "block-editor-hooks__layout-controls-unit-input",
label: (0,external_wp_i18n_namespaceObject.__)('Wide'),
labelPosition: "top",
__unstableInputWidth: "80px",
value: wideSize || contentSize || '',
onChange: nextWidth => {
nextWidth = 0 > parseFloat(nextWidth) ? '0' : nextWidth;
onChange({ ...layout,
wideSize: nextWidth
});
},
units: units
}), (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: stretch_wide
}))), (0,external_wp_element_namespaceObject.createElement)("p", {
className: "block-editor-hooks__layout-controls-helptext"
}, (0,external_wp_i18n_namespaceObject.__)('Customize the width for all elements that are assigned to the center or wide columns.')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToggleGroupControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Justification'),
value: justifyContent,
onChange: onJustificationChange
}, justificationOptions.map(_ref2 => {
let {
value,
icon,
label
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToggleGroupControlOptionIcon, {
key: value,
value: value,
icon: icon,
label: label
});
})));
},
toolBarControls: function DefaultLayoutToolbarControls() {
return null;
},
getLayoutStyle: function getLayoutStyle(_ref3) {
var _style$spacing, _style$spacing2;
let {
selector,
layout = {},
style,
blockName,
hasBlockGapSupport,
layoutDefinitions
} = _ref3;
const {
contentSize,
wideSize,
justifyContent
} = layout;
const blockGapStyleValue = getGapCSSValue(style === null || style === void 0 ? void 0 : (_style$spacing = style.spacing) === null || _style$spacing === void 0 ? void 0 : _style$spacing.blockGap); // If a block's block.json skips serialization for spacing or
// spacing.blockGap, don't apply the user-defined value to the styles.
let blockGapValue = '';
if (!shouldSkipSerialization(blockName, 'spacing', 'blockGap')) {
// If an object is provided only use the 'top' value for this kind of gap.
if (blockGapStyleValue !== null && blockGapStyleValue !== void 0 && blockGapStyleValue.top) {
blockGapValue = getGapCSSValue(blockGapStyleValue === null || blockGapStyleValue === void 0 ? void 0 : blockGapStyleValue.top);
} else if (typeof blockGapStyleValue === 'string') {
blockGapValue = getGapCSSValue(blockGapStyleValue);
}
}
const marginLeft = justifyContent === 'left' ? '0 !important' : 'auto !important';
const marginRight = justifyContent === 'right' ? '0 !important' : 'auto !important';
let output = !!contentSize || !!wideSize ? `
${appendSelectors(selector, '> :where(:not(.alignleft):not(.alignright):not(.alignfull))')} {
max-width: ${contentSize !== null && contentSize !== void 0 ? contentSize : wideSize};
margin-left: ${marginLeft};
margin-right: ${marginRight};
}
${appendSelectors(selector, '> .alignwide')} {
max-width: ${wideSize !== null && wideSize !== void 0 ? wideSize : contentSize};
}
${appendSelectors(selector, '> .alignfull')} {
max-width: none;
}
` : '';
if (justifyContent === 'left') {
output += `${appendSelectors(selector, '> :where(:not(.alignleft):not(.alignright):not(.alignfull))')}
{ margin-left: ${marginLeft}; }`;
} else if (justifyContent === 'right') {
output += `${appendSelectors(selector, '> :where(:not(.alignleft):not(.alignright):not(.alignfull))')}
{ margin-right: ${marginRight}; }`;
} // If there is custom padding, add negative margins for alignfull blocks.
if (style !== null && style !== void 0 && (_style$spacing2 = style.spacing) !== null && _style$spacing2 !== void 0 && _style$spacing2.padding) {
// The style object might be storing a preset so we need to make sure we get a usable value.
const paddingValues = (0,external_wp_styleEngine_namespaceObject.getCSSRules)(style);
paddingValues.forEach(rule => {
if (rule.key === 'paddingRight') {
output += `
${appendSelectors(selector, '> .alignfull')} {
margin-right: calc(${rule.value} * -1);
}
`;
} else if (rule.key === 'paddingLeft') {
output += `
${appendSelectors(selector, '> .alignfull')} {
margin-left: calc(${rule.value} * -1);
}
`;
}
});
} // Output blockGap styles based on rules contained in layout definitions in theme.json.
if (hasBlockGapSupport && blockGapValue) {
output += getBlockGapCSS(selector, layoutDefinitions, 'constrained', blockGapValue);
}
return output;
},
getOrientation() {
return 'vertical';
},
getAlignments(layout) {
const alignmentInfo = getAlignmentsInfo(layout);
if (layout.alignments !== undefined) {
if (!layout.alignments.includes('none')) {
layout.alignments.unshift('none');
}
return layout.alignments.map(alignment => ({
name: alignment,
info: alignmentInfo[alignment]
}));
}
const {
contentSize,
wideSize
} = layout;
const alignments = [{
name: 'left'
}, {
name: 'center'
}, {
name: 'right'
}];
if (contentSize) {
alignments.unshift({
name: 'full'
});
}
if (wideSize) {
alignments.unshift({
name: 'wide',
info: alignmentInfo.wide
});
}
alignments.unshift({
name: 'none',
info: alignmentInfo.none
});
return alignments;
}
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/layouts/index.js
/**
* Internal dependencies
*/
const layoutTypes = [flow, flex, constrained];
/**
* Retrieves a layout type by name.
*
* @param {string} name - The name of the layout type.
* @return {Object} Layout type.
*/
function getLayoutType() {
let name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'default';
return layoutTypes.find(layoutType => layoutType.name === name);
}
/**
* Retrieves the available layout types.
*
* @return {Array} Layout types.
*/
function getLayoutTypes() {
return layoutTypes;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-list/layout.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const defaultLayout = {
type: 'default'
};
const Layout = (0,external_wp_element_namespaceObject.createContext)(defaultLayout);
/**
* Allows to define the layout.
*/
const LayoutProvider = Layout.Provider;
/**
* React hook used to retrieve the layout config.
*/
function useLayout() {
return (0,external_wp_element_namespaceObject.useContext)(Layout);
}
function LayoutStyle(_ref) {
let {
layout = {},
css,
...props
} = _ref;
const layoutType = getLayoutType(layout.type);
const blockGapSupport = useSetting('spacing.blockGap');
const hasBlockGapSupport = blockGapSupport !== null;
if (layoutType) {
var _layoutType$getLayout;
if (css) {
return (0,external_wp_element_namespaceObject.createElement)("style", null, css);
}
const layoutStyle = (_layoutType$getLayout = layoutType.getLayoutStyle) === null || _layoutType$getLayout === void 0 ? void 0 : _layoutType$getLayout.call(layoutType, {
hasBlockGapSupport,
layout,
...props
});
if (layoutStyle) {
return (0,external_wp_element_namespaceObject.createElement)("style", null, layoutStyle);
}
}
return null;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-alignment-control/use-available-alignments.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const use_available_alignments_EMPTY_ARRAY = [];
const use_available_alignments_DEFAULT_CONTROLS = ['none', 'left', 'center', 'right', 'wide', 'full'];
const WIDE_CONTROLS = ['wide', 'full'];
function useAvailableAlignments() {
let controls = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : use_available_alignments_DEFAULT_CONTROLS;
// Always add the `none` option if not exists.
if (!controls.includes('none')) {
controls = ['none', ...controls];
}
const {
wideControlsEnabled = false,
themeSupportsLayout,
isBlockBasedTheme
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getSettings
} = select(store);
const settings = getSettings();
return {
wideControlsEnabled: settings.alignWide,
themeSupportsLayout: settings.supportsLayout,
isBlockBasedTheme: settings.__unstableIsBlockBasedTheme
};
}, []);
const layout = useLayout();
const layoutType = getLayoutType(layout === null || layout === void 0 ? void 0 : layout.type);
const layoutAlignments = layoutType.getAlignments(layout, isBlockBasedTheme);
if (themeSupportsLayout) {
const alignments = layoutAlignments.filter(_ref => {
let {
name: alignmentName
} = _ref;
return controls.includes(alignmentName);
}); // While we treat `none` as an alignment, we shouldn't return it if no
// other alignments exist.
if (alignments.length === 1 && alignments[0].name === 'none') {
return use_available_alignments_EMPTY_ARRAY;
}
return alignments;
} // Starting here, it's the fallback for themes not supporting the layout config.
if (layoutType.name !== 'default' && layoutType.name !== 'constrained') {
return use_available_alignments_EMPTY_ARRAY;
}
const {
alignments: availableAlignments = use_available_alignments_DEFAULT_CONTROLS
} = layout;
const enabledControls = controls.filter(control => (layout.alignments || // Ignore the global wideAlignment check if the layout explicitely defines alignments.
wideControlsEnabled || !WIDE_CONTROLS.includes(control)) && availableAlignments.includes(control)).map(enabledControl => ({
name: enabledControl
})); // While we treat `none` as an alignment, we shouldn't return it if no
// other alignments exist.
if (enabledControls.length === 1 && enabledControls[0].name === 'none') {
return use_available_alignments_EMPTY_ARRAY;
}
return enabledControls;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/align-none.js
/**
* WordPress dependencies
*/
const alignNone = (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: "M5 15h14V9H5v6zm0 4.8h14v-1.5H5v1.5zM5 4.2v1.5h14V4.2H5z"
}));
/* harmony default export */ var align_none = (alignNone);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/position-left.js
/**
* WordPress dependencies
*/
const positionLeft = (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: "M4 9v6h14V9H4zm8-4.8H4v1.5h8V4.2zM4 19.8h8v-1.5H4v1.5z"
}));
/* harmony default export */ var position_left = (positionLeft);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/position-right.js
/**
* WordPress dependencies
*/
const positionRight = (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: "M6 15h14V9H6v6zm6-10.8v1.5h8V4.2h-8zm0 15.6h8v-1.5h-8v1.5z"
}));
/* harmony default export */ var position_right = (positionRight);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/stretch-full-width.js
/**
* WordPress dependencies
*/
const stretchFullWidth = (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: "M5 4v11h14V4H5zm3 15.8h8v-1.5H8v1.5z"
}));
/* harmony default export */ var stretch_full_width = (stretchFullWidth);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-alignment-control/constants.js
/**
* WordPress dependencies
*/
const constants_BLOCK_ALIGNMENTS_CONTROLS = {
none: {
icon: align_none,
title: (0,external_wp_i18n_namespaceObject._x)('None', 'Alignment option')
},
left: {
icon: position_left,
title: (0,external_wp_i18n_namespaceObject.__)('Align left')
},
center: {
icon: position_center,
title: (0,external_wp_i18n_namespaceObject.__)('Align center')
},
right: {
icon: position_right,
title: (0,external_wp_i18n_namespaceObject.__)('Align right')
},
wide: {
icon: stretch_wide,
title: (0,external_wp_i18n_namespaceObject.__)('Wide width')
},
full: {
icon: stretch_full_width,
title: (0,external_wp_i18n_namespaceObject.__)('Full width')
}
};
const constants_DEFAULT_CONTROL = 'none';
const POPOVER_PROPS = {
variant: 'toolbar'
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-alignment-control/ui.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function BlockAlignmentUI(_ref) {
let {
value,
onChange,
controls,
isToolbar,
isCollapsed = true
} = _ref;
const enabledControls = useAvailableAlignments(controls);
const hasEnabledControls = !!enabledControls.length;
if (!hasEnabledControls) {
return null;
}
function onChangeAlignment(align) {
onChange([value, 'none'].includes(align) ? undefined : align);
}
const activeAlignmentControl = constants_BLOCK_ALIGNMENTS_CONTROLS[value];
const defaultAlignmentControl = constants_BLOCK_ALIGNMENTS_CONTROLS[constants_DEFAULT_CONTROL];
const UIComponent = isToolbar ? external_wp_components_namespaceObject.ToolbarGroup : external_wp_components_namespaceObject.ToolbarDropdownMenu;
const commonProps = {
icon: activeAlignmentControl ? activeAlignmentControl.icon : defaultAlignmentControl.icon,
label: (0,external_wp_i18n_namespaceObject.__)('Align')
};
const extraProps = isToolbar ? {
isCollapsed,
controls: enabledControls.map(_ref2 => {
let {
name: controlName
} = _ref2;
return { ...constants_BLOCK_ALIGNMENTS_CONTROLS[controlName],
isActive: value === controlName || !value && controlName === 'none',
role: isCollapsed ? 'menuitemradio' : undefined,
onClick: () => onChangeAlignment(controlName)
};
})
} : {
toggleProps: {
describedBy: (0,external_wp_i18n_namespaceObject.__)('Change alignment')
},
popoverProps: POPOVER_PROPS,
children: _ref3 => {
let {
onClose
} = _ref3;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, {
className: "block-editor-block-alignment-control__menu-group"
}, enabledControls.map(_ref4 => {
let {
name: controlName,
info
} = _ref4;
const {
icon,
title
} = constants_BLOCK_ALIGNMENTS_CONTROLS[controlName]; // If no value is provided, mark as selected the `none` option.
const isSelected = controlName === value || !value && controlName === 'none';
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
key: controlName,
icon: icon,
iconPosition: "left",
className: classnames_default()('components-dropdown-menu__menu-item', {
'is-active': isSelected
}),
isSelected: isSelected,
onClick: () => {
onChangeAlignment(controlName);
onClose();
},
role: "menuitemradio",
info: info
}, title);
})));
}
};
return (0,external_wp_element_namespaceObject.createElement)(UIComponent, _extends({}, commonProps, extraProps));
}
/* harmony default export */ var block_alignment_control_ui = (BlockAlignmentUI);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-alignment-control/index.js
/**
* Internal dependencies
*/
const BlockAlignmentControl = props => {
return (0,external_wp_element_namespaceObject.createElement)(block_alignment_control_ui, _extends({}, props, {
isToolbar: false
}));
};
const BlockAlignmentToolbar = props => {
return (0,external_wp_element_namespaceObject.createElement)(block_alignment_control_ui, _extends({}, props, {
isToolbar: true
}));
};
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/block-alignment-control/README.md
*/
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/align.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* An array which includes all possible valid alignments,
* used to validate if an alignment is valid or not.
*
* @constant
* @type {string[]}
*/
const ALL_ALIGNMENTS = ['left', 'center', 'right', 'wide', 'full'];
/**
* An array which includes all wide alignments.
* In order for this alignments to be valid they need to be supported by the block,
* and by the theme.
*
* @constant
* @type {string[]}
*/
const WIDE_ALIGNMENTS = ['wide', 'full'];
/**
* Returns the valid alignments.
* Takes into consideration the aligns supported by a block, if the block supports wide controls or not and if theme supports wide controls or not.
* Exported just for testing purposes, not exported outside the module.
*
* @param {?boolean|string[]} blockAlign Aligns supported by the block.
* @param {?boolean} hasWideBlockSupport True if block supports wide alignments. And False otherwise.
* @param {?boolean} hasWideEnabled True if theme supports wide alignments. And False otherwise.
*
* @return {string[]} Valid alignments.
*/
function getValidAlignments(blockAlign) {
let hasWideBlockSupport = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
let hasWideEnabled = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
let validAlignments;
if (Array.isArray(blockAlign)) {
validAlignments = ALL_ALIGNMENTS.filter(value => blockAlign.includes(value));
} else if (blockAlign === true) {
// `true` includes all alignments...
validAlignments = [...ALL_ALIGNMENTS];
} else {
validAlignments = [];
}
if (!hasWideEnabled || blockAlign === true && !hasWideBlockSupport) {
return validAlignments.filter(alignment => !WIDE_ALIGNMENTS.includes(alignment));
}
return validAlignments;
}
/**
* Filters registered block settings, extending attributes to include `align`.
*
* @param {Object} settings Original block settings.
*
* @return {Object} Filtered block settings.
*/
function addAttribute(settings) {
var _settings$attributes$, _settings$attributes;
// Allow blocks to specify their own attribute definition with default values if needed.
if ('type' in ((_settings$attributes$ = (_settings$attributes = settings.attributes) === null || _settings$attributes === void 0 ? void 0 : _settings$attributes.align) !== null && _settings$attributes$ !== void 0 ? _settings$attributes$ : {})) {
return settings;
}
if ((0,external_wp_blocks_namespaceObject.hasBlockSupport)(settings, 'align')) {
// Gracefully handle if settings.attributes is undefined.
settings.attributes = { ...settings.attributes,
align: {
type: 'string',
// Allow for '' since it is used by updateAlignment function
// in withToolbarControls for special cases with defined default values.
enum: [...ALL_ALIGNMENTS, '']
}
};
}
return settings;
}
/**
* Override the default edit UI to include new toolbar controls for block
* alignment, if block defines support.
*
* @param {Function} BlockEdit Original component.
*
* @return {Function} Wrapped component.
*/
const withToolbarControls = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(BlockEdit => props => {
const blockEdit = (0,external_wp_element_namespaceObject.createElement)(BlockEdit, props);
const {
name: blockName
} = props; // Compute the block valid alignments by taking into account,
// if the theme supports wide alignments or not and the layout's
// availble alignments. We do that for conditionally rendering
// Slot.
const blockAllowedAlignments = getValidAlignments((0,external_wp_blocks_namespaceObject.getBlockSupport)(blockName, 'align'), (0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockName, 'alignWide', true));
const validAlignments = useAvailableAlignments(blockAllowedAlignments).map(_ref => {
let {
name
} = _ref;
return name;
});
const isContentLocked = (0,external_wp_data_namespaceObject.useSelect)(select => {
return select(store).__unstableGetContentLockingParent(props.clientId);
}, [props.clientId]);
if (!validAlignments.length || isContentLocked) {
return blockEdit;
}
const updateAlignment = nextAlign => {
if (!nextAlign) {
var _blockType$attributes, _blockType$attributes2;
const blockType = (0,external_wp_blocks_namespaceObject.getBlockType)(props.name);
const blockDefaultAlign = blockType === null || blockType === void 0 ? void 0 : (_blockType$attributes = blockType.attributes) === null || _blockType$attributes === void 0 ? void 0 : (_blockType$attributes2 = _blockType$attributes.align) === null || _blockType$attributes2 === void 0 ? void 0 : _blockType$attributes2.default;
if (blockDefaultAlign) {
nextAlign = '';
}
}
props.setAttributes({
align: nextAlign
});
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(block_controls, {
group: "block",
__experimentalShareWithChildBlocks: true
}, (0,external_wp_element_namespaceObject.createElement)(BlockAlignmentControl, {
value: props.attributes.align,
onChange: updateAlignment,
controls: validAlignments
})), blockEdit);
}, 'withToolbarControls');
/**
* Override the default block element to add alignment wrapper props.
*
* @param {Function} BlockListBlock Original component.
*
* @return {Function} Wrapped component.
*/
const withDataAlign = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(BlockListBlock => props => {
const {
name,
attributes
} = props;
const {
align
} = attributes;
const blockAllowedAlignments = getValidAlignments((0,external_wp_blocks_namespaceObject.getBlockSupport)(name, 'align'), (0,external_wp_blocks_namespaceObject.hasBlockSupport)(name, 'alignWide', true));
const validAlignments = useAvailableAlignments(blockAllowedAlignments); // If an alignment is not assigned, there's no need to go through the
// effort to validate or assign its value.
if (align === undefined) {
return (0,external_wp_element_namespaceObject.createElement)(BlockListBlock, props);
}
let wrapperProps = props.wrapperProps;
if (validAlignments.some(alignment => alignment.name === align)) {
wrapperProps = { ...wrapperProps,
'data-align': align
};
}
return (0,external_wp_element_namespaceObject.createElement)(BlockListBlock, _extends({}, props, {
wrapperProps: wrapperProps
}));
});
/**
* Override props assigned to save component to inject alignment class name if
* block supports it.
*
* @param {Object} props Additional props applied to save element.
* @param {Object} blockType Block type.
* @param {Object} attributes Block attributes.
*
* @return {Object} Filtered props applied to save element.
*/
function addAssignedAlign(props, blockType, attributes) {
const {
align
} = attributes;
const blockAlign = (0,external_wp_blocks_namespaceObject.getBlockSupport)(blockType, 'align');
const hasWideBlockSupport = (0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockType, 'alignWide', true); // Compute valid alignments without taking into account if
// the theme supports wide alignments or not.
// This way changing themes does not impact the block save.
const isAlignValid = getValidAlignments(blockAlign, hasWideBlockSupport).includes(align);
if (isAlignValid) {
props.className = classnames_default()(`align${align}`, props.className);
}
return props;
}
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'core/align/addAttribute', addAttribute);
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockListBlock', 'core/editor/align/with-data-align', withDataAlign);
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockEdit', 'core/editor/align/with-toolbar-controls', withToolbarControls);
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.getSaveContent.extraProps', 'core/align/addAssignedAlign', addAssignedAlign);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/lock.js
/**
* WordPress dependencies
*/
/**
* Filters registered block settings, extending attributes to include `lock`.
*
* @param {Object} settings Original block settings.
*
* @return {Object} Filtered block settings.
*/
function lock_addAttribute(settings) {
var _settings$attributes$, _settings$attributes;
// Allow blocks to specify their own attribute definition with default values if needed.
if ('type' in ((_settings$attributes$ = (_settings$attributes = settings.attributes) === null || _settings$attributes === void 0 ? void 0 : _settings$attributes.lock) !== null && _settings$attributes$ !== void 0 ? _settings$attributes$ : {})) {
return settings;
} // Gracefully handle if settings.attributes is undefined.
settings.attributes = { ...settings.attributes,
lock: {
type: 'object'
}
};
return settings;
}
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'core/lock/addAttribute', lock_addAttribute);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/anchor.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Regular expression matching invalid anchor characters for replacement.
*
* @type {RegExp}
*/
const ANCHOR_REGEX = /[\s#]/g;
const ANCHOR_SCHEMA = {
type: 'string',
source: 'attribute',
attribute: 'id',
selector: '*'
};
/**
* Filters registered block settings, extending attributes with anchor using ID
* of the first node.
*
* @param {Object} settings Original block settings.
*
* @return {Object} Filtered block settings.
*/
function anchor_addAttribute(settings) {
var _settings$attributes$, _settings$attributes;
// Allow blocks to specify their own attribute definition with default values if needed.
if ('type' in ((_settings$attributes$ = (_settings$attributes = settings.attributes) === null || _settings$attributes === void 0 ? void 0 : _settings$attributes.anchor) !== null && _settings$attributes$ !== void 0 ? _settings$attributes$ : {})) {
return settings;
}
if ((0,external_wp_blocks_namespaceObject.hasBlockSupport)(settings, 'anchor')) {
// Gracefully handle if settings.attributes is undefined.
settings.attributes = { ...settings.attributes,
anchor: ANCHOR_SCHEMA
};
}
return settings;
}
/**
* Override the default edit UI to include a new block inspector control for
* assigning the anchor ID, if block supports anchor.
*
* @param {WPComponent} BlockEdit Original component.
*
* @return {WPComponent} Wrapped component.
*/
const withInspectorControl = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(BlockEdit => {
return props => {
const hasAnchor = (0,external_wp_blocks_namespaceObject.hasBlockSupport)(props.name, 'anchor');
if (hasAnchor && props.isSelected) {
const isWeb = external_wp_element_namespaceObject.Platform.OS === 'web';
const textControl = (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.TextControl, {
__nextHasNoMarginBottom: true,
className: "html-anchor-control",
label: (0,external_wp_i18n_namespaceObject.__)('HTML anchor'),
help: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_i18n_namespaceObject.__)('Enter a word or two — without spaces — to make a unique web address just for this block, called an “anchor.” Then, you’ll be able to link directly to this section of your page.'), isWeb && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ExternalLink, {
href: (0,external_wp_i18n_namespaceObject.__)('https://wordpress.org/support/article/page-jumps/')
}, (0,external_wp_i18n_namespaceObject.__)('Learn more about anchors'))),
value: props.attributes.anchor || '',
placeholder: !isWeb ? (0,external_wp_i18n_namespaceObject.__)('Add an anchor') : null,
onChange: nextValue => {
nextValue = nextValue.replace(ANCHOR_REGEX, '-');
props.setAttributes({
anchor: nextValue
});
},
autoCapitalize: "none",
autoComplete: "off"
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(BlockEdit, props), isWeb && (0,external_wp_element_namespaceObject.createElement)(inspector_controls, {
group: "advanced"
}, textControl), !isWeb && props.name === 'core/heading' && (0,external_wp_element_namespaceObject.createElement)(inspector_controls, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelBody, {
title: (0,external_wp_i18n_namespaceObject.__)('Heading settings')
}, textControl)));
}
return (0,external_wp_element_namespaceObject.createElement)(BlockEdit, props);
};
}, 'withInspectorControl');
/**
* Override props assigned to save component to inject anchor ID, if block
* supports anchor. This is only applied if the block's save result is an
* element and not a markup string.
*
* @param {Object} extraProps Additional props applied to save element.
* @param {Object} blockType Block type.
* @param {Object} attributes Current block attributes.
*
* @return {Object} Filtered props applied to save element.
*/
function addSaveProps(extraProps, blockType, attributes) {
if ((0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockType, 'anchor')) {
extraProps.id = attributes.anchor === '' ? null : attributes.anchor;
}
return extraProps;
}
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'core/anchor/attribute', anchor_addAttribute);
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockEdit', 'core/editor/anchor/with-inspector-control', withInspectorControl);
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.getSaveContent.extraProps', 'core/anchor/save-props', addSaveProps);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/aria-label.js
/**
* WordPress dependencies
*/
const ARIA_LABEL_SCHEMA = {
type: 'string',
source: 'attribute',
attribute: 'aria-label',
selector: '*'
};
/**
* Filters registered block settings, extending attributes with ariaLabel using aria-label
* of the first node.
*
* @param {Object} settings Original block settings.
*
* @return {Object} Filtered block settings.
*/
function aria_label_addAttribute(settings) {
var _settings$attributes, _settings$attributes$;
// Allow blocks to specify their own attribute definition with default values if needed.
if (settings !== null && settings !== void 0 && (_settings$attributes = settings.attributes) !== null && _settings$attributes !== void 0 && (_settings$attributes$ = _settings$attributes.ariaLabel) !== null && _settings$attributes$ !== void 0 && _settings$attributes$.type) {
return settings;
}
if ((0,external_wp_blocks_namespaceObject.hasBlockSupport)(settings, 'ariaLabel')) {
// Gracefully handle if settings.attributes is undefined.
settings.attributes = { ...settings.attributes,
ariaLabel: ARIA_LABEL_SCHEMA
};
}
return settings;
}
/**
* Override props assigned to save component to inject aria-label, if block
* supports ariaLabel. This is only applied if the block's save result is an
* element and not a markup string.
*
* @param {Object} extraProps Additional props applied to save element.
* @param {Object} blockType Block type.
* @param {Object} attributes Current block attributes.
*
* @return {Object} Filtered props applied to save element.
*/
function aria_label_addSaveProps(extraProps, blockType, attributes) {
if ((0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockType, 'ariaLabel')) {
extraProps['aria-label'] = attributes.ariaLabel === '' ? null : attributes.ariaLabel;
}
return extraProps;
}
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'core/ariaLabel/attribute', aria_label_addAttribute);
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.getSaveContent.extraProps', 'core/ariaLabel/save-props', aria_label_addSaveProps);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/custom-class-name.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Filters registered block settings, extending attributes with anchor using ID
* of the first node.
*
* @param {Object} settings Original block settings.
*
* @return {Object} Filtered block settings.
*/
function custom_class_name_addAttribute(settings) {
if ((0,external_wp_blocks_namespaceObject.hasBlockSupport)(settings, 'customClassName', true)) {
// Gracefully handle if settings.attributes is undefined.
settings.attributes = { ...settings.attributes,
className: {
type: 'string'
}
};
}
return settings;
}
/**
* Override the default edit UI to include a new block inspector control for
* assigning the custom class name, if block supports custom class name.
*
* @param {WPComponent} BlockEdit Original component.
*
* @return {WPComponent} Wrapped component.
*/
const custom_class_name_withInspectorControl = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(BlockEdit => {
return props => {
const hasCustomClassName = (0,external_wp_blocks_namespaceObject.hasBlockSupport)(props.name, 'customClassName', true);
if (hasCustomClassName && props.isSelected) {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(BlockEdit, props), (0,external_wp_element_namespaceObject.createElement)(inspector_controls, {
group: "advanced"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.TextControl, {
__nextHasNoMarginBottom: true,
autoComplete: "off",
label: (0,external_wp_i18n_namespaceObject.__)('Additional CSS class(es)'),
value: props.attributes.className || '',
onChange: nextValue => {
props.setAttributes({
className: nextValue !== '' ? nextValue : undefined
});
},
help: (0,external_wp_i18n_namespaceObject.__)('Separate multiple classes with spaces.')
})));
}
return (0,external_wp_element_namespaceObject.createElement)(BlockEdit, props);
};
}, 'withInspectorControl');
/**
* Override props assigned to save component to inject anchor ID, if block
* supports anchor. This is only applied if the block's save result is an
* element and not a markup string.
*
* @param {Object} extraProps Additional props applied to save element.
* @param {Object} blockType Block type.
* @param {Object} attributes Current block attributes.
*
* @return {Object} Filtered props applied to save element.
*/
function custom_class_name_addSaveProps(extraProps, blockType, attributes) {
if ((0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockType, 'customClassName', true) && attributes.className) {
extraProps.className = classnames_default()(extraProps.className, attributes.className);
}
return extraProps;
}
function addTransforms(result, source, index, results) {
if (!(0,external_wp_blocks_namespaceObject.hasBlockSupport)(result.name, 'customClassName', true)) {
return result;
} // If the condition verifies we are probably in the presence of a wrapping transform
// e.g: nesting paragraphs in a group or columns and in that case the class should not be kept.
if (results.length === 1 && result.innerBlocks.length === source.length) {
return result;
} // If we are transforming one block to multiple blocks or multiple blocks to one block,
// we ignore the class during the transform.
if (results.length === 1 && source.length > 1 || results.length > 1 && source.length === 1) {
return result;
} // If we are in presence of transform between one or more block in the source
// that have one or more blocks in the result
// we apply the class on source N to the result N,
// if source N does not exists we do nothing.
if (source[index]) {
var _source$index;
const originClassName = (_source$index = source[index]) === null || _source$index === void 0 ? void 0 : _source$index.attributes.className;
if (originClassName) {
return { ...result,
attributes: { ...result.attributes,
className: originClassName
}
};
}
}
return result;
}
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'core/custom-class-name/attribute', custom_class_name_addAttribute);
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockEdit', 'core/editor/custom-class-name/with-inspector-control', custom_class_name_withInspectorControl);
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.getSaveContent.extraProps', 'core/custom-class-name/save-props', custom_class_name_addSaveProps);
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.switchToBlockType.transformedBlock', 'core/color/addTransforms', addTransforms);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/generated-class-name.js
/**
* WordPress dependencies
*/
/**
* Override props assigned to save component to inject generated className if
* block supports it. This is only applied if the block's save result is an
* element and not a markup string.
*
* @param {Object} extraProps Additional props applied to save element.
* @param {Object} blockType Block type.
*
* @return {Object} Filtered props applied to save element.
*/
function addGeneratedClassName(extraProps, blockType) {
// Adding the generated className.
if ((0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockType, 'className', true)) {
if (typeof extraProps.className === 'string') {
// We have some extra classes and want to add the default classname
// We use uniq to prevent duplicate classnames.
extraProps.className = [...new Set([(0,external_wp_blocks_namespaceObject.getBlockDefaultClassName)(blockType.name), ...extraProps.className.split(' ')])].join(' ').trim();
} else {
// There is no string in the className variable,
// so we just dump the default name in there.
extraProps.className = (0,external_wp_blocks_namespaceObject.getBlockDefaultClassName)(blockType.name);
}
}
return extraProps;
}
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.getSaveContent.extraProps', 'core/generated-class-name/save-props', addGeneratedClassName);
;// CONCATENATED MODULE: external ["wp","dom"]
var external_wp_dom_namespaceObject = window["wp"]["dom"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-context/index.js
/**
* WordPress dependencies
*/
/** @typedef {import('react').ReactNode} ReactNode */
/**
* @typedef BlockContextProviderProps
*
* @property {Record<string,*>} value Context value to merge with current
* value.
* @property {ReactNode} children Component children.
*/
/** @type {import('react').Context<Record<string,*>>} */
const block_context_Context = (0,external_wp_element_namespaceObject.createContext)({});
/**
* Component which merges passed value with current consumed block context.
*
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/block-context/README.md
*
* @param {BlockContextProviderProps} props
*/
function BlockContextProvider(_ref) {
let {
value,
children
} = _ref;
const context = (0,external_wp_element_namespaceObject.useContext)(block_context_Context);
const nextValue = (0,external_wp_element_namespaceObject.useMemo)(() => ({ ...context,
...value
}), [context, value]);
return (0,external_wp_element_namespaceObject.createElement)(block_context_Context.Provider, {
value: nextValue,
children: children
});
}
/* harmony default export */ var block_context = (block_context_Context);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-edit/edit.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Default value used for blocks which do not define their own context needs,
* used to guarantee that a block's `context` prop will always be an object. It
* is assigned as a constant since it is always expected to be an empty object,
* and in order to avoid unnecessary React reconciliations of a changing object.
*
* @type {{}}
*/
const DEFAULT_BLOCK_CONTEXT = {};
const Edit = props => {
const {
attributes = {},
name
} = props;
const blockType = (0,external_wp_blocks_namespaceObject.getBlockType)(name);
const blockContext = (0,external_wp_element_namespaceObject.useContext)(block_context); // Assign context values using the block type's declared context needs.
const context = (0,external_wp_element_namespaceObject.useMemo)(() => {
return blockType && blockType.usesContext ? Object.fromEntries(Object.entries(blockContext).filter(_ref => {
let [key] = _ref;
return blockType.usesContext.includes(key);
})) : DEFAULT_BLOCK_CONTEXT;
}, [blockType, blockContext]);
if (!blockType) {
return null;
} // `edit` and `save` are functions or components describing the markup
// with which a block is displayed. If `blockType` is valid, assign
// them preferentially as the render value for the block.
const Component = blockType.edit || blockType.save;
if (blockType.apiVersion > 1) {
return (0,external_wp_element_namespaceObject.createElement)(Component, _extends({}, props, {
context: context
}));
} // Generate a class name for the block's editable form.
const generatedClassName = (0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockType, 'className', true) ? (0,external_wp_blocks_namespaceObject.getBlockDefaultClassName)(name) : null;
const className = classnames_default()(generatedClassName, attributes.className, props.className);
return (0,external_wp_element_namespaceObject.createElement)(Component, _extends({}, props, {
context: context,
className: className
}));
};
/* harmony default export */ var edit = ((0,external_wp_components_namespaceObject.withFilters)('editor.BlockEdit')(Edit));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-edit/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* The `useBlockEditContext` hook provides information about the block this hook is being used in.
* It returns an object with the `name`, `isSelected` state, and the `clientId` of the block.
* It is useful if you want to create custom hooks that need access to the current blocks clientId
* but don't want to rely on the data getting passed in as a parameter.
*
* @return {Object} Block edit context
*/
function BlockEdit(props) {
const {
name,
isSelected,
clientId,
attributes = {},
__unstableLayoutClassNames
} = props;
const {
layout = null
} = attributes;
const layoutSupport = (0,external_wp_blocks_namespaceObject.hasBlockSupport)(name, '__experimentalLayout', false);
const context = {
name,
isSelected,
clientId,
layout: layoutSupport ? layout : null,
__unstableLayoutClassNames
};
return (0,external_wp_element_namespaceObject.createElement)(Provider // It is important to return the same object if props haven't
// changed to avoid unnecessary rerenders.
// See https://reactjs.org/docs/context.html#caveats.
, {
value: (0,external_wp_element_namespaceObject.useMemo)(() => context, Object.values(context))
}, (0,external_wp_element_namespaceObject.createElement)(edit, props));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/more-horizontal.js
/**
* WordPress dependencies
*/
const moreHorizontal = (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: "M11 13h2v-2h-2v2zm-6 0h2v-2H5v2zm12-2v2h2v-2h-2z"
}));
/* harmony default export */ var more_horizontal = (moreHorizontal);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/warning/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
function Warning(_ref) {
let {
className,
actions,
children,
secondaryActions
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("div", {
style: {
display: 'contents',
all: 'initial'
}
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()(className, 'block-editor-warning')
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-warning__contents"
}, (0,external_wp_element_namespaceObject.createElement)("p", {
className: "block-editor-warning__message"
}, children), (external_wp_element_namespaceObject.Children.count(actions) > 0 || secondaryActions) && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-warning__actions"
}, external_wp_element_namespaceObject.Children.count(actions) > 0 && external_wp_element_namespaceObject.Children.map(actions, (action, i) => (0,external_wp_element_namespaceObject.createElement)("span", {
key: i,
className: "block-editor-warning__action"
}, action)), secondaryActions && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.DropdownMenu, {
className: "block-editor-warning__secondary",
icon: more_horizontal,
label: (0,external_wp_i18n_namespaceObject.__)('More options'),
popoverProps: {
position: 'bottom left',
className: 'block-editor-warning__dropdown'
},
noIcons: true
}, () => (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, null, secondaryActions.map((item, pos) => (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
onClick: item.onClick,
key: pos
}, item.title))))))));
}
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/warning/README.md
*/
/* harmony default export */ var warning = (Warning);
// EXTERNAL MODULE: ./node_modules/diff/lib/diff/character.js
var character = __webpack_require__(1973);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-compare/block-view.js
/**
* WordPress dependencies
*/
function BlockView(_ref) {
let {
title,
rawContent,
renderedContent,
action,
actionText,
className
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: className
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-compare__content"
}, (0,external_wp_element_namespaceObject.createElement)("h2", {
className: "block-editor-block-compare__heading"
}, title), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-compare__html"
}, rawContent), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-compare__preview edit-post-visual-editor"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.RawHTML, null, (0,external_wp_dom_namespaceObject.safeHTML)(renderedContent)))), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-compare__action"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "secondary",
tabIndex: "0",
onClick: action
}, actionText)));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-compare/index.js
/**
* External dependencies
*/
// diff doesn't tree-shake correctly, so we import from the individual
// module here, to avoid including too much of the library
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function BlockCompare(_ref) {
let {
block,
onKeep,
onConvert,
convertor,
convertButtonText
} = _ref;
function getDifference(originalContent, newContent) {
const difference = (0,character/* diffChars */.Kx)(originalContent, newContent);
return difference.map((item, pos) => {
const classes = classnames_default()({
'block-editor-block-compare__added': item.added,
'block-editor-block-compare__removed': item.removed
});
return (0,external_wp_element_namespaceObject.createElement)("span", {
key: pos,
className: classes
}, item.value);
});
}
function getConvertedContent(convertedBlock) {
// The convertor may return an array of items or a single item.
const newBlocks = Array.isArray(convertedBlock) ? convertedBlock : [convertedBlock]; // Get converted block details.
const newContent = newBlocks.map(item => (0,external_wp_blocks_namespaceObject.getSaveContent)(item.name, item.attributes, item.innerBlocks));
return newContent.join('');
}
const converted = getConvertedContent(convertor(block));
const difference = getDifference(block.originalContent, converted);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-compare__wrapper"
}, (0,external_wp_element_namespaceObject.createElement)(BlockView, {
title: (0,external_wp_i18n_namespaceObject.__)('Current'),
className: "block-editor-block-compare__current",
action: onKeep,
actionText: (0,external_wp_i18n_namespaceObject.__)('Convert to HTML'),
rawContent: block.originalContent,
renderedContent: block.originalContent
}), (0,external_wp_element_namespaceObject.createElement)(BlockView, {
title: (0,external_wp_i18n_namespaceObject.__)('After Conversion'),
className: "block-editor-block-compare__converted",
action: onConvert,
actionText: convertButtonText,
rawContent: difference,
renderedContent: converted
}));
}
/* harmony default export */ var block_compare = (BlockCompare);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-list/block-invalid-warning.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function BlockInvalidWarning(_ref) {
let {
convertToHTML,
convertToBlocks,
convertToClassic,
attemptBlockRecovery,
block
} = _ref;
const hasHTMLBlock = !!(0,external_wp_blocks_namespaceObject.getBlockType)('core/html');
const hasClassicBlock = !!(0,external_wp_blocks_namespaceObject.getBlockType)('core/freeform');
const [compare, setCompare] = (0,external_wp_element_namespaceObject.useState)(false);
const onCompare = (0,external_wp_element_namespaceObject.useCallback)(() => setCompare(true), []);
const onCompareClose = (0,external_wp_element_namespaceObject.useCallback)(() => setCompare(false), []); // We memo the array here to prevent the children components from being updated unexpectedly.
const hiddenActions = (0,external_wp_element_namespaceObject.useMemo)(() => [{
// translators: Button to fix block content
title: (0,external_wp_i18n_namespaceObject._x)('Resolve', 'imperative verb'),
onClick: onCompare
}, hasHTMLBlock && {
title: (0,external_wp_i18n_namespaceObject.__)('Convert to HTML'),
onClick: convertToHTML
}, hasClassicBlock && {
title: (0,external_wp_i18n_namespaceObject.__)('Convert to Classic Block'),
onClick: convertToClassic
}].filter(Boolean), [onCompare, hasHTMLBlock, convertToHTML, hasClassicBlock, convertToClassic]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(warning, {
actions: [(0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
key: "recover",
onClick: attemptBlockRecovery,
variant: "primary"
}, (0,external_wp_i18n_namespaceObject.__)('Attempt Block Recovery'))],
secondaryActions: hiddenActions
}, (0,external_wp_i18n_namespaceObject.__)('This block contains unexpected or invalid content.')), compare && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Modal, {
title: // translators: Dialog title to fix block content
(0,external_wp_i18n_namespaceObject.__)('Resolve Block'),
onRequestClose: onCompareClose,
className: "block-editor-block-compare"
}, (0,external_wp_element_namespaceObject.createElement)(block_compare, {
block: block,
onKeep: convertToHTML,
onConvert: convertToBlocks,
convertor: blockToBlocks,
convertButtonText: (0,external_wp_i18n_namespaceObject.__)('Convert to Blocks')
})));
}
const blockToClassic = block => (0,external_wp_blocks_namespaceObject.createBlock)('core/freeform', {
content: block.originalContent
});
const blockToHTML = block => (0,external_wp_blocks_namespaceObject.createBlock)('core/html', {
content: block.originalContent
});
const blockToBlocks = block => (0,external_wp_blocks_namespaceObject.rawHandler)({
HTML: block.originalContent
});
const recoverBlock = _ref2 => {
let {
name,
attributes,
innerBlocks
} = _ref2;
return (0,external_wp_blocks_namespaceObject.createBlock)(name, attributes, innerBlocks);
};
/* harmony default export */ var block_invalid_warning = ((0,external_wp_compose_namespaceObject.compose)([(0,external_wp_data_namespaceObject.withSelect)((select, _ref3) => {
let {
clientId
} = _ref3;
return {
block: select(store).getBlock(clientId)
};
}), (0,external_wp_data_namespaceObject.withDispatch)((dispatch, _ref4) => {
let {
block
} = _ref4;
const {
replaceBlock
} = dispatch(store);
return {
convertToClassic() {
replaceBlock(block.clientId, blockToClassic(block));
},
convertToHTML() {
replaceBlock(block.clientId, blockToHTML(block));
},
convertToBlocks() {
replaceBlock(block.clientId, blockToBlocks(block));
},
attemptBlockRecovery() {
replaceBlock(block.clientId, recoverBlock(block));
}
};
})])(BlockInvalidWarning));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-list/block-crash-warning.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const block_crash_warning_warning = (0,external_wp_element_namespaceObject.createElement)(warning, {
className: "block-editor-block-list__block-crash-warning"
}, (0,external_wp_i18n_namespaceObject.__)('This block has encountered an error and cannot be previewed.'));
/* harmony default export */ var block_crash_warning = (() => block_crash_warning_warning);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-list/block-crash-boundary.js
/**
* WordPress dependencies
*/
class BlockCrashBoundary extends external_wp_element_namespaceObject.Component {
constructor() {
super(...arguments);
this.state = {
hasError: false
};
}
componentDidCatch() {
this.setState({
hasError: true
});
}
render() {
if (this.state.hasError) {
return this.props.fallback;
}
return this.props.children;
}
}
/* harmony default export */ var block_crash_boundary = (BlockCrashBoundary);
// EXTERNAL MODULE: ./node_modules/react-autosize-textarea/lib/index.js
var lib = __webpack_require__(773);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-list/block-html.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function BlockHTML(_ref) {
let {
clientId
} = _ref;
const [html, setHtml] = (0,external_wp_element_namespaceObject.useState)('');
const block = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).getBlock(clientId), [clientId]);
const {
updateBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const onChange = () => {
const blockType = (0,external_wp_blocks_namespaceObject.getBlockType)(block.name);
if (!blockType) {
return;
}
const attributes = (0,external_wp_blocks_namespaceObject.getBlockAttributes)(blockType, html, block.attributes); // If html is empty we reset the block to the default HTML and mark it as valid to avoid triggering an error
const content = html ? html : (0,external_wp_blocks_namespaceObject.getSaveContent)(blockType, attributes);
const [isValid] = html ? (0,external_wp_blocks_namespaceObject.validateBlock)({ ...block,
attributes,
originalContent: content
}) : [true];
updateBlock(clientId, {
attributes,
originalContent: content,
isValid
}); // Ensure the state is updated if we reset so it displays the default content.
if (!html) {
setHtml({
content
});
}
};
(0,external_wp_element_namespaceObject.useEffect)(() => {
setHtml((0,external_wp_blocks_namespaceObject.getBlockContent)(block));
}, [block]);
return (0,external_wp_element_namespaceObject.createElement)(lib/* default */.Z, {
className: "block-editor-block-list__block-html-textarea",
value: html,
onBlur: onChange,
onChange: event => setHtml(event.target.value)
});
}
/* harmony default export */ var block_html = (BlockHTML);
// EXTERNAL MODULE: external "React"
var external_React_ = __webpack_require__(9196);
var external_React_default = /*#__PURE__*/__webpack_require__.n(external_React_);
;// CONCATENATED MODULE: ./node_modules/@react-spring/shared/dist/react-spring_shared.modern.mjs
var __defProp = Object.defineProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
// src/globals.ts
var globals_exports = {};
__export(globals_exports, {
assign: () => react_spring_shared_modern_assign,
colors: () => colors,
createStringInterpolator: () => createStringInterpolator,
skipAnimation: () => skipAnimation,
to: () => to,
willAdvance: () => willAdvance
});
// ../rafz/dist/react-spring_rafz.modern.mjs
var updateQueue = makeQueue();
var raf = (fn) => schedule(fn, updateQueue);
var writeQueue = makeQueue();
raf.write = (fn) => schedule(fn, writeQueue);
var onStartQueue = makeQueue();
raf.onStart = (fn) => schedule(fn, onStartQueue);
var onFrameQueue = makeQueue();
raf.onFrame = (fn) => schedule(fn, onFrameQueue);
var onFinishQueue = makeQueue();
raf.onFinish = (fn) => schedule(fn, onFinishQueue);
var timeouts = [];
raf.setTimeout = (handler, ms) => {
const time = raf.now() + ms;
const cancel = () => {
const i = timeouts.findIndex((t) => t.cancel == cancel);
if (~i)
timeouts.splice(i, 1);
pendingCount -= ~i ? 1 : 0;
};
const timeout = { time, handler, cancel };
timeouts.splice(findTimeout(time), 0, timeout);
pendingCount += 1;
start();
return timeout;
};
var findTimeout = (time) => ~(~timeouts.findIndex((t) => t.time > time) || ~timeouts.length);
raf.cancel = (fn) => {
onStartQueue.delete(fn);
onFrameQueue.delete(fn);
onFinishQueue.delete(fn);
updateQueue.delete(fn);
writeQueue.delete(fn);
};
raf.sync = (fn) => {
sync = true;
raf.batchedUpdates(fn);
sync = false;
};
raf.throttle = (fn) => {
let lastArgs;
function queuedFn() {
try {
fn(...lastArgs);
} finally {
lastArgs = null;
}
}
function throttled(...args) {
lastArgs = args;
raf.onStart(queuedFn);
}
throttled.handler = fn;
throttled.cancel = () => {
onStartQueue.delete(queuedFn);
lastArgs = null;
};
return throttled;
};
var nativeRaf = typeof window != "undefined" ? window.requestAnimationFrame : (
// eslint-disable-next-line @typescript-eslint/no-empty-function
() => {
}
);
raf.use = (impl) => nativeRaf = impl;
raf.now = typeof performance != "undefined" ? () => performance.now() : Date.now;
raf.batchedUpdates = (fn) => fn();
raf.catch = console.error;
raf.frameLoop = "always";
raf.advance = () => {
if (raf.frameLoop !== "demand") {
console.warn(
"Cannot call the manual advancement of rafz whilst frameLoop is not set as demand"
);
} else {
update();
}
};
var ts = -1;
var pendingCount = 0;
var sync = false;
function schedule(fn, queue) {
if (sync) {
queue.delete(fn);
fn(0);
} else {
queue.add(fn);
start();
}
}
function start() {
if (ts < 0) {
ts = 0;
if (raf.frameLoop !== "demand") {
nativeRaf(loop);
}
}
}
function stop() {
ts = -1;
}
function loop() {
if (~ts) {
nativeRaf(loop);
raf.batchedUpdates(update);
}
}
function update() {
const prevTs = ts;
ts = raf.now();
const count = findTimeout(ts);
if (count) {
eachSafely(timeouts.splice(0, count), (t) => t.handler());
pendingCount -= count;
}
if (!pendingCount) {
stop();
return;
}
onStartQueue.flush();
updateQueue.flush(prevTs ? Math.min(64, ts - prevTs) : 16.667);
onFrameQueue.flush();
writeQueue.flush();
onFinishQueue.flush();
}
function makeQueue() {
let next = /* @__PURE__ */ new Set();
let current = next;
return {
add(fn) {
pendingCount += current == next && !next.has(fn) ? 1 : 0;
next.add(fn);
},
delete(fn) {
pendingCount -= current == next && next.has(fn) ? 1 : 0;
return next.delete(fn);
},
flush(arg) {
if (current.size) {
next = /* @__PURE__ */ new Set();
pendingCount -= current.size;
eachSafely(current, (fn) => fn(arg) && next.add(fn));
pendingCount += next.size;
current = next;
}
}
};
}
function eachSafely(values, each2) {
values.forEach((value) => {
try {
each2(value);
} catch (e) {
raf.catch(e);
}
});
}
// src/helpers.ts
function noop() {
}
var defineHidden = (obj, key, value) => Object.defineProperty(obj, key, { value, writable: true, configurable: true });
var is = {
arr: Array.isArray,
obj: (a) => !!a && a.constructor.name === "Object",
fun: (a) => typeof a === "function",
str: (a) => typeof a === "string",
num: (a) => typeof a === "number",
und: (a) => a === void 0
};
function isEqual(a, b) {
if (is.arr(a)) {
if (!is.arr(b) || a.length !== b.length)
return false;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i])
return false;
}
return true;
}
return a === b;
}
var react_spring_shared_modern_each = (obj, fn) => obj.forEach(fn);
function eachProp(obj, fn, ctx) {
if (is.arr(obj)) {
for (let i = 0; i < obj.length; i++) {
fn.call(ctx, obj[i], `${i}`);
}
return;
}
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
fn.call(ctx, obj[key], key);
}
}
}
var toArray = (a) => is.und(a) ? [] : is.arr(a) ? a : [a];
function flush(queue, iterator) {
if (queue.size) {
const items = Array.from(queue);
queue.clear();
react_spring_shared_modern_each(items, iterator);
}
}
var flushCalls = (queue, ...args) => flush(queue, (fn) => fn(...args));
var isSSR = () => typeof window === "undefined" || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent);
// src/globals.ts
var createStringInterpolator;
var to;
var colors = null;
var skipAnimation = false;
var willAdvance = noop;
var react_spring_shared_modern_assign = (globals) => {
if (globals.to)
to = globals.to;
if (globals.now)
raf.now = globals.now;
if (globals.colors !== void 0)
colors = globals.colors;
if (globals.skipAnimation != null)
skipAnimation = globals.skipAnimation;
if (globals.createStringInterpolator)
createStringInterpolator = globals.createStringInterpolator;
if (globals.requestAnimationFrame)
raf.use(globals.requestAnimationFrame);
if (globals.batchedUpdates)
raf.batchedUpdates = globals.batchedUpdates;
if (globals.willAdvance)
willAdvance = globals.willAdvance;
if (globals.frameLoop)
raf.frameLoop = globals.frameLoop;
};
// src/FrameLoop.ts
var startQueue = /* @__PURE__ */ new Set();
var currentFrame = [];
var prevFrame = [];
var priority = 0;
var frameLoop = {
get idle() {
return !startQueue.size && !currentFrame.length;
},
/** Advance the given animation on every frame until idle. */
start(animation) {
if (priority > animation.priority) {
startQueue.add(animation);
raf.onStart(flushStartQueue);
} else {
startSafely(animation);
raf(advance);
}
},
/** Advance all animations by the given time. */
advance,
/** Call this when an animation's priority changes. */
sort(animation) {
if (priority) {
raf.onFrame(() => frameLoop.sort(animation));
} else {
const prevIndex = currentFrame.indexOf(animation);
if (~prevIndex) {
currentFrame.splice(prevIndex, 1);
startUnsafely(animation);
}
}
},
/**
* Clear all animations. For testing purposes.
*
* ☠️ Never call this from within the frameloop.
*/
clear() {
currentFrame = [];
startQueue.clear();
}
};
function flushStartQueue() {
startQueue.forEach(startSafely);
startQueue.clear();
raf(advance);
}
function startSafely(animation) {
if (!currentFrame.includes(animation))
startUnsafely(animation);
}
function startUnsafely(animation) {
currentFrame.splice(
findIndex(currentFrame, (other) => other.priority > animation.priority),
0,
animation
);
}
function advance(dt) {
const nextFrame = prevFrame;
for (let i = 0; i < currentFrame.length; i++) {
const animation = currentFrame[i];
priority = animation.priority;
if (!animation.idle) {
willAdvance(animation);
animation.advance(dt);
if (!animation.idle) {
nextFrame.push(animation);
}
}
}
priority = 0;
prevFrame = currentFrame;
prevFrame.length = 0;
currentFrame = nextFrame;
return currentFrame.length > 0;
}
function findIndex(arr, test) {
const index = arr.findIndex(test);
return index < 0 ? arr.length : index;
}
// src/clamp.ts
var clamp = (min, max, v) => Math.min(Math.max(v, min), max);
// src/colors.ts
var colors2 = {
transparent: 0,
aliceblue: 4042850303,
antiquewhite: 4209760255,
aqua: 16777215,
aquamarine: 2147472639,
azure: 4043309055,
beige: 4126530815,
bisque: 4293182719,
black: 255,
blanchedalmond: 4293643775,
blue: 65535,
blueviolet: 2318131967,
brown: 2771004159,
burlywood: 3736635391,
burntsienna: 3934150143,
cadetblue: 1604231423,
chartreuse: 2147418367,
chocolate: 3530104575,
coral: 4286533887,
cornflowerblue: 1687547391,
cornsilk: 4294499583,
crimson: 3692313855,
cyan: 16777215,
darkblue: 35839,
darkcyan: 9145343,
darkgoldenrod: 3095792639,
darkgray: 2846468607,
darkgreen: 6553855,
darkgrey: 2846468607,
darkkhaki: 3182914559,
darkmagenta: 2332068863,
darkolivegreen: 1433087999,
darkorange: 4287365375,
darkorchid: 2570243327,
darkred: 2332033279,
darksalmon: 3918953215,
darkseagreen: 2411499519,
darkslateblue: 1211993087,
darkslategray: 793726975,
darkslategrey: 793726975,
darkturquoise: 13554175,
darkviolet: 2483082239,
deeppink: 4279538687,
deepskyblue: 12582911,
dimgray: 1768516095,
dimgrey: 1768516095,
dodgerblue: 512819199,
firebrick: 2988581631,
floralwhite: 4294635775,
forestgreen: 579543807,
fuchsia: 4278255615,
gainsboro: 3705462015,
ghostwhite: 4177068031,
gold: 4292280575,
goldenrod: 3668254975,
gray: 2155905279,
green: 8388863,
greenyellow: 2919182335,
grey: 2155905279,
honeydew: 4043305215,
hotpink: 4285117695,
indianred: 3445382399,
indigo: 1258324735,
ivory: 4294963455,
khaki: 4041641215,
lavender: 3873897215,
lavenderblush: 4293981695,
lawngreen: 2096890111,
lemonchiffon: 4294626815,
lightblue: 2916673279,
lightcoral: 4034953471,
lightcyan: 3774873599,
lightgoldenrodyellow: 4210742015,
lightgray: 3553874943,
lightgreen: 2431553791,
lightgrey: 3553874943,
lightpink: 4290167295,
lightsalmon: 4288707327,
lightseagreen: 548580095,
lightskyblue: 2278488831,
lightslategray: 2005441023,
lightslategrey: 2005441023,
lightsteelblue: 2965692159,
lightyellow: 4294959359,
lime: 16711935,
limegreen: 852308735,
linen: 4210091775,
magenta: 4278255615,
maroon: 2147483903,
mediumaquamarine: 1724754687,
mediumblue: 52735,
mediumorchid: 3126187007,
mediumpurple: 2473647103,
mediumseagreen: 1018393087,
mediumslateblue: 2070474495,
mediumspringgreen: 16423679,
mediumturquoise: 1221709055,
mediumvioletred: 3340076543,
midnightblue: 421097727,
mintcream: 4127193855,
mistyrose: 4293190143,
moccasin: 4293178879,
navajowhite: 4292783615,
navy: 33023,
oldlace: 4260751103,
olive: 2155872511,
olivedrab: 1804477439,
orange: 4289003775,
orangered: 4282712319,
orchid: 3664828159,
palegoldenrod: 4008225535,
palegreen: 2566625535,
paleturquoise: 2951671551,
palevioletred: 3681588223,
papayawhip: 4293907967,
peachpuff: 4292524543,
peru: 3448061951,
pink: 4290825215,
plum: 3718307327,
powderblue: 2967529215,
purple: 2147516671,
rebeccapurple: 1714657791,
red: 4278190335,
rosybrown: 3163525119,
royalblue: 1097458175,
saddlebrown: 2336560127,
salmon: 4202722047,
sandybrown: 4104413439,
seagreen: 780883967,
seashell: 4294307583,
sienna: 2689740287,
silver: 3233857791,
skyblue: 2278484991,
slateblue: 1784335871,
slategray: 1887473919,
slategrey: 1887473919,
snow: 4294638335,
springgreen: 16744447,
steelblue: 1182971135,
tan: 3535047935,
teal: 8421631,
thistle: 3636451583,
tomato: 4284696575,
turquoise: 1088475391,
violet: 4001558271,
wheat: 4125012991,
white: 4294967295,
whitesmoke: 4126537215,
yellow: 4294902015,
yellowgreen: 2597139199
};
// src/colorMatchers.ts
var NUMBER = "[-+]?\\d*\\.?\\d+";
var PERCENTAGE = NUMBER + "%";
function call(...parts) {
return "\\(\\s*(" + parts.join(")\\s*,\\s*(") + ")\\s*\\)";
}
var rgb = new RegExp("rgb" + call(NUMBER, NUMBER, NUMBER));
var rgba = new RegExp("rgba" + call(NUMBER, NUMBER, NUMBER, NUMBER));
var hsl = new RegExp("hsl" + call(NUMBER, PERCENTAGE, PERCENTAGE));
var hsla = new RegExp(
"hsla" + call(NUMBER, PERCENTAGE, PERCENTAGE, NUMBER)
);
var hex3 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/;
var hex4 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/;
var hex6 = /^#([0-9a-fA-F]{6})$/;
var hex8 = /^#([0-9a-fA-F]{8})$/;
// src/normalizeColor.ts
function normalizeColor(color) {
let match;
if (typeof color === "number") {
return color >>> 0 === color && color >= 0 && color <= 4294967295 ? color : null;
}
if (match = hex6.exec(color))
return parseInt(match[1] + "ff", 16) >>> 0;
if (colors && colors[color] !== void 0) {
return colors[color];
}
if (match = rgb.exec(color)) {
return (parse255(match[1]) << 24 | // r
parse255(match[2]) << 16 | // g
parse255(match[3]) << 8 | // b
255) >>> // a
0;
}
if (match = rgba.exec(color)) {
return (parse255(match[1]) << 24 | // r
parse255(match[2]) << 16 | // g
parse255(match[3]) << 8 | // b
parse1(match[4])) >>> // a
0;
}
if (match = hex3.exec(color)) {
return parseInt(
match[1] + match[1] + // r
match[2] + match[2] + // g
match[3] + match[3] + // b
"ff",
// a
16
) >>> 0;
}
if (match = hex8.exec(color))
return parseInt(match[1], 16) >>> 0;
if (match = hex4.exec(color)) {
return parseInt(
match[1] + match[1] + // r
match[2] + match[2] + // g
match[3] + match[3] + // b
match[4] + match[4],
// a
16
) >>> 0;
}
if (match = hsl.exec(color)) {
return (hslToRgb(
parse360(match[1]),
// h
parsePercentage(match[2]),
// s
parsePercentage(match[3])
// l
) | 255) >>> // a
0;
}
if (match = hsla.exec(color)) {
return (hslToRgb(
parse360(match[1]),
// h
parsePercentage(match[2]),
// s
parsePercentage(match[3])
// l
) | parse1(match[4])) >>> // a
0;
}
return null;
}
function hue2rgb(p, q, t) {
if (t < 0)
t += 1;
if (t > 1)
t -= 1;
if (t < 1 / 6)
return p + (q - p) * 6 * t;
if (t < 1 / 2)
return q;
if (t < 2 / 3)
return p + (q - p) * (2 / 3 - t) * 6;
return p;
}
function hslToRgb(h, s, l) {
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
const r = hue2rgb(p, q, h + 1 / 3);
const g = hue2rgb(p, q, h);
const b = hue2rgb(p, q, h - 1 / 3);
return Math.round(r * 255) << 24 | Math.round(g * 255) << 16 | Math.round(b * 255) << 8;
}
function parse255(str) {
const int = parseInt(str, 10);
if (int < 0)
return 0;
if (int > 255)
return 255;
return int;
}
function parse360(str) {
const int = parseFloat(str);
return (int % 360 + 360) % 360 / 360;
}
function parse1(str) {
const num = parseFloat(str);
if (num < 0)
return 0;
if (num > 1)
return 255;
return Math.round(num * 255);
}
function parsePercentage(str) {
const int = parseFloat(str);
if (int < 0)
return 0;
if (int > 100)
return 1;
return int / 100;
}
// src/colorToRgba.ts
function colorToRgba(input) {
let int32Color = normalizeColor(input);
if (int32Color === null)
return input;
int32Color = int32Color || 0;
const r = (int32Color & 4278190080) >>> 24;
const g = (int32Color & 16711680) >>> 16;
const b = (int32Color & 65280) >>> 8;
const a = (int32Color & 255) / 255;
return `rgba(${r}, ${g}, ${b}, ${a})`;
}
// src/createInterpolator.ts
var createInterpolator = (range, output, extrapolate) => {
if (is.fun(range)) {
return range;
}
if (is.arr(range)) {
return createInterpolator({
range,
output,
extrapolate
});
}
if (is.str(range.output[0])) {
return createStringInterpolator(range);
}
const config = range;
const outputRange = config.output;
const inputRange = config.range || [0, 1];
const extrapolateLeft = config.extrapolateLeft || config.extrapolate || "extend";
const extrapolateRight = config.extrapolateRight || config.extrapolate || "extend";
const easing = config.easing || ((t) => t);
return (input) => {
const range2 = findRange(input, inputRange);
return interpolate(
input,
inputRange[range2],
inputRange[range2 + 1],
outputRange[range2],
outputRange[range2 + 1],
easing,
extrapolateLeft,
extrapolateRight,
config.map
);
};
};
function interpolate(input, inputMin, inputMax, outputMin, outputMax, easing, extrapolateLeft, extrapolateRight, map) {
let result = map ? map(input) : input;
if (result < inputMin) {
if (extrapolateLeft === "identity")
return result;
else if (extrapolateLeft === "clamp")
result = inputMin;
}
if (result > inputMax) {
if (extrapolateRight === "identity")
return result;
else if (extrapolateRight === "clamp")
result = inputMax;
}
if (outputMin === outputMax)
return outputMin;
if (inputMin === inputMax)
return input <= inputMin ? outputMin : outputMax;
if (inputMin === -Infinity)
result = -result;
else if (inputMax === Infinity)
result = result - inputMin;
else
result = (result - inputMin) / (inputMax - inputMin);
result = easing(result);
if (outputMin === -Infinity)
result = -result;
else if (outputMax === Infinity)
result = result + outputMin;
else
result = result * (outputMax - outputMin) + outputMin;
return result;
}
function findRange(input, inputRange) {
for (var i = 1; i < inputRange.length - 1; ++i)
if (inputRange[i] >= input)
break;
return i - 1;
}
// src/easings.ts
var steps = (steps2, direction = "end") => (progress2) => {
progress2 = direction === "end" ? Math.min(progress2, 0.999) : Math.max(progress2, 1e-3);
const expanded = progress2 * steps2;
const rounded = direction === "end" ? Math.floor(expanded) : Math.ceil(expanded);
return clamp(0, 1, rounded / steps2);
};
var c1 = 1.70158;
var c2 = c1 * 1.525;
var c3 = c1 + 1;
var c4 = 2 * Math.PI / 3;
var c5 = 2 * Math.PI / 4.5;
var bounceOut = (x) => {
const n1 = 7.5625;
const d1 = 2.75;
if (x < 1 / d1) {
return n1 * x * x;
} else if (x < 2 / d1) {
return n1 * (x -= 1.5 / d1) * x + 0.75;
} else if (x < 2.5 / d1) {
return n1 * (x -= 2.25 / d1) * x + 0.9375;
} else {
return n1 * (x -= 2.625 / d1) * x + 0.984375;
}
};
var easings = {
linear: (x) => x,
easeInQuad: (x) => x * x,
easeOutQuad: (x) => 1 - (1 - x) * (1 - x),
easeInOutQuad: (x) => x < 0.5 ? 2 * x * x : 1 - Math.pow(-2 * x + 2, 2) / 2,
easeInCubic: (x) => x * x * x,
easeOutCubic: (x) => 1 - Math.pow(1 - x, 3),
easeInOutCubic: (x) => x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2,
easeInQuart: (x) => x * x * x * x,
easeOutQuart: (x) => 1 - Math.pow(1 - x, 4),
easeInOutQuart: (x) => x < 0.5 ? 8 * x * x * x * x : 1 - Math.pow(-2 * x + 2, 4) / 2,
easeInQuint: (x) => x * x * x * x * x,
easeOutQuint: (x) => 1 - Math.pow(1 - x, 5),
easeInOutQuint: (x) => x < 0.5 ? 16 * x * x * x * x * x : 1 - Math.pow(-2 * x + 2, 5) / 2,
easeInSine: (x) => 1 - Math.cos(x * Math.PI / 2),
easeOutSine: (x) => Math.sin(x * Math.PI / 2),
easeInOutSine: (x) => -(Math.cos(Math.PI * x) - 1) / 2,
easeInExpo: (x) => x === 0 ? 0 : Math.pow(2, 10 * x - 10),
easeOutExpo: (x) => x === 1 ? 1 : 1 - Math.pow(2, -10 * x),
easeInOutExpo: (x) => x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ? Math.pow(2, 20 * x - 10) / 2 : (2 - Math.pow(2, -20 * x + 10)) / 2,
easeInCirc: (x) => 1 - Math.sqrt(1 - Math.pow(x, 2)),
easeOutCirc: (x) => Math.sqrt(1 - Math.pow(x - 1, 2)),
easeInOutCirc: (x) => x < 0.5 ? (1 - Math.sqrt(1 - Math.pow(2 * x, 2))) / 2 : (Math.sqrt(1 - Math.pow(-2 * x + 2, 2)) + 1) / 2,
easeInBack: (x) => c3 * x * x * x - c1 * x * x,
easeOutBack: (x) => 1 + c3 * Math.pow(x - 1, 3) + c1 * Math.pow(x - 1, 2),
easeInOutBack: (x) => x < 0.5 ? Math.pow(2 * x, 2) * ((c2 + 1) * 2 * x - c2) / 2 : (Math.pow(2 * x - 2, 2) * ((c2 + 1) * (x * 2 - 2) + c2) + 2) / 2,
easeInElastic: (x) => x === 0 ? 0 : x === 1 ? 1 : -Math.pow(2, 10 * x - 10) * Math.sin((x * 10 - 10.75) * c4),
easeOutElastic: (x) => x === 0 ? 0 : x === 1 ? 1 : Math.pow(2, -10 * x) * Math.sin((x * 10 - 0.75) * c4) + 1,
easeInOutElastic: (x) => x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ? -(Math.pow(2, 20 * x - 10) * Math.sin((20 * x - 11.125) * c5)) / 2 : Math.pow(2, -20 * x + 10) * Math.sin((20 * x - 11.125) * c5) / 2 + 1,
easeInBounce: (x) => 1 - bounceOut(1 - x),
easeOutBounce: bounceOut,
easeInOutBounce: (x) => x < 0.5 ? (1 - bounceOut(1 - 2 * x)) / 2 : (1 + bounceOut(2 * x - 1)) / 2,
steps
};
// src/fluids.ts
var $get = Symbol.for("FluidValue.get");
var $observers = Symbol.for("FluidValue.observers");
var hasFluidValue = (arg) => Boolean(arg && arg[$get]);
var getFluidValue = (arg) => arg && arg[$get] ? arg[$get]() : arg;
var getFluidObservers = (target) => target[$observers] || null;
function callFluidObserver(observer2, event) {
if (observer2.eventObserved) {
observer2.eventObserved(event);
} else {
observer2(event);
}
}
function callFluidObservers(target, event) {
const observers = target[$observers];
if (observers) {
observers.forEach((observer2) => {
callFluidObserver(observer2, event);
});
}
}
var FluidValue = class {
constructor(get) {
if (!get && !(get = this.get)) {
throw Error("Unknown getter");
}
setFluidGetter(this, get);
}
};
$get, $observers;
var setFluidGetter = (target, get) => setHidden(target, $get, get);
function addFluidObserver(target, observer2) {
if (target[$get]) {
let observers = target[$observers];
if (!observers) {
setHidden(target, $observers, observers = /* @__PURE__ */ new Set());
}
if (!observers.has(observer2)) {
observers.add(observer2);
if (target.observerAdded) {
target.observerAdded(observers.size, observer2);
}
}
}
return observer2;
}
function removeFluidObserver(target, observer2) {
const observers = target[$observers];
if (observers && observers.has(observer2)) {
const count = observers.size - 1;
if (count) {
observers.delete(observer2);
} else {
target[$observers] = null;
}
if (target.observerRemoved) {
target.observerRemoved(count, observer2);
}
}
}
var setHidden = (target, key, value) => Object.defineProperty(target, key, {
value,
writable: true,
configurable: true
});
// src/regexs.ts
var numberRegex = /[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
var colorRegex = /(#(?:[0-9a-f]{2}){2,4}|(#[0-9a-f]{3})|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d\.]+%?\))/gi;
var unitRegex = new RegExp(`(${numberRegex.source})(%|[a-z]+)`, "i");
var rgbaRegex = /rgba\(([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+)\)/gi;
var cssVariableRegex = /var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/;
// src/variableToRgba.ts
var variableToRgba = (input) => {
const [token, fallback] = parseCSSVariable(input);
if (!token || isSSR()) {
return input;
}
const value = window.getComputedStyle(document.documentElement).getPropertyValue(token);
if (value) {
return value.trim();
} else if (fallback && fallback.startsWith("--")) {
const value2 = window.getComputedStyle(document.documentElement).getPropertyValue(fallback);
if (value2) {
return value2;
} else {
return input;
}
} else if (fallback && cssVariableRegex.test(fallback)) {
return variableToRgba(fallback);
} else if (fallback) {
return fallback;
}
return input;
};
var parseCSSVariable = (current) => {
const match = cssVariableRegex.exec(current);
if (!match)
return [,];
const [, token, fallback] = match;
return [token, fallback];
};
// src/stringInterpolation.ts
var namedColorRegex;
var rgbaRound = (_, p1, p2, p3, p4) => `rgba(${Math.round(p1)}, ${Math.round(p2)}, ${Math.round(p3)}, ${p4})`;
var createStringInterpolator2 = (config) => {
if (!namedColorRegex)
namedColorRegex = colors ? (
// match color names, ignore partial matches
new RegExp(`(${Object.keys(colors).join("|")})(?!\\w)`, "g")
) : (
// never match
/^\b$/
);
const output = config.output.map((value) => {
return getFluidValue(value).replace(cssVariableRegex, variableToRgba).replace(colorRegex, colorToRgba).replace(namedColorRegex, colorToRgba);
});
const keyframes = output.map((value) => value.match(numberRegex).map(Number));
const outputRanges = keyframes[0].map(
(_, i) => keyframes.map((values) => {
if (!(i in values)) {
throw Error('The arity of each "output" value must be equal');
}
return values[i];
})
);
const interpolators = outputRanges.map(
(output2) => createInterpolator({ ...config, output: output2 })
);
return (input) => {
const missingUnit = !unitRegex.test(output[0]) && output.find((value) => unitRegex.test(value))?.replace(numberRegex, "");
let i = 0;
return output[0].replace(
numberRegex,
() => `${interpolators[i++](input)}${missingUnit || ""}`
).replace(rgbaRegex, rgbaRound);
};
};
// src/deprecations.ts
var prefix = "react-spring: ";
var once = (fn) => {
const func = fn;
let called = false;
if (typeof func != "function") {
throw new TypeError(`${prefix}once requires a function parameter`);
}
return (...args) => {
if (!called) {
func(...args);
called = true;
}
};
};
var warnInterpolate = once(console.warn);
function deprecateInterpolate() {
warnInterpolate(
`${prefix}The "interpolate" function is deprecated in v9 (use "to" instead)`
);
}
var warnDirectCall = once(console.warn);
function deprecateDirectCall() {
warnDirectCall(
`${prefix}Directly calling start instead of using the api object is deprecated in v9 (use ".start" instead), this will be removed in later 0.X.0 versions`
);
}
// src/isAnimatedString.ts
function isAnimatedString(value) {
return is.str(value) && (value[0] == "#" || /\d/.test(value) || // Do not identify a CSS variable as an AnimatedString if its SSR
!isSSR() && cssVariableRegex.test(value) || value in (colors || {}));
}
// src/dom-events/resize/resizeElement.ts
var observer;
var resizeHandlers = /* @__PURE__ */ new WeakMap();
var handleObservation = (entries) => entries.forEach(({ target, contentRect }) => {
return resizeHandlers.get(target)?.forEach((handler) => handler(contentRect));
});
function resizeElement(handler, target) {
if (!observer) {
if (typeof ResizeObserver !== "undefined") {
observer = new ResizeObserver(handleObservation);
}
}
let elementHandlers = resizeHandlers.get(target);
if (!elementHandlers) {
elementHandlers = /* @__PURE__ */ new Set();
resizeHandlers.set(target, elementHandlers);
}
elementHandlers.add(handler);
if (observer) {
observer.observe(target);
}
return () => {
const elementHandlers2 = resizeHandlers.get(target);
if (!elementHandlers2)
return;
elementHandlers2.delete(handler);
if (!elementHandlers2.size && observer) {
observer.unobserve(target);
}
};
}
// src/dom-events/resize/resizeWindow.ts
var listeners = /* @__PURE__ */ new Set();
var cleanupWindowResizeHandler;
var createResizeHandler = () => {
const handleResize = () => {
listeners.forEach(
(callback) => callback({
width: window.innerWidth,
height: window.innerHeight
})
);
};
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
};
};
var resizeWindow = (callback) => {
listeners.add(callback);
if (!cleanupWindowResizeHandler) {
cleanupWindowResizeHandler = createResizeHandler();
}
return () => {
listeners.delete(callback);
if (!listeners.size && cleanupWindowResizeHandler) {
cleanupWindowResizeHandler();
cleanupWindowResizeHandler = void 0;
}
};
};
// src/dom-events/resize/index.ts
var react_spring_shared_modern_onResize = (callback, { container = document.documentElement } = {}) => {
if (container === document.documentElement) {
return resizeWindow(callback);
} else {
return resizeElement(callback, container);
}
};
// src/progress.ts
var progress = (min, max, value) => max - min === 0 ? 1 : (value - min) / (max - min);
// src/dom-events/scroll/ScrollHandler.ts
var SCROLL_KEYS = {
x: {
length: "Width",
position: "Left"
},
y: {
length: "Height",
position: "Top"
}
};
var ScrollHandler = class {
constructor(callback, container) {
this.createAxis = () => ({
current: 0,
progress: 0,
scrollLength: 0
});
this.updateAxis = (axisName) => {
const axis = this.info[axisName];
const { length, position } = SCROLL_KEYS[axisName];
axis.current = this.container[`scroll${position}`];
axis.scrollLength = this.container["scroll" + length] - this.container["client" + length];
axis.progress = progress(0, axis.scrollLength, axis.current);
};
this.update = () => {
this.updateAxis("x");
this.updateAxis("y");
};
this.sendEvent = () => {
this.callback(this.info);
};
this.advance = () => {
this.update();
this.sendEvent();
};
this.callback = callback;
this.container = container;
this.info = {
time: 0,
x: this.createAxis(),
y: this.createAxis()
};
}
};
// src/dom-events/scroll/index.ts
var scrollListeners = /* @__PURE__ */ new WeakMap();
var resizeListeners = /* @__PURE__ */ new WeakMap();
var onScrollHandlers = /* @__PURE__ */ new WeakMap();
var getTarget = (container) => container === document.documentElement ? window : container;
var react_spring_shared_modern_onScroll = (callback, { container = document.documentElement } = {}) => {
let containerHandlers = onScrollHandlers.get(container);
if (!containerHandlers) {
containerHandlers = /* @__PURE__ */ new Set();
onScrollHandlers.set(container, containerHandlers);
}
const containerHandler = new ScrollHandler(callback, container);
containerHandlers.add(containerHandler);
if (!scrollListeners.has(container)) {
const listener = () => {
containerHandlers?.forEach((handler) => handler.advance());
return true;
};
scrollListeners.set(container, listener);
const target = getTarget(container);
window.addEventListener("resize", listener, { passive: true });
if (container !== document.documentElement) {
resizeListeners.set(container, react_spring_shared_modern_onResize(listener, { container }));
}
target.addEventListener("scroll", listener, { passive: true });
}
const animateScroll = scrollListeners.get(container);
raf(animateScroll);
return () => {
raf.cancel(animateScroll);
const containerHandlers2 = onScrollHandlers.get(container);
if (!containerHandlers2)
return;
containerHandlers2.delete(containerHandler);
if (containerHandlers2.size)
return;
const listener = scrollListeners.get(container);
scrollListeners.delete(container);
if (listener) {
getTarget(container).removeEventListener("scroll", listener);
window.removeEventListener("resize", listener);
resizeListeners.get(container)?.();
}
};
};
// src/hooks/useConstant.ts
function react_spring_shared_modern_useConstant(init) {
const ref = useRef(null);
if (ref.current === null) {
ref.current = init();
}
return ref.current;
}
// src/hooks/useForceUpdate.ts
// src/hooks/useIsMounted.ts
// src/hooks/useIsomorphicLayoutEffect.ts
var react_spring_shared_modern_useIsomorphicLayoutEffect = isSSR() ? external_React_.useEffect : external_React_.useLayoutEffect;
// src/hooks/useIsMounted.ts
var useIsMounted = () => {
const isMounted = (0,external_React_.useRef)(false);
react_spring_shared_modern_useIsomorphicLayoutEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);
return isMounted;
};
// src/hooks/useForceUpdate.ts
function useForceUpdate() {
const update2 = (0,external_React_.useState)()[1];
const isMounted = useIsMounted();
return () => {
if (isMounted.current) {
update2(Math.random());
}
};
}
// src/hooks/useMemoOne.ts
function useMemoOne(getResult, inputs) {
const [initial] = (0,external_React_.useState)(
() => ({
inputs,
result: getResult()
})
);
const committed = (0,external_React_.useRef)();
const prevCache = committed.current;
let cache = prevCache;
if (cache) {
const useCache = Boolean(
inputs && cache.inputs && areInputsEqual(inputs, cache.inputs)
);
if (!useCache) {
cache = {
inputs,
result: getResult()
};
}
} else {
cache = initial;
}
(0,external_React_.useEffect)(() => {
committed.current = cache;
if (prevCache == initial) {
initial.inputs = initial.result = void 0;
}
}, [cache]);
return cache.result;
}
function areInputsEqual(next, prev) {
if (next.length !== prev.length) {
return false;
}
for (let i = 0; i < next.length; i++) {
if (next[i] !== prev[i]) {
return false;
}
}
return true;
}
// src/hooks/useOnce.ts
var useOnce = (effect) => (0,external_React_.useEffect)(effect, emptyDeps);
var emptyDeps = [];
// src/hooks/usePrev.ts
function usePrev(value) {
const prevRef = (0,external_React_.useRef)();
(0,external_React_.useEffect)(() => {
prevRef.current = value;
});
return prevRef.current;
}
// src/hooks/useReducedMotion.ts
var useReducedMotion = () => {
const [reducedMotion, setReducedMotion] = useState3(null);
react_spring_shared_modern_useIsomorphicLayoutEffect(() => {
const mql = window.matchMedia("(prefers-reduced-motion)");
const handleMediaChange = (e) => {
setReducedMotion(e.matches);
react_spring_shared_modern_assign({
skipAnimation: e.matches
});
};
handleMediaChange(mql);
mql.addEventListener("change", handleMediaChange);
return () => {
mql.removeEventListener("change", handleMediaChange);
};
}, []);
return reducedMotion;
};
//# sourceMappingURL=react-spring_shared.modern.mjs.map
;// CONCATENATED MODULE: ./node_modules/@react-spring/animated/dist/react-spring_animated.modern.mjs
// src/Animated.ts
var $node = Symbol.for("Animated:node");
var isAnimated = (value) => !!value && value[$node] === value;
var getAnimated = (owner) => owner && owner[$node];
var setAnimated = (owner, node) => defineHidden(owner, $node, node);
var getPayload = (owner) => owner && owner[$node] && owner[$node].getPayload();
var Animated = class {
constructor() {
setAnimated(this, this);
}
/** Get every `AnimatedValue` used by this node. */
getPayload() {
return this.payload || [];
}
};
// src/AnimatedValue.ts
var AnimatedValue = class extends Animated {
constructor(_value) {
super();
this._value = _value;
this.done = true;
this.durationProgress = 0;
if (is.num(this._value)) {
this.lastPosition = this._value;
}
}
/** @internal */
static create(value) {
return new AnimatedValue(value);
}
getPayload() {
return [this];
}
getValue() {
return this._value;
}
setValue(value, step) {
if (is.num(value)) {
this.lastPosition = value;
if (step) {
value = Math.round(value / step) * step;
if (this.done) {
this.lastPosition = value;
}
}
}
if (this._value === value) {
return false;
}
this._value = value;
return true;
}
reset() {
const { done } = this;
this.done = false;
if (is.num(this._value)) {
this.elapsedTime = 0;
this.durationProgress = 0;
this.lastPosition = this._value;
if (done)
this.lastVelocity = null;
this.v0 = null;
}
}
};
// src/AnimatedString.ts
var AnimatedString = class extends AnimatedValue {
constructor(value) {
super(0);
this._string = null;
this._toString = createInterpolator({
output: [value, value]
});
}
/** @internal */
static create(value) {
return new AnimatedString(value);
}
getValue() {
const value = this._string;
return value == null ? this._string = this._toString(this._value) : value;
}
setValue(value) {
if (is.str(value)) {
if (value == this._string) {
return false;
}
this._string = value;
this._value = 1;
} else if (super.setValue(value)) {
this._string = null;
} else {
return false;
}
return true;
}
reset(goal) {
if (goal) {
this._toString = createInterpolator({
output: [this.getValue(), goal]
});
}
this._value = 0;
super.reset();
}
};
// src/AnimatedArray.ts
// src/AnimatedObject.ts
// src/context.ts
var TreeContext = { dependencies: null };
// src/AnimatedObject.ts
var AnimatedObject = class extends Animated {
constructor(source) {
super();
this.source = source;
this.setValue(source);
}
getValue(animated) {
const values = {};
eachProp(this.source, (source, key) => {
if (isAnimated(source)) {
values[key] = source.getValue(animated);
} else if (hasFluidValue(source)) {
values[key] = getFluidValue(source);
} else if (!animated) {
values[key] = source;
}
});
return values;
}
/** Replace the raw object data */
setValue(source) {
this.source = source;
this.payload = this._makePayload(source);
}
reset() {
if (this.payload) {
react_spring_shared_modern_each(this.payload, (node) => node.reset());
}
}
/** Create a payload set. */
_makePayload(source) {
if (source) {
const payload = /* @__PURE__ */ new Set();
eachProp(source, this._addToPayload, payload);
return Array.from(payload);
}
}
/** Add to a payload set. */
_addToPayload(source) {
if (TreeContext.dependencies && hasFluidValue(source)) {
TreeContext.dependencies.add(source);
}
const payload = getPayload(source);
if (payload) {
react_spring_shared_modern_each(payload, (node) => this.add(node));
}
}
};
// src/AnimatedArray.ts
var AnimatedArray = class extends AnimatedObject {
constructor(source) {
super(source);
}
/** @internal */
static create(source) {
return new AnimatedArray(source);
}
getValue() {
return this.source.map((node) => node.getValue());
}
setValue(source) {
const payload = this.getPayload();
if (source.length == payload.length) {
return payload.map((node, i) => node.setValue(source[i])).some(Boolean);
}
super.setValue(source.map(makeAnimated));
return true;
}
};
function makeAnimated(value) {
const nodeType = isAnimatedString(value) ? AnimatedString : AnimatedValue;
return nodeType.create(value);
}
// src/getAnimatedType.ts
function getAnimatedType(value) {
const parentNode = getAnimated(value);
return parentNode ? parentNode.constructor : is.arr(value) ? AnimatedArray : isAnimatedString(value) ? AnimatedString : AnimatedValue;
}
// src/createHost.ts
// src/withAnimated.tsx
var withAnimated = (Component, host) => {
const hasInstance = (
// Function components must use "forwardRef" to avoid being
// re-rendered on every animation frame.
!is.fun(Component) || Component.prototype && Component.prototype.isReactComponent
);
return (0,external_React_.forwardRef)((givenProps, givenRef) => {
const instanceRef = (0,external_React_.useRef)(null);
const ref = hasInstance && // eslint-disable-next-line react-hooks/rules-of-hooks
(0,external_React_.useCallback)(
(value) => {
instanceRef.current = updateRef(givenRef, value);
},
[givenRef]
);
const [props, deps] = getAnimatedState(givenProps, host);
const forceUpdate = useForceUpdate();
const callback = () => {
const instance = instanceRef.current;
if (hasInstance && !instance) {
return;
}
const didUpdate = instance ? host.applyAnimatedValues(instance, props.getValue(true)) : false;
if (didUpdate === false) {
forceUpdate();
}
};
const observer = new PropsObserver(callback, deps);
const observerRef = (0,external_React_.useRef)();
react_spring_shared_modern_useIsomorphicLayoutEffect(() => {
observerRef.current = observer;
react_spring_shared_modern_each(deps, (dep) => addFluidObserver(dep, observer));
return () => {
if (observerRef.current) {
react_spring_shared_modern_each(
observerRef.current.deps,
(dep) => removeFluidObserver(dep, observerRef.current)
);
raf.cancel(observerRef.current.update);
}
};
});
(0,external_React_.useEffect)(callback, []);
useOnce(() => () => {
const observer2 = observerRef.current;
react_spring_shared_modern_each(observer2.deps, (dep) => removeFluidObserver(dep, observer2));
});
const usedProps = host.getComponentProps(props.getValue());
return /* @__PURE__ */ external_React_.createElement(Component, { ...usedProps, ref });
});
};
var PropsObserver = class {
constructor(update, deps) {
this.update = update;
this.deps = deps;
}
eventObserved(event) {
if (event.type == "change") {
raf.write(this.update);
}
}
};
function getAnimatedState(props, host) {
const dependencies = /* @__PURE__ */ new Set();
TreeContext.dependencies = dependencies;
if (props.style)
props = {
...props,
style: host.createAnimatedStyle(props.style)
};
props = new AnimatedObject(props);
TreeContext.dependencies = null;
return [props, dependencies];
}
function updateRef(ref, value) {
if (ref) {
if (is.fun(ref))
ref(value);
else
ref.current = value;
}
return value;
}
// src/createHost.ts
var cacheKey = Symbol.for("AnimatedComponent");
var createHost = (components, {
applyAnimatedValues = () => false,
createAnimatedStyle = (style) => new AnimatedObject(style),
getComponentProps = (props) => props
} = {}) => {
const hostConfig = {
applyAnimatedValues,
createAnimatedStyle,
getComponentProps
};
const animated = (Component) => {
const displayName = getDisplayName(Component) || "Anonymous";
if (is.str(Component)) {
Component = animated[Component] || (animated[Component] = withAnimated(Component, hostConfig));
} else {
Component = Component[cacheKey] || (Component[cacheKey] = withAnimated(Component, hostConfig));
}
Component.displayName = `Animated(${displayName})`;
return Component;
};
eachProp(components, (Component, key) => {
if (is.arr(components)) {
key = getDisplayName(Component);
}
animated[key] = animated(Component);
});
return {
animated
};
};
var getDisplayName = (arg) => is.str(arg) ? arg : arg && is.str(arg.displayName) ? arg.displayName : is.fun(arg) && arg.name || null;
//# sourceMappingURL=react-spring_animated.modern.mjs.map
;// CONCATENATED MODULE: ./node_modules/@react-spring/core/dist/react-spring_core.modern.mjs
// src/hooks/useChain.ts
// src/helpers.ts
function callProp(value, ...args) {
return is.fun(value) ? value(...args) : value;
}
var matchProp = (value, key) => value === true || !!(key && value && (is.fun(value) ? value(key) : toArray(value).includes(key)));
var resolveProp = (prop, key) => is.obj(prop) ? key && prop[key] : prop;
var getDefaultProp = (props, key) => props.default === true ? props[key] : props.default ? props.default[key] : void 0;
var noopTransform = (value) => value;
var getDefaultProps = (props, transform = noopTransform) => {
let keys = DEFAULT_PROPS;
if (props.default && props.default !== true) {
props = props.default;
keys = Object.keys(props);
}
const defaults2 = {};
for (const key of keys) {
const value = transform(props[key], key);
if (!is.und(value)) {
defaults2[key] = value;
}
}
return defaults2;
};
var DEFAULT_PROPS = [
"config",
"onProps",
"onStart",
"onChange",
"onPause",
"onResume",
"onRest"
];
var RESERVED_PROPS = {
config: 1,
from: 1,
to: 1,
ref: 1,
loop: 1,
reset: 1,
pause: 1,
cancel: 1,
reverse: 1,
immediate: 1,
default: 1,
delay: 1,
onProps: 1,
onStart: 1,
onChange: 1,
onPause: 1,
onResume: 1,
onRest: 1,
onResolve: 1,
// Transition props
items: 1,
trail: 1,
sort: 1,
expires: 1,
initial: 1,
enter: 1,
update: 1,
leave: 1,
children: 1,
onDestroyed: 1,
// Internal props
keys: 1,
callId: 1,
parentId: 1
};
function getForwardProps(props) {
const forward = {};
let count = 0;
eachProp(props, (value, prop) => {
if (!RESERVED_PROPS[prop]) {
forward[prop] = value;
count++;
}
});
if (count) {
return forward;
}
}
function inferTo(props) {
const to2 = getForwardProps(props);
if (to2) {
const out = { to: to2 };
eachProp(props, (val, key) => key in to2 || (out[key] = val));
return out;
}
return { ...props };
}
function computeGoal(value) {
value = getFluidValue(value);
return is.arr(value) ? value.map(computeGoal) : isAnimatedString(value) ? globals_exports.createStringInterpolator({
range: [0, 1],
output: [value, value]
})(1) : value;
}
function hasProps(props) {
for (const _ in props)
return true;
return false;
}
function isAsyncTo(to2) {
return is.fun(to2) || is.arr(to2) && is.obj(to2[0]);
}
function detachRefs(ctrl, ref) {
ctrl.ref?.delete(ctrl);
ref?.delete(ctrl);
}
function replaceRef(ctrl, ref) {
if (ref && ctrl.ref !== ref) {
ctrl.ref?.delete(ctrl);
ref.add(ctrl);
ctrl.ref = ref;
}
}
// src/hooks/useChain.ts
function useChain(refs, timeSteps, timeFrame = 1e3) {
useIsomorphicLayoutEffect(() => {
if (timeSteps) {
let prevDelay = 0;
each(refs, (ref, i) => {
const controllers = ref.current;
if (controllers.length) {
let delay = timeFrame * timeSteps[i];
if (isNaN(delay))
delay = prevDelay;
else
prevDelay = delay;
each(controllers, (ctrl) => {
each(ctrl.queue, (props) => {
const memoizedDelayProp = props.delay;
props.delay = (key) => delay + callProp(memoizedDelayProp || 0, key);
});
});
ref.start();
}
});
} else {
let p = Promise.resolve();
each(refs, (ref) => {
const controllers = ref.current;
if (controllers.length) {
const queues = controllers.map((ctrl) => {
const q = ctrl.queue;
ctrl.queue = [];
return q;
});
p = p.then(() => {
each(
controllers,
(ctrl, i) => each(queues[i] || [], (update2) => ctrl.queue.push(update2))
);
return Promise.all(ref.start());
});
}
});
}
});
}
// src/hooks/useSpring.ts
// src/hooks/useSprings.ts
// src/SpringValue.ts
// src/AnimationConfig.ts
// src/constants.ts
var config = {
default: { tension: 170, friction: 26 },
gentle: { tension: 120, friction: 14 },
wobbly: { tension: 180, friction: 12 },
stiff: { tension: 210, friction: 20 },
slow: { tension: 280, friction: 60 },
molasses: { tension: 280, friction: 120 }
};
// src/AnimationConfig.ts
var defaults = {
...config.default,
mass: 1,
damping: 1,
easing: easings.linear,
clamp: false
};
var AnimationConfig = class {
constructor() {
/**
* The initial velocity of one or more values.
*
* @default 0
*/
this.velocity = 0;
Object.assign(this, defaults);
}
};
function mergeConfig(config2, newConfig, defaultConfig) {
if (defaultConfig) {
defaultConfig = { ...defaultConfig };
sanitizeConfig(defaultConfig, newConfig);
newConfig = { ...defaultConfig, ...newConfig };
}
sanitizeConfig(config2, newConfig);
Object.assign(config2, newConfig);
for (const key in defaults) {
if (config2[key] == null) {
config2[key] = defaults[key];
}
}
let { frequency, damping } = config2;
const { mass } = config2;
if (!is.und(frequency)) {
if (frequency < 0.01)
frequency = 0.01;
if (damping < 0)
damping = 0;
config2.tension = Math.pow(2 * Math.PI / frequency, 2) * mass;
config2.friction = 4 * Math.PI * damping * mass / frequency;
}
return config2;
}
function sanitizeConfig(config2, props) {
if (!is.und(props.decay)) {
config2.duration = void 0;
} else {
const isTensionConfig = !is.und(props.tension) || !is.und(props.friction);
if (isTensionConfig || !is.und(props.frequency) || !is.und(props.damping) || !is.und(props.mass)) {
config2.duration = void 0;
config2.decay = void 0;
}
if (isTensionConfig) {
config2.frequency = void 0;
}
}
}
// src/Animation.ts
var emptyArray = [];
var Animation = class {
constructor() {
this.changed = false;
this.values = emptyArray;
this.toValues = null;
this.fromValues = emptyArray;
this.config = new AnimationConfig();
this.immediate = false;
}
};
// src/scheduleProps.ts
function scheduleProps(callId, { key, props, defaultProps, state, actions }) {
return new Promise((resolve, reject) => {
let delay;
let timeout;
let cancel = matchProp(props.cancel ?? defaultProps?.cancel, key);
if (cancel) {
onStart();
} else {
if (!is.und(props.pause)) {
state.paused = matchProp(props.pause, key);
}
let pause = defaultProps?.pause;
if (pause !== true) {
pause = state.paused || matchProp(pause, key);
}
delay = callProp(props.delay || 0, key);
if (pause) {
state.resumeQueue.add(onResume);
actions.pause();
} else {
actions.resume();
onResume();
}
}
function onPause() {
state.resumeQueue.add(onResume);
state.timeouts.delete(timeout);
timeout.cancel();
delay = timeout.time - raf.now();
}
function onResume() {
if (delay > 0 && !globals_exports.skipAnimation) {
state.delayed = true;
timeout = raf.setTimeout(onStart, delay);
state.pauseQueue.add(onPause);
state.timeouts.add(timeout);
} else {
onStart();
}
}
function onStart() {
if (state.delayed) {
state.delayed = false;
}
state.pauseQueue.delete(onPause);
state.timeouts.delete(timeout);
if (callId <= (state.cancelId || 0)) {
cancel = true;
}
try {
actions.start({ ...props, callId, cancel }, resolve);
} catch (err) {
reject(err);
}
}
});
}
// src/runAsync.ts
// src/AnimationResult.ts
var getCombinedResult = (target, results) => results.length == 1 ? results[0] : results.some((result) => result.cancelled) ? getCancelledResult(target.get()) : results.every((result) => result.noop) ? getNoopResult(target.get()) : getFinishedResult(
target.get(),
results.every((result) => result.finished)
);
var getNoopResult = (value) => ({
value,
noop: true,
finished: true,
cancelled: false
});
var getFinishedResult = (value, finished, cancelled = false) => ({
value,
finished,
cancelled
});
var getCancelledResult = (value) => ({
value,
cancelled: true,
finished: false
});
// src/runAsync.ts
function runAsync(to2, props, state, target) {
const { callId, parentId, onRest } = props;
const { asyncTo: prevTo, promise: prevPromise } = state;
if (!parentId && to2 === prevTo && !props.reset) {
return prevPromise;
}
return state.promise = (async () => {
state.asyncId = callId;
state.asyncTo = to2;
const defaultProps = getDefaultProps(
props,
(value, key) => (
// The `onRest` prop is only called when the `runAsync` promise is resolved.
key === "onRest" ? void 0 : value
)
);
let preventBail;
let bail;
const bailPromise = new Promise(
(resolve, reject) => (preventBail = resolve, bail = reject)
);
const bailIfEnded = (bailSignal) => {
const bailResult = (
// The `cancel` prop or `stop` method was used.
callId <= (state.cancelId || 0) && getCancelledResult(target) || // The async `to` prop was replaced.
callId !== state.asyncId && getFinishedResult(target, false)
);
if (bailResult) {
bailSignal.result = bailResult;
bail(bailSignal);
throw bailSignal;
}
};
const animate = (arg1, arg2) => {
const bailSignal = new BailSignal();
const skipAnimationSignal = new SkipAnimationSignal();
return (async () => {
if (globals_exports.skipAnimation) {
stopAsync(state);
skipAnimationSignal.result = getFinishedResult(target, false);
bail(skipAnimationSignal);
throw skipAnimationSignal;
}
bailIfEnded(bailSignal);
const props2 = is.obj(arg1) ? { ...arg1 } : { ...arg2, to: arg1 };
props2.parentId = callId;
eachProp(defaultProps, (value, key) => {
if (is.und(props2[key])) {
props2[key] = value;
}
});
const result2 = await target.start(props2);
bailIfEnded(bailSignal);
if (state.paused) {
await new Promise((resume) => {
state.resumeQueue.add(resume);
});
}
return result2;
})();
};
let result;
if (globals_exports.skipAnimation) {
stopAsync(state);
return getFinishedResult(target, false);
}
try {
let animating;
if (is.arr(to2)) {
animating = (async (queue) => {
for (const props2 of queue) {
await animate(props2);
}
})(to2);
} else {
animating = Promise.resolve(to2(animate, target.stop.bind(target)));
}
await Promise.all([animating.then(preventBail), bailPromise]);
result = getFinishedResult(target.get(), true, false);
} catch (err) {
if (err instanceof BailSignal) {
result = err.result;
} else if (err instanceof SkipAnimationSignal) {
result = err.result;
} else {
throw err;
}
} finally {
if (callId == state.asyncId) {
state.asyncId = parentId;
state.asyncTo = parentId ? prevTo : void 0;
state.promise = parentId ? prevPromise : void 0;
}
}
if (is.fun(onRest)) {
raf.batchedUpdates(() => {
onRest(result, target, target.item);
});
}
return result;
})();
}
function stopAsync(state, cancelId) {
flush(state.timeouts, (t) => t.cancel());
state.pauseQueue.clear();
state.resumeQueue.clear();
state.asyncId = state.asyncTo = state.promise = void 0;
if (cancelId)
state.cancelId = cancelId;
}
var BailSignal = class extends Error {
constructor() {
super(
"An async animation has been interrupted. You see this error because you forgot to use `await` or `.catch(...)` on its returned promise."
);
}
};
var SkipAnimationSignal = class extends Error {
constructor() {
super("SkipAnimationSignal");
}
};
// src/FrameValue.ts
var isFrameValue = (value) => value instanceof FrameValue;
var nextId = 1;
var FrameValue = class extends FluidValue {
constructor() {
super(...arguments);
this.id = nextId++;
this._priority = 0;
}
get priority() {
return this._priority;
}
set priority(priority) {
if (this._priority != priority) {
this._priority = priority;
this._onPriorityChange(priority);
}
}
/** Get the current value */
get() {
const node = getAnimated(this);
return node && node.getValue();
}
/** Create a spring that maps our value to another value */
to(...args) {
return globals_exports.to(this, args);
}
/** @deprecated Use the `to` method instead. */
interpolate(...args) {
deprecateInterpolate();
return globals_exports.to(this, args);
}
toJSON() {
return this.get();
}
observerAdded(count) {
if (count == 1)
this._attach();
}
observerRemoved(count) {
if (count == 0)
this._detach();
}
/** Called when the first child is added. */
_attach() {
}
/** Called when the last child is removed. */
_detach() {
}
/** Tell our children about our new value */
_onChange(value, idle = false) {
callFluidObservers(this, {
type: "change",
parent: this,
value,
idle
});
}
/** Tell our children about our new priority */
_onPriorityChange(priority) {
if (!this.idle) {
frameLoop.sort(this);
}
callFluidObservers(this, {
type: "priority",
parent: this,
priority
});
}
};
// src/SpringPhase.ts
var $P = Symbol.for("SpringPhase");
var HAS_ANIMATED = 1;
var IS_ANIMATING = 2;
var IS_PAUSED = 4;
var hasAnimated = (target) => (target[$P] & HAS_ANIMATED) > 0;
var isAnimating = (target) => (target[$P] & IS_ANIMATING) > 0;
var isPaused = (target) => (target[$P] & IS_PAUSED) > 0;
var setActiveBit = (target, active) => active ? target[$P] |= IS_ANIMATING | HAS_ANIMATED : target[$P] &= ~IS_ANIMATING;
var setPausedBit = (target, paused) => paused ? target[$P] |= IS_PAUSED : target[$P] &= ~IS_PAUSED;
// src/SpringValue.ts
var SpringValue = class extends FrameValue {
constructor(arg1, arg2) {
super();
/** The animation state */
this.animation = new Animation();
/** Some props have customizable default values */
this.defaultProps = {};
/** The state for `runAsync` calls */
this._state = {
paused: false,
delayed: false,
pauseQueue: /* @__PURE__ */ new Set(),
resumeQueue: /* @__PURE__ */ new Set(),
timeouts: /* @__PURE__ */ new Set()
};
/** The promise resolvers of pending `start` calls */
this._pendingCalls = /* @__PURE__ */ new Set();
/** The counter for tracking `scheduleProps` calls */
this._lastCallId = 0;
/** The last `scheduleProps` call that changed the `to` prop */
this._lastToId = 0;
this._memoizedDuration = 0;
if (!is.und(arg1) || !is.und(arg2)) {
const props = is.obj(arg1) ? { ...arg1 } : { ...arg2, from: arg1 };
if (is.und(props.default)) {
props.default = true;
}
this.start(props);
}
}
/** Equals true when not advancing on each frame. */
get idle() {
return !(isAnimating(this) || this._state.asyncTo) || isPaused(this);
}
get goal() {
return getFluidValue(this.animation.to);
}
get velocity() {
const node = getAnimated(this);
return node instanceof AnimatedValue ? node.lastVelocity || 0 : node.getPayload().map((node2) => node2.lastVelocity || 0);
}
/**
* When true, this value has been animated at least once.
*/
get hasAnimated() {
return hasAnimated(this);
}
/**
* When true, this value has an unfinished animation,
* which is either active or paused.
*/
get isAnimating() {
return isAnimating(this);
}
/**
* When true, all current and future animations are paused.
*/
get isPaused() {
return isPaused(this);
}
/**
*
*
*/
get isDelayed() {
return this._state.delayed;
}
/** Advance the current animation by a number of milliseconds */
advance(dt) {
let idle = true;
let changed = false;
const anim = this.animation;
let { toValues } = anim;
const { config: config2 } = anim;
const payload = getPayload(anim.to);
if (!payload && hasFluidValue(anim.to)) {
toValues = toArray(getFluidValue(anim.to));
}
anim.values.forEach((node2, i) => {
if (node2.done)
return;
const to2 = (
// Animated strings always go from 0 to 1.
node2.constructor == AnimatedString ? 1 : payload ? payload[i].lastPosition : toValues[i]
);
let finished = anim.immediate;
let position = to2;
if (!finished) {
position = node2.lastPosition;
if (config2.tension <= 0) {
node2.done = true;
return;
}
let elapsed = node2.elapsedTime += dt;
const from = anim.fromValues[i];
const v0 = node2.v0 != null ? node2.v0 : node2.v0 = is.arr(config2.velocity) ? config2.velocity[i] : config2.velocity;
let velocity;
const precision = config2.precision || (from == to2 ? 5e-3 : Math.min(1, Math.abs(to2 - from) * 1e-3));
if (!is.und(config2.duration)) {
let p = 1;
if (config2.duration > 0) {
if (this._memoizedDuration !== config2.duration) {
this._memoizedDuration = config2.duration;
if (node2.durationProgress > 0) {
node2.elapsedTime = config2.duration * node2.durationProgress;
elapsed = node2.elapsedTime += dt;
}
}
p = (config2.progress || 0) + elapsed / this._memoizedDuration;
p = p > 1 ? 1 : p < 0 ? 0 : p;
node2.durationProgress = p;
}
position = from + config2.easing(p) * (to2 - from);
velocity = (position - node2.lastPosition) / dt;
finished = p == 1;
} else if (config2.decay) {
const decay = config2.decay === true ? 0.998 : config2.decay;
const e = Math.exp(-(1 - decay) * elapsed);
position = from + v0 / (1 - decay) * (1 - e);
finished = Math.abs(node2.lastPosition - position) <= precision;
velocity = v0 * e;
} else {
velocity = node2.lastVelocity == null ? v0 : node2.lastVelocity;
const restVelocity = config2.restVelocity || precision / 10;
const bounceFactor = config2.clamp ? 0 : config2.bounce;
const canBounce = !is.und(bounceFactor);
const isGrowing = from == to2 ? node2.v0 > 0 : from < to2;
let isMoving;
let isBouncing = false;
const step = 1;
const numSteps = Math.ceil(dt / step);
for (let n = 0; n < numSteps; ++n) {
isMoving = Math.abs(velocity) > restVelocity;
if (!isMoving) {
finished = Math.abs(to2 - position) <= precision;
if (finished) {
break;
}
}
if (canBounce) {
isBouncing = position == to2 || position > to2 == isGrowing;
if (isBouncing) {
velocity = -velocity * bounceFactor;
position = to2;
}
}
const springForce = -config2.tension * 1e-6 * (position - to2);
const dampingForce = -config2.friction * 1e-3 * velocity;
const acceleration = (springForce + dampingForce) / config2.mass;
velocity = velocity + acceleration * step;
position = position + velocity * step;
}
}
node2.lastVelocity = velocity;
if (Number.isNaN(position)) {
console.warn(`Got NaN while animating:`, this);
finished = true;
}
}
if (payload && !payload[i].done) {
finished = false;
}
if (finished) {
node2.done = true;
} else {
idle = false;
}
if (node2.setValue(position, config2.round)) {
changed = true;
}
});
const node = getAnimated(this);
const currVal = node.getValue();
if (idle) {
const finalVal = getFluidValue(anim.to);
if ((currVal !== finalVal || changed) && !config2.decay) {
node.setValue(finalVal);
this._onChange(finalVal);
} else if (changed && config2.decay) {
this._onChange(currVal);
}
this._stop();
} else if (changed) {
this._onChange(currVal);
}
}
/** Set the current value, while stopping the current animation */
set(value) {
raf.batchedUpdates(() => {
this._stop();
this._focus(value);
this._set(value);
});
return this;
}
/**
* Freeze the active animation in time, as well as any updates merged
* before `resume` is called.
*/
pause() {
this._update({ pause: true });
}
/** Resume the animation if paused. */
resume() {
this._update({ pause: false });
}
/** Skip to the end of the current animation. */
finish() {
if (isAnimating(this)) {
const { to: to2, config: config2 } = this.animation;
raf.batchedUpdates(() => {
this._onStart();
if (!config2.decay) {
this._set(to2, false);
}
this._stop();
});
}
return this;
}
/** Push props into the pending queue. */
update(props) {
const queue = this.queue || (this.queue = []);
queue.push(props);
return this;
}
start(to2, arg2) {
let queue;
if (!is.und(to2)) {
queue = [is.obj(to2) ? to2 : { ...arg2, to: to2 }];
} else {
queue = this.queue || [];
this.queue = [];
}
return Promise.all(
queue.map((props) => {
const up = this._update(props);
return up;
})
).then((results) => getCombinedResult(this, results));
}
/**
* Stop the current animation, and cancel any delayed updates.
*
* Pass `true` to call `onRest` with `cancelled: true`.
*/
stop(cancel) {
const { to: to2 } = this.animation;
this._focus(this.get());
stopAsync(this._state, cancel && this._lastCallId);
raf.batchedUpdates(() => this._stop(to2, cancel));
return this;
}
/** Restart the animation. */
reset() {
this._update({ reset: true });
}
/** @internal */
eventObserved(event) {
if (event.type == "change") {
this._start();
} else if (event.type == "priority") {
this.priority = event.priority + 1;
}
}
/**
* Parse the `to` and `from` range from the given `props` object.
*
* This also ensures the initial value is available to animated components
* during the render phase.
*/
_prepareNode(props) {
const key = this.key || "";
let { to: to2, from } = props;
to2 = is.obj(to2) ? to2[key] : to2;
if (to2 == null || isAsyncTo(to2)) {
to2 = void 0;
}
from = is.obj(from) ? from[key] : from;
if (from == null) {
from = void 0;
}
const range = { to: to2, from };
if (!hasAnimated(this)) {
if (props.reverse)
[to2, from] = [from, to2];
from = getFluidValue(from);
if (!is.und(from)) {
this._set(from);
} else if (!getAnimated(this)) {
this._set(to2);
}
}
return range;
}
/** Every update is processed by this method before merging. */
_update({ ...props }, isLoop) {
const { key, defaultProps } = this;
if (props.default)
Object.assign(
defaultProps,
getDefaultProps(
props,
(value, prop) => /^on/.test(prop) ? resolveProp(value, key) : value
)
);
mergeActiveFn(this, props, "onProps");
sendEvent(this, "onProps", props, this);
const range = this._prepareNode(props);
if (Object.isFrozen(this)) {
throw Error(
"Cannot animate a `SpringValue` object that is frozen. Did you forget to pass your component to `animated(...)` before animating its props?"
);
}
const state = this._state;
return scheduleProps(++this._lastCallId, {
key,
props,
defaultProps,
state,
actions: {
pause: () => {
if (!isPaused(this)) {
setPausedBit(this, true);
flushCalls(state.pauseQueue);
sendEvent(
this,
"onPause",
getFinishedResult(this, checkFinished(this, this.animation.to)),
this
);
}
},
resume: () => {
if (isPaused(this)) {
setPausedBit(this, false);
if (isAnimating(this)) {
this._resume();
}
flushCalls(state.resumeQueue);
sendEvent(
this,
"onResume",
getFinishedResult(this, checkFinished(this, this.animation.to)),
this
);
}
},
start: this._merge.bind(this, range)
}
}).then((result) => {
if (props.loop && result.finished && !(isLoop && result.noop)) {
const nextProps = createLoopUpdate(props);
if (nextProps) {
return this._update(nextProps, true);
}
}
return result;
});
}
/** Merge props into the current animation */
_merge(range, props, resolve) {
if (props.cancel) {
this.stop(true);
return resolve(getCancelledResult(this));
}
const hasToProp = !is.und(range.to);
const hasFromProp = !is.und(range.from);
if (hasToProp || hasFromProp) {
if (props.callId > this._lastToId) {
this._lastToId = props.callId;
} else {
return resolve(getCancelledResult(this));
}
}
const { key, defaultProps, animation: anim } = this;
const { to: prevTo, from: prevFrom } = anim;
let { to: to2 = prevTo, from = prevFrom } = range;
if (hasFromProp && !hasToProp && (!props.default || is.und(to2))) {
to2 = from;
}
if (props.reverse)
[to2, from] = [from, to2];
const hasFromChanged = !isEqual(from, prevFrom);
if (hasFromChanged) {
anim.from = from;
}
from = getFluidValue(from);
const hasToChanged = !isEqual(to2, prevTo);
if (hasToChanged) {
this._focus(to2);
}
const hasAsyncTo = isAsyncTo(props.to);
const { config: config2 } = anim;
const { decay, velocity } = config2;
if (hasToProp || hasFromProp) {
config2.velocity = 0;
}
if (props.config && !hasAsyncTo) {
mergeConfig(
config2,
callProp(props.config, key),
// Avoid calling the same "config" prop twice.
props.config !== defaultProps.config ? callProp(defaultProps.config, key) : void 0
);
}
let node = getAnimated(this);
if (!node || is.und(to2)) {
return resolve(getFinishedResult(this, true));
}
const reset = (
// When `reset` is undefined, the `from` prop implies `reset: true`,
// except for declarative updates. When `reset` is defined, there
// must exist a value to animate from.
is.und(props.reset) ? hasFromProp && !props.default : !is.und(from) && matchProp(props.reset, key)
);
const value = reset ? from : this.get();
const goal = computeGoal(to2);
const isAnimatable = is.num(goal) || is.arr(goal) || isAnimatedString(goal);
const immediate = !hasAsyncTo && (!isAnimatable || matchProp(defaultProps.immediate || props.immediate, key));
if (hasToChanged) {
const nodeType = getAnimatedType(to2);
if (nodeType !== node.constructor) {
if (immediate) {
node = this._set(goal);
} else
throw Error(
`Cannot animate between ${node.constructor.name} and ${nodeType.name}, as the "to" prop suggests`
);
}
}
const goalType = node.constructor;
let started = hasFluidValue(to2);
let finished = false;
if (!started) {
const hasValueChanged = reset || !hasAnimated(this) && hasFromChanged;
if (hasToChanged || hasValueChanged) {
finished = isEqual(computeGoal(value), goal);
started = !finished;
}
if (!isEqual(anim.immediate, immediate) && !immediate || !isEqual(config2.decay, decay) || !isEqual(config2.velocity, velocity)) {
started = true;
}
}
if (finished && isAnimating(this)) {
if (anim.changed && !reset) {
started = true;
} else if (!started) {
this._stop(prevTo);
}
}
if (!hasAsyncTo) {
if (started || hasFluidValue(prevTo)) {
anim.values = node.getPayload();
anim.toValues = hasFluidValue(to2) ? null : goalType == AnimatedString ? [1] : toArray(goal);
}
if (anim.immediate != immediate) {
anim.immediate = immediate;
if (!immediate && !reset) {
this._set(prevTo);
}
}
if (started) {
const { onRest } = anim;
react_spring_shared_modern_each(ACTIVE_EVENTS, (type) => mergeActiveFn(this, props, type));
const result = getFinishedResult(this, checkFinished(this, prevTo));
flushCalls(this._pendingCalls, result);
this._pendingCalls.add(resolve);
if (anim.changed)
raf.batchedUpdates(() => {
anim.changed = !reset;
onRest?.(result, this);
if (reset) {
callProp(defaultProps.onRest, result);
} else {
anim.onStart?.(result, this);
}
});
}
}
if (reset) {
this._set(value);
}
if (hasAsyncTo) {
resolve(runAsync(props.to, props, this._state, this));
} else if (started) {
this._start();
} else if (isAnimating(this) && !hasToChanged) {
this._pendingCalls.add(resolve);
} else {
resolve(getNoopResult(value));
}
}
/** Update the `animation.to` value, which might be a `FluidValue` */
_focus(value) {
const anim = this.animation;
if (value !== anim.to) {
if (getFluidObservers(this)) {
this._detach();
}
anim.to = value;
if (getFluidObservers(this)) {
this._attach();
}
}
}
_attach() {
let priority = 0;
const { to: to2 } = this.animation;
if (hasFluidValue(to2)) {
addFluidObserver(to2, this);
if (isFrameValue(to2)) {
priority = to2.priority + 1;
}
}
this.priority = priority;
}
_detach() {
const { to: to2 } = this.animation;
if (hasFluidValue(to2)) {
removeFluidObserver(to2, this);
}
}
/**
* Update the current value from outside the frameloop,
* and return the `Animated` node.
*/
_set(arg, idle = true) {
const value = getFluidValue(arg);
if (!is.und(value)) {
const oldNode = getAnimated(this);
if (!oldNode || !isEqual(value, oldNode.getValue())) {
const nodeType = getAnimatedType(value);
if (!oldNode || oldNode.constructor != nodeType) {
setAnimated(this, nodeType.create(value));
} else {
oldNode.setValue(value);
}
if (oldNode) {
raf.batchedUpdates(() => {
this._onChange(value, idle);
});
}
}
}
return getAnimated(this);
}
_onStart() {
const anim = this.animation;
if (!anim.changed) {
anim.changed = true;
sendEvent(
this,
"onStart",
getFinishedResult(this, checkFinished(this, anim.to)),
this
);
}
}
_onChange(value, idle) {
if (!idle) {
this._onStart();
callProp(this.animation.onChange, value, this);
}
callProp(this.defaultProps.onChange, value, this);
super._onChange(value, idle);
}
// This method resets the animation state (even if already animating) to
// ensure the latest from/to range is used, and it also ensures this spring
// is added to the frameloop.
_start() {
const anim = this.animation;
getAnimated(this).reset(getFluidValue(anim.to));
if (!anim.immediate) {
anim.fromValues = anim.values.map((node) => node.lastPosition);
}
if (!isAnimating(this)) {
setActiveBit(this, true);
if (!isPaused(this)) {
this._resume();
}
}
}
_resume() {
if (globals_exports.skipAnimation) {
this.finish();
} else {
frameLoop.start(this);
}
}
/**
* Exit the frameloop and notify `onRest` listeners.
*
* Always wrap `_stop` calls with `batchedUpdates`.
*/
_stop(goal, cancel) {
if (isAnimating(this)) {
setActiveBit(this, false);
const anim = this.animation;
react_spring_shared_modern_each(anim.values, (node) => {
node.done = true;
});
if (anim.toValues) {
anim.onChange = anim.onPause = anim.onResume = void 0;
}
callFluidObservers(this, {
type: "idle",
parent: this
});
const result = cancel ? getCancelledResult(this.get()) : getFinishedResult(this.get(), checkFinished(this, goal ?? anim.to));
flushCalls(this._pendingCalls, result);
if (anim.changed) {
anim.changed = false;
sendEvent(this, "onRest", result, this);
}
}
}
};
function checkFinished(target, to2) {
const goal = computeGoal(to2);
const value = computeGoal(target.get());
return isEqual(value, goal);
}
function createLoopUpdate(props, loop = props.loop, to2 = props.to) {
const loopRet = callProp(loop);
if (loopRet) {
const overrides = loopRet !== true && inferTo(loopRet);
const reverse = (overrides || props).reverse;
const reset = !overrides || overrides.reset;
return createUpdate({
...props,
loop,
// Avoid updating default props when looping.
default: false,
// Never loop the `pause` prop.
pause: void 0,
// For the "reverse" prop to loop as expected, the "to" prop
// must be undefined. The "reverse" prop is ignored when the
// "to" prop is an array or function.
to: !reverse || isAsyncTo(to2) ? to2 : void 0,
// Ignore the "from" prop except on reset.
from: reset ? props.from : void 0,
reset,
// The "loop" prop can return a "useSpring" props object to
// override any of the original props.
...overrides
});
}
}
function createUpdate(props) {
const { to: to2, from } = props = inferTo(props);
const keys = /* @__PURE__ */ new Set();
if (is.obj(to2))
findDefined(to2, keys);
if (is.obj(from))
findDefined(from, keys);
props.keys = keys.size ? Array.from(keys) : null;
return props;
}
function declareUpdate(props) {
const update2 = createUpdate(props);
if (is.und(update2.default)) {
update2.default = getDefaultProps(update2);
}
return update2;
}
function findDefined(values, keys) {
eachProp(values, (value, key) => value != null && keys.add(key));
}
var ACTIVE_EVENTS = [
"onStart",
"onRest",
"onChange",
"onPause",
"onResume"
];
function mergeActiveFn(target, props, type) {
target.animation[type] = props[type] !== getDefaultProp(props, type) ? resolveProp(props[type], target.key) : void 0;
}
function sendEvent(target, type, ...args) {
target.animation[type]?.(...args);
target.defaultProps[type]?.(...args);
}
// src/Controller.ts
var BATCHED_EVENTS = ["onStart", "onChange", "onRest"];
var nextId2 = 1;
var Controller = class {
constructor(props, flush3) {
this.id = nextId2++;
/** The animated values */
this.springs = {};
/** The queue of props passed to the `update` method. */
this.queue = [];
/** The counter for tracking `scheduleProps` calls */
this._lastAsyncId = 0;
/** The values currently being animated */
this._active = /* @__PURE__ */ new Set();
/** The values that changed recently */
this._changed = /* @__PURE__ */ new Set();
/** Equals false when `onStart` listeners can be called */
this._started = false;
/** State used by the `runAsync` function */
this._state = {
paused: false,
pauseQueue: /* @__PURE__ */ new Set(),
resumeQueue: /* @__PURE__ */ new Set(),
timeouts: /* @__PURE__ */ new Set()
};
/** The event queues that are flushed once per frame maximum */
this._events = {
onStart: /* @__PURE__ */ new Map(),
onChange: /* @__PURE__ */ new Map(),
onRest: /* @__PURE__ */ new Map()
};
this._onFrame = this._onFrame.bind(this);
if (flush3) {
this._flush = flush3;
}
if (props) {
this.start({ default: true, ...props });
}
}
/**
* Equals `true` when no spring values are in the frameloop, and
* no async animation is currently active.
*/
get idle() {
return !this._state.asyncTo && Object.values(this.springs).every((spring) => {
return spring.idle && !spring.isDelayed && !spring.isPaused;
});
}
get item() {
return this._item;
}
set item(item) {
this._item = item;
}
/** Get the current values of our springs */
get() {
const values = {};
this.each((spring, key) => values[key] = spring.get());
return values;
}
/** Set the current values without animating. */
set(values) {
for (const key in values) {
const value = values[key];
if (!is.und(value)) {
this.springs[key].set(value);
}
}
}
/** Push an update onto the queue of each value. */
update(props) {
if (props) {
this.queue.push(createUpdate(props));
}
return this;
}
/**
* Start the queued animations for every spring, and resolve the returned
* promise once all queued animations have finished or been cancelled.
*
* When you pass a queue (instead of nothing), that queue is used instead of
* the queued animations added with the `update` method, which are left alone.
*/
start(props) {
let { queue } = this;
if (props) {
queue = toArray(props).map(createUpdate);
} else {
this.queue = [];
}
if (this._flush) {
return this._flush(this, queue);
}
prepareKeys(this, queue);
return flushUpdateQueue(this, queue);
}
/** @internal */
stop(arg, keys) {
if (arg !== !!arg) {
keys = arg;
}
if (keys) {
const springs = this.springs;
react_spring_shared_modern_each(toArray(keys), (key) => springs[key].stop(!!arg));
} else {
stopAsync(this._state, this._lastAsyncId);
this.each((spring) => spring.stop(!!arg));
}
return this;
}
/** Freeze the active animation in time */
pause(keys) {
if (is.und(keys)) {
this.start({ pause: true });
} else {
const springs = this.springs;
react_spring_shared_modern_each(toArray(keys), (key) => springs[key].pause());
}
return this;
}
/** Resume the animation if paused. */
resume(keys) {
if (is.und(keys)) {
this.start({ pause: false });
} else {
const springs = this.springs;
react_spring_shared_modern_each(toArray(keys), (key) => springs[key].resume());
}
return this;
}
/** Call a function once per spring value */
each(iterator) {
eachProp(this.springs, iterator);
}
/** @internal Called at the end of every animation frame */
_onFrame() {
const { onStart, onChange, onRest } = this._events;
const active = this._active.size > 0;
const changed = this._changed.size > 0;
if (active && !this._started || changed && !this._started) {
this._started = true;
flush(onStart, ([onStart2, result]) => {
result.value = this.get();
onStart2(result, this, this._item);
});
}
const idle = !active && this._started;
const values = changed || idle && onRest.size ? this.get() : null;
if (changed && onChange.size) {
flush(onChange, ([onChange2, result]) => {
result.value = values;
onChange2(result, this, this._item);
});
}
if (idle) {
this._started = false;
flush(onRest, ([onRest2, result]) => {
result.value = values;
onRest2(result, this, this._item);
});
}
}
/** @internal */
eventObserved(event) {
if (event.type == "change") {
this._changed.add(event.parent);
if (!event.idle) {
this._active.add(event.parent);
}
} else if (event.type == "idle") {
this._active.delete(event.parent);
} else
return;
raf.onFrame(this._onFrame);
}
};
function flushUpdateQueue(ctrl, queue) {
return Promise.all(queue.map((props) => flushUpdate(ctrl, props))).then(
(results) => getCombinedResult(ctrl, results)
);
}
async function flushUpdate(ctrl, props, isLoop) {
const { keys, to: to2, from, loop, onRest, onResolve } = props;
const defaults2 = is.obj(props.default) && props.default;
if (loop) {
props.loop = false;
}
if (to2 === false)
props.to = null;
if (from === false)
props.from = null;
const asyncTo = is.arr(to2) || is.fun(to2) ? to2 : void 0;
if (asyncTo) {
props.to = void 0;
props.onRest = void 0;
if (defaults2) {
defaults2.onRest = void 0;
}
} else {
react_spring_shared_modern_each(BATCHED_EVENTS, (key) => {
const handler = props[key];
if (is.fun(handler)) {
const queue = ctrl["_events"][key];
props[key] = ({ finished, cancelled }) => {
const result2 = queue.get(handler);
if (result2) {
if (!finished)
result2.finished = false;
if (cancelled)
result2.cancelled = true;
} else {
queue.set(handler, {
value: null,
finished: finished || false,
cancelled: cancelled || false
});
}
};
if (defaults2) {
defaults2[key] = props[key];
}
}
});
}
const state = ctrl["_state"];
if (props.pause === !state.paused) {
state.paused = props.pause;
flushCalls(props.pause ? state.pauseQueue : state.resumeQueue);
} else if (state.paused) {
props.pause = true;
}
const promises = (keys || Object.keys(ctrl.springs)).map(
(key) => ctrl.springs[key].start(props)
);
const cancel = props.cancel === true || getDefaultProp(props, "cancel") === true;
if (asyncTo || cancel && state.asyncId) {
promises.push(
scheduleProps(++ctrl["_lastAsyncId"], {
props,
state,
actions: {
pause: noop,
resume: noop,
start(props2, resolve) {
if (cancel) {
stopAsync(state, ctrl["_lastAsyncId"]);
resolve(getCancelledResult(ctrl));
} else {
props2.onRest = onRest;
resolve(
runAsync(
asyncTo,
props2,
state,
ctrl
)
);
}
}
}
})
);
}
if (state.paused) {
await new Promise((resume) => {
state.resumeQueue.add(resume);
});
}
const result = getCombinedResult(ctrl, await Promise.all(promises));
if (loop && result.finished && !(isLoop && result.noop)) {
const nextProps = createLoopUpdate(props, loop, to2);
if (nextProps) {
prepareKeys(ctrl, [nextProps]);
return flushUpdate(ctrl, nextProps, true);
}
}
if (onResolve) {
raf.batchedUpdates(() => onResolve(result, ctrl, ctrl.item));
}
return result;
}
function getSprings(ctrl, props) {
const springs = { ...ctrl.springs };
if (props) {
react_spring_shared_modern_each(toArray(props), (props2) => {
if (is.und(props2.keys)) {
props2 = createUpdate(props2);
}
if (!is.obj(props2.to)) {
props2 = { ...props2, to: void 0 };
}
prepareSprings(springs, props2, (key) => {
return createSpring(key);
});
});
}
setSprings(ctrl, springs);
return springs;
}
function setSprings(ctrl, springs) {
eachProp(springs, (spring, key) => {
if (!ctrl.springs[key]) {
ctrl.springs[key] = spring;
addFluidObserver(spring, ctrl);
}
});
}
function createSpring(key, observer) {
const spring = new SpringValue();
spring.key = key;
if (observer) {
addFluidObserver(spring, observer);
}
return spring;
}
function prepareSprings(springs, props, create) {
if (props.keys) {
react_spring_shared_modern_each(props.keys, (key) => {
const spring = springs[key] || (springs[key] = create(key));
spring["_prepareNode"](props);
});
}
}
function prepareKeys(ctrl, queue) {
react_spring_shared_modern_each(queue, (props) => {
prepareSprings(ctrl.springs, props, (key) => {
return createSpring(key, ctrl);
});
});
}
// src/SpringContext.tsx
var SpringContext = ({
children,
...props
}) => {
const inherited = (0,external_React_.useContext)(ctx);
const pause = props.pause || !!inherited.pause, immediate = props.immediate || !!inherited.immediate;
props = useMemoOne(() => ({ pause, immediate }), [pause, immediate]);
const { Provider } = ctx;
return /* @__PURE__ */ external_React_.createElement(Provider, { value: props }, children);
};
var ctx = makeContext(SpringContext, {});
SpringContext.Provider = ctx.Provider;
SpringContext.Consumer = ctx.Consumer;
function makeContext(target, init) {
Object.assign(target, external_React_.createContext(init));
target.Provider._context = target;
target.Consumer._context = target;
return target;
}
// src/SpringRef.ts
var SpringRef = () => {
const current = [];
const SpringRef2 = function(props) {
deprecateDirectCall();
const results = [];
react_spring_shared_modern_each(current, (ctrl, i) => {
if (is.und(props)) {
results.push(ctrl.start());
} else {
const update2 = _getProps(props, ctrl, i);
if (update2) {
results.push(ctrl.start(update2));
}
}
});
return results;
};
SpringRef2.current = current;
SpringRef2.add = function(ctrl) {
if (!current.includes(ctrl)) {
current.push(ctrl);
}
};
SpringRef2.delete = function(ctrl) {
const i = current.indexOf(ctrl);
if (~i)
current.splice(i, 1);
};
SpringRef2.pause = function() {
react_spring_shared_modern_each(current, (ctrl) => ctrl.pause(...arguments));
return this;
};
SpringRef2.resume = function() {
react_spring_shared_modern_each(current, (ctrl) => ctrl.resume(...arguments));
return this;
};
SpringRef2.set = function(values) {
react_spring_shared_modern_each(current, (ctrl, i) => {
const update2 = is.fun(values) ? values(i, ctrl) : values;
if (update2) {
ctrl.set(update2);
}
});
};
SpringRef2.start = function(props) {
const results = [];
react_spring_shared_modern_each(current, (ctrl, i) => {
if (is.und(props)) {
results.push(ctrl.start());
} else {
const update2 = this._getProps(props, ctrl, i);
if (update2) {
results.push(ctrl.start(update2));
}
}
});
return results;
};
SpringRef2.stop = function() {
react_spring_shared_modern_each(current, (ctrl) => ctrl.stop(...arguments));
return this;
};
SpringRef2.update = function(props) {
react_spring_shared_modern_each(current, (ctrl, i) => ctrl.update(this._getProps(props, ctrl, i)));
return this;
};
const _getProps = function(arg, ctrl, index) {
return is.fun(arg) ? arg(index, ctrl) : arg;
};
SpringRef2._getProps = _getProps;
return SpringRef2;
};
// src/hooks/useSprings.ts
function useSprings(length, props, deps) {
const propsFn = is.fun(props) && props;
if (propsFn && !deps)
deps = [];
const ref = (0,external_React_.useMemo)(
() => propsFn || arguments.length == 3 ? SpringRef() : void 0,
[]
);
const layoutId = (0,external_React_.useRef)(0);
const forceUpdate = useForceUpdate();
const state = (0,external_React_.useMemo)(
() => ({
ctrls: [],
queue: [],
flush(ctrl, updates2) {
const springs2 = getSprings(ctrl, updates2);
const canFlushSync = layoutId.current > 0 && !state.queue.length && !Object.keys(springs2).some((key) => !ctrl.springs[key]);
return canFlushSync ? flushUpdateQueue(ctrl, updates2) : new Promise((resolve) => {
setSprings(ctrl, springs2);
state.queue.push(() => {
resolve(flushUpdateQueue(ctrl, updates2));
});
forceUpdate();
});
}
}),
[]
);
const ctrls = (0,external_React_.useRef)([...state.ctrls]);
const updates = [];
const prevLength = usePrev(length) || 0;
(0,external_React_.useMemo)(() => {
react_spring_shared_modern_each(ctrls.current.slice(length, prevLength), (ctrl) => {
detachRefs(ctrl, ref);
ctrl.stop(true);
});
ctrls.current.length = length;
declareUpdates(prevLength, length);
}, [length]);
(0,external_React_.useMemo)(() => {
declareUpdates(0, Math.min(prevLength, length));
}, deps);
function declareUpdates(startIndex, endIndex) {
for (let i = startIndex; i < endIndex; i++) {
const ctrl = ctrls.current[i] || (ctrls.current[i] = new Controller(null, state.flush));
const update2 = propsFn ? propsFn(i, ctrl) : props[i];
if (update2) {
updates[i] = declareUpdate(update2);
}
}
}
const springs = ctrls.current.map((ctrl, i) => getSprings(ctrl, updates[i]));
const context = (0,external_React_.useContext)(SpringContext);
const prevContext = usePrev(context);
const hasContext = context !== prevContext && hasProps(context);
react_spring_shared_modern_useIsomorphicLayoutEffect(() => {
layoutId.current++;
state.ctrls = ctrls.current;
const { queue } = state;
if (queue.length) {
state.queue = [];
react_spring_shared_modern_each(queue, (cb) => cb());
}
react_spring_shared_modern_each(ctrls.current, (ctrl, i) => {
ref?.add(ctrl);
if (hasContext) {
ctrl.start({ default: context });
}
const update2 = updates[i];
if (update2) {
replaceRef(ctrl, update2.ref);
if (ctrl.ref) {
ctrl.queue.push(update2);
} else {
ctrl.start(update2);
}
}
});
});
useOnce(() => () => {
react_spring_shared_modern_each(state.ctrls, (ctrl) => ctrl.stop(true));
});
const values = springs.map((x) => ({ ...x }));
return ref ? [values, ref] : values;
}
// src/hooks/useSpring.ts
function useSpring(props, deps) {
const isFn = is.fun(props);
const [[values], ref] = useSprings(
1,
isFn ? props : [props],
isFn ? deps || [] : deps
);
return isFn || arguments.length == 2 ? [values, ref] : values;
}
// src/hooks/useSpringRef.ts
var initSpringRef = () => SpringRef();
var useSpringRef = () => useState(initSpringRef)[0];
// src/hooks/useSpringValue.ts
var useSpringValue = (initial, props) => {
const springValue = useConstant(() => new SpringValue(initial, props));
useOnce2(() => () => {
springValue.stop();
});
return springValue;
};
// src/hooks/useTrail.ts
function useTrail(length, propsArg, deps) {
const propsFn = is10.fun(propsArg) && propsArg;
if (propsFn && !deps)
deps = [];
let reverse = true;
let passedRef = void 0;
const result = useSprings(
length,
(i, ctrl) => {
const props = propsFn ? propsFn(i, ctrl) : propsArg;
passedRef = props.ref;
reverse = reverse && props.reverse;
return props;
},
// Ensure the props function is called when no deps exist.
// This works around the 3 argument rule.
deps || [{}]
);
useIsomorphicLayoutEffect3(() => {
each6(result[1].current, (ctrl, i) => {
const parent = result[1].current[i + (reverse ? 1 : -1)];
replaceRef(ctrl, passedRef);
if (ctrl.ref) {
if (parent) {
ctrl.update({ to: parent.springs });
}
return;
}
if (parent) {
ctrl.start({ to: parent.springs });
} else {
ctrl.start();
}
});
}, deps);
if (propsFn || arguments.length == 3) {
const ref = passedRef ?? result[1];
ref["_getProps"] = (propsArg2, ctrl, i) => {
const props = is10.fun(propsArg2) ? propsArg2(i, ctrl) : propsArg2;
if (props) {
const parent = ref.current[i + (props.reverse ? 1 : -1)];
if (parent)
props.to = parent.springs;
return props;
}
};
return result;
}
return result[0];
}
// src/hooks/useTransition.tsx
function useTransition(data, props, deps) {
const propsFn = is11.fun(props) && props;
const {
reset,
sort,
trail = 0,
expires = true,
exitBeforeEnter = false,
onDestroyed,
ref: propsRef,
config: propsConfig
} = propsFn ? propsFn() : props;
const ref = useMemo2(
() => propsFn || arguments.length == 3 ? SpringRef() : void 0,
[]
);
const items = toArray4(data);
const transitions = [];
const usedTransitions = useRef2(null);
const prevTransitions = reset ? null : usedTransitions.current;
useIsomorphicLayoutEffect4(() => {
usedTransitions.current = transitions;
});
useOnce3(() => {
each7(transitions, (t) => {
ref?.add(t.ctrl);
t.ctrl.ref = ref;
});
return () => {
each7(usedTransitions.current, (t) => {
if (t.expired) {
clearTimeout(t.expirationId);
}
detachRefs(t.ctrl, ref);
t.ctrl.stop(true);
});
};
});
const keys = getKeys(items, propsFn ? propsFn() : props, prevTransitions);
const expired = reset && usedTransitions.current || [];
useIsomorphicLayoutEffect4(
() => each7(expired, ({ ctrl, item, key }) => {
detachRefs(ctrl, ref);
callProp(onDestroyed, item, key);
})
);
const reused = [];
if (prevTransitions)
each7(prevTransitions, (t, i) => {
if (t.expired) {
clearTimeout(t.expirationId);
expired.push(t);
} else {
i = reused[i] = keys.indexOf(t.key);
if (~i)
transitions[i] = t;
}
});
each7(items, (item, i) => {
if (!transitions[i]) {
transitions[i] = {
key: keys[i],
item,
phase: "mount" /* MOUNT */,
ctrl: new Controller()
};
transitions[i].ctrl.item = item;
}
});
if (reused.length) {
let i = -1;
const { leave } = propsFn ? propsFn() : props;
each7(reused, (keyIndex, prevIndex) => {
const t = prevTransitions[prevIndex];
if (~keyIndex) {
i = transitions.indexOf(t);
transitions[i] = { ...t, item: items[keyIndex] };
} else if (leave) {
transitions.splice(++i, 0, t);
}
});
}
if (is11.fun(sort)) {
transitions.sort((a, b) => sort(a.item, b.item));
}
let delay = -trail;
const forceUpdate = useForceUpdate2();
const defaultProps = getDefaultProps(props);
const changes = /* @__PURE__ */ new Map();
const exitingTransitions = useRef2(/* @__PURE__ */ new Map());
const forceChange = useRef2(false);
each7(transitions, (t, i) => {
const key = t.key;
const prevPhase = t.phase;
const p = propsFn ? propsFn() : props;
let to2;
let phase;
const propsDelay = callProp(p.delay || 0, key);
if (prevPhase == "mount" /* MOUNT */) {
to2 = p.enter;
phase = "enter" /* ENTER */;
} else {
const isLeave = keys.indexOf(key) < 0;
if (prevPhase != "leave" /* LEAVE */) {
if (isLeave) {
to2 = p.leave;
phase = "leave" /* LEAVE */;
} else if (to2 = p.update) {
phase = "update" /* UPDATE */;
} else
return;
} else if (!isLeave) {
to2 = p.enter;
phase = "enter" /* ENTER */;
} else
return;
}
to2 = callProp(to2, t.item, i);
to2 = is11.obj(to2) ? inferTo(to2) : { to: to2 };
if (!to2.config) {
const config2 = propsConfig || defaultProps.config;
to2.config = callProp(config2, t.item, i, phase);
}
delay += trail;
const payload = {
...defaultProps,
// we need to add our props.delay value you here.
delay: propsDelay + delay,
ref: propsRef,
immediate: p.immediate,
// This prevents implied resets.
reset: false,
// Merge any phase-specific props.
...to2
};
if (phase == "enter" /* ENTER */ && is11.und(payload.from)) {
const p2 = propsFn ? propsFn() : props;
const from = is11.und(p2.initial) || prevTransitions ? p2.from : p2.initial;
payload.from = callProp(from, t.item, i);
}
const { onResolve } = payload;
payload.onResolve = (result) => {
callProp(onResolve, result);
const transitions2 = usedTransitions.current;
const t2 = transitions2.find((t3) => t3.key === key);
if (!t2)
return;
if (result.cancelled && t2.phase != "update" /* UPDATE */) {
return;
}
if (t2.ctrl.idle) {
const idle = transitions2.every((t3) => t3.ctrl.idle);
if (t2.phase == "leave" /* LEAVE */) {
const expiry = callProp(expires, t2.item);
if (expiry !== false) {
const expiryMs = expiry === true ? 0 : expiry;
t2.expired = true;
if (!idle && expiryMs > 0) {
if (expiryMs <= 2147483647)
t2.expirationId = setTimeout(forceUpdate, expiryMs);
return;
}
}
}
if (idle && transitions2.some((t3) => t3.expired)) {
exitingTransitions.current.delete(t2);
if (exitBeforeEnter) {
forceChange.current = true;
}
forceUpdate();
}
}
};
const springs = getSprings(t.ctrl, payload);
if (phase === "leave" /* LEAVE */ && exitBeforeEnter) {
exitingTransitions.current.set(t, { phase, springs, payload });
} else {
changes.set(t, { phase, springs, payload });
}
});
const context = useContext3(SpringContext);
const prevContext = usePrev2(context);
const hasContext = context !== prevContext && hasProps(context);
useIsomorphicLayoutEffect4(() => {
if (hasContext) {
each7(transitions, (t) => {
t.ctrl.start({ default: context });
});
}
}, [context]);
each7(changes, (_, t) => {
if (exitingTransitions.current.size) {
const ind = transitions.findIndex((state) => state.key === t.key);
transitions.splice(ind, 1);
}
});
useIsomorphicLayoutEffect4(
() => {
each7(
exitingTransitions.current.size ? exitingTransitions.current : changes,
({ phase, payload }, t) => {
const { ctrl } = t;
t.phase = phase;
ref?.add(ctrl);
if (hasContext && phase == "enter" /* ENTER */) {
ctrl.start({ default: context });
}
if (payload) {
replaceRef(ctrl, payload.ref);
if ((ctrl.ref || ref) && !forceChange.current) {
ctrl.update(payload);
} else {
ctrl.start(payload);
if (forceChange.current) {
forceChange.current = false;
}
}
}
}
);
},
reset ? void 0 : deps
);
const renderTransitions = (render) => /* @__PURE__ */ React2.createElement(React2.Fragment, null, transitions.map((t, i) => {
const { springs } = changes.get(t) || t.ctrl;
const elem = render({ ...springs }, t.item, t, i);
return elem && elem.type ? /* @__PURE__ */ React2.createElement(
elem.type,
{
...elem.props,
key: is11.str(t.key) || is11.num(t.key) ? t.key : t.ctrl.id,
ref: elem.ref
}
) : elem;
}));
return ref ? [renderTransitions, ref] : renderTransitions;
}
var nextKey = 1;
function getKeys(items, { key, keys = key }, prevTransitions) {
if (keys === null) {
const reused = /* @__PURE__ */ new Set();
return items.map((item) => {
const t = prevTransitions && prevTransitions.find(
(t2) => t2.item === item && t2.phase !== "leave" /* LEAVE */ && !reused.has(t2)
);
if (t) {
reused.add(t);
return t.key;
}
return nextKey++;
});
}
return is11.und(keys) ? items : is11.fun(keys) ? items.map(keys) : toArray4(keys);
}
// src/hooks/useScroll.ts
var useScroll = ({
container,
...springOptions
} = {}) => {
const [scrollValues, api] = useSpring(
() => ({
scrollX: 0,
scrollY: 0,
scrollXProgress: 0,
scrollYProgress: 0,
...springOptions
}),
[]
);
useIsomorphicLayoutEffect5(() => {
const cleanupScroll = onScroll(
({ x, y }) => {
api.start({
scrollX: x.current,
scrollXProgress: x.progress,
scrollY: y.current,
scrollYProgress: y.progress
});
},
{ container: container?.current || void 0 }
);
return () => {
each8(Object.values(scrollValues), (value) => value.stop());
cleanupScroll();
};
}, []);
return scrollValues;
};
// src/hooks/useResize.ts
var useResize = ({
container,
...springOptions
}) => {
const [sizeValues, api] = useSpring(
() => ({
width: 0,
height: 0,
...springOptions
}),
[]
);
useIsomorphicLayoutEffect6(() => {
const cleanupScroll = onResize(
({ width, height }) => {
api.start({
width,
height,
immediate: sizeValues.width.get() === 0 || sizeValues.height.get() === 0
});
},
{ container: container?.current || void 0 }
);
return () => {
each9(Object.values(sizeValues), (value) => value.stop());
cleanupScroll();
};
}, []);
return sizeValues;
};
// src/hooks/useInView.ts
var defaultThresholdOptions = {
any: 0,
all: 1
};
function useInView(props, args) {
const [isInView, setIsInView] = useState2(false);
const ref = useRef3();
const propsFn = is12.fun(props) && props;
const springsProps = propsFn ? propsFn() : {};
const { to: to2 = {}, from = {}, ...restSpringProps } = springsProps;
const intersectionArguments = propsFn ? args : props;
const [springs, api] = useSpring(() => ({ from, ...restSpringProps }), []);
useIsomorphicLayoutEffect7(() => {
const element = ref.current;
const {
root,
once,
amount = "any",
...restArgs
} = intersectionArguments ?? {};
if (!element || once && isInView || typeof IntersectionObserver === "undefined")
return;
const activeIntersections = /* @__PURE__ */ new WeakMap();
const onEnter = () => {
if (to2) {
api.start(to2);
}
setIsInView(true);
const cleanup = () => {
if (from) {
api.start(from);
}
setIsInView(false);
};
return once ? void 0 : cleanup;
};
const handleIntersection = (entries) => {
entries.forEach((entry) => {
const onLeave = activeIntersections.get(entry.target);
if (entry.isIntersecting === Boolean(onLeave)) {
return;
}
if (entry.isIntersecting) {
const newOnLeave = onEnter();
if (is12.fun(newOnLeave)) {
activeIntersections.set(entry.target, newOnLeave);
} else {
observer.unobserve(entry.target);
}
} else if (onLeave) {
onLeave();
activeIntersections.delete(entry.target);
}
});
};
const observer = new IntersectionObserver(handleIntersection, {
root: root && root.current || void 0,
threshold: typeof amount === "number" || Array.isArray(amount) ? amount : defaultThresholdOptions[amount],
...restArgs
});
observer.observe(element);
return () => observer.unobserve(element);
}, [intersectionArguments]);
if (propsFn) {
return [ref, springs];
}
return [ref, isInView];
}
// src/components/Spring.tsx
function Spring({ children, ...props }) {
return children(useSpring(props));
}
// src/components/Trail.tsx
function Trail({
items,
children,
...props
}) {
const trails = useTrail(items.length, props);
return items.map((item, index) => {
const result = children(item, index);
return is13.fun(result) ? result(trails[index]) : result;
});
}
// src/components/Transition.tsx
function Transition({
items,
children,
...props
}) {
return useTransition(items, props)(children);
}
// src/interpolate.ts
// src/Interpolation.ts
var Interpolation = class extends FrameValue {
constructor(source, args) {
super();
this.source = source;
/** Equals false when in the frameloop */
this.idle = true;
/** The inputs which are currently animating */
this._active = /* @__PURE__ */ new Set();
this.calc = createInterpolator(...args);
const value = this._get();
const nodeType = getAnimatedType(value);
setAnimated(this, nodeType.create(value));
}
advance(_dt) {
const value = this._get();
const oldValue = this.get();
if (!isEqual(value, oldValue)) {
getAnimated(this).setValue(value);
this._onChange(value, this.idle);
}
if (!this.idle && checkIdle(this._active)) {
becomeIdle(this);
}
}
_get() {
const inputs = is.arr(this.source) ? this.source.map(getFluidValue) : toArray(getFluidValue(this.source));
return this.calc(...inputs);
}
_start() {
if (this.idle && !checkIdle(this._active)) {
this.idle = false;
react_spring_shared_modern_each(getPayload(this), (node) => {
node.done = false;
});
if (globals_exports.skipAnimation) {
raf.batchedUpdates(() => this.advance());
becomeIdle(this);
} else {
frameLoop.start(this);
}
}
}
// Observe our sources only when we're observed.
_attach() {
let priority = 1;
react_spring_shared_modern_each(toArray(this.source), (source) => {
if (hasFluidValue(source)) {
addFluidObserver(source, this);
}
if (isFrameValue(source)) {
if (!source.idle) {
this._active.add(source);
}
priority = Math.max(priority, source.priority + 1);
}
});
this.priority = priority;
this._start();
}
// Stop observing our sources once we have no observers.
_detach() {
react_spring_shared_modern_each(toArray(this.source), (source) => {
if (hasFluidValue(source)) {
removeFluidObserver(source, this);
}
});
this._active.clear();
becomeIdle(this);
}
/** @internal */
eventObserved(event) {
if (event.type == "change") {
if (event.idle) {
this.advance();
} else {
this._active.add(event.parent);
this._start();
}
} else if (event.type == "idle") {
this._active.delete(event.parent);
} else if (event.type == "priority") {
this.priority = toArray(this.source).reduce(
(highest, parent) => Math.max(highest, (isFrameValue(parent) ? parent.priority : 0) + 1),
0
);
}
}
};
function isIdle(source) {
return source.idle !== false;
}
function checkIdle(active) {
return !active.size || Array.from(active).every(isIdle);
}
function becomeIdle(self) {
if (!self.idle) {
self.idle = true;
react_spring_shared_modern_each(getPayload(self), (node) => {
node.done = true;
});
callFluidObservers(self, {
type: "idle",
parent: self
});
}
}
// src/interpolate.ts
var react_spring_core_modern_to = (source, ...args) => new Interpolation(source, args);
var react_spring_core_modern_interpolate = (source, ...args) => (deprecateInterpolate2(), new Interpolation(source, args));
// src/globals.ts
globals_exports.assign({
createStringInterpolator: createStringInterpolator2,
to: (source, args) => new Interpolation(source, args)
});
var react_spring_core_modern_update = frameLoop.advance;
// src/index.ts
//# sourceMappingURL=react-spring_core.modern.mjs.map
;// CONCATENATED MODULE: external "ReactDOM"
var external_ReactDOM_namespaceObject = window["ReactDOM"];
;// CONCATENATED MODULE: ./node_modules/@react-spring/web/dist/react-spring_web.modern.mjs
// src/index.ts
// src/applyAnimatedValues.ts
var isCustomPropRE = /^--/;
function dangerousStyleValue(name, value) {
if (value == null || typeof value === "boolean" || value === "")
return "";
if (typeof value === "number" && value !== 0 && !isCustomPropRE.test(name) && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]))
return value + "px";
return ("" + value).trim();
}
var attributeCache = {};
function applyAnimatedValues(instance, props) {
if (!instance.nodeType || !instance.setAttribute) {
return false;
}
const isFilterElement = instance.nodeName === "filter" || instance.parentNode && instance.parentNode.nodeName === "filter";
const { style, children, scrollTop, scrollLeft, viewBox, ...attributes } = props;
const values = Object.values(attributes);
const names = Object.keys(attributes).map(
(name) => isFilterElement || instance.hasAttribute(name) ? name : attributeCache[name] || (attributeCache[name] = name.replace(
/([A-Z])/g,
// Attributes are written in dash case
(n) => "-" + n.toLowerCase()
))
);
if (children !== void 0) {
instance.textContent = children;
}
for (const name in style) {
if (style.hasOwnProperty(name)) {
const value = dangerousStyleValue(name, style[name]);
if (isCustomPropRE.test(name)) {
instance.style.setProperty(name, value);
} else {
instance.style[name] = value;
}
}
}
names.forEach((name, i) => {
instance.setAttribute(name, values[i]);
});
if (scrollTop !== void 0) {
instance.scrollTop = scrollTop;
}
if (scrollLeft !== void 0) {
instance.scrollLeft = scrollLeft;
}
if (viewBox !== void 0) {
instance.setAttribute("viewBox", viewBox);
}
}
var isUnitlessNumber = {
animationIterationCount: true,
borderImageOutset: true,
borderImageSlice: true,
borderImageWidth: true,
boxFlex: true,
boxFlexGroup: true,
boxOrdinalGroup: true,
columnCount: true,
columns: true,
flex: true,
flexGrow: true,
flexPositive: true,
flexShrink: true,
flexNegative: true,
flexOrder: true,
gridRow: true,
gridRowEnd: true,
gridRowSpan: true,
gridRowStart: true,
gridColumn: true,
gridColumnEnd: true,
gridColumnSpan: true,
gridColumnStart: true,
fontWeight: true,
lineClamp: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
tabSize: true,
widows: true,
zIndex: true,
zoom: true,
// SVG-related properties
fillOpacity: true,
floodOpacity: true,
stopOpacity: true,
strokeDasharray: true,
strokeDashoffset: true,
strokeMiterlimit: true,
strokeOpacity: true,
strokeWidth: true
};
var prefixKey = (prefix, key) => prefix + key.charAt(0).toUpperCase() + key.substring(1);
var prefixes = ["Webkit", "Ms", "Moz", "O"];
isUnitlessNumber = Object.keys(isUnitlessNumber).reduce((acc, prop) => {
prefixes.forEach((prefix) => acc[prefixKey(prefix, prop)] = acc[prop]);
return acc;
}, isUnitlessNumber);
// src/AnimatedStyle.ts
var domTransforms = /^(matrix|translate|scale|rotate|skew)/;
var pxTransforms = /^(translate)/;
var degTransforms = /^(rotate|skew)/;
var addUnit = (value, unit) => is.num(value) && value !== 0 ? value + unit : value;
var isValueIdentity = (value, id) => is.arr(value) ? value.every((v) => isValueIdentity(v, id)) : is.num(value) ? value === id : parseFloat(value) === id;
var AnimatedStyle = class extends AnimatedObject {
constructor({ x, y, z, ...style }) {
const inputs = [];
const transforms = [];
if (x || y || z) {
inputs.push([x || 0, y || 0, z || 0]);
transforms.push((xyz) => [
`translate3d(${xyz.map((v) => addUnit(v, "px")).join(",")})`,
// prettier-ignore
isValueIdentity(xyz, 0)
]);
}
eachProp(style, (value, key) => {
if (key === "transform") {
inputs.push([value || ""]);
transforms.push((transform) => [transform, transform === ""]);
} else if (domTransforms.test(key)) {
delete style[key];
if (is.und(value))
return;
const unit = pxTransforms.test(key) ? "px" : degTransforms.test(key) ? "deg" : "";
inputs.push(toArray(value));
transforms.push(
key === "rotate3d" ? ([x2, y2, z2, deg]) => [
`rotate3d(${x2},${y2},${z2},${addUnit(deg, unit)})`,
isValueIdentity(deg, 0)
] : (input) => [
`${key}(${input.map((v) => addUnit(v, unit)).join(",")})`,
isValueIdentity(input, key.startsWith("scale") ? 1 : 0)
]
);
}
});
if (inputs.length) {
style.transform = new FluidTransform(inputs, transforms);
}
super(style);
}
};
var FluidTransform = class extends FluidValue {
constructor(inputs, transforms) {
super();
this.inputs = inputs;
this.transforms = transforms;
this._value = null;
}
get() {
return this._value || (this._value = this._get());
}
_get() {
let transform = "";
let identity = true;
react_spring_shared_modern_each(this.inputs, (input, i) => {
const arg1 = getFluidValue(input[0]);
const [t, id] = this.transforms[i](
is.arr(arg1) ? arg1 : input.map(getFluidValue)
);
transform += " " + t;
identity = identity && id;
});
return identity ? "none" : transform;
}
// Start observing our inputs once we have an observer.
observerAdded(count) {
if (count == 1)
react_spring_shared_modern_each(
this.inputs,
(input) => react_spring_shared_modern_each(
input,
(value) => hasFluidValue(value) && addFluidObserver(value, this)
)
);
}
// Stop observing our inputs once we have no observers.
observerRemoved(count) {
if (count == 0)
react_spring_shared_modern_each(
this.inputs,
(input) => react_spring_shared_modern_each(
input,
(value) => hasFluidValue(value) && removeFluidObserver(value, this)
)
);
}
eventObserved(event) {
if (event.type == "change") {
this._value = null;
}
callFluidObservers(this, event);
}
};
// src/primitives.ts
var primitives = [
"a",
"abbr",
"address",
"area",
"article",
"aside",
"audio",
"b",
"base",
"bdi",
"bdo",
"big",
"blockquote",
"body",
"br",
"button",
"canvas",
"caption",
"cite",
"code",
"col",
"colgroup",
"data",
"datalist",
"dd",
"del",
"details",
"dfn",
"dialog",
"div",
"dl",
"dt",
"em",
"embed",
"fieldset",
"figcaption",
"figure",
"footer",
"form",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"head",
"header",
"hgroup",
"hr",
"html",
"i",
"iframe",
"img",
"input",
"ins",
"kbd",
"keygen",
"label",
"legend",
"li",
"link",
"main",
"map",
"mark",
"menu",
"menuitem",
"meta",
"meter",
"nav",
"noscript",
"object",
"ol",
"optgroup",
"option",
"output",
"p",
"param",
"picture",
"pre",
"progress",
"q",
"rp",
"rt",
"ruby",
"s",
"samp",
"script",
"section",
"select",
"small",
"source",
"span",
"strong",
"style",
"sub",
"summary",
"sup",
"table",
"tbody",
"td",
"textarea",
"tfoot",
"th",
"thead",
"time",
"title",
"tr",
"track",
"u",
"ul",
"var",
"video",
"wbr",
// SVG
"circle",
"clipPath",
"defs",
"ellipse",
"foreignObject",
"g",
"image",
"line",
"linearGradient",
"mask",
"path",
"pattern",
"polygon",
"polyline",
"radialGradient",
"rect",
"stop",
"svg",
"text",
"tspan"
];
// src/index.ts
globals_exports.assign({
batchedUpdates: external_ReactDOM_namespaceObject.unstable_batchedUpdates,
createStringInterpolator: createStringInterpolator2,
colors: colors2
});
var host = createHost(primitives, {
applyAnimatedValues,
createAnimatedStyle: (style) => new AnimatedStyle(style),
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getComponentProps: ({ scrollTop, scrollLeft, ...props }) => props
});
var animated = host.animated;
//# sourceMappingURL=react-spring_web.modern.mjs.map
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/use-moving-animation/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Simple reducer used to increment a counter.
*
* @param {number} state Previous counter value.
* @return {number} New state value.
*/
const counterReducer = state => state + 1;
const getAbsolutePosition = element => {
return {
top: element.offsetTop,
left: element.offsetLeft
};
};
/**
* Hook used to compute the styles required to move a div into a new position.
*
* The way this animation works is the following:
* - It first renders the element as if there was no animation.
* - It takes a snapshot of the position of the block to use it
* as a destination point for the animation.
* - It restores the element to the previous position using a CSS transform
* - It uses the "resetAnimation" flag to reset the animation
* from the beginning in order to animate to the new destination point.
*
* @param {Object} $1 Options
* @param {boolean} $1.isSelected Whether it's the current block or not.
* @param {boolean} $1.adjustScrolling Adjust the scroll position to the current block.
* @param {boolean} $1.enableAnimation Enable/Disable animation.
* @param {*} $1.triggerAnimationOnChange Variable used to trigger the animation if it changes.
*/
function useMovingAnimation(_ref) {
let {
isSelected,
adjustScrolling,
enableAnimation,
triggerAnimationOnChange
} = _ref;
const ref = (0,external_wp_element_namespaceObject.useRef)();
const prefersReducedMotion = (0,external_wp_compose_namespaceObject.useReducedMotion)() || !enableAnimation;
const [triggeredAnimation, triggerAnimation] = (0,external_wp_element_namespaceObject.useReducer)(counterReducer, 0);
const [finishedAnimation, endAnimation] = (0,external_wp_element_namespaceObject.useReducer)(counterReducer, 0);
const [transform, setTransform] = (0,external_wp_element_namespaceObject.useState)({
x: 0,
y: 0
});
const previous = (0,external_wp_element_namespaceObject.useMemo)(() => ref.current ? getAbsolutePosition(ref.current) : null, [triggerAnimationOnChange]); // Calculate the previous position of the block relative to the viewport and
// return a function to maintain that position by scrolling.
const preserveScrollPosition = (0,external_wp_element_namespaceObject.useMemo)(() => {
if (!adjustScrolling || !ref.current) {
return () => {};
}
const scrollContainer = (0,external_wp_dom_namespaceObject.getScrollContainer)(ref.current);
if (!scrollContainer) {
return () => {};
}
const prevRect = ref.current.getBoundingClientRect();
return () => {
const blockRect = ref.current.getBoundingClientRect();
const diff = blockRect.top - prevRect.top;
if (diff) {
scrollContainer.scrollTop += diff;
}
};
}, [triggerAnimationOnChange, adjustScrolling]);
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
if (triggeredAnimation) {
endAnimation();
}
}, [triggeredAnimation]);
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
if (!previous) {
return;
}
if (prefersReducedMotion) {
// If the animation is disabled and the scroll needs to be adjusted,
// just move directly to the final scroll position.
preserveScrollPosition();
return;
}
ref.current.style.transform = undefined;
const destination = getAbsolutePosition(ref.current);
triggerAnimation();
setTransform({
x: Math.round(previous.left - destination.left),
y: Math.round(previous.top - destination.top)
});
}, [triggerAnimationOnChange]);
function onChange(_ref2) {
let {
value
} = _ref2;
if (!ref.current) {
return;
}
let {
x,
y
} = value;
x = Math.round(x);
y = Math.round(y);
const finishedMoving = x === 0 && y === 0;
ref.current.style.transformOrigin = 'center center';
ref.current.style.transform = finishedMoving ? undefined : `translate3d(${x}px,${y}px,0)`;
ref.current.style.zIndex = isSelected ? '1' : '';
preserveScrollPosition();
}
useSpring({
from: {
x: transform.x,
y: transform.y
},
to: {
x: 0,
y: 0
},
reset: triggeredAnimation !== finishedAnimation,
config: {
mass: 5,
tension: 2000,
friction: 200
},
immediate: prefersReducedMotion,
onChange
});
return ref;
}
/* harmony default export */ var use_moving_animation = (useMovingAnimation);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/utils/dom.js
const BLOCK_SELECTOR = '.block-editor-block-list__block';
const APPENDER_SELECTOR = '.block-list-appender';
const BLOCK_APPENDER_CLASS = '.block-editor-button-block-appender';
/**
* Returns true if two elements are contained within the same block.
*
* @param {Element} a First element.
* @param {Element} b Second element.
*
* @return {boolean} Whether elements are in the same block.
*/
function isInSameBlock(a, b) {
return a.closest(BLOCK_SELECTOR) === b.closest(BLOCK_SELECTOR);
}
/**
* Returns true if an element is considered part of the block and not its inner
* blocks or appender.
*
* @param {Element} blockElement Block container element.
* @param {Element} element Element.
*
* @return {boolean} Whether an element is considered part of the block and not
* its inner blocks or appender.
*/
function isInsideRootBlock(blockElement, element) {
const parentBlock = element.closest([BLOCK_SELECTOR, APPENDER_SELECTOR, BLOCK_APPENDER_CLASS].join(','));
return parentBlock === blockElement;
}
/**
* Finds the block client ID given any DOM node inside the block.
*
* @param {Node?} node DOM node.
*
* @return {string|undefined} Client ID or undefined if the node is not part of
* a block.
*/
function getBlockClientId(node) {
while (node && node.nodeType !== node.ELEMENT_NODE) {
node = node.parentNode;
}
if (!node) {
return;
}
const elementNode =
/** @type {Element} */
node;
const blockNode = elementNode.closest(BLOCK_SELECTOR);
if (!blockNode) {
return;
}
return blockNode.id.slice('block-'.length);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-list/use-block-props/use-focus-first-element.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/** @typedef {import('@wordpress/element').RefObject} RefObject */
/**
* Returns the initial position if the block needs to be focussed, `undefined`
* otherwise. The initial position is either 0 (start) or -1 (end).
*
* @param {string} clientId Block client ID.
*
* @return {number} The initial position, either 0 (start) or -1 (end).
*/
function useInitialPosition(clientId) {
return (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getSelectedBlocksInitialCaretPosition,
__unstableGetEditorMode,
isBlockSelected
} = select(store);
if (!isBlockSelected(clientId)) {
return;
}
if (__unstableGetEditorMode() !== 'edit') {
return;
} // If there's no initial position, return 0 to focus the start.
return getSelectedBlocksInitialCaretPosition();
}, [clientId]);
}
/**
* Transitions focus to the block or inner tabbable when the block becomes
* selected and an initial position is set.
*
* @param {string} clientId Block client ID.
*
* @return {RefObject} React ref with the block element.
*/
function useFocusFirstElement(clientId) {
const ref = (0,external_wp_element_namespaceObject.useRef)();
const initialPosition = useInitialPosition(clientId);
const {
isBlockSelected,
isMultiSelecting
} = (0,external_wp_data_namespaceObject.useSelect)(store);
(0,external_wp_element_namespaceObject.useEffect)(() => {
// Check if the block is still selected at the time this effect runs.
if (!isBlockSelected(clientId) || isMultiSelecting()) {
return;
}
if (initialPosition === undefined || initialPosition === null) {
return;
}
if (!ref.current) {
return;
}
const {
ownerDocument
} = ref.current; // Do not focus the block if it already contains the active element.
if (isInsideRootBlock(ref.current, ownerDocument.activeElement)) {
return;
} // Find all tabbables within node.
const textInputs = external_wp_dom_namespaceObject.focus.tabbable.find(ref.current).filter(node => (0,external_wp_dom_namespaceObject.isTextField)(node)); // If reversed (e.g. merge via backspace), use the last in the set of
// tabbables.
const isReverse = -1 === initialPosition;
const target = textInputs[isReverse ? textInputs.length - 1 : 0] || ref.current;
if (!isInsideRootBlock(ref.current, target)) {
ref.current.focus();
return;
} // Check to see if element is focussable before a generic caret insert.
if (!ref.current.getAttribute('contenteditable')) {
const focusElement = external_wp_dom_namespaceObject.focus.tabbable.findNext(ref.current); // Make sure focusElement is valid, contained in the same block, and a form field.
if (focusElement && isInsideRootBlock(ref.current, focusElement) && (0,external_wp_dom_namespaceObject.isFormElement)(focusElement)) {
focusElement.focus();
return;
}
}
(0,external_wp_dom_namespaceObject.placeCaretAtHorizontalEdge)(target, isReverse);
}, [initialPosition, clientId]);
return ref;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-list/use-block-props/use-is-hovered.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function listener(event) {
if (event.defaultPrevented) {
return;
}
const action = event.type === 'mouseover' ? 'add' : 'remove';
event.preventDefault();
event.currentTarget.classList[action]('is-hovered');
}
/**
* Adds `is-hovered` class when the block is hovered and in navigation or
* outline mode.
*/
function useIsHovered() {
const isEnabled = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getSettings
} = select(store);
return getSettings().outlineMode;
}, []);
return (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
if (isEnabled) {
node.addEventListener('mouseout', listener);
node.addEventListener('mouseover', listener);
return () => {
node.removeEventListener('mouseout', listener);
node.removeEventListener('mouseover', listener); // Remove class in case it lingers.
node.classList.remove('is-hovered');
};
}
}, [isEnabled]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-list/use-block-props/use-block-class-names.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Returns the class names used for the different states of the block.
*
* @param {string} clientId The block client ID.
*
* @return {string} The class names.
*/
function useBlockClassNames(clientId) {
return (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
isBlockBeingDragged,
isBlockHighlighted,
isBlockSelected,
isBlockMultiSelected,
getBlockName,
getSettings,
hasSelectedInnerBlock,
isTyping,
__unstableIsFullySelected,
__unstableSelectionHasUnmergeableBlock
} = select(store);
const {
outlineMode
} = getSettings();
const isDragging = isBlockBeingDragged(clientId);
const isSelected = isBlockSelected(clientId);
const name = getBlockName(clientId);
const checkDeep = true; // "ancestor" is the more appropriate label due to "deep" check.
const isAncestorOfSelectedBlock = hasSelectedInnerBlock(clientId, checkDeep);
const isMultiSelected = isBlockMultiSelected(clientId);
return classnames_default()({
'is-selected': isSelected,
'is-highlighted': isBlockHighlighted(clientId),
'is-multi-selected': isMultiSelected,
'is-partially-selected': isMultiSelected && !__unstableIsFullySelected() && !__unstableSelectionHasUnmergeableBlock(),
'is-reusable': (0,external_wp_blocks_namespaceObject.isReusableBlock)((0,external_wp_blocks_namespaceObject.getBlockType)(name)),
'is-dragging': isDragging,
'has-child-selected': isAncestorOfSelectedBlock,
'remove-outline': isSelected && outlineMode && isTyping()
});
}, [clientId]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-list/use-block-props/use-block-default-class-name.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Returns the default class name if the block is a light block and it supports
* `className`.
*
* @param {string} clientId The block client ID.
*
* @return {string} The class name, e.g. `wp-block-paragraph`.
*/
function useBlockDefaultClassName(clientId) {
return (0,external_wp_data_namespaceObject.useSelect)(select => {
const name = select(store).getBlockName(clientId);
const blockType = (0,external_wp_blocks_namespaceObject.getBlockType)(name);
const hasLightBlockWrapper = (blockType === null || blockType === void 0 ? void 0 : blockType.apiVersion) > 1;
if (!hasLightBlockWrapper) {
return;
}
return (0,external_wp_blocks_namespaceObject.getBlockDefaultClassName)(name);
}, [clientId]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-list/use-block-props/use-block-custom-class-name.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Returns the custom class name if the block is a light block.
*
* @param {string} clientId The block client ID.
*
* @return {string} The custom class name.
*/
function useBlockCustomClassName(clientId) {
// It's good for this to be a separate selector because it will be executed
// on every attribute change, while the other selectors are not re-evaluated
// as much.
return (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlockName,
getBlockAttributes
} = select(store);
const attributes = getBlockAttributes(clientId);
if (!(attributes !== null && attributes !== void 0 && attributes.className)) {
return;
}
const blockType = (0,external_wp_blocks_namespaceObject.getBlockType)(getBlockName(clientId));
const hasLightBlockWrapper = (blockType === null || blockType === void 0 ? void 0 : blockType.apiVersion) > 1;
if (!hasLightBlockWrapper) {
return;
}
return attributes.className;
}, [clientId]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-list/use-block-props/use-block-moving-mode-class-names.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Returns the class names used for block moving mode.
*
* @param {string} clientId The block client ID to insert above.
*
* @return {string} The class names.
*/
function useBlockMovingModeClassNames(clientId) {
return (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
hasBlockMovingClientId,
canInsertBlockType,
getBlockName,
getBlockRootClientId,
isBlockSelected
} = select(store); // The classes are only relevant for the selected block. Avoid
// re-rendering all blocks!
if (!isBlockSelected(clientId)) {
return;
}
const movingClientId = hasBlockMovingClientId();
if (!movingClientId) {
return;
}
return classnames_default()('is-block-moving-mode', {
'can-insert-moving-block': canInsertBlockType(getBlockName(movingClientId), getBlockRootClientId(clientId))
});
}, [clientId]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-list/use-block-props/use-focus-handler.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Selects the block if it receives focus.
*
* @param {string} clientId Block client ID.
*/
function useFocusHandler(clientId) {
const {
isBlockSelected
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const {
selectBlock,
selectionChange
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
return (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
/**
* Marks the block as selected when focused and not already
* selected. This specifically handles the case where block does not
* set focus on its own (via `setFocus`), typically if there is no
* focusable input in the block.
*
* @param {FocusEvent} event Focus event.
*/
function onFocus(event) {
// When the whole editor is editable, let writing flow handle
// selection.
if (node.parentElement.closest('[contenteditable="true"]')) {
return;
} // Check synchronously because a non-selected block might be
// getting data through `useSelect` asynchronously.
if (isBlockSelected(clientId)) {
// Potentially change selection away from rich text.
if (!event.target.isContentEditable) {
selectionChange(clientId);
}
return;
} // If an inner block is focussed, that block is resposible for
// setting the selected block.
if (!isInsideRootBlock(node, event.target)) {
return;
}
selectBlock(clientId);
}
node.addEventListener('focusin', onFocus);
return () => {
node.removeEventListener('focusin', onFocus);
};
}, [isBlockSelected, selectBlock]);
}
;// CONCATENATED MODULE: external ["wp","keycodes"]
var external_wp_keycodes_namespaceObject = window["wp"]["keycodes"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-list/use-block-props/use-selected-block-event-handlers.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Adds block behaviour:
* - Removes the block on BACKSPACE.
* - Inserts a default block on ENTER.
* - Disables dragging of block contents.
*
* @param {string} clientId Block client ID.
*/
function useEventHandlers(clientId) {
const isSelected = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).isBlockSelected(clientId), [clientId]);
const {
getBlockRootClientId,
getBlockIndex
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const {
insertDefaultBlock,
removeBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
return (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
if (!isSelected) {
return;
}
/**
* Interprets keydown event intent to remove or insert after block if
* key event occurs on wrapper node. This can occur when the block has
* no text fields of its own, particularly after initial insertion, to
* allow for easy deletion and continuous writing flow to add additional
* content.
*
* @param {KeyboardEvent} event Keydown event.
*/
function onKeyDown(event) {
const {
keyCode,
target
} = event;
if (keyCode !== external_wp_keycodes_namespaceObject.ENTER && keyCode !== external_wp_keycodes_namespaceObject.BACKSPACE && keyCode !== external_wp_keycodes_namespaceObject.DELETE) {
return;
}
if (target !== node || (0,external_wp_dom_namespaceObject.isTextField)(target)) {
return;
}
event.preventDefault();
if (keyCode === external_wp_keycodes_namespaceObject.ENTER) {
insertDefaultBlock({}, getBlockRootClientId(clientId), getBlockIndex(clientId) + 1);
} else {
removeBlock(clientId);
}
}
/**
* Prevents default dragging behavior within a block. To do: we must
* handle this in the future and clean up the drag target.
*
* @param {DragEvent} event Drag event.
*/
function onDragStart(event) {
event.preventDefault();
}
node.addEventListener('keydown', onKeyDown);
node.addEventListener('dragstart', onDragStart);
return () => {
node.removeEventListener('keydown', onKeyDown);
node.removeEventListener('dragstart', onDragStart);
};
}, [clientId, isSelected, getBlockRootClientId, getBlockIndex, insertDefaultBlock, removeBlock]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-list/use-block-props/use-nav-mode-exit.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Allows navigation mode to be exited by clicking in the selected block.
*
* @param {string} clientId Block client ID.
*/
function useNavModeExit(clientId) {
const {
isNavigationMode,
isBlockSelected
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const {
setNavigationMode,
selectBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
return (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
function onMouseDown(event) {
// Don't select a block if it's already handled by a child
// block.
if (isNavigationMode() && !event.defaultPrevented) {
// Prevent focus from moving to the block.
event.preventDefault(); // When clicking on a selected block, exit navigation mode.
if (isBlockSelected(clientId)) {
setNavigationMode(false);
} else {
selectBlock(clientId);
}
}
}
node.addEventListener('mousedown', onMouseDown);
return () => {
node.addEventListener('mousedown', onMouseDown);
};
}, [clientId, isNavigationMode, isBlockSelected, setNavigationMode]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-list/use-block-props/use-intersection-observer.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useIntersectionObserver() {
const observer = (0,external_wp_element_namespaceObject.useContext)(block_list_IntersectionObserver);
return (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
if (observer) {
observer.observe(node);
return () => {
observer.unobserve(node);
};
}
}, [observer]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-content-overlay/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useBlockOverlayActive(clientId) {
return (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
__unstableHasActiveBlockOverlayActive
} = select(store);
return __unstableHasActiveBlockOverlayActive(clientId);
}, [clientId]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-list/use-block-props/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* If the block count exceeds the threshold, we disable the reordering animation
* to avoid laginess.
*/
const BLOCK_ANIMATION_THRESHOLD = 200;
/**
* This hook is used to lightly mark an element as a block element. The element
* should be the outermost element of a block. Call this hook and pass the
* returned props to the element to mark as a block. If you define a ref for the
* element, it is important to pass the ref to this hook, which the hook in turn
* will pass to the component through the props it returns. Optionally, you can
* also pass any other props through this hook, and they will be merged and
* returned.
*
* @param {Object} props Optional. Props to pass to the element. Must contain
* the ref if one is defined.
* @param {Object} options Options for internal use only.
* @param {boolean} options.__unstableIsHtml
*
* @return {Object} Props to pass to the element to mark as a block.
*/
function useBlockProps() {
let props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let {
__unstableIsHtml
} = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const {
clientId,
className,
wrapperProps = {},
isAligned
} = (0,external_wp_element_namespaceObject.useContext)(BlockListBlockContext);
const {
index,
mode,
name,
blockApiVersion,
blockTitle,
isPartOfSelection,
adjustScrolling,
enableAnimation
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlockAttributes,
getBlockIndex,
getBlockMode,
getBlockName,
isTyping,
getGlobalBlockCount,
isBlockSelected,
isBlockMultiSelected,
isAncestorMultiSelected,
isFirstMultiSelectedBlock
} = select(store);
const {
getActiveBlockVariation
} = select(external_wp_blocks_namespaceObject.store);
const isSelected = isBlockSelected(clientId);
const isPartOfMultiSelection = isBlockMultiSelected(clientId) || isAncestorMultiSelected(clientId);
const blockName = getBlockName(clientId);
const blockType = (0,external_wp_blocks_namespaceObject.getBlockType)(blockName);
const attributes = getBlockAttributes(clientId);
const match = getActiveBlockVariation(blockName, attributes);
return {
index: getBlockIndex(clientId),
mode: getBlockMode(clientId),
name: blockName,
blockApiVersion: (blockType === null || blockType === void 0 ? void 0 : blockType.apiVersion) || 1,
blockTitle: (match === null || match === void 0 ? void 0 : match.title) || (blockType === null || blockType === void 0 ? void 0 : blockType.title),
isPartOfSelection: isSelected || isPartOfMultiSelection,
adjustScrolling: isSelected || isFirstMultiSelectedBlock(clientId),
enableAnimation: !isTyping() && getGlobalBlockCount() <= BLOCK_ANIMATION_THRESHOLD
};
}, [clientId]);
const hasOverlay = useBlockOverlayActive(clientId); // translators: %s: Type of block (i.e. Text, Image etc)
const blockLabel = (0,external_wp_i18n_namespaceObject.sprintf)((0,external_wp_i18n_namespaceObject.__)('Block: %s'), blockTitle);
const htmlSuffix = mode === 'html' && !__unstableIsHtml ? '-visual' : '';
const mergedRefs = (0,external_wp_compose_namespaceObject.useMergeRefs)([props.ref, useFocusFirstElement(clientId), useBlockRefProvider(clientId), useFocusHandler(clientId), useEventHandlers(clientId), useNavModeExit(clientId), useIsHovered(), useIntersectionObserver(), use_moving_animation({
isSelected: isPartOfSelection,
adjustScrolling,
enableAnimation,
triggerAnimationOnChange: index
}), (0,external_wp_compose_namespaceObject.useDisabled)({
isDisabled: !hasOverlay
})]);
const blockEditContext = useBlockEditContext(); // Ensures it warns only inside the `edit` implementation for the block.
if (blockApiVersion < 2 && clientId === blockEditContext.clientId) {
typeof process !== "undefined" && process.env && "production" !== "production" ? 0 : void 0;
}
return {
tabIndex: 0,
...wrapperProps,
...props,
ref: mergedRefs,
id: `block-${clientId}${htmlSuffix}`,
role: 'document',
'aria-label': blockLabel,
'data-block': clientId,
'data-type': name,
'data-title': blockTitle,
className: classnames_default()( // The wp-block className is important for editor styles.
classnames_default()('block-editor-block-list__block', {
'wp-block': !isAligned,
'has-block-overlay': hasOverlay
}), className, props.className, wrapperProps.className, useBlockClassNames(clientId), useBlockDefaultClassName(clientId), useBlockCustomClassName(clientId), useBlockMovingModeClassNames(clientId)),
style: { ...wrapperProps.style,
...props.style
}
};
}
/**
* Call within a save function to get the props for the block wrapper.
*
* @param {Object} props Optional. Props to pass to the element.
*/
useBlockProps.save = external_wp_blocks_namespaceObject.__unstableGetBlockProps;
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-list/block.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const BlockListBlockContext = (0,external_wp_element_namespaceObject.createContext)();
/**
* Merges wrapper props with special handling for classNames and styles.
*
* @param {Object} propsA
* @param {Object} propsB
*
* @return {Object} Merged props.
*/
function mergeWrapperProps(propsA, propsB) {
const newProps = { ...propsA,
...propsB
};
if (propsA !== null && propsA !== void 0 && propsA.className && propsB !== null && propsB !== void 0 && propsB.className) {
newProps.className = classnames_default()(propsA.className, propsB.className);
}
if (propsA !== null && propsA !== void 0 && propsA.style && propsB !== null && propsB !== void 0 && propsB.style) {
newProps.style = { ...propsA.style,
...propsB.style
};
}
return newProps;
}
function Block(_ref) {
let {
children,
isHtml,
...props
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("div", useBlockProps(props, {
__unstableIsHtml: isHtml
}), children);
}
function BlockListBlock(_ref2) {
var _wrapperProps;
let {
block: {
__unstableBlockSource
},
mode,
isLocked,
canRemove,
clientId,
isSelected,
isSelectionEnabled,
className,
__unstableLayoutClassNames: layoutClassNames,
name,
isValid,
attributes,
wrapperProps,
setAttributes,
onReplace,
onInsertBlocksAfter,
onMerge,
toggleSelection
} = _ref2;
const {
themeSupportsLayout,
hasContentLockedParent,
isContentBlock,
isContentLocking,
isTemporarilyEditingAsBlocks
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getSettings,
__unstableGetContentLockingParent,
getTemplateLock,
__unstableGetTemporarilyEditingAsBlocks
} = select(store);
const _hasContentLockedParent = !!__unstableGetContentLockingParent(clientId);
return {
themeSupportsLayout: getSettings().supportsLayout,
isContentBlock: select(external_wp_blocks_namespaceObject.store).__experimentalHasContentRoleAttribute(name),
hasContentLockedParent: _hasContentLockedParent,
isContentLocking: getTemplateLock(clientId) === 'contentOnly' && !_hasContentLockedParent,
isTemporarilyEditingAsBlocks: __unstableGetTemporarilyEditingAsBlocks() === clientId
};
}, [name, clientId]);
const {
removeBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const onRemove = (0,external_wp_element_namespaceObject.useCallback)(() => removeBlock(clientId), [clientId]);
const parentLayout = useLayout() || {}; // We wrap the BlockEdit component in a div that hides it when editing in
// HTML mode. This allows us to render all of the ancillary pieces
// (InspectorControls, etc.) which are inside `BlockEdit` but not
// `BlockHTML`, even in HTML mode.
let blockEdit = (0,external_wp_element_namespaceObject.createElement)(BlockEdit, {
name: name,
isSelected: isSelected,
attributes: attributes,
setAttributes: setAttributes,
insertBlocksAfter: isLocked ? undefined : onInsertBlocksAfter,
onReplace: canRemove ? onReplace : undefined,
onRemove: canRemove ? onRemove : undefined,
mergeBlocks: canRemove ? onMerge : undefined,
clientId: clientId,
isSelectionEnabled: isSelectionEnabled,
toggleSelection: toggleSelection,
__unstableLayoutClassNames: layoutClassNames,
__unstableParentLayout: Object.keys(parentLayout).length ? parentLayout : undefined
});
const blockType = (0,external_wp_blocks_namespaceObject.getBlockType)(name);
if (hasContentLockedParent && !isContentBlock) {
wrapperProps = { ...wrapperProps,
tabIndex: -1
};
} // Determine whether the block has props to apply to the wrapper.
if (blockType !== null && blockType !== void 0 && blockType.getEditWrapperProps) {
wrapperProps = mergeWrapperProps(wrapperProps, blockType.getEditWrapperProps(attributes));
}
const isAligned = wrapperProps && !!wrapperProps['data-align'] && !themeSupportsLayout; // For aligned blocks, provide a wrapper element so the block can be
// positioned relative to the block column.
// This is only kept for classic themes that don't support layout
// Historically we used to rely on extra divs and data-align to
// provide the alignments styles in the editor.
// Due to the differences between frontend and backend, we migrated
// to the layout feature, and we're now aligning the markup of frontend
// and backend.
if (isAligned) {
blockEdit = (0,external_wp_element_namespaceObject.createElement)("div", {
className: "wp-block",
"data-align": wrapperProps['data-align']
}, blockEdit);
}
let block;
if (!isValid) {
const saveContent = __unstableBlockSource ? (0,external_wp_blocks_namespaceObject.serializeRawBlock)(__unstableBlockSource) : (0,external_wp_blocks_namespaceObject.getSaveContent)(blockType, attributes);
block = (0,external_wp_element_namespaceObject.createElement)(Block, {
className: "has-warning"
}, (0,external_wp_element_namespaceObject.createElement)(block_invalid_warning, {
clientId: clientId
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.RawHTML, null, (0,external_wp_dom_namespaceObject.safeHTML)(saveContent)));
} else if (mode === 'html') {
// Render blockEdit so the inspector controls don't disappear.
// See #8969.
block = (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("div", {
style: {
display: 'none'
}
}, blockEdit), (0,external_wp_element_namespaceObject.createElement)(Block, {
isHtml: true
}, (0,external_wp_element_namespaceObject.createElement)(block_html, {
clientId: clientId
})));
} else if ((blockType === null || blockType === void 0 ? void 0 : blockType.apiVersion) > 1) {
block = blockEdit;
} else {
block = (0,external_wp_element_namespaceObject.createElement)(Block, wrapperProps, blockEdit);
}
const {
'data-align': dataAlign,
...restWrapperProps
} = (_wrapperProps = wrapperProps) !== null && _wrapperProps !== void 0 ? _wrapperProps : {};
const value = {
clientId,
className: classnames_default()({
'is-content-locked': isContentLocking,
'is-content-locked-temporarily-editing-as-blocks': isTemporarilyEditingAsBlocks,
'is-content-block': hasContentLockedParent && isContentBlock
}, dataAlign && themeSupportsLayout && `align${dataAlign}`, className),
wrapperProps: restWrapperProps,
isAligned
};
const memoizedValue = (0,external_wp_element_namespaceObject.useMemo)(() => value, Object.values(value));
return (0,external_wp_element_namespaceObject.createElement)(BlockListBlockContext.Provider, {
value: memoizedValue
}, (0,external_wp_element_namespaceObject.createElement)(block_crash_boundary, {
fallback: (0,external_wp_element_namespaceObject.createElement)(Block, {
className: "has-warning"
}, (0,external_wp_element_namespaceObject.createElement)(block_crash_warning, null))
}, block));
}
const applyWithSelect = (0,external_wp_data_namespaceObject.withSelect)((select, _ref3) => {
let {
clientId,
rootClientId
} = _ref3;
const {
isBlockSelected,
getBlockMode,
isSelectionEnabled,
getTemplateLock,
__unstableGetBlockWithoutInnerBlocks,
canRemoveBlock,
canMoveBlock
} = select(store);
const block = __unstableGetBlockWithoutInnerBlocks(clientId);
const isSelected = isBlockSelected(clientId);
const templateLock = getTemplateLock(rootClientId);
const canRemove = canRemoveBlock(clientId, rootClientId);
const canMove = canMoveBlock(clientId, rootClientId); // The fallback to `{}` is a temporary fix.
// This function should never be called when a block is not present in
// the state. It happens now because the order in withSelect rendering
// is not correct.
const {
name,
attributes,
isValid
} = block || {}; // Do not add new properties here, use `useSelect` instead to avoid
// leaking new props to the public API (editor.BlockListBlock filter).
return {
mode: getBlockMode(clientId),
isSelectionEnabled: isSelectionEnabled(),
isLocked: !!templateLock,
canRemove,
canMove,
// Users of the editor.BlockListBlock filter used to be able to
// access the block prop.
// Ideally these blocks would rely on the clientId prop only.
// This is kept for backward compatibility reasons.
block,
name,
attributes,
isValid,
isSelected
};
});
const applyWithDispatch = (0,external_wp_data_namespaceObject.withDispatch)((dispatch, ownProps, registry) => {
const {
updateBlockAttributes,
insertBlocks,
mergeBlocks,
replaceBlocks,
toggleSelection,
__unstableMarkLastChangeAsPersistent,
moveBlocksToPosition,
removeBlock
} = dispatch(store); // Do not add new properties here, use `useDispatch` instead to avoid
// leaking new props to the public API (editor.BlockListBlock filter).
return {
setAttributes(newAttributes) {
const {
getMultiSelectedBlockClientIds
} = registry.select(store);
const multiSelectedBlockClientIds = getMultiSelectedBlockClientIds();
const {
clientId
} = ownProps;
const clientIds = multiSelectedBlockClientIds.length ? multiSelectedBlockClientIds : [clientId];
updateBlockAttributes(clientIds, newAttributes);
},
onInsertBlocks(blocks, index) {
const {
rootClientId
} = ownProps;
insertBlocks(blocks, index, rootClientId);
},
onInsertBlocksAfter(blocks) {
const {
clientId,
rootClientId
} = ownProps;
const {
getBlockIndex
} = registry.select(store);
const index = getBlockIndex(clientId);
insertBlocks(blocks, index + 1, rootClientId);
},
onMerge(forward) {
const {
clientId,
rootClientId
} = ownProps;
const {
getPreviousBlockClientId,
getNextBlockClientId,
getBlock,
getBlockAttributes,
getBlockName,
getBlockOrder,
getBlockIndex,
getBlockRootClientId,
canInsertBlockType
} = registry.select(store);
/**
* Moves the block with clientId up one level. If the block type
* cannot be inserted at the new location, it will be attempted to
* convert to the default block type.
*
* @param {string} _clientId The block to move.
* @param {boolean} changeSelection Whether to change the selection
* to the moved block.
*/
function moveFirstItemUp(_clientId) {
let changeSelection = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
const targetRootClientId = getBlockRootClientId(_clientId);
const blockOrder = getBlockOrder(_clientId);
const [firstClientId] = blockOrder;
if (blockOrder.length === 1 && (0,external_wp_blocks_namespaceObject.isUnmodifiedBlock)(getBlock(firstClientId))) {
removeBlock(_clientId);
} else {
if (canInsertBlockType(getBlockName(firstClientId), targetRootClientId)) {
moveBlocksToPosition([firstClientId], _clientId, targetRootClientId, getBlockIndex(_clientId));
} else {
const replacement = (0,external_wp_blocks_namespaceObject.switchToBlockType)(getBlock(firstClientId), (0,external_wp_blocks_namespaceObject.getDefaultBlockName)());
if (replacement && replacement.length) {
registry.batch(() => {
insertBlocks(replacement, getBlockIndex(_clientId), targetRootClientId, changeSelection);
removeBlock(firstClientId, false);
});
}
}
if (!getBlockOrder(_clientId).length && (0,external_wp_blocks_namespaceObject.isUnmodifiedBlock)(getBlock(_clientId))) {
removeBlock(_clientId, false);
}
}
} // For `Delete` or forward merge, we should do the exact same thing
// as `Backspace`, but from the other block.
if (forward) {
if (rootClientId) {
const nextRootClientId = getNextBlockClientId(rootClientId);
if (nextRootClientId) {
// If there is a block that follows with the same parent
// block name and the same attributes, merge the inner
// blocks.
if (getBlockName(rootClientId) === getBlockName(nextRootClientId)) {
const rootAttributes = getBlockAttributes(rootClientId);
const previousRootAttributes = getBlockAttributes(nextRootClientId);
if (Object.keys(rootAttributes).every(key => rootAttributes[key] === previousRootAttributes[key])) {
registry.batch(() => {
moveBlocksToPosition(getBlockOrder(nextRootClientId), nextRootClientId, rootClientId);
removeBlock(nextRootClientId, false);
});
return;
}
} else {
mergeBlocks(rootClientId, nextRootClientId);
return;
}
}
}
const nextBlockClientId = getNextBlockClientId(clientId);
if (!nextBlockClientId) {
return;
}
if (getBlockOrder(nextBlockClientId).length) {
moveFirstItemUp(nextBlockClientId, false);
} else {
mergeBlocks(clientId, nextBlockClientId);
}
} else {
const previousBlockClientId = getPreviousBlockClientId(clientId);
if (previousBlockClientId) {
mergeBlocks(previousBlockClientId, clientId);
} else if (rootClientId) {
const previousRootClientId = getPreviousBlockClientId(rootClientId); // If there is a preceding block with the same parent block
// name and the same attributes, merge the inner blocks.
if (previousRootClientId && getBlockName(rootClientId) === getBlockName(previousRootClientId)) {
const rootAttributes = getBlockAttributes(rootClientId);
const previousRootAttributes = getBlockAttributes(previousRootClientId);
if (Object.keys(rootAttributes).every(key => rootAttributes[key] === previousRootAttributes[key])) {
registry.batch(() => {
moveBlocksToPosition(getBlockOrder(rootClientId), rootClientId, previousRootClientId);
removeBlock(rootClientId, false);
});
return;
}
}
moveFirstItemUp(rootClientId);
}
}
},
onReplace(blocks, indexToSelect, initialPosition) {
if (blocks.length && !(0,external_wp_blocks_namespaceObject.isUnmodifiedDefaultBlock)(blocks[blocks.length - 1])) {
__unstableMarkLastChangeAsPersistent();
}
replaceBlocks([ownProps.clientId], blocks, indexToSelect, initialPosition);
},
toggleSelection(selectionEnabled) {
toggleSelection(selectionEnabled);
}
};
});
/* harmony default export */ var block = ((0,external_wp_compose_namespaceObject.compose)(external_wp_compose_namespaceObject.pure, applyWithSelect, applyWithDispatch, // Block is sometimes not mounted at the right time, causing it be undefined
// see issue for more info
// https://github.com/WordPress/gutenberg/issues/17013
(0,external_wp_compose_namespaceObject.ifCondition)(_ref4 => {
let {
block
} = _ref4;
return !!block;
}), (0,external_wp_components_namespaceObject.withFilters)('editor.BlockListBlock'))(BlockListBlock));
;// CONCATENATED MODULE: external ["wp","htmlEntities"]
var external_wp_htmlEntities_namespaceObject = window["wp"]["htmlEntities"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/plus.js
/**
* WordPress dependencies
*/
const plus = (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: "M18 11.2h-5.2V6h-1.6v5.2H6v1.6h5.2V18h1.6v-5.2H18z"
}));
/* harmony default export */ var library_plus = (plus);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/tips.js
/**
* WordPress dependencies
*/
const globalTips = [(0,external_wp_element_namespaceObject.createInterpolateElement)((0,external_wp_i18n_namespaceObject.__)('While writing, you can press <kbd>/</kbd> to quickly insert new blocks.'), {
kbd: (0,external_wp_element_namespaceObject.createElement)("kbd", null)
}), (0,external_wp_element_namespaceObject.createInterpolateElement)((0,external_wp_i18n_namespaceObject.__)('Indent a list by pressing <kbd>space</kbd> at the beginning of a line.'), {
kbd: (0,external_wp_element_namespaceObject.createElement)("kbd", null)
}), (0,external_wp_element_namespaceObject.createInterpolateElement)((0,external_wp_i18n_namespaceObject.__)('Outdent a list by pressing <kbd>backspace</kbd> at the beginning of a line.'), {
kbd: (0,external_wp_element_namespaceObject.createElement)("kbd", null)
}), (0,external_wp_i18n_namespaceObject.__)('Drag files into the editor to automatically insert media blocks.'), (0,external_wp_i18n_namespaceObject.__)("Change a block's type by pressing the block icon on the toolbar.")];
function Tips() {
const [randomIndex] = (0,external_wp_element_namespaceObject.useState)( // Disable Reason: I'm not generating an HTML id.
// eslint-disable-next-line no-restricted-syntax
Math.floor(Math.random() * globalTips.length));
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Tip, null, globalTips[randomIndex]);
}
/* harmony default export */ var tips = (Tips);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/chevron-right.js
/**
* WordPress dependencies
*/
const chevronRight = (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: "M10.6 6L9.4 7l4.6 5-4.6 5 1.2 1 5.4-6z"
}));
/* harmony default export */ var chevron_right = (chevronRight);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/chevron-left.js
/**
* WordPress dependencies
*/
const chevronLeft = (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: "M14.6 7l-1.2-1L8 12l5.4 6 1.2-1-4.6-5z"
}));
/* harmony default export */ var chevron_left = (chevronLeft);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/block-default.js
/**
* WordPress dependencies
*/
const blockDefault = (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 8h-1V6h-5v2h-2V6H6v2H5c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-8c0-1.1-.9-2-2-2zm.5 10c0 .3-.2.5-.5.5H5c-.3 0-.5-.2-.5-.5v-8c0-.3.2-.5.5-.5h14c.3 0 .5.2.5.5v8z"
}));
/* harmony default export */ var block_default = (blockDefault);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-icon/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
function BlockIcon(_ref) {
var _icon;
let {
icon,
showColors = false,
className,
context
} = _ref;
if (((_icon = icon) === null || _icon === void 0 ? void 0 : _icon.src) === 'block-default') {
icon = {
src: block_default
};
}
const renderedIcon = (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Icon, {
icon: icon && icon.src ? icon.src : icon,
context: context
});
const style = showColors ? {
backgroundColor: icon && icon.background,
color: icon && icon.foreground
} : {};
return (0,external_wp_element_namespaceObject.createElement)("span", {
style: style,
className: classnames_default()('block-editor-block-icon', className, {
'has-colors': showColors
})
}, renderedIcon);
}
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/block-icon/README.md
*/
/* harmony default export */ var block_icon = ((0,external_wp_element_namespaceObject.memo)(BlockIcon));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-card/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function BlockCard(_ref) {
let {
title,
icon,
description,
blockType,
className
} = _ref;
if (blockType) {
external_wp_deprecated_default()('`blockType` property in `BlockCard component`', {
since: '5.7',
alternative: '`title, icon and description` properties'
});
({
title,
icon,
description
} = blockType);
}
const {
parentNavBlockClientId
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getSelectedBlockClientId,
getBlockParentsByBlockName
} = select(store);
const _selectedBlockClientId = getSelectedBlockClientId();
return {
parentNavBlockClientId: getBlockParentsByBlockName(_selectedBlockClientId, 'core/navigation', true)[0]
};
}, []);
const {
selectBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('block-editor-block-card', className)
}, parentNavBlockClientId && // This is only used by the Navigation block for now. It's not ideal having Navigation block specific code here.
(0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
onClick: () => selectBlock(parentNavBlockClientId),
label: (0,external_wp_i18n_namespaceObject.__)('Go to parent Navigation block'),
style: // TODO: This style override is also used in ToolsPanelHeader.
// It should be supported out-of-the-box by Button.
{
minWidth: 24,
padding: 0
},
icon: (0,external_wp_i18n_namespaceObject.isRTL)() ? chevron_right : chevron_left,
isSmall: true
}), (0,external_wp_element_namespaceObject.createElement)(block_icon, {
icon: icon,
showColors: true
}), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-card__content"
}, (0,external_wp_element_namespaceObject.createElement)("h2", {
className: "block-editor-block-card__title"
}, title), (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-block-card__description"
}, description)));
}
/* harmony default export */ var block_card = (BlockCard);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/provider/with-registry-provider.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const withRegistryProvider = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(WrappedComponent => {
return (0,external_wp_data_namespaceObject.withRegistry)(_ref => {
let {
useSubRegistry = true,
registry,
...props
} = _ref;
if (!useSubRegistry) {
return (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, _extends({
registry: registry
}, props));
}
const [subRegistry, setSubRegistry] = (0,external_wp_element_namespaceObject.useState)(null);
(0,external_wp_element_namespaceObject.useEffect)(() => {
const newRegistry = (0,external_wp_data_namespaceObject.createRegistry)({}, registry);
newRegistry.registerStore(STORE_NAME, storeConfig);
setSubRegistry(newRegistry);
}, [registry]);
if (!subRegistry) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_data_namespaceObject.RegistryProvider, {
value: subRegistry
}, (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, _extends({
registry: subRegistry
}, props)));
});
}, 'withRegistryProvider');
/* harmony default export */ var with_registry_provider = (withRegistryProvider);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/provider/use-block-sync.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const use_block_sync_noop = () => {};
/**
* A function to call when the block value has been updated in the block-editor
* store.
*
* @callback onBlockUpdate
* @param {Object[]} blocks The updated blocks.
* @param {Object} options The updated block options, such as selectionStart
* and selectionEnd.
*/
/**
* useBlockSync is a side effect which handles bidirectional sync between the
* block-editor store and a controlling data source which provides blocks. This
* is most commonly used by the BlockEditorProvider to synchronize the contents
* of the block-editor store with the root entity, like a post.
*
* Another example would be the template part block, which provides blocks from
* a separate entity data source than a root entity. This hook syncs edits to
* the template part in the block editor back to the entity and vice-versa.
*
* Here are some of its basic functions:
* - Initalizes the block-editor store for the given clientID to the blocks
* given via props.
* - Adds incoming changes (like undo) to the block-editor store.
* - Adds outgoing changes (like editing content) to the controlling entity,
* determining if a change should be considered persistent or not.
* - Handles edge cases and race conditions which occur in those operations.
* - Ignores changes which happen to other entities (like nested inner block
* controllers.
* - Passes selection state from the block-editor store to the controlling entity.
*
* @param {Object} props Props for the block sync hook
* @param {string} props.clientId The client ID of the inner block controller.
* If none is passed, then it is assumed to be a
* root controller rather than an inner block
* controller.
* @param {Object[]} props.value The control value for the blocks. This value
* is used to initalize the block-editor store
* and for resetting the blocks to incoming
* changes like undo.
* @param {Object} props.selection The selection state responsible to restore the selection on undo/redo.
* @param {onBlockUpdate} props.onChange Function to call when a persistent
* change has been made in the block-editor blocks
* for the given clientId. For example, after
* this function is called, an entity is marked
* dirty because it has changes to save.
* @param {onBlockUpdate} props.onInput Function to call when a non-persistent
* change has been made in the block-editor blocks
* for the given clientId. When this is called,
* controlling sources do not become dirty.
*/
function useBlockSync(_ref) {
let {
clientId = null,
value: controlledBlocks,
selection: controlledSelection,
onChange = use_block_sync_noop,
onInput = use_block_sync_noop
} = _ref;
const registry = (0,external_wp_data_namespaceObject.useRegistry)();
const {
resetBlocks,
resetSelection,
replaceInnerBlocks,
setHasControlledInnerBlocks,
__unstableMarkNextChangeAsNotPersistent
} = registry.dispatch(store);
const {
getBlockName,
getBlocks
} = registry.select(store);
const isControlled = (0,external_wp_data_namespaceObject.useSelect)(select => {
return !clientId || select(store).areInnerBlocksControlled(clientId);
}, [clientId]);
const pendingChanges = (0,external_wp_element_namespaceObject.useRef)({
incoming: null,
outgoing: []
});
const subscribed = (0,external_wp_element_namespaceObject.useRef)(false);
const setControlledBlocks = () => {
if (!controlledBlocks) {
return;
} // We don't need to persist this change because we only replace
// controlled inner blocks when the change was caused by an entity,
// and so it would already be persisted.
__unstableMarkNextChangeAsNotPersistent();
if (clientId) {
// It is important to batch here because otherwise,
// as soon as `setHasControlledInnerBlocks` is called
// the effect to restore might be triggered
// before the actual blocks get set properly in state.
registry.batch(() => {
setHasControlledInnerBlocks(clientId, true);
const storeBlocks = controlledBlocks.map(block => (0,external_wp_blocks_namespaceObject.cloneBlock)(block));
if (subscribed.current) {
pendingChanges.current.incoming = storeBlocks;
}
__unstableMarkNextChangeAsNotPersistent();
replaceInnerBlocks(clientId, storeBlocks);
});
} else {
if (subscribed.current) {
pendingChanges.current.incoming = controlledBlocks;
}
resetBlocks(controlledBlocks);
}
}; // Add a subscription to the block-editor registry to detect when changes
// have been made. This lets us inform the data source of changes. This
// is an effect so that the subscriber can run synchronously without
// waiting for React renders for changes.
const onInputRef = (0,external_wp_element_namespaceObject.useRef)(onInput);
const onChangeRef = (0,external_wp_element_namespaceObject.useRef)(onChange);
(0,external_wp_element_namespaceObject.useEffect)(() => {
onInputRef.current = onInput;
onChangeRef.current = onChange;
}, [onInput, onChange]); // Determine if blocks need to be reset when they change.
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (pendingChanges.current.outgoing.includes(controlledBlocks)) {
// Skip block reset if the value matches expected outbound sync
// triggered by this component by a preceding change detection.
// Only skip if the value matches expectation, since a reset should
// still occur if the value is modified (not equal by reference),
// to allow that the consumer may apply modifications to reflect
// back on the editor.
if (pendingChanges.current.outgoing[pendingChanges.current.outgoing.length - 1] === controlledBlocks) {
pendingChanges.current.outgoing = [];
}
} else if (getBlocks(clientId) !== controlledBlocks) {
// Reset changing value in all other cases than the sync described
// above. Since this can be reached in an update following an out-
// bound sync, unset the outbound value to avoid considering it in
// subsequent renders.
pendingChanges.current.outgoing = [];
setControlledBlocks();
if (controlledSelection) {
resetSelection(controlledSelection.selectionStart, controlledSelection.selectionEnd, controlledSelection.initialPosition);
}
}
}, [controlledBlocks, clientId]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
// When the block becomes uncontrolled, it means its inner state has been reset
// we need to take the blocks again from the external value property.
if (!isControlled) {
pendingChanges.current.outgoing = [];
setControlledBlocks();
}
}, [isControlled]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
const {
getSelectionStart,
getSelectionEnd,
getSelectedBlocksInitialCaretPosition,
isLastBlockChangePersistent,
__unstableIsLastBlockChangeIgnored,
areInnerBlocksControlled
} = registry.select(store);
let blocks = getBlocks(clientId);
let isPersistent = isLastBlockChangePersistent();
let previousAreBlocksDifferent = false;
subscribed.current = true;
const unsubscribe = registry.subscribe(() => {
// Sometimes, when changing block lists, lingering subscriptions
// might trigger before they are cleaned up. If the block for which
// the subscription runs is no longer in the store, this would clear
// its parent entity's block list. To avoid this, we bail out if
// the subscription is triggering for a block (`clientId !== null`)
// and its block name can't be found because it's not on the list.
// (`getBlockName( clientId ) === null`).
if (clientId !== null && getBlockName(clientId) === null) return; // When RESET_BLOCKS on parent blocks get called, the controlled blocks
// can reset to uncontrolled, in these situations, it means we need to populate
// the blocks again from the external blocks (the value property here)
// and we should stop triggering onChange
const isStillControlled = !clientId || areInnerBlocksControlled(clientId);
if (!isStillControlled) {
return;
}
const newIsPersistent = isLastBlockChangePersistent();
const newBlocks = getBlocks(clientId);
const areBlocksDifferent = newBlocks !== blocks;
blocks = newBlocks;
if (areBlocksDifferent && (pendingChanges.current.incoming || __unstableIsLastBlockChangeIgnored())) {
pendingChanges.current.incoming = null;
isPersistent = newIsPersistent;
return;
} // Since we often dispatch an action to mark the previous action as
// persistent, we need to make sure that the blocks changed on the
// previous action before committing the change.
const didPersistenceChange = previousAreBlocksDifferent && !areBlocksDifferent && newIsPersistent && !isPersistent;
if (areBlocksDifferent || didPersistenceChange) {
isPersistent = newIsPersistent; // We know that onChange/onInput will update controlledBlocks.
// We need to be aware that it was caused by an outgoing change
// so that we do not treat it as an incoming change later on,
// which would cause a block reset.
pendingChanges.current.outgoing.push(blocks); // Inform the controlling entity that changes have been made to
// the block-editor store they should be aware about.
const updateParent = isPersistent ? onChangeRef.current : onInputRef.current;
updateParent(blocks, {
selection: {
selectionStart: getSelectionStart(),
selectionEnd: getSelectionEnd(),
initialPosition: getSelectedBlocksInitialCaretPosition()
}
});
}
previousAreBlocksDifferent = areBlocksDifferent;
});
return () => {
subscribed.current = false;
unsubscribe();
};
}, [registry, clientId]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/provider/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/** @typedef {import('@wordpress/data').WPDataRegistry} WPDataRegistry */
const ExperimentalBlockEditorProvider = with_registry_provider(props => {
const {
children,
settings,
stripExperimentalSettings = false
} = props;
const {
__experimentalUpdateSettings
} = unlock((0,external_wp_data_namespaceObject.useDispatch)(store));
(0,external_wp_element_namespaceObject.useEffect)(() => {
__experimentalUpdateSettings({ ...settings,
__internalIsInitialized: true
}, stripExperimentalSettings);
}, [settings]); // Syncs the entity provider with changes in the block-editor store.
useBlockSync(props);
return (0,external_wp_element_namespaceObject.createElement)(BlockRefsProvider, null, children);
});
const BlockEditorProvider = props => {
return (0,external_wp_element_namespaceObject.createElement)(ExperimentalBlockEditorProvider, _extends({}, props, {
stripExperimentalSettings: true
}), props.children);
};
/* harmony default export */ var provider = (BlockEditorProvider);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-selection-clearer/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Pass the returned ref callback to an element that should clear block
* selection. Selection will only be cleared if the element is clicked directly,
* not if a child element is clicked.
*
* @return {import('react').RefCallback} Ref callback.
*/
function useBlockSelectionClearer() {
const {
getSettings,
hasSelectedBlock,
hasMultiSelection
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const {
clearSelectedBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const {
clearBlockSelection: isEnabled
} = getSettings();
return (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
if (!isEnabled) {
return;
}
function onMouseDown(event) {
if (!hasSelectedBlock() && !hasMultiSelection()) {
return;
} // Only handle clicks on the element, not the children.
if (event.target !== node) {
return;
}
clearSelectedBlock();
}
node.addEventListener('mousedown', onMouseDown);
return () => {
node.removeEventListener('mousedown', onMouseDown);
};
}, [hasSelectedBlock, hasMultiSelection, clearSelectedBlock, isEnabled]);
}
function BlockSelectionClearer(props) {
return (0,external_wp_element_namespaceObject.createElement)("div", _extends({
ref: useBlockSelectionClearer()
}, props));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/writing-flow/use-multi-selection.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function selector(select) {
const {
isMultiSelecting,
getMultiSelectedBlockClientIds,
hasMultiSelection,
getSelectedBlockClientId,
getSelectedBlocksInitialCaretPosition,
__unstableIsFullySelected
} = select(store);
return {
isMultiSelecting: isMultiSelecting(),
multiSelectedBlockClientIds: getMultiSelectedBlockClientIds(),
hasMultiSelection: hasMultiSelection(),
selectedBlockClientId: getSelectedBlockClientId(),
initialPosition: getSelectedBlocksInitialCaretPosition(),
isFullSelection: __unstableIsFullySelected()
};
}
function useMultiSelection() {
const {
initialPosition,
isMultiSelecting,
multiSelectedBlockClientIds,
hasMultiSelection,
selectedBlockClientId,
isFullSelection
} = (0,external_wp_data_namespaceObject.useSelect)(selector, []);
/**
* When the component updates, and there is multi selection, we need to
* select the entire block contents.
*/
return (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
const {
ownerDocument
} = node;
const {
defaultView
} = ownerDocument; // Allow initialPosition to bypass focus behavior. This is useful
// for the list view or other areas where we don't want to transfer
// focus to the editor canvas.
if (initialPosition === undefined || initialPosition === null) {
return;
}
if (!hasMultiSelection || isMultiSelecting) {
return;
}
const {
length
} = multiSelectedBlockClientIds;
if (length < 2) {
return;
}
if (!isFullSelection) {
return;
} // Allow cross contentEditable selection by temporarily making
// all content editable. We can't rely on using the store and
// React because re-rending happens too slowly. We need to be
// able to select across instances immediately.
node.contentEditable = true; // For some browsers, like Safari, it is important that focus
// happens BEFORE selection removal.
node.focus();
defaultView.getSelection().removeAllRanges();
}, [hasMultiSelection, isMultiSelecting, multiSelectedBlockClientIds, selectedBlockClientId, initialPosition, isFullSelection]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/writing-flow/use-tab-nav.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useTabNav() {
const container = (0,external_wp_element_namespaceObject.useRef)();
const focusCaptureBeforeRef = (0,external_wp_element_namespaceObject.useRef)();
const focusCaptureAfterRef = (0,external_wp_element_namespaceObject.useRef)();
const lastFocus = (0,external_wp_element_namespaceObject.useRef)();
const {
hasMultiSelection,
getSelectedBlockClientId,
getBlockCount
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const {
setNavigationMode
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const isNavigationMode = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).isNavigationMode(), []); // Don't allow tabbing to this element in Navigation mode.
const focusCaptureTabIndex = !isNavigationMode ? '0' : undefined; // Reference that holds the a flag for enabling or disabling
// capturing on the focus capture elements.
const noCapture = (0,external_wp_element_namespaceObject.useRef)();
function onFocusCapture(event) {
// Do not capture incoming focus if set by us in WritingFlow.
if (noCapture.current) {
noCapture.current = null;
} else if (hasMultiSelection()) {
container.current.focus();
} else if (getSelectedBlockClientId()) {
lastFocus.current.focus();
} else {
setNavigationMode(true);
const isBefore = // eslint-disable-next-line no-bitwise
event.target.compareDocumentPosition(container.current) & event.target.DOCUMENT_POSITION_FOLLOWING;
const action = isBefore ? 'findNext' : 'findPrevious';
external_wp_dom_namespaceObject.focus.tabbable[action](event.target).focus();
}
}
const before = (0,external_wp_element_namespaceObject.createElement)("div", {
ref: focusCaptureBeforeRef,
tabIndex: focusCaptureTabIndex,
onFocus: onFocusCapture
});
const after = (0,external_wp_element_namespaceObject.createElement)("div", {
ref: focusCaptureAfterRef,
tabIndex: focusCaptureTabIndex,
onFocus: onFocusCapture
});
const ref = (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
function onKeyDown(event) {
if (event.defaultPrevented) {
return;
}
if (event.keyCode === external_wp_keycodes_namespaceObject.ESCAPE) {
event.preventDefault();
setNavigationMode(true);
return;
} // In Edit mode, Tab should focus the first tabbable element after
// the content, which is normally the sidebar (with block controls)
// and Shift+Tab should focus the first tabbable element before the
// content, which is normally the block toolbar.
// Arrow keys can be used, and Tab and arrow keys can be used in
// Navigation mode (press Esc), to navigate through blocks.
if (event.keyCode !== external_wp_keycodes_namespaceObject.TAB) {
return;
}
const isShift = event.shiftKey;
const direction = isShift ? 'findPrevious' : 'findNext';
if (!hasMultiSelection() && !getSelectedBlockClientId()) {
// Preserve the behaviour of entering navigation mode when
// tabbing into the content without a block selection.
// `onFocusCapture` already did this previously, but we need to
// do it again here because after clearing block selection,
// focus land on the writing flow container and pressing Tab
// will no longer send focus through the focus capture element.
if (event.target === node) setNavigationMode(true);
return;
} // Allow tabbing from the block wrapper to a form element,
// and between form elements rendered in a block,
// such as inside a placeholder. Form elements are generally
// meant to be UI rather than part of the content. Ideally
// these are not rendered in the content and perhaps in the
// future they can be rendered in an iframe or shadow DOM.
if (((0,external_wp_dom_namespaceObject.isFormElement)(event.target) || event.target.getAttribute('data-block') === getSelectedBlockClientId()) && (0,external_wp_dom_namespaceObject.isFormElement)(external_wp_dom_namespaceObject.focus.tabbable[direction](event.target))) {
return;
}
const next = isShift ? focusCaptureBeforeRef : focusCaptureAfterRef; // Disable focus capturing on the focus capture element, so it
// doesn't refocus this block and so it allows default behaviour
// (moving focus to the next tabbable element).
noCapture.current = true; // Focusing the focus capture element, which is located above and
// below the editor, should not scroll the page all the way up or
// down.
next.current.focus({
preventScroll: true
});
}
function onFocusOut(event) {
lastFocus.current = event.target;
const {
ownerDocument
} = node; // If focus disappears due to there being no blocks, move focus to
// the writing flow wrapper.
if (!event.relatedTarget && ownerDocument.activeElement === ownerDocument.body && getBlockCount() === 0) {
node.focus();
}
} // When tabbing back to an element in block list, this event handler prevents scrolling if the
// focus capture divs (before/after) are outside of the viewport. (For example shift+tab back to a paragraph
// when focus is on a sidebar element. This prevents the scrollable writing area from jumping either to the
// top or bottom of the document.
//
// Note that it isn't possible to disable scrolling in the onFocus event. We need to intercept this
// earlier in the keypress handler, and call focus( { preventScroll: true } ) instead.
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/focus#parameters
function preventScrollOnTab(event) {
var _event$target;
if (event.keyCode !== external_wp_keycodes_namespaceObject.TAB) {
return;
}
if (((_event$target = event.target) === null || _event$target === void 0 ? void 0 : _event$target.getAttribute('role')) === 'region') {
return;
}
if (container.current === event.target) {
return;
}
const isShift = event.shiftKey;
const direction = isShift ? 'findPrevious' : 'findNext';
const target = external_wp_dom_namespaceObject.focus.tabbable[direction](event.target); // Only do something when the next tabbable is a focus capture div (before/after)
if (target === focusCaptureBeforeRef.current || target === focusCaptureAfterRef.current) {
event.preventDefault();
target.focus({
preventScroll: true
});
}
}
const {
ownerDocument
} = node;
const {
defaultView
} = ownerDocument;
defaultView.addEventListener('keydown', preventScrollOnTab);
node.addEventListener('keydown', onKeyDown);
node.addEventListener('focusout', onFocusOut);
return () => {
defaultView.removeEventListener('keydown', preventScrollOnTab);
node.removeEventListener('keydown', onKeyDown);
node.removeEventListener('focusout', onFocusOut);
};
}, []);
const mergedRefs = (0,external_wp_compose_namespaceObject.useMergeRefs)([container, ref]);
return [before, mergedRefs, after];
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/writing-flow/use-arrow-nav.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Returns true if the element should consider edge navigation upon a keyboard
* event of the given directional key code, or false otherwise.
*
* @param {Element} element HTML element to test.
* @param {number} keyCode KeyboardEvent keyCode to test.
* @param {boolean} hasModifier Whether a modifier is pressed.
*
* @return {boolean} Whether element should consider edge navigation.
*/
function isNavigationCandidate(element, keyCode, hasModifier) {
const isVertical = keyCode === external_wp_keycodes_namespaceObject.UP || keyCode === external_wp_keycodes_namespaceObject.DOWN; // Currently, all elements support unmodified vertical navigation.
if (isVertical && !hasModifier) {
return true;
}
const {
tagName
} = element; // Native inputs should not navigate horizontally, unless they are simple types that don't need left/right arrow keys.
if (tagName === 'INPUT') {
const simpleInputTypes = ['button', 'checkbox', 'color', 'file', 'image', 'radio', 'reset', 'submit'];
return simpleInputTypes.includes(element.getAttribute('type'));
} // Native textareas should not navigate horizontally.
return tagName !== 'TEXTAREA';
}
/**
* Returns the optimal tab target from the given focused element in the desired
* direction. A preference is made toward text fields, falling back to the block
* focus stop if no other candidates exist for the block.
*
* @param {Element} target Currently focused text field.
* @param {boolean} isReverse True if considering as the first field.
* @param {Element} containerElement Element containing all blocks.
* @param {boolean} onlyVertical Whether to only consider tabbable elements
* that are visually above or under the
* target.
*
* @return {?Element} Optimal tab target, if one exists.
*/
function getClosestTabbable(target, isReverse, containerElement, onlyVertical) {
// Since the current focus target is not guaranteed to be a text field, find
// all focusables. Tabbability is considered later.
let focusableNodes = external_wp_dom_namespaceObject.focus.focusable.find(containerElement);
if (isReverse) {
focusableNodes.reverse();
} // Consider as candidates those focusables after the current target. It's
// assumed this can only be reached if the target is focusable (on its
// keydown event), so no need to verify it exists in the set.
focusableNodes = focusableNodes.slice(focusableNodes.indexOf(target) + 1);
let targetRect;
if (onlyVertical) {
targetRect = target.getBoundingClientRect();
}
function isTabCandidate(node) {
// Skip if there's only one child that is content editable (and thus a
// better candidate).
if (node.children.length === 1 && isInSameBlock(node, node.firstElementChild) && node.firstElementChild.getAttribute('contenteditable') === 'true') {
return;
} // Not a candidate if the node is not tabbable.
if (!external_wp_dom_namespaceObject.focus.tabbable.isTabbableIndex(node)) {
return false;
} // Skip focusable elements such as links within content editable nodes.
if (node.isContentEditable && node.contentEditable !== 'true') {
return false;
}
if (onlyVertical) {
const nodeRect = node.getBoundingClientRect();
if (nodeRect.left >= targetRect.right || nodeRect.right <= targetRect.left) {
return false;
}
}
return true;
}
return focusableNodes.find(isTabCandidate);
}
function useArrowNav() {
const {
getMultiSelectedBlocksStartClientId,
getMultiSelectedBlocksEndClientId,
getSettings,
hasMultiSelection,
__unstableIsFullySelected
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const {
selectBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
return (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
// Here a DOMRect is stored while moving the caret vertically so
// vertical position of the start position can be restored. This is to
// recreate browser behaviour across blocks.
let verticalRect;
function onMouseDown() {
verticalRect = null;
}
function isClosestTabbableABlock(target, isReverse) {
const closestTabbable = getClosestTabbable(target, isReverse, node);
return closestTabbable && getBlockClientId(closestTabbable);
}
function onKeyDown(event) {
// Abort if navigation has already been handled (e.g. RichText
// inline boundaries).
if (event.defaultPrevented) {
return;
}
const {
keyCode,
target,
shiftKey,
ctrlKey,
altKey,
metaKey
} = event;
const isUp = keyCode === external_wp_keycodes_namespaceObject.UP;
const isDown = keyCode === external_wp_keycodes_namespaceObject.DOWN;
const isLeft = keyCode === external_wp_keycodes_namespaceObject.LEFT;
const isRight = keyCode === external_wp_keycodes_namespaceObject.RIGHT;
const isReverse = isUp || isLeft;
const isHorizontal = isLeft || isRight;
const isVertical = isUp || isDown;
const isNav = isHorizontal || isVertical;
const hasModifier = shiftKey || ctrlKey || altKey || metaKey;
const isNavEdge = isVertical ? external_wp_dom_namespaceObject.isVerticalEdge : external_wp_dom_namespaceObject.isHorizontalEdge;
const {
ownerDocument
} = node;
const {
defaultView
} = ownerDocument;
if (!isNav) {
return;
} // If there is a multi-selection, the arrow keys should collapse the
// selection to the start or end of the selection.
if (hasMultiSelection()) {
if (shiftKey) {
return;
} // Only handle if we have a full selection (not a native partial
// selection).
if (!__unstableIsFullySelected()) {
return;
}
event.preventDefault();
if (isReverse) {
selectBlock(getMultiSelectedBlocksStartClientId());
} else {
selectBlock(getMultiSelectedBlocksEndClientId(), -1);
}
return;
} // Abort if our current target is not a candidate for navigation
// (e.g. preserve native input behaviors).
if (!isNavigationCandidate(target, keyCode, hasModifier)) {
return;
} // When presing any key other than up or down, the initial vertical
// position must ALWAYS be reset. The vertical position is saved so
// it can be restored as well as possible on sebsequent vertical
// arrow key presses. It may not always be possible to restore the
// exact same position (such as at an empty line), so it wouldn't be
// good to compute the position right before any vertical arrow key
// press.
if (!isVertical) {
verticalRect = null;
} else if (!verticalRect) {
verticalRect = (0,external_wp_dom_namespaceObject.computeCaretRect)(defaultView);
} // In the case of RTL scripts, right means previous and left means
// next, which is the exact reverse of LTR.
const isReverseDir = (0,external_wp_dom_namespaceObject.isRTL)(target) ? !isReverse : isReverse;
const {
keepCaretInsideBlock
} = getSettings();
if (shiftKey) {
if (isClosestTabbableABlock(target, isReverse) && isNavEdge(target, isReverse)) {
node.contentEditable = true; // Firefox doesn't automatically move focus.
node.focus();
}
} else if (isVertical && (0,external_wp_dom_namespaceObject.isVerticalEdge)(target, isReverse) && ( // When Alt is pressed, only intercept if the caret is also at
// the horizontal edge.
altKey ? (0,external_wp_dom_namespaceObject.isHorizontalEdge)(target, isReverseDir) : true) && !keepCaretInsideBlock) {
const closestTabbable = getClosestTabbable(target, isReverse, node, true);
if (closestTabbable) {
(0,external_wp_dom_namespaceObject.placeCaretAtVerticalEdge)(closestTabbable, // When Alt is pressed, place the caret at the furthest
// horizontal edge and the furthest vertical edge.
altKey ? !isReverse : isReverse, altKey ? undefined : verticalRect);
event.preventDefault();
}
} else if (isHorizontal && defaultView.getSelection().isCollapsed && (0,external_wp_dom_namespaceObject.isHorizontalEdge)(target, isReverseDir) && !keepCaretInsideBlock) {
const closestTabbable = getClosestTabbable(target, isReverseDir, node);
(0,external_wp_dom_namespaceObject.placeCaretAtHorizontalEdge)(closestTabbable, isReverse);
event.preventDefault();
}
}
node.addEventListener('mousedown', onMouseDown);
node.addEventListener('keydown', onKeyDown);
return () => {
node.removeEventListener('mousedown', onMouseDown);
node.removeEventListener('keydown', onKeyDown);
};
}, []);
}
;// CONCATENATED MODULE: external ["wp","keyboardShortcuts"]
var external_wp_keyboardShortcuts_namespaceObject = window["wp"]["keyboardShortcuts"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/writing-flow/use-select-all.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useSelectAll() {
const {
getBlockOrder,
getSelectedBlockClientIds,
getBlockRootClientId
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const {
multiSelect,
selectBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const isMatch = (0,external_wp_keyboardShortcuts_namespaceObject.__unstableUseShortcutEventMatch)();
return (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
function onKeyDown(event) {
if (!isMatch('core/block-editor/select-all', event)) {
return;
}
const selectedClientIds = getSelectedBlockClientIds();
if (selectedClientIds.length < 2 && !(0,external_wp_dom_namespaceObject.isEntirelySelected)(event.target)) {
return;
}
event.preventDefault();
const [firstSelectedClientId] = selectedClientIds;
const rootClientId = getBlockRootClientId(firstSelectedClientId);
const blockClientIds = getBlockOrder(rootClientId); // If we have selected all sibling nested blocks, try selecting up a
// level. See: https://github.com/WordPress/gutenberg/pull/31859/
if (selectedClientIds.length === blockClientIds.length) {
if (rootClientId) {
node.ownerDocument.defaultView.getSelection().removeAllRanges();
selectBlock(rootClientId);
}
return;
}
multiSelect(blockClientIds[0], blockClientIds[blockClientIds.length - 1]);
}
node.addEventListener('keydown', onKeyDown);
return () => {
node.removeEventListener('keydown', onKeyDown);
};
}, []);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/writing-flow/use-drag-selection.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Sets the `contenteditable` wrapper element to `value`.
*
* @param {HTMLElement} node Block element.
* @param {boolean} value `contentEditable` value (true or false)
*/
function setContentEditableWrapper(node, value) {
node.contentEditable = value; // Firefox doesn't automatically move focus.
if (value) node.focus();
}
/**
* Sets a multi-selection based on the native selection across blocks.
*/
function useDragSelection() {
const {
startMultiSelect,
stopMultiSelect
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const {
isSelectionEnabled,
hasMultiSelection,
isDraggingBlocks
} = (0,external_wp_data_namespaceObject.useSelect)(store);
return (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
const {
ownerDocument
} = node;
const {
defaultView
} = ownerDocument;
let anchorElement;
let rafId;
function onMouseUp() {
stopMultiSelect(); // Equivalent to attaching the listener once.
defaultView.removeEventListener('mouseup', onMouseUp); // The browser selection won't have updated yet at this point,
// so wait until the next animation frame to get the browser
// selection.
rafId = defaultView.requestAnimationFrame(() => {
if (hasMultiSelection()) {
return;
} // If the selection is complete (on mouse up), and no
// multiple blocks have been selected, set focus back to the
// anchor element. if the anchor element contains the
// selection. Additionally, the contentEditable wrapper can
// now be disabled again.
setContentEditableWrapper(node, false);
const selection = defaultView.getSelection();
if (selection.rangeCount) {
const {
commonAncestorContainer
} = selection.getRangeAt(0);
if (anchorElement.contains(commonAncestorContainer)) {
anchorElement.focus();
}
}
});
}
function onMouseLeave(_ref) {
let {
buttons,
target
} = _ref;
// Avoid triggering a multi-selection if the user is already
// dragging blocks.
if (isDraggingBlocks()) {
return;
} // The primary button must be pressed to initiate selection.
// See https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons
if (buttons !== 1) {
return;
} // Check the attribute, not the contentEditable attribute. All
// child elements of the content editable wrapper are editable
// and return true for this property. We only want to start
// multi selecting when the mouse leaves the wrapper.
if (!target.getAttribute('contenteditable')) {
return;
}
if (!isSelectionEnabled()) {
return;
}
anchorElement = ownerDocument.activeElement;
startMultiSelect(); // `onSelectionStart` is called after `mousedown` and
// `mouseleave` (from a block). The selection ends when
// `mouseup` happens anywhere in the window.
defaultView.addEventListener('mouseup', onMouseUp); // Allow cross contentEditable selection by temporarily making
// all content editable. We can't rely on using the store and
// React because re-rending happens too slowly. We need to be
// able to select across instances immediately.
setContentEditableWrapper(node, true);
}
node.addEventListener('mouseout', onMouseLeave);
return () => {
node.removeEventListener('mouseout', onMouseLeave);
defaultView.removeEventListener('mouseup', onMouseUp);
defaultView.cancelAnimationFrame(rafId);
};
}, [startMultiSelect, stopMultiSelect, isSelectionEnabled, hasMultiSelection]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/writing-flow/use-selection-observer.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Extract the selection start node from the selection. When the anchor node is
* not a text node, the selection offset is the index of a child node.
*
* @param {Selection} selection The selection.
*
* @return {Element} The selection start node.
*/
function extractSelectionStartNode(selection) {
const {
anchorNode,
anchorOffset
} = selection;
if (anchorNode.nodeType === anchorNode.TEXT_NODE) {
return anchorNode;
}
if (anchorOffset === 0) {
return anchorNode;
}
return anchorNode.childNodes[anchorOffset - 1];
}
/**
* Extract the selection end node from the selection. When the focus node is not
* a text node, the selection offset is the index of a child node. The selection
* reaches up to but excluding that child node.
*
* @param {Selection} selection The selection.
*
* @return {Element} The selection start node.
*/
function extractSelectionEndNode(selection) {
const {
focusNode,
focusOffset
} = selection;
if (focusNode.nodeType === focusNode.TEXT_NODE) {
return focusNode;
}
if (focusOffset === focusNode.childNodes.length) {
return focusNode;
}
return focusNode.childNodes[focusOffset];
}
function findDepth(a, b) {
let depth = 0;
while (a[depth] === b[depth]) {
depth++;
}
return depth;
}
/**
* Sets the `contenteditable` wrapper element to `value`.
*
* @param {HTMLElement} node Block element.
* @param {boolean} value `contentEditable` value (true or false)
*/
function use_selection_observer_setContentEditableWrapper(node, value) {
node.contentEditable = value; // Firefox doesn't automatically move focus.
if (value) node.focus();
}
/**
* Sets a multi-selection based on the native selection across blocks.
*/
function useSelectionObserver() {
const {
multiSelect,
selectBlock,
selectionChange
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const {
getBlockParents,
getBlockSelectionStart
} = (0,external_wp_data_namespaceObject.useSelect)(store);
return (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
const {
ownerDocument
} = node;
const {
defaultView
} = ownerDocument;
function onSelectionChange(event) {
const selection = defaultView.getSelection();
if (!selection.rangeCount) {
return;
} // If selection is collapsed and we haven't used `shift+click`,
// end multi selection and disable the contentEditable wrapper.
// We have to check about `shift+click` case because elements
// that don't support text selection might be involved, and we might
// update the clientIds to multi-select blocks.
// For now we check if the event is a `mouse` event.
const isClickShift = event.shiftKey && event.type === 'mouseup';
if (selection.isCollapsed && !isClickShift) {
use_selection_observer_setContentEditableWrapper(node, false);
return;
}
let startClientId = getBlockClientId(extractSelectionStartNode(selection));
let endClientId = getBlockClientId(extractSelectionEndNode(selection)); // If the selection has changed and we had pressed `shift+click`,
// we need to check if in an element that doesn't support
// text selection has been clicked.
if (isClickShift) {
const selectedClientId = getBlockSelectionStart();
const clickedClientId = getBlockClientId(event.target); // `endClientId` is not defined if we end the selection by clicking a non-selectable block.
// We need to check if there was already a selection with a non-selectable focusNode.
const focusNodeIsNonSelectable = clickedClientId !== endClientId;
if (startClientId === endClientId && selection.isCollapsed || !endClientId || focusNodeIsNonSelectable) {
endClientId = clickedClientId;
} // Handle the case when we have a non-selectable block
// selected and click another one.
if (startClientId !== selectedClientId) {
startClientId = selectedClientId;
}
} // If the selection did not involve a block, return.
if (startClientId === undefined && endClientId === undefined) {
use_selection_observer_setContentEditableWrapper(node, false);
return;
}
const isSingularSelection = startClientId === endClientId;
if (isSingularSelection) {
selectBlock(startClientId);
} else {
const startPath = [...getBlockParents(startClientId), startClientId];
const endPath = [...getBlockParents(endClientId), endClientId];
const depth = findDepth(startPath, endPath);
multiSelect(startPath[depth], endPath[depth]);
}
}
function addListeners() {
ownerDocument.addEventListener('selectionchange', onSelectionChange);
defaultView.addEventListener('mouseup', onSelectionChange);
}
function removeListeners() {
ownerDocument.removeEventListener('selectionchange', onSelectionChange);
defaultView.removeEventListener('mouseup', onSelectionChange);
}
function resetListeners() {
removeListeners();
addListeners();
}
addListeners(); // We must allow rich text to set selection first. This ensures that
// our `selectionchange` listener is always reset to be called after
// the rich text one.
node.addEventListener('focusin', resetListeners);
return () => {
removeListeners();
node.removeEventListener('focusin', resetListeners);
};
}, [multiSelect, selectBlock, selectionChange, getBlockParents]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/writing-flow/use-click-selection.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useClickSelection() {
const {
selectBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const {
isSelectionEnabled,
getBlockSelectionStart,
hasMultiSelection
} = (0,external_wp_data_namespaceObject.useSelect)(store);
return (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
function onMouseDown(event) {
// The main button.
// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
if (!isSelectionEnabled() || event.button !== 0) {
return;
}
const startClientId = getBlockSelectionStart();
const clickedClientId = getBlockClientId(event.target);
if (event.shiftKey) {
if (startClientId !== clickedClientId) {
node.contentEditable = true; // Firefox doesn't automatically move focus.
node.focus();
}
} else if (hasMultiSelection()) {
// Allow user to escape out of a multi-selection to a
// singular selection of a block via click. This is handled
// here since focus handling excludes blocks when there is
// multiselection, as focus can be incurred by starting a
// multiselection (focus moved to first block's multi-
// controls).
selectBlock(clickedClientId);
}
}
node.addEventListener('mousedown', onMouseDown);
return () => {
node.removeEventListener('mousedown', onMouseDown);
};
}, [selectBlock, isSelectionEnabled, getBlockSelectionStart, hasMultiSelection]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/writing-flow/use-input.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Handles input for selections across blocks.
*/
function useInput() {
const {
__unstableIsFullySelected,
getSelectedBlockClientIds,
__unstableIsSelectionMergeable,
hasMultiSelection
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const {
replaceBlocks,
__unstableSplitSelection,
removeBlocks,
__unstableDeleteSelection,
__unstableExpandSelection
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
return (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
function onBeforeInput(event) {
var _event$inputType;
if (!hasMultiSelection()) {
return;
} // Prevent the browser to format something when we have multiselection.
if ((_event$inputType = event.inputType) !== null && _event$inputType !== void 0 && _event$inputType.startsWith('format')) {
event.preventDefault();
}
}
function onKeyDown(event) {
if (event.defaultPrevented) {
return;
}
if (!hasMultiSelection()) {
return;
}
if (event.keyCode === external_wp_keycodes_namespaceObject.ENTER) {
node.contentEditable = false;
event.preventDefault();
if (__unstableIsFullySelected()) {
replaceBlocks(getSelectedBlockClientIds(), (0,external_wp_blocks_namespaceObject.createBlock)((0,external_wp_blocks_namespaceObject.getDefaultBlockName)()));
} else {
__unstableSplitSelection();
}
} else if (event.keyCode === external_wp_keycodes_namespaceObject.BACKSPACE || event.keyCode === external_wp_keycodes_namespaceObject.DELETE) {
node.contentEditable = false;
event.preventDefault();
if (__unstableIsFullySelected()) {
removeBlocks(getSelectedBlockClientIds());
} else if (__unstableIsSelectionMergeable()) {
__unstableDeleteSelection(event.keyCode === external_wp_keycodes_namespaceObject.DELETE);
} else {
__unstableExpandSelection();
}
} else if ( // If key.length is longer than 1, it's a control key that doesn't
// input anything.
event.key.length === 1 && !(event.metaKey || event.ctrlKey)) {
node.contentEditable = false;
if (__unstableIsSelectionMergeable()) {
__unstableDeleteSelection(event.keyCode === external_wp_keycodes_namespaceObject.DELETE);
} else {
event.preventDefault(); // Safari does not stop default behaviour with either
// event.preventDefault() or node.contentEditable = false, so
// remove the selection to stop browser manipulation.
node.ownerDocument.defaultView.getSelection().removeAllRanges();
}
}
}
function onCompositionStart(event) {
if (!hasMultiSelection()) {
return;
}
node.contentEditable = false;
if (__unstableIsSelectionMergeable()) {
__unstableDeleteSelection();
} else {
event.preventDefault(); // Safari does not stop default behaviour with either
// event.preventDefault() or node.contentEditable = false, so
// remove the selection to stop browser manipulation.
node.ownerDocument.defaultView.getSelection().removeAllRanges();
}
}
node.addEventListener('beforeinput', onBeforeInput);
node.addEventListener('keydown', onKeyDown);
node.addEventListener('compositionstart', onCompositionStart);
return () => {
node.removeEventListener('beforeinput', onBeforeInput);
node.removeEventListener('keydown', onKeyDown);
node.removeEventListener('compositionstart', onCompositionStart);
};
}, []);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/writing-flow/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useWritingFlow() {
const [before, ref, after] = useTabNav();
const hasMultiSelection = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).hasMultiSelection(), []);
return [before, (0,external_wp_compose_namespaceObject.useMergeRefs)([ref, useInput(), useDragSelection(), useSelectionObserver(), useClickSelection(), useMultiSelection(), useSelectAll(), useArrowNav(), (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
node.tabIndex = 0;
node.contentEditable = hasMultiSelection;
if (!hasMultiSelection) {
return;
}
node.classList.add('has-multi-selection');
node.setAttribute('aria-label', (0,external_wp_i18n_namespaceObject.__)('Multiple selected blocks'));
return () => {
node.classList.remove('has-multi-selection');
node.removeAttribute('aria-label');
};
}, [hasMultiSelection])]), after];
}
function WritingFlow(_ref, forwardedRef) {
let {
children,
...props
} = _ref;
const [before, ref, after] = useWritingFlow();
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, before, (0,external_wp_element_namespaceObject.createElement)("div", _extends({}, props, {
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([ref, forwardedRef]),
className: classnames_default()(props.className, 'block-editor-writing-flow')
}), children), after);
}
/**
* Handles selection and navigation across blocks. This component should be
* wrapped around BlockList.
*
* @param {Object} props Component properties.
* @param {WPElement} props.children Children to be rendered.
*/
/* harmony default export */ var writing_flow = ((0,external_wp_element_namespaceObject.forwardRef)(WritingFlow));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/iframe/use-compatibility-styles.js
/**
* WordPress dependencies
*/
/**
* Returns a list of stylesheets that target the editor canvas. A stylesheet is
* considered targetting the editor a canvas if it contains the
* `editor-styles-wrapper`, `wp-block`, or `wp-block-*` class selectors.
*
* Ideally, this hook should be removed in the future and styles should be added
* explicitly as editor styles.
*/
function useCompatibilityStyles() {
// Only memoize the result once on load, since these stylesheets should not
// change.
return (0,external_wp_element_namespaceObject.useMemo)(() => {
// Search the document for stylesheets targetting the editor canvas.
return Array.from(document.styleSheets).reduce((accumulator, styleSheet) => {
try {
// May fail for external styles.
// eslint-disable-next-line no-unused-expressions
styleSheet.cssRules;
} catch (e) {
return accumulator;
}
const {
ownerNode,
cssRules
} = styleSheet; // Stylesheet is added by another stylesheet. See
// https://developer.mozilla.org/en-US/docs/Web/API/StyleSheet/ownerNode#notes.
if (ownerNode === null) {
return accumulator;
}
if (!cssRules) {
return accumulator;
} // Generally, ignore inline styles. We add inline styles belonging to a
// stylesheet later, which may or may not match the selectors.
if (ownerNode.tagName !== 'LINK') {
return accumulator;
} // Don't try to add the reset styles, which were removed as a dependency
// from `edit-blocks` for the iframe since we don't need to reset admin
// styles.
if (ownerNode.id === 'wp-reset-editor-styles-css') {
return accumulator;
}
function matchFromRules(_cssRules) {
return Array.from(_cssRules).find(_ref => {
let {
selectorText,
conditionText,
cssRules: __cssRules
} = _ref;
// If the rule is conditional then it will not have selector text.
// Recurse into child CSS ruleset to determine selector eligibility.
if (conditionText) {
return matchFromRules(__cssRules);
}
return selectorText && (selectorText.includes('.editor-styles-wrapper') || selectorText.includes('.wp-block'));
});
}
if (matchFromRules(cssRules)) {
// Display warning once we have a way to add style dependencies to the editor.
// See: https://github.com/WordPress/gutenberg/pull/37466.
accumulator.push(ownerNode.cloneNode(true)); // Add inline styles belonging to the stylesheet.
const inlineCssId = ownerNode.id.replace('-css', '-inline-css');
const inlineCssElement = document.getElementById(inlineCssId);
if (inlineCssElement) {
accumulator.push(inlineCssElement.cloneNode(true));
}
}
return accumulator;
}, []);
}, []);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/iframe/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Bubbles some event types (keydown, keypress, and dragover) to parent document
* document to ensure that the keyboard shortcuts and drag and drop work.
*
* Ideally, we should remove event bubbling in the future. Keyboard shortcuts
* should be context dependent, e.g. actions on blocks like Cmd+A should not
* work globally outside the block editor.
*
* @param {Document} doc Document to attach listeners to.
*/
function bubbleEvents(doc) {
const {
defaultView
} = doc;
const {
frameElement
} = defaultView;
function bubbleEvent(event) {
const prototype = Object.getPrototypeOf(event);
const constructorName = prototype.constructor.name;
const Constructor = window[constructorName];
const init = {};
for (const key in event) {
init[key] = event[key];
}
if (event instanceof defaultView.MouseEvent) {
const rect = frameElement.getBoundingClientRect();
init.clientX += rect.left;
init.clientY += rect.top;
}
const newEvent = new Constructor(event.type, init);
const cancelled = !frameElement.dispatchEvent(newEvent);
if (cancelled) {
event.preventDefault();
}
}
const eventTypes = ['dragover'];
for (const name of eventTypes) {
doc.addEventListener(name, bubbleEvent);
}
}
function useParsedAssets(html) {
return (0,external_wp_element_namespaceObject.useMemo)(() => {
const doc = document.implementation.createHTMLDocument('');
doc.body.innerHTML = html;
return Array.from(doc.body.children);
}, [html]);
}
async function loadScript(head, _ref) {
let {
id,
src
} = _ref;
return new Promise((resolve, reject) => {
const script = head.ownerDocument.createElement('script');
script.id = id;
if (src) {
script.src = src;
script.onload = () => resolve();
script.onerror = () => reject();
} else {
resolve();
}
head.appendChild(script);
});
}
function Iframe(_ref2) {
let {
contentRef,
children,
head,
tabIndex = 0,
scale = 1,
frameSize = 0,
readonly,
forwardedRef: ref,
...props
} = _ref2;
const assets = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).getSettings().__unstableResolvedAssets, []);
const [, forceRender] = (0,external_wp_element_namespaceObject.useReducer)(() => ({}));
const [iframeDocument, setIframeDocument] = (0,external_wp_element_namespaceObject.useState)();
const [bodyClasses, setBodyClasses] = (0,external_wp_element_namespaceObject.useState)([]);
const styles = useParsedAssets(assets === null || assets === void 0 ? void 0 : assets.styles);
const styleIds = styles.map(style => style.id);
const compatStyles = useCompatibilityStyles();
const neededCompatStyles = compatStyles.filter(style => !styleIds.includes(style.id));
const scripts = useParsedAssets(assets === null || assets === void 0 ? void 0 : assets.scripts);
const clearerRef = useBlockSelectionClearer();
const [before, writingFlowRef, after] = useWritingFlow();
const [contentResizeListener, {
height: contentHeight
}] = (0,external_wp_compose_namespaceObject.useResizeObserver)();
const setRef = (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
let iFrameDocument; // Prevent the default browser action for files dropped outside of dropzones.
function preventFileDropDefault(event) {
event.preventDefault();
}
function setDocumentIfReady() {
const {
contentDocument,
ownerDocument
} = node;
const {
readyState,
documentElement
} = contentDocument;
iFrameDocument = contentDocument;
if (readyState !== 'interactive' && readyState !== 'complete') {
return false;
}
bubbleEvents(contentDocument);
setIframeDocument(contentDocument);
clearerRef(documentElement); // Ideally ALL classes that are added through get_body_class should
// be added in the editor too, which we'll somehow have to get from
// the server in the future (which will run the PHP filters).
setBodyClasses(Array.from(ownerDocument.body.classList).filter(name => name.startsWith('admin-color-') || name.startsWith('post-type-') || name === 'wp-embed-responsive'));
contentDocument.dir = ownerDocument.dir;
documentElement.removeChild(contentDocument.head);
documentElement.removeChild(contentDocument.body);
iFrameDocument.addEventListener('dragover', preventFileDropDefault, false);
iFrameDocument.addEventListener('drop', preventFileDropDefault, false);
return true;
} // Document set with srcDoc is not immediately ready.
node.addEventListener('load', setDocumentIfReady);
return () => {
var _iFrameDocument, _iFrameDocument2;
node.removeEventListener('load', setDocumentIfReady);
(_iFrameDocument = iFrameDocument) === null || _iFrameDocument === void 0 ? void 0 : _iFrameDocument.removeEventListener('dragover', preventFileDropDefault);
(_iFrameDocument2 = iFrameDocument) === null || _iFrameDocument2 === void 0 ? void 0 : _iFrameDocument2.removeEventListener('drop', preventFileDropDefault);
};
}, []);
const headRef = (0,external_wp_compose_namespaceObject.useRefEffect)(element => {
scripts.reduce((promise, script) => promise.then(() => loadScript(element, script)), Promise.resolve()).finally(() => {
// When script are loaded, re-render blocks to allow them
// to initialise.
forceRender();
});
}, []);
const disabledRef = (0,external_wp_compose_namespaceObject.useDisabled)({
isDisabled: !readonly
});
const bodyRef = (0,external_wp_compose_namespaceObject.useMergeRefs)([contentRef, clearerRef, writingFlowRef, disabledRef]);
const styleAssets = (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("style", null, 'html{height:auto!important;}body{margin:0}'), [...styles, ...neededCompatStyles].map(_ref3 => {
let {
tagName,
href,
id,
rel,
media,
textContent
} = _ref3;
const TagName = tagName.toLowerCase();
if (TagName === 'style') {
return (0,external_wp_element_namespaceObject.createElement)(TagName, {
id,
key: id
}, textContent);
}
return (0,external_wp_element_namespaceObject.createElement)(TagName, {
href,
id,
rel,
media,
key: id
});
})); // Correct doctype is required to enable rendering in standards
// mode. Also preload the styles to avoid a flash of unstyled
// content.
const srcDoc = (0,external_wp_element_namespaceObject.useMemo)(() => {
return '<!doctype html>' + (0,external_wp_element_namespaceObject.renderToString)(styleAssets);
}, []);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, tabIndex >= 0 && before, (0,external_wp_element_namespaceObject.createElement)("iframe", _extends({}, props, {
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([ref, setRef]),
tabIndex: tabIndex // Correct doctype is required to enable rendering in standards
// mode. Also preload the styles to avoid a flash of unstyled
// content.
,
srcDoc: srcDoc,
title: (0,external_wp_i18n_namespaceObject.__)('Editor canvas')
}), iframeDocument && (0,external_wp_element_namespaceObject.createPortal)((0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("head", {
ref: headRef
}, styleAssets, head, (0,external_wp_element_namespaceObject.createElement)("style", null, `html { transition: background 5s; ${frameSize ? 'background: #2f2f2f; transition: background 0s;' : ''} }`)), (0,external_wp_element_namespaceObject.createElement)("body", {
ref: bodyRef,
className: classnames_default()('block-editor-iframe__body', 'editor-styles-wrapper', ...bodyClasses),
style: {
// This is the remaining percentage from the scaling down
// of the iframe body(`scale(0.45)`). We also need to subtract
// the body's bottom margin.
marginBottom: `-${contentHeight * (1 - scale) - frameSize}px`,
marginTop: frameSize,
transform: `scale( ${scale} )`
}
}, contentResizeListener, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalStyleProvider, {
document: iframeDocument
}, children))), iframeDocument.documentElement)), tabIndex >= 0 && after);
}
function IframeIfReady(props, ref) {
const isInitialised = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).getSettings().__internalIsInitialized, []); // We shouldn't render the iframe until the editor settings are initialised.
// The initial settings are needed to get the styles for the srcDoc, which
// cannot be changed after the iframe is mounted. srcDoc is used to to set
// the initial iframe HTML, which is required to avoid a flash of unstyled
// content.
if (!isInitialised) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(Iframe, _extends({}, props, {
forwardedRef: ref
}));
}
/* harmony default export */ var iframe = ((0,external_wp_element_namespaceObject.forwardRef)(IframeIfReady));
;// CONCATENATED MODULE: ./node_modules/colord/index.mjs
var r={grad:.9,turn:360,rad:360/(2*Math.PI)},t=function(r){return"string"==typeof r?r.length>0:"number"==typeof r},n=function(r,t,n){return void 0===t&&(t=0),void 0===n&&(n=Math.pow(10,t)),Math.round(n*r)/n+0},e=function(r,t,n){return void 0===t&&(t=0),void 0===n&&(n=1),r>n?n:r>t?r:t},u=function(r){return(r=isFinite(r)?r%360:0)>0?r:r+360},a=function(r){return{r:e(r.r,0,255),g:e(r.g,0,255),b:e(r.b,0,255),a:e(r.a)}},o=function(r){return{r:n(r.r),g:n(r.g),b:n(r.b),a:n(r.a,3)}},i=/^#([0-9a-f]{3,8})$/i,s=function(r){var t=r.toString(16);return t.length<2?"0"+t:t},h=function(r){var t=r.r,n=r.g,e=r.b,u=r.a,a=Math.max(t,n,e),o=a-Math.min(t,n,e),i=o?a===t?(n-e)/o:a===n?2+(e-t)/o:4+(t-n)/o:0;return{h:60*(i<0?i+6:i),s:a?o/a*100:0,v:a/255*100,a:u}},b=function(r){var t=r.h,n=r.s,e=r.v,u=r.a;t=t/360*6,n/=100,e/=100;var a=Math.floor(t),o=e*(1-n),i=e*(1-(t-a)*n),s=e*(1-(1-t+a)*n),h=a%6;return{r:255*[e,i,o,o,s,e][h],g:255*[s,e,e,i,o,o][h],b:255*[o,o,s,e,e,i][h],a:u}},g=function(r){return{h:u(r.h),s:e(r.s,0,100),l:e(r.l,0,100),a:e(r.a)}},d=function(r){return{h:n(r.h),s:n(r.s),l:n(r.l),a:n(r.a,3)}},f=function(r){return b((n=(t=r).s,{h:t.h,s:(n*=((e=t.l)<50?e:100-e)/100)>0?2*n/(e+n)*100:0,v:e+n,a:t.a}));var t,n,e},c=function(r){return{h:(t=h(r)).h,s:(u=(200-(n=t.s))*(e=t.v)/100)>0&&u<200?n*e/100/(u<=100?u:200-u)*100:0,l:u/2,a:t.a};var t,n,e,u},l=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,p=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,v=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,m=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,y={string:[[function(r){var t=i.exec(r);return t?(r=t[1]).length<=4?{r:parseInt(r[0]+r[0],16),g:parseInt(r[1]+r[1],16),b:parseInt(r[2]+r[2],16),a:4===r.length?n(parseInt(r[3]+r[3],16)/255,2):1}:6===r.length||8===r.length?{r:parseInt(r.substr(0,2),16),g:parseInt(r.substr(2,2),16),b:parseInt(r.substr(4,2),16),a:8===r.length?n(parseInt(r.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(r){var t=v.exec(r)||m.exec(r);return t?t[2]!==t[4]||t[4]!==t[6]?null:a({r:Number(t[1])/(t[2]?100/255:1),g:Number(t[3])/(t[4]?100/255:1),b:Number(t[5])/(t[6]?100/255:1),a:void 0===t[7]?1:Number(t[7])/(t[8]?100:1)}):null},"rgb"],[function(t){var n=l.exec(t)||p.exec(t);if(!n)return null;var e,u,a=g({h:(e=n[1],u=n[2],void 0===u&&(u="deg"),Number(e)*(r[u]||1)),s:Number(n[3]),l:Number(n[4]),a:void 0===n[5]?1:Number(n[5])/(n[6]?100:1)});return f(a)},"hsl"]],object:[[function(r){var n=r.r,e=r.g,u=r.b,o=r.a,i=void 0===o?1:o;return t(n)&&t(e)&&t(u)?a({r:Number(n),g:Number(e),b:Number(u),a:Number(i)}):null},"rgb"],[function(r){var n=r.h,e=r.s,u=r.l,a=r.a,o=void 0===a?1:a;if(!t(n)||!t(e)||!t(u))return null;var i=g({h:Number(n),s:Number(e),l:Number(u),a:Number(o)});return f(i)},"hsl"],[function(r){var n=r.h,a=r.s,o=r.v,i=r.a,s=void 0===i?1:i;if(!t(n)||!t(a)||!t(o))return null;var h=function(r){return{h:u(r.h),s:e(r.s,0,100),v:e(r.v,0,100),a:e(r.a)}}({h:Number(n),s:Number(a),v:Number(o),a:Number(s)});return b(h)},"hsv"]]},N=function(r,t){for(var n=0;n<t.length;n++){var e=t[n][0](r);if(e)return[e,t[n][1]]}return[null,void 0]},x=function(r){return"string"==typeof r?N(r.trim(),y.string):"object"==typeof r&&null!==r?N(r,y.object):[null,void 0]},I=function(r){return x(r)[1]},M=function(r,t){var n=c(r);return{h:n.h,s:e(n.s+100*t,0,100),l:n.l,a:n.a}},H=function(r){return(299*r.r+587*r.g+114*r.b)/1e3/255},$=function(r,t){var n=c(r);return{h:n.h,s:n.s,l:e(n.l+100*t,0,100),a:n.a}},j=function(){function r(r){this.parsed=x(r)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return r.prototype.isValid=function(){return null!==this.parsed},r.prototype.brightness=function(){return n(H(this.rgba),2)},r.prototype.isDark=function(){return H(this.rgba)<.5},r.prototype.isLight=function(){return H(this.rgba)>=.5},r.prototype.toHex=function(){return r=o(this.rgba),t=r.r,e=r.g,u=r.b,i=(a=r.a)<1?s(n(255*a)):"","#"+s(t)+s(e)+s(u)+i;var r,t,e,u,a,i},r.prototype.toRgb=function(){return o(this.rgba)},r.prototype.toRgbString=function(){return r=o(this.rgba),t=r.r,n=r.g,e=r.b,(u=r.a)<1?"rgba("+t+", "+n+", "+e+", "+u+")":"rgb("+t+", "+n+", "+e+")";var r,t,n,e,u},r.prototype.toHsl=function(){return d(c(this.rgba))},r.prototype.toHslString=function(){return r=d(c(this.rgba)),t=r.h,n=r.s,e=r.l,(u=r.a)<1?"hsla("+t+", "+n+"%, "+e+"%, "+u+")":"hsl("+t+", "+n+"%, "+e+"%)";var r,t,n,e,u},r.prototype.toHsv=function(){return r=h(this.rgba),{h:n(r.h),s:n(r.s),v:n(r.v),a:n(r.a,3)};var r},r.prototype.invert=function(){return w({r:255-(r=this.rgba).r,g:255-r.g,b:255-r.b,a:r.a});var r},r.prototype.saturate=function(r){return void 0===r&&(r=.1),w(M(this.rgba,r))},r.prototype.desaturate=function(r){return void 0===r&&(r=.1),w(M(this.rgba,-r))},r.prototype.grayscale=function(){return w(M(this.rgba,-1))},r.prototype.lighten=function(r){return void 0===r&&(r=.1),w($(this.rgba,r))},r.prototype.darken=function(r){return void 0===r&&(r=.1),w($(this.rgba,-r))},r.prototype.rotate=function(r){return void 0===r&&(r=15),this.hue(this.hue()+r)},r.prototype.alpha=function(r){return"number"==typeof r?w({r:(t=this.rgba).r,g:t.g,b:t.b,a:r}):n(this.rgba.a,3);var t},r.prototype.hue=function(r){var t=c(this.rgba);return"number"==typeof r?w({h:r,s:t.s,l:t.l,a:t.a}):n(t.h)},r.prototype.isEqual=function(r){return this.toHex()===w(r).toHex()},r}(),w=function(r){return r instanceof j?r:new j(r)},S=[],k=function(r){r.forEach(function(r){S.indexOf(r)<0&&(r(j,y),S.push(r))})},E=function(){return new j({r:255*Math.random(),g:255*Math.random(),b:255*Math.random()})};
;// CONCATENATED MODULE: ./node_modules/colord/plugins/names.mjs
/* harmony default export */ function names(e,f){var a={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},r={};for(var d in a)r[a[d]]=d;var l={};e.prototype.toName=function(f){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var d,i,n=r[this.toHex()];if(n)return n;if(null==f?void 0:f.closest){var o=this.toRgb(),t=1/0,b="black";if(!l.length)for(var c in a)l[c]=new e(a[c]).toRgb();for(var g in a){var u=(d=o,i=l[g],Math.pow(d.r-i.r,2)+Math.pow(d.g-i.g,2)+Math.pow(d.b-i.b,2));u<t&&(t=u,b=g)}return b}};f.string.push([function(f){var r=f.toLowerCase(),d="transparent"===r?"#0000":a[r];return d?new e(d).toRgb():null},"name"])}
;// CONCATENATED MODULE: ./node_modules/colord/plugins/a11y.mjs
var a11y_o=function(o){var t=o/255;return t<.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)},a11y_t=function(t){return.2126*a11y_o(t.r)+.7152*a11y_o(t.g)+.0722*a11y_o(t.b)};/* harmony default export */ function a11y(o){o.prototype.luminance=function(){return o=a11y_t(this.rgba),void 0===(r=2)&&(r=0),void 0===n&&(n=Math.pow(10,r)),Math.round(n*o)/n+0;var o,r,n},o.prototype.contrast=function(r){void 0===r&&(r="#FFF");var n,a,i,e,v,u,d,c=r instanceof o?r:new o(r);return e=this.rgba,v=c.toRgb(),u=a11y_t(e),d=a11y_t(v),n=u>d?(u+.05)/(d+.05):(d+.05)/(u+.05),void 0===(a=2)&&(a=0),void 0===i&&(i=Math.pow(10,a)),Math.floor(i*n)/i+0},o.prototype.isReadable=function(o,t){return void 0===o&&(o="#FFF"),void 0===t&&(t={}),this.contrast(o)>=(e=void 0===(i=(r=t).size)?"normal":i,"AAA"===(a=void 0===(n=r.level)?"AA":n)&&"normal"===e?7:"AA"===a&&"large"===e?3:4.5);var r,n,a,i,e}}
// EXTERNAL MODULE: ./node_modules/traverse/index.js
var traverse = __webpack_require__(3124);
var traverse_default = /*#__PURE__*/__webpack_require__.n(traverse);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/utils/transform-styles/ast/parse.js
/* eslint-disable @wordpress/no-unused-vars-before-return */
// Adapted from https://github.com/reworkcss/css
// because we needed to remove source map support.
// http://www.w3.org/TR/CSS21/grammar.htm
// https://github.com/visionmedia/css-parse/pull/49#issuecomment-30088027
const commentre = /\/\*[^*]*\*+([^/*][^*]*\*+)*\//g;
/* harmony default export */ function parse(css, options) {
options = options || {};
/**
* Positional.
*/
let lineno = 1;
let column = 1;
/**
* Update lineno and column based on `str`.
*/
function updatePosition(str) {
const lines = str.match(/\n/g);
if (lines) {
lineno += lines.length;
}
const i = str.lastIndexOf('\n'); // eslint-disable-next-line no-bitwise
column = ~i ? str.length - i : column + str.length;
}
/**
* Mark position and patch `node.position`.
*/
function position() {
const start = {
line: lineno,
column
};
return function (node) {
node.position = new Position(start);
whitespace();
return node;
};
}
/**
* Store position information for a node
*/
function Position(start) {
this.start = start;
this.end = {
line: lineno,
column
};
this.source = options.source;
}
/**
* Non-enumerable source string
*/
Position.prototype.content = css;
/**
* Error `msg`.
*/
const errorsList = [];
function error(msg) {
const err = new Error(options.source + ':' + lineno + ':' + column + ': ' + msg);
err.reason = msg;
err.filename = options.source;
err.line = lineno;
err.column = column;
err.source = css;
if (options.silent) {
errorsList.push(err);
} else {
throw err;
}
}
/**
* Parse stylesheet.
*/
function stylesheet() {
const rulesList = rules();
return {
type: 'stylesheet',
stylesheet: {
source: options.source,
rules: rulesList,
parsingErrors: errorsList
}
};
}
/**
* Opening brace.
*/
function open() {
return match(/^{\s*/);
}
/**
* Closing brace.
*/
function close() {
return match(/^}/);
}
/**
* Parse ruleset.
*/
function rules() {
let node;
const accumulator = [];
whitespace();
comments(accumulator);
while (css.length && css.charAt(0) !== '}' && (node = atrule() || rule())) {
if (node !== false) {
accumulator.push(node);
comments(accumulator);
}
}
return accumulator;
}
/**
* Match `re` and return captures.
*/
function match(re) {
const m = re.exec(css);
if (!m) {
return;
}
const str = m[0];
updatePosition(str);
css = css.slice(str.length);
return m;
}
/**
* Parse whitespace.
*/
function whitespace() {
match(/^\s*/);
}
/**
* Parse comments;
*/
function comments(accumulator) {
let c;
accumulator = accumulator || []; // eslint-disable-next-line no-cond-assign
while (c = comment()) {
if (c !== false) {
accumulator.push(c);
}
}
return accumulator;
}
/**
* Parse comment.
*/
function comment() {
const pos = position();
if ('/' !== css.charAt(0) || '*' !== css.charAt(1)) {
return;
}
let i = 2;
while ('' !== css.charAt(i) && ('*' !== css.charAt(i) || '/' !== css.charAt(i + 1))) {
++i;
}
i += 2;
if ('' === css.charAt(i - 1)) {
return error('End of comment missing');
}
const str = css.slice(2, i - 2);
column += 2;
updatePosition(str);
css = css.slice(i);
column += 2;
return pos({
type: 'comment',
comment: str
});
}
/**
* Parse selector.
*/
function selector() {
const m = match(/^([^{]+)/);
if (!m) {
return;
} // FIXME: Remove all comments from selectors http://ostermiller.org/findcomment.html
return trim(m[0]).replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/g, '').replace(/"(?:\\"|[^"])*"|'(?:\\'|[^'])*'/g, function (matched) {
return matched.replace(/,/g, '\u200C');
}).split(/\s*(?![^(]*\)),\s*/).map(function (s) {
return s.replace(/\u200C/g, ',');
});
}
/**
* Parse declaration.
*/
function declaration() {
const pos = position(); // prop.
let prop = match(/^(\*?[-#\/\*\\\w]+(\[[0-9a-z_-]+\])?)\s*/);
if (!prop) {
return;
}
prop = trim(prop[0]); // :
if (!match(/^:\s*/)) {
return error("property missing ':'");
} // val.
const val = match(/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^\)]*?\)|[^};])+)/);
const ret = pos({
type: 'declaration',
property: prop.replace(commentre, ''),
value: val ? trim(val[0]).replace(commentre, '') : ''
}); // ;
match(/^[;\s]*/);
return ret;
}
/**
* Parse declarations.
*/
function declarations() {
const decls = [];
if (!open()) {
return error("missing '{'");
}
comments(decls); // declarations.
let decl; // eslint-disable-next-line no-cond-assign
while (decl = declaration()) {
if (decl !== false) {
decls.push(decl);
comments(decls);
}
}
if (!close()) {
return error("missing '}'");
}
return decls;
}
/**
* Parse keyframe.
*/
function keyframe() {
let m;
const vals = [];
const pos = position(); // eslint-disable-next-line no-cond-assign
while (m = match(/^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/)) {
vals.push(m[1]);
match(/^,\s*/);
}
if (!vals.length) {
return;
}
return pos({
type: 'keyframe',
values: vals,
declarations: declarations()
});
}
/**
* Parse keyframes.
*/
function atkeyframes() {
const pos = position();
let m = match(/^@([-\w]+)?keyframes\s*/);
if (!m) {
return;
}
const vendor = m[1]; // identifier
m = match(/^([-\w]+)\s*/);
if (!m) {
return error('@keyframes missing name');
}
const name = m[1];
if (!open()) {
return error("@keyframes missing '{'");
}
let frame;
let frames = comments(); // eslint-disable-next-line no-cond-assign
while (frame = keyframe()) {
frames.push(frame);
frames = frames.concat(comments());
}
if (!close()) {
return error("@keyframes missing '}'");
}
return pos({
type: 'keyframes',
name,
vendor,
keyframes: frames
});
}
/**
* Parse supports.
*/
function atsupports() {
const pos = position();
const m = match(/^@supports *([^{]+)/);
if (!m) {
return;
}
const supports = trim(m[1]);
if (!open()) {
return error("@supports missing '{'");
}
const style = comments().concat(rules());
if (!close()) {
return error("@supports missing '}'");
}
return pos({
type: 'supports',
supports,
rules: style
});
}
/**
* Parse host.
*/
function athost() {
const pos = position();
const m = match(/^@host\s*/);
if (!m) {
return;
}
if (!open()) {
return error("@host missing '{'");
}
const style = comments().concat(rules());
if (!close()) {
return error("@host missing '}'");
}
return pos({
type: 'host',
rules: style
});
}
/**
* Parse media.
*/
function atmedia() {
const pos = position();
const m = match(/^@media *([^{]+)/);
if (!m) {
return;
}
const media = trim(m[1]);
if (!open()) {
return error("@media missing '{'");
}
const style = comments().concat(rules());
if (!close()) {
return error("@media missing '}'");
}
return pos({
type: 'media',
media,
rules: style
});
}
/**
* Parse custom-media.
*/
function atcustommedia() {
const pos = position();
const m = match(/^@custom-media\s+(--[^\s]+)\s*([^{;]+);/);
if (!m) {
return;
}
return pos({
type: 'custom-media',
name: trim(m[1]),
media: trim(m[2])
});
}
/**
* Parse paged media.
*/
function atpage() {
const pos = position();
const m = match(/^@page */);
if (!m) {
return;
}
const sel = selector() || [];
if (!open()) {
return error("@page missing '{'");
}
let decls = comments(); // declarations.
let decl; // eslint-disable-next-line no-cond-assign
while (decl = declaration()) {
decls.push(decl);
decls = decls.concat(comments());
}
if (!close()) {
return error("@page missing '}'");
}
return pos({
type: 'page',
selectors: sel,
declarations: decls
});
}
/**
* Parse document.
*/
function atdocument() {
const pos = position();
const m = match(/^@([-\w]+)?document *([^{]+)/);
if (!m) {
return;
}
const vendor = trim(m[1]);
const doc = trim(m[2]);
if (!open()) {
return error("@document missing '{'");
}
const style = comments().concat(rules());
if (!close()) {
return error("@document missing '}'");
}
return pos({
type: 'document',
document: doc,
vendor,
rules: style
});
}
/**
* Parse font-face.
*/
function atfontface() {
const pos = position();
const m = match(/^@font-face\s*/);
if (!m) {
return;
}
if (!open()) {
return error("@font-face missing '{'");
}
let decls = comments(); // declarations.
let decl; // eslint-disable-next-line no-cond-assign
while (decl = declaration()) {
decls.push(decl);
decls = decls.concat(comments());
}
if (!close()) {
return error("@font-face missing '}'");
}
return pos({
type: 'font-face',
declarations: decls
});
}
/**
* Parse import
*/
const atimport = _compileAtrule('import');
/**
* Parse charset
*/
const atcharset = _compileAtrule('charset');
/**
* Parse namespace
*/
const atnamespace = _compileAtrule('namespace');
/**
* Parse non-block at-rules
*/
function _compileAtrule(name) {
const re = new RegExp('^@' + name + '\\s*([^;]+);');
return function () {
const pos = position();
const m = match(re);
if (!m) {
return;
}
const ret = {
type: name
};
ret[name] = m[1].trim();
return pos(ret);
};
}
/**
* Parse at rule.
*/
function atrule() {
if (css[0] !== '@') {
return;
}
return atkeyframes() || atmedia() || atcustommedia() || atsupports() || atimport() || atcharset() || atnamespace() || atdocument() || atpage() || athost() || atfontface();
}
/**
* Parse rule.
*/
function rule() {
const pos = position();
const sel = selector();
if (!sel) {
return error('selector missing');
}
comments();
return pos({
type: 'rule',
selectors: sel,
declarations: declarations()
});
}
return addParent(stylesheet());
}
/**
* Trim `str`.
*/
function trim(str) {
return str ? str.replace(/^\s+|\s+$/g, '') : '';
}
/**
* Adds non-enumerable parent node reference to each node.
*/
function addParent(obj, parent) {
const isNode = obj && typeof obj.type === 'string';
const childParent = isNode ? obj : parent;
for (const k in obj) {
const value = obj[k];
if (Array.isArray(value)) {
value.forEach(function (v) {
addParent(v, childParent);
});
} else if (value && typeof value === 'object') {
addParent(value, childParent);
}
}
if (isNode) {
Object.defineProperty(obj, 'parent', {
configurable: true,
writable: true,
enumerable: false,
value: parent || null
});
}
return obj;
}
/* eslint-enable @wordpress/no-unused-vars-before-return */
// EXTERNAL MODULE: ./node_modules/inherits/inherits_browser.js
var inherits_browser = __webpack_require__(8575);
var inherits_browser_default = /*#__PURE__*/__webpack_require__.n(inherits_browser);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/utils/transform-styles/ast/stringify/compiler.js
// Adapted from https://github.com/reworkcss/css
// because we needed to remove source map support.
/**
* Expose `Compiler`.
*/
/* harmony default export */ var compiler = (Compiler);
/**
* Initialize a compiler.
*/
function Compiler(opts) {
this.options = opts || {};
}
/**
* Emit `str`
*/
Compiler.prototype.emit = function (str) {
return str;
};
/**
* Visit `node`.
*/
Compiler.prototype.visit = function (node) {
return this[node.type](node);
};
/**
* Map visit over array of `nodes`, optionally using a `delim`
*/
Compiler.prototype.mapVisit = function (nodes, delim) {
let buf = '';
delim = delim || '';
for (let i = 0, length = nodes.length; i < length; i++) {
buf += this.visit(nodes[i]);
if (delim && i < length - 1) {
buf += this.emit(delim);
}
}
return buf;
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/utils/transform-styles/ast/stringify/compress.js
// Adapted from https://github.com/reworkcss/css
// because we needed to remove source map support.
/**
* External dependencies
*/
/**
* Internal dependencies
*/
/**
* Expose compiler.
*/
/* harmony default export */ var compress = (compress_Compiler);
/**
* Initialize a new `Compiler`.
*/
function compress_Compiler(options) {
compiler.call(this, options);
}
/**
* Inherit from `Base.prototype`.
*/
inherits_browser_default()(compress_Compiler, compiler);
/**
* Compile `node`.
*/
compress_Compiler.prototype.compile = function (node) {
return node.stylesheet.rules.map(this.visit, this).join('');
};
/**
* Visit comment node.
*/
compress_Compiler.prototype.comment = function (node) {
return this.emit('', node.position);
};
/**
* Visit import node.
*/
compress_Compiler.prototype.import = function (node) {
return this.emit('@import ' + node.import + ';', node.position);
};
/**
* Visit media node.
*/
compress_Compiler.prototype.media = function (node) {
return this.emit('@media ' + node.media, node.position) + this.emit('{') + this.mapVisit(node.rules) + this.emit('}');
};
/**
* Visit document node.
*/
compress_Compiler.prototype.document = function (node) {
const doc = '@' + (node.vendor || '') + 'document ' + node.document;
return this.emit(doc, node.position) + this.emit('{') + this.mapVisit(node.rules) + this.emit('}');
};
/**
* Visit charset node.
*/
compress_Compiler.prototype.charset = function (node) {
return this.emit('@charset ' + node.charset + ';', node.position);
};
/**
* Visit namespace node.
*/
compress_Compiler.prototype.namespace = function (node) {
return this.emit('@namespace ' + node.namespace + ';', node.position);
};
/**
* Visit supports node.
*/
compress_Compiler.prototype.supports = function (node) {
return this.emit('@supports ' + node.supports, node.position) + this.emit('{') + this.mapVisit(node.rules) + this.emit('}');
};
/**
* Visit keyframes node.
*/
compress_Compiler.prototype.keyframes = function (node) {
return this.emit('@' + (node.vendor || '') + 'keyframes ' + node.name, node.position) + this.emit('{') + this.mapVisit(node.keyframes) + this.emit('}');
};
/**
* Visit keyframe node.
*/
compress_Compiler.prototype.keyframe = function (node) {
const decls = node.declarations;
return this.emit(node.values.join(','), node.position) + this.emit('{') + this.mapVisit(decls) + this.emit('}');
};
/**
* Visit page node.
*/
compress_Compiler.prototype.page = function (node) {
const sel = node.selectors.length ? node.selectors.join(', ') : '';
return this.emit('@page ' + sel, node.position) + this.emit('{') + this.mapVisit(node.declarations) + this.emit('}');
};
/**
* Visit font-face node.
*/
compress_Compiler.prototype['font-face'] = function (node) {
return this.emit('@font-face', node.position) + this.emit('{') + this.mapVisit(node.declarations) + this.emit('}');
};
/**
* Visit host node.
*/
compress_Compiler.prototype.host = function (node) {
return this.emit('@host', node.position) + this.emit('{') + this.mapVisit(node.rules) + this.emit('}');
};
/**
* Visit custom-media node.
*/
compress_Compiler.prototype['custom-media'] = function (node) {
return this.emit('@custom-media ' + node.name + ' ' + node.media + ';', node.position);
};
/**
* Visit rule node.
*/
compress_Compiler.prototype.rule = function (node) {
const decls = node.declarations;
if (!decls.length) {
return '';
}
return this.emit(node.selectors.join(','), node.position) + this.emit('{') + this.mapVisit(decls) + this.emit('}');
};
/**
* Visit declaration node.
*/
compress_Compiler.prototype.declaration = function (node) {
return this.emit(node.property + ':' + node.value, node.position) + this.emit(';');
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/utils/transform-styles/ast/stringify/identity.js
/* eslint-disable @wordpress/no-unused-vars-before-return */
// Adapted from https://github.com/reworkcss/css
// because we needed to remove source map support.
/**
* External dependencies
*/
/**
* Internal dependencies
*/
/**
* Expose compiler.
*/
/* harmony default export */ var stringify_identity = (identity_Compiler);
/**
* Initialize a new `Compiler`.
*/
function identity_Compiler(options) {
options = options || {};
compiler.call(this, options);
this.indentation = options.indent;
}
/**
* Inherit from `Base.prototype`.
*/
inherits_browser_default()(identity_Compiler, compiler);
/**
* Compile `node`.
*/
identity_Compiler.prototype.compile = function (node) {
return this.stylesheet(node);
};
/**
* Visit stylesheet node.
*/
identity_Compiler.prototype.stylesheet = function (node) {
return this.mapVisit(node.stylesheet.rules, '\n\n');
};
/**
* Visit comment node.
*/
identity_Compiler.prototype.comment = function (node) {
return this.emit(this.indent() + '/*' + node.comment + '*/', node.position);
};
/**
* Visit import node.
*/
identity_Compiler.prototype.import = function (node) {
return this.emit('@import ' + node.import + ';', node.position);
};
/**
* Visit media node.
*/
identity_Compiler.prototype.media = function (node) {
return this.emit('@media ' + node.media, node.position) + this.emit(' {\n' + this.indent(1)) + this.mapVisit(node.rules, '\n\n') + this.emit(this.indent(-1) + '\n}');
};
/**
* Visit document node.
*/
identity_Compiler.prototype.document = function (node) {
const doc = '@' + (node.vendor || '') + 'document ' + node.document;
return this.emit(doc, node.position) + this.emit(' ' + ' {\n' + this.indent(1)) + this.mapVisit(node.rules, '\n\n') + this.emit(this.indent(-1) + '\n}');
};
/**
* Visit charset node.
*/
identity_Compiler.prototype.charset = function (node) {
return this.emit('@charset ' + node.charset + ';', node.position);
};
/**
* Visit namespace node.
*/
identity_Compiler.prototype.namespace = function (node) {
return this.emit('@namespace ' + node.namespace + ';', node.position);
};
/**
* Visit supports node.
*/
identity_Compiler.prototype.supports = function (node) {
return this.emit('@supports ' + node.supports, node.position) + this.emit(' {\n' + this.indent(1)) + this.mapVisit(node.rules, '\n\n') + this.emit(this.indent(-1) + '\n}');
};
/**
* Visit keyframes node.
*/
identity_Compiler.prototype.keyframes = function (node) {
return this.emit('@' + (node.vendor || '') + 'keyframes ' + node.name, node.position) + this.emit(' {\n' + this.indent(1)) + this.mapVisit(node.keyframes, '\n') + this.emit(this.indent(-1) + '}');
};
/**
* Visit keyframe node.
*/
identity_Compiler.prototype.keyframe = function (node) {
const decls = node.declarations;
return this.emit(this.indent()) + this.emit(node.values.join(', '), node.position) + this.emit(' {\n' + this.indent(1)) + this.mapVisit(decls, '\n') + this.emit(this.indent(-1) + '\n' + this.indent() + '}\n');
};
/**
* Visit page node.
*/
identity_Compiler.prototype.page = function (node) {
const sel = node.selectors.length ? node.selectors.join(', ') + ' ' : '';
return this.emit('@page ' + sel, node.position) + this.emit('{\n') + this.emit(this.indent(1)) + this.mapVisit(node.declarations, '\n') + this.emit(this.indent(-1)) + this.emit('\n}');
};
/**
* Visit font-face node.
*/
identity_Compiler.prototype['font-face'] = function (node) {
return this.emit('@font-face ', node.position) + this.emit('{\n') + this.emit(this.indent(1)) + this.mapVisit(node.declarations, '\n') + this.emit(this.indent(-1)) + this.emit('\n}');
};
/**
* Visit host node.
*/
identity_Compiler.prototype.host = function (node) {
return this.emit('@host', node.position) + this.emit(' {\n' + this.indent(1)) + this.mapVisit(node.rules, '\n\n') + this.emit(this.indent(-1) + '\n}');
};
/**
* Visit custom-media node.
*/
identity_Compiler.prototype['custom-media'] = function (node) {
return this.emit('@custom-media ' + node.name + ' ' + node.media + ';', node.position);
};
/**
* Visit rule node.
*/
identity_Compiler.prototype.rule = function (node) {
const indent = this.indent();
const decls = node.declarations;
if (!decls.length) {
return '';
}
return this.emit(node.selectors.map(function (s) {
return indent + s;
}).join(',\n'), node.position) + this.emit(' {\n') + this.emit(this.indent(1)) + this.mapVisit(decls, '\n') + this.emit(this.indent(-1)) + this.emit('\n' + this.indent() + '}');
};
/**
* Visit declaration node.
*/
identity_Compiler.prototype.declaration = function (node) {
return this.emit(this.indent()) + this.emit(node.property + ': ' + node.value, node.position) + this.emit(';');
};
/**
* Increase, decrease or return current indentation.
*/
identity_Compiler.prototype.indent = function (level) {
this.level = this.level || 1;
if (null !== level) {
this.level += level;
return '';
}
return Array(this.level).join(this.indentation || ' ');
};
/* eslint-enable @wordpress/no-unused-vars-before-return */
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/utils/transform-styles/ast/stringify/index.js
// Adapted from https://github.com/reworkcss/css
// because we needed to remove source map support.
/**
* Internal dependencies
*/
/**
* Stringfy the given AST `node`.
*
* Options:
*
* - `compress` space-optimized output
* - `sourcemap` return an object with `.code` and `.map`
*
* @param {Object} node
* @param {Object} [options]
* @return {string}
*/
/* harmony default export */ function stringify(node, options) {
options = options || {};
const compiler = options.compress ? new compress(options) : new stringify_identity(options);
const code = compiler.compile(node);
return code;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/utils/transform-styles/traverse.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function traverseCSS(css, callback) {
try {
const parsed = parse(css);
const updated = traverse_default().map(parsed, function (node) {
if (!node) {
return node;
}
const updatedNode = callback(node);
return this.update(updatedNode);
});
return stringify(updated);
} catch (err) {
// eslint-disable-next-line no-console
console.warn('Error while traversing the CSS: ' + err);
return null;
}
}
/* harmony default export */ var transform_styles_traverse = (traverseCSS);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/utils/transform-styles/transforms/url-rewrite.js
/**
* Return `true` if the given path is http/https.
*
* @param {string} filePath path
*
* @return {boolean} is remote path.
*/
function isRemotePath(filePath) {
return /^(?:https?:)?\/\//.test(filePath);
}
/**
* Return `true` if the given filePath is an absolute url.
*
* @param {string} filePath path
*
* @return {boolean} is absolute path.
*/
function isAbsolutePath(filePath) {
return /^\/(?!\/)/.test(filePath);
}
/**
* Whether or not the url should be inluded.
*
* @param {Object} meta url meta info
*
* @return {boolean} is valid.
*/
function isValidURL(meta) {
// Ignore hashes or data uris.
if (meta.value.indexOf('data:') === 0 || meta.value.indexOf('#') === 0) {
return false;
}
if (isAbsolutePath(meta.value)) {
return false;
} // Do not handle the http/https urls if `includeRemote` is false.
if (isRemotePath(meta.value)) {
return false;
}
return true;
}
/**
* Get the absolute path of the url, relative to the basePath
*
* @param {string} str the url
* @param {string} baseURL base URL
*
* @return {string} the full path to the file
*/
function getResourcePath(str, baseURL) {
return new URL(str, baseURL).toString();
}
/**
* Process the single `url()` pattern
*
* @param {string} baseURL the base URL for relative URLs.
*
* @return {Promise} the Promise.
*/
function processURL(baseURL) {
return meta => ({ ...meta,
newUrl: 'url(' + meta.before + meta.quote + getResourcePath(meta.value, baseURL) + meta.quote + meta.after + ')'
});
}
/**
* Get all `url()`s, and return the meta info
*
* @param {string} value decl.value.
*
* @return {Array} the urls.
*/
function getURLs(value) {
const reg = /url\((\s*)(['"]?)(.+?)\2(\s*)\)/g;
let match;
const URLs = [];
while ((match = reg.exec(value)) !== null) {
const meta = {
source: match[0],
before: match[1],
quote: match[2],
value: match[3],
after: match[4]
};
if (isValidURL(meta)) {
URLs.push(meta);
}
}
return URLs;
}
/**
* Replace the raw value's `url()` segment to the new value
*
* @param {string} raw the raw value.
* @param {Array} URLs the URLs to replace.
*
* @return {string} the new value.
*/
function replaceURLs(raw, URLs) {
URLs.forEach(item => {
raw = raw.replace(item.source, item.newUrl);
});
return raw;
}
const rewrite = rootURL => node => {
if (node.type === 'declaration') {
const updatedURLs = getURLs(node.value).map(processURL(rootURL));
return { ...node,
value: replaceURLs(node.value, updatedURLs)
};
}
return node;
};
/* harmony default export */ var url_rewrite = (rewrite);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/utils/transform-styles/transforms/wrap.js
/**
* @constant string IS_ROOT_TAG Regex to check if the selector is a root tag selector.
*/
const IS_ROOT_TAG = /^(body|html|:root).*$/;
/**
* Creates a callback to modify selectors so they only apply within a certain
* namespace.
*
* @param {string} namespace Namespace to prefix selectors with.
* @param {string[]} ignore Selectors to not prefix.
*
* @return {(node: Object) => Object} Callback to wrap selectors.
*/
const wrap = function (namespace) {
let ignore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
return node => {
/**
* Updates selector if necessary.
*
* @param {string} selector Selector to modify.
*
* @return {string} Updated selector.
*/
const updateSelector = selector => {
if (ignore.includes(selector.trim())) {
return selector;
} // Anything other than a root tag is always prefixed.
{
if (!selector.match(IS_ROOT_TAG)) {
return namespace + ' ' + selector;
}
} // HTML and Body elements cannot be contained within our container so lets extract their styles.
return selector.replace(/^(body|html|:root)/, namespace);
};
if (node.type === 'rule') {
return { ...node,
selectors: node.selectors.map(updateSelector)
};
}
return node;
};
};
/* harmony default export */ var transforms_wrap = (wrap);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/utils/transform-styles/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Applies a series of CSS rule transforms to wrap selectors inside a given class and/or rewrite URLs depending on the parameters passed.
*
* @param {Array} styles CSS rules.
* @param {string} wrapperClassName Wrapper Class Name.
* @return {Array} converted rules.
*/
const transform_styles_transformStyles = function (styles) {
let wrapperClassName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
return Object.values(styles !== null && styles !== void 0 ? styles : []).map(_ref => {
let {
css,
baseURL
} = _ref;
const transforms = [];
if (wrapperClassName) {
transforms.push(transforms_wrap(wrapperClassName));
}
if (baseURL) {
transforms.push(url_rewrite(baseURL));
}
if (transforms.length) {
return transform_styles_traverse(css, (0,external_wp_compose_namespaceObject.compose)(transforms));
}
return css;
});
};
/* harmony default export */ var transform_styles = (transform_styles_transformStyles);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/editor-styles/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const EDITOR_STYLES_SELECTOR = '.editor-styles-wrapper';
k([names, a11y]);
function useDarkThemeBodyClassName(styles) {
return (0,external_wp_element_namespaceObject.useCallback)(node => {
if (!node) {
return;
}
const {
ownerDocument
} = node;
const {
defaultView,
body
} = ownerDocument;
const canvas = ownerDocument.querySelector(EDITOR_STYLES_SELECTOR);
let backgroundColor;
if (!canvas) {
// The real .editor-styles-wrapper element might not exist in the
// DOM, so calculate the background color by creating a fake
// wrapper.
const tempCanvas = ownerDocument.createElement('div');
tempCanvas.classList.add('editor-styles-wrapper');
body.appendChild(tempCanvas);
backgroundColor = defaultView.getComputedStyle(tempCanvas, null).getPropertyValue('background-color');
body.removeChild(tempCanvas);
} else {
backgroundColor = defaultView.getComputedStyle(canvas, null).getPropertyValue('background-color');
}
const colordBackgroundColor = w(backgroundColor); // If background is transparent, it should be treated as light color.
if (colordBackgroundColor.luminance() > 0.5 || colordBackgroundColor.alpha() === 0) {
body.classList.remove('is-dark-theme');
} else {
body.classList.add('is-dark-theme');
}
}, [styles]);
}
function EditorStyles(_ref) {
let {
styles
} = _ref;
const transformedStyles = (0,external_wp_element_namespaceObject.useMemo)(() => transform_styles(styles, EDITOR_STYLES_SELECTOR), [styles]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("style", {
ref: useDarkThemeBodyClassName(styles)
}), transformedStyles.map((css, index) => (0,external_wp_element_namespaceObject.createElement)("style", {
key: index
}, css)));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/duotone/utils.js
/**
* External dependencies
*/
/**
* Convert a list of colors to an object of R, G, and B values.
*
* @param {string[]} colors Array of RBG color strings.
*
* @return {Object} R, G, and B values.
*/
function getValuesFromColors() {
let colors = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
const values = {
r: [],
g: [],
b: [],
a: []
};
colors.forEach(color => {
const rgbColor = w(color).toRgb();
values.r.push(rgbColor.r / 255);
values.g.push(rgbColor.g / 255);
values.b.push(rgbColor.b / 255);
values.a.push(rgbColor.a);
});
return values;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/duotone/components.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* SVG and stylesheet needed for rendering the duotone filter.
*
* @param {Object} props Duotone props.
* @param {string} props.selector Selector to apply the filter to.
* @param {string} props.id Unique id for this duotone filter.
*
* @return {WPElement} Duotone element.
*/
function DuotoneStylesheet(_ref) {
let {
selector,
id
} = _ref;
const css = `
${selector} {
filter: url( #${id} );
}
`;
return (0,external_wp_element_namespaceObject.createElement)("style", null, css);
}
/**
* Stylesheet for disabling a global styles duotone filter.
*
* @param {Object} props Duotone props.
* @param {string} props.selector Selector to disable the filter for.
*
* @return {WPElement} Filter none style element.
*/
function DuotoneUnsetStylesheet(_ref2) {
let {
selector
} = _ref2;
const css = `
${selector} {
filter: none;
}
`;
return (0,external_wp_element_namespaceObject.createElement)("style", null, css);
}
/**
* The SVG part of the duotone filter.
*
* @param {Object} props Duotone props.
* @param {string} props.id Unique id for this duotone filter.
* @param {string[]} props.colors Color strings from dark to light.
*
* @return {WPElement} Duotone SVG.
*/
function DuotoneFilter(_ref3) {
let {
id,
colors
} = _ref3;
const values = getValuesFromColors(colors);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SVG, {
xmlnsXlink: "http://www.w3.org/1999/xlink",
viewBox: "0 0 0 0",
width: "0",
height: "0",
focusable: "false",
role: "none",
style: {
visibility: 'hidden',
position: 'absolute',
left: '-9999px',
overflow: 'hidden'
}
}, (0,external_wp_element_namespaceObject.createElement)("defs", null, (0,external_wp_element_namespaceObject.createElement)("filter", {
id: id
}, (0,external_wp_element_namespaceObject.createElement)("feColorMatrix", {
// Use sRGB instead of linearRGB so transparency looks correct.
colorInterpolationFilters: "sRGB",
type: "matrix" // Use perceptual brightness to convert to grayscale.
,
values: " .299 .587 .114 0 0 .299 .587 .114 0 0 .299 .587 .114 0 0 .299 .587 .114 0 0 "
}), (0,external_wp_element_namespaceObject.createElement)("feComponentTransfer", {
// Use sRGB instead of linearRGB to be consistent with how CSS gradients work.
colorInterpolationFilters: "sRGB"
}, (0,external_wp_element_namespaceObject.createElement)("feFuncR", {
type: "table",
tableValues: values.r.join(' ')
}), (0,external_wp_element_namespaceObject.createElement)("feFuncG", {
type: "table",
tableValues: values.g.join(' ')
}), (0,external_wp_element_namespaceObject.createElement)("feFuncB", {
type: "table",
tableValues: values.b.join(' ')
}), (0,external_wp_element_namespaceObject.createElement)("feFuncA", {
type: "table",
tableValues: values.a.join(' ')
})), (0,external_wp_element_namespaceObject.createElement)("feComposite", {
// Re-mask the image with the original transparency since the feColorMatrix above loses that information.
in2: "SourceGraphic",
operator: "in"
}))));
}
/**
* SVG from a duotone preset
*
* @param {Object} props Duotone props.
* @param {Object} props.preset Duotone preset settings.
*
* @return {WPElement} Duotone element.
*/
function PresetDuotoneFilter(_ref4) {
let {
preset
} = _ref4;
return (0,external_wp_element_namespaceObject.createElement)(DuotoneFilter, {
id: `wp-duotone-${preset.slug}`,
colors: preset.colors
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-preview/auto.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
// This is used to avoid rendering the block list if the sizes change.
let MemoizedBlockList;
const MAX_HEIGHT = 2000;
function ScaledBlockPreview(_ref) {
let {
viewportWidth,
containerWidth,
minHeight,
additionalStyles = []
} = _ref;
if (!viewportWidth) {
viewportWidth = containerWidth;
}
const [contentResizeListener, {
height: contentHeight
}] = (0,external_wp_compose_namespaceObject.useResizeObserver)();
const {
styles,
duotone
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _settings$__experimen, _settings$__experimen2;
const settings = select(store).getSettings();
return {
styles: settings.styles,
duotone: (_settings$__experimen = settings.__experimentalFeatures) === null || _settings$__experimen === void 0 ? void 0 : (_settings$__experimen2 = _settings$__experimen.color) === null || _settings$__experimen2 === void 0 ? void 0 : _settings$__experimen2.duotone
};
}, []); // Avoid scrollbars for pattern previews.
const editorStyles = (0,external_wp_element_namespaceObject.useMemo)(() => {
if (styles) {
return [...styles, {
css: 'body{height:auto;overflow:hidden;border:none;padding:0;}',
__unstableType: 'presets'
}, ...additionalStyles];
}
return styles;
}, [styles, additionalStyles]);
const svgFilters = (0,external_wp_element_namespaceObject.useMemo)(() => {
var _duotone$default, _duotone$theme;
return [...((_duotone$default = duotone === null || duotone === void 0 ? void 0 : duotone.default) !== null && _duotone$default !== void 0 ? _duotone$default : []), ...((_duotone$theme = duotone === null || duotone === void 0 ? void 0 : duotone.theme) !== null && _duotone$theme !== void 0 ? _duotone$theme : [])];
}, [duotone]); // Initialize on render instead of module top level, to avoid circular dependency issues.
MemoizedBlockList = MemoizedBlockList || (0,external_wp_compose_namespaceObject.pure)(BlockList);
const scale = containerWidth / viewportWidth;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Disabled, {
className: "block-editor-block-preview__content",
style: {
transform: `scale(${scale})`,
height: contentHeight * scale,
maxHeight: contentHeight > MAX_HEIGHT ? MAX_HEIGHT * scale : undefined,
minHeight
}
}, (0,external_wp_element_namespaceObject.createElement)(iframe, {
head: (0,external_wp_element_namespaceObject.createElement)(EditorStyles, {
styles: editorStyles
}),
contentRef: (0,external_wp_compose_namespaceObject.useRefEffect)(bodyElement => {
const {
ownerDocument: {
documentElement
}
} = bodyElement;
documentElement.classList.add('block-editor-block-preview__content-iframe');
documentElement.style.position = 'absolute';
documentElement.style.width = '100%'; // Necessary for contentResizeListener to work.
bodyElement.style.boxSizing = 'border-box';
bodyElement.style.position = 'absolute';
bodyElement.style.width = '100%';
}, []),
"aria-hidden": true,
tabIndex: -1,
style: {
position: 'absolute',
width: viewportWidth,
height: contentHeight,
pointerEvents: 'none',
// This is a catch-all max-height for patterns.
// See: https://github.com/WordPress/gutenberg/pull/38175.
maxHeight: MAX_HEIGHT,
minHeight: scale !== 0 && scale < 1 && minHeight ? minHeight / scale : minHeight
}
}, contentResizeListener,
/* Filters need to be rendered before children to avoid Safari rendering issues. */
svgFilters.map(preset => (0,external_wp_element_namespaceObject.createElement)(PresetDuotoneFilter, {
preset: preset,
key: preset.slug
})), (0,external_wp_element_namespaceObject.createElement)(MemoizedBlockList, {
renderAppender: false
})));
}
function AutoBlockPreview(props) {
const [containerResizeListener, {
width: containerWidth
}] = (0,external_wp_compose_namespaceObject.useResizeObserver)();
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("div", {
style: {
position: 'relative',
width: '100%',
height: 0
}
}, containerResizeListener), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-preview__container"
}, !!containerWidth && (0,external_wp_element_namespaceObject.createElement)(ScaledBlockPreview, _extends({}, props, {
containerWidth: containerWidth
}))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-preview/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function BlockPreview(_ref) {
let {
blocks,
viewportWidth = 1200,
minHeight,
additionalStyles = [],
// Deprecated props:
__experimentalMinHeight,
__experimentalPadding
} = _ref;
if (__experimentalMinHeight) {
minHeight = __experimentalMinHeight;
external_wp_deprecated_default()('The __experimentalMinHeight prop', {
since: '6.2',
version: '6.4',
alternative: 'minHeight'
});
}
if (__experimentalPadding) {
additionalStyles = [...additionalStyles, {
css: `body { padding: ${__experimentalPadding}px; }`
}];
external_wp_deprecated_default()('The __experimentalPadding prop of BlockPreview', {
since: '6.2',
version: '6.4',
alternative: 'additionalStyles'
});
}
const originalSettings = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).getSettings(), []);
const settings = (0,external_wp_element_namespaceObject.useMemo)(() => ({ ...originalSettings,
__unstableIsPreviewMode: true
}), [originalSettings]);
const renderedBlocks = (0,external_wp_element_namespaceObject.useMemo)(() => Array.isArray(blocks) ? blocks : [blocks], [blocks]);
if (!blocks || blocks.length === 0) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(ExperimentalBlockEditorProvider, {
value: renderedBlocks,
settings: settings
}, (0,external_wp_element_namespaceObject.createElement)(AutoBlockPreview, {
viewportWidth: viewportWidth,
minHeight: minHeight,
additionalStyles: additionalStyles
}));
}
/**
* BlockPreview renders a preview of a block or array of blocks.
*
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/block-preview/README.md
*
* @param {Object} preview options for how the preview should be shown
* @param {Array|Object} preview.blocks A block instance (object) or an array of blocks to be previewed.
* @param {number} preview.viewportWidth Width of the preview container in pixels. Controls at what size the blocks will be rendered inside the preview. Default: 700.
*
* @return {WPComponent} The component to be rendered.
*/
/* harmony default export */ var block_preview = ((0,external_wp_element_namespaceObject.memo)(BlockPreview));
/**
* This hook is used to lightly mark an element as a block preview wrapper
* element. Call this hook and pass the returned props to the element to mark as
* a block preview wrapper, automatically rendering inner blocks as children. If
* you define a ref for the element, it is important to pass the ref to this
* hook, which the hook in turn will pass to the component through the props it
* returns. Optionally, you can also pass any other props through this hook, and
* they will be merged and returned.
*
* @param {Object} options Preview options.
* @param {WPBlock[]} options.blocks Block objects.
* @param {Object} options.props Optional. Props to pass to the element. Must contain
* the ref if one is defined.
* @param {Object} options.__experimentalLayout Layout settings to be used in the preview.
*
*/
function useBlockPreview(_ref2) {
let {
blocks,
props = {},
__experimentalLayout
} = _ref2;
const originalSettings = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).getSettings(), []);
const settings = (0,external_wp_element_namespaceObject.useMemo)(() => ({ ...originalSettings,
__unstableIsPreviewMode: true
}), [originalSettings]);
const disabledRef = (0,external_wp_compose_namespaceObject.useDisabled)();
const ref = (0,external_wp_compose_namespaceObject.useMergeRefs)([props.ref, disabledRef]);
const renderedBlocks = (0,external_wp_element_namespaceObject.useMemo)(() => Array.isArray(blocks) ? blocks : [blocks], [blocks]);
const children = (0,external_wp_element_namespaceObject.createElement)(ExperimentalBlockEditorProvider, {
value: renderedBlocks,
settings: settings
}, (0,external_wp_element_namespaceObject.createElement)(BlockListItems, {
renderAppender: false,
__experimentalLayout: __experimentalLayout
}));
return { ...props,
ref,
className: classnames_default()(props.className, 'block-editor-block-preview__live-content', 'components-disabled'),
children: blocks !== null && blocks !== void 0 && blocks.length ? children : null
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/preview-panel.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function InserterPreviewPanel(_ref) {
var _example$viewportWidt;
let {
item
} = _ref;
const {
name,
title,
icon,
description,
initialAttributes,
example
} = item;
const isReusable = (0,external_wp_blocks_namespaceObject.isReusableBlock)(item);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__preview-container"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__preview"
}, isReusable || example ? (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__preview-content"
}, (0,external_wp_element_namespaceObject.createElement)(block_preview, {
blocks: example ? (0,external_wp_blocks_namespaceObject.getBlockFromExample)(name, {
attributes: { ...example.attributes,
...initialAttributes
},
innerBlocks: example.innerBlocks
}) : (0,external_wp_blocks_namespaceObject.createBlock)(name, initialAttributes),
viewportWidth: (_example$viewportWidt = example === null || example === void 0 ? void 0 : example.viewportWidth) !== null && _example$viewportWidt !== void 0 ? _example$viewportWidt : 500,
additionalStyles: [{
css: 'body { padding: 16px; }'
}]
})) : (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__preview-content-missing"
}, (0,external_wp_i18n_namespaceObject.__)('No Preview Available.'))), !isReusable && (0,external_wp_element_namespaceObject.createElement)(block_card, {
title: title,
icon: icon,
description: description
}));
}
/* harmony default export */ var preview_panel = (InserterPreviewPanel);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter-listbox/context.js
/**
* WordPress dependencies
*/
const InserterListboxContext = (0,external_wp_element_namespaceObject.createContext)();
/* harmony default export */ var context = (InserterListboxContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter-listbox/item.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function InserterListboxItem(_ref, ref) {
let {
isFirst,
as: Component,
children,
...props
} = _ref;
const state = (0,external_wp_element_namespaceObject.useContext)(context);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableCompositeItem, _extends({
ref: ref,
state: state,
role: "option" // Use the CompositeItem `focusable` prop over Button's
// isFocusable. The latter was shown to cause an issue
// with tab order in the inserter list.
,
focusable: true
}, props), htmlProps => {
const propsWithTabIndex = { ...htmlProps,
tabIndex: isFirst ? 0 : htmlProps.tabIndex
};
if (Component) {
return (0,external_wp_element_namespaceObject.createElement)(Component, propsWithTabIndex, children);
}
if (typeof children === 'function') {
return children(propsWithTabIndex);
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, propsWithTabIndex, children);
});
}
/* harmony default export */ var inserter_listbox_item = ((0,external_wp_element_namespaceObject.forwardRef)(InserterListboxItem));
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/drag-handle.js
/**
* WordPress dependencies
*/
const dragHandle = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
width: "24",
height: "24",
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M8 7h2V5H8v2zm0 6h2v-2H8v2zm0 6h2v-2H8v2zm6-14v2h2V5h-2zm0 8h2v-2h-2v2zm0 6h2v-2h-2v2z"
}));
/* harmony default export */ var drag_handle = (dragHandle);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-draggable/draggable-chip.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function BlockDraggableChip(_ref) {
let {
count,
icon,
isPattern
} = _ref;
const patternLabel = isPattern && (0,external_wp_i18n_namespaceObject.__)('Pattern');
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-draggable-chip-wrapper"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-draggable-chip",
"data-testid": "block-draggable-chip"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Flex, {
justify: "center",
className: "block-editor-block-draggable-chip__content"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexItem, null, icon ? (0,external_wp_element_namespaceObject.createElement)(block_icon, {
icon: icon
}) : patternLabel || (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %d: Number of blocks. */
(0,external_wp_i18n_namespaceObject._n)('%d block', '%d blocks', count), count)), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexItem, null, (0,external_wp_element_namespaceObject.createElement)(block_icon, {
icon: drag_handle
})))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter-draggable-blocks/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const InserterDraggableBlocks = _ref => {
let {
isEnabled,
blocks,
icon,
children,
isPattern
} = _ref;
const transferData = {
type: 'inserter',
blocks
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Draggable, {
__experimentalTransferDataType: "wp-blocks",
transferData: transferData,
__experimentalDragComponent: (0,external_wp_element_namespaceObject.createElement)(BlockDraggableChip, {
count: blocks.length,
icon: icon,
isPattern: isPattern
})
}, _ref2 => {
let {
onDraggableStart,
onDraggableEnd
} = _ref2;
return children({
draggable: isEnabled,
onDragStart: isEnabled ? onDraggableStart : undefined,
onDragEnd: isEnabled ? onDraggableEnd : undefined
});
});
};
/* harmony default export */ var inserter_draggable_blocks = (InserterDraggableBlocks);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter-list-item/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function InserterListItem(_ref) {
let {
className,
isFirst,
item,
onSelect,
onHover,
isDraggable,
...props
} = _ref;
const isDragging = (0,external_wp_element_namespaceObject.useRef)(false);
const itemIconStyle = item.icon ? {
backgroundColor: item.icon.background,
color: item.icon.foreground
} : {};
const blocks = (0,external_wp_element_namespaceObject.useMemo)(() => {
return [(0,external_wp_blocks_namespaceObject.createBlock)(item.name, item.initialAttributes, (0,external_wp_blocks_namespaceObject.createBlocksFromInnerBlocksTemplate)(item.innerBlocks))];
}, [item.name, item.initialAttributes, item.initialAttributes]);
const isSynced = (0,external_wp_blocks_namespaceObject.isReusableBlock)(item) || (0,external_wp_blocks_namespaceObject.isTemplatePart)(item);
return (0,external_wp_element_namespaceObject.createElement)(inserter_draggable_blocks, {
isEnabled: isDraggable && !item.disabled,
blocks: blocks,
icon: item.icon
}, _ref2 => {
let {
draggable,
onDragStart,
onDragEnd
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('block-editor-block-types-list__list-item', {
'is-synced': isSynced
}),
draggable: draggable,
onDragStart: event => {
isDragging.current = true;
if (onDragStart) {
onHover(null);
onDragStart(event);
}
},
onDragEnd: event => {
isDragging.current = false;
if (onDragEnd) {
onDragEnd(event);
}
}
}, (0,external_wp_element_namespaceObject.createElement)(inserter_listbox_item, _extends({
isFirst: isFirst,
className: classnames_default()('block-editor-block-types-list__item', className),
disabled: item.isDisabled,
onClick: event => {
event.preventDefault();
onSelect(item, (0,external_wp_keycodes_namespaceObject.isAppleOS)() ? event.metaKey : event.ctrlKey);
onHover(null);
},
onKeyDown: event => {
const {
keyCode
} = event;
if (keyCode === external_wp_keycodes_namespaceObject.ENTER) {
event.preventDefault();
onSelect(item, (0,external_wp_keycodes_namespaceObject.isAppleOS)() ? event.metaKey : event.ctrlKey);
onHover(null);
}
},
onMouseEnter: () => {
if (isDragging.current) {
return;
}
onHover(item);
},
onMouseLeave: () => onHover(null)
}, props), (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-block-types-list__item-icon",
style: itemIconStyle
}, (0,external_wp_element_namespaceObject.createElement)(block_icon, {
icon: item.icon,
showColors: true
})), (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-block-types-list__item-title"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalTruncate, {
numberOfLines: 3
}, item.title))));
});
}
/* harmony default export */ var inserter_list_item = ((0,external_wp_element_namespaceObject.memo)(InserterListItem));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter-listbox/group.js
/**
* WordPress dependencies
*/
function InserterListboxGroup(props, ref) {
const [shouldSpeak, setShouldSpeak] = (0,external_wp_element_namespaceObject.useState)(false);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (shouldSpeak) {
(0,external_wp_a11y_namespaceObject.speak)((0,external_wp_i18n_namespaceObject.__)('Use left and right arrow keys to move through blocks'));
}
}, [shouldSpeak]);
return (0,external_wp_element_namespaceObject.createElement)("div", _extends({
ref: ref,
role: "listbox",
"aria-orientation": "horizontal",
onFocus: () => {
setShouldSpeak(true);
},
onBlur: event => {
const focusingOutsideGroup = !event.currentTarget.contains(event.relatedTarget);
if (focusingOutsideGroup) {
setShouldSpeak(false);
}
}
}, props));
}
/* harmony default export */ var group = ((0,external_wp_element_namespaceObject.forwardRef)(InserterListboxGroup));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter-listbox/row.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function InserterListboxRow(props, ref) {
const state = (0,external_wp_element_namespaceObject.useContext)(context);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableCompositeGroup, _extends({
state: state,
role: "presentation",
ref: ref
}, props));
}
/* harmony default export */ var inserter_listbox_row = ((0,external_wp_element_namespaceObject.forwardRef)(InserterListboxRow));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-types-list/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function chunk(array, size) {
const chunks = [];
for (let i = 0, j = array.length; i < j; i += size) {
chunks.push(array.slice(i, i + size));
}
return chunks;
}
function BlockTypesList(_ref) {
let {
items = [],
onSelect,
onHover = () => {},
children,
label,
isDraggable = true
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(group, {
className: "block-editor-block-types-list",
"aria-label": label
}, chunk(items, 3).map((row, i) => (0,external_wp_element_namespaceObject.createElement)(inserter_listbox_row, {
key: i
}, row.map((item, j) => (0,external_wp_element_namespaceObject.createElement)(inserter_list_item, {
key: item.id,
item: item,
className: (0,external_wp_blocks_namespaceObject.getBlockMenuDefaultClassName)(item.id),
onSelect: onSelect,
onHover: onHover,
isDraggable: isDraggable && !item.isDisabled,
isFirst: i === 0 && j === 0
})))), children);
}
/* harmony default export */ var block_types_list = (BlockTypesList);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/panel.js
/**
* WordPress dependencies
*/
function InserterPanel(_ref) {
let {
title,
icon,
children
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__panel-header"
}, (0,external_wp_element_namespaceObject.createElement)("h2", {
className: "block-editor-inserter__panel-title"
}, title), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Icon, {
icon: icon
})), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__panel-content"
}, children));
}
/* harmony default export */ var panel = (InserterPanel);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/hooks/use-block-types-state.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Retrieves the block types inserter state.
*
* @param {string=} rootClientId Insertion's root client ID.
* @param {Function} onInsert function called when inserter a list of blocks.
* @return {Array} Returns the block types state. (block types, categories, collections, onSelect handler)
*/
const useBlockTypesState = (rootClientId, onInsert) => {
const {
categories,
collections,
items
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getInserterItems
} = select(store);
const {
getCategories,
getCollections
} = select(external_wp_blocks_namespaceObject.store);
return {
categories: getCategories(),
collections: getCollections(),
items: getInserterItems(rootClientId)
};
}, [rootClientId]);
const onSelectItem = (0,external_wp_element_namespaceObject.useCallback)((_ref, shouldFocusBlock) => {
let {
name,
initialAttributes,
innerBlocks
} = _ref;
const insertedBlock = (0,external_wp_blocks_namespaceObject.createBlock)(name, initialAttributes, (0,external_wp_blocks_namespaceObject.createBlocksFromInnerBlocksTemplate)(innerBlocks));
onInsert(insertedBlock, undefined, shouldFocusBlock);
}, [onInsert]);
return [items, categories, collections, onSelectItem];
};
/* harmony default export */ var use_block_types_state = (useBlockTypesState);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter-listbox/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function InserterListbox(_ref) {
let {
children
} = _ref;
const compositeState = (0,external_wp_components_namespaceObject.__unstableUseCompositeState)({
shift: true,
wrap: 'horizontal'
});
return (0,external_wp_element_namespaceObject.createElement)(context.Provider, {
value: compositeState
}, children);
}
/* harmony default export */ var inserter_listbox = (InserterListbox);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/block-types-tab.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const getBlockNamespace = item => item.name.split('/')[0];
const MAX_SUGGESTED_ITEMS = 6;
/**
* Shared reference to an empty array for cases where it is important to avoid
* returning a new array reference on every invocation and rerendering the component.
*
* @type {Array}
*/
const block_types_tab_EMPTY_ARRAY = [];
function BlockTypesTab(_ref) {
let {
rootClientId,
onInsert,
onHover,
showMostUsedBlocks
} = _ref;
const [items, categories, collections, onSelectItem] = use_block_types_state(rootClientId, onInsert);
const suggestedItems = (0,external_wp_element_namespaceObject.useMemo)(() => {
return orderBy(items, 'frecency', 'desc').slice(0, MAX_SUGGESTED_ITEMS);
}, [items]);
const uncategorizedItems = (0,external_wp_element_namespaceObject.useMemo)(() => {
return items.filter(item => !item.category);
}, [items]);
const itemsPerCategory = (0,external_wp_element_namespaceObject.useMemo)(() => {
return (0,external_wp_compose_namespaceObject.pipe)(itemList => itemList.filter(item => item.category && item.category !== 'reusable'), itemList => (0,external_lodash_namespaceObject.groupBy)(itemList, 'category'))(items);
}, [items]);
const itemsPerCollection = (0,external_wp_element_namespaceObject.useMemo)(() => {
// Create a new Object to avoid mutating collection.
const result = { ...collections
};
Object.keys(collections).forEach(namespace => {
result[namespace] = items.filter(item => getBlockNamespace(item) === namespace);
if (result[namespace].length === 0) {
delete result[namespace];
}
});
return result;
}, [items, collections]); // Hide block preview on unmount.
(0,external_wp_element_namespaceObject.useEffect)(() => () => onHover(null), []);
/**
* The inserter contains a big number of blocks and opening it is a costful operation.
* The rendering is the most costful part of it, in order to improve the responsiveness
* of the "opening" action, these lazy lists allow us to render the inserter category per category,
* once all the categories are rendered, we start rendering the collections and the uncategorized block types.
*/
const currentlyRenderedCategories = (0,external_wp_compose_namespaceObject.useAsyncList)(categories);
const didRenderAllCategories = categories.length === currentlyRenderedCategories.length; // Async List requires an array.
const collectionEntries = (0,external_wp_element_namespaceObject.useMemo)(() => {
return Object.entries(collections);
}, [collections]);
const currentlyRenderedCollections = (0,external_wp_compose_namespaceObject.useAsyncList)(didRenderAllCategories ? collectionEntries : block_types_tab_EMPTY_ARRAY);
return (0,external_wp_element_namespaceObject.createElement)(inserter_listbox, null, (0,external_wp_element_namespaceObject.createElement)("div", null, showMostUsedBlocks && !!suggestedItems.length && (0,external_wp_element_namespaceObject.createElement)(panel, {
title: (0,external_wp_i18n_namespaceObject._x)('Most used', 'blocks')
}, (0,external_wp_element_namespaceObject.createElement)(block_types_list, {
items: suggestedItems,
onSelect: onSelectItem,
onHover: onHover,
label: (0,external_wp_i18n_namespaceObject._x)('Most used', 'blocks')
})), currentlyRenderedCategories.map(category => {
const categoryItems = itemsPerCategory[category.slug];
if (!categoryItems || !categoryItems.length) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(panel, {
key: category.slug,
title: category.title,
icon: category.icon
}, (0,external_wp_element_namespaceObject.createElement)(block_types_list, {
items: categoryItems,
onSelect: onSelectItem,
onHover: onHover,
label: category.title
}));
}), didRenderAllCategories && uncategorizedItems.length > 0 && (0,external_wp_element_namespaceObject.createElement)(panel, {
className: "block-editor-inserter__uncategorized-blocks-panel",
title: (0,external_wp_i18n_namespaceObject.__)('Uncategorized')
}, (0,external_wp_element_namespaceObject.createElement)(block_types_list, {
items: uncategorizedItems,
onSelect: onSelectItem,
onHover: onHover,
label: (0,external_wp_i18n_namespaceObject.__)('Uncategorized')
})), currentlyRenderedCollections.map(_ref2 => {
let [namespace, collection] = _ref2;
const collectionItems = itemsPerCollection[namespace];
if (!collectionItems || !collectionItems.length) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(panel, {
key: namespace,
title: collection.title,
icon: collection.icon
}, (0,external_wp_element_namespaceObject.createElement)(block_types_list, {
items: collectionItems,
onSelect: onSelectItem,
onHover: onHover,
label: collection.title
}));
})));
}
/* harmony default export */ var block_types_tab = (BlockTypesTab);
;// CONCATENATED MODULE: external ["wp","notices"]
var external_wp_notices_namespaceObject = window["wp"]["notices"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/hooks/use-patterns-state.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Retrieves the block patterns inserter state.
*
* @param {Function} onInsert function called when inserter a list of blocks.
* @param {string=} rootClientId Insertion's root client ID.
*
* @return {Array} Returns the patterns state. (patterns, categories, onSelect handler)
*/
const usePatternsState = (onInsert, rootClientId) => {
const {
patternCategories,
patterns
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
__experimentalGetAllowedPatterns,
getSettings
} = select(store);
return {
patterns: __experimentalGetAllowedPatterns(rootClientId),
patternCategories: getSettings().__experimentalBlockPatternCategories
};
}, [rootClientId]);
const {
createSuccessNotice
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_notices_namespaceObject.store);
const onClickPattern = (0,external_wp_element_namespaceObject.useCallback)((pattern, blocks) => {
onInsert((blocks !== null && blocks !== void 0 ? blocks : []).map(block => (0,external_wp_blocks_namespaceObject.cloneBlock)(block)), pattern.name);
createSuccessNotice((0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: block pattern title. */
(0,external_wp_i18n_namespaceObject.__)('Block pattern "%s" inserted.'), pattern.title), {
type: 'snackbar'
});
}, []);
return [patterns, patternCategories, onClickPattern];
};
/* harmony default export */ var use_patterns_state = (usePatternsState);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-patterns-list/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const WithToolTip = _ref => {
let {
showTooltip,
title,
children
} = _ref;
if (showTooltip) {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Tooltip, {
text: title
}, children);
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, children);
};
function BlockPattern(_ref2) {
let {
isDraggable,
pattern,
onClick,
onHover,
composite,
showTooltip
} = _ref2;
const [isDragging, setIsDragging] = (0,external_wp_element_namespaceObject.useState)(false);
const {
blocks,
viewportWidth
} = pattern;
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(BlockPattern);
const descriptionId = `block-editor-block-patterns-list__item-description-${instanceId}`;
return (0,external_wp_element_namespaceObject.createElement)(inserter_draggable_blocks, {
isEnabled: isDraggable,
blocks: blocks,
isPattern: !!pattern
}, _ref3 => {
let {
draggable,
onDragStart,
onDragEnd
} = _ref3;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-patterns-list__list-item",
draggable: draggable,
onDragStart: event => {
setIsDragging(true);
if (onDragStart) {
onHover === null || onHover === void 0 ? void 0 : onHover(null);
onDragStart(event);
}
},
onDragEnd: event => {
setIsDragging(false);
if (onDragEnd) {
onDragEnd(event);
}
}
}, (0,external_wp_element_namespaceObject.createElement)(WithToolTip, {
showTooltip: showTooltip,
title: pattern.title
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableCompositeItem, _extends({
role: "option",
as: "div"
}, composite, {
className: "block-editor-block-patterns-list__item",
onClick: () => {
onClick(pattern, blocks);
onHover === null || onHover === void 0 ? void 0 : onHover(null);
},
onMouseEnter: () => {
if (isDragging) {
return;
}
onHover === null || onHover === void 0 ? void 0 : onHover(pattern);
},
onMouseLeave: () => onHover === null || onHover === void 0 ? void 0 : onHover(null),
"aria-label": pattern.title,
"aria-describedby": pattern.description ? descriptionId : undefined
}), (0,external_wp_element_namespaceObject.createElement)(block_preview, {
blocks: blocks,
viewportWidth: viewportWidth
}), !showTooltip && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-patterns-list__item-title"
}, pattern.title), !!pattern.description && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.VisuallyHidden, {
id: descriptionId
}, pattern.description))));
});
}
function BlockPatternPlaceholder() {
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-patterns-list__item is-placeholder"
});
}
function BlockPatternList(_ref4) {
let {
isDraggable,
blockPatterns,
shownPatterns,
onHover,
onClickPattern,
orientation,
label = (0,external_wp_i18n_namespaceObject.__)('Block Patterns'),
showTitlesAsTooltip
} = _ref4;
const composite = (0,external_wp_components_namespaceObject.__unstableUseCompositeState)({
orientation
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableComposite, _extends({}, composite, {
role: "listbox",
className: "block-editor-block-patterns-list",
"aria-label": label
}), blockPatterns.map(pattern => {
const isShown = shownPatterns.includes(pattern);
return isShown ? (0,external_wp_element_namespaceObject.createElement)(BlockPattern, {
key: pattern.name,
pattern: pattern,
onClick: onClickPattern,
onHover: onHover,
isDraggable: isDraggable,
composite: composite,
showTooltip: showTitlesAsTooltip
}) : (0,external_wp_element_namespaceObject.createElement)(BlockPatternPlaceholder, {
key: pattern.name
});
}));
}
/* harmony default export */ var block_patterns_list = (BlockPatternList);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/block-patterns-explorer/sidebar.js
/**
* WordPress dependencies
*/
function PatternCategoriesList(_ref) {
let {
selectedCategory,
patternCategories,
onClickCategory
} = _ref;
const baseClassName = 'block-editor-block-patterns-explorer__sidebar';
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: `${baseClassName}__categories-list`
}, patternCategories.map(_ref2 => {
let {
name,
label
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
key: name,
label: label,
className: `${baseClassName}__categories-list__item`,
isPressed: selectedCategory === name,
onClick: () => {
onClickCategory(name);
}
}, label);
}));
}
function PatternsExplorerSearch(_ref3) {
let {
filterValue,
setFilterValue
} = _ref3;
const baseClassName = 'block-editor-block-patterns-explorer__search';
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: baseClassName
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SearchControl, {
__nextHasNoMarginBottom: true,
onChange: setFilterValue,
value: filterValue,
label: (0,external_wp_i18n_namespaceObject.__)('Search for patterns'),
placeholder: (0,external_wp_i18n_namespaceObject.__)('Search')
}));
}
function PatternExplorerSidebar(_ref4) {
let {
selectedCategory,
patternCategories,
onClickCategory,
filterValue,
setFilterValue
} = _ref4;
const baseClassName = 'block-editor-block-patterns-explorer__sidebar';
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: baseClassName
}, (0,external_wp_element_namespaceObject.createElement)(PatternsExplorerSearch, {
filterValue: filterValue,
setFilterValue: setFilterValue
}), !filterValue && (0,external_wp_element_namespaceObject.createElement)(PatternCategoriesList, {
selectedCategory: selectedCategory,
patternCategories: patternCategories,
onClickCategory: onClickCategory
}));
}
/* harmony default export */ var sidebar = (PatternExplorerSidebar);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/no-results.js
/**
* WordPress dependencies
*/
function InserterNoResults() {
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__no-results"
}, (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
className: "block-editor-inserter__no-results-icon",
icon: block_default
}), (0,external_wp_element_namespaceObject.createElement)("p", null, (0,external_wp_i18n_namespaceObject.__)('No results found.')));
}
/* harmony default export */ var no_results = (InserterNoResults);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/hooks/use-insertion-point.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* @typedef WPInserterConfig
*
* @property {string=} rootClientId If set, insertion will be into the
* block with this ID.
* @property {number=} insertionIndex If set, insertion will be into this
* explicit position.
* @property {string=} clientId If set, insertion will be after the
* block with this ID.
* @property {boolean=} isAppender Whether the inserter is an appender
* or not.
* @property {Function=} onSelect Called after insertion.
*/
/**
* Returns the insertion point state given the inserter config.
*
* @param {WPInserterConfig} config Inserter Config.
* @return {Array} Insertion Point State (rootClientID, onInsertBlocks and onToggle).
*/
function useInsertionPoint(_ref) {
let {
rootClientId = '',
insertionIndex,
clientId,
isAppender,
onSelect,
shouldFocusBlock = true,
selectBlockOnInsert = true
} = _ref;
const {
getSelectedBlock
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const {
destinationRootClientId,
destinationIndex
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getSelectedBlockClientId,
getBlockRootClientId,
getBlockIndex,
getBlockOrder
} = select(store);
const selectedBlockClientId = getSelectedBlockClientId();
let _destinationRootClientId = rootClientId;
let _destinationIndex;
if (insertionIndex !== undefined) {
// Insert into a specific index.
_destinationIndex = insertionIndex;
} else if (clientId) {
// Insert after a specific client ID.
_destinationIndex = getBlockIndex(clientId);
} else if (!isAppender && selectedBlockClientId) {
_destinationRootClientId = getBlockRootClientId(selectedBlockClientId);
_destinationIndex = getBlockIndex(selectedBlockClientId) + 1;
} else {
// Insert at the end of the list.
_destinationIndex = getBlockOrder(_destinationRootClientId).length;
}
return {
destinationRootClientId: _destinationRootClientId,
destinationIndex: _destinationIndex
};
}, [rootClientId, insertionIndex, clientId, isAppender]);
const {
replaceBlocks,
insertBlocks,
showInsertionPoint,
hideInsertionPoint
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const onInsertBlocks = (0,external_wp_element_namespaceObject.useCallback)(function (blocks, meta) {
let shouldForceFocusBlock = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
const selectedBlock = getSelectedBlock();
if (!isAppender && selectedBlock && (0,external_wp_blocks_namespaceObject.isUnmodifiedDefaultBlock)(selectedBlock)) {
replaceBlocks(selectedBlock.clientId, blocks, null, shouldFocusBlock || shouldForceFocusBlock ? 0 : null, meta);
} else {
insertBlocks(blocks, destinationIndex, destinationRootClientId, selectBlockOnInsert, shouldFocusBlock || shouldForceFocusBlock ? 0 : null, meta);
}
const blockLength = Array.isArray(blocks) ? blocks.length : 1;
const message = (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %d: the name of the block that has been added
(0,external_wp_i18n_namespaceObject._n)('%d block added.', '%d blocks added.', blockLength), blockLength);
(0,external_wp_a11y_namespaceObject.speak)(message);
if (onSelect) {
onSelect(blocks);
}
}, [isAppender, getSelectedBlock, replaceBlocks, insertBlocks, destinationRootClientId, destinationIndex, onSelect, shouldFocusBlock]);
const onToggleInsertionPoint = (0,external_wp_element_namespaceObject.useCallback)(show => {
if (show) {
showInsertionPoint(destinationRootClientId, destinationIndex);
} else {
hideInsertionPoint();
}
}, [showInsertionPoint, hideInsertionPoint, destinationRootClientId, destinationIndex]);
return [destinationRootClientId, onInsertBlocks, onToggleInsertionPoint];
}
/* harmony default export */ var use_insertion_point = (useInsertionPoint);
// EXTERNAL MODULE: ./node_modules/remove-accents/index.js
var remove_accents = __webpack_require__(4793);
var remove_accents_default = /*#__PURE__*/__webpack_require__.n(remove_accents);
;// 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/@wordpress/block-editor/build-module/components/inserter/search-items.js
/**
* External dependencies
*/
// Default search helpers.
const defaultGetName = item => item.name || '';
const defaultGetTitle = item => item.title;
const defaultGetDescription = item => item.description || '';
const defaultGetKeywords = item => item.keywords || [];
const defaultGetCategory = item => item.category;
const defaultGetCollection = () => null;
/**
* Extracts words from an input string.
*
* @param {string} input The input string.
*
* @return {Array} Words, extracted from the input string.
*/
function extractWords() {
let input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
return noCase(input, {
splitRegexp: [/([\p{Ll}\p{Lo}\p{N}])([\p{Lu}\p{Lt}])/gu, // One lowercase or digit, followed by one uppercase.
/([\p{Lu}\p{Lt}])([\p{Lu}\p{Lt}][\p{Ll}\p{Lo}])/gu // One uppercase followed by one uppercase and one lowercase.
],
stripRegexp: /(\p{C}|\p{P}|\p{S})+/giu // Anything that's not a punctuation, symbol or control/format character.
}).split(' ').filter(Boolean);
}
/**
* Sanitizes the search input string.
*
* @param {string} input The search input to normalize.
*
* @return {string} The normalized search input.
*/
function normalizeSearchInput() {
let input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
// Disregard diacritics.
// Input: "média"
input = remove_accents_default()(input); // Accommodate leading slash, matching autocomplete expectations.
// Input: "/media"
input = input.replace(/^\//, ''); // Lowercase.
// Input: "MEDIA"
input = input.toLowerCase();
return input;
}
/**
* Converts the search term into a list of normalized terms.
*
* @param {string} input The search term to normalize.
*
* @return {string[]} The normalized list of search terms.
*/
const getNormalizedSearchTerms = function () {
let input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
return extractWords(normalizeSearchInput(input));
};
const removeMatchingTerms = (unmatchedTerms, unprocessedTerms) => {
return unmatchedTerms.filter(term => !getNormalizedSearchTerms(unprocessedTerms).some(unprocessedTerm => unprocessedTerm.includes(term)));
};
const searchBlockItems = (items, categories, collections, searchInput) => {
const normalizedSearchTerms = getNormalizedSearchTerms(searchInput);
if (normalizedSearchTerms.length === 0) {
return items;
}
const config = {
getCategory: item => {
var _categories$find;
return (_categories$find = categories.find(_ref => {
let {
slug
} = _ref;
return slug === item.category;
})) === null || _categories$find === void 0 ? void 0 : _categories$find.title;
},
getCollection: item => {
var _collections$item$nam;
return (_collections$item$nam = collections[item.name.split('/')[0]]) === null || _collections$item$nam === void 0 ? void 0 : _collections$item$nam.title;
}
};
return searchItems(items, searchInput, config);
};
/**
* Filters an item list given a search term.
*
* @param {Array} items Item list
* @param {string} searchInput Search input.
* @param {Object} config Search Config.
*
* @return {Array} Filtered item list.
*/
const searchItems = function () {
let items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
let searchInput = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
let config = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
const normalizedSearchTerms = getNormalizedSearchTerms(searchInput);
if (normalizedSearchTerms.length === 0) {
return items;
}
const rankedItems = items.map(item => {
return [item, getItemSearchRank(item, searchInput, config)];
}).filter(_ref2 => {
let [, rank] = _ref2;
return rank > 0;
});
rankedItems.sort((_ref3, _ref4) => {
let [, rank1] = _ref3;
let [, rank2] = _ref4;
return rank2 - rank1;
});
return rankedItems.map(_ref5 => {
let [item] = _ref5;
return item;
});
};
/**
* Get the search rank for a given item and a specific search term.
* The better the match, the higher the rank.
* If the rank equals 0, it should be excluded from the results.
*
* @param {Object} item Item to filter.
* @param {string} searchTerm Search term.
* @param {Object} config Search Config.
*
* @return {number} Search Rank.
*/
function getItemSearchRank(item, searchTerm) {
let config = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
const {
getName = defaultGetName,
getTitle = defaultGetTitle,
getDescription = defaultGetDescription,
getKeywords = defaultGetKeywords,
getCategory = defaultGetCategory,
getCollection = defaultGetCollection
} = config;
const name = getName(item);
const title = getTitle(item);
const description = getDescription(item);
const keywords = getKeywords(item);
const category = getCategory(item);
const collection = getCollection(item);
const normalizedSearchInput = normalizeSearchInput(searchTerm);
const normalizedTitle = normalizeSearchInput(title);
let rank = 0; // Prefers exact matches
// Then prefers if the beginning of the title matches the search term
// name, keywords, categories, collection, variations match come later.
if (normalizedSearchInput === normalizedTitle) {
rank += 30;
} else if (normalizedTitle.startsWith(normalizedSearchInput)) {
rank += 20;
} else {
const terms = [name, title, description, ...keywords, category, collection].join(' ');
const normalizedSearchTerms = extractWords(normalizedSearchInput);
const unmatchedTerms = removeMatchingTerms(normalizedSearchTerms, terms);
if (unmatchedTerms.length === 0) {
rank += 10;
}
} // Give a better rank to "core" namespaced items.
if (rank !== 0 && name.startsWith('core/')) {
const isCoreBlockVariation = name !== item.id; // Give a bit better rank to "core" blocks over "core" block variations.
rank += isCoreBlockVariation ? 1 : 2;
}
return rank;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/block-patterns-explorer/patterns-list.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const INITIAL_INSERTER_RESULTS = 2;
function PatternsListHeader(_ref) {
let {
filterValue,
filteredBlockPatternsLength
} = _ref;
if (!filterValue) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalHeading, {
level: 2,
lineHeight: '48px',
className: "block-editor-block-patterns-explorer__search-results-count"
}, (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %d: number of patterns. %s: block pattern search query */
(0,external_wp_i18n_namespaceObject._n)('%1$d pattern found for "%2$s"', '%1$d patterns found for "%2$s"', filteredBlockPatternsLength), filteredBlockPatternsLength, filterValue));
}
function PatternList(_ref2) {
let {
filterValue,
selectedCategory,
patternCategories
} = _ref2;
const debouncedSpeak = (0,external_wp_compose_namespaceObject.useDebounce)(external_wp_a11y_namespaceObject.speak, 500);
const [destinationRootClientId, onInsertBlocks] = use_insertion_point({
shouldFocusBlock: true
});
const [allPatterns,, onSelectBlockPattern] = use_patterns_state(onInsertBlocks, destinationRootClientId);
const registeredPatternCategories = (0,external_wp_element_namespaceObject.useMemo)(() => patternCategories.map(patternCategory => patternCategory.name), [patternCategories]);
const filteredBlockPatterns = (0,external_wp_element_namespaceObject.useMemo)(() => {
if (!filterValue) {
return allPatterns.filter(pattern => {
var _pattern$categories, _pattern$categories2;
return selectedCategory === 'uncategorized' ? !((_pattern$categories = pattern.categories) !== null && _pattern$categories !== void 0 && _pattern$categories.length) || pattern.categories.every(category => !registeredPatternCategories.includes(category)) : (_pattern$categories2 = pattern.categories) === null || _pattern$categories2 === void 0 ? void 0 : _pattern$categories2.includes(selectedCategory);
});
}
return searchItems(allPatterns, filterValue);
}, [filterValue, selectedCategory, allPatterns]); // Announce search results on change.
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (!filterValue) {
return;
}
const count = filteredBlockPatterns.length;
const resultsFoundMessage = (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %d: number of results. */
(0,external_wp_i18n_namespaceObject._n)('%d result found.', '%d results found.', count), count);
debouncedSpeak(resultsFoundMessage);
}, [filterValue, debouncedSpeak]);
const currentShownPatterns = (0,external_wp_compose_namespaceObject.useAsyncList)(filteredBlockPatterns, {
step: INITIAL_INSERTER_RESULTS
});
const hasItems = !!(filteredBlockPatterns !== null && filteredBlockPatterns !== void 0 && filteredBlockPatterns.length);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-patterns-explorer__list"
}, hasItems && (0,external_wp_element_namespaceObject.createElement)(PatternsListHeader, {
filterValue: filterValue,
filteredBlockPatternsLength: filteredBlockPatterns.length
}), (0,external_wp_element_namespaceObject.createElement)(inserter_listbox, null, !hasItems && (0,external_wp_element_namespaceObject.createElement)(no_results, null), hasItems && (0,external_wp_element_namespaceObject.createElement)(block_patterns_list, {
shownPatterns: currentShownPatterns,
blockPatterns: filteredBlockPatterns,
onClickPattern: onSelectBlockPattern,
isDraggable: false
})));
}
/* harmony default export */ var patterns_list = (PatternList);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/block-patterns-explorer/explorer.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PatternsExplorer(_ref) {
let {
initialCategory,
patternCategories
} = _ref;
const [filterValue, setFilterValue] = (0,external_wp_element_namespaceObject.useState)('');
const [selectedCategory, setSelectedCategory] = (0,external_wp_element_namespaceObject.useState)(initialCategory === null || initialCategory === void 0 ? void 0 : initialCategory.name);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-patterns-explorer"
}, (0,external_wp_element_namespaceObject.createElement)(sidebar, {
selectedCategory: selectedCategory,
patternCategories: patternCategories,
onClickCategory: setSelectedCategory,
filterValue: filterValue,
setFilterValue: setFilterValue
}), (0,external_wp_element_namespaceObject.createElement)(patterns_list, {
filterValue: filterValue,
selectedCategory: selectedCategory,
patternCategories: patternCategories
}));
}
function PatternsExplorerModal(_ref2) {
let {
onModalClose,
...restProps
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Modal, {
title: (0,external_wp_i18n_namespaceObject.__)('Patterns'),
onRequestClose: onModalClose,
isFullScreen: true
}, (0,external_wp_element_namespaceObject.createElement)(PatternsExplorer, restProps));
}
/* harmony default export */ var explorer = (PatternsExplorerModal);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/mobile-tab-navigation.js
/**
* WordPress dependencies
*/
function ScreenHeader(_ref) {
let {
title
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalVStack, {
spacing: 0
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalView, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalSpacer, {
marginBottom: 0,
paddingX: 4,
paddingY: 3
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalHStack, {
spacing: 2
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalNavigatorBackButton, {
style: // TODO: This style override is also used in ToolsPanelHeader.
// It should be supported out-of-the-box by Button.
{
minWidth: 24,
padding: 0
},
icon: (0,external_wp_i18n_namespaceObject.isRTL)() ? chevron_right : chevron_left,
isSmall: true,
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Navigate to the previous view')
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalSpacer, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalHeading, {
level: 5
}, title))))));
}
function MobileTabNavigation(_ref2) {
let {
categories,
children
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalNavigatorProvider, {
initialPath: "/",
className: "block-editor-inserter__mobile-tab-navigation"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalNavigatorScreen, {
path: "/"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalItemGroup, null, categories.map(category => (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalNavigatorButton, {
key: category.name,
path: `/category/${category.name}`,
as: external_wp_components_namespaceObject.__experimentalItem,
isAction: true
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalHStack, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexBlock, null, category.label), (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: (0,external_wp_i18n_namespaceObject.isRTL)() ? chevron_left : chevron_right
})))))), categories.map(category => (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalNavigatorScreen, {
key: category.name,
path: `/category/${category.name}`
}, (0,external_wp_element_namespaceObject.createElement)(ScreenHeader, {
title: (0,external_wp_i18n_namespaceObject.__)('Back')
}), children(category))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/block-patterns-tab.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const block_patterns_tab_noop = () => {}; // Preferred order of pattern categories. Any other categories should
// be at the bottom without any re-ordering.
const patternCategoriesOrder = ['featured', 'posts', 'text', 'gallery', 'call-to-action', 'banner', 'header', 'footer'];
function usePatternsCategories(rootClientId) {
const [allPatterns, allCategories] = use_patterns_state(undefined, rootClientId);
const hasRegisteredCategory = (0,external_wp_element_namespaceObject.useCallback)(pattern => {
if (!pattern.categories || !pattern.categories.length) {
return false;
}
return pattern.categories.some(cat => allCategories.some(category => category.name === cat));
}, [allCategories]); // Remove any empty categories.
const populatedCategories = (0,external_wp_element_namespaceObject.useMemo)(() => {
const categories = allCategories.filter(category => allPatterns.some(pattern => {
var _pattern$categories;
return (_pattern$categories = pattern.categories) === null || _pattern$categories === void 0 ? void 0 : _pattern$categories.includes(category.name);
})).sort((_ref, _ref2) => {
let {
name: currentName
} = _ref;
let {
name: nextName
} = _ref2;
// The pattern categories should be ordered as follows:
// 1. The categories from `patternCategoriesOrder` in that specific order should be at the top.
// 2. The rest categories should be at the bottom without any re-ordering.
if (![currentName, nextName].some(categoryName => patternCategoriesOrder.includes(categoryName))) {
return 0;
}
if ([currentName, nextName].every(categoryName => patternCategoriesOrder.includes(categoryName))) {
return patternCategoriesOrder.indexOf(currentName) - patternCategoriesOrder.indexOf(nextName);
}
return patternCategoriesOrder.includes(currentName) ? -1 : 1;
});
if (allPatterns.some(pattern => !hasRegisteredCategory(pattern)) && !categories.find(category => category.name === 'uncategorized')) {
categories.push({
name: 'uncategorized',
label: (0,external_wp_i18n_namespaceObject._x)('Uncategorized')
});
}
return categories;
}, [allPatterns, allCategories]);
return populatedCategories;
}
function BlockPatternsCategoryDialog(_ref3) {
let {
rootClientId,
onInsert,
onHover,
category,
showTitlesAsTooltip
} = _ref3;
const container = (0,external_wp_element_namespaceObject.useRef)();
(0,external_wp_element_namespaceObject.useEffect)(() => {
const timeout = setTimeout(() => {
const [firstTabbable] = external_wp_dom_namespaceObject.focus.tabbable.find(container.current);
firstTabbable === null || firstTabbable === void 0 ? void 0 : firstTabbable.focus();
});
return () => clearTimeout(timeout);
}, [category]);
return (0,external_wp_element_namespaceObject.createElement)("div", {
ref: container,
className: "block-editor-inserter__patterns-category-dialog"
}, (0,external_wp_element_namespaceObject.createElement)(BlockPatternsCategoryPanel, {
rootClientId: rootClientId,
onInsert: onInsert,
onHover: onHover,
category: category,
showTitlesAsTooltip: showTitlesAsTooltip
}));
}
function BlockPatternsCategoryPanel(_ref4) {
let {
rootClientId,
onInsert,
onHover = block_patterns_tab_noop,
category,
showTitlesAsTooltip
} = _ref4;
const [allPatterns,, onClick] = use_patterns_state(onInsert, rootClientId);
const availableCategories = usePatternsCategories(rootClientId);
const currentCategoryPatterns = (0,external_wp_element_namespaceObject.useMemo)(() => allPatterns.filter(pattern => {
var _pattern$categories$f, _pattern$categories3;
if (category.name !== 'uncategorized') {
var _pattern$categories2;
return (_pattern$categories2 = pattern.categories) === null || _pattern$categories2 === void 0 ? void 0 : _pattern$categories2.includes(category.name);
} // The uncategorized category should show all the patterns without any category
// or with no available category.
const availablePatternCategories = (_pattern$categories$f = (_pattern$categories3 = pattern.categories) === null || _pattern$categories3 === void 0 ? void 0 : _pattern$categories3.filter(cat => availableCategories.find(availableCategory => availableCategory.name === cat))) !== null && _pattern$categories$f !== void 0 ? _pattern$categories$f : [];
return availablePatternCategories.length === 0;
}), [allPatterns, category]);
const currentShownPatterns = (0,external_wp_compose_namespaceObject.useAsyncList)(currentCategoryPatterns); // Hide block pattern preview on unmount.
(0,external_wp_element_namespaceObject.useEffect)(() => () => onHover(null), []);
if (!currentCategoryPatterns.length) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__patterns-category-panel"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__patterns-category-panel-title"
}, category.label), (0,external_wp_element_namespaceObject.createElement)("p", null, category.description), (0,external_wp_element_namespaceObject.createElement)(block_patterns_list, {
shownPatterns: currentShownPatterns,
blockPatterns: currentCategoryPatterns,
onClickPattern: onClick,
onHover: onHover,
label: category.label,
orientation: "vertical",
category: category.label,
isDraggable: true,
showTitlesAsTooltip: showTitlesAsTooltip
}));
}
function BlockPatternsTabs(_ref5) {
let {
onSelectCategory,
selectedCategory,
onInsert,
rootClientId
} = _ref5;
const [showPatternsExplorer, setShowPatternsExplorer] = (0,external_wp_element_namespaceObject.useState)(false);
const categories = usePatternsCategories(rootClientId);
const initialCategory = selectedCategory || categories[0];
const isMobile = (0,external_wp_compose_namespaceObject.useViewportMatch)('medium', '<');
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, !isMobile && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__block-patterns-tabs-container"
}, (0,external_wp_element_namespaceObject.createElement)("nav", {
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Block pattern categories')
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalItemGroup, {
role: "list",
className: "block-editor-inserter__block-patterns-tabs"
}, categories.map(category => (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalItem, {
role: "listitem",
key: category.name,
onClick: () => onSelectCategory(category),
className: category === selectedCategory ? 'block-editor-inserter__patterns-category block-editor-inserter__patterns-selected-category' : 'block-editor-inserter__patterns-category',
"aria-label": category.label,
"aria-current": category === selectedCategory ? 'true' : undefined
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalHStack, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexBlock, null, category.label), (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: chevron_right
})))), (0,external_wp_element_namespaceObject.createElement)("div", {
role: "listitem"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "block-editor-inserter__patterns-explore-button",
onClick: () => setShowPatternsExplorer(true),
variant: "secondary"
}, (0,external_wp_i18n_namespaceObject.__)('Explore all patterns')))))), isMobile && (0,external_wp_element_namespaceObject.createElement)(MobileTabNavigation, {
categories: categories
}, category => (0,external_wp_element_namespaceObject.createElement)(BlockPatternsCategoryPanel, {
onInsert: onInsert,
rootClientId: rootClientId,
category: category,
showTitlesAsTooltip: false
})), showPatternsExplorer && (0,external_wp_element_namespaceObject.createElement)(explorer, {
initialCategory: initialCategory,
patternCategories: categories,
onModalClose: () => setShowPatternsExplorer(false)
}));
}
/* harmony default export */ var block_patterns_tab = (BlockPatternsTabs);
;// CONCATENATED MODULE: external ["wp","url"]
var external_wp_url_namespaceObject = window["wp"]["url"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/reusable-blocks-tab.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ReusableBlocksList(_ref) {
let {
onHover,
onInsert,
rootClientId
} = _ref;
const [items,,, onSelectItem] = use_block_types_state(rootClientId, onInsert);
const filteredItems = (0,external_wp_element_namespaceObject.useMemo)(() => {
return items.filter(_ref2 => {
let {
category
} = _ref2;
return category === 'reusable';
});
}, [items]);
if (filteredItems.length === 0) {
return (0,external_wp_element_namespaceObject.createElement)(no_results, null);
}
return (0,external_wp_element_namespaceObject.createElement)(panel, {
title: (0,external_wp_i18n_namespaceObject.__)('Reusable blocks')
}, (0,external_wp_element_namespaceObject.createElement)(block_types_list, {
items: filteredItems,
onSelect: onSelectItem,
onHover: onHover,
label: (0,external_wp_i18n_namespaceObject.__)('Reusable blocks')
}));
} // The unwrapped component is only exported for use by unit tests.
/**
* List of reusable blocks shown in the "Reusable" tab of the inserter.
*
* @param {Object} props Component props.
* @param {?string} props.rootClientId Client id of block to insert into.
* @param {Function} props.onInsert Callback to run when item is inserted.
* @param {Function} props.onHover Callback to run when item is hovered.
*
* @return {WPComponent} The component.
*/
function ReusableBlocksTab(_ref3) {
let {
rootClientId,
onInsert,
onHover
} = _ref3;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(ReusableBlocksList, {
onHover: onHover,
onInsert: onInsert,
rootClientId: rootClientId
}), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__manage-reusable-blocks-container"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "block-editor-inserter__manage-reusable-blocks",
variant: "secondary",
href: (0,external_wp_url_namespaceObject.addQueryArgs)('edit.php', {
post_type: 'wp_block'
})
}, (0,external_wp_i18n_namespaceObject.__)('Manage Reusable blocks'))));
}
/* harmony default export */ var reusable_blocks_tab = (ReusableBlocksTab);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/media-tab/hooks.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Interface for inserter media requests.
*
* @typedef {Object} InserterMediaRequest
* @property {number} per_page How many items to fetch per page.
* @property {string} search The search term to use for filtering the results.
*/
/**
* Interface for inserter media responses. Any media resource should
* map their response to this interface, in order to create the core
* WordPress media blocks (image, video, audio).
*
* @typedef {Object} InserterMediaItem
* @property {string} title The title of the media item.
* @property {string} url The source url of the media item.
* @property {string} [previewUrl] The preview source url of the media item to display in the media list.
* @property {number} [id] The WordPress id of the media item.
* @property {number|string} [sourceId] The id of the media item from external source.
* @property {string} [alt] The alt text of the media item.
* @property {string} [caption] The caption of the media item.
*/
/**
* Fetches media items based on the provided category.
* Each media category is responsible for providing a `fetch` function.
*
* @param {Object} category The media category to fetch results for.
* @param {InserterMediaRequest} query The query args to use for the request.
* @return {InserterMediaItem[]} The media results.
*/
function useMediaResults(category) {
let query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const [mediaList, setMediaList] = (0,external_wp_element_namespaceObject.useState)();
const [isLoading, setIsLoading] = (0,external_wp_element_namespaceObject.useState)(false); // We need to keep track of the last request made because
// multiple request can be fired without knowing the order
// of resolution, and we need to ensure we are showing
// the results of the last request.
// In the future we could use AbortController to cancel previous
// requests, but we don't for now as it involves adding support
// for this to `core-data` package.
const lastRequest = (0,external_wp_element_namespaceObject.useRef)();
(0,external_wp_element_namespaceObject.useEffect)(() => {
(async () => {
var _category$fetch;
const key = JSON.stringify({
category: category.name,
...query
});
lastRequest.current = key;
setIsLoading(true);
setMediaList([]); // Empty the previous results.
const _media = await ((_category$fetch = category.fetch) === null || _category$fetch === void 0 ? void 0 : _category$fetch.call(category, query));
if (key === lastRequest.current) {
setMediaList(_media);
setIsLoading(false);
}
})();
}, [category.name, ...Object.values(query)]);
return {
mediaList,
isLoading
};
}
function useInserterMediaCategories() {
const {
inserterMediaCategories,
allowedMimeTypes,
enableOpenverseMediaCategory
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const settings = select(store).getSettings();
return {
inserterMediaCategories: settings.inserterMediaCategories,
allowedMimeTypes: settings.allowedMimeTypes,
enableOpenverseMediaCategory: settings.enableOpenverseMediaCategory
};
}, []); // The allowed `mime_types` can be altered by `upload_mimes` filter and restrict
// some of them. In this case we shouldn't add the category to the available media
// categories list in the inserter.
const allowedCategories = (0,external_wp_element_namespaceObject.useMemo)(() => {
if (!inserterMediaCategories || !allowedMimeTypes) {
return;
}
return inserterMediaCategories.filter(category => {
// Check if Openverse category is enabled.
if (!enableOpenverseMediaCategory && category.name === 'openverse') {
return false;
}
return Object.values(allowedMimeTypes).some(mimeType => mimeType.startsWith(`${category.mediaType}/`));
});
}, [inserterMediaCategories, allowedMimeTypes, enableOpenverseMediaCategory]);
return allowedCategories;
}
function useMediaCategories(rootClientId) {
const [categories, setCategories] = (0,external_wp_element_namespaceObject.useState)([]);
const {
canInsertImage,
canInsertVideo,
canInsertAudio
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
canInsertBlockType
} = select(store);
return {
canInsertImage: canInsertBlockType('core/image', rootClientId),
canInsertVideo: canInsertBlockType('core/video', rootClientId),
canInsertAudio: canInsertBlockType('core/audio', rootClientId)
};
}, [rootClientId]);
const inserterMediaCategories = useInserterMediaCategories();
(0,external_wp_element_namespaceObject.useEffect)(() => {
(async () => {
const _categories = []; // If `inserterMediaCategories` is not defined in
// block editor settings, do not show any media categories.
if (!inserterMediaCategories) {
return;
} // Loop through categories to check if they have at least one media item.
const categoriesHaveMedia = new Map(await Promise.all(inserterMediaCategories.map(async category => {
// Some sources are external and we don't need to make a request.
if (category.isExternalResource) {
return [category.name, true];
}
let results = [];
try {
results = await category.fetch({
per_page: 1
});
} catch (e) {// If the request fails, we shallow the error and just don't show
// the category, in order to not break the media tab.
}
return [category.name, !!results.length];
}))); // We need to filter out categories that don't have any media items or
// whose corresponding block type is not allowed to be inserted, based
// on the category's `mediaType`.
const canInsertMediaType = {
image: canInsertImage,
video: canInsertVideo,
audio: canInsertAudio
};
inserterMediaCategories.forEach(category => {
if (canInsertMediaType[category.mediaType] && categoriesHaveMedia.get(category.name)) {
_categories.push(category);
}
});
if (!!_categories.length) {
setCategories(_categories);
}
})();
}, [canInsertImage, canInsertVideo, canInsertAudio, inserterMediaCategories]);
return categories;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/more-vertical.js
/**
* WordPress dependencies
*/
const moreVertical = (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: "M13 19h-2v-2h2v2zm0-6h-2v-2h2v2zm0-6h-2V5h2v2z"
}));
/* harmony default export */ var more_vertical = (moreVertical);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/external.js
/**
* WordPress dependencies
*/
const external = (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: "M18.2 17c0 .7-.6 1.2-1.2 1.2H7c-.7 0-1.2-.6-1.2-1.2V7c0-.7.6-1.2 1.2-1.2h3.2V4.2H7C5.5 4.2 4.2 5.5 4.2 7v10c0 1.5 1.2 2.8 2.8 2.8h10c1.5 0 2.8-1.2 2.8-2.8v-3.6h-1.5V17zM14.9 3v1.5h3.7l-6.4 6.4 1.1 1.1 6.4-6.4v3.7h1.5V3h-6.3z"
}));
/* harmony default export */ var library_external = (external);
;// CONCATENATED MODULE: external ["wp","blob"]
var external_wp_blob_namespaceObject = window["wp"]["blob"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/media-tab/utils.js
/**
* WordPress dependencies
*/
const mediaTypeTag = {
image: 'img',
video: 'video',
audio: 'audio'
};
/** @typedef {import('./hooks').InserterMediaItem} InserterMediaItem */
/**
* Creates a block and a preview element from a media object.
*
* @param {InserterMediaItem} media The media object to create the block from.
* @param {('image'|'audio'|'video')} mediaType The media type to create the block for.
* @return {[WPBlock, JSX.Element]} An array containing the block and the preview element.
*/
function getBlockAndPreviewFromMedia(media, mediaType) {
// Add the common attributes between the different media types.
const attributes = {
id: media.id || undefined,
caption: media.caption || undefined
};
const mediaSrc = media.url;
const alt = media.alt || undefined;
if (mediaType === 'image') {
attributes.url = mediaSrc;
attributes.alt = alt;
} else if (['video', 'audio'].includes(mediaType)) {
attributes.src = mediaSrc;
}
const PreviewTag = mediaTypeTag[mediaType];
const preview = (0,external_wp_element_namespaceObject.createElement)(PreviewTag, {
src: media.previewUrl || mediaSrc,
alt: alt,
controls: mediaType === 'audio' ? true : undefined,
inert: "true",
onError: _ref => {
let {
currentTarget
} = _ref;
// Fall back to the media source if the preview cannot be loaded.
if (currentTarget.src === media.previewUrl) {
currentTarget.src = mediaSrc;
}
}
});
return [(0,external_wp_blocks_namespaceObject.createBlock)(`core/${mediaType}`, attributes), preview];
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/media-tab/media-preview.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const ALLOWED_MEDIA_TYPES = ['image'];
const MAXIMUM_TITLE_LENGTH = 25;
const MEDIA_OPTIONS_POPOVER_PROPS = {
position: 'bottom left',
className: 'block-editor-inserter__media-list__item-preview-options__popover'
};
function MediaPreviewOptions(_ref) {
let {
category,
media
} = _ref;
if (!category.getReportUrl) {
return null;
}
const reportUrl = category.getReportUrl(media);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.DropdownMenu, {
className: "block-editor-inserter__media-list__item-preview-options",
label: (0,external_wp_i18n_namespaceObject.__)('Options'),
popoverProps: MEDIA_OPTIONS_POPOVER_PROPS,
icon: more_vertical
}, () => (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
onClick: () => window.open(reportUrl, '_blank').focus(),
icon: library_external
}, (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: The media type to report e.g: "image", "video", "audio" */
(0,external_wp_i18n_namespaceObject.__)('Report %s'), category.mediaType))));
}
function InsertExternalImageModal(_ref2) {
let {
onClose,
onSubmit
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Modal, {
title: (0,external_wp_i18n_namespaceObject.__)('Insert external image'),
onRequestClose: onClose,
className: "block-editor-inserter-media-tab-media-preview-inserter-external-image-modal"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalVStack, {
spacing: 3
}, (0,external_wp_element_namespaceObject.createElement)("p", null, (0,external_wp_i18n_namespaceObject.__)('This image cannot be uploaded to your Media Library, but it can still be inserted as an external image.')), (0,external_wp_element_namespaceObject.createElement)("p", null, (0,external_wp_i18n_namespaceObject.__)('External images can be removed by the external provider without warning and could even have legal compliance issues related to privacy legislation.'))), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Flex, {
className: "block-editor-block-lock-modal__actions",
justify: "flex-end",
expanded: false
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexItem, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "tertiary",
onClick: onClose
}, (0,external_wp_i18n_namespaceObject.__)('Cancel'))), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexItem, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "primary",
onClick: onSubmit
}, (0,external_wp_i18n_namespaceObject.__)('Insert')))));
}
function MediaPreview(_ref3) {
var _media$title;
let {
media,
onClick,
composite,
category
} = _ref3;
const [showExternalUploadModal, setShowExternalUploadModal] = (0,external_wp_element_namespaceObject.useState)(false);
const [isHovered, setIsHovered] = (0,external_wp_element_namespaceObject.useState)(false);
const [isInserting, setIsInserting] = (0,external_wp_element_namespaceObject.useState)(false);
const [block, preview] = (0,external_wp_element_namespaceObject.useMemo)(() => getBlockAndPreviewFromMedia(media, category.mediaType), [media, category.mediaType]);
const {
createErrorNotice,
createSuccessNotice
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_notices_namespaceObject.store);
const mediaUpload = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).getSettings().mediaUpload, []);
const onMediaInsert = (0,external_wp_element_namespaceObject.useCallback)(previewBlock => {
// Prevent multiple uploads when we're in the process of inserting.
if (isInserting) {
return;
}
const clonedBlock = (0,external_wp_blocks_namespaceObject.cloneBlock)(previewBlock);
const {
id,
url,
caption
} = clonedBlock.attributes; // Media item already exists in library, so just insert it.
if (!!id) {
onClick(clonedBlock);
return;
}
setIsInserting(true); // Media item does not exist in library, so try to upload it.
// Fist fetch the image data. This may fail if the image host
// doesn't allow CORS with the domain.
// If this happens, we insert the image block using the external
// URL and let the user know about the possible implications.
window.fetch(url).then(response => response.blob()).then(blob => {
mediaUpload({
filesList: [blob],
additionalData: {
caption
},
onFileChange(_ref4) {
let [img] = _ref4;
if ((0,external_wp_blob_namespaceObject.isBlobURL)(img.url)) {
return;
}
onClick({ ...clonedBlock,
attributes: { ...clonedBlock.attributes,
id: img.id,
url: img.url
}
});
createSuccessNotice((0,external_wp_i18n_namespaceObject.__)('Image uploaded and inserted.'), {
type: 'snackbar'
});
setIsInserting(false);
},
allowedTypes: ALLOWED_MEDIA_TYPES,
onError(message) {
createErrorNotice(message, {
type: 'snackbar'
});
setIsInserting(false);
}
});
}).catch(() => {
setShowExternalUploadModal(true);
setIsInserting(false);
});
}, [isInserting, onClick, mediaUpload, createErrorNotice, createSuccessNotice]);
const title = ((_media$title = media.title) === null || _media$title === void 0 ? void 0 : _media$title.rendered) || media.title;
let truncatedTitle;
if (title.length > MAXIMUM_TITLE_LENGTH) {
const omission = '...';
truncatedTitle = title.slice(0, MAXIMUM_TITLE_LENGTH - omission.length) + omission;
}
const onMouseEnter = (0,external_wp_element_namespaceObject.useCallback)(() => setIsHovered(true), []);
const onMouseLeave = (0,external_wp_element_namespaceObject.useCallback)(() => setIsHovered(false), []);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(inserter_draggable_blocks, {
isEnabled: true,
blocks: [block]
}, _ref5 => {
let {
draggable,
onDragStart,
onDragEnd
} = _ref5;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('block-editor-inserter__media-list__list-item', {
'is-hovered': isHovered
}),
draggable: draggable,
onDragStart: onDragStart,
onDragEnd: onDragEnd
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Tooltip, {
text: truncatedTitle || title
}, (0,external_wp_element_namespaceObject.createElement)("div", {
onMouseEnter: onMouseEnter,
onMouseLeave: onMouseLeave
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableCompositeItem, _extends({
role: "option",
as: "div"
}, composite, {
className: "block-editor-inserter__media-list__item",
onClick: () => onMediaInsert(block),
"aria-label": title
}), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__media-list__item-preview"
}, preview, isInserting && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__media-list__item-preview-spinner"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Spinner, null)))), !isInserting && (0,external_wp_element_namespaceObject.createElement)(MediaPreviewOptions, {
category: category,
media: media
}))));
}), showExternalUploadModal && (0,external_wp_element_namespaceObject.createElement)(InsertExternalImageModal, {
onClose: () => setShowExternalUploadModal(false),
onSubmit: () => {
onClick((0,external_wp_blocks_namespaceObject.cloneBlock)(block));
createSuccessNotice((0,external_wp_i18n_namespaceObject.__)('Image inserted.'), {
type: 'snackbar'
});
setShowExternalUploadModal(false);
}
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/media-tab/media-list.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function MediaList(_ref) {
let {
mediaList,
category,
onClick,
label = (0,external_wp_i18n_namespaceObject.__)('Media List')
} = _ref;
const composite = (0,external_wp_components_namespaceObject.__unstableUseCompositeState)();
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableComposite, _extends({}, composite, {
role: "listbox",
className: "block-editor-inserter__media-list",
"aria-label": label
}), mediaList.map((media, index) => (0,external_wp_element_namespaceObject.createElement)(MediaPreview, {
key: media.id || media.sourceId || index,
media: media,
category: category,
onClick: onClick,
composite: composite
})));
}
/* harmony default export */ var media_list = (MediaList);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/hooks/use-debounced-input.js
/**
* WordPress dependencies
*/
function useDebouncedInput() {
let defaultValue = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
const [input, setInput] = (0,external_wp_element_namespaceObject.useState)(defaultValue);
const [debounced, setter] = (0,external_wp_element_namespaceObject.useState)(defaultValue);
const setDebounced = (0,external_wp_compose_namespaceObject.useDebounce)(setter, 250);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (debounced !== input) {
setDebounced(input);
}
}, [debounced, input]);
return [input, setInput, debounced];
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/media-tab/media-panel.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const INITIAL_MEDIA_ITEMS_PER_PAGE = 10;
function MediaCategoryDialog(_ref) {
let {
rootClientId,
onInsert,
category
} = _ref;
const container = (0,external_wp_element_namespaceObject.useRef)();
(0,external_wp_element_namespaceObject.useEffect)(() => {
const timeout = setTimeout(() => {
const [firstTabbable] = external_wp_dom_namespaceObject.focus.tabbable.find(container.current);
firstTabbable === null || firstTabbable === void 0 ? void 0 : firstTabbable.focus();
});
return () => clearTimeout(timeout);
}, [category]);
return (0,external_wp_element_namespaceObject.createElement)("div", {
ref: container,
className: "block-editor-inserter__media-dialog"
}, (0,external_wp_element_namespaceObject.createElement)(MediaCategoryPanel, {
rootClientId: rootClientId,
onInsert: onInsert,
category: category
}));
}
function MediaCategoryPanel(_ref2) {
let {
rootClientId,
onInsert,
category
} = _ref2;
const [search, setSearch, debouncedSearch] = useDebouncedInput();
const {
mediaList,
isLoading
} = useMediaResults(category, {
per_page: !!debouncedSearch ? 20 : INITIAL_MEDIA_ITEMS_PER_PAGE,
search: debouncedSearch
});
const baseCssClass = 'block-editor-inserter__media-panel';
const searchLabel = category.labels.search_items || (0,external_wp_i18n_namespaceObject.__)('Search');
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: baseCssClass
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SearchControl, {
className: `${baseCssClass}-search`,
onChange: setSearch,
value: search,
label: searchLabel,
placeholder: searchLabel
}), isLoading && (0,external_wp_element_namespaceObject.createElement)("div", {
className: `${baseCssClass}-spinner`
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Spinner, null)), !isLoading && !(mediaList !== null && mediaList !== void 0 && mediaList.length) && (0,external_wp_element_namespaceObject.createElement)(no_results, null), !isLoading && !!(mediaList !== null && mediaList !== void 0 && mediaList.length) && (0,external_wp_element_namespaceObject.createElement)(media_list, {
rootClientId: rootClientId,
onClick: onInsert,
mediaList: mediaList,
category: category
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/media-upload/check.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function MediaUploadCheck(_ref) {
let {
fallback = null,
children
} = _ref;
const hasUploadPermissions = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getSettings
} = select(store);
return !!getSettings().mediaUpload;
}, []);
return hasUploadPermissions ? children : fallback;
}
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/media-upload/README.md
*/
/* harmony default export */ var check = (MediaUploadCheck);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/media-upload/index.js
/**
* WordPress dependencies
*/
/**
* This is a placeholder for the media upload component necessary to make it possible to provide
* an integration with the core blocks that handle media files. By default it renders nothing but
* it provides a way to have it overridden with the `editor.MediaUpload` filter.
*
* @return {WPComponent} The component to be rendered.
*/
const MediaUpload = () => null;
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/media-upload/README.md
*/
/* harmony default export */ var media_upload = ((0,external_wp_components_namespaceObject.withFilters)('editor.MediaUpload')(MediaUpload));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/media-tab/media-tab.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const media_tab_ALLOWED_MEDIA_TYPES = ['image', 'video', 'audio'];
function MediaTab(_ref) {
let {
rootClientId,
selectedCategory,
onSelectCategory,
onInsert
} = _ref;
const mediaCategories = useMediaCategories(rootClientId);
const isMobile = (0,external_wp_compose_namespaceObject.useViewportMatch)('medium', '<');
const baseCssClass = 'block-editor-inserter__media-tabs';
const onSelectMedia = (0,external_wp_element_namespaceObject.useCallback)(media => {
if (!(media !== null && media !== void 0 && media.url)) {
return;
}
const [block] = getBlockAndPreviewFromMedia(media, media.type);
onInsert(block);
}, [onInsert]);
const mobileMediaCategories = (0,external_wp_element_namespaceObject.useMemo)(() => mediaCategories.map(mediaCategory => ({ ...mediaCategory,
label: mediaCategory.labels.name
})), [mediaCategories]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, !isMobile && (0,external_wp_element_namespaceObject.createElement)("div", {
className: `${baseCssClass}-container`
}, (0,external_wp_element_namespaceObject.createElement)("nav", {
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Media categories')
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalItemGroup, {
role: "list",
className: baseCssClass
}, mediaCategories.map(mediaCategory => (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalItem, {
role: "listitem",
key: mediaCategory.name,
onClick: () => onSelectCategory(mediaCategory),
className: classnames_default()(`${baseCssClass}__media-category`, {
'is-selected': selectedCategory === mediaCategory
}),
"aria-label": mediaCategory.labels.name,
"aria-current": mediaCategory === selectedCategory ? 'true' : undefined
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalHStack, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexBlock, null, mediaCategory.labels.name), (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: chevron_right
})))), (0,external_wp_element_namespaceObject.createElement)("div", {
role: "listitem"
}, (0,external_wp_element_namespaceObject.createElement)(check, null, (0,external_wp_element_namespaceObject.createElement)(media_upload, {
multiple: false,
onSelect: onSelectMedia,
allowedTypes: media_tab_ALLOWED_MEDIA_TYPES,
render: _ref2 => {
let {
open
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
onClick: event => {
// Safari doesn't emit a focus event on button elements when
// clicked and we need to manually focus the button here.
// The reason is that core's Media Library modal explicitly triggers a
// focus event and therefore a `blur` event is triggered on a different
// element, which doesn't contain the `data-unstable-ignore-focus-outside-for-relatedtarget`
// attribute making the Inserter dialog to close.
event.target.focus();
open();
},
className: "block-editor-inserter__media-library-button",
variant: "secondary",
"data-unstable-ignore-focus-outside-for-relatedtarget": ".media-modal"
}, (0,external_wp_i18n_namespaceObject.__)('Open Media Library'));
}
})))))), isMobile && (0,external_wp_element_namespaceObject.createElement)(MobileTabNavigation, {
categories: mobileMediaCategories
}, category => (0,external_wp_element_namespaceObject.createElement)(MediaCategoryPanel, {
onInsert: onInsert,
rootClientId: rootClientId,
category: category
})));
}
/* harmony default export */ var media_tab = (MediaTab);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter-menu-extension/index.js
/**
* WordPress dependencies
*/
const {
Fill: __unstableInserterMenuExtension,
Slot
} = (0,external_wp_components_namespaceObject.createSlotFill)('__unstableInserterMenuExtension');
__unstableInserterMenuExtension.Slot = Slot;
/* harmony default export */ var inserter_menu_extension = (__unstableInserterMenuExtension);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/search-results.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const search_results_INITIAL_INSERTER_RESULTS = 9;
/**
* Shared reference to an empty array for cases where it is important to avoid
* returning a new array reference on every invocation and rerendering the component.
*
* @type {Array}
*/
const search_results_EMPTY_ARRAY = [];
function InserterSearchResults(_ref) {
let {
filterValue,
onSelect,
onHover,
rootClientId,
clientId,
isAppender,
__experimentalInsertionIndex,
maxBlockPatterns,
maxBlockTypes,
showBlockDirectory = false,
isDraggable = true,
shouldFocusBlock = true,
prioritizePatterns,
selectBlockOnInsert,
orderInitialBlockItems
} = _ref;
const debouncedSpeak = (0,external_wp_compose_namespaceObject.useDebounce)(external_wp_a11y_namespaceObject.speak, 500);
const [destinationRootClientId, onInsertBlocks] = use_insertion_point({
onSelect,
rootClientId,
clientId,
isAppender,
insertionIndex: __experimentalInsertionIndex,
shouldFocusBlock,
selectBlockOnInsert
});
const [blockTypes, blockTypeCategories, blockTypeCollections, onSelectBlockType] = use_block_types_state(destinationRootClientId, onInsertBlocks);
const [patterns,, onSelectBlockPattern] = use_patterns_state(onInsertBlocks, destinationRootClientId);
const filteredBlockPatterns = (0,external_wp_element_namespaceObject.useMemo)(() => {
if (maxBlockPatterns === 0) {
return [];
}
const results = searchItems(patterns, filterValue);
return maxBlockPatterns !== undefined ? results.slice(0, maxBlockPatterns) : results;
}, [filterValue, patterns, maxBlockPatterns]);
let maxBlockTypesToShow = maxBlockTypes;
if (prioritizePatterns && filteredBlockPatterns.length > 2) {
maxBlockTypesToShow = 0;
}
const filteredBlockTypes = (0,external_wp_element_namespaceObject.useMemo)(() => {
if (maxBlockTypesToShow === 0) {
return [];
}
let orderedItems = orderBy(blockTypes, 'frecency', 'desc');
if (!filterValue && orderInitialBlockItems) {
orderedItems = orderInitialBlockItems(orderedItems);
}
const results = searchBlockItems(orderedItems, blockTypeCategories, blockTypeCollections, filterValue);
return maxBlockTypesToShow !== undefined ? results.slice(0, maxBlockTypesToShow) : results;
}, [filterValue, blockTypes, blockTypeCategories, blockTypeCollections, maxBlockTypes, orderInitialBlockItems]); // Announce search results on change.
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (!filterValue) {
return;
}
const count = filteredBlockTypes.length + filteredBlockPatterns.length;
const resultsFoundMessage = (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %d: number of results. */
(0,external_wp_i18n_namespaceObject._n)('%d result found.', '%d results found.', count), count);
debouncedSpeak(resultsFoundMessage);
}, [filterValue, debouncedSpeak]);
const currentShownBlockTypes = (0,external_wp_compose_namespaceObject.useAsyncList)(filteredBlockTypes, {
step: search_results_INITIAL_INSERTER_RESULTS
});
const currentShownPatterns = (0,external_wp_compose_namespaceObject.useAsyncList)(currentShownBlockTypes.length === filteredBlockTypes.length ? filteredBlockPatterns : search_results_EMPTY_ARRAY);
const hasItems = filteredBlockTypes.length > 0 || filteredBlockPatterns.length > 0;
const blocksUI = !!filteredBlockTypes.length && (0,external_wp_element_namespaceObject.createElement)(panel, {
title: (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.VisuallyHidden, null, (0,external_wp_i18n_namespaceObject.__)('Blocks'))
}, (0,external_wp_element_namespaceObject.createElement)(block_types_list, {
items: currentShownBlockTypes,
onSelect: onSelectBlockType,
onHover: onHover,
label: (0,external_wp_i18n_namespaceObject.__)('Blocks'),
isDraggable: isDraggable
}));
const patternsUI = !!filteredBlockPatterns.length && (0,external_wp_element_namespaceObject.createElement)(panel, {
title: (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.VisuallyHidden, null, (0,external_wp_i18n_namespaceObject.__)('Block Patterns'))
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__quick-inserter-patterns"
}, (0,external_wp_element_namespaceObject.createElement)(block_patterns_list, {
shownPatterns: currentShownPatterns,
blockPatterns: filteredBlockPatterns,
onClickPattern: onSelectBlockPattern,
onHover: onHover,
isDraggable: isDraggable
})));
return (0,external_wp_element_namespaceObject.createElement)(inserter_listbox, null, !showBlockDirectory && !hasItems && (0,external_wp_element_namespaceObject.createElement)(no_results, null), prioritizePatterns ? patternsUI : blocksUI, !!filteredBlockTypes.length && !!filteredBlockPatterns.length && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__quick-inserter-separator"
}), prioritizePatterns ? blocksUI : patternsUI, showBlockDirectory && (0,external_wp_element_namespaceObject.createElement)(inserter_menu_extension.Slot, {
fillProps: {
onSelect: onSelectBlockType,
onHover,
filterValue,
hasItems,
rootClientId: destinationRootClientId
}
}, fills => {
if (fills.length) {
return fills;
}
if (!hasItems) {
return (0,external_wp_element_namespaceObject.createElement)(no_results, null);
}
return null;
}));
}
/* harmony default export */ var search_results = (InserterSearchResults);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/tabs.js
/**
* WordPress dependencies
*/
const blocksTab = {
name: 'blocks',
/* translators: Blocks tab title in the block inserter. */
title: (0,external_wp_i18n_namespaceObject.__)('Blocks')
};
const patternsTab = {
name: 'patterns',
/* translators: Patterns tab title in the block inserter. */
title: (0,external_wp_i18n_namespaceObject.__)('Patterns')
};
const reusableBlocksTab = {
name: 'reusable',
/* translators: Reusable blocks tab title in the block inserter. */
title: (0,external_wp_i18n_namespaceObject.__)('Reusable'),
icon: library_symbol
};
const mediaTab = {
name: 'media',
/* translators: Media tab title in the block inserter. */
title: (0,external_wp_i18n_namespaceObject.__)('Media')
};
function InserterTabs(_ref) {
let {
children,
showPatterns = false,
showReusableBlocks = false,
showMedia = false,
onSelect,
prioritizePatterns
} = _ref;
const tabs = (0,external_wp_element_namespaceObject.useMemo)(() => {
const tempTabs = [];
if (prioritizePatterns && showPatterns) {
tempTabs.push(patternsTab);
}
tempTabs.push(blocksTab);
if (!prioritizePatterns && showPatterns) {
tempTabs.push(patternsTab);
}
if (showMedia) {
tempTabs.push(mediaTab);
}
if (showReusableBlocks) {
tempTabs.push(reusableBlocksTab);
}
return tempTabs;
}, [prioritizePatterns, blocksTab, showPatterns, patternsTab, showReusableBlocks, showMedia, reusableBlocksTab]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.TabPanel, {
className: "block-editor-inserter__tabs",
tabs: tabs,
onSelect: onSelect
}, children);
}
/* harmony default export */ var tabs = (InserterTabs);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/menu.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function InserterMenu(_ref, ref) {
let {
rootClientId,
clientId,
isAppender,
__experimentalInsertionIndex,
onSelect,
showInserterHelpPanel,
showMostUsedBlocks,
__experimentalFilterValue = '',
shouldFocusBlock = true,
prioritizePatterns
} = _ref;
const [filterValue, setFilterValue, delayedFilterValue] = useDebouncedInput(__experimentalFilterValue);
const [hoveredItem, setHoveredItem] = (0,external_wp_element_namespaceObject.useState)(null);
const [selectedPatternCategory, setSelectedPatternCategory] = (0,external_wp_element_namespaceObject.useState)(null);
const [selectedMediaCategory, setSelectedMediaCategory] = (0,external_wp_element_namespaceObject.useState)(null);
const [selectedTab, setSelectedTab] = (0,external_wp_element_namespaceObject.useState)(null);
const [destinationRootClientId, onInsertBlocks, onToggleInsertionPoint] = use_insertion_point({
rootClientId,
clientId,
isAppender,
insertionIndex: __experimentalInsertionIndex,
shouldFocusBlock
});
const {
showPatterns,
inserterItems
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
__experimentalGetAllowedPatterns,
getInserterItems
} = select(store);
return {
showPatterns: !!__experimentalGetAllowedPatterns(destinationRootClientId).length,
inserterItems: getInserterItems(destinationRootClientId)
};
}, [destinationRootClientId]);
const hasReusableBlocks = (0,external_wp_element_namespaceObject.useMemo)(() => {
return inserterItems.some(_ref2 => {
let {
category
} = _ref2;
return category === 'reusable';
});
}, [inserterItems]);
const mediaCategories = useMediaCategories(destinationRootClientId);
const showMedia = !!mediaCategories.length;
const onInsert = (0,external_wp_element_namespaceObject.useCallback)((blocks, meta, shouldForceFocusBlock) => {
onInsertBlocks(blocks, meta, shouldForceFocusBlock);
onSelect();
}, [onInsertBlocks, onSelect]);
const onInsertPattern = (0,external_wp_element_namespaceObject.useCallback)((blocks, patternName) => {
onInsertBlocks(blocks, {
patternName
});
onSelect();
}, [onInsertBlocks, onSelect]);
const onHover = (0,external_wp_element_namespaceObject.useCallback)(item => {
onToggleInsertionPoint(!!item);
setHoveredItem(item);
}, [onToggleInsertionPoint, setHoveredItem]);
const onHoverPattern = (0,external_wp_element_namespaceObject.useCallback)(item => {
onToggleInsertionPoint(!!item);
}, [onToggleInsertionPoint]);
const onClickPatternCategory = (0,external_wp_element_namespaceObject.useCallback)(patternCategory => {
setSelectedPatternCategory(patternCategory);
}, [setSelectedPatternCategory]);
const blocksTab = (0,external_wp_element_namespaceObject.useMemo)(() => (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__block-list"
}, (0,external_wp_element_namespaceObject.createElement)(block_types_tab, {
rootClientId: destinationRootClientId,
onInsert: onInsert,
onHover: onHover,
showMostUsedBlocks: showMostUsedBlocks
})), showInserterHelpPanel && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__tips"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.VisuallyHidden, {
as: "h2"
}, (0,external_wp_i18n_namespaceObject.__)('A tip for using the block editor')), (0,external_wp_element_namespaceObject.createElement)(tips, null))), [destinationRootClientId, onInsert, onHover, delayedFilterValue, showMostUsedBlocks, showInserterHelpPanel]);
const patternsTab = (0,external_wp_element_namespaceObject.useMemo)(() => (0,external_wp_element_namespaceObject.createElement)(block_patterns_tab, {
rootClientId: destinationRootClientId,
onInsert: onInsertPattern,
onSelectCategory: onClickPatternCategory,
selectedCategory: selectedPatternCategory
}), [destinationRootClientId, onInsertPattern, onClickPatternCategory, selectedPatternCategory]);
const reusableBlocksTab = (0,external_wp_element_namespaceObject.useMemo)(() => (0,external_wp_element_namespaceObject.createElement)(reusable_blocks_tab, {
rootClientId: destinationRootClientId,
onInsert: onInsert,
onHover: onHover
}), [destinationRootClientId, onInsert, onHover]);
const mediaTab = (0,external_wp_element_namespaceObject.useMemo)(() => (0,external_wp_element_namespaceObject.createElement)(media_tab, {
rootClientId: destinationRootClientId,
selectedCategory: selectedMediaCategory,
onSelectCategory: setSelectedMediaCategory,
onInsert: onInsert
}), [destinationRootClientId, onInsert, selectedMediaCategory, setSelectedMediaCategory]);
const getCurrentTab = (0,external_wp_element_namespaceObject.useCallback)(tab => {
if (tab.name === 'blocks') {
return blocksTab;
} else if (tab.name === 'patterns') {
return patternsTab;
} else if (tab.name === 'reusable') {
return reusableBlocksTab;
} else if (tab.name === 'media') {
return mediaTab;
}
}, [blocksTab, patternsTab, reusableBlocksTab, mediaTab]);
const searchRef = (0,external_wp_element_namespaceObject.useRef)();
(0,external_wp_element_namespaceObject.useImperativeHandle)(ref, () => ({
focusSearch: () => {
searchRef.current.focus();
}
}));
const showPatternPanel = selectedTab === 'patterns' && !delayedFilterValue && selectedPatternCategory;
const showAsTabs = !delayedFilterValue && (showPatterns || hasReusableBlocks || showMedia);
const showMediaPanel = selectedTab === 'media' && !delayedFilterValue && selectedMediaCategory;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__menu"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('block-editor-inserter__main-area', {
'show-as-tabs': showAsTabs
})
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SearchControl, {
__nextHasNoMarginBottom: true,
className: "block-editor-inserter__search",
onChange: value => {
if (hoveredItem) setHoveredItem(null);
setFilterValue(value);
},
value: filterValue,
label: (0,external_wp_i18n_namespaceObject.__)('Search for blocks and patterns'),
placeholder: (0,external_wp_i18n_namespaceObject.__)('Search'),
ref: searchRef
}), !!delayedFilterValue && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__no-tab-container"
}, (0,external_wp_element_namespaceObject.createElement)(search_results, {
filterValue: delayedFilterValue,
onSelect: onSelect,
onHover: onHover,
rootClientId: rootClientId,
clientId: clientId,
isAppender: isAppender,
__experimentalInsertionIndex: __experimentalInsertionIndex,
showBlockDirectory: true,
shouldFocusBlock: shouldFocusBlock
})), showAsTabs && (0,external_wp_element_namespaceObject.createElement)(tabs, {
showPatterns: showPatterns,
showReusableBlocks: hasReusableBlocks,
showMedia: showMedia,
prioritizePatterns: prioritizePatterns,
onSelect: setSelectedTab
}, getCurrentTab), !delayedFilterValue && !showAsTabs && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__no-tab-container"
}, blocksTab)), showMediaPanel && (0,external_wp_element_namespaceObject.createElement)(MediaCategoryDialog, {
rootClientId: destinationRootClientId,
onInsert: onInsert,
category: selectedMediaCategory
}), showInserterHelpPanel && hoveredItem && (0,external_wp_element_namespaceObject.createElement)(preview_panel, {
item: hoveredItem
}), showPatternPanel && (0,external_wp_element_namespaceObject.createElement)(BlockPatternsCategoryDialog, {
rootClientId: destinationRootClientId,
onInsert: onInsertPattern,
onHover: onHoverPattern,
category: selectedPatternCategory,
showTitlesAsTooltip: true
}));
}
/* harmony default export */ var menu = ((0,external_wp_element_namespaceObject.forwardRef)(InserterMenu));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/quick-inserter.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const SEARCH_THRESHOLD = 6;
const SHOWN_BLOCK_TYPES = 6;
const SHOWN_BLOCK_PATTERNS = 2;
const SHOWN_BLOCK_PATTERNS_WITH_PRIORITIZATION = 4;
function QuickInserter(_ref) {
let {
onSelect,
rootClientId,
clientId,
isAppender,
prioritizePatterns,
selectBlockOnInsert,
orderInitialBlockItems
} = _ref;
const [filterValue, setFilterValue] = (0,external_wp_element_namespaceObject.useState)('');
const [destinationRootClientId, onInsertBlocks] = use_insertion_point({
onSelect,
rootClientId,
clientId,
isAppender,
selectBlockOnInsert
});
const [blockTypes] = use_block_types_state(destinationRootClientId, onInsertBlocks);
const [patterns] = use_patterns_state(onInsertBlocks, destinationRootClientId);
const {
setInserterIsOpened,
insertionIndex
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getSettings,
getBlockIndex,
getBlockCount
} = select(store);
const settings = getSettings();
const index = getBlockIndex(clientId);
const blockCount = getBlockCount();
return {
setInserterIsOpened: settings.__experimentalSetIsInserterOpened,
insertionIndex: index === -1 ? blockCount : index
};
}, [clientId]);
const showPatterns = patterns.length && (!!filterValue || prioritizePatterns);
const showSearch = showPatterns && patterns.length > SEARCH_THRESHOLD || blockTypes.length > SEARCH_THRESHOLD;
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (setInserterIsOpened) {
setInserterIsOpened(false);
}
}, [setInserterIsOpened]); // When clicking Browse All select the appropriate block so as
// the insertion point can work as expected.
const onBrowseAll = () => {
setInserterIsOpened({
rootClientId,
insertionIndex,
filterValue
});
};
let maxBlockPatterns = 0;
if (showPatterns) {
maxBlockPatterns = prioritizePatterns ? SHOWN_BLOCK_PATTERNS_WITH_PRIORITIZATION : SHOWN_BLOCK_PATTERNS;
}
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('block-editor-inserter__quick-inserter', {
'has-search': showSearch,
'has-expand': setInserterIsOpened
})
}, showSearch && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SearchControl, {
__nextHasNoMarginBottom: true,
className: "block-editor-inserter__search",
value: filterValue,
onChange: value => {
setFilterValue(value);
},
label: (0,external_wp_i18n_namespaceObject.__)('Search for blocks and patterns'),
placeholder: (0,external_wp_i18n_namespaceObject.__)('Search')
}), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inserter__quick-inserter-results"
}, (0,external_wp_element_namespaceObject.createElement)(search_results, {
filterValue: filterValue,
onSelect: onSelect,
rootClientId: rootClientId,
clientId: clientId,
isAppender: isAppender,
maxBlockPatterns: maxBlockPatterns,
maxBlockTypes: SHOWN_BLOCK_TYPES,
isDraggable: false,
prioritizePatterns: prioritizePatterns,
selectBlockOnInsert: selectBlockOnInsert,
orderInitialBlockItems: orderInitialBlockItems
})), setInserterIsOpened && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "block-editor-inserter__quick-inserter-expand",
onClick: onBrowseAll,
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Browse all. This will open the main inserter panel in the editor toolbar.')
}, (0,external_wp_i18n_namespaceObject.__)('Browse all')));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const defaultRenderToggle = _ref => {
let {
onToggle,
disabled,
isOpen,
blockTitle,
hasSingleBlockType,
toggleProps = {},
prioritizePatterns
} = _ref;
const {
as: Wrapper = external_wp_components_namespaceObject.Button,
label: labelProp,
onClick,
...rest
} = toggleProps;
let label = labelProp;
if (!label && hasSingleBlockType) {
label = (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: the name of the block when there is only one
(0,external_wp_i18n_namespaceObject._x)('Add %s', 'directly add the only allowed block'), blockTitle);
} else if (!label && prioritizePatterns) {
label = (0,external_wp_i18n_namespaceObject.__)('Add pattern');
} else if (!label) {
label = (0,external_wp_i18n_namespaceObject._x)('Add block', 'Generic label for block inserter button');
} // Handle both onClick functions from the toggle and the parent component.
function handleClick(event) {
if (onToggle) {
onToggle(event);
}
if (onClick) {
onClick(event);
}
}
return (0,external_wp_element_namespaceObject.createElement)(Wrapper, _extends({
icon: library_plus,
label: label,
tooltipPosition: "bottom",
onClick: handleClick,
className: "block-editor-inserter__toggle",
"aria-haspopup": !hasSingleBlockType ? 'true' : false,
"aria-expanded": !hasSingleBlockType ? isOpen : false,
disabled: disabled
}, rest));
};
class PrivateInserter extends external_wp_element_namespaceObject.Component {
constructor() {
super(...arguments);
this.onToggle = this.onToggle.bind(this);
this.renderToggle = this.renderToggle.bind(this);
this.renderContent = this.renderContent.bind(this);
}
onToggle(isOpen) {
const {
onToggle
} = this.props; // Surface toggle callback to parent component.
if (onToggle) {
onToggle(isOpen);
}
}
/**
* Render callback to display Dropdown toggle element.
*
* @param {Object} options
* @param {Function} options.onToggle Callback to invoke when toggle is
* pressed.
* @param {boolean} options.isOpen Whether dropdown is currently open.
*
* @return {WPElement} Dropdown toggle element.
*/
renderToggle(_ref2) {
let {
onToggle,
isOpen
} = _ref2;
const {
disabled,
blockTitle,
hasSingleBlockType,
directInsertBlock,
toggleProps,
hasItems,
renderToggle = defaultRenderToggle,
prioritizePatterns
} = this.props;
return renderToggle({
onToggle,
isOpen,
disabled: disabled || !hasItems,
blockTitle,
hasSingleBlockType,
directInsertBlock,
toggleProps,
prioritizePatterns
});
}
/**
* Render callback to display Dropdown content element.
*
* @param {Object} options
* @param {Function} options.onClose Callback to invoke when dropdown is
* closed.
*
* @return {WPElement} Dropdown content element.
*/
renderContent(_ref3) {
let {
onClose
} = _ref3;
const {
rootClientId,
clientId,
isAppender,
showInserterHelpPanel,
// This prop is experimental to give some time for the quick inserter to mature
// Feel free to make them stable after a few releases.
__experimentalIsQuick: isQuick,
prioritizePatterns,
onSelectOrClose,
selectBlockOnInsert,
orderInitialBlockItems
} = this.props;
if (isQuick) {
return (0,external_wp_element_namespaceObject.createElement)(QuickInserter, {
onSelect: blocks => {
const firstBlock = Array.isArray(blocks) && blocks !== null && blocks !== void 0 && blocks.length ? blocks[0] : blocks;
if (onSelectOrClose && typeof onSelectOrClose === 'function') {
onSelectOrClose(firstBlock);
}
onClose();
},
rootClientId: rootClientId,
clientId: clientId,
isAppender: isAppender,
prioritizePatterns: prioritizePatterns,
selectBlockOnInsert: selectBlockOnInsert,
orderInitialBlockItems: orderInitialBlockItems
});
}
return (0,external_wp_element_namespaceObject.createElement)(menu, {
onSelect: () => {
onClose();
},
rootClientId: rootClientId,
clientId: clientId,
isAppender: isAppender,
showInserterHelpPanel: showInserterHelpPanel,
prioritizePatterns: prioritizePatterns
});
}
render() {
const {
position,
hasSingleBlockType,
directInsertBlock,
insertOnlyAllowedBlock,
__experimentalIsQuick: isQuick,
onSelectOrClose
} = this.props;
if (hasSingleBlockType || directInsertBlock) {
return this.renderToggle({
onToggle: insertOnlyAllowedBlock
});
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Dropdown, {
className: "block-editor-inserter",
contentClassName: classnames_default()('block-editor-inserter__popover', {
'is-quick': isQuick
}),
popoverProps: {
position,
shift: true
},
onToggle: this.onToggle,
expandOnMobile: true,
headerTitle: (0,external_wp_i18n_namespaceObject.__)('Add a block'),
renderToggle: this.renderToggle,
renderContent: this.renderContent,
onClose: onSelectOrClose
});
}
}
const ComposedPrivateInserter = (0,external_wp_compose_namespaceObject.compose)([(0,external_wp_data_namespaceObject.withSelect)((select, _ref4) => {
var _getBlockVariations;
let {
clientId,
rootClientId,
shouldDirectInsert = true
} = _ref4;
const {
getBlockRootClientId,
hasInserterItems,
getAllowedBlocks,
__experimentalGetDirectInsertBlock,
getSettings
} = select(store);
const {
getBlockVariations
} = select(external_wp_blocks_namespaceObject.store);
rootClientId = rootClientId || getBlockRootClientId(clientId) || undefined;
const allowedBlocks = getAllowedBlocks(rootClientId);
const directInsertBlock = shouldDirectInsert && __experimentalGetDirectInsertBlock(rootClientId);
const settings = getSettings();
const hasSingleBlockType = (allowedBlocks === null || allowedBlocks === void 0 ? void 0 : allowedBlocks.length) === 1 && ((_getBlockVariations = getBlockVariations(allowedBlocks[0].name, 'inserter')) === null || _getBlockVariations === void 0 ? void 0 : _getBlockVariations.length) === 0;
let allowedBlockType = false;
if (hasSingleBlockType) {
allowedBlockType = allowedBlocks[0];
}
return {
hasItems: hasInserterItems(rootClientId),
hasSingleBlockType,
blockTitle: allowedBlockType ? allowedBlockType.title : '',
allowedBlockType,
directInsertBlock,
rootClientId,
prioritizePatterns: settings.__experimentalPreferPatternsOnRoot && !rootClientId
};
}), (0,external_wp_data_namespaceObject.withDispatch)((dispatch, ownProps, _ref5) => {
let {
select
} = _ref5;
return {
insertOnlyAllowedBlock() {
const {
rootClientId,
clientId,
isAppender,
hasSingleBlockType,
allowedBlockType,
directInsertBlock,
onSelectOrClose,
selectBlockOnInsert
} = ownProps;
if (!hasSingleBlockType && !directInsertBlock) {
return;
}
function getAdjacentBlockAttributes(attributesToCopy) {
const {
getBlock,
getPreviousBlockClientId
} = select(store);
if (!attributesToCopy || !clientId && !rootClientId) {
return {};
}
const result = {};
let adjacentAttributes = {}; // If there is no clientId, then attempt to get attributes
// from the last block within innerBlocks of the root block.
if (!clientId) {
var _parentBlock$innerBlo;
const parentBlock = getBlock(rootClientId);
if (parentBlock !== null && parentBlock !== void 0 && (_parentBlock$innerBlo = parentBlock.innerBlocks) !== null && _parentBlock$innerBlo !== void 0 && _parentBlock$innerBlo.length) {
const lastInnerBlock = parentBlock.innerBlocks[parentBlock.innerBlocks.length - 1];
if (directInsertBlock && (directInsertBlock === null || directInsertBlock === void 0 ? void 0 : directInsertBlock.name) === lastInnerBlock.name) {
adjacentAttributes = lastInnerBlock.attributes;
}
}
} else {
// Otherwise, attempt to get attributes from the
// previous block relative to the current clientId.
const currentBlock = getBlock(clientId);
const previousBlock = getBlock(getPreviousBlockClientId(clientId));
if ((currentBlock === null || currentBlock === void 0 ? void 0 : currentBlock.name) === (previousBlock === null || previousBlock === void 0 ? void 0 : previousBlock.name)) {
adjacentAttributes = (previousBlock === null || previousBlock === void 0 ? void 0 : previousBlock.attributes) || {};
}
} // Copy over only those attributes flagged to be copied.
attributesToCopy.forEach(attribute => {
if (adjacentAttributes.hasOwnProperty(attribute)) {
result[attribute] = adjacentAttributes[attribute];
}
});
return result;
}
function getInsertionIndex() {
const {
getBlockIndex,
getBlockSelectionEnd,
getBlockOrder,
getBlockRootClientId
} = select(store); // If the clientId is defined, we insert at the position of the block.
if (clientId) {
return getBlockIndex(clientId);
} // If there a selected block, we insert after the selected block.
const end = getBlockSelectionEnd();
if (!isAppender && end && getBlockRootClientId(end) === rootClientId) {
return getBlockIndex(end) + 1;
} // Otherwise, we insert at the end of the current rootClientId.
return getBlockOrder(rootClientId).length;
}
const {
insertBlock
} = dispatch(store);
let blockToInsert; // Attempt to augment the directInsertBlock with attributes from an adjacent block.
// This ensures styling from nearby blocks is preserved in the newly inserted block.
// See: https://github.com/WordPress/gutenberg/issues/37904
if (directInsertBlock) {
const newAttributes = getAdjacentBlockAttributes(directInsertBlock.attributesToCopy);
blockToInsert = (0,external_wp_blocks_namespaceObject.createBlock)(directInsertBlock.name, { ...(directInsertBlock.attributes || {}),
...newAttributes
});
} else {
blockToInsert = (0,external_wp_blocks_namespaceObject.createBlock)(allowedBlockType.name);
}
insertBlock(blockToInsert, getInsertionIndex(), rootClientId, selectBlockOnInsert);
if (onSelectOrClose) {
var _blockToInsert;
onSelectOrClose({
clientId: (_blockToInsert = blockToInsert) === null || _blockToInsert === void 0 ? void 0 : _blockToInsert.clientId
});
}
const message = (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: the name of the block that has been added
(0,external_wp_i18n_namespaceObject.__)('%s block added'), allowedBlockType.title);
(0,external_wp_a11y_namespaceObject.speak)(message);
}
};
}), // The global inserter should always be visible, we are using ( ! isAppender && ! rootClientId && ! clientId ) as
// a way to detect the global Inserter.
(0,external_wp_compose_namespaceObject.ifCondition)(_ref6 => {
let {
hasItems,
isAppender,
rootClientId,
clientId
} = _ref6;
return hasItems || !isAppender && !rootClientId && !clientId;
})])(PrivateInserter);
const Inserter = (0,external_wp_element_namespaceObject.forwardRef)((props, ref) => {
return (0,external_wp_element_namespaceObject.createElement)(ComposedPrivateInserter, _extends({
ref: ref
}, props, {
orderInitialBlockItems: undefined
}));
});
/* harmony default export */ var inserter = (Inserter);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/default-block-appender/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Zero width non-breaking space, used as padding for the paragraph when it is
* empty.
*/
const ZWNBSP = '\ufeff';
function DefaultBlockAppender(_ref) {
let {
isLocked,
onAppend,
showPrompt,
placeholder,
rootClientId
} = _ref;
if (isLocked) {
return null;
}
const value = (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(placeholder) || (0,external_wp_i18n_namespaceObject.__)('Type / to choose a block');
return (0,external_wp_element_namespaceObject.createElement)("div", {
"data-root-client-id": rootClientId || '',
className: classnames_default()('block-editor-default-block-appender', {
'has-visible-prompt': showPrompt
})
}, (0,external_wp_element_namespaceObject.createElement)("p", {
tabIndex: "0" // We want this element to be styled as a paragraph by themes.
// eslint-disable-next-line jsx-a11y/no-noninteractive-element-to-interactive-role
,
role: "button",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Add default block') // A wrapping container for this one already has the wp-block className.
,
className: "block-editor-default-block-appender__content",
onKeyDown: event => {
if (external_wp_keycodes_namespaceObject.ENTER === event.keyCode || external_wp_keycodes_namespaceObject.SPACE === event.keyCode) {
onAppend();
}
},
onClick: () => onAppend(),
onFocus: () => {
if (showPrompt) {
onAppend();
}
}
}, showPrompt ? value : ZWNBSP), (0,external_wp_element_namespaceObject.createElement)(inserter, {
rootClientId: rootClientId,
position: "bottom right",
isAppender: true,
__experimentalIsQuick: true
}));
}
/* harmony default export */ var default_block_appender = ((0,external_wp_compose_namespaceObject.compose)((0,external_wp_data_namespaceObject.withSelect)((select, ownProps) => {
const {
getBlockCount,
getSettings,
getTemplateLock
} = select(store);
const isEmpty = !getBlockCount(ownProps.rootClientId);
const {
bodyPlaceholder
} = getSettings();
return {
showPrompt: isEmpty,
isLocked: !!getTemplateLock(ownProps.rootClientId),
placeholder: bodyPlaceholder
};
}), (0,external_wp_data_namespaceObject.withDispatch)((dispatch, ownProps) => {
const {
insertDefaultBlock,
startTyping
} = dispatch(store);
return {
onAppend() {
const {
rootClientId
} = ownProps;
insertDefaultBlock(undefined, rootClientId);
startTyping();
}
};
}))(DefaultBlockAppender));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/button-block-appender/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ButtonBlockAppender(_ref, ref) {
let {
rootClientId,
className,
onFocus,
tabIndex
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(inserter, {
position: "bottom center",
rootClientId: rootClientId,
__experimentalIsQuick: true,
renderToggle: _ref2 => {
let {
onToggle,
disabled,
isOpen,
blockTitle,
hasSingleBlockType
} = _ref2;
let label;
if (hasSingleBlockType) {
label = (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: the name of the block when there is only one
(0,external_wp_i18n_namespaceObject._x)('Add %s', 'directly add the only allowed block'), blockTitle);
} else {
label = (0,external_wp_i18n_namespaceObject._x)('Add block', 'Generic label for block inserter button');
}
const isToggleButton = !hasSingleBlockType;
let inserterButton = (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
ref: ref,
onFocus: onFocus,
tabIndex: tabIndex,
className: classnames_default()(className, 'block-editor-button-block-appender'),
onClick: onToggle,
"aria-haspopup": isToggleButton ? 'true' : undefined,
"aria-expanded": isToggleButton ? isOpen : undefined,
disabled: disabled,
label: label
}, !hasSingleBlockType && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.VisuallyHidden, {
as: "span"
}, label), (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: library_plus
}));
if (isToggleButton || hasSingleBlockType) {
inserterButton = (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Tooltip, {
text: label
}, inserterButton);
}
return inserterButton;
},
isAppender: true
});
}
/**
* Use `ButtonBlockAppender` instead.
*
* @deprecated
*/
const ButtonBlockerAppender = (0,external_wp_element_namespaceObject.forwardRef)((props, ref) => {
external_wp_deprecated_default()(`wp.blockEditor.ButtonBlockerAppender`, {
alternative: 'wp.blockEditor.ButtonBlockAppender',
since: '5.9'
});
return ButtonBlockAppender(props, ref);
});
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/button-block-appender/README.md
*/
/* harmony default export */ var button_block_appender = ((0,external_wp_element_namespaceObject.forwardRef)(ButtonBlockAppender));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-list-appender/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function DefaultAppender(_ref) {
let {
rootClientId
} = _ref;
const canInsertDefaultBlock = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).canInsertBlockType((0,external_wp_blocks_namespaceObject.getDefaultBlockName)(), rootClientId));
if (canInsertDefaultBlock) {
// Render the default block appender if the context supports use
// of the default appender.
return (0,external_wp_element_namespaceObject.createElement)(default_block_appender, {
rootClientId: rootClientId
});
} // Fallback in case the default block can't be inserted.
return (0,external_wp_element_namespaceObject.createElement)(button_block_appender, {
rootClientId: rootClientId,
className: "block-list-appender__toggle"
});
}
function useAppender(rootClientId, CustomAppender) {
const {
hideInserter,
isParentSelected
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getTemplateLock,
getSelectedBlockClientId,
__unstableGetEditorMode
} = select(store);
const selectedBlockClientId = getSelectedBlockClientId();
return {
hideInserter: !!getTemplateLock(rootClientId) || __unstableGetEditorMode() === 'zoom-out',
isParentSelected: rootClientId === selectedBlockClientId || !rootClientId && !selectedBlockClientId
};
}, [rootClientId]);
if (hideInserter || CustomAppender === false) {
return null;
}
if (CustomAppender) {
// Prefer custom render prop if provided.
return (0,external_wp_element_namespaceObject.createElement)(CustomAppender, null);
}
if (!isParentSelected) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(DefaultAppender, {
rootClientId: rootClientId
});
}
function BlockListAppender(_ref2) {
let {
rootClientId,
renderAppender,
className,
tagName: TagName = 'div'
} = _ref2;
const appender = useAppender(rootClientId, renderAppender);
if (!appender) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(TagName // A `tabIndex` is used on the wrapping `div` element in order to
// force a focus event to occur when an appender `button` element
// is clicked. In some browsers (Firefox, Safari), button clicks do
// not emit a focus event, which could cause this event to propagate
// unexpectedly. The `tabIndex` ensures that the interaction is
// captured as a focus, without also adding an extra tab stop.
//
// See: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Clicking_and_focus
, {
tabIndex: -1,
className: classnames_default()('block-list-appender wp-block', className) // Needed in case the whole editor is content editable (for multi
// selection). It fixes an edge case where ArrowDown and ArrowRight
// should collapse the selection to the end of that selection and
// not into the appender.
,
contentEditable: false // The appender exists to let you add the first Paragraph before
// any is inserted. To that end, this appender should visually be
// presented as a block. That means theme CSS should style it as if
// it were an empty paragraph block. That means a `wp-block` class to
// ensure the width is correct, and a [data-block] attribute to ensure
// the correct margin is applied, especially for classic themes which
// have commonly targeted that attribute for margins.
,
"data-block": true
}, appender);
}
/* harmony default export */ var block_list_appender = (BlockListAppender);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-popover/inbetween.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const inbetween_MAX_POPOVER_RECOMPUTE_COUNTER = Number.MAX_SAFE_INTEGER;
const InsertionPointOpenRef = (0,external_wp_element_namespaceObject.createContext)();
function BlockPopoverInbetween(_ref) {
let {
previousClientId,
nextClientId,
children,
__unstablePopoverSlot,
__unstableContentRef,
...props
} = _ref;
// This is a temporary hack to get the inbetween inserter to recompute properly.
const [popoverRecomputeCounter, forcePopoverRecompute] = (0,external_wp_element_namespaceObject.useReducer)( // Module is there to make sure that the counter doesn't overflow.
s => (s + 1) % inbetween_MAX_POPOVER_RECOMPUTE_COUNTER, 0);
const {
orientation,
rootClientId,
isVisible
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _getBlockListSettings;
const {
getBlockListSettings,
getBlockRootClientId,
isBlockVisible
} = select(store);
const _rootClientId = getBlockRootClientId(previousClientId !== null && previousClientId !== void 0 ? previousClientId : nextClientId);
return {
orientation: ((_getBlockListSettings = getBlockListSettings(_rootClientId)) === null || _getBlockListSettings === void 0 ? void 0 : _getBlockListSettings.orientation) || 'vertical',
rootClientId: _rootClientId,
isVisible: isBlockVisible(previousClientId) && isBlockVisible(nextClientId)
};
}, [previousClientId, nextClientId]);
const previousElement = useBlockElement(previousClientId);
const nextElement = useBlockElement(nextClientId);
const isVertical = orientation === 'vertical';
const style = (0,external_wp_element_namespaceObject.useMemo)(() => {
if ( // popoverRecomputeCounter is by definition always equal or greater than 0.
// This check is only there to satisfy the correctness of the
// exhaustive-deps rule for the `useMemo` hook.
popoverRecomputeCounter < 0 || !previousElement && !nextElement || !isVisible) {
return {};
}
const previousRect = previousElement ? previousElement.getBoundingClientRect() : null;
const nextRect = nextElement ? nextElement.getBoundingClientRect() : null;
if (isVertical) {
return {
width: previousRect ? previousRect.width : nextRect.width,
height: nextRect && previousRect ? nextRect.top - previousRect.bottom : 0
};
}
let width = 0;
if (previousRect && nextRect) {
width = (0,external_wp_i18n_namespaceObject.isRTL)() ? previousRect.left - nextRect.right : nextRect.left - previousRect.right;
}
return {
width,
height: previousRect ? previousRect.height : nextRect.height
};
}, [previousElement, nextElement, isVertical, popoverRecomputeCounter, isVisible]);
const popoverAnchor = (0,external_wp_element_namespaceObject.useMemo)(() => {
if ( // popoverRecomputeCounter is by definition always equal or greater than 0.
// This check is only there to satisfy the correctness of the
// exhaustive-deps rule for the `useMemo` hook.
popoverRecomputeCounter < 0 || !previousElement && !nextElement || !isVisible) {
return undefined;
}
const {
ownerDocument
} = previousElement || nextElement;
return {
ownerDocument,
getBoundingClientRect() {
const previousRect = previousElement ? previousElement.getBoundingClientRect() : null;
const nextRect = nextElement ? nextElement.getBoundingClientRect() : null;
let left = 0;
let top = 0;
if (isVertical) {
// vertical
top = previousRect ? previousRect.bottom : nextRect.top;
if ((0,external_wp_i18n_namespaceObject.isRTL)()) {
// vertical, rtl
left = previousRect ? previousRect.right : nextRect.right;
} else {
// vertical, ltr
left = previousRect ? previousRect.left : nextRect.left;
}
} else {
top = previousRect ? previousRect.top : nextRect.top;
if ((0,external_wp_i18n_namespaceObject.isRTL)()) {
// non vertical, rtl
left = previousRect ? previousRect.left : nextRect.right;
} else {
// non vertical, ltr
left = previousRect ? previousRect.right : nextRect.left;
}
}
return new window.DOMRect(left, top, 0, 0);
}
};
}, [previousElement, nextElement, popoverRecomputeCounter, isVertical, isVisible]);
const popoverScrollRef = use_popover_scroll(__unstableContentRef); // This is only needed for a smooth transition when moving blocks.
// When blocks are moved up/down, their position can be set by
// updating the `transform` property manually (i.e. without using CSS
// transitions or animations). The animation, which can also scroll the block
// editor, can sometimes cause the position of the Popover to get out of sync.
// A MutationObserver is therefore used to make sure that changes to the
// selectedElement's attribute (i.e. `transform`) can be tracked and used to
// trigger the Popover to rerender.
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
if (!previousElement) {
return;
}
const observer = new window.MutationObserver(forcePopoverRecompute);
observer.observe(previousElement, {
attributes: true
});
return () => {
observer.disconnect();
};
}, [previousElement]);
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
if (!nextElement) {
return;
}
const observer = new window.MutationObserver(forcePopoverRecompute);
observer.observe(nextElement, {
attributes: true
});
return () => {
observer.disconnect();
};
}, [nextElement]);
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
if (!previousElement) {
return;
}
previousElement.ownerDocument.defaultView.addEventListener('resize', forcePopoverRecompute);
return () => {
var _previousElement$owne;
(_previousElement$owne = previousElement.ownerDocument.defaultView) === null || _previousElement$owne === void 0 ? void 0 : _previousElement$owne.removeEventListener('resize', forcePopoverRecompute);
};
}, [previousElement]); // If there's either a previous or a next element, show the inbetween popover.
// Note that drag and drop uses the inbetween popover to show the drop indicator
// before the first block and after the last block.
if (!previousElement && !nextElement || !isVisible) {
return null;
}
/* eslint-disable jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events */
// While ideally it would be enough to capture the
// bubbling focus event from the Inserter, due to the
// characteristics of click focusing of `button`s in
// Firefox and Safari, it is not reliable.
//
// See: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Clicking_and_focus
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Popover, _extends({
ref: popoverScrollRef,
animate: false,
anchor: popoverAnchor,
focusOnMount: false // Render in the old slot if needed for backward compatibility,
// otherwise render in place (not in the default popover slot).
,
__unstableSlotName: __unstablePopoverSlot || null // Forces a remount of the popover when its position changes
// This makes sure the popover doesn't animate from its previous position.
,
key: nextClientId + '--' + rootClientId
}, props, {
className: classnames_default()('block-editor-block-popover', 'block-editor-block-popover__inbetween', props.className),
resize: false,
flip: false,
placement: "bottom-start",
variant: "unstyled"
}), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-popover__inbetween-container",
style: style
}, children));
/* eslint-enable jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events */
}
/* harmony default export */ var inbetween = (BlockPopoverInbetween);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-popover/drop-zone.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const animateVariants = {
hide: {
opacity: 0,
scaleY: 0.75
},
show: {
opacity: 1,
scaleY: 1
},
exit: {
opacity: 0,
scaleY: 0.9
}
};
function BlockDropZonePopover(_ref) {
let {
__unstablePopoverSlot,
__unstableContentRef
} = _ref;
const {
clientId
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlockOrder,
getBlockInsertionPoint
} = select(store);
const insertionPoint = getBlockInsertionPoint();
const order = getBlockOrder(insertionPoint.rootClientId);
if (!order.length) {
return {};
}
return {
clientId: order[insertionPoint.index]
};
}, []);
const reducedMotion = (0,external_wp_compose_namespaceObject.useReducedMotion)();
return (0,external_wp_element_namespaceObject.createElement)(block_popover, {
clientId: clientId,
__unstableCoverTarget: true,
__unstablePopoverSlot: __unstablePopoverSlot,
__unstableContentRef: __unstableContentRef,
className: "block-editor-block-popover__drop-zone"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableMotion.div, {
"data-testid": "block-popover-drop-zone",
initial: reducedMotion ? animateVariants.show : animateVariants.hide,
animate: animateVariants.show,
exit: reducedMotion ? animateVariants.show : animateVariants.exit,
className: "block-editor-block-popover__drop-zone-foreground"
}));
}
/* harmony default export */ var drop_zone = (BlockDropZonePopover);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-tools/insertion-point.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const insertion_point_InsertionPointOpenRef = (0,external_wp_element_namespaceObject.createContext)();
function InbetweenInsertionPointPopover(_ref) {
let {
__unstablePopoverSlot,
__unstableContentRef
} = _ref;
const {
selectBlock,
hideInsertionPoint
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const openRef = (0,external_wp_element_namespaceObject.useContext)(insertion_point_InsertionPointOpenRef);
const ref = (0,external_wp_element_namespaceObject.useRef)();
const {
orientation,
previousClientId,
nextClientId,
rootClientId,
isInserterShown,
isDistractionFree,
isNavigationMode
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _getBlockListSettings;
const {
getBlockOrder,
getBlockListSettings,
getBlockInsertionPoint,
isBlockBeingDragged,
getPreviousBlockClientId,
getNextBlockClientId,
getSettings,
isNavigationMode: _isNavigationMode
} = select(store);
const insertionPoint = getBlockInsertionPoint();
const order = getBlockOrder(insertionPoint.rootClientId);
if (!order.length) {
return {};
}
let _previousClientId = order[insertionPoint.index - 1];
let _nextClientId = order[insertionPoint.index];
while (isBlockBeingDragged(_previousClientId)) {
_previousClientId = getPreviousBlockClientId(_previousClientId);
}
while (isBlockBeingDragged(_nextClientId)) {
_nextClientId = getNextBlockClientId(_nextClientId);
}
const settings = getSettings();
return {
previousClientId: _previousClientId,
nextClientId: _nextClientId,
orientation: ((_getBlockListSettings = getBlockListSettings(insertionPoint.rootClientId)) === null || _getBlockListSettings === void 0 ? void 0 : _getBlockListSettings.orientation) || 'vertical',
rootClientId: insertionPoint.rootClientId,
isNavigationMode: _isNavigationMode(),
isDistractionFree: settings.isDistractionFree,
isInserterShown: insertionPoint === null || insertionPoint === void 0 ? void 0 : insertionPoint.__unstableWithInserter
};
}, []);
const disableMotion = (0,external_wp_compose_namespaceObject.useReducedMotion)();
function onClick(event) {
if (event.target === ref.current && nextClientId) {
selectBlock(nextClientId, -1);
}
}
function maybeHideInserterPoint(event) {
// Only hide the inserter if it's triggered on the wrapper,
// and the inserter is not open.
if (event.target === ref.current && !openRef.current) {
hideInsertionPoint();
}
}
function onFocus(event) {
// Only handle click on the wrapper specifically, and not an event
// bubbled from the inserter itself.
if (event.target !== ref.current) {
openRef.current = true;
}
}
const lineVariants = {
// Initial position starts from the center and invisible.
start: {
opacity: 0,
scale: 0
},
// The line expands to fill the container. If the inserter is visible it
// is delayed so it appears orchestrated.
rest: {
opacity: 1,
scale: 1,
transition: {
delay: isInserterShown ? 0.5 : 0,
type: 'tween'
}
},
hover: {
opacity: 1,
scale: 1,
transition: {
delay: 0.5,
type: 'tween'
}
}
};
const inserterVariants = {
start: {
scale: disableMotion ? 1 : 0
},
rest: {
scale: 1,
transition: {
delay: 0.4,
type: 'tween'
}
}
};
if (isDistractionFree && !isNavigationMode) {
return null;
}
const className = classnames_default()('block-editor-block-list__insertion-point', 'is-' + orientation);
return (0,external_wp_element_namespaceObject.createElement)(inbetween, {
previousClientId: previousClientId,
nextClientId: nextClientId,
__unstablePopoverSlot: __unstablePopoverSlot,
__unstableContentRef: __unstableContentRef
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableMotion.div, {
layout: !disableMotion,
initial: disableMotion ? 'rest' : 'start',
animate: "rest",
whileHover: "hover",
whileTap: "pressed",
exit: "start",
ref: ref,
tabIndex: -1,
onClick: onClick,
onFocus: onFocus,
className: classnames_default()(className, {
'is-with-inserter': isInserterShown
}),
onHoverEnd: maybeHideInserterPoint
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableMotion.div, {
variants: lineVariants,
className: "block-editor-block-list__insertion-point-indicator",
"data-testid": "block-list-insertion-point-indicator"
}), isInserterShown && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableMotion.div, {
variants: inserterVariants,
className: classnames_default()('block-editor-block-list__insertion-point-inserter')
}, (0,external_wp_element_namespaceObject.createElement)(inserter, {
position: "bottom center",
clientId: nextClientId,
rootClientId: rootClientId,
__experimentalIsQuick: true,
onToggle: isOpen => {
openRef.current = isOpen;
},
onSelectOrClose: () => {
openRef.current = false;
}
}))));
}
function InsertionPoint(props) {
const {
insertionPoint,
isVisible
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlockInsertionPoint,
isBlockInsertionPointVisible
} = select(store);
return {
insertionPoint: getBlockInsertionPoint(),
isVisible: isBlockInsertionPointVisible()
};
}, []);
if (!isVisible) {
return null;
}
/**
* Render a popover that overlays the block when the desired operation is to replace it.
* Otherwise, render a popover in between blocks for the indication of inserting between them.
*/
return insertionPoint.operation === 'replace' ? (0,external_wp_element_namespaceObject.createElement)(drop_zone // Force remount to trigger the animation.
, _extends({
key: `${insertionPoint.rootClientId}-${insertionPoint.index}`
}, props)) : (0,external_wp_element_namespaceObject.createElement)(InbetweenInsertionPointPopover, props);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-list/use-in-between-inserter.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useInBetweenInserter() {
const openRef = (0,external_wp_element_namespaceObject.useContext)(insertion_point_InsertionPointOpenRef);
const isInBetweenInserterDisabled = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).getSettings().isDistractionFree || select(store).__unstableGetEditorMode() === 'zoom-out', []);
const {
getBlockListSettings,
getBlockRootClientId,
getBlockIndex,
isBlockInsertionPointVisible,
isMultiSelecting,
getSelectedBlockClientIds,
getTemplateLock,
__unstableIsWithinBlockOverlay
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const {
showInsertionPoint,
hideInsertionPoint
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
return (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
if (isInBetweenInserterDisabled) {
return;
}
function onMouseMove(event) {
var _getBlockListSettings;
if (openRef.current) {
return;
} // Ignore text nodes sometimes detected in FireFox.
if (event.target.nodeType === event.target.TEXT_NODE) {
return;
}
if (isMultiSelecting()) {
return;
}
if (!event.target.classList.contains('block-editor-block-list__layout')) {
hideInsertionPoint();
return;
}
let rootClientId;
if (!event.target.classList.contains('is-root-container')) {
const blockElement = !!event.target.getAttribute('data-block') ? event.target : event.target.closest('[data-block]');
rootClientId = blockElement.getAttribute('data-block');
} // Don't set the insertion point if the template is locked.
if (getTemplateLock(rootClientId)) {
return;
}
const orientation = ((_getBlockListSettings = getBlockListSettings(rootClientId)) === null || _getBlockListSettings === void 0 ? void 0 : _getBlockListSettings.orientation) || 'vertical';
const offsetTop = event.clientY;
const offsetLeft = event.clientX;
const children = Array.from(event.target.children);
let element = children.find(blockEl => {
const blockElRect = blockEl.getBoundingClientRect();
return blockEl.classList.contains('wp-block') && orientation === 'vertical' && blockElRect.top > offsetTop || blockEl.classList.contains('wp-block') && orientation === 'horizontal' && blockElRect.left > offsetLeft;
});
if (!element) {
hideInsertionPoint();
return;
} // The block may be in an alignment wrapper, so check the first direct
// child if the element has no ID.
if (!element.id) {
element = element.firstElementChild;
if (!element) {
hideInsertionPoint();
return;
}
} // Don't show the insertion point if a parent block has an "overlay"
// See https://github.com/WordPress/gutenberg/pull/34012#pullrequestreview-727762337
const clientId = element.id.slice('block-'.length);
if (!clientId || __unstableIsWithinBlockOverlay(clientId)) {
return;
} // Don't show the inserter when hovering above (conflicts with
// block toolbar) or inside selected block(s).
if (getSelectedBlockClientIds().includes(clientId)) {
return;
}
const elementRect = element.getBoundingClientRect();
if (orientation === 'horizontal' && (event.clientY > elementRect.bottom || event.clientY < elementRect.top) || orientation === 'vertical' && (event.clientX > elementRect.right || event.clientX < elementRect.left)) {
hideInsertionPoint();
return;
}
const index = getBlockIndex(clientId); // Don't show the in-between inserter before the first block in
// the list (preserves the original behaviour).
if (index === 0) {
hideInsertionPoint();
return;
}
showInsertionPoint(rootClientId, index, {
__unstableWithInserter: true
});
}
node.addEventListener('mousemove', onMouseMove);
return () => {
node.removeEventListener('mousemove', onMouseMove);
};
}, [openRef, getBlockListSettings, getBlockRootClientId, getBlockIndex, isBlockInsertionPointVisible, isMultiSelecting, showInsertionPoint, hideInsertionPoint, getSelectedBlockClientIds, isInBetweenInserterDisabled]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/utils/pre-parse-patterns.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const requestIdleCallback = (() => {
if (typeof window === 'undefined') {
return callback => {
setTimeout(() => callback(Date.now()), 0);
};
}
return window.requestIdleCallback || window.requestAnimationFrame;
})();
const cancelIdleCallback = (() => {
if (typeof window === 'undefined') {
return clearTimeout;
}
return window.cancelIdleCallback || window.cancelAnimationFrame;
})();
function usePreParsePatterns() {
const {
patterns,
isPreviewMode
} = (0,external_wp_data_namespaceObject.useSelect)(_select => {
const {
__experimentalBlockPatterns,
__unstableIsPreviewMode
} = _select(store).getSettings();
return {
patterns: __experimentalBlockPatterns,
isPreviewMode: __unstableIsPreviewMode
};
}, []);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (isPreviewMode) {
return;
}
if (!(patterns !== null && patterns !== void 0 && patterns.length)) {
return;
}
let handle;
let index = -1;
const callback = () => {
index++;
if (index >= patterns.length) {
return;
}
(0,external_wp_data_namespaceObject.select)(store).__experimentalGetParsedPattern(patterns[index].name);
handle = requestIdleCallback(callback);
};
handle = requestIdleCallback(callback);
return () => cancelIdleCallback(handle);
}, [patterns, isPreviewMode]);
return null;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/use-block-display-information/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/** @typedef {import('@wordpress/blocks').WPIcon} WPIcon */
/**
* Contains basic block's information for display reasons.
*
* @typedef {Object} WPBlockDisplayInformation
*
* @property {boolean} isSynced True if is a reusable block or template part
* @property {string} title Human-readable block type label.
* @property {WPIcon} icon Block type icon.
* @property {string} description A detailed block type description.
* @property {string} anchor HTML anchor.
*/
/**
* Hook used to try to find a matching block variation and return
* the appropriate information for display reasons. In order to
* to try to find a match we need to things:
* 1. Block's client id to extract it's current attributes.
* 2. A block variation should have set `isActive` prop to a proper function.
*
* If for any reason a block variation match cannot be found,
* the returned information come from the Block Type.
* If no blockType is found with the provided clientId, returns null.
*
* @param {string} clientId Block's client id.
* @return {?WPBlockDisplayInformation} Block's display information, or `null` when the block or its type not found.
*/
function useBlockDisplayInformation(clientId) {
return (0,external_wp_data_namespaceObject.useSelect)(select => {
if (!clientId) return null;
const {
getBlockName,
getBlockAttributes
} = select(store);
const {
getBlockType,
getActiveBlockVariation
} = select(external_wp_blocks_namespaceObject.store);
const blockName = getBlockName(clientId);
const blockType = getBlockType(blockName);
if (!blockType) return null;
const attributes = getBlockAttributes(clientId);
const match = getActiveBlockVariation(blockName, attributes);
const isSynced = (0,external_wp_blocks_namespaceObject.isReusableBlock)(blockType) || (0,external_wp_blocks_namespaceObject.isTemplatePart)(blockType);
const blockTypeInfo = {
isSynced,
title: blockType.title,
icon: blockType.icon,
description: blockType.description,
anchor: attributes === null || attributes === void 0 ? void 0 : attributes.anchor
};
if (!match) return blockTypeInfo;
return {
isSynced,
title: match.title || blockType.title,
icon: match.icon || blockType.icon,
description: match.description || blockType.description,
anchor: attributes === null || attributes === void 0 ? void 0 : attributes.anchor
};
}, [clientId]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-title/use-block-display-title.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Returns the block's configured title as a string, or empty if the title
* cannot be determined.
*
* @example
*
* ```js
* useBlockDisplayTitle( { clientId: 'afd1cb17-2c08-4e7a-91be-007ba7ddc3a1', maximumLength: 17 } );
* ```
*
* @param {Object} props
* @param {string} props.clientId Client ID of block.
* @param {number|undefined} props.maximumLength The maximum length that the block title string may be before truncated.
* @param {string|undefined} props.context The context to pass to `getBlockLabel`.
* @return {?string} Block title.
*/
function useBlockDisplayTitle(_ref) {
let {
clientId,
maximumLength,
context
} = _ref;
const {
attributes,
name,
reusableBlockTitle
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
if (!clientId) {
return {};
}
const {
getBlockName,
getBlockAttributes,
__experimentalGetReusableBlockTitle
} = select(store);
const blockName = getBlockName(clientId);
if (!blockName) {
return {};
}
const isReusable = (0,external_wp_blocks_namespaceObject.isReusableBlock)((0,external_wp_blocks_namespaceObject.getBlockType)(blockName));
return {
attributes: getBlockAttributes(clientId),
name: blockName,
reusableBlockTitle: isReusable && __experimentalGetReusableBlockTitle(getBlockAttributes(clientId).ref)
};
}, [clientId]);
const blockInformation = useBlockDisplayInformation(clientId);
if (!name || !blockInformation) {
return null;
}
const blockType = (0,external_wp_blocks_namespaceObject.getBlockType)(name);
const blockLabel = blockType ? (0,external_wp_blocks_namespaceObject.__experimentalGetBlockLabel)(blockType, attributes, context) : null;
const label = reusableBlockTitle || blockLabel; // Label will fallback to the title if no label is defined for the current
// label context. If the label is defined we prioritize it over a
// possible block variation title match.
const blockTitle = label && label !== blockType.title ? label : blockInformation.title;
if (maximumLength && maximumLength > 0 && blockTitle.length > maximumLength) {
const omission = '...';
return blockTitle.slice(0, maximumLength - omission.length) + omission;
}
return blockTitle;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-title/index.js
/**
* Internal dependencies
*/
/**
* Renders the block's configured title as a string, or empty if the title
* cannot be determined.
*
* @example
*
* ```jsx
* <BlockTitle clientId="afd1cb17-2c08-4e7a-91be-007ba7ddc3a1" maximumLength={ 17 }/>
* ```
*
* @param {Object} props
* @param {string} props.clientId Client ID of block.
* @param {number|undefined} props.maximumLength The maximum length that the block title string may be before truncated.
* @param {string|undefined} props.context The context to pass to `getBlockLabel`.
*
* @return {JSX.Element} Block title.
*/
function BlockTitle(_ref) {
let {
clientId,
maximumLength,
context
} = _ref;
return useBlockDisplayTitle({
clientId,
maximumLength,
context
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-draggable/use-scroll-when-dragging.js
/**
* WordPress dependencies
*/
const SCROLL_INACTIVE_DISTANCE_PX = 50;
const SCROLL_INTERVAL_MS = 25;
const PIXELS_PER_SECOND_PER_PERCENTAGE = 1000;
const VELOCITY_MULTIPLIER = PIXELS_PER_SECOND_PER_PERCENTAGE * (SCROLL_INTERVAL_MS / 1000);
/**
* React hook that scrolls the scroll container when a block is being dragged.
*
* @return {Function[]} `startScrolling`, `scrollOnDragOver`, `stopScrolling`
* functions to be called in `onDragStart`, `onDragOver`
* and `onDragEnd` events respectively.
*/
function useScrollWhenDragging() {
const dragStartY = (0,external_wp_element_namespaceObject.useRef)(null);
const velocityY = (0,external_wp_element_namespaceObject.useRef)(null);
const scrollParentY = (0,external_wp_element_namespaceObject.useRef)(null);
const scrollEditorInterval = (0,external_wp_element_namespaceObject.useRef)(null); // Clear interval when unmounting.
(0,external_wp_element_namespaceObject.useEffect)(() => () => {
if (scrollEditorInterval.current) {
clearInterval(scrollEditorInterval.current);
scrollEditorInterval.current = null;
}
}, []);
const startScrolling = (0,external_wp_element_namespaceObject.useCallback)(event => {
dragStartY.current = event.clientY; // Find nearest parent(s) to scroll.
scrollParentY.current = (0,external_wp_dom_namespaceObject.getScrollContainer)(event.target);
scrollEditorInterval.current = setInterval(() => {
if (scrollParentY.current && velocityY.current) {
const newTop = scrollParentY.current.scrollTop + velocityY.current; // Setting `behavior: 'smooth'` as a scroll property seems to hurt performance.
// Better to use a small scroll interval.
scrollParentY.current.scroll({
top: newTop
});
}
}, SCROLL_INTERVAL_MS);
}, []);
const scrollOnDragOver = (0,external_wp_element_namespaceObject.useCallback)(event => {
if (!scrollParentY.current) {
return;
}
const scrollParentHeight = scrollParentY.current.offsetHeight;
const offsetDragStartPosition = dragStartY.current - scrollParentY.current.offsetTop;
const offsetDragPosition = event.clientY - scrollParentY.current.offsetTop;
if (event.clientY > offsetDragStartPosition) {
// User is dragging downwards.
const moveableDistance = Math.max(scrollParentHeight - offsetDragStartPosition - SCROLL_INACTIVE_DISTANCE_PX, 0);
const dragDistance = Math.max(offsetDragPosition - offsetDragStartPosition - SCROLL_INACTIVE_DISTANCE_PX, 0);
const distancePercentage = dragDistance / moveableDistance;
velocityY.current = VELOCITY_MULTIPLIER * distancePercentage;
} else if (event.clientY < offsetDragStartPosition) {
// User is dragging upwards.
const moveableDistance = Math.max(offsetDragStartPosition - SCROLL_INACTIVE_DISTANCE_PX, 0);
const dragDistance = Math.max(offsetDragStartPosition - offsetDragPosition - SCROLL_INACTIVE_DISTANCE_PX, 0);
const distancePercentage = dragDistance / moveableDistance;
velocityY.current = -VELOCITY_MULTIPLIER * distancePercentage;
} else {
velocityY.current = 0;
}
}, []);
const stopScrolling = () => {
dragStartY.current = null;
scrollParentY.current = null;
if (scrollEditorInterval.current) {
clearInterval(scrollEditorInterval.current);
scrollEditorInterval.current = null;
}
};
return [startScrolling, scrollOnDragOver, stopScrolling];
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-draggable/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const BlockDraggable = _ref => {
let {
children,
clientIds,
cloneClassname,
onDragStart,
onDragEnd
} = _ref;
const {
srcRootClientId,
isDraggable,
icon
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _getBlockType;
const {
canMoveBlocks,
getBlockRootClientId,
getBlockName
} = select(store);
const rootClientId = getBlockRootClientId(clientIds[0]);
const blockName = getBlockName(clientIds[0]);
return {
srcRootClientId: rootClientId,
isDraggable: canMoveBlocks(clientIds, rootClientId),
icon: (_getBlockType = (0,external_wp_blocks_namespaceObject.getBlockType)(blockName)) === null || _getBlockType === void 0 ? void 0 : _getBlockType.icon
};
}, [clientIds]);
const isDragging = (0,external_wp_element_namespaceObject.useRef)(false);
const [startScrolling, scrollOnDragOver, stopScrolling] = useScrollWhenDragging();
const {
startDraggingBlocks,
stopDraggingBlocks
} = (0,external_wp_data_namespaceObject.useDispatch)(store); // Stop dragging blocks if the block draggable is unmounted.
(0,external_wp_element_namespaceObject.useEffect)(() => {
return () => {
if (isDragging.current) {
stopDraggingBlocks();
}
};
}, []);
if (!isDraggable) {
return children({
draggable: false
});
}
const transferData = {
type: 'block',
srcClientIds: clientIds,
srcRootClientId
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Draggable, {
cloneClassname: cloneClassname,
__experimentalTransferDataType: "wp-blocks",
transferData: transferData,
onDragStart: event => {
startDraggingBlocks(clientIds);
isDragging.current = true;
startScrolling(event);
if (onDragStart) {
onDragStart();
}
},
onDragOver: scrollOnDragOver,
onDragEnd: () => {
stopDraggingBlocks();
isDragging.current = false;
stopScrolling();
if (onDragEnd) {
onDragEnd();
}
},
__experimentalDragComponent: (0,external_wp_element_namespaceObject.createElement)(BlockDraggableChip, {
count: clientIds.length,
icon: icon
})
}, _ref2 => {
let {
onDraggableStart,
onDraggableEnd
} = _ref2;
return children({
draggable: true,
onDragStart: onDraggableStart,
onDragEnd: onDraggableEnd
});
});
};
/* harmony default export */ var block_draggable = (BlockDraggable);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/chevron-up.js
/**
* WordPress dependencies
*/
const chevronUp = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M6.5 12.4L12 8l5.5 4.4-.9 1.2L12 10l-4.5 3.6-1-1.2z"
}));
/* harmony default export */ var chevron_up = (chevronUp);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/chevron-down.js
/**
* WordPress dependencies
*/
const chevronDown = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M17.5 11.6L12 16l-5.5-4.4.9-1.2L12 14l4.5-3.6 1 1.2z"
}));
/* harmony default export */ var chevron_down = (chevronDown);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-mover/mover-description.js
/**
* WordPress dependencies
*/
const getMovementDirection = (moveDirection, orientation) => {
if (moveDirection === 'up') {
if (orientation === 'horizontal') {
return (0,external_wp_i18n_namespaceObject.isRTL)() ? 'right' : 'left';
}
return 'up';
} else if (moveDirection === 'down') {
if (orientation === 'horizontal') {
return (0,external_wp_i18n_namespaceObject.isRTL)() ? 'left' : 'right';
}
return 'down';
}
return null;
};
/**
* Return a label for the block movement controls depending on block position.
*
* @param {number} selectedCount Number of blocks selected.
* @param {string} type Block type - in the case of a single block, should
* define its 'type'. I.e. 'Text', 'Heading', 'Image' etc.
* @param {number} firstIndex The index (position - 1) of the first block selected.
* @param {boolean} isFirst This is the first block.
* @param {boolean} isLast This is the last block.
* @param {number} dir Direction of movement (> 0 is considered to be going
* down, < 0 is up).
* @param {string} orientation The orientation of the block movers, vertical or
* horizontal.
*
* @return {string | undefined} Label for the block movement controls.
*/
function getBlockMoverDescription(selectedCount, type, firstIndex, isFirst, isLast, dir, orientation) {
const position = firstIndex + 1;
if (selectedCount > 1) {
return getMultiBlockMoverDescription(selectedCount, firstIndex, isFirst, isLast, dir, orientation);
}
if (isFirst && isLast) {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: Type of block (i.e. Text, Image etc)
(0,external_wp_i18n_namespaceObject.__)('Block %s is the only block, and cannot be moved'), type);
}
if (dir > 0 && !isLast) {
// Moving down.
const movementDirection = getMovementDirection('down', orientation);
if (movementDirection === 'down') {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: 1: Type of block (i.e. Text, Image etc), 2: Position of selected block, 3: New position
(0,external_wp_i18n_namespaceObject.__)('Move %1$s block from position %2$d down to position %3$d'), type, position, position + 1);
}
if (movementDirection === 'left') {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: 1: Type of block (i.e. Text, Image etc), 2: Position of selected block, 3: New position
(0,external_wp_i18n_namespaceObject.__)('Move %1$s block from position %2$d left to position %3$d'), type, position, position + 1);
}
if (movementDirection === 'right') {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: 1: Type of block (i.e. Text, Image etc), 2: Position of selected block, 3: New position
(0,external_wp_i18n_namespaceObject.__)('Move %1$s block from position %2$d right to position %3$d'), type, position, position + 1);
}
}
if (dir > 0 && isLast) {
// Moving down, and is the last item.
const movementDirection = getMovementDirection('down', orientation);
if (movementDirection === 'down') {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: 1: Type of block (i.e. Text, Image etc)
(0,external_wp_i18n_namespaceObject.__)('Block %1$s is at the end of the content and can’t be moved down'), type);
}
if (movementDirection === 'left') {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: 1: Type of block (i.e. Text, Image etc)
(0,external_wp_i18n_namespaceObject.__)('Block %1$s is at the end of the content and can’t be moved left'), type);
}
if (movementDirection === 'right') {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: 1: Type of block (i.e. Text, Image etc)
(0,external_wp_i18n_namespaceObject.__)('Block %1$s is at the end of the content and can’t be moved right'), type);
}
}
if (dir < 0 && !isFirst) {
// Moving up.
const movementDirection = getMovementDirection('up', orientation);
if (movementDirection === 'up') {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: 1: Type of block (i.e. Text, Image etc), 2: Position of selected block, 3: New position
(0,external_wp_i18n_namespaceObject.__)('Move %1$s block from position %2$d up to position %3$d'), type, position, position - 1);
}
if (movementDirection === 'left') {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: 1: Type of block (i.e. Text, Image etc), 2: Position of selected block, 3: New position
(0,external_wp_i18n_namespaceObject.__)('Move %1$s block from position %2$d left to position %3$d'), type, position, position - 1);
}
if (movementDirection === 'right') {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: 1: Type of block (i.e. Text, Image etc), 2: Position of selected block, 3: New position
(0,external_wp_i18n_namespaceObject.__)('Move %1$s block from position %2$d right to position %3$d'), type, position, position - 1);
}
}
if (dir < 0 && isFirst) {
// Moving up, and is the first item.
const movementDirection = getMovementDirection('up', orientation);
if (movementDirection === 'up') {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: 1: Type of block (i.e. Text, Image etc)
(0,external_wp_i18n_namespaceObject.__)('Block %1$s is at the beginning of the content and can’t be moved up'), type);
}
if (movementDirection === 'left') {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: 1: Type of block (i.e. Text, Image etc)
(0,external_wp_i18n_namespaceObject.__)('Block %1$s is at the beginning of the content and can’t be moved left'), type);
}
if (movementDirection === 'right') {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: 1: Type of block (i.e. Text, Image etc)
(0,external_wp_i18n_namespaceObject.__)('Block %1$s is at the beginning of the content and can’t be moved right'), type);
}
}
}
/**
* Return a label for the block movement controls depending on block position.
*
* @param {number} selectedCount Number of blocks selected.
* @param {number} firstIndex The index (position - 1) of the first block selected.
* @param {boolean} isFirst This is the first block.
* @param {boolean} isLast This is the last block.
* @param {number} dir Direction of movement (> 0 is considered to be going
* down, < 0 is up).
* @param {string} orientation The orientation of the block movers, vertical or
* horizontal.
*
* @return {string | undefined} Label for the block movement controls.
*/
function getMultiBlockMoverDescription(selectedCount, firstIndex, isFirst, isLast, dir, orientation) {
const position = firstIndex + 1;
if (isFirst && isLast) {
// All blocks are selected
return (0,external_wp_i18n_namespaceObject.__)('All blocks are selected, and cannot be moved');
}
if (dir > 0 && !isLast) {
// moving down
const movementDirection = getMovementDirection('down', orientation);
if (movementDirection === 'down') {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: 1: Number of selected blocks, 2: Position of selected blocks
(0,external_wp_i18n_namespaceObject.__)('Move %1$d blocks from position %2$d down by one place'), selectedCount, position);
}
if (movementDirection === 'left') {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: 1: Number of selected blocks, 2: Position of selected blocks
(0,external_wp_i18n_namespaceObject.__)('Move %1$d blocks from position %2$d left by one place'), selectedCount, position);
}
if (movementDirection === 'right') {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: 1: Number of selected blocks, 2: Position of selected blocks
(0,external_wp_i18n_namespaceObject.__)('Move %1$d blocks from position %2$d right by one place'), selectedCount, position);
}
}
if (dir > 0 && isLast) {
// moving down, and the selected blocks are the last item
const movementDirection = getMovementDirection('down', orientation);
if (movementDirection === 'down') {
return (0,external_wp_i18n_namespaceObject.__)('Blocks cannot be moved down as they are already at the bottom');
}
if (movementDirection === 'left') {
return (0,external_wp_i18n_namespaceObject.__)('Blocks cannot be moved left as they are already are at the leftmost position');
}
if (movementDirection === 'right') {
return (0,external_wp_i18n_namespaceObject.__)('Blocks cannot be moved right as they are already are at the rightmost position');
}
}
if (dir < 0 && !isFirst) {
// moving up
const movementDirection = getMovementDirection('up', orientation);
if (movementDirection === 'up') {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: 1: Number of selected blocks, 2: Position of selected blocks
(0,external_wp_i18n_namespaceObject.__)('Move %1$d blocks from position %2$d up by one place'), selectedCount, position);
}
if (movementDirection === 'left') {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: 1: Number of selected blocks, 2: Position of selected blocks
(0,external_wp_i18n_namespaceObject.__)('Move %1$d blocks from position %2$d left by one place'), selectedCount, position);
}
if (movementDirection === 'right') {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: 1: Number of selected blocks, 2: Position of selected blocks
(0,external_wp_i18n_namespaceObject.__)('Move %1$d blocks from position %2$d right by one place'), selectedCount, position);
}
}
if (dir < 0 && isFirst) {
// moving up, and the selected blocks are the first item
const movementDirection = getMovementDirection('up', orientation);
if (movementDirection === 'up') {
return (0,external_wp_i18n_namespaceObject.__)('Blocks cannot be moved up as they are already at the top');
}
if (movementDirection === 'left') {
return (0,external_wp_i18n_namespaceObject.__)('Blocks cannot be moved left as they are already are at the leftmost position');
}
if (movementDirection === 'right') {
return (0,external_wp_i18n_namespaceObject.__)('Blocks cannot be moved right as they are already are at the rightmost position');
}
}
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-mover/button.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const getArrowIcon = (direction, orientation) => {
if (direction === 'up') {
if (orientation === 'horizontal') {
return (0,external_wp_i18n_namespaceObject.isRTL)() ? chevron_right : chevron_left;
}
return chevron_up;
} else if (direction === 'down') {
if (orientation === 'horizontal') {
return (0,external_wp_i18n_namespaceObject.isRTL)() ? chevron_left : chevron_right;
}
return chevron_down;
}
return null;
};
const getMovementDirectionLabel = (moveDirection, orientation) => {
if (moveDirection === 'up') {
if (orientation === 'horizontal') {
return (0,external_wp_i18n_namespaceObject.isRTL)() ? (0,external_wp_i18n_namespaceObject.__)('Move right') : (0,external_wp_i18n_namespaceObject.__)('Move left');
}
return (0,external_wp_i18n_namespaceObject.__)('Move up');
} else if (moveDirection === 'down') {
if (orientation === 'horizontal') {
return (0,external_wp_i18n_namespaceObject.isRTL)() ? (0,external_wp_i18n_namespaceObject.__)('Move left') : (0,external_wp_i18n_namespaceObject.__)('Move right');
}
return (0,external_wp_i18n_namespaceObject.__)('Move down');
}
return null;
};
const BlockMoverButton = (0,external_wp_element_namespaceObject.forwardRef)((_ref, ref) => {
let {
clientIds,
direction,
orientation: moverOrientation,
...props
} = _ref;
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(BlockMoverButton);
const normalizedClientIds = Array.isArray(clientIds) ? clientIds : [clientIds];
const blocksCount = normalizedClientIds.length;
const {
blockType,
isDisabled,
rootClientId,
isFirst,
isLast,
firstIndex,
orientation = 'vertical'
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlockIndex,
getBlockRootClientId,
getBlockOrder,
getBlock,
getBlockListSettings
} = select(store);
const firstClientId = normalizedClientIds[0];
const blockRootClientId = getBlockRootClientId(firstClientId);
const firstBlockIndex = getBlockIndex(firstClientId);
const lastBlockIndex = getBlockIndex(normalizedClientIds[normalizedClientIds.length - 1]);
const blockOrder = getBlockOrder(blockRootClientId);
const block = getBlock(firstClientId);
const isFirstBlock = firstBlockIndex === 0;
const isLastBlock = lastBlockIndex === blockOrder.length - 1;
const {
orientation: blockListOrientation
} = getBlockListSettings(blockRootClientId) || {};
return {
blockType: block ? (0,external_wp_blocks_namespaceObject.getBlockType)(block.name) : null,
isDisabled: direction === 'up' ? isFirstBlock : isLastBlock,
rootClientId: blockRootClientId,
firstIndex: firstBlockIndex,
isFirst: isFirstBlock,
isLast: isLastBlock,
orientation: moverOrientation || blockListOrientation
};
}, [clientIds, direction]);
const {
moveBlocksDown,
moveBlocksUp
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const moverFunction = direction === 'up' ? moveBlocksUp : moveBlocksDown;
const onClick = event => {
moverFunction(clientIds, rootClientId);
if (props.onClick) {
props.onClick(event);
}
};
const descriptionId = `block-editor-block-mover-button__description-${instanceId}`;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, _extends({
ref: ref,
className: classnames_default()('block-editor-block-mover-button', `is-${direction}-button`),
icon: getArrowIcon(direction, orientation),
label: getMovementDirectionLabel(direction, orientation),
"aria-describedby": descriptionId
}, props, {
onClick: isDisabled ? null : onClick,
disabled: isDisabled,
__experimentalIsFocusable: true
})), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.VisuallyHidden, {
id: descriptionId
}, getBlockMoverDescription(blocksCount, blockType && blockType.title, firstIndex, isFirst, isLast, direction === 'up' ? -1 : 1, orientation)));
});
const BlockMoverUpButton = (0,external_wp_element_namespaceObject.forwardRef)((props, ref) => {
return (0,external_wp_element_namespaceObject.createElement)(BlockMoverButton, _extends({
direction: "up",
ref: ref
}, props));
});
const BlockMoverDownButton = (0,external_wp_element_namespaceObject.forwardRef)((props, ref) => {
return (0,external_wp_element_namespaceObject.createElement)(BlockMoverButton, _extends({
direction: "down",
ref: ref
}, props));
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-mover/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function BlockMover(_ref) {
let {
clientIds,
hideDragHandle
} = _ref;
const {
canMove,
rootClientId,
isFirst,
isLast,
orientation
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _getBlockListSettings;
const {
getBlockIndex,
getBlockListSettings,
canMoveBlocks,
getBlockOrder,
getBlockRootClientId
} = select(store);
const normalizedClientIds = Array.isArray(clientIds) ? clientIds : [clientIds];
const firstClientId = normalizedClientIds[0];
const _rootClientId = getBlockRootClientId(firstClientId);
const firstIndex = getBlockIndex(firstClientId);
const lastIndex = getBlockIndex(normalizedClientIds[normalizedClientIds.length - 1]);
const blockOrder = getBlockOrder(_rootClientId);
return {
canMove: canMoveBlocks(clientIds, _rootClientId),
rootClientId: _rootClientId,
isFirst: firstIndex === 0,
isLast: lastIndex === blockOrder.length - 1,
orientation: (_getBlockListSettings = getBlockListSettings(_rootClientId)) === null || _getBlockListSettings === void 0 ? void 0 : _getBlockListSettings.orientation
};
}, [clientIds]);
if (!canMove || isFirst && isLast && !rootClientId) {
return null;
}
const dragHandleLabel = (0,external_wp_i18n_namespaceObject.__)('Drag');
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarGroup, {
className: classnames_default()('block-editor-block-mover', {
'is-horizontal': orientation === 'horizontal'
})
}, !hideDragHandle && (0,external_wp_element_namespaceObject.createElement)(block_draggable, {
clientIds: clientIds
}, draggableProps => (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, _extends({
icon: drag_handle,
className: "block-editor-block-mover__drag-handle",
"aria-hidden": "true",
label: dragHandleLabel // Should not be able to tab to drag handle as this
// button can only be used with a pointer device.
,
tabIndex: "-1"
}, draggableProps))), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-mover__move-button-container"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarItem, null, itemProps => (0,external_wp_element_namespaceObject.createElement)(BlockMoverUpButton, _extends({
clientIds: clientIds
}, itemProps))), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarItem, null, itemProps => (0,external_wp_element_namespaceObject.createElement)(BlockMoverDownButton, _extends({
clientIds: clientIds
}, itemProps)))));
}
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/block-mover/README.md
*/
/* harmony default export */ var block_mover = (BlockMover);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-tools/block-selection-button.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Block selection button component, displaying the label of the block. If the block
* descends from a root block, a button is displayed enabling the user to select
* the root block.
*
* @param {string} props Component props.
* @param {string} props.clientId Client ID of block.
*
* @return {WPComponent} The component to be rendered.
*/
function BlockSelectionButton(_ref) {
let {
clientId,
rootClientId
} = _ref;
const blockInformation = useBlockDisplayInformation(clientId);
const selected = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _getBlockListSettings;
const {
getBlock,
getBlockIndex,
hasBlockMovingClientId,
getBlockListSettings,
__unstableGetEditorMode
} = select(store);
const index = getBlockIndex(clientId);
const {
name,
attributes
} = getBlock(clientId);
const blockMovingMode = hasBlockMovingClientId();
return {
index,
name,
attributes,
blockMovingMode,
orientation: (_getBlockListSettings = getBlockListSettings(rootClientId)) === null || _getBlockListSettings === void 0 ? void 0 : _getBlockListSettings.orientation,
editorMode: __unstableGetEditorMode()
};
}, [clientId, rootClientId]);
const {
index,
name,
attributes,
blockMovingMode,
orientation,
editorMode
} = selected;
const {
setNavigationMode,
removeBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const ref = (0,external_wp_element_namespaceObject.useRef)();
const blockType = (0,external_wp_blocks_namespaceObject.getBlockType)(name);
const label = (0,external_wp_blocks_namespaceObject.__experimentalGetAccessibleBlockLabel)(blockType, attributes, index + 1, orientation); // Focus the breadcrumb in navigation mode.
(0,external_wp_element_namespaceObject.useEffect)(() => {
ref.current.focus();
(0,external_wp_a11y_namespaceObject.speak)(label);
}, [label]);
const blockElement = useBlockElement(clientId);
const {
hasBlockMovingClientId,
getBlockIndex,
getBlockRootClientId,
getClientIdsOfDescendants,
getSelectedBlockClientId,
getMultiSelectedBlocksEndClientId,
getPreviousBlockClientId,
getNextBlockClientId
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const {
selectBlock,
clearSelectedBlock,
setBlockMovingClientId,
moveBlockToPosition
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
function onKeyDown(event) {
const {
keyCode
} = event;
const isUp = keyCode === external_wp_keycodes_namespaceObject.UP;
const isDown = keyCode === external_wp_keycodes_namespaceObject.DOWN;
const isLeft = keyCode === external_wp_keycodes_namespaceObject.LEFT;
const isRight = keyCode === external_wp_keycodes_namespaceObject.RIGHT;
const isTab = keyCode === external_wp_keycodes_namespaceObject.TAB;
const isEscape = keyCode === external_wp_keycodes_namespaceObject.ESCAPE;
const isEnter = keyCode === external_wp_keycodes_namespaceObject.ENTER;
const isSpace = keyCode === external_wp_keycodes_namespaceObject.SPACE;
const isShift = event.shiftKey;
if (keyCode === external_wp_keycodes_namespaceObject.BACKSPACE || keyCode === external_wp_keycodes_namespaceObject.DELETE) {
removeBlock(clientId);
event.preventDefault();
return;
}
const selectedBlockClientId = getSelectedBlockClientId();
const selectionEndClientId = getMultiSelectedBlocksEndClientId();
const selectionBeforeEndClientId = getPreviousBlockClientId(selectionEndClientId || selectedBlockClientId);
const selectionAfterEndClientId = getNextBlockClientId(selectionEndClientId || selectedBlockClientId);
const navigateUp = isTab && isShift || isUp;
const navigateDown = isTab && !isShift || isDown; // Move out of current nesting level (no effect if at root level).
const navigateOut = isLeft; // Move into next nesting level (no effect if the current block has no innerBlocks).
const navigateIn = isRight;
let focusedBlockUid;
if (navigateUp) {
focusedBlockUid = selectionBeforeEndClientId;
} else if (navigateDown) {
focusedBlockUid = selectionAfterEndClientId;
} else if (navigateOut) {
var _getBlockRootClientId;
focusedBlockUid = (_getBlockRootClientId = getBlockRootClientId(selectedBlockClientId)) !== null && _getBlockRootClientId !== void 0 ? _getBlockRootClientId : selectedBlockClientId;
} else if (navigateIn) {
var _getClientIdsOfDescen;
focusedBlockUid = (_getClientIdsOfDescen = getClientIdsOfDescendants([selectedBlockClientId])[0]) !== null && _getClientIdsOfDescen !== void 0 ? _getClientIdsOfDescen : selectedBlockClientId;
}
const startingBlockClientId = hasBlockMovingClientId();
if (isEscape && startingBlockClientId && !event.defaultPrevented) {
setBlockMovingClientId(null);
event.preventDefault();
}
if ((isEnter || isSpace) && startingBlockClientId) {
const sourceRoot = getBlockRootClientId(startingBlockClientId);
const destRoot = getBlockRootClientId(selectedBlockClientId);
const sourceBlockIndex = getBlockIndex(startingBlockClientId);
let destinationBlockIndex = getBlockIndex(selectedBlockClientId);
if (sourceBlockIndex < destinationBlockIndex && sourceRoot === destRoot) {
destinationBlockIndex -= 1;
}
moveBlockToPosition(startingBlockClientId, sourceRoot, destRoot, destinationBlockIndex);
selectBlock(startingBlockClientId);
setBlockMovingClientId(null);
}
if (navigateDown || navigateUp || navigateOut || navigateIn) {
if (focusedBlockUid) {
event.preventDefault();
selectBlock(focusedBlockUid);
} else if (isTab && selectedBlockClientId) {
let nextTabbable;
if (navigateDown) {
nextTabbable = blockElement;
do {
nextTabbable = external_wp_dom_namespaceObject.focus.tabbable.findNext(nextTabbable);
} while (nextTabbable && blockElement.contains(nextTabbable));
if (!nextTabbable) {
nextTabbable = blockElement.ownerDocument.defaultView.frameElement;
nextTabbable = external_wp_dom_namespaceObject.focus.tabbable.findNext(nextTabbable);
}
} else {
nextTabbable = external_wp_dom_namespaceObject.focus.tabbable.findPrevious(blockElement);
}
if (nextTabbable) {
event.preventDefault();
nextTabbable.focus();
clearSelectedBlock();
}
}
}
}
const classNames = classnames_default()('block-editor-block-list__block-selection-button', {
'is-block-moving-mode': !!blockMovingMode
});
const dragHandleLabel = (0,external_wp_i18n_namespaceObject.__)('Drag');
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classNames
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Flex, {
justify: "center",
className: "block-editor-block-list__block-selection-button__content"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexItem, null, (0,external_wp_element_namespaceObject.createElement)(block_icon, {
icon: blockInformation === null || blockInformation === void 0 ? void 0 : blockInformation.icon,
showColors: true
})), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexItem, null, editorMode === 'zoom-out' && (0,external_wp_element_namespaceObject.createElement)(block_mover, {
clientIds: [clientId],
hideDragHandle: true
}), editorMode === 'navigation' && (0,external_wp_element_namespaceObject.createElement)(block_draggable, {
clientIds: [clientId]
}, draggableProps => (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, _extends({
icon: drag_handle,
className: "block-selection-button_drag-handle",
"aria-hidden": "true",
label: dragHandleLabel // Should not be able to tab to drag handle as this
// button can only be used with a pointer device.
,
tabIndex: "-1"
}, draggableProps)))), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexItem, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
ref: ref,
onClick: editorMode === 'navigation' ? () => setNavigationMode(false) : undefined,
onKeyDown: onKeyDown,
label: label,
showTooltip: false,
className: "block-selection-button_select-button"
}, (0,external_wp_element_namespaceObject.createElement)(BlockTitle, {
clientId: clientId,
maximumLength: 35
})))));
}
/* harmony default export */ var block_selection_button = (BlockSelectionButton);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/navigable-toolbar/index.js
/**
* WordPress dependencies
*/
function hasOnlyToolbarItem(elements) {
const dataProp = 'toolbarItem';
return !elements.some(element => !(dataProp in element.dataset));
}
function getAllToolbarItemsIn(container) {
return Array.from(container.querySelectorAll('[data-toolbar-item]'));
}
function hasFocusWithin(container) {
return container.contains(container.ownerDocument.activeElement);
}
function focusFirstTabbableIn(container) {
const [firstTabbable] = external_wp_dom_namespaceObject.focus.tabbable.find(container);
if (firstTabbable) {
firstTabbable.focus({
// When focusing newly mounted toolbars,
// the position of the popover is often not right on the first render
// This prevents the layout shifts when focusing the dialogs.
preventScroll: true
});
}
}
function useIsAccessibleToolbar(ref) {
/*
* By default, we'll assume the starting accessible state of the Toolbar
* is true, as it seems to be the most common case.
*
* Transitioning from an (initial) false to true state causes the
* <Toolbar /> component to mount twice, which is causing undesired
* side-effects. These side-effects appear to only affect certain
* E2E tests.
*
* This was initial discovered in this pull-request:
* https://github.com/WordPress/gutenberg/pull/23425
*/
const initialAccessibleToolbarState = true; // By default, it's gonna render NavigableMenu. If all the tabbable elements
// inside the toolbar are ToolbarItem components (or derived components like
// ToolbarButton), then we can wrap them with the accessible Toolbar
// component.
const [isAccessibleToolbar, setIsAccessibleToolbar] = (0,external_wp_element_namespaceObject.useState)(initialAccessibleToolbarState);
const determineIsAccessibleToolbar = (0,external_wp_element_namespaceObject.useCallback)(() => {
const tabbables = external_wp_dom_namespaceObject.focus.tabbable.find(ref.current);
const onlyToolbarItem = hasOnlyToolbarItem(tabbables);
if (!onlyToolbarItem) {
external_wp_deprecated_default()('Using custom components as toolbar controls', {
since: '5.6',
alternative: 'ToolbarItem, ToolbarButton or ToolbarDropdownMenu components',
link: 'https://developer.wordpress.org/block-editor/components/toolbar-button/#inside-blockcontrols'
});
}
setIsAccessibleToolbar(onlyToolbarItem);
}, []);
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
// Toolbar buttons may be rendered asynchronously, so we use
// MutationObserver to check if the toolbar subtree has been modified.
const observer = new window.MutationObserver(determineIsAccessibleToolbar);
observer.observe(ref.current, {
childList: true,
subtree: true
});
return () => observer.disconnect();
}, [isAccessibleToolbar]);
return isAccessibleToolbar;
}
function useToolbarFocus(ref, focusOnMount, isAccessibleToolbar, defaultIndex, onIndexChange) {
// Make sure we don't use modified versions of this prop.
const [initialFocusOnMount] = (0,external_wp_element_namespaceObject.useState)(focusOnMount);
const [initialIndex] = (0,external_wp_element_namespaceObject.useState)(defaultIndex);
const focusToolbar = (0,external_wp_element_namespaceObject.useCallback)(() => {
focusFirstTabbableIn(ref.current);
}, []); // Focus on toolbar when pressing alt+F10 when the toolbar is visible.
(0,external_wp_keyboardShortcuts_namespaceObject.useShortcut)('core/block-editor/focus-toolbar', focusToolbar);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (initialFocusOnMount) {
focusToolbar();
}
}, [isAccessibleToolbar, initialFocusOnMount, focusToolbar]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
// If initialIndex is passed, we focus on that toolbar item when the
// toolbar gets mounted and initial focus is not forced.
// We have to wait for the next browser paint because block controls aren't
// rendered right away when the toolbar gets mounted.
let raf = 0;
if (initialIndex && !initialFocusOnMount) {
raf = window.requestAnimationFrame(() => {
const items = getAllToolbarItemsIn(ref.current);
const index = initialIndex || 0;
if (items[index] && hasFocusWithin(ref.current)) {
items[index].focus({
// When focusing newly mounted toolbars,
// the position of the popover is often not right on the first render
// This prevents the layout shifts when focusing the dialogs.
preventScroll: true
});
}
});
}
return () => {
window.cancelAnimationFrame(raf);
if (!onIndexChange || !ref.current) return; // When the toolbar element is unmounted and onIndexChange is passed, we
// pass the focused toolbar item index so it can be hydrated later.
const items = getAllToolbarItemsIn(ref.current);
const index = items.findIndex(item => item.tabIndex === 0);
onIndexChange(index);
};
}, [initialIndex, initialFocusOnMount]);
}
function NavigableToolbar(_ref) {
let {
children,
focusOnMount,
__experimentalInitialIndex: initialIndex,
__experimentalOnIndexChange: onIndexChange,
...props
} = _ref;
const ref = (0,external_wp_element_namespaceObject.useRef)();
const isAccessibleToolbar = useIsAccessibleToolbar(ref);
useToolbarFocus(ref, focusOnMount, isAccessibleToolbar, initialIndex, onIndexChange);
if (isAccessibleToolbar) {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Toolbar, _extends({
label: props['aria-label'],
ref: ref
}, props), children);
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.NavigableMenu, _extends({
orientation: "horizontal",
role: "toolbar",
ref: ref
}, props), children);
}
/* harmony default export */ var navigable_toolbar = (NavigableToolbar);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-toolbar/utils.js
/**
* WordPress dependencies
*/
const {
clearTimeout: utils_clearTimeout,
setTimeout: utils_setTimeout
} = window;
const utils_noop = () => {};
const DEBOUNCE_TIMEOUT = 200;
/**
* Hook that creates a showMover state, as well as debounced show/hide callbacks.
*
* @param {Object} props Component props.
* @param {Object} props.ref Element reference.
* @param {boolean} props.isFocused Whether the component has current focus.
* @param {number} [props.debounceTimeout=250] Debounce timeout in milliseconds.
* @param {Function} [props.onChange=noop] Callback function.
*/
function useDebouncedShowMovers(_ref) {
let {
ref,
isFocused,
debounceTimeout = DEBOUNCE_TIMEOUT,
onChange = utils_noop
} = _ref;
const [showMovers, setShowMovers] = (0,external_wp_element_namespaceObject.useState)(false);
const timeoutRef = (0,external_wp_element_namespaceObject.useRef)();
const handleOnChange = nextIsFocused => {
if (ref !== null && ref !== void 0 && ref.current) {
setShowMovers(nextIsFocused);
}
onChange(nextIsFocused);
};
const getIsHovered = () => {
return (ref === null || ref === void 0 ? void 0 : ref.current) && ref.current.matches(':hover');
};
const shouldHideMovers = () => {
const isHovered = getIsHovered();
return !isFocused && !isHovered;
};
const clearTimeoutRef = () => {
const timeout = timeoutRef.current;
if (timeout && utils_clearTimeout) {
utils_clearTimeout(timeout);
}
};
const debouncedShowMovers = event => {
if (event) {
event.stopPropagation();
}
clearTimeoutRef();
if (!showMovers) {
handleOnChange(true);
}
};
const debouncedHideMovers = event => {
if (event) {
event.stopPropagation();
}
clearTimeoutRef();
timeoutRef.current = utils_setTimeout(() => {
if (shouldHideMovers()) {
handleOnChange(false);
}
}, debounceTimeout);
};
(0,external_wp_element_namespaceObject.useEffect)(() => () => {
/**
* We need to call the change handler with `isFocused`
* set to false on unmount because we also clear the
* timeout that would handle that.
*/
handleOnChange(false);
clearTimeoutRef();
}, []);
return {
showMovers,
debouncedShowMovers,
debouncedHideMovers
};
}
/**
* Hook that provides a showMovers state and gesture events for DOM elements
* that interact with the showMovers state.
*
* @param {Object} props Component props.
* @param {Object} props.ref Element reference.
* @param {number} [props.debounceTimeout=250] Debounce timeout in milliseconds.
* @param {Function} [props.onChange=noop] Callback function.
*/
function useShowMoversGestures(_ref2) {
let {
ref,
debounceTimeout = DEBOUNCE_TIMEOUT,
onChange = utils_noop
} = _ref2;
const [isFocused, setIsFocused] = (0,external_wp_element_namespaceObject.useState)(false);
const {
showMovers,
debouncedShowMovers,
debouncedHideMovers
} = useDebouncedShowMovers({
ref,
debounceTimeout,
isFocused,
onChange
});
const registerRef = (0,external_wp_element_namespaceObject.useRef)(false);
const isFocusedWithin = () => {
return (ref === null || ref === void 0 ? void 0 : ref.current) && ref.current.contains(ref.current.ownerDocument.activeElement);
};
(0,external_wp_element_namespaceObject.useEffect)(() => {
const node = ref.current;
const handleOnFocus = () => {
if (isFocusedWithin()) {
setIsFocused(true);
debouncedShowMovers();
}
};
const handleOnBlur = () => {
if (!isFocusedWithin()) {
setIsFocused(false);
debouncedHideMovers();
}
};
/**
* Events are added via DOM events (vs. React synthetic events),
* as the child React components swallow mouse events.
*/
if (node && !registerRef.current) {
node.addEventListener('focus', handleOnFocus, true);
node.addEventListener('blur', handleOnBlur, true);
registerRef.current = true;
}
return () => {
if (node) {
node.removeEventListener('focus', handleOnFocus);
node.removeEventListener('blur', handleOnBlur);
}
};
}, [ref, registerRef, setIsFocused, debouncedShowMovers, debouncedHideMovers]);
return {
showMovers,
gestures: {
onMouseMove: debouncedShowMovers,
onMouseLeave: debouncedHideMovers
}
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-parent-selector/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Block parent selector component, displaying the hierarchy of the
* current block selection as a single icon to "go up" a level.
*
* @return {WPComponent} Parent block selector.
*/
function BlockParentSelector() {
const {
selectBlock,
toggleBlockHighlight
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const {
firstParentClientId,
shouldHide,
isDistractionFree
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlockName,
getBlockParents,
getSelectedBlockClientId,
getSettings
} = select(store);
const {
hasBlockSupport
} = select(external_wp_blocks_namespaceObject.store);
const selectedBlockClientId = getSelectedBlockClientId();
const parents = getBlockParents(selectedBlockClientId);
const _firstParentClientId = parents[parents.length - 1];
const parentBlockName = getBlockName(_firstParentClientId);
const _parentBlockType = (0,external_wp_blocks_namespaceObject.getBlockType)(parentBlockName);
const settings = getSettings();
return {
firstParentClientId: _firstParentClientId,
shouldHide: !hasBlockSupport(_parentBlockType, '__experimentalParentSelector', true),
isDistractionFree: settings.isDistractionFree
};
}, []);
const blockInformation = useBlockDisplayInformation(firstParentClientId); // Allows highlighting the parent block outline when focusing or hovering
// the parent block selector within the child.
const nodeRef = (0,external_wp_element_namespaceObject.useRef)();
const {
gestures: showMoversGestures
} = useShowMoversGestures({
ref: nodeRef,
onChange(isFocused) {
if (isFocused && isDistractionFree) {
return;
}
toggleBlockHighlight(firstParentClientId, isFocused);
}
});
if (shouldHide || firstParentClientId === undefined) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)("div", _extends({
className: "block-editor-block-parent-selector",
key: firstParentClientId,
ref: nodeRef
}, showMoversGestures), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
className: "block-editor-block-parent-selector__button",
onClick: () => selectBlock(firstParentClientId),
label: (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: Name of the block's parent. */
(0,external_wp_i18n_namespaceObject.__)('Select %s'), blockInformation === null || blockInformation === void 0 ? void 0 : blockInformation.title),
showTooltip: true,
icon: (0,external_wp_element_namespaceObject.createElement)(block_icon, {
icon: blockInformation === null || blockInformation === void 0 ? void 0 : blockInformation.icon
})
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/copy.js
/**
* WordPress dependencies
*/
const copy = (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: "M20.2 8v11c0 .7-.6 1.2-1.2 1.2H6v1.5h13c1.5 0 2.7-1.2 2.7-2.8V8zM18 16.4V4.6c0-.9-.7-1.6-1.6-1.6H4.6C3.7 3 3 3.7 3 4.6v11.8c0 .9.7 1.6 1.6 1.6h11.8c.9 0 1.6-.7 1.6-1.6zm-13.5 0V4.6c0-.1.1-.1.1-.1h11.8c.1 0 .1.1.1.1v11.8c0 .1-.1.1-.1.1H4.6l-.1-.1z"
}));
/* harmony default export */ var library_copy = (copy);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-switcher/preview-block-popover.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PreviewBlockPopover(_ref) {
let {
blocks
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-switcher__popover__preview__parent"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-switcher__popover__preview__container"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Popover, {
className: "block-editor-block-switcher__preview__popover",
placement: "bottom-start",
focusOnMount: false
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-switcher__preview"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-switcher__preview-title"
}, (0,external_wp_i18n_namespaceObject.__)('Preview')), (0,external_wp_element_namespaceObject.createElement)(block_preview, {
viewportWidth: 500,
blocks: blocks
})))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-switcher/block-transformations-menu.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Helper hook to group transformations to display them in a specific order in the UI.
* For now we group only priority content driven transformations(ex. paragraph -> heading).
*
* Later on we could also group 'layout' transformations(ex. paragraph -> group) and
* display them in different sections.
*
* @param {Object[]} possibleBlockTransformations The available block transformations.
* @return {Record<string, Object[]>} The grouped block transformations.
*/
function useGroupedTransforms(possibleBlockTransformations) {
const priorityContentTranformationBlocks = {
'core/paragraph': 1,
'core/heading': 2,
'core/list': 3,
'core/quote': 4
};
const transformations = (0,external_wp_element_namespaceObject.useMemo)(() => {
const priorityTextTranformsNames = Object.keys(priorityContentTranformationBlocks);
return possibleBlockTransformations.reduce((accumulator, item) => {
const {
name
} = item;
if (priorityTextTranformsNames.includes(name)) {
accumulator.priorityTextTransformations.push(item);
} else {
accumulator.restTransformations.push(item);
}
return accumulator;
}, {
priorityTextTransformations: [],
restTransformations: []
});
}, [possibleBlockTransformations]); // Order the priority text transformations.
transformations.priorityTextTransformations.sort((_ref, _ref2) => {
let {
name: currentName
} = _ref;
let {
name: nextName
} = _ref2;
return priorityContentTranformationBlocks[currentName] < priorityContentTranformationBlocks[nextName] ? -1 : 1;
});
return transformations;
}
const BlockTransformationsMenu = _ref3 => {
let {
className,
possibleBlockTransformations,
onSelect,
blocks
} = _ref3;
const [hoveredTransformItemName, setHoveredTransformItemName] = (0,external_wp_element_namespaceObject.useState)();
const {
priorityTextTransformations,
restTransformations
} = useGroupedTransforms(possibleBlockTransformations); // We have to check if both content transformations(priority and rest) are set
// in order to create a separate MenuGroup for them.
const hasBothContentTransformations = priorityTextTransformations.length && restTransformations.length;
const restTransformItems = !!restTransformations.length && (0,external_wp_element_namespaceObject.createElement)(RestTransformationItems, {
restTransformations: restTransformations,
onSelect: onSelect,
setHoveredTransformItemName: setHoveredTransformItemName
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, {
label: (0,external_wp_i18n_namespaceObject.__)('Transform to'),
className: className
}, hoveredTransformItemName && (0,external_wp_element_namespaceObject.createElement)(PreviewBlockPopover, {
blocks: (0,external_wp_blocks_namespaceObject.switchToBlockType)(blocks, hoveredTransformItemName)
}), priorityTextTransformations.map(item => (0,external_wp_element_namespaceObject.createElement)(BlockTranformationItem, {
key: item.name,
item: item,
onSelect: onSelect,
setHoveredTransformItemName: setHoveredTransformItemName
})), !hasBothContentTransformations && restTransformItems), !!hasBothContentTransformations && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, {
className: className
}, restTransformItems));
};
function RestTransformationItems(_ref4) {
let {
restTransformations,
onSelect,
setHoveredTransformItemName
} = _ref4;
return restTransformations.map(item => (0,external_wp_element_namespaceObject.createElement)(BlockTranformationItem, {
key: item.name,
item: item,
onSelect: onSelect,
setHoveredTransformItemName: setHoveredTransformItemName
}));
}
function BlockTranformationItem(_ref5) {
let {
item,
onSelect,
setHoveredTransformItemName
} = _ref5;
const {
name,
icon,
title,
isDisabled
} = item;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
className: (0,external_wp_blocks_namespaceObject.getBlockMenuDefaultClassName)(name),
onClick: event => {
event.preventDefault();
onSelect(name);
},
disabled: isDisabled,
onMouseLeave: () => setHoveredTransformItemName(null),
onMouseEnter: () => setHoveredTransformItemName(name)
}, (0,external_wp_element_namespaceObject.createElement)(block_icon, {
icon: icon,
showColors: true
}), title);
}
/* harmony default export */ var block_transformations_menu = (BlockTransformationsMenu);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/check.js
/**
* WordPress dependencies
*/
const check_check = (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: "M16.7 7.1l-6.3 8.5-3.3-2.5-.9 1.2 4.5 3.4L17.9 8z"
}));
/* harmony default export */ var library_check = (check_check);
;// CONCATENATED MODULE: external ["wp","tokenList"]
var external_wp_tokenList_namespaceObject = window["wp"]["tokenList"];
var external_wp_tokenList_default = /*#__PURE__*/__webpack_require__.n(external_wp_tokenList_namespaceObject);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-styles/utils.js
/**
* WordPress dependencies
*/
/**
* Returns the active style from the given className.
*
* @param {Array} styles Block styles.
* @param {string} className Class name
*
* @return {Object?} The active style.
*/
function getActiveStyle(styles, className) {
for (const style of new (external_wp_tokenList_default())(className).values()) {
if (style.indexOf('is-style-') === -1) {
continue;
}
const potentialStyleName = style.substring(9);
const activeStyle = styles === null || styles === void 0 ? void 0 : styles.find(_ref => {
let {
name
} = _ref;
return name === potentialStyleName;
});
if (activeStyle) {
return activeStyle;
}
}
return getDefaultStyle(styles);
}
/**
* Replaces the active style in the block's className.
*
* @param {string} className Class name.
* @param {Object?} activeStyle The replaced style.
* @param {Object} newStyle The replacing style.
*
* @return {string} The updated className.
*/
function replaceActiveStyle(className, activeStyle, newStyle) {
const list = new (external_wp_tokenList_default())(className);
if (activeStyle) {
list.remove('is-style-' + activeStyle.name);
}
list.add('is-style-' + newStyle.name);
return list.value;
}
/**
* Returns a collection of styles that can be represented on the frontend.
* The function checks a style collection for a default style. If none is found, it adds one to
* act as a fallback for when there is no active style applied to a block. The default item also serves
* as a switch on the frontend to deactivate non-default styles.
*
* @param {Array} styles Block styles.
*
* @return {Array<Object?>} The style collection.
*/
function getRenderedStyles(styles) {
if (!styles || styles.length === 0) {
return [];
}
return getDefaultStyle(styles) ? styles : [{
name: 'default',
label: (0,external_wp_i18n_namespaceObject._x)('Default', 'block style'),
isDefault: true
}, ...styles];
}
/**
* Returns a style object from a collection of styles where that style object is the default block style.
*
* @param {Array} styles Block styles.
*
* @return {Object?} The default style object, if found.
*/
function getDefaultStyle(styles) {
return styles === null || styles === void 0 ? void 0 : styles.find(style => style.isDefault);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-styles/use-styles-for-block.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
*
* @param {WPBlock} block Block object.
* @param {WPBlockType} type Block type settings.
* @return {WPBlock} A generic block ready for styles preview.
*/
function useGenericPreviewBlock(block, type) {
return (0,external_wp_element_namespaceObject.useMemo)(() => {
const example = type === null || type === void 0 ? void 0 : type.example;
const blockName = type === null || type === void 0 ? void 0 : type.name;
if (example && blockName) {
return (0,external_wp_blocks_namespaceObject.getBlockFromExample)(blockName, {
attributes: example.attributes,
innerBlocks: example.innerBlocks
});
}
if (block) {
return (0,external_wp_blocks_namespaceObject.cloneBlock)(block);
}
}, [type !== null && type !== void 0 && type.example ? block === null || block === void 0 ? void 0 : block.name : block, type]);
}
/**
* @typedef useStylesForBlocksArguments
* @property {string} clientId Block client ID.
* @property {() => void} onSwitch Block style switch callback function.
*/
/**
*
* @param {useStylesForBlocksArguments} useStylesForBlocks arguments.
* @return {Object} Results of the select methods.
*/
function useStylesForBlocks(_ref) {
let {
clientId,
onSwitch
} = _ref;
const selector = select => {
const {
getBlock
} = select(store);
const block = getBlock(clientId);
if (!block) {
return {};
}
const blockType = (0,external_wp_blocks_namespaceObject.getBlockType)(block.name);
const {
getBlockStyles
} = select(external_wp_blocks_namespaceObject.store);
return {
block,
blockType,
styles: getBlockStyles(block.name),
className: block.attributes.className || ''
};
};
const {
styles,
block,
blockType,
className
} = (0,external_wp_data_namespaceObject.useSelect)(selector, [clientId]);
const {
updateBlockAttributes
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const stylesToRender = getRenderedStyles(styles);
const activeStyle = getActiveStyle(stylesToRender, className);
const genericPreviewBlock = useGenericPreviewBlock(block, blockType);
const onSelect = style => {
const styleClassName = replaceActiveStyle(className, activeStyle, style);
updateBlockAttributes(clientId, {
className: styleClassName
});
onSwitch();
};
return {
onSelect,
stylesToRender,
activeStyle,
genericPreviewBlock,
className
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-styles/menu-items.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const menu_items_noop = () => {};
function BlockStylesMenuItems(_ref) {
let {
clientId,
onSwitch = menu_items_noop
} = _ref;
const {
onSelect,
stylesToRender,
activeStyle
} = useStylesForBlocks({
clientId,
onSwitch
});
if (!stylesToRender || stylesToRender.length === 0) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, stylesToRender.map(style => {
const menuItemText = style.label || style.name;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
key: style.name,
icon: activeStyle.name === style.name ? library_check : null,
onClick: () => onSelect(style)
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalText, {
as: "span",
limit: 18,
ellipsizeMode: "tail",
truncate: true
}, menuItemText));
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-switcher/block-styles-menu.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function BlockStylesMenu(_ref) {
let {
hoveredBlock,
onSwitch
} = _ref;
const {
clientId
} = hoveredBlock;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, {
label: (0,external_wp_i18n_namespaceObject.__)('Styles'),
className: "block-editor-block-switcher__styles__menugroup"
}, (0,external_wp_element_namespaceObject.createElement)(BlockStylesMenuItems, {
clientId: clientId,
onSwitch: onSwitch
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-switcher/utils.js
/**
* WordPress dependencies
*/
/**
* Try to find a matching block by a block's name in a provided
* block. We recurse through InnerBlocks and return the reference
* of the matched block (it could be an InnerBlock).
* If no match is found return nothing.
*
* @param {WPBlock} block The block to try to find a match.
* @param {string} selectedBlockName The block's name to use for matching condition.
* @param {Set} consumedBlocks A set holding the previously matched/consumed blocks.
*
* @return {WPBlock | undefined} The matched block if found or nothing(`undefined`).
*/
const getMatchingBlockByName = function (block, selectedBlockName) {
let consumedBlocks = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Set();
const {
clientId,
name,
innerBlocks = []
} = block; // Check if block has been consumed already.
if (consumedBlocks.has(clientId)) return;
if (name === selectedBlockName) return block; // Try to find a matching block from InnerBlocks recursively.
for (const innerBlock of innerBlocks) {
const match = getMatchingBlockByName(innerBlock, selectedBlockName, consumedBlocks);
if (match) return match;
}
};
/**
* Find and return the block attributes to retain through
* the transformation, based on Block Type's `role:content`
* attributes. If no `role:content` attributes exist,
* return selected block's attributes.
*
* @param {string} name Block type's namespaced name.
* @param {Object} attributes Selected block's attributes.
* @return {Object} The block's attributes to retain.
*/
const getRetainedBlockAttributes = (name, attributes) => {
const contentAttributes = (0,external_wp_blocks_namespaceObject.__experimentalGetBlockAttributesNamesByRole)(name, 'content');
if (!(contentAttributes !== null && contentAttributes !== void 0 && contentAttributes.length)) return attributes;
return contentAttributes.reduce((_accumulator, attribute) => {
if (attributes[attribute]) _accumulator[attribute] = attributes[attribute];
return _accumulator;
}, {});
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-switcher/use-transformed-patterns.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Mutate the matched block's attributes by getting
* which block type's attributes to retain and prioritize
* them in the merging of the attributes.
*
* @param {WPBlock} match The matched block.
* @param {WPBlock} selectedBlock The selected block.
* @return {void}
*/
const transformMatchingBlock = (match, selectedBlock) => {
// Get the block attributes to retain through the transformation.
const retainedBlockAttributes = getRetainedBlockAttributes(selectedBlock.name, selectedBlock.attributes);
match.attributes = { ...match.attributes,
...retainedBlockAttributes
};
};
/**
* By providing the selected blocks and pattern's blocks
* find the matching blocks, transform them and return them.
* If not all selected blocks are matched, return nothing.
*
* @param {WPBlock[]} selectedBlocks The selected blocks.
* @param {WPBlock[]} patternBlocks The pattern's blocks.
* @return {WPBlock[]|void} The transformed pattern's blocks or undefined if not all selected blocks have been matched.
*/
const getPatternTransformedBlocks = (selectedBlocks, patternBlocks) => {
// Clone Pattern's blocks to produce new clientIds and be able to mutate the matches.
const _patternBlocks = patternBlocks.map(block => (0,external_wp_blocks_namespaceObject.cloneBlock)(block));
/**
* Keep track of the consumed pattern blocks.
* This is needed because we loop the selected blocks
* and for example we may have selected two paragraphs and
* the pattern's blocks could have more `paragraphs`.
*/
const consumedBlocks = new Set();
for (const selectedBlock of selectedBlocks) {
let isMatch = false;
for (const patternBlock of _patternBlocks) {
const match = getMatchingBlockByName(patternBlock, selectedBlock.name, consumedBlocks);
if (!match) continue;
isMatch = true;
consumedBlocks.add(match.clientId); // We update (mutate) the matching pattern block.
transformMatchingBlock(match, selectedBlock); // No need to loop through other pattern's blocks.
break;
} // Bail eary if a selected block has not been matched.
if (!isMatch) return;
}
return _patternBlocks;
};
/**
* @typedef {WPBlockPattern & {transformedBlocks: WPBlock[]}} TransformedBlockPattern
*/
/**
* Custom hook that accepts patterns from state and the selected
* blocks and tries to match these with the pattern's blocks.
* If all selected blocks are matched with a Pattern's block,
* we transform them by retaining block's attributes with `role:content`.
* The transformed pattern's blocks are set to a new pattern
* property `transformedBlocks`.
*
* @param {WPBlockPattern[]} patterns Patterns from state.
* @param {WPBlock[]} selectedBlocks The currently selected blocks.
* @return {TransformedBlockPattern[]} Returns the eligible matched patterns with all the selected blocks.
*/
const useTransformedPatterns = (patterns, selectedBlocks) => {
return (0,external_wp_element_namespaceObject.useMemo)(() => patterns.reduce((accumulator, _pattern) => {
const transformedBlocks = getPatternTransformedBlocks(selectedBlocks, _pattern.blocks);
if (transformedBlocks) {
accumulator.push({ ..._pattern,
transformedBlocks
});
}
return accumulator;
}, []), [patterns, selectedBlocks]);
};
/* harmony default export */ var use_transformed_patterns = (useTransformedPatterns);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-switcher/pattern-transformations-menu.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PatternTransformationsMenu(_ref) {
let {
blocks,
patterns: statePatterns,
onSelect
} = _ref;
const [showTransforms, setShowTransforms] = (0,external_wp_element_namespaceObject.useState)(false);
const patterns = use_transformed_patterns(statePatterns, blocks);
if (!patterns.length) return null;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, {
className: "block-editor-block-switcher__pattern__transforms__menugroup"
}, showTransforms && (0,external_wp_element_namespaceObject.createElement)(PreviewPatternsPopover, {
patterns: patterns,
onSelect: onSelect
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
onClick: event => {
event.preventDefault();
setShowTransforms(!showTransforms);
},
icon: chevron_right
}, (0,external_wp_i18n_namespaceObject.__)('Patterns')));
}
function PreviewPatternsPopover(_ref2) {
let {
patterns,
onSelect
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-switcher__popover__preview__parent"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-switcher__popover__preview__container"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Popover, {
className: "block-editor-block-switcher__preview__popover",
position: "bottom right"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-switcher__preview"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-switcher__preview-title"
}, (0,external_wp_i18n_namespaceObject.__)('Preview')), (0,external_wp_element_namespaceObject.createElement)(BlockPatternsList, {
patterns: patterns,
onSelect: onSelect
})))));
}
function BlockPatternsList(_ref3) {
let {
patterns,
onSelect
} = _ref3;
const composite = (0,external_wp_components_namespaceObject.__unstableUseCompositeState)();
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableComposite, _extends({}, composite, {
role: "listbox",
className: "block-editor-block-switcher__preview-patterns-container",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Patterns list')
}), patterns.map(pattern => (0,external_wp_element_namespaceObject.createElement)(pattern_transformations_menu_BlockPattern, {
key: pattern.name,
pattern: pattern,
onSelect: onSelect,
composite: composite
})));
}
function pattern_transformations_menu_BlockPattern(_ref4) {
let {
pattern,
onSelect,
composite
} = _ref4;
// TODO check pattern/preview width...
const baseClassName = 'block-editor-block-switcher__preview-patterns-container';
const descriptionId = (0,external_wp_compose_namespaceObject.useInstanceId)(pattern_transformations_menu_BlockPattern, `${baseClassName}-list__item-description`);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: `${baseClassName}-list__list-item`,
"aria-label": pattern.title,
"aria-describedby": pattern.description ? descriptionId : undefined
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableCompositeItem, _extends({
role: "option",
as: "div"
}, composite, {
className: `${baseClassName}-list__item`,
onClick: () => onSelect(pattern.transformedBlocks)
}), (0,external_wp_element_namespaceObject.createElement)(block_preview, {
blocks: pattern.transformedBlocks,
viewportWidth: pattern.viewportWidth || 500
}), (0,external_wp_element_namespaceObject.createElement)("div", {
className: `${baseClassName}-list__item-title`
}, pattern.title)), !!pattern.description && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.VisuallyHidden, {
id: descriptionId
}, pattern.description));
}
/* harmony default export */ var pattern_transformations_menu = (PatternTransformationsMenu);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-switcher/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const BlockSwitcherDropdownMenu = _ref => {
let {
clientIds,
blocks
} = _ref;
const {
replaceBlocks,
multiSelect
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const blockInformation = useBlockDisplayInformation(blocks[0].clientId);
const {
possibleBlockTransformations,
canRemove,
hasBlockStyles,
icon,
patterns
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlockRootClientId,
getBlockTransformItems,
__experimentalGetPatternTransformItems
} = select(store);
const {
getBlockStyles,
getBlockType
} = select(external_wp_blocks_namespaceObject.store);
const {
canRemoveBlocks
} = select(store);
const rootClientId = getBlockRootClientId(Array.isArray(clientIds) ? clientIds[0] : clientIds);
const [{
name: firstBlockName
}] = blocks;
const _isSingleBlockSelected = blocks.length === 1;
const styles = _isSingleBlockSelected && getBlockStyles(firstBlockName);
let _icon;
if (_isSingleBlockSelected) {
_icon = blockInformation === null || blockInformation === void 0 ? void 0 : blockInformation.icon; // Take into account active block variations.
} else {
var _getBlockType;
const isSelectionOfSameType = new Set(blocks.map(_ref2 => {
let {
name
} = _ref2;
return name;
})).size === 1; // When selection consists of blocks of multiple types, display an
// appropriate icon to communicate the non-uniformity.
_icon = isSelectionOfSameType ? (_getBlockType = getBlockType(firstBlockName)) === null || _getBlockType === void 0 ? void 0 : _getBlockType.icon : library_copy;
}
return {
possibleBlockTransformations: getBlockTransformItems(blocks, rootClientId),
canRemove: canRemoveBlocks(clientIds, rootClientId),
hasBlockStyles: !!(styles !== null && styles !== void 0 && styles.length),
icon: _icon,
patterns: __experimentalGetPatternTransformItems(blocks, rootClientId)
};
}, [clientIds, blocks, blockInformation === null || blockInformation === void 0 ? void 0 : blockInformation.icon]);
const blockTitle = useBlockDisplayTitle({
clientId: Array.isArray(clientIds) ? clientIds[0] : clientIds,
maximumLength: 35
});
const isReusable = blocks.length === 1 && (0,external_wp_blocks_namespaceObject.isReusableBlock)(blocks[0]);
const isTemplate = blocks.length === 1 && (0,external_wp_blocks_namespaceObject.isTemplatePart)(blocks[0]);
function selectForMultipleBlocks(insertedBlocks) {
if (insertedBlocks.length > 1) {
multiSelect(insertedBlocks[0].clientId, insertedBlocks[insertedBlocks.length - 1].clientId);
}
} // Simple block tranformation based on the `Block Transforms` API.
function onBlockTransform(name) {
const newBlocks = (0,external_wp_blocks_namespaceObject.switchToBlockType)(blocks, name);
replaceBlocks(clientIds, newBlocks);
selectForMultipleBlocks(newBlocks);
} // Pattern transformation through the `Patterns` API.
function onPatternTransform(transformedBlocks) {
replaceBlocks(clientIds, transformedBlocks);
selectForMultipleBlocks(transformedBlocks);
}
/**
* The `isTemplate` check is a stopgap solution here.
* Ideally, the Transforms API should handle this
* by allowing to exclude blocks from wildcard transformations.
*/
const hasPossibleBlockTransformations = !!possibleBlockTransformations.length && canRemove && !isTemplate;
const hasPatternTransformation = !!(patterns !== null && patterns !== void 0 && patterns.length) && canRemove;
if (!hasBlockStyles && !hasPossibleBlockTransformations) {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarGroup, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
disabled: true,
className: "block-editor-block-switcher__no-switcher-icon",
title: blockTitle,
icon: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(block_icon, {
icon: icon,
showColors: true
}), (isReusable || isTemplate) && (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-block-switcher__toggle-text"
}, blockTitle))
}));
}
const blockSwitcherLabel = blockTitle;
const blockSwitcherDescription = 1 === blocks.length ? (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: block title. */
(0,external_wp_i18n_namespaceObject.__)('%s: Change block type or style'), blockTitle) : (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %d: number of blocks. */
(0,external_wp_i18n_namespaceObject._n)('Change type of %d block', 'Change type of %d blocks', blocks.length), blocks.length);
const showDropDown = hasBlockStyles || hasPossibleBlockTransformations || hasPatternTransformation;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarGroup, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarItem, null, toggleProps => (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.DropdownMenu, {
className: "block-editor-block-switcher",
label: blockSwitcherLabel,
popoverProps: {
position: 'bottom right',
variant: 'toolbar',
className: 'block-editor-block-switcher__popover'
},
icon: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(block_icon, {
icon: icon,
className: "block-editor-block-switcher__toggle",
showColors: true
}), (isReusable || isTemplate) && (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-block-switcher__toggle-text"
}, blockTitle)),
toggleProps: {
describedBy: blockSwitcherDescription,
...toggleProps
},
menuProps: {
orientation: 'both'
}
}, _ref3 => {
let {
onClose
} = _ref3;
return showDropDown && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-switcher__container"
}, hasPatternTransformation && (0,external_wp_element_namespaceObject.createElement)(pattern_transformations_menu, {
blocks: blocks,
patterns: patterns,
onSelect: transformedBlocks => {
onPatternTransform(transformedBlocks);
onClose();
}
}), hasPossibleBlockTransformations && (0,external_wp_element_namespaceObject.createElement)(block_transformations_menu, {
className: "block-editor-block-switcher__transforms__menugroup",
possibleBlockTransformations: possibleBlockTransformations,
blocks: blocks,
onSelect: name => {
onBlockTransform(name);
onClose();
}
}), hasBlockStyles && (0,external_wp_element_namespaceObject.createElement)(BlockStylesMenu, {
hoveredBlock: blocks[0],
onSwitch: onClose
}));
})));
};
const BlockSwitcher = _ref4 => {
let {
clientIds
} = _ref4;
const blocks = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).getBlocksByClientId(clientIds), [clientIds]);
if (!blocks.length || blocks.some(block => !block)) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(BlockSwitcherDropdownMenu, {
clientIds: clientIds,
blocks: blocks
});
};
/* harmony default export */ var block_switcher = (BlockSwitcher);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-toolbar/block-toolbar-last-item.js
/**
* WordPress dependencies
*/
const {
Fill: __unstableBlockToolbarLastItem,
Slot: block_toolbar_last_item_Slot
} = (0,external_wp_components_namespaceObject.createSlotFill)('__unstableBlockToolbarLastItem');
__unstableBlockToolbarLastItem.Slot = block_toolbar_last_item_Slot;
/* harmony default export */ var block_toolbar_last_item = (__unstableBlockToolbarLastItem);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/utils/pasting.js
/**
* WordPress dependencies
*/
function getPasteEventData(_ref) {
let {
clipboardData
} = _ref;
let plainText = '';
let html = ''; // IE11 only supports `Text` as an argument for `getData` and will
// otherwise throw an invalid argument error, so we try the standard
// arguments first, then fallback to `Text` if they fail.
try {
plainText = clipboardData.getData('text/plain');
html = clipboardData.getData('text/html');
} catch (error1) {
try {
html = clipboardData.getData('Text');
} catch (error2) {
// Some browsers like UC Browser paste plain text by default and
// don't support clipboardData at all, so allow default
// behaviour.
return;
}
}
const files = (0,external_wp_dom_namespaceObject.getFilesFromDataTransfer)(clipboardData);
if (files.length && !shouldDismissPastedFiles(files, html, plainText)) {
return {
files
};
}
return {
html,
plainText,
files: []
};
}
/**
* Given a collection of DataTransfer files and HTML and plain text strings,
* determine whether the files are to be dismissed in favor of the HTML.
*
* Certain office-type programs, like Microsoft Word or Apple Numbers,
* will, upon copy, generate a screenshot of the content being copied and
* attach it to the clipboard alongside the actual rich text that the user
* sought to copy. In those cases, we should let Gutenberg handle the rich text
* content and not the screenshot, since this allows Gutenberg to insert
* meaningful blocks, like paragraphs, lists or even tables.
*
* @param {File[]} files File objects obtained from a paste event
* @param {string} html HTML content obtained from a paste event
* @return {boolean} True if the files should be dismissed
*/
function shouldDismissPastedFiles(files, html
/*, plainText */
) {
// The question is only relevant when there is actual HTML content and when
// there is exactly one image file.
if (html && (files === null || files === void 0 ? void 0 : files.length) === 1 && files[0].type.indexOf('image/') === 0) {
var _html$match;
// A single <img> tag found in the HTML source suggests that the
// content being pasted revolves around an image. Sometimes there are
// other elements found, like <figure>, but we assume that the user's
// intention is to paste the actual image file.
const IMAGE_TAG = /<\s*img\b/gi;
if (((_html$match = html.match(IMAGE_TAG)) === null || _html$match === void 0 ? void 0 : _html$match.length) !== 1) return true; // Even when there is exactly one <img> tag in the HTML payload, we
// choose to weed out local images, i.e. those whose source starts with
// "file://". These payloads occur in specific configurations, such as
// when copying an entire document from Microsoft Word, that contains
// text and exactly one image, and pasting that content using Google
// Chrome.
const IMG_WITH_LOCAL_SRC = /<\s*img\b[^>]*\bsrc="file:\/\//i;
if (html.match(IMG_WITH_LOCAL_SRC)) return true;
}
return false;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/copy-handler/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useNotifyCopy() {
const {
getBlockName
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const {
getBlockType
} = (0,external_wp_data_namespaceObject.useSelect)(external_wp_blocks_namespaceObject.store);
const {
createSuccessNotice
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_notices_namespaceObject.store);
return (0,external_wp_element_namespaceObject.useCallback)((eventType, selectedBlockClientIds) => {
let notice = '';
if (selectedBlockClientIds.length === 1) {
var _getBlockType;
const clientId = selectedBlockClientIds[0];
const title = (_getBlockType = getBlockType(getBlockName(clientId))) === null || _getBlockType === void 0 ? void 0 : _getBlockType.title;
notice = eventType === 'copy' ? (0,external_wp_i18n_namespaceObject.sprintf)( // Translators: Name of the block being copied, e.g. "Paragraph".
(0,external_wp_i18n_namespaceObject.__)('Copied "%s" to clipboard.'), title) : (0,external_wp_i18n_namespaceObject.sprintf)( // Translators: Name of the block being cut, e.g. "Paragraph".
(0,external_wp_i18n_namespaceObject.__)('Moved "%s" to clipboard.'), title);
} else {
notice = eventType === 'copy' ? (0,external_wp_i18n_namespaceObject.sprintf)( // Translators: %d: Number of blocks being copied.
(0,external_wp_i18n_namespaceObject._n)('Copied %d block to clipboard.', 'Copied %d blocks to clipboard.', selectedBlockClientIds.length), selectedBlockClientIds.length) : (0,external_wp_i18n_namespaceObject.sprintf)( // Translators: %d: Number of blocks being cut.
(0,external_wp_i18n_namespaceObject._n)('Moved %d block to clipboard.', 'Moved %d blocks to clipboard.', selectedBlockClientIds.length), selectedBlockClientIds.length);
}
createSuccessNotice(notice, {
type: 'snackbar'
});
}, []);
}
function useClipboardHandler() {
const {
getBlocksByClientId,
getSelectedBlockClientIds,
hasMultiSelection,
getSettings,
__unstableIsFullySelected,
__unstableIsSelectionCollapsed,
__unstableIsSelectionMergeable,
__unstableGetSelectedBlocksWithPartialSelection,
canInsertBlockType
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const {
flashBlock,
removeBlocks,
replaceBlocks,
__unstableDeleteSelection,
__unstableExpandSelection,
insertBlocks
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const notifyCopy = useNotifyCopy();
return (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
function handler(event) {
const selectedBlockClientIds = getSelectedBlockClientIds();
if (selectedBlockClientIds.length === 0) {
return;
} // Always handle multiple selected blocks.
if (!hasMultiSelection()) {
const {
target
} = event;
const {
ownerDocument
} = target; // If copying, only consider actual text selection as selection.
// Otherwise, any focus on an input field is considered.
const hasSelection = event.type === 'copy' || event.type === 'cut' ? (0,external_wp_dom_namespaceObject.documentHasUncollapsedSelection)(ownerDocument) : (0,external_wp_dom_namespaceObject.documentHasSelection)(ownerDocument); // Let native copy behaviour take over in input fields.
if (hasSelection) {
return;
}
}
if (!node.contains(event.target.ownerDocument.activeElement)) {
return;
}
const eventDefaultPrevented = event.defaultPrevented;
event.preventDefault();
const isSelectionMergeable = __unstableIsSelectionMergeable();
const shouldHandleWholeBlocks = __unstableIsSelectionCollapsed() || __unstableIsFullySelected();
const expandSelectionIsNeeded = !shouldHandleWholeBlocks && !isSelectionMergeable;
if (event.type === 'copy' || event.type === 'cut') {
if (selectedBlockClientIds.length === 1) {
flashBlock(selectedBlockClientIds[0]);
} // If we have a partial selection that is not mergeable, just
// expand the selection to the whole blocks.
if (expandSelectionIsNeeded) {
__unstableExpandSelection();
} else {
notifyCopy(event.type, selectedBlockClientIds);
let blocks; // Check if we have partial selection.
if (shouldHandleWholeBlocks) {
blocks = getBlocksByClientId(selectedBlockClientIds);
} else {
const [head, tail] = __unstableGetSelectedBlocksWithPartialSelection();
const inBetweenBlocks = getBlocksByClientId(selectedBlockClientIds.slice(1, selectedBlockClientIds.length - 1));
blocks = [head, ...inBetweenBlocks, tail];
}
const wrapperBlockName = event.clipboardData.getData('__unstableWrapperBlockName');
if (wrapperBlockName) {
blocks = (0,external_wp_blocks_namespaceObject.createBlock)(wrapperBlockName, JSON.parse(event.clipboardData.getData('__unstableWrapperBlockAttributes')), blocks);
}
const serialized = (0,external_wp_blocks_namespaceObject.serialize)(blocks);
event.clipboardData.setData('text/plain', toPlainText(serialized));
event.clipboardData.setData('text/html', serialized);
}
}
if (event.type === 'cut') {
// We need to also check if at the start we needed to
// expand the selection, as in this point we might have
// programmatically fully selected the blocks above.
if (shouldHandleWholeBlocks && !expandSelectionIsNeeded) {
removeBlocks(selectedBlockClientIds);
} else {
__unstableDeleteSelection();
}
} else if (event.type === 'paste') {
if (eventDefaultPrevented) {
// This was likely already handled in rich-text/use-paste-handler.js.
return;
}
const {
__experimentalCanUserUseUnfilteredHTML: canUserUseUnfilteredHTML
} = getSettings();
const {
plainText,
html,
files
} = getPasteEventData(event);
let blocks = [];
if (files.length) {
const fromTransforms = (0,external_wp_blocks_namespaceObject.getBlockTransforms)('from');
blocks = files.reduce((accumulator, file) => {
const transformation = (0,external_wp_blocks_namespaceObject.findTransform)(fromTransforms, transform => transform.type === 'files' && transform.isMatch([file]));
if (transformation) {
accumulator.push(transformation.transform([file]));
}
return accumulator;
}, []).flat();
} else {
blocks = (0,external_wp_blocks_namespaceObject.pasteHandler)({
HTML: html,
plainText,
mode: 'BLOCKS',
canUserUseUnfilteredHTML
});
}
if (selectedBlockClientIds.length === 1) {
const [selectedBlockClientId] = selectedBlockClientIds;
if (blocks.every(block => canInsertBlockType(block.name, selectedBlockClientId))) {
insertBlocks(blocks, undefined, selectedBlockClientId);
return;
}
}
replaceBlocks(selectedBlockClientIds, blocks, blocks.length - 1, -1);
}
}
node.ownerDocument.addEventListener('copy', handler);
node.ownerDocument.addEventListener('cut', handler);
node.ownerDocument.addEventListener('paste', handler);
return () => {
node.ownerDocument.removeEventListener('copy', handler);
node.ownerDocument.removeEventListener('cut', handler);
node.ownerDocument.removeEventListener('paste', handler);
};
}, []);
}
function CopyHandler(_ref) {
let {
children
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("div", {
ref: useClipboardHandler()
}, children);
}
/**
* Given a string of HTML representing serialized blocks, returns the plain
* text extracted after stripping the HTML of any tags and fixing line breaks.
*
* @param {string} html Serialized blocks.
* @return {string} The plain-text content with any html removed.
*/
function toPlainText(html) {
// Manually handle BR tags as line breaks prior to `stripHTML` call
html = html.replace(/<br>/g, '\n');
const plainText = (0,external_wp_dom_namespaceObject.__unstableStripHTML)(html).trim(); // Merge any consecutive line breaks
return plainText.replace(/\n\n+/g, '\n\n');
}
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/copy-handler/README.md
*/
/* harmony default export */ var copy_handler = (CopyHandler);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/supports.js
/**
* WordPress dependencies
*/
const ALIGN_SUPPORT_KEY = 'align';
const ALIGN_WIDE_SUPPORT_KEY = 'alignWide';
const BORDER_SUPPORT_KEY = '__experimentalBorder';
const COLOR_SUPPORT_KEY = 'color';
const CUSTOM_CLASS_NAME_SUPPORT_KEY = 'customClassName';
const FONT_FAMILY_SUPPORT_KEY = 'typography.__experimentalFontFamily';
const FONT_SIZE_SUPPORT_KEY = 'typography.fontSize';
const LINE_HEIGHT_SUPPORT_KEY = 'typography.lineHeight';
/**
* Key within block settings' support array indicating support for font style.
*/
const FONT_STYLE_SUPPORT_KEY = 'typography.__experimentalFontStyle';
/**
* Key within block settings' support array indicating support for font weight.
*/
const FONT_WEIGHT_SUPPORT_KEY = 'typography.__experimentalFontWeight';
/**
* Key within block settings' supports array indicating support for text
* decorations e.g. settings found in `block.json`.
*/
const TEXT_DECORATION_SUPPORT_KEY = 'typography.__experimentalTextDecoration';
/**
* Key within block settings' supports array indicating support for text
* transforms e.g. settings found in `block.json`.
*/
const TEXT_TRANSFORM_SUPPORT_KEY = 'typography.__experimentalTextTransform';
/**
* Key within block settings' supports array indicating support for letter-spacing
* e.g. settings found in `block.json`.
*/
const LETTER_SPACING_SUPPORT_KEY = 'typography.__experimentalLetterSpacing';
const LAYOUT_SUPPORT_KEY = '__experimentalLayout';
const TYPOGRAPHY_SUPPORT_KEYS = [LINE_HEIGHT_SUPPORT_KEY, FONT_SIZE_SUPPORT_KEY, FONT_STYLE_SUPPORT_KEY, FONT_WEIGHT_SUPPORT_KEY, FONT_FAMILY_SUPPORT_KEY, TEXT_DECORATION_SUPPORT_KEY, TEXT_TRANSFORM_SUPPORT_KEY, LETTER_SPACING_SUPPORT_KEY];
const supports_SPACING_SUPPORT_KEY = 'spacing';
const styleSupportKeys = [...TYPOGRAPHY_SUPPORT_KEYS, BORDER_SUPPORT_KEY, COLOR_SUPPORT_KEY, supports_SPACING_SUPPORT_KEY];
/**
* Returns true if the block defines support for align.
*
* @param {string|Object} nameOrType Block name or type object.
* @return {boolean} Whether the block supports the feature.
*/
const hasAlignSupport = nameOrType => (0,external_wp_blocks_namespaceObject.hasBlockSupport)(nameOrType, ALIGN_SUPPORT_KEY);
/**
* Returns the block support value for align, if defined.
*
* @param {string|Object} nameOrType Block name or type object.
* @return {unknown} The block support value.
*/
const getAlignSupport = nameOrType => getBlockSupport(nameOrType, ALIGN_SUPPORT_KEY);
/**
* Returns true if the block defines support for align wide.
*
* @param {string|Object} nameOrType Block name or type object.
* @return {boolean} Whether the block supports the feature.
*/
const hasAlignWideSupport = nameOrType => hasBlockSupport(nameOrType, ALIGN_WIDE_SUPPORT_KEY);
/**
* Returns the block support value for align wide, if defined.
*
* @param {string|Object} nameOrType Block name or type object.
* @return {unknown} The block support value.
*/
const getAlignWideSupport = nameOrType => getBlockSupport(nameOrType, ALIGN_WIDE_SUPPORT_KEY);
/**
* Determine whether there is block support for border properties.
*
* @param {string|Object} nameOrType Block name or type object.
* @param {string} feature Border feature to check support for.
*
* @return {boolean} Whether there is support.
*/
function hasBorderSupport(nameOrType) {
let feature = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'any';
if (external_wp_element_namespaceObject.Platform.OS !== 'web') {
return false;
}
const support = (0,external_wp_blocks_namespaceObject.getBlockSupport)(nameOrType, BORDER_SUPPORT_KEY);
if (support === true) {
return true;
}
if (feature === 'any') {
return !!(support !== null && support !== void 0 && support.color || support !== null && support !== void 0 && support.radius || support !== null && support !== void 0 && support.width || support !== null && support !== void 0 && support.style);
}
return !!(support !== null && support !== void 0 && support[feature]);
}
/**
* Get block support for border properties.
*
* @param {string|Object} nameOrType Block name or type object.
* @param {string} feature Border feature to get.
*
* @return {unknown} The block support.
*/
const getBorderSupport = (nameOrType, feature) => getBlockSupport(nameOrType, [BORDER_SUPPORT_KEY, feature]);
/**
* Returns true if the block defines support for color.
*
* @param {string|Object} nameOrType Block name or type object.
* @return {boolean} Whether the block supports the feature.
*/
const hasColorSupport = nameOrType => {
const colorSupport = getBlockSupport(nameOrType, COLOR_SUPPORT_KEY);
return colorSupport && (colorSupport.link === true || colorSupport.gradient === true || colorSupport.background !== false || colorSupport.text !== false);
};
/**
* Returns true if the block defines support for link color.
*
* @param {string|Object} nameOrType Block name or type object.
* @return {boolean} Whether the block supports the feature.
*/
const hasLinkColorSupport = nameOrType => {
if (Platform.OS !== 'web') {
return false;
}
const colorSupport = getBlockSupport(nameOrType, COLOR_SUPPORT_KEY);
return colorSupport !== null && typeof colorSupport === 'object' && !!colorSupport.link;
};
/**
* Returns true if the block defines support for gradient color.
*
* @param {string|Object} nameOrType Block name or type object.
* @return {boolean} Whether the block supports the feature.
*/
const hasGradientSupport = nameOrType => {
const colorSupport = (0,external_wp_blocks_namespaceObject.getBlockSupport)(nameOrType, COLOR_SUPPORT_KEY);
return colorSupport !== null && typeof colorSupport === 'object' && !!colorSupport.gradients;
};
/**
* Returns true if the block defines support for background color.
*
* @param {string|Object} nameOrType Block name or type object.
* @return {boolean} Whether the block supports the feature.
*/
const hasBackgroundColorSupport = nameOrType => {
const colorSupport = (0,external_wp_blocks_namespaceObject.getBlockSupport)(nameOrType, COLOR_SUPPORT_KEY);
return colorSupport && colorSupport.background !== false;
};
/**
* Returns true if the block defines support for background color.
*
* @param {string|Object} nameOrType Block name or type object.
* @return {boolean} Whether the block supports the feature.
*/
const hasTextColorSupport = nameOrType => {
const colorSupport = (0,external_wp_blocks_namespaceObject.getBlockSupport)(nameOrType, COLOR_SUPPORT_KEY);
return colorSupport && colorSupport.text !== false;
};
/**
* Get block support for color properties.
*
* @param {string|Object} nameOrType Block name or type object.
* @param {string} feature Color feature to get.
*
* @return {unknown} The block support.
*/
const getColorSupport = (nameOrType, feature) => getBlockSupport(nameOrType, [COLOR_SUPPORT_KEY, feature]);
/**
* Returns true if the block defines support for custom class name.
*
* @param {string|Object} nameOrType Block name or type object.
* @return {boolean} Whether the block supports the feature.
*/
const hasCustomClassNameSupport = nameOrType => (0,external_wp_blocks_namespaceObject.hasBlockSupport)(nameOrType, CUSTOM_CLASS_NAME_SUPPORT_KEY, true);
/**
* Returns the block support value for custom class name, if defined.
*
* @param {string|Object} nameOrType Block name or type object.
* @return {unknown} The block support value.
*/
const getCustomClassNameSupport = nameOrType => getBlockSupport(nameOrType, CUSTOM_CLASS_NAME_SUPPORT_KEY, true);
/**
* Returns true if the block defines support for font family.
*
* @param {string|Object} nameOrType Block name or type object.
* @return {boolean} Whether the block supports the feature.
*/
const hasFontFamilySupport = nameOrType => (0,external_wp_blocks_namespaceObject.hasBlockSupport)(nameOrType, FONT_FAMILY_SUPPORT_KEY);
/**
* Returns the block support value for font family, if defined.
*
* @param {string|Object} nameOrType Block name or type object.
* @return {unknown} The block support value.
*/
const getFontFamilySupport = nameOrType => getBlockSupport(nameOrType, FONT_FAMILY_SUPPORT_KEY);
/**
* Returns true if the block defines support for font size.
*
* @param {string|Object} nameOrType Block name or type object.
* @return {boolean} Whether the block supports the feature.
*/
const hasFontSizeSupport = nameOrType => (0,external_wp_blocks_namespaceObject.hasBlockSupport)(nameOrType, FONT_SIZE_SUPPORT_KEY);
/**
* Returns the block support value for font size, if defined.
*
* @param {string|Object} nameOrType Block name or type object.
* @return {unknown} The block support value.
*/
const getFontSizeSupport = nameOrType => getBlockSupport(nameOrType, FONT_SIZE_SUPPORT_KEY);
/**
* Returns true if the block defines support for layout.
*
* @param {string|Object} nameOrType Block name or type object.
* @return {boolean} Whether the block supports the feature.
*/
const hasLayoutSupport = nameOrType => (0,external_wp_blocks_namespaceObject.hasBlockSupport)(nameOrType, LAYOUT_SUPPORT_KEY);
/**
* Returns the block support value for layout, if defined.
*
* @param {string|Object} nameOrType Block name or type object.
* @return {unknown} The block support value.
*/
const getLayoutSupport = nameOrType => getBlockSupport(nameOrType, LAYOUT_SUPPORT_KEY);
/**
* Returns true if the block defines support for style.
*
* @param {string|Object} nameOrType Block name or type object.
* @return {boolean} Whether the block supports the feature.
*/
const hasStyleSupport = nameOrType => styleSupportKeys.some(key => (0,external_wp_blocks_namespaceObject.hasBlockSupport)(nameOrType, key));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/use-paste-styles/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Determine if the copied text looks like serialized blocks or not.
* Since plain text will always get parsed into a freeform block,
* we check that if the parsed blocks is anything other than that.
*
* @param {string} text The copied text.
* @return {boolean} True if the text looks like serialized blocks, false otherwise.
*/
function hasSerializedBlocks(text) {
try {
const blocks = (0,external_wp_blocks_namespaceObject.parse)(text, {
__unstableSkipMigrationLogs: true,
__unstableSkipAutop: true
});
if (blocks.length === 1 && blocks[0].name === 'core/freeform') {
// It's likely that the text is just plain text and not serialized blocks.
return false;
}
return true;
} catch (err) {
// Parsing error, the text is not serialized blocks.
// (Even though that it technically won't happen)
return false;
}
}
/**
* Style attributes are attributes being added in `block-editor/src/hooks/*`.
* (Except for some unrelated to style like `anchor` or `settings`.)
* They generally represent the default block supports.
*/
const STYLE_ATTRIBUTES = {
align: hasAlignSupport,
borderColor: nameOrType => hasBorderSupport(nameOrType, 'color'),
backgroundColor: hasBackgroundColorSupport,
textColor: hasTextColorSupport,
gradient: hasGradientSupport,
className: hasCustomClassNameSupport,
fontFamily: hasFontFamilySupport,
fontSize: hasFontSizeSupport,
layout: hasLayoutSupport,
style: hasStyleSupport
};
/**
* Get the "style attributes" from a given block to a target block.
*
* @param {WPBlock} sourceBlock The source block.
* @param {WPBlock} targetBlock The target block.
* @return {Object} the filtered attributes object.
*/
function getStyleAttributes(sourceBlock, targetBlock) {
return Object.entries(STYLE_ATTRIBUTES).reduce((attributes, _ref) => {
let [attributeKey, hasSupport] = _ref;
// Only apply the attribute if both blocks support it.
if (hasSupport(sourceBlock.name) && hasSupport(targetBlock.name)) {
// Override attributes that are not present in the block to their defaults.
attributes[attributeKey] = sourceBlock.attributes[attributeKey];
}
return attributes;
}, {});
}
/**
* Update the target blocks with style attributes recursively.
*
* @param {WPBlock[]} targetBlocks The target blocks to be updated.
* @param {WPBlock[]} sourceBlocks The source blocks to get th style attributes from.
* @param {Function} updateBlockAttributes The function to update the attributes.
*/
function recursivelyUpdateBlockAttributes(targetBlocks, sourceBlocks, updateBlockAttributes) {
for (let index = 0; index < Math.min(sourceBlocks.length, targetBlocks.length); index += 1) {
updateBlockAttributes(targetBlocks[index].clientId, getStyleAttributes(sourceBlocks[index], targetBlocks[index]));
recursivelyUpdateBlockAttributes(targetBlocks[index].innerBlocks, sourceBlocks[index].innerBlocks, updateBlockAttributes);
}
}
/**
* A hook to return a pasteStyles event function for handling pasting styles to blocks.
*
* @return {Function} A function to update the styles to the blocks.
*/
function usePasteStyles() {
const registry = (0,external_wp_data_namespaceObject.useRegistry)();
const {
updateBlockAttributes
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const {
createSuccessNotice,
createWarningNotice,
createErrorNotice
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_notices_namespaceObject.store);
return (0,external_wp_element_namespaceObject.useCallback)(async targetBlocks => {
let html = '';
try {
// `http:` sites won't have the clipboard property on navigator.
// (with the exception of localhost.)
if (!window.navigator.clipboard) {
createErrorNotice((0,external_wp_i18n_namespaceObject.__)('Unable to paste styles. This feature is only available on secure (https) sites in supporting browsers.'), {
type: 'snackbar'
});
return;
}
html = await window.navigator.clipboard.readText();
} catch (error) {
// Possibly the permission is denied.
createErrorNotice((0,external_wp_i18n_namespaceObject.__)('Unable to paste styles. Please allow browser clipboard permissions before continuing.'), {
type: 'snackbar'
});
return;
} // Abort if the copied text is empty or doesn't look like serialized blocks.
if (!html || !hasSerializedBlocks(html)) {
createWarningNotice((0,external_wp_i18n_namespaceObject.__)("Unable to paste styles. Block styles couldn't be found within the copied content."), {
type: 'snackbar'
});
return;
}
const copiedBlocks = (0,external_wp_blocks_namespaceObject.parse)(html);
if (copiedBlocks.length === 1) {
// Apply styles of the block to all the target blocks.
registry.batch(() => {
recursivelyUpdateBlockAttributes(targetBlocks, targetBlocks.map(() => copiedBlocks[0]), updateBlockAttributes);
});
} else {
registry.batch(() => {
recursivelyUpdateBlockAttributes(targetBlocks, copiedBlocks, updateBlockAttributes);
});
}
if (targetBlocks.length === 1) {
var _getBlockType;
const title = (_getBlockType = (0,external_wp_blocks_namespaceObject.getBlockType)(targetBlocks[0].name)) === null || _getBlockType === void 0 ? void 0 : _getBlockType.title;
createSuccessNotice((0,external_wp_i18n_namespaceObject.sprintf)( // Translators: Name of the block being pasted, e.g. "Paragraph".
(0,external_wp_i18n_namespaceObject.__)('Pasted styles to %s.'), title), {
type: 'snackbar'
});
} else {
createSuccessNotice((0,external_wp_i18n_namespaceObject.sprintf)( // Translators: The number of the blocks.
(0,external_wp_i18n_namespaceObject.__)('Pasted styles to %d blocks.'), targetBlocks.length), {
type: 'snackbar'
});
}
}, [registry.batch, updateBlockAttributes, createSuccessNotice, createWarningNotice, createErrorNotice]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-actions/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function BlockActions(_ref) {
let {
clientIds,
children,
__experimentalUpdateSelection: updateSelection
} = _ref;
const {
canInsertBlockType,
getBlockRootClientId,
getBlocksByClientId,
canMoveBlocks,
canRemoveBlocks
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const {
getDefaultBlockName,
getGroupingBlockName
} = (0,external_wp_data_namespaceObject.useSelect)(external_wp_blocks_namespaceObject.store);
const blocks = getBlocksByClientId(clientIds);
const rootClientId = getBlockRootClientId(clientIds[0]);
const canDuplicate = blocks.every(block => {
return !!block && (0,external_wp_blocks_namespaceObject.hasBlockSupport)(block.name, 'multiple', true) && canInsertBlockType(block.name, rootClientId);
});
const canInsertDefaultBlock = canInsertBlockType(getDefaultBlockName(), rootClientId);
const canMove = canMoveBlocks(clientIds, rootClientId);
const canRemove = canRemoveBlocks(clientIds, rootClientId);
const {
removeBlocks,
replaceBlocks,
duplicateBlocks,
insertAfterBlock,
insertBeforeBlock,
flashBlock,
setBlockMovingClientId,
setNavigationMode,
selectBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const notifyCopy = useNotifyCopy();
const pasteStyles = usePasteStyles();
return children({
canDuplicate,
canInsertDefaultBlock,
canMove,
canRemove,
rootClientId,
blocks,
onDuplicate() {
return duplicateBlocks(clientIds, updateSelection);
},
onRemove() {
return removeBlocks(clientIds, updateSelection);
},
onInsertBefore() {
const clientId = Array.isArray(clientIds) ? clientIds[0] : clientId;
insertBeforeBlock(clientId);
},
onInsertAfter() {
const clientId = Array.isArray(clientIds) ? clientIds[clientIds.length - 1] : clientId;
insertAfterBlock(clientId);
},
onMoveTo() {
setNavigationMode(true);
selectBlock(clientIds[0]);
setBlockMovingClientId(clientIds[0]);
},
onGroup() {
if (!blocks.length) {
return;
}
const groupingBlockName = getGroupingBlockName(); // Activate the `transform` on `core/group` which does the conversion.
const newBlocks = (0,external_wp_blocks_namespaceObject.switchToBlockType)(blocks, groupingBlockName);
if (!newBlocks) {
return;
}
replaceBlocks(clientIds, newBlocks);
},
onUngroup() {
if (!blocks.length) {
return;
}
const innerBlocks = blocks[0].innerBlocks;
if (!innerBlocks.length) {
return;
}
replaceBlocks(clientIds, innerBlocks);
},
onCopy() {
const selectedBlockClientIds = blocks.map(_ref2 => {
let {
clientId
} = _ref2;
return clientId;
});
if (blocks.length === 1) {
flashBlock(selectedBlockClientIds[0]);
}
notifyCopy('copy', selectedBlockClientIds);
},
async onPasteStyles() {
await pasteStyles(blocks);
}
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-settings-menu/block-mode-toggle.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const block_mode_toggle_noop = () => {};
function BlockModeToggle(_ref) {
let {
blockType,
mode,
onToggleMode,
small = false,
isCodeEditingEnabled = true
} = _ref;
if (!blockType || !(0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockType, 'html', true) || !isCodeEditingEnabled) {
return null;
}
const label = mode === 'visual' ? (0,external_wp_i18n_namespaceObject.__)('Edit as HTML') : (0,external_wp_i18n_namespaceObject.__)('Edit visually');
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
onClick: onToggleMode
}, !small && label);
}
/* harmony default export */ var block_mode_toggle = ((0,external_wp_compose_namespaceObject.compose)([(0,external_wp_data_namespaceObject.withSelect)((select, _ref2) => {
let {
clientId
} = _ref2;
const {
getBlock,
getBlockMode,
getSettings
} = select(store);
const block = getBlock(clientId);
const isCodeEditingEnabled = getSettings().codeEditingEnabled;
return {
mode: getBlockMode(clientId),
blockType: block ? (0,external_wp_blocks_namespaceObject.getBlockType)(block.name) : null,
isCodeEditingEnabled
};
}), (0,external_wp_data_namespaceObject.withDispatch)((dispatch, _ref3) => {
let {
onToggle = block_mode_toggle_noop,
clientId
} = _ref3;
return {
onToggleMode() {
dispatch(store).toggleBlockMode(clientId);
onToggle();
}
};
})])(BlockModeToggle));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-settings-menu/block-convert-button.js
/**
* WordPress dependencies
*/
function BlockConvertButton(_ref) {
let {
shouldRender,
onClick,
small
} = _ref;
if (!shouldRender) {
return null;
}
const label = (0,external_wp_i18n_namespaceObject.__)('Convert to Blocks');
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
onClick: onClick
}, !small && label);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-settings-menu/block-html-convert-button.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/* harmony default export */ var block_html_convert_button = ((0,external_wp_compose_namespaceObject.compose)((0,external_wp_data_namespaceObject.withSelect)((select, _ref) => {
let {
clientId
} = _ref;
const block = select(store).getBlock(clientId);
return {
block,
shouldRender: block && block.name === 'core/html'
};
}), (0,external_wp_data_namespaceObject.withDispatch)((dispatch, _ref2) => {
let {
block
} = _ref2;
return {
onClick: () => dispatch(store).replaceBlocks(block.clientId, (0,external_wp_blocks_namespaceObject.rawHandler)({
HTML: (0,external_wp_blocks_namespaceObject.getBlockContent)(block)
}))
};
}))(BlockConvertButton));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-settings-menu/block-settings-menu-first-item.js
/**
* WordPress dependencies
*/
const {
Fill: __unstableBlockSettingsMenuFirstItem,
Slot: block_settings_menu_first_item_Slot
} = (0,external_wp_components_namespaceObject.createSlotFill)('__unstableBlockSettingsMenuFirstItem');
__unstableBlockSettingsMenuFirstItem.Slot = block_settings_menu_first_item_Slot;
/* harmony default export */ var block_settings_menu_first_item = (__unstableBlockSettingsMenuFirstItem);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/convert-to-group-buttons/use-convert-to-group-button-props.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Contains the properties `ConvertToGroupButton` component needs.
*
* @typedef {Object} ConvertToGroupButtonProps
* @property {string[]} clientIds An array of the selected client ids.
* @property {boolean} isGroupable Indicates if the selected blocks can be grouped.
* @property {boolean} isUngroupable Indicates if the selected blocks can be ungrouped.
* @property {WPBlock[]} blocksSelection An array of the selected blocks.
* @property {string} groupingBlockName The name of block used for handling grouping interactions.
*/
/**
* Returns the properties `ConvertToGroupButton` component needs to work properly.
* It is used in `BlockSettingsMenuControls` to know if `ConvertToGroupButton`
* should be rendered, to avoid ending up with an empty MenuGroup.
*
* @return {ConvertToGroupButtonProps} Returns the properties needed by `ConvertToGroupButton`.
*/
function useConvertToGroupButtonProps() {
const {
clientIds,
isGroupable,
isUngroupable,
blocksSelection,
groupingBlockName
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _blocksSelection$;
const {
getBlockRootClientId,
getBlocksByClientId,
canInsertBlockType,
getSelectedBlockClientIds
} = select(store);
const {
getGroupingBlockName
} = select(external_wp_blocks_namespaceObject.store);
const _clientIds = getSelectedBlockClientIds();
const _groupingBlockName = getGroupingBlockName();
const rootClientId = !!(_clientIds !== null && _clientIds !== void 0 && _clientIds.length) ? getBlockRootClientId(_clientIds[0]) : undefined;
const groupingBlockAvailable = canInsertBlockType(_groupingBlockName, rootClientId);
const _blocksSelection = getBlocksByClientId(_clientIds);
const isSingleGroupingBlock = _blocksSelection.length === 1 && ((_blocksSelection$ = _blocksSelection[0]) === null || _blocksSelection$ === void 0 ? void 0 : _blocksSelection$.name) === _groupingBlockName; // Do we have
// 1. Grouping block available to be inserted?
// 2. One or more blocks selected
const _isGroupable = groupingBlockAvailable && _blocksSelection.length; // Do we have a single Group Block selected and does that group have inner blocks?
const _isUngroupable = isSingleGroupingBlock && !!_blocksSelection[0].innerBlocks.length;
return {
clientIds: _clientIds,
isGroupable: _isGroupable,
isUngroupable: _isUngroupable,
blocksSelection: _blocksSelection,
groupingBlockName: _groupingBlockName
};
}, []);
return {
clientIds,
isGroupable,
isUngroupable,
blocksSelection,
groupingBlockName
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/convert-to-group-buttons/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ConvertToGroupButton(_ref) {
let {
clientIds,
isGroupable,
isUngroupable,
blocksSelection,
groupingBlockName,
onClose = () => {}
} = _ref;
const {
replaceBlocks
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const onConvertToGroup = () => {
// Activate the `transform` on the Grouping Block which does the conversion.
const newBlocks = (0,external_wp_blocks_namespaceObject.switchToBlockType)(blocksSelection, groupingBlockName);
if (newBlocks) {
replaceBlocks(clientIds, newBlocks);
}
};
const onConvertFromGroup = () => {
const innerBlocks = blocksSelection[0].innerBlocks;
if (!innerBlocks.length) {
return;
}
replaceBlocks(clientIds, innerBlocks);
};
if (!isGroupable && !isUngroupable) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, isGroupable && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
onClick: () => {
onConvertToGroup();
onClose();
}
}, (0,external_wp_i18n_namespaceObject._x)('Group', 'verb')), isUngroupable && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
onClick: () => {
onConvertFromGroup();
onClose();
}
}, (0,external_wp_i18n_namespaceObject._x)('Ungroup', 'Ungrouping blocks from within a Group block back into individual blocks within the Editor ')));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-lock/use-block-lock.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Return details about the block lock status.
*
* @param {string} clientId The block client Id.
*
* @return {Object} Block lock status
*/
function useBlockLock(clientId) {
return (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
canEditBlock,
canMoveBlock,
canRemoveBlock,
canLockBlockType,
getBlockName,
getBlockRootClientId,
getTemplateLock
} = select(store);
const rootClientId = getBlockRootClientId(clientId);
const canEdit = canEditBlock(clientId);
const canMove = canMoveBlock(clientId, rootClientId);
const canRemove = canRemoveBlock(clientId, rootClientId);
return {
canEdit,
canMove,
canRemove,
canLock: canLockBlockType(getBlockName(clientId)),
isContentLocked: getTemplateLock(clientId) === 'contentOnly',
isLocked: !canEdit || !canMove || !canRemove
};
}, [clientId]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/unlock.js
/**
* WordPress dependencies
*/
const unlock_unlock = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M17 10h-1.2V7c0-2.1-1.7-3.8-3.8-3.8-2.1 0-3.8 1.7-3.8 3.8h1.5c0-1.2 1-2.2 2.2-2.2s2.2 1 2.2 2.2v3H7c-.6 0-1 .4-1 1v8c0 .6.4 1 1 1h10c.6 0 1-.4 1-1v-8c0-.6-.4-1-1-1z"
}));
/* harmony default export */ var library_unlock = (unlock_unlock);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/lock-outline.js
/**
* WordPress dependencies
*/
const lockOutline = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M17 10h-1.2V7c0-2.1-1.7-3.8-3.8-3.8-2.1 0-3.8 1.7-3.8 3.8v3H7c-.6 0-1 .4-1 1v8c0 .6.4 1 1 1h10c.6 0 1-.4 1-1v-8c0-.6-.4-1-1-1zM9.8 7c0-1.2 1-2.2 2.2-2.2 1.2 0 2.2 1 2.2 2.2v3H9.8V7zm6.7 11.5h-9v-7h9v7z"
}));
/* harmony default export */ var lock_outline = (lockOutline);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/lock.js
/**
* WordPress dependencies
*/
const lock_lock = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M17 10h-1.2V7c0-2.1-1.7-3.8-3.8-3.8-2.1 0-3.8 1.7-3.8 3.8v3H7c-.6 0-1 .4-1 1v8c0 .6.4 1 1 1h10c.6 0 1-.4 1-1v-8c0-.6-.4-1-1-1zm-2.8 0H9.8V7c0-1.2 1-2.2 2.2-2.2s2.2 1 2.2 2.2v3z"
}));
/* harmony default export */ var library_lock = (lock_lock);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-lock/modal.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
// Entity based blocks which allow edit locking
const ALLOWS_EDIT_LOCKING = ['core/block', 'core/navigation'];
function getTemplateLockValue(lock) {
// Prevents all operations.
if (lock.remove && lock.move) {
return 'all';
} // Prevents inserting or removing blocks, but allows moving existing blocks.
if (lock.remove && !lock.move) {
return 'insert';
}
return false;
}
function BlockLockModal(_ref) {
let {
clientId,
onClose
} = _ref;
const [lock, setLock] = (0,external_wp_element_namespaceObject.useState)({
move: false,
remove: false
});
const {
canEdit,
canMove,
canRemove
} = useBlockLock(clientId);
const {
allowsEditLocking,
templateLock,
hasTemplateLock
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _getBlockAttributes, _blockType$attributes;
const {
getBlockName,
getBlockAttributes
} = select(store);
const blockName = getBlockName(clientId);
const blockType = (0,external_wp_blocks_namespaceObject.getBlockType)(blockName);
return {
allowsEditLocking: ALLOWS_EDIT_LOCKING.includes(blockName),
templateLock: (_getBlockAttributes = getBlockAttributes(clientId)) === null || _getBlockAttributes === void 0 ? void 0 : _getBlockAttributes.templateLock,
hasTemplateLock: !!(blockType !== null && blockType !== void 0 && (_blockType$attributes = blockType.attributes) !== null && _blockType$attributes !== void 0 && _blockType$attributes.templateLock)
};
}, [clientId]);
const [applyTemplateLock, setApplyTemplateLock] = (0,external_wp_element_namespaceObject.useState)(!!templateLock);
const {
updateBlockAttributes
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const blockInformation = useBlockDisplayInformation(clientId);
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(BlockLockModal, 'block-editor-block-lock-modal__options-title');
(0,external_wp_element_namespaceObject.useEffect)(() => {
setLock({
move: !canMove,
remove: !canRemove,
...(allowsEditLocking ? {
edit: !canEdit
} : {})
});
}, [canEdit, canMove, canRemove, allowsEditLocking]);
const isAllChecked = Object.values(lock).every(Boolean);
const isMixed = Object.values(lock).some(Boolean) && !isAllChecked;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Modal, {
title: (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: Name of the block. */
(0,external_wp_i18n_namespaceObject.__)('Lock %s'), blockInformation.title),
overlayClassName: "block-editor-block-lock-modal",
onRequestClose: onClose
}, (0,external_wp_element_namespaceObject.createElement)("p", null, (0,external_wp_i18n_namespaceObject.__)('Choose specific attributes to restrict or lock all available options.')), (0,external_wp_element_namespaceObject.createElement)("form", {
onSubmit: event => {
event.preventDefault();
updateBlockAttributes([clientId], {
lock,
templateLock: applyTemplateLock ? getTemplateLockValue(lock) : undefined
});
onClose();
}
}, (0,external_wp_element_namespaceObject.createElement)("div", {
role: "group",
"aria-labelledby": instanceId,
className: "block-editor-block-lock-modal__options"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.CheckboxControl, {
__nextHasNoMarginBottom: true,
className: "block-editor-block-lock-modal__options-title",
label: (0,external_wp_element_namespaceObject.createElement)("span", {
id: instanceId
}, (0,external_wp_i18n_namespaceObject.__)('Lock all')),
checked: isAllChecked,
indeterminate: isMixed,
onChange: newValue => setLock({
move: newValue,
remove: newValue,
...(allowsEditLocking ? {
edit: newValue
} : {})
})
}), (0,external_wp_element_namespaceObject.createElement)("ul", {
className: "block-editor-block-lock-modal__checklist"
}, allowsEditLocking && (0,external_wp_element_namespaceObject.createElement)("li", {
className: "block-editor-block-lock-modal__checklist-item"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.CheckboxControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Restrict editing'),
checked: !!lock.edit,
onChange: edit => setLock(prevLock => ({ ...prevLock,
edit
}))
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Icon, {
className: "block-editor-block-lock-modal__lock-icon",
icon: lock.edit ? library_lock : library_unlock
})), (0,external_wp_element_namespaceObject.createElement)("li", {
className: "block-editor-block-lock-modal__checklist-item"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.CheckboxControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Disable movement'),
checked: lock.move,
onChange: move => setLock(prevLock => ({ ...prevLock,
move
}))
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Icon, {
className: "block-editor-block-lock-modal__lock-icon",
icon: lock.move ? library_lock : library_unlock
})), (0,external_wp_element_namespaceObject.createElement)("li", {
className: "block-editor-block-lock-modal__checklist-item"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.CheckboxControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Prevent removal'),
checked: lock.remove,
onChange: remove => setLock(prevLock => ({ ...prevLock,
remove
}))
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Icon, {
className: "block-editor-block-lock-modal__lock-icon",
icon: lock.remove ? library_lock : library_unlock
}))), hasTemplateLock && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToggleControl, {
className: "block-editor-block-lock-modal__template-lock",
label: (0,external_wp_i18n_namespaceObject.__)('Apply to all blocks inside'),
checked: applyTemplateLock,
disabled: lock.move && !lock.remove,
onChange: () => setApplyTemplateLock(!applyTemplateLock)
})), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Flex, {
className: "block-editor-block-lock-modal__actions",
justify: "flex-end",
expanded: false
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexItem, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "tertiary",
onClick: onClose
}, (0,external_wp_i18n_namespaceObject.__)('Cancel'))), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexItem, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "primary",
type: "submit"
}, (0,external_wp_i18n_namespaceObject.__)('Apply'))))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-lock/menu-item.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function BlockLockMenuItem(_ref) {
let {
clientId
} = _ref;
const {
canLock,
isLocked
} = useBlockLock(clientId);
const [isModalOpen, toggleModal] = (0,external_wp_element_namespaceObject.useReducer)(isActive => !isActive, false);
if (!canLock) {
return null;
}
const label = isLocked ? (0,external_wp_i18n_namespaceObject.__)('Unlock') : (0,external_wp_i18n_namespaceObject.__)('Lock');
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: isLocked ? library_unlock : lock_outline,
onClick: toggleModal
}, label), isModalOpen && (0,external_wp_element_namespaceObject.createElement)(BlockLockModal, {
clientId: clientId,
onClose: toggleModal
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-settings-menu-controls/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const {
Fill,
Slot: block_settings_menu_controls_Slot
} = (0,external_wp_components_namespaceObject.createSlotFill)('BlockSettingsMenuControls');
const BlockSettingsMenuControlsSlot = _ref => {
let {
fillProps,
clientIds = null,
__unstableDisplayLocation
} = _ref;
const {
selectedBlocks,
selectedClientIds,
canRemove
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlockNamesByClientId,
getSelectedBlockClientIds,
canRemoveBlocks
} = select(store);
const ids = clientIds !== null ? clientIds : getSelectedBlockClientIds();
return {
selectedBlocks: getBlockNamesByClientId(ids),
selectedClientIds: ids,
canRemove: canRemoveBlocks(ids)
};
}, [clientIds]);
const {
canLock
} = useBlockLock(selectedClientIds[0]);
const showLockButton = selectedClientIds.length === 1 && canLock; // Check if current selection of blocks is Groupable or Ungroupable
// and pass this props down to ConvertToGroupButton.
const convertToGroupButtonProps = useConvertToGroupButtonProps();
const {
isGroupable,
isUngroupable
} = convertToGroupButtonProps;
const showConvertToGroupButton = (isGroupable || isUngroupable) && canRemove;
return (0,external_wp_element_namespaceObject.createElement)(block_settings_menu_controls_Slot, {
fillProps: { ...fillProps,
__unstableDisplayLocation,
selectedBlocks,
selectedClientIds
}
}, fills => {
if (!(fills !== null && fills !== void 0 && fills.length) > 0 && !showConvertToGroupButton && !showLockButton) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, null, showLockButton && (0,external_wp_element_namespaceObject.createElement)(BlockLockMenuItem, {
clientId: selectedClientIds[0]
}), fills, showConvertToGroupButton && (0,external_wp_element_namespaceObject.createElement)(ConvertToGroupButton, _extends({}, convertToGroupButtonProps, {
onClose: fillProps === null || fillProps === void 0 ? void 0 : fillProps.onClose
})));
});
};
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/block-settings-menu-controls/README.md
*
* @param {Object} props Fill props.
* @return {WPElement} Element.
*/
function BlockSettingsMenuControls(_ref2) {
let { ...props
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalStyleProvider, {
document: document
}, (0,external_wp_element_namespaceObject.createElement)(Fill, props));
}
BlockSettingsMenuControls.Slot = BlockSettingsMenuControlsSlot;
/* harmony default export */ var block_settings_menu_controls = (BlockSettingsMenuControls);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-settings-menu/block-settings-dropdown.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const block_settings_dropdown_noop = () => {};
const block_settings_dropdown_POPOVER_PROPS = {
className: 'block-editor-block-settings-menu__popover',
position: 'bottom right',
variant: 'toolbar'
};
function CopyMenuItem(_ref) {
let {
blocks,
onCopy,
label
} = _ref;
const ref = (0,external_wp_compose_namespaceObject.useCopyToClipboard)(() => (0,external_wp_blocks_namespaceObject.serialize)(blocks), onCopy);
const copyMenuItemBlocksLabel = blocks.length > 1 ? (0,external_wp_i18n_namespaceObject.__)('Copy blocks') : (0,external_wp_i18n_namespaceObject.__)('Copy block');
const copyMenuItemLabel = label ? label : copyMenuItemBlocksLabel;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
ref: ref
}, copyMenuItemLabel);
}
function BlockSettingsDropdown(_ref2) {
let {
clientIds,
__experimentalSelectBlock,
children,
__unstableDisplayLocation,
...props
} = _ref2;
const blockClientIds = Array.isArray(clientIds) ? clientIds : [clientIds];
const count = blockClientIds.length;
const firstBlockClientId = blockClientIds[0];
const {
firstParentClientId,
isDistractionFree,
onlyBlock,
parentBlockType,
previousBlockClientId,
nextBlockClientId,
selectedBlockClientIds
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlockCount,
getBlockName,
getBlockRootClientId,
getPreviousBlockClientId,
getNextBlockClientId,
getSelectedBlockClientIds,
getSettings,
getBlockAttributes
} = select(store);
const {
getActiveBlockVariation
} = select(external_wp_blocks_namespaceObject.store);
const _firstParentClientId = getBlockRootClientId(firstBlockClientId);
const parentBlockName = _firstParentClientId && getBlockName(_firstParentClientId);
return {
firstParentClientId: _firstParentClientId,
isDistractionFree: getSettings().isDistractionFree,
onlyBlock: 1 === getBlockCount(_firstParentClientId),
parentBlockType: _firstParentClientId && (getActiveBlockVariation(parentBlockName, getBlockAttributes(_firstParentClientId)) || (0,external_wp_blocks_namespaceObject.getBlockType)(parentBlockName)),
previousBlockClientId: getPreviousBlockClientId(firstBlockClientId),
nextBlockClientId: getNextBlockClientId(firstBlockClientId),
selectedBlockClientIds: getSelectedBlockClientIds()
};
}, [firstBlockClientId]);
const shortcuts = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getShortcutRepresentation
} = select(external_wp_keyboardShortcuts_namespaceObject.store);
return {
duplicate: getShortcutRepresentation('core/block-editor/duplicate'),
remove: getShortcutRepresentation('core/block-editor/remove'),
insertAfter: getShortcutRepresentation('core/block-editor/insert-after'),
insertBefore: getShortcutRepresentation('core/block-editor/insert-before')
};
}, []);
const {
selectBlock,
toggleBlockHighlight
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const updateSelectionAfterDuplicate = (0,external_wp_element_namespaceObject.useCallback)(__experimentalSelectBlock ? async clientIdsPromise => {
const ids = await clientIdsPromise;
if (ids && ids[0]) {
__experimentalSelectBlock(ids[0]);
}
} : block_settings_dropdown_noop, [__experimentalSelectBlock]);
const blockTitle = useBlockDisplayTitle({
clientId: firstBlockClientId,
maximumLength: 25
});
const updateSelectionAfterRemove = (0,external_wp_element_namespaceObject.useCallback)(__experimentalSelectBlock ? () => {
const blockToSelect = previousBlockClientId || nextBlockClientId || firstParentClientId;
if (blockToSelect && // From the block options dropdown, it's possible to remove a block that is not selected,
// in this case, it's not necessary to update the selection since the selected block wasn't removed.
selectedBlockClientIds.includes(firstBlockClientId) && // Don't update selection when next/prev block also is in the selection ( and gets removed ),
// In case someone selects all blocks and removes them at once.
!selectedBlockClientIds.includes(blockToSelect)) {
__experimentalSelectBlock(blockToSelect);
}
} : block_settings_dropdown_noop, [__experimentalSelectBlock, previousBlockClientId, nextBlockClientId, firstParentClientId, selectedBlockClientIds]);
const label = (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: block name */
(0,external_wp_i18n_namespaceObject.__)('Remove %s'), blockTitle);
const removeBlockLabel = count === 1 ? label : (0,external_wp_i18n_namespaceObject.__)('Remove blocks'); // Allows highlighting the parent block outline when focusing or hovering
// the parent block selector within the child.
const selectParentButtonRef = (0,external_wp_element_namespaceObject.useRef)();
const {
gestures: showParentOutlineGestures
} = useShowMoversGestures({
ref: selectParentButtonRef,
onChange(isFocused) {
if (isFocused && isDistractionFree) {
return;
}
toggleBlockHighlight(firstParentClientId, isFocused);
}
}); // This can occur when the selected block (the parent)
// displays child blocks within a List View.
const parentBlockIsSelected = selectedBlockClientIds === null || selectedBlockClientIds === void 0 ? void 0 : selectedBlockClientIds.includes(firstParentClientId);
return (0,external_wp_element_namespaceObject.createElement)(BlockActions, {
clientIds: clientIds,
__experimentalUpdateSelection: !__experimentalSelectBlock
}, _ref3 => {
let {
canDuplicate,
canInsertDefaultBlock,
canMove,
canRemove,
onDuplicate,
onInsertAfter,
onInsertBefore,
onRemove,
onCopy,
onPasteStyles,
onMoveTo,
blocks
} = _ref3;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.DropdownMenu, _extends({
icon: more_vertical,
label: (0,external_wp_i18n_namespaceObject.__)('Options'),
className: "block-editor-block-settings-menu",
popoverProps: block_settings_dropdown_POPOVER_PROPS,
noIcons: true
}, props), _ref4 => {
let {
onClose
} = _ref4;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, null, (0,external_wp_element_namespaceObject.createElement)(block_settings_menu_first_item.Slot, {
fillProps: {
onClose
}
}), !parentBlockIsSelected && !!firstParentClientId && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, _extends({}, showParentOutlineGestures, {
ref: selectParentButtonRef,
icon: (0,external_wp_element_namespaceObject.createElement)(block_icon, {
icon: parentBlockType.icon
}),
onClick: () => selectBlock(firstParentClientId)
}), (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: Name of the block's parent. */
(0,external_wp_i18n_namespaceObject.__)('Select parent block (%s)'), parentBlockType.title)), count === 1 && (0,external_wp_element_namespaceObject.createElement)(block_html_convert_button, {
clientId: firstBlockClientId
}), (0,external_wp_element_namespaceObject.createElement)(CopyMenuItem, {
blocks: blocks,
onCopy: onCopy
}), canDuplicate && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
onClick: (0,external_wp_compose_namespaceObject.pipe)(onClose, onDuplicate, updateSelectionAfterDuplicate),
shortcut: shortcuts.duplicate
}, (0,external_wp_i18n_namespaceObject.__)('Duplicate')), canInsertDefaultBlock && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
onClick: (0,external_wp_compose_namespaceObject.pipe)(onClose, onInsertBefore),
shortcut: shortcuts.insertBefore
}, (0,external_wp_i18n_namespaceObject.__)('Insert before')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
onClick: (0,external_wp_compose_namespaceObject.pipe)(onClose, onInsertAfter),
shortcut: shortcuts.insertAfter
}, (0,external_wp_i18n_namespaceObject.__)('Insert after'))), canMove && !onlyBlock && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
onClick: (0,external_wp_compose_namespaceObject.pipe)(onClose, onMoveTo)
}, (0,external_wp_i18n_namespaceObject.__)('Move to')), count === 1 && (0,external_wp_element_namespaceObject.createElement)(block_mode_toggle, {
clientId: firstBlockClientId,
onToggle: onClose
})), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, null, (0,external_wp_element_namespaceObject.createElement)(CopyMenuItem, {
blocks: blocks,
onCopy: onCopy,
label: (0,external_wp_i18n_namespaceObject.__)('Copy styles')
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
onClick: onPasteStyles
}, (0,external_wp_i18n_namespaceObject.__)('Paste styles'))), (0,external_wp_element_namespaceObject.createElement)(block_settings_menu_controls.Slot, {
fillProps: {
onClose
},
clientIds: clientIds,
__unstableDisplayLocation: __unstableDisplayLocation
}), typeof children === 'function' ? children({
onClose
}) : external_wp_element_namespaceObject.Children.map(child => (0,external_wp_element_namespaceObject.cloneElement)(child, {
onClose
})), canRemove && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
onClick: (0,external_wp_compose_namespaceObject.pipe)(onClose, onRemove, updateSelectionAfterRemove),
shortcut: shortcuts.remove
}, removeBlockLabel)));
});
});
}
/* harmony default export */ var block_settings_dropdown = (BlockSettingsDropdown);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-settings-menu/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function BlockSettingsMenu(_ref) {
let {
clientIds,
...props
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarGroup, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarItem, null, toggleProps => (0,external_wp_element_namespaceObject.createElement)(block_settings_dropdown, _extends({
clientIds: clientIds,
toggleProps: toggleProps
}, props))));
}
/* harmony default export */ var block_settings_menu = (BlockSettingsMenu);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-lock/toolbar.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function BlockLockToolbar(_ref) {
let {
clientId
} = _ref;
const blockInformation = useBlockDisplayInformation(clientId);
const {
canEdit,
canMove,
canRemove,
canLock
} = useBlockLock(clientId);
const [isModalOpen, toggleModal] = (0,external_wp_element_namespaceObject.useReducer)(isActive => !isActive, false);
if (!canLock) {
return null;
}
if (canEdit && canMove && canRemove) {
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.ToolbarGroup, {
className: "block-editor-block-lock-toolbar"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
icon: library_lock,
label: (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: block name */
(0,external_wp_i18n_namespaceObject.__)('Unlock %s'), blockInformation.title),
onClick: toggleModal
})), isModalOpen && (0,external_wp_element_namespaceObject.createElement)(BlockLockModal, {
clientId: clientId,
onClose: toggleModal
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/group.js
/**
* WordPress dependencies
*/
const group_group = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M18 4h-7c-1.1 0-2 .9-2 2v3H6c-1.1 0-2 .9-2 2v7c0 1.1.9 2 2 2h7c1.1 0 2-.9 2-2v-3h3c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-4.5 14c0 .3-.2.5-.5.5H6c-.3 0-.5-.2-.5-.5v-7c0-.3.2-.5.5-.5h3V13c0 1.1.9 2 2 2h2.5v3zm0-4.5H11c-.3 0-.5-.2-.5-.5v-2.5H13c.3 0 .5.2.5.5v2.5zm5-.5c0 .3-.2.5-.5.5h-3V11c0-1.1-.9-2-2-2h-2.5V6c0-.3.2-.5.5-.5h7c.3 0 .5.2.5.5v7z"
}));
/* harmony default export */ var library_group = (group_group);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/row.js
/**
* WordPress dependencies
*/
const row = (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: "M9.2 6.5H4V8h5.2c.3 0 .5.2.5.5v7c0 .3-.2.5-.5.5H4v1.5h5.2c1.1 0 2-.9 2-2v-7c0-1.1-.8-2-2-2zM14.8 8H20V6.5h-5.2c-1.1 0-2 .9-2 2v7c0 1.1.9 2 2 2H20V16h-5.2c-.3 0-.5-.2-.5-.5v-7c-.1-.3.2-.5.5-.5z"
}));
/* harmony default export */ var library_row = (row);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/stack.js
/**
* WordPress dependencies
*/
const stack = (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: "M16 4v5.2c0 .3-.2.5-.5.5h-7c-.3.1-.5-.2-.5-.5V4H6.5v5.2c0 1.1.9 2 2 2h7c1.1 0 2-.9 2-2V4H16zm-.5 8.8h-7c-1.1 0-2 .9-2 2V20H8v-5.2c0-.3.2-.5.5-.5h7c.3 0 .5.2.5.5V20h1.5v-5.2c0-1.2-.9-2-2-2z"
}));
/* harmony default export */ var library_stack = (stack);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/convert-to-group-buttons/toolbar.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const layouts = {
group: {
type: 'constrained'
},
row: {
type: 'flex',
flexWrap: 'nowrap'
},
stack: {
type: 'flex',
orientation: 'vertical'
}
};
function BlockGroupToolbar() {
const {
blocksSelection,
clientIds,
groupingBlockName,
isGroupable
} = useConvertToGroupButtonProps();
const {
replaceBlocks
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const {
canRemove,
variations
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
canRemoveBlocks
} = select(store);
const {
getBlockVariations
} = select(external_wp_blocks_namespaceObject.store);
return {
canRemove: canRemoveBlocks(clientIds),
variations: getBlockVariations(groupingBlockName, 'transform')
};
}, [clientIds, groupingBlockName]);
const onConvertToGroup = layout => {
const newBlocks = (0,external_wp_blocks_namespaceObject.switchToBlockType)(blocksSelection, groupingBlockName);
if (typeof layout !== 'string') {
layout = 'group';
}
if (newBlocks && newBlocks.length > 0) {
// Because the block is not in the store yet we can't use
// updateBlockAttributes so need to manually update attributes.
newBlocks[0].attributes.layout = layouts[layout];
replaceBlocks(clientIds, newBlocks);
}
};
const onConvertToRow = () => onConvertToGroup('row');
const onConvertToStack = () => onConvertToGroup('stack'); // Don't render the button if the current selection cannot be grouped.
// A good example is selecting multiple button blocks within a Buttons block:
// The group block is not a valid child of Buttons, so we should not show the button.
// Any blocks that are locked against removal also cannot be grouped.
if (!isGroupable || !canRemove) {
return null;
}
const canInsertRow = !!variations.find(_ref => {
let {
name
} = _ref;
return name === 'group-row';
});
const canInsertStack = !!variations.find(_ref2 => {
let {
name
} = _ref2;
return name === 'group-stack';
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarGroup, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
icon: library_group,
label: (0,external_wp_i18n_namespaceObject._x)('Group', 'verb'),
onClick: onConvertToGroup
}), canInsertRow && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
icon: library_row,
label: (0,external_wp_i18n_namespaceObject._x)('Row', 'single horizontal line'),
onClick: onConvertToRow
}), canInsertStack && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
icon: library_stack,
label: (0,external_wp_i18n_namespaceObject._x)('Stack', 'verb'),
onClick: onConvertToStack
}));
}
/* harmony default export */ var toolbar = (BlockGroupToolbar);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-edit-visually-button/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function BlockEditVisuallyButton(_ref) {
let {
clientIds
} = _ref;
// Edit visually only works for single block selection.
const clientId = clientIds.length === 1 ? clientIds[0] : undefined;
const canEditVisually = (0,external_wp_data_namespaceObject.useSelect)(select => !!clientId && select(store).getBlockMode(clientId) === 'html', [clientId]);
const {
toggleBlockMode
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
if (!canEditVisually) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarGroup, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
onClick: () => {
toggleBlockMode(clientId);
}
}, (0,external_wp_i18n_namespaceObject.__)('Edit visually')));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-toolbar/block-name-context.js
/**
* WordPress dependencies
*/
const __unstableBlockNameContext = (0,external_wp_element_namespaceObject.createContext)('');
/* harmony default export */ var block_name_context = (__unstableBlockNameContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-toolbar/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const BlockToolbar = _ref => {
let {
hideDragHandle
} = _ref;
const {
blockClientIds,
blockClientId,
blockType,
hasFixedToolbar,
isDistractionFree,
isValid,
isVisual,
isContentLocked
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlockName,
getBlockMode,
getSelectedBlockClientIds,
isBlockValid,
getBlockRootClientId,
getSettings,
__unstableGetContentLockingParent
} = select(store);
const selectedBlockClientIds = getSelectedBlockClientIds();
const selectedBlockClientId = selectedBlockClientIds[0];
const blockRootClientId = getBlockRootClientId(selectedBlockClientId);
const settings = getSettings();
return {
blockClientIds: selectedBlockClientIds,
blockClientId: selectedBlockClientId,
blockType: selectedBlockClientId && (0,external_wp_blocks_namespaceObject.getBlockType)(getBlockName(selectedBlockClientId)),
hasFixedToolbar: settings.hasFixedToolbar,
isDistractionFree: settings.isDistractionFree,
rootClientId: blockRootClientId,
isValid: selectedBlockClientIds.every(id => isBlockValid(id)),
isVisual: selectedBlockClientIds.every(id => getBlockMode(id) === 'visual'),
isContentLocked: !!__unstableGetContentLockingParent(selectedBlockClientId)
};
}, []); // Handles highlighting the current block outline on hover or focus of the
// block type toolbar area.
const {
toggleBlockHighlight
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const nodeRef = (0,external_wp_element_namespaceObject.useRef)();
const {
showMovers,
gestures: showMoversGestures
} = useShowMoversGestures({
ref: nodeRef,
onChange(isFocused) {
if (isFocused && isDistractionFree) {
return;
}
toggleBlockHighlight(blockClientId, isFocused);
}
}); // Account for the cases where the block toolbar is rendered within the
// header area and not contextually to the block.
const displayHeaderToolbar = (0,external_wp_compose_namespaceObject.useViewportMatch)('medium', '<') || hasFixedToolbar;
if (blockType) {
if (!(0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockType, '__experimentalToolbar', true)) {
return null;
}
}
const shouldShowMovers = displayHeaderToolbar || showMovers;
if (blockClientIds.length === 0) {
return null;
}
const shouldShowVisualToolbar = isValid && isVisual;
const isMultiToolbar = blockClientIds.length > 1;
const isSynced = (0,external_wp_blocks_namespaceObject.isReusableBlock)(blockType) || (0,external_wp_blocks_namespaceObject.isTemplatePart)(blockType);
const classes = classnames_default()('block-editor-block-toolbar', {
'is-showing-movers': shouldShowMovers,
'is-synced': isSynced
});
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classes
}, !isMultiToolbar && !displayHeaderToolbar && !isContentLocked && (0,external_wp_element_namespaceObject.createElement)(BlockParentSelector, null), (0,external_wp_element_namespaceObject.createElement)("div", _extends({
ref: nodeRef
}, showMoversGestures), (shouldShowVisualToolbar || isMultiToolbar) && !isContentLocked && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarGroup, {
className: "block-editor-block-toolbar__block-controls"
}, (0,external_wp_element_namespaceObject.createElement)(block_switcher, {
clientIds: blockClientIds
}), !isMultiToolbar && (0,external_wp_element_namespaceObject.createElement)(BlockLockToolbar, {
clientId: blockClientIds[0]
}), (0,external_wp_element_namespaceObject.createElement)(block_mover, {
clientIds: blockClientIds,
hideDragHandle: hideDragHandle
}))), shouldShowVisualToolbar && isMultiToolbar && (0,external_wp_element_namespaceObject.createElement)(toolbar, null), shouldShowVisualToolbar && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(block_controls.Slot, {
group: "parent",
className: "block-editor-block-toolbar__slot"
}), (0,external_wp_element_namespaceObject.createElement)(block_controls.Slot, {
group: "block",
className: "block-editor-block-toolbar__slot"
}), (0,external_wp_element_namespaceObject.createElement)(block_controls.Slot, {
className: "block-editor-block-toolbar__slot"
}), (0,external_wp_element_namespaceObject.createElement)(block_controls.Slot, {
group: "inline",
className: "block-editor-block-toolbar__slot"
}), (0,external_wp_element_namespaceObject.createElement)(block_controls.Slot, {
group: "other",
className: "block-editor-block-toolbar__slot"
}), (0,external_wp_element_namespaceObject.createElement)(block_name_context.Provider, {
value: blockType === null || blockType === void 0 ? void 0 : blockType.name
}, (0,external_wp_element_namespaceObject.createElement)(block_toolbar_last_item.Slot, null))), (0,external_wp_element_namespaceObject.createElement)(BlockEditVisuallyButton, {
clientIds: blockClientIds
}), !isContentLocked && (0,external_wp_element_namespaceObject.createElement)(block_settings_menu, {
clientIds: blockClientIds
}));
};
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/block-toolbar/README.md
*/
/* harmony default export */ var block_toolbar = (BlockToolbar);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-tools/block-contextual-toolbar.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function BlockContextualToolbar(_ref) {
let {
focusOnMount,
isFixed,
...props
} = _ref;
const {
blockType,
hasParents,
showParentSelector
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlockName,
getBlockParents,
getSelectedBlockClientIds,
__unstableGetContentLockingParent
} = select(store);
const {
getBlockType
} = select(external_wp_blocks_namespaceObject.store);
const selectedBlockClientIds = getSelectedBlockClientIds();
const selectedBlockClientId = selectedBlockClientIds[0];
const parents = getBlockParents(selectedBlockClientId);
const firstParentClientId = parents[parents.length - 1];
const parentBlockName = getBlockName(firstParentClientId);
const parentBlockType = getBlockType(parentBlockName);
return {
blockType: selectedBlockClientId && getBlockType(getBlockName(selectedBlockClientId)),
hasParents: parents.length,
showParentSelector: parentBlockType && (0,external_wp_blocks_namespaceObject.hasBlockSupport)(parentBlockType, '__experimentalParentSelector', true) && selectedBlockClientIds.length <= 1 && !__unstableGetContentLockingParent(selectedBlockClientId)
};
}, []);
if (blockType) {
if (!(0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockType, '__experimentalToolbar', true)) {
return null;
}
} // Shifts the toolbar to make room for the parent block selector.
const classes = classnames_default()('block-editor-block-contextual-toolbar', {
'has-parent': hasParents && showParentSelector,
'is-fixed': isFixed
});
return (0,external_wp_element_namespaceObject.createElement)(navigable_toolbar, _extends({
focusOnMount: focusOnMount,
className: classes
/* translators: accessibility text for the block toolbar */
,
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Block tools')
}, props), (0,external_wp_element_namespaceObject.createElement)(block_toolbar, {
hideDragHandle: isFixed
}));
}
/* harmony default export */ var block_contextual_toolbar = (BlockContextualToolbar);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/position.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const {
CustomSelectControl
} = unlock(external_wp_components_namespaceObject.privateApis);
const POSITION_SUPPORT_KEY = 'position';
const OPTION_CLASSNAME = 'block-editor-hooks__position-selection__select-control__option';
const DEFAULT_OPTION = {
key: 'default',
value: '',
name: (0,external_wp_i18n_namespaceObject.__)('Default'),
className: OPTION_CLASSNAME
};
const STICKY_OPTION = {
key: 'sticky',
value: 'sticky',
name: (0,external_wp_i18n_namespaceObject._x)('Sticky', 'Name for the value of the CSS position property'),
className: OPTION_CLASSNAME,
__experimentalHint: (0,external_wp_i18n_namespaceObject.__)('The block will stick to the top of the window instead of scrolling.')
};
const FIXED_OPTION = {
key: 'fixed',
value: 'fixed',
name: (0,external_wp_i18n_namespaceObject._x)('Fixed', 'Name for the value of the CSS position property'),
className: OPTION_CLASSNAME,
__experimentalHint: (0,external_wp_i18n_namespaceObject.__)('The block will not move when the page is scrolled.')
};
const POSITION_SIDES = ['top', 'right', 'bottom', 'left'];
const VALID_POSITION_TYPES = ['sticky', 'fixed'];
/**
* Get calculated position CSS.
*
* @param {Object} props Component props.
* @param {string} props.selector Selector to use.
* @param {Object} props.style Style object.
* @return {string} The generated CSS rules.
*/
function getPositionCSS(_ref) {
let {
selector,
style
} = _ref;
let output = '';
const {
type: positionType
} = (style === null || style === void 0 ? void 0 : style.position) || {};
if (!VALID_POSITION_TYPES.includes(positionType)) {
return output;
}
output += `${selector} {`;
output += `position: ${positionType};`;
POSITION_SIDES.forEach(side => {
var _style$position;
if ((style === null || style === void 0 ? void 0 : (_style$position = style.position) === null || _style$position === void 0 ? void 0 : _style$position[side]) !== undefined) {
output += `${side}: ${style.position[side]};`;
}
});
if (positionType === 'sticky' || positionType === 'fixed') {
// TODO: Replace hard-coded z-index value with a z-index preset approach in theme.json.
output += `z-index: 10`;
}
output += `}`;
return output;
}
/**
* Determines if there is sticky position support.
*
* @param {string|Object} blockType Block name or Block Type object.
*
* @return {boolean} Whether there is support.
*/
function hasStickyPositionSupport(blockType) {
const support = (0,external_wp_blocks_namespaceObject.getBlockSupport)(blockType, POSITION_SUPPORT_KEY);
return !!(true === support || support !== null && support !== void 0 && support.sticky);
}
/**
* Determines if there is fixed position support.
*
* @param {string|Object} blockType Block name or Block Type object.
*
* @return {boolean} Whether there is support.
*/
function hasFixedPositionSupport(blockType) {
const support = (0,external_wp_blocks_namespaceObject.getBlockSupport)(blockType, POSITION_SUPPORT_KEY);
return !!(true === support || support !== null && support !== void 0 && support.fixed);
}
/**
* Determines if there is position support.
*
* @param {string|Object} blockType Block name or Block Type object.
*
* @return {boolean} Whether there is support.
*/
function hasPositionSupport(blockType) {
const support = (0,external_wp_blocks_namespaceObject.getBlockSupport)(blockType, POSITION_SUPPORT_KEY);
return !!support;
}
/**
* Checks if there is a current value in the position block support attributes.
*
* @param {Object} props Block props.
* @return {boolean} Whether or not the block has a position value set.
*/
function hasPositionValue(props) {
var _props$attributes$sty, _props$attributes$sty2;
return ((_props$attributes$sty = props.attributes.style) === null || _props$attributes$sty === void 0 ? void 0 : (_props$attributes$sty2 = _props$attributes$sty.position) === null || _props$attributes$sty2 === void 0 ? void 0 : _props$attributes$sty2.type) !== undefined;
}
/**
* Checks if the block is currently set to a sticky or fixed position.
* This check is helpful for determining how to position block toolbars or other elements.
*
* @param {Object} attributes Block attributes.
* @return {boolean} Whether or not the block is set to a sticky or fixed position.
*/
function hasStickyOrFixedPositionValue(attributes) {
var _attributes$style, _attributes$style$pos;
const positionType = (_attributes$style = attributes.style) === null || _attributes$style === void 0 ? void 0 : (_attributes$style$pos = _attributes$style.position) === null || _attributes$style$pos === void 0 ? void 0 : _attributes$style$pos.type;
return positionType === 'sticky' || positionType === 'fixed';
}
/**
* Resets the position block support attributes. This can be used when disabling
* the position support controls for a block via a `ToolsPanel`.
*
* @param {Object} props Block props.
* @param {Object} props.attributes Block's attributes.
* @param {Object} props.setAttributes Function to set block's attributes.
*/
function resetPosition(_ref2) {
let {
attributes = {},
setAttributes
} = _ref2;
const {
style = {}
} = attributes;
setAttributes({
style: cleanEmptyObject({ ...style,
position: { ...(style === null || style === void 0 ? void 0 : style.position),
type: undefined,
top: undefined,
right: undefined,
bottom: undefined,
left: undefined
}
})
});
}
/**
* Custom hook that checks if position settings have been disabled.
*
* @param {string} name The name of the block.
*
* @return {boolean} Whether padding setting is disabled.
*/
function useIsPositionDisabled() {
let {
name: blockName
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const allowFixed = useSetting('position.fixed');
const allowSticky = useSetting('position.sticky');
const isDisabled = !allowFixed && !allowSticky;
return !hasPositionSupport(blockName) || isDisabled;
}
/*
* Position controls rendered in an inspector control panel.
*
* @param {Object} props
*
* @return {WPElement} Position panel.
*/
function PositionPanel(props) {
var _style$position2;
const {
attributes: {
style = {}
},
clientId,
name: blockName,
setAttributes
} = props;
const allowFixed = hasFixedPositionSupport(blockName);
const allowSticky = hasStickyPositionSupport(blockName);
const value = style === null || style === void 0 ? void 0 : (_style$position2 = style.position) === null || _style$position2 === void 0 ? void 0 : _style$position2.type;
const {
hasParents
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlockParents
} = select(store);
const parents = getBlockParents(clientId);
return {
hasParents: parents.length
};
}, [clientId]);
const options = (0,external_wp_element_namespaceObject.useMemo)(() => {
const availableOptions = [DEFAULT_OPTION]; // Only display sticky option if the block has no parents (is at the root of the document),
// or if the block already has a sticky position value set.
if (allowSticky && !hasParents || value === STICKY_OPTION.value) {
availableOptions.push(STICKY_OPTION);
}
if (allowFixed || value === FIXED_OPTION.value) {
availableOptions.push(FIXED_OPTION);
}
return availableOptions;
}, [allowFixed, allowSticky, hasParents, value]);
const onChangeType = next => {
// For now, use a hard-coded `0px` value for the position.
// `0px` is preferred over `0` as it can be used in `calc()` functions.
// In the future, it could be useful to allow for an offset value.
const placementValue = '0px';
const newStyle = { ...style,
position: { ...(style === null || style === void 0 ? void 0 : style.position),
type: next,
top: next === 'sticky' || next === 'fixed' ? placementValue : undefined
}
};
setAttributes({
style: utils_cleanEmptyObject(newStyle)
});
};
const selectedOption = value ? options.find(option => option.value === value) || DEFAULT_OPTION : DEFAULT_OPTION; // Only display position controls if there is at least one option to choose from.
return external_wp_element_namespaceObject.Platform.select({
web: options.length > 1 ? (0,external_wp_element_namespaceObject.createElement)(inspector_controls, {
group: "position"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.BaseControl, {
className: "block-editor-hooks__position-selection"
}, (0,external_wp_element_namespaceObject.createElement)(CustomSelectControl, {
__nextUnconstrainedWidth: true,
__next36pxDefaultSize: true,
className: "block-editor-hooks__position-selection__select-control",
label: (0,external_wp_i18n_namespaceObject.__)('Position'),
hideLabelFromVision: true,
describedBy: (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: Currently selected position.
(0,external_wp_i18n_namespaceObject.__)('Currently selected position: %s'), selectedOption.name),
options: options,
value: selectedOption,
__experimentalShowSelectedHint: true,
onChange: _ref3 => {
let {
selectedItem
} = _ref3;
onChangeType(selectedItem.value);
},
size: '__unstable-large'
}))) : null,
native: null
});
}
/**
* Override the default edit UI to include position controls.
*
* @param {Function} BlockEdit Original component.
*
* @return {Function} Wrapped component.
*/
const withInspectorControls = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(BlockEdit => props => {
const {
name: blockName
} = props;
const positionSupport = (0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockName, POSITION_SUPPORT_KEY);
const showPositionControls = positionSupport && !useIsPositionDisabled(props);
return [showPositionControls && (0,external_wp_element_namespaceObject.createElement)(PositionPanel, _extends({
key: "position"
}, props)), (0,external_wp_element_namespaceObject.createElement)(BlockEdit, _extends({
key: "edit"
}, props))];
}, 'withInspectorControls');
/**
* Override the default block element to add the position styles.
*
* @param {Function} BlockListBlock Original component.
*
* @return {Function} Wrapped component.
*/
const withPositionStyles = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(BlockListBlock => props => {
var _attributes$style2, _attributes$style2$po, _attributes$style3, _attributes$style3$po;
const {
name,
attributes
} = props;
const hasPositionBlockSupport = (0,external_wp_blocks_namespaceObject.hasBlockSupport)(name, POSITION_SUPPORT_KEY);
const allowPositionStyles = hasPositionBlockSupport && !useIsPositionDisabled(props);
const id = (0,external_wp_compose_namespaceObject.useInstanceId)(BlockListBlock);
const element = (0,external_wp_element_namespaceObject.useContext)(BlockList.__unstableElementContext); // Higher specificity to override defaults in editor UI.
const positionSelector = `.wp-container-${id}.wp-container-${id}`; // Get CSS string for the current position values.
let css;
if (allowPositionStyles) {
css = getPositionCSS({
selector: positionSelector,
style: attributes === null || attributes === void 0 ? void 0 : attributes.style
}) || '';
} // Attach a `wp-container-` id-based class name.
const className = classnames_default()(props === null || props === void 0 ? void 0 : props.className, {
[`wp-container-${id}`]: allowPositionStyles && !!css,
// Only attach a container class if there is generated CSS to be attached.
[`is-position-${attributes === null || attributes === void 0 ? void 0 : (_attributes$style2 = attributes.style) === null || _attributes$style2 === void 0 ? void 0 : (_attributes$style2$po = _attributes$style2.position) === null || _attributes$style2$po === void 0 ? void 0 : _attributes$style2$po.type}`]: allowPositionStyles && !!css && !!(attributes !== null && attributes !== void 0 && (_attributes$style3 = attributes.style) !== null && _attributes$style3 !== void 0 && (_attributes$style3$po = _attributes$style3.position) !== null && _attributes$style3$po !== void 0 && _attributes$style3$po.type)
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, allowPositionStyles && element && !!css && (0,external_wp_element_namespaceObject.createPortal)((0,external_wp_element_namespaceObject.createElement)("style", null, css), element), (0,external_wp_element_namespaceObject.createElement)(BlockListBlock, _extends({}, props, {
className: className
})));
});
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockListBlock', 'core/editor/position/with-position-styles', withPositionStyles);
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockEdit', 'core/editor/position/with-inspector-controls', withInspectorControls);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-tools/use-block-toolbar-popover-props.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const COMMON_PROPS = {
placement: 'top-start'
}; // By default the toolbar sets the `shift` prop. If the user scrolls the page
// down the toolbar will stay on screen by adopting a sticky position at the
// top of the viewport.
const use_block_toolbar_popover_props_DEFAULT_PROPS = { ...COMMON_PROPS,
flip: false,
shift: true
}; // When there isn't enough height between the top of the block and the editor
// canvas, the `shift` prop is set to `false`, as it will cause the block to be
// obscured. The `flip` behavior is enabled, which positions the toolbar below
// the block. This only happens if the block is smaller than the viewport, as
// otherwise the toolbar will be off-screen.
const RESTRICTED_HEIGHT_PROPS = { ...COMMON_PROPS,
flip: true,
shift: false
};
/**
* Get the popover props for the block toolbar, determined by the space at the top of the canvas and the toolbar height.
*
* @param {Element} contentElement The DOM element that represents the editor content or canvas.
* @param {Element} selectedBlockElement The outer DOM element of the first selected block.
* @param {Element} scrollContainer The scrollable container for the contentElement.
* @param {number} toolbarHeight The height of the toolbar in pixels.
* @param {boolean} isSticky Whether or not the selected block is sticky or fixed.
*
* @return {Object} The popover props used to determine the position of the toolbar.
*/
function getProps(contentElement, selectedBlockElement, scrollContainer, toolbarHeight, isSticky) {
if (!contentElement || !selectedBlockElement) {
return use_block_toolbar_popover_props_DEFAULT_PROPS;
} // Get how far the content area has been scrolled.
const scrollTop = (scrollContainer === null || scrollContainer === void 0 ? void 0 : scrollContainer.scrollTop) || 0;
const blockRect = selectedBlockElement.getBoundingClientRect();
const contentRect = contentElement.getBoundingClientRect(); // Get the vertical position of top of the visible content area.
const topOfContentElementInViewport = scrollTop + contentRect.top; // The document element's clientHeight represents the viewport height.
const viewportHeight = contentElement.ownerDocument.documentElement.clientHeight; // The restricted height area is calculated as the sum of the
// vertical position of the visible content area, plus the height
// of the block toolbar.
const restrictedTopArea = topOfContentElementInViewport + toolbarHeight;
const hasSpaceForToolbarAbove = blockRect.top > restrictedTopArea;
const isBlockTallerThanViewport = blockRect.height > viewportHeight - toolbarHeight; // Sticky blocks are treated as if they will never have enough space for the toolbar above.
if (!isSticky && (hasSpaceForToolbarAbove || isBlockTallerThanViewport)) {
return use_block_toolbar_popover_props_DEFAULT_PROPS;
}
return RESTRICTED_HEIGHT_PROPS;
}
/**
* Determines the desired popover positioning behavior, returning a set of appropriate props.
*
* @param {Object} elements
* @param {Element} elements.contentElement The DOM element that represents the editor content or canvas.
* @param {string} elements.clientId The clientId of the first selected block.
*
* @return {Object} The popover props used to determine the position of the toolbar.
*/
function useBlockToolbarPopoverProps(_ref) {
let {
contentElement,
clientId
} = _ref;
const selectedBlockElement = useBlockElement(clientId);
const [toolbarHeight, setToolbarHeight] = (0,external_wp_element_namespaceObject.useState)(0);
const {
blockIndex,
isSticky
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlockIndex,
getBlockAttributes
} = select(store);
return {
blockIndex: getBlockIndex(clientId),
isSticky: hasStickyOrFixedPositionValue(getBlockAttributes(clientId))
};
}, [clientId]);
const scrollContainer = (0,external_wp_element_namespaceObject.useMemo)(() => {
if (!contentElement) {
return;
}
return (0,external_wp_dom_namespaceObject.getScrollContainer)(contentElement);
}, [contentElement]);
const [props, setProps] = (0,external_wp_element_namespaceObject.useState)(() => getProps(contentElement, selectedBlockElement, scrollContainer, toolbarHeight, isSticky));
const popoverRef = (0,external_wp_compose_namespaceObject.useRefEffect)(popoverNode => {
setToolbarHeight(popoverNode.offsetHeight);
}, []);
const updateProps = (0,external_wp_element_namespaceObject.useCallback)(() => setProps(getProps(contentElement, selectedBlockElement, scrollContainer, toolbarHeight, isSticky)), [contentElement, selectedBlockElement, scrollContainer, toolbarHeight]); // Update props when the block is moved. This also ensures the props are
// correct on initial mount, and when the selected block or content element
// changes (since the callback ref will update).
(0,external_wp_element_namespaceObject.useLayoutEffect)(updateProps, [blockIndex, updateProps]); // Update props when the viewport is resized or the block is resized.
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
var _contentElement$owner, _contentView$addEvent, _selectedBlockElement;
if (!contentElement || !selectedBlockElement) {
return;
} // Update the toolbar props on viewport resize.
const contentView = contentElement === null || contentElement === void 0 ? void 0 : (_contentElement$owner = contentElement.ownerDocument) === null || _contentElement$owner === void 0 ? void 0 : _contentElement$owner.defaultView;
contentView === null || contentView === void 0 ? void 0 : (_contentView$addEvent = contentView.addEventHandler) === null || _contentView$addEvent === void 0 ? void 0 : _contentView$addEvent.call(contentView, 'resize', updateProps); // Update the toolbar props on block resize.
let resizeObserver;
const blockView = selectedBlockElement === null || selectedBlockElement === void 0 ? void 0 : (_selectedBlockElement = selectedBlockElement.ownerDocument) === null || _selectedBlockElement === void 0 ? void 0 : _selectedBlockElement.defaultView;
if (blockView.ResizeObserver) {
resizeObserver = new blockView.ResizeObserver(updateProps);
resizeObserver.observe(selectedBlockElement);
}
return () => {
var _contentView$removeEv;
contentView === null || contentView === void 0 ? void 0 : (_contentView$removeEv = contentView.removeEventHandler) === null || _contentView$removeEv === void 0 ? void 0 : _contentView$removeEv.call(contentView, 'resize', updateProps);
if (resizeObserver) {
resizeObserver.disconnect();
}
};
}, [updateProps, contentElement, selectedBlockElement]);
return { ...props,
ref: popoverRef
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-tools/selected-block-popover.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function selected_block_popover_selector(select) {
const {
__unstableGetEditorMode,
isMultiSelecting,
hasMultiSelection,
isTyping,
isBlockInterfaceHidden,
getSettings,
getLastMultiSelectedBlockClientId
} = unlock(select(store));
return {
editorMode: __unstableGetEditorMode(),
hasMultiSelection: hasMultiSelection(),
isMultiSelecting: isMultiSelecting(),
isTyping: isTyping(),
isBlockInterfaceHidden: isBlockInterfaceHidden(),
hasFixedToolbar: getSettings().hasFixedToolbar,
isDistractionFree: getSettings().isDistractionFree,
lastClientId: hasMultiSelection() ? getLastMultiSelectedBlockClientId() : null
};
}
function SelectedBlockPopover(_ref) {
let {
clientId,
rootClientId,
isEmptyDefaultBlock,
showContents,
// we may need to mount an empty popover because we reuse
capturingClientId,
__unstablePopoverSlot,
__unstableContentRef
} = _ref;
const {
editorMode,
hasMultiSelection,
isMultiSelecting,
isTyping,
isBlockInterfaceHidden,
hasFixedToolbar,
isDistractionFree,
lastClientId
} = (0,external_wp_data_namespaceObject.useSelect)(selected_block_popover_selector, []);
const isInsertionPointVisible = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
isBlockInsertionPointVisible,
getBlockInsertionPoint,
getBlockOrder
} = select(store);
if (!isBlockInsertionPointVisible()) {
return false;
}
const insertionPoint = getBlockInsertionPoint();
const order = getBlockOrder(insertionPoint.rootClientId);
return order[insertionPoint.index] === clientId;
}, [clientId]);
const isLargeViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('medium');
const isToolbarForced = (0,external_wp_element_namespaceObject.useRef)(false);
const {
stopTyping
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const showEmptyBlockSideInserter = !isTyping && editorMode === 'edit' && isEmptyDefaultBlock;
const shouldShowBreadcrumb = !hasMultiSelection && (editorMode === 'navigation' || editorMode === 'zoom-out');
const shouldShowContextualToolbar = editorMode === 'edit' && !hasFixedToolbar && isLargeViewport && !isMultiSelecting && !showEmptyBlockSideInserter && !isTyping && !isBlockInterfaceHidden;
const canFocusHiddenToolbar = editorMode === 'edit' && !shouldShowContextualToolbar && !hasFixedToolbar && !isDistractionFree && !isEmptyDefaultBlock;
(0,external_wp_keyboardShortcuts_namespaceObject.useShortcut)('core/block-editor/focus-toolbar', () => {
isToolbarForced.current = true;
stopTyping(true);
}, {
isDisabled: !canFocusHiddenToolbar
});
(0,external_wp_element_namespaceObject.useEffect)(() => {
isToolbarForced.current = false;
}); // Stores the active toolbar item index so the block toolbar can return focus
// to it when re-mounting.
const initialToolbarItemIndexRef = (0,external_wp_element_namespaceObject.useRef)();
const popoverProps = useBlockToolbarPopoverProps({
contentElement: __unstableContentRef === null || __unstableContentRef === void 0 ? void 0 : __unstableContentRef.current,
clientId
});
if (showEmptyBlockSideInserter) {
return (0,external_wp_element_namespaceObject.createElement)(block_popover, _extends({
clientId: capturingClientId || clientId,
__unstableCoverTarget: true,
bottomClientId: lastClientId,
className: classnames_default()('block-editor-block-list__block-side-inserter-popover', {
'is-insertion-point-visible': isInsertionPointVisible
}),
__unstablePopoverSlot: __unstablePopoverSlot,
__unstableContentRef: __unstableContentRef,
resize: false,
shift: false
}, popoverProps), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-list__empty-block-inserter"
}, (0,external_wp_element_namespaceObject.createElement)(inserter, {
position: "bottom right",
rootClientId: rootClientId,
clientId: clientId,
__experimentalIsQuick: true
})));
}
if (shouldShowBreadcrumb || shouldShowContextualToolbar) {
return (0,external_wp_element_namespaceObject.createElement)(block_popover, _extends({
clientId: capturingClientId || clientId,
bottomClientId: lastClientId,
className: classnames_default()('block-editor-block-list__block-popover', {
'is-insertion-point-visible': isInsertionPointVisible
}),
__unstablePopoverSlot: __unstablePopoverSlot,
__unstableContentRef: __unstableContentRef,
resize: false
}, popoverProps), shouldShowContextualToolbar && showContents && (0,external_wp_element_namespaceObject.createElement)(block_contextual_toolbar // If the toolbar is being shown because of being forced
// it should focus the toolbar right after the mount.
, {
focusOnMount: isToolbarForced.current,
__experimentalInitialIndex: initialToolbarItemIndexRef.current,
__experimentalOnIndexChange: index => {
initialToolbarItemIndexRef.current = index;
} // Resets the index whenever the active block changes so
// this is not persisted. See https://github.com/WordPress/gutenberg/pull/25760#issuecomment-717906169
,
key: clientId
}), shouldShowBreadcrumb && (0,external_wp_element_namespaceObject.createElement)(block_selection_button, {
clientId: clientId,
rootClientId: rootClientId
}));
}
return null;
}
function wrapperSelector(select) {
const {
getSelectedBlockClientId,
getFirstMultiSelectedBlockClientId,
getBlockRootClientId,
getBlock,
getBlockParents,
getSettings,
isNavigationMode: _isNavigationMode,
__experimentalGetBlockListSettingsForBlocks
} = select(store);
const clientId = getSelectedBlockClientId() || getFirstMultiSelectedBlockClientId();
if (!clientId) {
return;
}
const {
name,
attributes = {}
} = getBlock(clientId) || {};
const blockParentsClientIds = getBlockParents(clientId); // Get Block List Settings for all ancestors of the current Block clientId.
const parentBlockListSettings = __experimentalGetBlockListSettingsForBlocks(blockParentsClientIds); // Get the clientId of the topmost parent with the capture toolbars setting.
const capturingClientId = blockParentsClientIds.find(parentClientId => {
var _parentBlockListSetti;
return (_parentBlockListSetti = parentBlockListSettings[parentClientId]) === null || _parentBlockListSetti === void 0 ? void 0 : _parentBlockListSetti.__experimentalCaptureToolbars;
});
const settings = getSettings();
return {
clientId,
rootClientId: getBlockRootClientId(clientId),
name,
isDistractionFree: settings.isDistractionFree,
isNavigationMode: _isNavigationMode(),
isEmptyDefaultBlock: name && (0,external_wp_blocks_namespaceObject.isUnmodifiedDefaultBlock)({
name,
attributes
}),
capturingClientId
};
}
function WrappedBlockPopover(_ref2) {
let {
__unstablePopoverSlot,
__unstableContentRef
} = _ref2;
const selected = (0,external_wp_data_namespaceObject.useSelect)(wrapperSelector, []);
if (!selected) {
return null;
}
const {
clientId,
rootClientId,
name,
isEmptyDefaultBlock,
capturingClientId,
isDistractionFree,
isNavigationMode
} = selected;
if (!name) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(SelectedBlockPopover, {
clientId: clientId,
rootClientId: rootClientId,
isEmptyDefaultBlock: isEmptyDefaultBlock,
showContents: !isDistractionFree || isNavigationMode,
capturingClientId: capturingClientId,
__unstablePopoverSlot: __unstablePopoverSlot,
__unstableContentRef: __unstableContentRef
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-tools/back-compat.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function BlockToolsBackCompat(_ref) {
let {
children
} = _ref;
const openRef = (0,external_wp_element_namespaceObject.useContext)(insertion_point_InsertionPointOpenRef);
const isDisabled = (0,external_wp_element_namespaceObject.useContext)(external_wp_components_namespaceObject.Disabled.Context); // If context is set, `BlockTools` is a parent component.
if (openRef || isDisabled) {
return children;
}
external_wp_deprecated_default()('wp.components.Popover.Slot name="block-toolbar"', {
alternative: 'wp.blockEditor.BlockTools',
since: '5.8',
version: '6.3'
});
return (0,external_wp_element_namespaceObject.createElement)(InsertionPoint, {
__unstablePopoverSlot: "block-toolbar"
}, (0,external_wp_element_namespaceObject.createElement)(WrappedBlockPopover, {
__unstablePopoverSlot: "block-toolbar"
}), children);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inner-blocks/with-client-id.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const withClientId = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(WrappedComponent => props => {
const {
clientId
} = useBlockEditContext();
return (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, _extends({}, props, {
clientId: clientId
}));
}, 'withClientId');
/* harmony default export */ var with_client_id = (withClientId);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inner-blocks/button-block-appender.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
const button_block_appender_ButtonBlockAppender = _ref => {
let {
clientId,
showSeparator,
isFloating,
onAddBlock,
isToggle
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(button_block_appender, {
className: classnames_default()({
'block-list-appender__toggle': isToggle
}),
rootClientId: clientId,
showSeparator: showSeparator,
isFloating: isFloating,
onAddBlock: onAddBlock
});
};
/* harmony default export */ var inner_blocks_button_block_appender = (with_client_id(button_block_appender_ButtonBlockAppender));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inner-blocks/default-block-appender.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const default_block_appender_DefaultBlockAppender = _ref => {
let {
clientId
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(default_block_appender, {
rootClientId: clientId
});
};
/* harmony default export */ var inner_blocks_default_block_appender = ((0,external_wp_compose_namespaceObject.compose)([with_client_id, (0,external_wp_data_namespaceObject.withSelect)((select, _ref2) => {
let {
clientId
} = _ref2;
const {
getBlockOrder
} = select(store);
const blockClientIds = getBlockOrder(clientId);
return {
lastBlockClientId: blockClientIds[blockClientIds.length - 1]
};
})])(default_block_appender_DefaultBlockAppender));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inner-blocks/use-nested-settings-update.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/** @typedef {import('../../selectors').WPDirectInsertBlock } WPDirectInsertBlock */
const pendingSettingsUpdates = new WeakMap();
/**
* This hook is a side effect which updates the block-editor store when changes
* happen to inner block settings. The given props are transformed into a
* settings object, and if that is different from the current settings object in
* the block-editor store, then the store is updated with the new settings which
* came from props.
*
* @param {string} clientId The client ID of the block to update.
* @param {string[]} allowedBlocks An array of block names which are permitted
* in inner blocks.
* @param {?WPDirectInsertBlock} __experimentalDefaultBlock The default block to insert: [ blockName, { blockAttributes } ].
* @param {?Function|boolean} __experimentalDirectInsert If a default block should be inserted directly by the
* appender.
* @param {string} [templateLock] The template lock specified for the inner
* blocks component. (e.g. "all")
* @param {boolean} captureToolbars Whether or children toolbars should be shown
* in the inner blocks component rather than on
* the child block.
* @param {string} orientation The direction in which the block
* should face.
* @param {Object} layout The layout object for the block container.
*/
function useNestedSettingsUpdate(clientId, allowedBlocks, __experimentalDefaultBlock, __experimentalDirectInsert, templateLock, captureToolbars, orientation, layout) {
const {
updateBlockListSettings
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const registry = (0,external_wp_data_namespaceObject.useRegistry)();
const {
blockListSettings,
parentLock
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const rootClientId = select(store).getBlockRootClientId(clientId);
return {
blockListSettings: select(store).getBlockListSettings(clientId),
parentLock: select(store).getTemplateLock(rootClientId)
};
}, [clientId]); // Memoize as inner blocks implementors often pass a new array on every
// render.
const _allowedBlocks = (0,external_wp_element_namespaceObject.useMemo)(() => allowedBlocks, allowedBlocks);
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
const newSettings = {
allowedBlocks: _allowedBlocks,
templateLock: templateLock === undefined || parentLock === 'contentOnly' ? parentLock : templateLock
}; // These values are not defined for RN, so only include them if they
// are defined.
if (captureToolbars !== undefined) {
newSettings.__experimentalCaptureToolbars = captureToolbars;
} // Orientation depends on layout,
// ideally the separate orientation prop should be deprecated.
if (orientation !== undefined) {
newSettings.orientation = orientation;
} else {
const layoutType = getLayoutType(layout === null || layout === void 0 ? void 0 : layout.type);
newSettings.orientation = layoutType.getOrientation(layout);
}
if (__experimentalDefaultBlock !== undefined) {
newSettings.__experimentalDefaultBlock = __experimentalDefaultBlock;
}
if (__experimentalDirectInsert !== undefined) {
newSettings.__experimentalDirectInsert = __experimentalDirectInsert;
}
if (!external_wp_isShallowEqual_default()(blockListSettings, newSettings)) {
// Batch updates to block list settings to avoid triggering cascading renders
// for each container block included in a tree and optimize initial render.
// To avoid triggering updateBlockListSettings for each container block
// causing X re-renderings for X container blocks,
// we batch all the updatedBlockListSettings in a single "data" batch
// which results in a single re-render.
if (!pendingSettingsUpdates.get(registry)) {
pendingSettingsUpdates.set(registry, []);
}
pendingSettingsUpdates.get(registry).push([clientId, newSettings]);
window.queueMicrotask(() => {
var _pendingSettingsUpdat;
if ((_pendingSettingsUpdat = pendingSettingsUpdates.get(registry)) !== null && _pendingSettingsUpdat !== void 0 && _pendingSettingsUpdat.length) {
registry.batch(() => {
pendingSettingsUpdates.get(registry).forEach(args => {
updateBlockListSettings(...args);
});
pendingSettingsUpdates.set(registry, []);
});
}
});
}
}, [clientId, blockListSettings, _allowedBlocks, __experimentalDefaultBlock, __experimentalDirectInsert, templateLock, parentLock, captureToolbars, orientation, updateBlockListSettings, layout, registry]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inner-blocks/use-inner-block-template-sync.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* This hook makes sure that a block's inner blocks stay in sync with the given
* block "template". The template is a block hierarchy to which inner blocks must
* conform. If the blocks get "out of sync" with the template and the template
* is meant to be locked (e.g. templateLock = "all" or templateLock = "contentOnly"),
* then we replace the inner blocks with the correct value after synchronizing it with the template.
*
* @param {string} clientId The block client ID.
* @param {Object} template The template to match.
* @param {string} templateLock The template lock state for the inner blocks. For
* example, if the template lock is set to "all",
* then the inner blocks will stay in sync with the
* template. If not defined or set to false, then
* the inner blocks will not be synchronized with
* the given template.
* @param {boolean} templateInsertUpdatesSelection Whether or not to update the
* block-editor selection state when inner blocks
* are replaced after template synchronization.
*/
function useInnerBlockTemplateSync(clientId, template, templateLock, templateInsertUpdatesSelection) {
const {
getBlocks,
getSelectedBlocksInitialCaretPosition,
isBlockSelected
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const {
replaceInnerBlocks,
__unstableMarkNextChangeAsNotPersistent
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const {
innerBlocks
} = (0,external_wp_data_namespaceObject.useSelect)(select => ({
innerBlocks: select(store).getBlocks(clientId)
}), [clientId]); // Maintain a reference to the previous value so we can do a deep equality check.
const existingTemplate = (0,external_wp_element_namespaceObject.useRef)(null);
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
let isCancelled = false; // There's an implicit dependency between useInnerBlockTemplateSync and useNestedSettingsUpdate
// The former needs to happen after the latter and since the latter is using microtasks to batch updates (performance optimization),
// we need to schedule this one in a microtask as well.
// Example: If you remove queueMicrotask here, ctrl + click to insert quote block won't close the inserter.
window.queueMicrotask(() => {
if (isCancelled) {
return;
} // Only synchronize innerBlocks with template if innerBlocks are empty
// or a locking "all" or "contentOnly" exists directly on the block.
const currentInnerBlocks = getBlocks(clientId);
const shouldApplyTemplate = currentInnerBlocks.length === 0 || templateLock === 'all' || templateLock === 'contentOnly';
const hasTemplateChanged = !es6_default()(template, existingTemplate.current);
if (!shouldApplyTemplate || !hasTemplateChanged) {
return;
}
existingTemplate.current = template;
const nextBlocks = (0,external_wp_blocks_namespaceObject.synchronizeBlocksWithTemplate)(currentInnerBlocks, template);
if (!es6_default()(nextBlocks, currentInnerBlocks)) {
__unstableMarkNextChangeAsNotPersistent();
replaceInnerBlocks(clientId, nextBlocks, currentInnerBlocks.length === 0 && templateInsertUpdatesSelection && nextBlocks.length !== 0 && isBlockSelected(clientId), // This ensures the "initialPosition" doesn't change when applying the template
// If we're supposed to focus the block, we'll focus the first inner block
// otherwise, we won't apply any auto-focus.
// This ensures for instance that the focus stays in the inserter when inserting the "buttons" block.
getSelectedBlocksInitialCaretPosition());
}
});
return () => {
isCancelled = true;
};
}, [innerBlocks, template, templateLock, clientId]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inner-blocks/use-block-context.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Returns a context object for a given block.
*
* @param {string} clientId The block client ID.
*
* @return {Record<string,*>} Context value.
*/
function useBlockContext(clientId) {
return (0,external_wp_data_namespaceObject.useSelect)(select => {
const block = select(store).getBlock(clientId);
if (!block) {
return undefined;
}
const blockType = select(external_wp_blocks_namespaceObject.store).getBlockType(block.name);
if (!blockType) {
return undefined;
}
if (Object.keys(blockType.providesContext).length === 0) {
return undefined;
}
return Object.fromEntries(Object.entries(blockType.providesContext).map(_ref => {
let [contextName, attributeName] = _ref;
return [contextName, block.attributes[attributeName]];
}));
}, [clientId]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/use-on-block-drop/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/** @typedef {import('@wordpress/element').WPSyntheticEvent} WPSyntheticEvent */
/** @typedef {import('./types').WPDropOperation} WPDropOperation */
/**
* Retrieve the data for a block drop event.
*
* @param {WPSyntheticEvent} event The drop event.
*
* @return {Object} An object with block drag and drop data.
*/
function parseDropEvent(event) {
let result = {
srcRootClientId: null,
srcClientIds: null,
srcIndex: null,
type: null,
blocks: null
};
if (!event.dataTransfer) {
return result;
}
try {
result = Object.assign(result, JSON.parse(event.dataTransfer.getData('wp-blocks')));
} catch (err) {
return result;
}
return result;
}
/**
* A function that returns an event handler function for block drop events.
*
* @param {string} targetRootClientId The root client id where the block(s) will be inserted.
* @param {number} targetBlockIndex The index where the block(s) will be inserted.
* @param {Function} getBlockIndex A function that gets the index of a block.
* @param {Function} getClientIdsOfDescendants A function that gets the client ids of descendant blocks.
* @param {Function} moveBlocks A function that moves blocks.
* @param {Function} insertOrReplaceBlocks A function that inserts or replaces blocks.
* @param {Function} clearSelectedBlock A function that clears block selection.
* @return {Function} The event handler for a block drop event.
*/
function onBlockDrop(targetRootClientId, targetBlockIndex, getBlockIndex, getClientIdsOfDescendants, moveBlocks, insertOrReplaceBlocks, clearSelectedBlock) {
return event => {
const {
srcRootClientId: sourceRootClientId,
srcClientIds: sourceClientIds,
type: dropType,
blocks
} = parseDropEvent(event); // If the user is inserting a block.
if (dropType === 'inserter') {
clearSelectedBlock();
const blocksToInsert = blocks.map(block => (0,external_wp_blocks_namespaceObject.cloneBlock)(block));
insertOrReplaceBlocks(blocksToInsert, true, null);
} // If the user is moving a block.
if (dropType === 'block') {
const sourceBlockIndex = getBlockIndex(sourceClientIds[0]); // If the user is dropping to the same position, return early.
if (sourceRootClientId === targetRootClientId && sourceBlockIndex === targetBlockIndex) {
return;
} // If the user is attempting to drop a block within its own
// nested blocks, return early as this would create infinite
// recursion.
if (sourceClientIds.includes(targetRootClientId) || getClientIdsOfDescendants(sourceClientIds).some(id => id === targetRootClientId)) {
return;
}
const isAtSameLevel = sourceRootClientId === targetRootClientId;
const draggedBlockCount = sourceClientIds.length; // If the block is kept at the same level and moved downwards,
// subtract to take into account that the blocks being dragged
// were removed from the block list above the insertion point.
const insertIndex = isAtSameLevel && sourceBlockIndex < targetBlockIndex ? targetBlockIndex - draggedBlockCount : targetBlockIndex;
moveBlocks(sourceClientIds, sourceRootClientId, insertIndex);
}
};
}
/**
* A function that returns an event handler function for block-related file drop events.
*
* @param {string} targetRootClientId The root client id where the block(s) will be inserted.
* @param {number} targetBlockIndex The index where the block(s) will be inserted.
* @param {boolean} hasUploadPermissions Whether the user has upload permissions.
* @param {Function} updateBlockAttributes A function that updates a block's attributes.
* @param {Function} canInsertBlockType A function that returns checks whether a block type can be inserted.
* @param {Function} insertOrReplaceBlocks A function that inserts or replaces blocks.
*
* @return {Function} The event handler for a block-related file drop event.
*/
function onFilesDrop(targetRootClientId, targetBlockIndex, hasUploadPermissions, updateBlockAttributes, canInsertBlockType, insertOrReplaceBlocks) {
return files => {
if (!hasUploadPermissions) {
return;
}
const transformation = (0,external_wp_blocks_namespaceObject.findTransform)((0,external_wp_blocks_namespaceObject.getBlockTransforms)('from'), transform => transform.type === 'files' && canInsertBlockType(transform.blockName, targetRootClientId) && transform.isMatch(files));
if (transformation) {
const blocks = transformation.transform(files, updateBlockAttributes);
insertOrReplaceBlocks(blocks);
}
};
}
/**
* A function that returns an event handler function for block-related HTML drop events.
*
* @param {string} targetRootClientId The root client id where the block(s) will be inserted.
* @param {number} targetBlockIndex The index where the block(s) will be inserted.
* @param {Function} insertOrReplaceBlocks A function that inserts or replaces blocks.
*
* @return {Function} The event handler for a block-related HTML drop event.
*/
function onHTMLDrop(targetRootClientId, targetBlockIndex, insertOrReplaceBlocks) {
return HTML => {
const blocks = (0,external_wp_blocks_namespaceObject.pasteHandler)({
HTML,
mode: 'BLOCKS'
});
if (blocks.length) {
insertOrReplaceBlocks(blocks);
}
};
}
/**
* A React hook for handling block drop events.
*
* @param {string} targetRootClientId The root client id where the block(s) will be inserted.
* @param {number} targetBlockIndex The index where the block(s) will be inserted.
* @param {Object} options The optional options.
* @param {WPDropOperation} [options.operation] The type of operation to perform on drop. Could be `insert` or `replace` for now.
*
* @return {Function} A function to be passed to the onDrop handler.
*/
function useOnBlockDrop(targetRootClientId, targetBlockIndex) {
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
const {
operation = 'insert'
} = options;
const hasUploadPermissions = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).getSettings().mediaUpload, []);
const {
canInsertBlockType,
getBlockIndex,
getClientIdsOfDescendants,
getBlockOrder,
getBlocksByClientId
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const {
insertBlocks,
moveBlocksToPosition,
updateBlockAttributes,
clearSelectedBlock,
replaceBlocks,
removeBlocks
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const registry = (0,external_wp_data_namespaceObject.useRegistry)();
const insertOrReplaceBlocks = (0,external_wp_element_namespaceObject.useCallback)(function (blocks) {
let updateSelection = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
let initialPosition = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
if (operation === 'replace') {
const clientIds = getBlockOrder(targetRootClientId);
const clientId = clientIds[targetBlockIndex];
replaceBlocks(clientId, blocks, undefined, initialPosition);
} else {
insertBlocks(blocks, targetBlockIndex, targetRootClientId, updateSelection, initialPosition);
}
}, [operation, getBlockOrder, insertBlocks, replaceBlocks, targetBlockIndex, targetRootClientId]);
const moveBlocks = (0,external_wp_element_namespaceObject.useCallback)((sourceClientIds, sourceRootClientId, insertIndex) => {
if (operation === 'replace') {
const sourceBlocks = getBlocksByClientId(sourceClientIds);
const targetBlockClientIds = getBlockOrder(targetRootClientId);
const targetBlockClientId = targetBlockClientIds[targetBlockIndex];
registry.batch(() => {
// Remove the source blocks.
removeBlocks(sourceClientIds, false); // Replace the target block with the source blocks.
replaceBlocks(targetBlockClientId, sourceBlocks, undefined, 0);
});
} else {
moveBlocksToPosition(sourceClientIds, sourceRootClientId, targetRootClientId, insertIndex);
}
}, [operation, getBlockOrder, getBlocksByClientId, insertBlocks, moveBlocksToPosition, removeBlocks, targetBlockIndex, targetRootClientId]);
const _onDrop = onBlockDrop(targetRootClientId, targetBlockIndex, getBlockIndex, getClientIdsOfDescendants, moveBlocks, insertOrReplaceBlocks, clearSelectedBlock);
const _onFilesDrop = onFilesDrop(targetRootClientId, targetBlockIndex, hasUploadPermissions, updateBlockAttributes, canInsertBlockType, insertOrReplaceBlocks);
const _onHTMLDrop = onHTMLDrop(targetRootClientId, targetBlockIndex, insertOrReplaceBlocks);
return event => {
const files = (0,external_wp_dom_namespaceObject.getFilesFromDataTransfer)(event.dataTransfer);
const html = event.dataTransfer.getData('text/html');
/**
* From Windows Chrome 96, the `event.dataTransfer` returns both file object and HTML.
* The order of the checks is important to recognise the HTML drop.
*/
if (html) {
_onHTMLDrop(html);
} else if (files.length) {
_onFilesDrop(files);
} else {
_onDrop(event);
}
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/utils/math.js
/**
* A string representing the name of an edge.
*
* @typedef {'top'|'right'|'bottom'|'left'} WPEdgeName
*/
/**
* @typedef {Object} WPPoint
* @property {number} x The horizontal position.
* @property {number} y The vertical position.
*/
/**
* Given a point, a DOMRect and the name of an edge, returns the distance to
* that edge of the rect.
*
* This function works for edges that are horizontal or vertical (e.g. not
* rotated), the following terms are used so that the function works in both
* orientations:
*
* - Forward, meaning the axis running horizontally when an edge is vertical
* and vertically when an edge is horizontal.
* - Lateral, meaning the axis running vertically when an edge is vertical
* and horizontally when an edge is horizontal.
*
* @param {WPPoint} point The point to measure distance from.
* @param {DOMRect} rect A DOM Rect containing edge positions.
* @param {WPEdgeName} edge The edge to measure to.
*/
function getDistanceFromPointToEdge(point, rect, edge) {
const isHorizontal = edge === 'top' || edge === 'bottom';
const {
x,
y
} = point;
const pointLateralPosition = isHorizontal ? x : y;
const pointForwardPosition = isHorizontal ? y : x;
const edgeStart = isHorizontal ? rect.left : rect.top;
const edgeEnd = isHorizontal ? rect.right : rect.bottom;
const edgeForwardPosition = rect[edge]; // Measure the straight line distance to the edge of the rect, when the
// point is adjacent to the edge.
// Else, if the point is positioned diagonally to the edge of the rect,
// measure diagonally to the nearest corner that the edge meets.
let edgeLateralPosition;
if (pointLateralPosition >= edgeStart && pointLateralPosition <= edgeEnd) {
edgeLateralPosition = pointLateralPosition;
} else if (pointLateralPosition < edgeEnd) {
edgeLateralPosition = edgeStart;
} else {
edgeLateralPosition = edgeEnd;
}
return Math.sqrt((pointLateralPosition - edgeLateralPosition) ** 2 + (pointForwardPosition - edgeForwardPosition) ** 2);
}
/**
* Given a point, a DOMRect and a list of allowed edges returns the name of and
* distance to the nearest edge.
*
* @param {WPPoint} point The point to measure distance from.
* @param {DOMRect} rect A DOM Rect containing edge positions.
* @param {WPEdgeName[]} allowedEdges A list of the edges included in the
* calculation. Defaults to all edges.
*
* @return {[number, string]} An array where the first value is the distance
* and a second is the edge name.
*/
function getDistanceToNearestEdge(point, rect) {
let allowedEdges = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ['top', 'bottom', 'left', 'right'];
let candidateDistance;
let candidateEdge;
allowedEdges.forEach(edge => {
const distance = getDistanceFromPointToEdge(point, rect, edge);
if (candidateDistance === undefined || distance < candidateDistance) {
candidateDistance = distance;
candidateEdge = edge;
}
});
return [candidateDistance, candidateEdge];
}
/**
* Is the point contained by the rectangle.
*
* @param {WPPoint} point The point.
* @param {DOMRect} rect The rectangle.
*
* @return {boolean} True if the point is contained by the rectangle, false otherwise.
*/
function isPointContainedByRect(point, rect) {
return rect.left <= point.x && rect.right >= point.x && rect.top <= point.y && rect.bottom >= point.y;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/use-block-drop-zone/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/** @typedef {import('../../utils/math').WPPoint} WPPoint */
/** @typedef {import('../use-on-block-drop/types').WPDropOperation} WPDropOperation */
/**
* The orientation of a block list.
*
* @typedef {'horizontal'|'vertical'|undefined} WPBlockListOrientation
*/
/**
* The insert position when dropping a block.
*
* @typedef {'before'|'after'} WPInsertPosition
*/
/**
* @typedef {Object} WPBlockData
* @property {boolean} isUnmodifiedDefaultBlock Is the block unmodified default block.
* @property {() => DOMRect} getBoundingClientRect Get the bounding client rect of the block.
* @property {number} blockIndex The index of the block.
*/
/**
* Get the drop target position from a given drop point and the orientation.
*
* @param {WPBlockData[]} blocksData The block data list.
* @param {WPPoint} position The position of the item being dragged.
* @param {WPBlockListOrientation} orientation The orientation of the block list.
* @return {[number, WPDropOperation]} The drop target position.
*/
function getDropTargetPosition(blocksData, position) {
var _blocksData$nearestIn, _blocksData$adjacentI;
let orientation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'vertical';
const allowedEdges = orientation === 'horizontal' ? ['left', 'right'] : ['top', 'bottom'];
const isRightToLeft = (0,external_wp_i18n_namespaceObject.isRTL)();
let nearestIndex = 0;
let insertPosition = 'before';
let minDistance = Infinity;
blocksData.forEach(_ref => {
let {
isUnmodifiedDefaultBlock,
getBoundingClientRect,
blockIndex
} = _ref;
const rect = getBoundingClientRect();
let [distance, edge] = getDistanceToNearestEdge(position, rect, allowedEdges); // Prioritize the element if the point is inside of an unmodified default block.
if (isUnmodifiedDefaultBlock && isPointContainedByRect(position, rect)) {
distance = 0;
}
if (distance < minDistance) {
// Where the dropped block will be inserted on the nearest block.
insertPosition = edge === 'bottom' || !isRightToLeft && edge === 'right' || isRightToLeft && edge === 'left' ? 'after' : 'before'; // Update the currently known best candidate.
minDistance = distance;
nearestIndex = blockIndex;
}
});
const adjacentIndex = nearestIndex + (insertPosition === 'after' ? 1 : -1);
const isNearestBlockUnmodifiedDefaultBlock = !!((_blocksData$nearestIn = blocksData[nearestIndex]) !== null && _blocksData$nearestIn !== void 0 && _blocksData$nearestIn.isUnmodifiedDefaultBlock);
const isAdjacentBlockUnmodifiedDefaultBlock = !!((_blocksData$adjacentI = blocksData[adjacentIndex]) !== null && _blocksData$adjacentI !== void 0 && _blocksData$adjacentI.isUnmodifiedDefaultBlock); // If both blocks are not unmodified default blocks then just insert between them.
if (!isNearestBlockUnmodifiedDefaultBlock && !isAdjacentBlockUnmodifiedDefaultBlock) {
// If the user is dropping to the trailing edge of the block
// add 1 to the index to represent dragging after.
const insertionIndex = insertPosition === 'after' ? nearestIndex + 1 : nearestIndex;
return [insertionIndex, 'insert'];
} // Otherwise, replace the nearest unmodified default block.
return [isNearestBlockUnmodifiedDefaultBlock ? nearestIndex : adjacentIndex, 'replace'];
}
/**
* @typedef {Object} WPBlockDropZoneConfig
* @property {string} rootClientId The root client id for the block list.
*/
/**
* A React hook that can be used to make a block list handle drag and drop.
*
* @param {WPBlockDropZoneConfig} dropZoneConfig configuration data for the drop zone.
*/
function useBlockDropZone() {
let {
// An undefined value represents a top-level block. Default to an empty
// string for this so that `targetRootClientId` can be easily compared to
// values returned by the `getRootBlockClientId` selector, which also uses
// an empty string to represent top-level blocks.
rootClientId: targetRootClientId = ''
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const [dropTarget, setDropTarget] = (0,external_wp_element_namespaceObject.useState)({
index: null,
operation: 'insert'
});
const isDisabled = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getTemplateLock,
__unstableIsWithinBlockOverlay,
__unstableHasActiveBlockOverlayActive
} = select(store);
const templateLock = getTemplateLock(targetRootClientId);
return ['all', 'contentOnly'].some(lock => lock === templateLock) || __unstableHasActiveBlockOverlayActive(targetRootClientId) || __unstableIsWithinBlockOverlay(targetRootClientId);
}, [targetRootClientId]);
const {
getBlockListSettings,
getBlocks,
getBlockIndex
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const {
showInsertionPoint,
hideInsertionPoint
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const onBlockDrop = useOnBlockDrop(targetRootClientId, dropTarget.index, {
operation: dropTarget.operation
});
const throttled = (0,external_wp_compose_namespaceObject.useThrottle)((0,external_wp_element_namespaceObject.useCallback)((event, ownerDocument) => {
var _getBlockListSettings;
const blocks = getBlocks(targetRootClientId); // The block list is empty, don't show the insertion point but still allow dropping.
if (blocks.length === 0) {
setDropTarget({
index: 0,
operation: 'insert'
});
return;
}
const blocksData = blocks.map(block => {
const clientId = block.clientId;
return {
isUnmodifiedDefaultBlock: (0,external_wp_blocks_namespaceObject.isUnmodifiedDefaultBlock)(block),
getBoundingClientRect: () => ownerDocument.getElementById(`block-${clientId}`).getBoundingClientRect(),
blockIndex: getBlockIndex(clientId)
};
});
const [targetIndex, operation] = getDropTargetPosition(blocksData, {
x: event.clientX,
y: event.clientY
}, (_getBlockListSettings = getBlockListSettings(targetRootClientId)) === null || _getBlockListSettings === void 0 ? void 0 : _getBlockListSettings.orientation);
setDropTarget({
index: targetIndex,
operation
});
showInsertionPoint(targetRootClientId, targetIndex, {
operation
});
}, [targetRootClientId]), 200);
return (0,external_wp_compose_namespaceObject.__experimentalUseDropZone)({
isDisabled,
onDrop: onBlockDrop,
onDragOver(event) {
// `currentTarget` is only available while the event is being
// handled, so get it now and pass it to the thottled function.
// https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget
throttled(event, event.currentTarget.ownerDocument);
},
onDragLeave() {
throttled.cancel();
hideInsertionPoint();
},
onDragEnd() {
throttled.cancel();
hideInsertionPoint();
}
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inner-blocks/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const EMPTY_OBJECT = {};
/**
* InnerBlocks is a component which allows a single block to have multiple blocks
* as children. The UncontrolledInnerBlocks component is used whenever the inner
* blocks are not controlled by another entity. In other words, it is normally
* used for inner blocks in the post editor
*
* @param {Object} props The component props.
*/
function UncontrolledInnerBlocks(props) {
const {
clientId,
allowedBlocks,
__experimentalDefaultBlock,
__experimentalDirectInsert,
template,
templateLock,
wrapperRef,
templateInsertUpdatesSelection,
__experimentalCaptureToolbars: captureToolbars,
__experimentalAppenderTagName,
renderAppender,
orientation,
placeholder,
layout
} = props;
useNestedSettingsUpdate(clientId, allowedBlocks, __experimentalDefaultBlock, __experimentalDirectInsert, templateLock, captureToolbars, orientation, layout);
useInnerBlockTemplateSync(clientId, template, templateLock, templateInsertUpdatesSelection);
const context = useBlockContext(clientId);
const name = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _select$getBlock;
return (_select$getBlock = select(store).getBlock(clientId)) === null || _select$getBlock === void 0 ? void 0 : _select$getBlock.name;
}, [clientId]);
const defaultLayoutBlockSupport = (0,external_wp_blocks_namespaceObject.getBlockSupport)(name, '__experimentalLayout') || EMPTY_OBJECT;
const {
allowSizingOnChildren = false
} = defaultLayoutBlockSupport;
const defaultLayout = useSetting('layout') || EMPTY_OBJECT;
const usedLayout = layout || defaultLayoutBlockSupport;
const memoedLayout = (0,external_wp_element_namespaceObject.useMemo)(() => ({ // Default layout will know about any content/wide size defined by the theme.
...defaultLayout,
...usedLayout,
...(allowSizingOnChildren && {
allowSizingOnChildren: true
})
}), [defaultLayout, usedLayout, allowSizingOnChildren]); // This component needs to always be synchronous as it's the one changing
// the async mode depending on the block selection.
return (0,external_wp_element_namespaceObject.createElement)(BlockContextProvider, {
value: context
}, (0,external_wp_element_namespaceObject.createElement)(BlockListItems, {
rootClientId: clientId,
renderAppender: renderAppender,
__experimentalAppenderTagName: __experimentalAppenderTagName,
__experimentalLayout: memoedLayout,
wrapperRef: wrapperRef,
placeholder: placeholder
}));
}
/**
* The controlled inner blocks component wraps the uncontrolled inner blocks
* component with the blockSync hook. This keeps the innerBlocks of the block in
* the block-editor store in sync with the blocks of the controlling entity. An
* example of an inner block controller is a template part block, which provides
* its own blocks from the template part entity data source.
*
* @param {Object} props The component props.
*/
function ControlledInnerBlocks(props) {
useBlockSync(props);
return (0,external_wp_element_namespaceObject.createElement)(UncontrolledInnerBlocks, props);
}
const ForwardedInnerBlocks = (0,external_wp_element_namespaceObject.forwardRef)((props, ref) => {
const innerBlocksProps = useInnerBlocksProps({
ref
}, props);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inner-blocks"
}, (0,external_wp_element_namespaceObject.createElement)("div", innerBlocksProps));
});
/**
* This hook is used to lightly mark an element as an inner blocks wrapper
* element. Call this hook and pass the returned props to the element to mark as
* an inner blocks wrapper, automatically rendering inner blocks as children. If
* you define a ref for the element, it is important to pass the ref to this
* hook, which the hook in turn will pass to the component through the props it
* returns. Optionally, you can also pass any other props through this hook, and
* they will be merged and returned.
*
* @param {Object} props Optional. Props to pass to the element. Must contain
* the ref if one is defined.
* @param {Object} options Optional. Inner blocks options.
*
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/inner-blocks/README.md
*/
function useInnerBlocksProps() {
let props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const {
__unstableDisableLayoutClassNames,
__unstableDisableDropZone
} = options;
const {
clientId,
layout = null,
__unstableLayoutClassNames: layoutClassNames = ''
} = useBlockEditContext();
const isSmallScreen = (0,external_wp_compose_namespaceObject.useViewportMatch)('medium', '<');
const {
__experimentalCaptureToolbars,
hasOverlay
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
if (!clientId) {
return {};
}
const {
getBlockName,
isBlockSelected,
hasSelectedInnerBlock,
__unstableGetEditorMode
} = select(store);
const blockName = getBlockName(clientId);
const enableClickThrough = __unstableGetEditorMode() === 'navigation' || isSmallScreen;
return {
__experimentalCaptureToolbars: select(external_wp_blocks_namespaceObject.store).hasBlockSupport(blockName, '__experimentalExposeControlsToChildren', false),
hasOverlay: blockName !== 'core/template' && !isBlockSelected(clientId) && !hasSelectedInnerBlock(clientId, true) && enableClickThrough
};
}, [clientId, isSmallScreen]);
const blockDropZoneRef = useBlockDropZone({
rootClientId: clientId
});
const ref = (0,external_wp_compose_namespaceObject.useMergeRefs)([props.ref, __unstableDisableDropZone ? null : blockDropZoneRef]);
const innerBlocksProps = {
__experimentalCaptureToolbars,
layout,
...options
};
const InnerBlocks = innerBlocksProps.value && innerBlocksProps.onChange ? ControlledInnerBlocks : UncontrolledInnerBlocks;
return { ...props,
ref,
className: classnames_default()(props.className, 'block-editor-block-list__layout', __unstableDisableLayoutClassNames ? '' : layoutClassNames, {
'has-overlay': hasOverlay
}),
children: clientId ? (0,external_wp_element_namespaceObject.createElement)(InnerBlocks, _extends({}, innerBlocksProps, {
clientId: clientId
})) : (0,external_wp_element_namespaceObject.createElement)(BlockListItems, options)
};
}
useInnerBlocksProps.save = external_wp_blocks_namespaceObject.__unstableGetInnerBlocksProps; // Expose default appender placeholders as components.
ForwardedInnerBlocks.DefaultBlockAppender = inner_blocks_default_block_appender;
ForwardedInnerBlocks.ButtonBlockAppender = inner_blocks_button_block_appender;
ForwardedInnerBlocks.Content = () => useInnerBlocksProps.save().children;
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/inner-blocks/README.md
*/
/* harmony default export */ var inner_blocks = (ForwardedInnerBlocks);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-list/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const elementContext = (0,external_wp_element_namespaceObject.createContext)();
const block_list_IntersectionObserver = (0,external_wp_element_namespaceObject.createContext)();
const pendingBlockVisibilityUpdatesPerRegistry = new WeakMap();
function Root(_ref) {
let {
className,
...settings
} = _ref;
const [element, setElement] = (0,external_wp_element_namespaceObject.useState)();
const isLargeViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('medium');
const {
isOutlineMode,
isFocusMode,
editorMode
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getSettings,
__unstableGetEditorMode
} = select(store);
const {
outlineMode,
focusMode
} = getSettings();
return {
isOutlineMode: outlineMode,
isFocusMode: focusMode,
editorMode: __unstableGetEditorMode()
};
}, []);
const registry = (0,external_wp_data_namespaceObject.useRegistry)();
const {
setBlockVisibility
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const delayedBlockVisibilityUpdates = (0,external_wp_compose_namespaceObject.useDebounce)((0,external_wp_element_namespaceObject.useCallback)(() => {
const updates = {};
pendingBlockVisibilityUpdatesPerRegistry.get(registry).forEach(_ref2 => {
let [id, isIntersecting] = _ref2;
updates[id] = isIntersecting;
});
setBlockVisibility(updates);
}, [registry]), 300, {
trailing: true
});
const intersectionObserver = (0,external_wp_element_namespaceObject.useMemo)(() => {
const {
IntersectionObserver: Observer
} = window;
if (!Observer) {
return;
}
return new Observer(entries => {
if (!pendingBlockVisibilityUpdatesPerRegistry.get(registry)) {
pendingBlockVisibilityUpdatesPerRegistry.set(registry, []);
}
for (const entry of entries) {
const clientId = entry.target.getAttribute('data-block');
pendingBlockVisibilityUpdatesPerRegistry.get(registry).push([clientId, entry.isIntersecting]);
}
delayedBlockVisibilityUpdates();
});
}, []);
const innerBlocksProps = useInnerBlocksProps({
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([useBlockSelectionClearer(), useInBetweenInserter(), setElement]),
className: classnames_default()('is-root-container', className, {
'is-outline-mode': isOutlineMode,
'is-focus-mode': isFocusMode && isLargeViewport,
'is-navigate-mode': editorMode === 'navigation'
})
}, settings);
return (0,external_wp_element_namespaceObject.createElement)(elementContext.Provider, {
value: element
}, (0,external_wp_element_namespaceObject.createElement)(block_list_IntersectionObserver.Provider, {
value: intersectionObserver
}, (0,external_wp_element_namespaceObject.createElement)("div", innerBlocksProps)));
}
function BlockList(settings) {
usePreParsePatterns();
return (0,external_wp_element_namespaceObject.createElement)(BlockToolsBackCompat, null, (0,external_wp_element_namespaceObject.createElement)(Provider, {
value: DEFAULT_BLOCK_EDIT_CONTEXT
}, (0,external_wp_element_namespaceObject.createElement)(Root, settings)));
}
BlockList.__unstableElementContext = elementContext;
function Items(_ref3) {
let {
placeholder,
rootClientId,
renderAppender,
__experimentalAppenderTagName,
__experimentalLayout: layout = defaultLayout
} = _ref3;
const {
order,
selectedBlocks,
visibleBlocks
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlockOrder,
getSelectedBlockClientIds,
__unstableGetVisibleBlocks
} = select(store);
return {
order: getBlockOrder(rootClientId),
selectedBlocks: getSelectedBlockClientIds(),
visibleBlocks: __unstableGetVisibleBlocks()
};
}, [rootClientId]);
return (0,external_wp_element_namespaceObject.createElement)(LayoutProvider, {
value: layout
}, order.map(clientId => (0,external_wp_element_namespaceObject.createElement)(external_wp_data_namespaceObject.AsyncModeProvider, {
key: clientId,
value: // Only provide data asynchronously if the block is
// not visible and not selected.
!visibleBlocks.has(clientId) && !selectedBlocks.includes(clientId)
}, (0,external_wp_element_namespaceObject.createElement)(block, {
rootClientId: rootClientId,
clientId: clientId
}))), order.length < 1 && placeholder, (0,external_wp_element_namespaceObject.createElement)(block_list_appender, {
tagName: __experimentalAppenderTagName,
rootClientId: rootClientId,
renderAppender: renderAppender
}));
}
function BlockListItems(props) {
// This component needs to always be synchronous as it's the one changing
// the async mode depending on the block selection.
return (0,external_wp_element_namespaceObject.createElement)(external_wp_data_namespaceObject.AsyncModeProvider, {
value: false
}, (0,external_wp_element_namespaceObject.createElement)(Items, props));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/border-radius-control/utils.js
/**
* WordPress dependencies
*/
/**
* Gets the (non-undefined) item with the highest occurrence within an array
* Based in part on: https://stackoverflow.com/a/20762713
*
* Undefined values are always sorted to the end by `sort`, so this function
* returns the first element, to always prioritize real values over undefined
* values.
*
* See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#description
*
* @param {Array<any>} inputArray Array of items to check.
* @return {any} The item with the most occurrences.
*/
function utils_mode(inputArray) {
const arr = [...inputArray];
return arr.sort((a, b) => inputArray.filter(v => v === b).length - inputArray.filter(v => v === a).length).shift();
}
/**
* Returns the most common CSS unit from the current CSS unit selections.
*
* - If a single flat border radius is set, its unit will be used
* - If individual corner selections, the most common of those will be used
* - Failing any unit selections a default of 'px' is returned.
*
* @param {Object} selectedUnits Unit selections for flat radius & each corner.
* @return {string} Most common CSS unit from current selections. Default: `px`.
*/
function getAllUnit() {
let selectedUnits = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const {
flat,
...cornerUnits
} = selectedUnits;
return flat || utils_mode(Object.values(cornerUnits).filter(Boolean)) || 'px';
}
/**
* Gets the 'all' input value and unit from values data.
*
* @param {Object|string} values Radius values.
* @return {string} A value + unit for the 'all' input.
*/
function getAllValue() {
let values = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
/**
* Border radius support was originally a single pixel value.
*
* To maintain backwards compatibility treat this case as the all value.
*/
if (typeof values === 'string') {
return values;
}
const parsedQuantitiesAndUnits = Object.values(values).map(value => (0,external_wp_components_namespaceObject.__experimentalParseQuantityAndUnitFromRawValue)(value));
const allValues = parsedQuantitiesAndUnits.map(value => {
var _value$;
return (_value$ = value[0]) !== null && _value$ !== void 0 ? _value$ : '';
});
const allUnits = parsedQuantitiesAndUnits.map(value => value[1]);
const value = allValues.every(v => v === allValues[0]) ? allValues[0] : '';
const unit = utils_mode(allUnits);
const allValue = value === 0 || value ? `${value}${unit}` : undefined;
return allValue;
}
/**
* Checks to determine if values are mixed.
*
* @param {Object} values Radius values.
* @return {boolean} Whether values are mixed.
*/
function hasMixedValues() {
let values = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const allValue = getAllValue(values);
const isMixed = typeof values === 'string' ? false : isNaN(parseFloat(allValue));
return isMixed;
}
/**
* Checks to determine if values are defined.
*
* @param {Object} values Radius values.
* @return {boolean} Whether values are mixed.
*/
function hasDefinedValues(values) {
if (!values) {
return false;
} // A string value represents a shorthand value.
if (typeof values === 'string') {
return true;
} // An object represents longhand border radius values, if any are set
// flag values as being defined.
const filteredValues = Object.values(values).filter(value => {
return !!value || value === 0;
});
return !!filteredValues.length;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/border-radius-control/all-input-control.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function all_input_control_AllInputControl(_ref) {
let {
onChange,
selectedUnits,
setSelectedUnits,
values,
...props
} = _ref;
let allValue = getAllValue(values);
if (allValue === undefined) {
// If we don't have any value set the unit to any current selection
// or the most common unit from the individual radii values.
allValue = getAllUnit(selectedUnits);
}
const hasValues = hasDefinedValues(values);
const isMixed = hasValues && hasMixedValues(values);
const allPlaceholder = isMixed ? (0,external_wp_i18n_namespaceObject.__)('Mixed') : null; // Filter out CSS-unit-only values to prevent invalid styles.
const handleOnChange = next => {
const isNumeric = !isNaN(parseFloat(next));
const nextValue = isNumeric ? next : undefined;
onChange(nextValue);
}; // Store current unit selection for use as fallback for individual
// radii controls.
const handleOnUnitChange = unit => {
setSelectedUnits({
topLeft: unit,
topRight: unit,
bottomLeft: unit,
bottomRight: unit
});
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalUnitControl, _extends({}, props, {
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Border radius'),
disableUnits: isMixed,
isOnly: true,
value: allValue,
onChange: handleOnChange,
onUnitChange: handleOnUnitChange,
placeholder: allPlaceholder,
size: '__unstable-large'
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/border-radius-control/input-controls.js
/**
* WordPress dependencies
*/
const CORNERS = {
topLeft: (0,external_wp_i18n_namespaceObject.__)('Top left'),
topRight: (0,external_wp_i18n_namespaceObject.__)('Top right'),
bottomLeft: (0,external_wp_i18n_namespaceObject.__)('Bottom left'),
bottomRight: (0,external_wp_i18n_namespaceObject.__)('Bottom right')
};
function input_controls_BoxInputControls(_ref) {
let {
onChange,
selectedUnits,
setSelectedUnits,
values: valuesProp,
...props
} = _ref;
const createHandleOnChange = corner => next => {
if (!onChange) {
return;
} // Filter out CSS-unit-only values to prevent invalid styles.
const isNumeric = !isNaN(parseFloat(next));
const nextValue = isNumeric ? next : undefined;
onChange({ ...values,
[corner]: nextValue
});
};
const createHandleOnUnitChange = side => next => {
const newUnits = { ...selectedUnits
};
newUnits[side] = next;
setSelectedUnits(newUnits);
}; // For shorthand style & backwards compatibility, handle flat string value.
const values = typeof valuesProp !== 'string' ? valuesProp : {
topLeft: valuesProp,
topRight: valuesProp,
bottomLeft: valuesProp,
bottomRight: valuesProp
}; // Controls are wrapped in tooltips as visible labels aren't desired here.
// Tooltip rendering also requires the UnitControl to be wrapped. See:
// https://github.com/WordPress/gutenberg/pull/24966#issuecomment-685875026
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-border-radius-control__input-controls-wrapper"
}, Object.entries(CORNERS).map(_ref2 => {
let [corner, label] = _ref2;
const [parsedQuantity, parsedUnit] = (0,external_wp_components_namespaceObject.__experimentalParseQuantityAndUnitFromRawValue)(values[corner]);
const computedUnit = values[corner] ? parsedUnit : selectedUnits[corner] || selectedUnits.flat;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Tooltip, {
text: label,
position: "top",
key: corner
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-border-radius-control__tooltip-wrapper"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalUnitControl, _extends({}, props, {
"aria-label": label,
value: [parsedQuantity, computedUnit].join(''),
onChange: createHandleOnChange(corner),
onUnitChange: createHandleOnUnitChange(corner),
size: '__unstable-large'
}))));
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/border-radius-control/linked-button.js
/**
* WordPress dependencies
*/
function linked_button_LinkedButton(_ref) {
let {
isLinked,
...props
} = _ref;
const label = isLinked ? (0,external_wp_i18n_namespaceObject.__)('Unlink radii') : (0,external_wp_i18n_namespaceObject.__)('Link radii'); // TODO: Remove span after merging https://github.com/WordPress/gutenberg/pull/44198
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Tooltip, {
text: label
}, (0,external_wp_element_namespaceObject.createElement)("span", null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, _extends({}, props, {
className: "component-border-radius-control__linked-button",
isSmall: true,
icon: isLinked ? library_link : link_off,
iconSize: 24,
"aria-label": label
}))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/border-radius-control/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const border_radius_control_DEFAULT_VALUES = {
topLeft: undefined,
topRight: undefined,
bottomLeft: undefined,
bottomRight: undefined
};
const MIN_BORDER_RADIUS_VALUE = 0;
const MAX_BORDER_RADIUS_VALUES = {
px: 100,
em: 20,
rem: 20
};
/**
* Control to display border radius options.
*
* @param {Object} props Component props.
* @param {Function} props.onChange Callback to handle onChange.
* @param {Object} props.values Border radius values.
*
* @return {WPElement} Custom border radius control.
*/
function BorderRadiusControl(_ref) {
let {
onChange,
values
} = _ref;
const [isLinked, setIsLinked] = (0,external_wp_element_namespaceObject.useState)(!hasDefinedValues(values) || !hasMixedValues(values)); // Tracking selected units via internal state allows filtering of CSS unit
// only values from being saved while maintaining preexisting unit selection
// behaviour. Filtering CSS unit only values prevents invalid style values.
const [selectedUnits, setSelectedUnits] = (0,external_wp_element_namespaceObject.useState)({
flat: typeof values === 'string' ? (0,external_wp_components_namespaceObject.__experimentalParseQuantityAndUnitFromRawValue)(values)[1] : undefined,
topLeft: (0,external_wp_components_namespaceObject.__experimentalParseQuantityAndUnitFromRawValue)(values === null || values === void 0 ? void 0 : values.topLeft)[1],
topRight: (0,external_wp_components_namespaceObject.__experimentalParseQuantityAndUnitFromRawValue)(values === null || values === void 0 ? void 0 : values.topRight)[1],
bottomLeft: (0,external_wp_components_namespaceObject.__experimentalParseQuantityAndUnitFromRawValue)(values === null || values === void 0 ? void 0 : values.bottomLeft)[1],
bottomRight: (0,external_wp_components_namespaceObject.__experimentalParseQuantityAndUnitFromRawValue)(values === null || values === void 0 ? void 0 : values.bottomRight)[1]
});
const units = (0,external_wp_components_namespaceObject.__experimentalUseCustomUnits)({
availableUnits: useSetting('spacing.units') || ['px', 'em', 'rem']
});
const unit = getAllUnit(selectedUnits);
const unitConfig = units && units.find(item => item.value === unit);
const step = (unitConfig === null || unitConfig === void 0 ? void 0 : unitConfig.step) || 1;
const [allValue] = (0,external_wp_components_namespaceObject.__experimentalParseQuantityAndUnitFromRawValue)(getAllValue(values));
const toggleLinked = () => setIsLinked(!isLinked);
const handleSliderChange = next => {
onChange(next !== undefined ? `${next}${unit}` : undefined);
};
return (0,external_wp_element_namespaceObject.createElement)("fieldset", {
className: "components-border-radius-control"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.BaseControl.VisualLabel, {
as: "legend"
}, (0,external_wp_i18n_namespaceObject.__)('Radius')), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "components-border-radius-control__wrapper"
}, isLinked ? (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(all_input_control_AllInputControl, {
className: "components-border-radius-control__unit-control",
values: values,
min: MIN_BORDER_RADIUS_VALUE,
onChange: onChange,
selectedUnits: selectedUnits,
setSelectedUnits: setSelectedUnits,
units: units
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.RangeControl, {
label: (0,external_wp_i18n_namespaceObject.__)('Border radius'),
hideLabelFromVision: true,
className: "components-border-radius-control__range-control",
value: allValue !== null && allValue !== void 0 ? allValue : '',
min: MIN_BORDER_RADIUS_VALUE,
max: MAX_BORDER_RADIUS_VALUES[unit],
initialPosition: 0,
withInputField: false,
onChange: handleSliderChange,
step: step,
__nextHasNoMarginBottom: true
})) : (0,external_wp_element_namespaceObject.createElement)(input_controls_BoxInputControls, {
min: MIN_BORDER_RADIUS_VALUE,
onChange: onChange,
selectedUnits: selectedUnits,
setSelectedUnits: setSelectedUnits,
values: values || border_radius_control_DEFAULT_VALUES,
units: units
}), (0,external_wp_element_namespaceObject.createElement)(linked_button_LinkedButton, {
onClick: toggleLinked,
isLinked: isLinked
})));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/border-radius.js
/**
* Internal dependencies
*/
/**
* Inspector control panel containing the border radius related configuration.
*
* @param {Object} props Block properties.
*
* @return {WPElement} Border radius edit element.
*/
function BorderRadiusEdit(props) {
var _style$border;
const {
attributes: {
style
},
setAttributes
} = props;
const onChange = newRadius => {
const newStyle = utils_cleanEmptyObject({ ...style,
border: { ...(style === null || style === void 0 ? void 0 : style.border),
radius: newRadius
}
});
setAttributes({
style: newStyle
});
};
return (0,external_wp_element_namespaceObject.createElement)(BorderRadiusControl, {
values: style === null || style === void 0 ? void 0 : (_style$border = style.border) === null || _style$border === void 0 ? void 0 : _style$border.radius,
onChange: onChange
});
}
/**
* Checks if there is a current value in the border radius block support
* attributes.
*
* @param {Object} props Block props.
* @return {boolean} Whether or not the block has a border radius value set.
*/
function hasBorderRadiusValue(props) {
var _props$attributes$sty, _props$attributes$sty2;
const borderRadius = (_props$attributes$sty = props.attributes.style) === null || _props$attributes$sty === void 0 ? void 0 : (_props$attributes$sty2 = _props$attributes$sty.border) === null || _props$attributes$sty2 === void 0 ? void 0 : _props$attributes$sty2.radius;
if (typeof borderRadius === 'object') {
return Object.entries(borderRadius).some(Boolean);
}
return !!borderRadius;
}
/**
* Resets the border radius block support attributes. This can be used when
* disabling the border radius support controls for a block via a progressive
* discovery panel.
*
* @param {Object} props Block props.
* @param {Object} props.attributes Block's attributes.
* @param {Object} props.setAttributes Function to set block's attributes.
*/
function resetBorderRadius(_ref) {
let {
attributes = {},
setAttributes
} = _ref;
const {
style
} = attributes;
setAttributes({
style: removeBorderAttribute(style, 'radius')
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/colors/utils.js
/**
* External dependencies
*/
k([names, a11y]);
/**
* Provided an array of color objects as set by the theme or by the editor defaults,
* and the values of the defined color or custom color returns a color object describing the color.
*
* @param {Array} colors Array of color objects as set by the theme or by the editor defaults.
* @param {?string} definedColor A string containing the color slug.
* @param {?string} customColor A string containing the customColor value.
*
* @return {?Object} If definedColor is passed and the name is found in colors,
* the color object exactly as set by the theme or editor defaults is returned.
* Otherwise, an object that just sets the color is defined.
*/
const getColorObjectByAttributeValues = (colors, definedColor, customColor) => {
if (definedColor) {
const colorObj = colors === null || colors === void 0 ? void 0 : colors.find(color => color.slug === definedColor);
if (colorObj) {
return colorObj;
}
}
return {
color: customColor
};
};
/**
* Provided an array of color objects as set by the theme or by the editor defaults, and a color value returns the color object matching that value or undefined.
*
* @param {Array} colors Array of color objects as set by the theme or by the editor defaults.
* @param {?string} colorValue A string containing the color value.
*
* @return {?Object} Color object included in the colors array whose color property equals colorValue.
* Returns undefined if no color object matches this requirement.
*/
const getColorObjectByColorValue = (colors, colorValue) => {
return colors === null || colors === void 0 ? void 0 : colors.find(color => color.color === colorValue);
};
/**
* Returns a class based on the context a color is being used and its slug.
*
* @param {string} colorContextName Context/place where color is being used e.g: background, text etc...
* @param {string} colorSlug Slug of the color.
*
* @return {?string} String with the class corresponding to the color in the provided context.
* Returns undefined if either colorContextName or colorSlug are not provided.
*/
function getColorClassName(colorContextName, colorSlug) {
if (!colorContextName || !colorSlug) {
return undefined;
}
return `has-${(0,external_lodash_namespaceObject.kebabCase)(colorSlug)}-${colorContextName}`;
}
/**
* Given an array of color objects and a color value returns the color value of the most readable color in the array.
*
* @param {Array} colors Array of color objects as set by the theme or by the editor defaults.
* @param {?string} colorValue A string containing the color value.
*
* @return {string} String with the color value of the most readable color.
*/
function getMostReadableColor(colors, colorValue) {
const colordColor = w(colorValue);
const getColorContrast = _ref => {
let {
color
} = _ref;
return colordColor.contrast(color);
};
const maxContrast = Math.max(...colors.map(getColorContrast));
return colors.find(color => getColorContrast(color) === maxContrast).color;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/colors-gradients/use-multiple-origin-colors-and-gradients.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Retrieves color and gradient related settings.
*
* The arrays for colors and gradients are made up of color palettes from each
* origin i.e. "Core", "Theme", and "User".
*
* @return {Object} Color and gradient related settings.
*/
function useMultipleOriginColorsAndGradients() {
const colorGradientSettings = {
disableCustomColors: !useSetting('color.custom'),
disableCustomGradients: !useSetting('color.customGradient')
};
const customColors = useSetting('color.palette.custom');
const themeColors = useSetting('color.palette.theme');
const defaultColors = useSetting('color.palette.default');
const shouldDisplayDefaultColors = useSetting('color.defaultPalette');
colorGradientSettings.colors = (0,external_wp_element_namespaceObject.useMemo)(() => {
const result = [];
if (themeColors && themeColors.length) {
result.push({
name: (0,external_wp_i18n_namespaceObject._x)('Theme', 'Indicates this palette comes from the theme.'),
colors: themeColors
});
}
if (shouldDisplayDefaultColors && defaultColors && defaultColors.length) {
result.push({
name: (0,external_wp_i18n_namespaceObject._x)('Default', 'Indicates this palette comes from WordPress.'),
colors: defaultColors
});
}
if (customColors && customColors.length) {
result.push({
name: (0,external_wp_i18n_namespaceObject._x)('Custom', 'Indicates this palette comes from the theme.'),
colors: customColors
});
}
return result;
}, [defaultColors, themeColors, customColors]);
const customGradients = useSetting('color.gradients.custom');
const themeGradients = useSetting('color.gradients.theme');
const defaultGradients = useSetting('color.gradients.default');
const shouldDisplayDefaultGradients = useSetting('color.defaultGradients');
colorGradientSettings.gradients = (0,external_wp_element_namespaceObject.useMemo)(() => {
const result = [];
if (themeGradients && themeGradients.length) {
result.push({
name: (0,external_wp_i18n_namespaceObject._x)('Theme', 'Indicates this palette comes from the theme.'),
gradients: themeGradients
});
}
if (shouldDisplayDefaultGradients && defaultGradients && defaultGradients.length) {
result.push({
name: (0,external_wp_i18n_namespaceObject._x)('Default', 'Indicates this palette comes from WordPress.'),
gradients: defaultGradients
});
}
if (customGradients && customGradients.length) {
result.push({
name: (0,external_wp_i18n_namespaceObject._x)('Custom', 'Indicates this palette is created by the user.'),
gradients: customGradients
});
}
return result;
}, [customGradients, themeGradients, defaultGradients]);
return colorGradientSettings;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/border.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const border_BORDER_SUPPORT_KEY = '__experimentalBorder';
const borderSides = ['top', 'right', 'bottom', 'left'];
const hasBorderValue = props => {
const {
borderColor,
style
} = props.attributes;
return (0,external_wp_components_namespaceObject.__experimentalIsDefinedBorder)(style === null || style === void 0 ? void 0 : style.border) || !!borderColor;
}; // The border color, style, and width are omitted so they get undefined. The
// border radius is separate and must retain its selection.
const resetBorder = _ref => {
var _style$border;
let {
attributes = {},
setAttributes
} = _ref;
const {
style
} = attributes;
setAttributes({
borderColor: undefined,
style: { ...style,
border: utils_cleanEmptyObject({
radius: style === null || style === void 0 ? void 0 : (_style$border = style.border) === null || _style$border === void 0 ? void 0 : _style$border.radius
})
}
});
};
const resetBorderFilter = newAttributes => {
var _newAttributes$style, _newAttributes$style$;
return { ...newAttributes,
borderColor: undefined,
style: { ...newAttributes.style,
border: {
radius: (_newAttributes$style = newAttributes.style) === null || _newAttributes$style === void 0 ? void 0 : (_newAttributes$style$ = _newAttributes$style.border) === null || _newAttributes$style$ === void 0 ? void 0 : _newAttributes$style$.radius
}
}
};
};
const getColorByProperty = (colors, property, value) => {
let matchedColor;
colors.some(origin => origin.colors.some(color => {
if (color[property] === value) {
matchedColor = color;
return true;
}
return false;
}));
return matchedColor;
};
const getMultiOriginColor = _ref2 => {
let {
colors,
namedColor,
customColor
} = _ref2;
// Search each origin (default, theme, or user) for matching color by name.
if (namedColor) {
const colorObject = getColorByProperty(colors, 'slug', namedColor);
if (colorObject) {
return colorObject;
}
} // Skip if no custom color or matching named color.
if (!customColor) {
return {
color: undefined
};
} // Attempt to find color via custom color value or build new object.
const colorObject = getColorByProperty(colors, 'color', customColor);
return colorObject ? colorObject : {
color: customColor
};
};
const getBorderObject = (attributes, colors) => {
const {
borderColor,
style
} = attributes;
const {
border: borderStyles
} = style || {}; // If we have a named color for a flat border. Fetch that color object and
// apply that color's value to the color property within the style object.
if (borderColor) {
const {
color
} = getMultiOriginColor({
colors,
namedColor: borderColor
});
return color ? { ...borderStyles,
color
} : borderStyles;
} // Individual side border color slugs are stored within the border style
// object. If we don't have a border styles object we have nothing further
// to hydrate.
if (!borderStyles) {
return borderStyles;
} // If we have named colors for the individual side borders, retrieve their
// related color objects and apply the real color values to the split
// border objects.
const hydratedBorderStyles = { ...borderStyles
};
borderSides.forEach(side => {
var _hydratedBorderStyles;
const colorSlug = getColorSlugFromVariable((_hydratedBorderStyles = hydratedBorderStyles[side]) === null || _hydratedBorderStyles === void 0 ? void 0 : _hydratedBorderStyles.color);
if (colorSlug) {
const {
color
} = getMultiOriginColor({
colors,
namedColor: colorSlug
});
hydratedBorderStyles[side] = { ...hydratedBorderStyles[side],
color
};
}
});
return hydratedBorderStyles;
};
function getColorSlugFromVariable(value) {
const namedColor = /var:preset\|color\|(.+)/.exec(value);
if (namedColor && namedColor[1]) {
return namedColor[1];
}
return null;
}
function BorderPanel(props) {
const {
attributes,
clientId,
setAttributes
} = props;
const {
style
} = attributes;
const {
colors
} = useMultipleOriginColorsAndGradients();
const isSupported = border_hasBorderSupport(props.name);
const isColorSupported = useSetting('border.color') && border_hasBorderSupport(props.name, 'color');
const isRadiusSupported = useSetting('border.radius') && border_hasBorderSupport(props.name, 'radius');
const isStyleSupported = useSetting('border.style') && border_hasBorderSupport(props.name, 'style');
const isWidthSupported = useSetting('border.width') && border_hasBorderSupport(props.name, 'width');
const isDisabled = [!isColorSupported, !isRadiusSupported, !isStyleSupported, !isWidthSupported].every(Boolean);
if (isDisabled || !isSupported) {
return null;
}
const defaultBorderControls = (0,external_wp_blocks_namespaceObject.getBlockSupport)(props.name, [border_BORDER_SUPPORT_KEY, '__experimentalDefaultControls']);
const showBorderByDefault = (defaultBorderControls === null || defaultBorderControls === void 0 ? void 0 : defaultBorderControls.color) || (defaultBorderControls === null || defaultBorderControls === void 0 ? void 0 : defaultBorderControls.width);
const onBorderChange = newBorder => {
var _style$border2;
// Filter out named colors and apply them to appropriate block
// attributes so that CSS classes can be used to apply those colors.
// e.g. has-primary-border-top-color.
let newBorderStyles = { ...newBorder
};
let newBorderColor;
if ((0,external_wp_components_namespaceObject.__experimentalHasSplitBorders)(newBorder)) {
// For each side check if the side has a color value set
// If so, determine if it belongs to a named color, in which case
// we update the color property.
//
// This deliberately overwrites `newBorderStyles` to avoid mutating
// the passed object which causes problems otherwise.
newBorderStyles = {
top: { ...newBorder.top
},
right: { ...newBorder.right
},
bottom: { ...newBorder.bottom
},
left: { ...newBorder.left
}
};
borderSides.forEach(side => {
var _newBorder$side;
if ((_newBorder$side = newBorder[side]) !== null && _newBorder$side !== void 0 && _newBorder$side.color) {
var _newBorder$side2;
const colorObject = getMultiOriginColor({
colors,
customColor: (_newBorder$side2 = newBorder[side]) === null || _newBorder$side2 === void 0 ? void 0 : _newBorder$side2.color
});
if (colorObject.slug) {
newBorderStyles[side].color = `var:preset|color|${colorObject.slug}`;
}
}
});
} else if (newBorder !== null && newBorder !== void 0 && newBorder.color) {
// We have a flat border configuration. Apply named color slug to
// `borderColor` attribute and clear color style property if found.
const customColor = newBorder === null || newBorder === void 0 ? void 0 : newBorder.color;
const colorObject = getMultiOriginColor({
colors,
customColor
});
if (colorObject.slug) {
newBorderColor = colorObject.slug;
newBorderStyles.color = undefined;
}
} // Ensure previous border radius styles are maintained and clean
// overall result for empty objects or properties.
const newStyle = utils_cleanEmptyObject({ ...style,
border: {
radius: style === null || style === void 0 ? void 0 : (_style$border2 = style.border) === null || _style$border2 === void 0 ? void 0 : _style$border2.radius,
...newBorderStyles
}
});
setAttributes({
style: newStyle,
borderColor: newBorderColor
});
};
const hydratedBorder = getBorderObject(attributes, colors);
return (0,external_wp_element_namespaceObject.createElement)(inspector_controls, {
group: "border"
}, (isWidthSupported || isColorSupported) && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToolsPanelItem, {
hasValue: () => hasBorderValue(props),
label: (0,external_wp_i18n_namespaceObject.__)('Border'),
onDeselect: () => resetBorder(props),
isShownByDefault: showBorderByDefault,
resetAllFilter: resetBorderFilter,
panelId: clientId
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalBorderBoxControl, {
colors: colors,
enableAlpha: true,
enableStyle: isStyleSupported,
onChange: onBorderChange,
popoverOffset: 40,
popoverPlacement: "left-start",
size: "__unstable-large",
value: hydratedBorder,
__experimentalIsRenderedInSidebar: true
})), isRadiusSupported && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToolsPanelItem, {
hasValue: () => hasBorderRadiusValue(props),
label: (0,external_wp_i18n_namespaceObject.__)('Radius'),
onDeselect: () => resetBorderRadius(props),
isShownByDefault: defaultBorderControls === null || defaultBorderControls === void 0 ? void 0 : defaultBorderControls.radius,
resetAllFilter: newAttributes => {
var _newAttributes$style2;
return { ...newAttributes,
style: { ...newAttributes.style,
border: { ...((_newAttributes$style2 = newAttributes.style) === null || _newAttributes$style2 === void 0 ? void 0 : _newAttributes$style2.border),
radius: undefined
}
}
};
},
panelId: clientId
}, (0,external_wp_element_namespaceObject.createElement)(BorderRadiusEdit, props)));
}
/**
* Determine whether there is block support for border properties.
*
* @param {string} blockName Block name.
* @param {string} feature Border feature to check support for.
*
* @return {boolean} Whether there is support.
*/
function border_hasBorderSupport(blockName) {
let feature = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'any';
if (external_wp_element_namespaceObject.Platform.OS !== 'web') {
return false;
}
const support = (0,external_wp_blocks_namespaceObject.getBlockSupport)(blockName, border_BORDER_SUPPORT_KEY);
if (support === true) {
return true;
}
if (feature === 'any') {
return !!(support !== null && support !== void 0 && support.color || support !== null && support !== void 0 && support.radius || support !== null && support !== void 0 && support.width || support !== null && support !== void 0 && support.style);
}
return !!(support !== null && support !== void 0 && support[feature]);
}
/**
* Returns a new style object where the specified border attribute has been
* removed.
*
* @param {Object} style Styles from block attributes.
* @param {string} attribute The border style attribute to clear.
*
* @return {Object} Style object with the specified attribute removed.
*/
function removeBorderAttribute(style, attribute) {
return utils_cleanEmptyObject({ ...style,
border: { ...(style === null || style === void 0 ? void 0 : style.border),
[attribute]: undefined
}
});
}
/**
* Filters registered block settings, extending attributes to include
* `borderColor` if needed.
*
* @param {Object} settings Original block settings.
*
* @return {Object} Updated block settings.
*/
function addAttributes(settings) {
if (!border_hasBorderSupport(settings, 'color')) {
return settings;
} // Allow blocks to specify default value if needed.
if (settings.attributes.borderColor) {
return settings;
} // Add new borderColor attribute to block settings.
return { ...settings,
attributes: { ...settings.attributes,
borderColor: {
type: 'string'
}
}
};
}
/**
* Override props assigned to save component to inject border color.
*
* @param {Object} props Additional props applied to save element.
* @param {Object} blockType Block type definition.
* @param {Object} attributes Block's attributes.
*
* @return {Object} Filtered props to apply to save element.
*/
function border_addSaveProps(props, blockType, attributes) {
if (!border_hasBorderSupport(blockType, 'color') || shouldSkipSerialization(blockType, border_BORDER_SUPPORT_KEY, 'color')) {
return props;
}
const borderClasses = getBorderClasses(attributes);
const newClassName = classnames_default()(props.className, borderClasses); // If we are clearing the last of the previous classes in `className`
// set it to `undefined` to avoid rendering empty DOM attributes.
props.className = newClassName ? newClassName : undefined;
return props;
}
/**
* Generates a CSS class name consisting of all the applicable border color
* classes given the current block attributes.
*
* @param {Object} attributes Block's attributes.
*
* @return {string} CSS class name.
*/
function getBorderClasses(attributes) {
var _style$border3;
const {
borderColor,
style
} = attributes;
const borderColorClass = getColorClassName('border-color', borderColor);
return classnames_default()({
'has-border-color': borderColor || (style === null || style === void 0 ? void 0 : (_style$border3 = style.border) === null || _style$border3 === void 0 ? void 0 : _style$border3.color),
[borderColorClass]: !!borderColorClass
});
}
/**
* Filters the registered block settings to apply border color styles and
* classnames to the block edit wrapper.
*
* @param {Object} settings Original block settings.
*
* @return {Object} Filtered block settings.
*/
function addEditProps(settings) {
if (!border_hasBorderSupport(settings, 'color') || shouldSkipSerialization(settings, border_BORDER_SUPPORT_KEY, 'color')) {
return settings;
}
const existingGetEditWrapperProps = settings.getEditWrapperProps;
settings.getEditWrapperProps = attributes => {
let props = {};
if (existingGetEditWrapperProps) {
props = existingGetEditWrapperProps(attributes);
}
return border_addSaveProps(props, settings, attributes);
};
return settings;
}
/**
* This adds inline styles for color palette colors.
* Ideally, this is not needed and themes should load their palettes on the editor.
*
* @param {Function} BlockListBlock Original component.
*
* @return {Function} Wrapped component.
*/
const withBorderColorPaletteStyles = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(BlockListBlock => props => {
var _style$border4, _style$border4$top, _style$border5, _style$border5$right, _style$border6, _style$border6$bottom, _style$border7, _style$border7$left, _props$wrapperProps;
const {
name,
attributes
} = props;
const {
borderColor,
style
} = attributes;
const {
colors
} = useMultipleOriginColorsAndGradients();
if (!border_hasBorderSupport(name, 'color') || shouldSkipSerialization(name, border_BORDER_SUPPORT_KEY, 'color')) {
return (0,external_wp_element_namespaceObject.createElement)(BlockListBlock, props);
}
const {
color: borderColorValue
} = getMultiOriginColor({
colors,
namedColor: borderColor
});
const {
color: borderTopColor
} = getMultiOriginColor({
colors,
namedColor: getColorSlugFromVariable(style === null || style === void 0 ? void 0 : (_style$border4 = style.border) === null || _style$border4 === void 0 ? void 0 : (_style$border4$top = _style$border4.top) === null || _style$border4$top === void 0 ? void 0 : _style$border4$top.color)
});
const {
color: borderRightColor
} = getMultiOriginColor({
colors,
namedColor: getColorSlugFromVariable(style === null || style === void 0 ? void 0 : (_style$border5 = style.border) === null || _style$border5 === void 0 ? void 0 : (_style$border5$right = _style$border5.right) === null || _style$border5$right === void 0 ? void 0 : _style$border5$right.color)
});
const {
color: borderBottomColor
} = getMultiOriginColor({
colors,
namedColor: getColorSlugFromVariable(style === null || style === void 0 ? void 0 : (_style$border6 = style.border) === null || _style$border6 === void 0 ? void 0 : (_style$border6$bottom = _style$border6.bottom) === null || _style$border6$bottom === void 0 ? void 0 : _style$border6$bottom.color)
});
const {
color: borderLeftColor
} = getMultiOriginColor({
colors,
namedColor: getColorSlugFromVariable(style === null || style === void 0 ? void 0 : (_style$border7 = style.border) === null || _style$border7 === void 0 ? void 0 : (_style$border7$left = _style$border7.left) === null || _style$border7$left === void 0 ? void 0 : _style$border7$left.color)
});
const extraStyles = {
borderTopColor: borderTopColor || borderColorValue,
borderRightColor: borderRightColor || borderColorValue,
borderBottomColor: borderBottomColor || borderColorValue,
borderLeftColor: borderLeftColor || borderColorValue
};
let wrapperProps = props.wrapperProps;
wrapperProps = { ...props.wrapperProps,
style: { ...((_props$wrapperProps = props.wrapperProps) === null || _props$wrapperProps === void 0 ? void 0 : _props$wrapperProps.style),
...extraStyles
}
};
return (0,external_wp_element_namespaceObject.createElement)(BlockListBlock, _extends({}, props, {
wrapperProps: wrapperProps
}));
});
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'core/border/addAttributes', addAttributes);
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.getSaveContent.extraProps', 'core/border/addSaveProps', border_addSaveProps);
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'core/border/addEditProps', addEditProps);
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockListBlock', 'core/border/with-border-color-palette-styles', withBorderColorPaletteStyles);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/gradients/use-gradient.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function __experimentalGetGradientClass(gradientSlug) {
if (!gradientSlug) {
return undefined;
}
return `has-${gradientSlug}-gradient-background`;
}
/**
* Retrieves the gradient value per slug.
*
* @param {Array} gradients Gradient Palette
* @param {string} slug Gradient slug
*
* @return {string} Gradient value.
*/
function getGradientValueBySlug(gradients, slug) {
const gradient = gradients === null || gradients === void 0 ? void 0 : gradients.find(g => g.slug === slug);
return gradient && gradient.gradient;
}
function __experimentalGetGradientObjectByGradientValue(gradients, value) {
const gradient = gradients === null || gradients === void 0 ? void 0 : gradients.find(g => g.gradient === value);
return gradient;
}
/**
* Retrieves the gradient slug per slug.
*
* @param {Array} gradients Gradient Palette
* @param {string} value Gradient value
* @return {string} Gradient slug.
*/
function getGradientSlugByValue(gradients, value) {
const gradient = __experimentalGetGradientObjectByGradientValue(gradients, value);
return gradient && gradient.slug;
}
function __experimentalUseGradient() {
let {
gradientAttribute = 'gradient',
customGradientAttribute = 'customGradient'
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const {
clientId
} = useBlockEditContext();
const userGradientPalette = useSetting('color.gradients.custom');
const themeGradientPalette = useSetting('color.gradients.theme');
const defaultGradientPalette = useSetting('color.gradients.default');
const allGradients = (0,external_wp_element_namespaceObject.useMemo)(() => [...(userGradientPalette || []), ...(themeGradientPalette || []), ...(defaultGradientPalette || [])], [userGradientPalette, themeGradientPalette, defaultGradientPalette]);
const {
gradient,
customGradient
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlockAttributes
} = select(store);
const attributes = getBlockAttributes(clientId) || {};
return {
customGradient: attributes[customGradientAttribute],
gradient: attributes[gradientAttribute]
};
}, [clientId, gradientAttribute, customGradientAttribute]);
const {
updateBlockAttributes
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const setGradient = (0,external_wp_element_namespaceObject.useCallback)(newGradientValue => {
const slug = getGradientSlugByValue(allGradients, newGradientValue);
if (slug) {
updateBlockAttributes(clientId, {
[gradientAttribute]: slug,
[customGradientAttribute]: undefined
});
return;
}
updateBlockAttributes(clientId, {
[gradientAttribute]: undefined,
[customGradientAttribute]: newGradientValue
});
}, [allGradients, clientId, updateBlockAttributes]);
const gradientClass = __experimentalGetGradientClass(gradient);
let gradientValue;
if (gradient) {
gradientValue = getGradientValueBySlug(allGradients, gradient);
} else {
gradientValue = customGradient;
}
return {
gradientClass,
gradientValue,
setGradient
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/colors-gradients/control.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const colorsAndGradientKeys = ['colors', 'disableCustomColors', 'gradients', 'disableCustomGradients'];
const TAB_COLOR = {
name: 'color',
title: 'Solid',
value: 'color'
};
const TAB_GRADIENT = {
name: 'gradient',
title: 'Gradient',
value: 'gradient'
};
const TABS_SETTINGS = [TAB_COLOR, TAB_GRADIENT];
function ColorGradientControlInner(_ref) {
let {
colors,
gradients,
disableCustomColors,
disableCustomGradients,
__experimentalIsRenderedInSidebar,
className,
label,
onColorChange,
onGradientChange,
colorValue,
gradientValue,
clearable,
showTitle = true,
enableAlpha
} = _ref;
const canChooseAColor = onColorChange && (!(0,external_lodash_namespaceObject.isEmpty)(colors) || !disableCustomColors);
const canChooseAGradient = onGradientChange && (!(0,external_lodash_namespaceObject.isEmpty)(gradients) || !disableCustomGradients);
if (!canChooseAColor && !canChooseAGradient) {
return null;
}
const tabPanels = {
[TAB_COLOR.value]: (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ColorPalette, {
value: colorValue,
onChange: canChooseAGradient ? newColor => {
onColorChange(newColor);
onGradientChange();
} : onColorChange,
colors,
disableCustomColors,
__experimentalIsRenderedInSidebar: __experimentalIsRenderedInSidebar,
clearable: clearable,
enableAlpha: enableAlpha
}),
[TAB_GRADIENT.value]: (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.GradientPicker, {
__nextHasNoMargin: true,
value: gradientValue,
onChange: canChooseAColor ? newGradient => {
onGradientChange(newGradient);
onColorChange();
} : onGradientChange,
gradients,
disableCustomGradients,
__experimentalIsRenderedInSidebar: __experimentalIsRenderedInSidebar,
clearable: clearable
})
};
const renderPanelType = type => (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-color-gradient-control__panel"
}, tabPanels[type]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.BaseControl, {
__nextHasNoMarginBottom: true,
className: classnames_default()('block-editor-color-gradient-control', className)
}, (0,external_wp_element_namespaceObject.createElement)("fieldset", {
className: "block-editor-color-gradient-control__fieldset"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalVStack, {
spacing: 1
}, showTitle && (0,external_wp_element_namespaceObject.createElement)("legend", null, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-color-gradient-control__color-indicator"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.BaseControl.VisualLabel, null, label))), canChooseAColor && canChooseAGradient && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.TabPanel, {
className: "block-editor-color-gradient-control__tabs",
tabs: TABS_SETTINGS,
initialTabName: gradientValue ? TAB_GRADIENT.value : !!canChooseAColor && TAB_COLOR.value
}, tab => renderPanelType(tab.value)), !canChooseAGradient && renderPanelType(TAB_COLOR.value), !canChooseAColor && renderPanelType(TAB_GRADIENT.value))));
}
function ColorGradientControlSelect(props) {
const colorGradientSettings = {};
colorGradientSettings.colors = useSetting('color.palette');
colorGradientSettings.gradients = useSetting('color.gradients');
colorGradientSettings.disableCustomColors = !useSetting('color.custom');
colorGradientSettings.disableCustomGradients = !useSetting('color.customGradient');
return (0,external_wp_element_namespaceObject.createElement)(ColorGradientControlInner, _extends({}, colorGradientSettings, props));
}
function ColorGradientControl(props) {
if (colorsAndGradientKeys.every(key => props.hasOwnProperty(key))) {
return (0,external_wp_element_namespaceObject.createElement)(ColorGradientControlInner, props);
}
return (0,external_wp_element_namespaceObject.createElement)(ColorGradientControlSelect, props);
}
/* harmony default export */ var control = (ColorGradientControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/colors-gradients/dropdown.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
// When the `ColorGradientSettingsDropdown` controls are being rendered to a
// `ToolsPanel` they must be wrapped in a `ToolsPanelItem`.
const WithToolsPanelItem = _ref => {
let {
setting,
children,
panelId,
...props
} = _ref;
const clearValue = () => {
if (setting.colorValue) {
setting.onColorChange();
} else if (setting.gradientValue) {
setting.onGradientChange();
}
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToolsPanelItem, _extends({
hasValue: () => {
return !!setting.colorValue || !!setting.gradientValue;
},
label: setting.label,
onDeselect: clearValue,
isShownByDefault: setting.isShownByDefault !== undefined ? setting.isShownByDefault : true
}, props, {
className: "block-editor-tools-panel-color-gradient-settings__item",
panelId: panelId // Pass resetAllFilter if supplied due to rendering via SlotFill
// into parent ToolsPanel.
,
resetAllFilter: setting.resetAllFilter
}), children);
};
const LabeledColorIndicator = _ref2 => {
let {
colorValue,
label
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalHStack, {
justify: "flex-start"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ColorIndicator, {
className: "block-editor-panel-color-gradient-settings__color-indicator",
colorValue: colorValue
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexItem, {
className: "block-editor-panel-color-gradient-settings__color-name",
title: label
}, label));
}; // Renders a color dropdown's toggle as an `Item` if it is within an `ItemGroup`
// or as a `Button` if it isn't e.g. the controls are being rendered in
// a `ToolsPanel`.
const renderToggle = settings => _ref3 => {
let {
onToggle,
isOpen
} = _ref3;
const {
colorValue,
label
} = settings;
const toggleProps = {
onClick: onToggle,
className: classnames_default()('block-editor-panel-color-gradient-settings__dropdown', {
'is-open': isOpen
}),
'aria-expanded': isOpen
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, toggleProps, (0,external_wp_element_namespaceObject.createElement)(LabeledColorIndicator, {
colorValue: colorValue,
label: label
}));
}; // Renders a collection of color controls as dropdowns. Depending upon the
// context in which these dropdowns are being rendered, they may be wrapped
// in an `ItemGroup` with each dropdown's toggle as an `Item`, or alternatively,
// the may be individually wrapped in a `ToolsPanelItem` with the toggle as
// a regular `Button`.
//
// For more context see: https://github.com/WordPress/gutenberg/pull/40084
function ColorGradientSettingsDropdown(_ref4) {
let {
colors,
disableCustomColors,
disableCustomGradients,
enableAlpha,
gradients,
settings,
__experimentalIsRenderedInSidebar,
...props
} = _ref4;
let popoverProps;
if (__experimentalIsRenderedInSidebar) {
popoverProps = {
placement: 'left-start',
offset: 36,
shift: true
};
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, settings.map((setting, index) => {
var _setting$gradientValu;
const controlProps = {
clearable: false,
colorValue: setting.colorValue,
colors,
disableCustomColors,
disableCustomGradients,
enableAlpha,
gradientValue: setting.gradientValue,
gradients,
label: setting.label,
onColorChange: setting.onColorChange,
onGradientChange: setting.onGradientChange,
showTitle: false,
__experimentalIsRenderedInSidebar,
...setting
};
const toggleSettings = {
colorValue: (_setting$gradientValu = setting.gradientValue) !== null && _setting$gradientValu !== void 0 ? _setting$gradientValu : setting.colorValue,
label: setting.label
};
return setting && // If not in an `ItemGroup` wrap the dropdown in a
// `ToolsPanelItem`
(0,external_wp_element_namespaceObject.createElement)(WithToolsPanelItem, _extends({
key: index,
setting: setting
}, props), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Dropdown, {
popoverProps: popoverProps,
className: "block-editor-tools-panel-color-gradient-settings__dropdown",
renderToggle: renderToggle(toggleSettings),
renderContent: () => (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalDropdownContentWrapper, {
paddingSize: "none"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-panel-color-gradient-settings__dropdown-content"
}, (0,external_wp_element_namespaceObject.createElement)(control, controlProps)))
}));
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/contrast-checker/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
k([names, a11y]);
function ContrastChecker(_ref) {
let {
backgroundColor,
fallbackBackgroundColor,
fallbackTextColor,
fallbackLinkColor,
fontSize,
// Font size value in pixels.
isLargeText,
textColor,
linkColor,
enableAlphaChecker = false
} = _ref;
const currentBackgroundColor = backgroundColor || fallbackBackgroundColor; // Must have a background color.
if (!currentBackgroundColor) {
return null;
}
const currentTextColor = textColor || fallbackTextColor;
const currentLinkColor = linkColor || fallbackLinkColor; // Must have at least one text color.
if (!currentTextColor && !currentLinkColor) {
return null;
}
const textColors = [{
color: currentTextColor,
description: (0,external_wp_i18n_namespaceObject.__)('text color')
}, {
color: currentLinkColor,
description: (0,external_wp_i18n_namespaceObject.__)('link color')
}];
const colordBackgroundColor = w(currentBackgroundColor);
const backgroundColorHasTransparency = colordBackgroundColor.alpha() < 1;
const backgroundColorBrightness = colordBackgroundColor.brightness();
const isReadableOptions = {
level: 'AA',
size: isLargeText || isLargeText !== false && fontSize >= 24 ? 'large' : 'small'
};
let message = '';
let speakMessage = '';
for (const item of textColors) {
// If there is no color, go no further.
if (!item.color) {
continue;
}
const colordTextColor = w(item.color);
const isColordTextReadable = colordTextColor.isReadable(colordBackgroundColor, isReadableOptions);
const textHasTransparency = colordTextColor.alpha() < 1; // If the contrast is not readable.
if (!isColordTextReadable) {
// Don't show the message if the background or text is transparent.
if (backgroundColorHasTransparency || textHasTransparency) {
continue;
}
message = backgroundColorBrightness < colordTextColor.brightness() ? (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s is a type of text color, e.g., "text color" or "link color".
(0,external_wp_i18n_namespaceObject.__)('This color combination may be hard for people to read. Try using a darker background color and/or a brighter %s.'), item.description) : (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s is a type of text color, e.g., "text color" or "link color".
(0,external_wp_i18n_namespaceObject.__)('This color combination may be hard for people to read. Try using a brighter background color and/or a darker %s.'), item.description);
speakMessage = (0,external_wp_i18n_namespaceObject.__)('This color combination may be hard for people to read.'); // Break from the loop when we have a contrast warning.
// These messages take priority over the transparency warning.
break;
} // If there is no contrast warning and the text is transparent,
// show the transparent warning if alpha check is enabled.
if (textHasTransparency && enableAlphaChecker) {
message = (0,external_wp_i18n_namespaceObject.__)('Transparent text may be hard for people to read.');
speakMessage = (0,external_wp_i18n_namespaceObject.__)('Transparent text may be hard for people to read.');
}
}
if (!message) {
return null;
} // Note: The `Notice` component can speak messages via its `spokenMessage`
// prop, but the contrast checker requires granular control over when the
// announcements are made. Notably, the message will be re-announced if a
// new color combination is selected and the contrast is still insufficient.
(0,external_wp_a11y_namespaceObject.speak)(speakMessage);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-contrast-checker"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Notice, {
spokenMessage: null,
status: "warning",
isDismissible: false
}, message));
}
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/contrast-checker/README.md
*/
/* harmony default export */ var contrast_checker = (ContrastChecker);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/color-panel.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function getComputedStyle(node) {
return node.ownerDocument.defaultView.getComputedStyle(node);
}
function ColorPanel(_ref) {
let {
enableAlpha = false,
settings,
clientId,
enableContrastChecking = true
} = _ref;
const [detectedBackgroundColor, setDetectedBackgroundColor] = (0,external_wp_element_namespaceObject.useState)();
const [detectedColor, setDetectedColor] = (0,external_wp_element_namespaceObject.useState)();
const [detectedLinkColor, setDetectedLinkColor] = (0,external_wp_element_namespaceObject.useState)();
const ref = useBlockRef(clientId);
const definedColors = settings.filter(setting => setting === null || setting === void 0 ? void 0 : setting.colorValue);
(0,external_wp_element_namespaceObject.useEffect)(() => {
var _ref$current;
if (!enableContrastChecking) {
return;
}
if (!definedColors.length) {
if (detectedBackgroundColor) {
setDetectedBackgroundColor();
}
if (detectedColor) {
setDetectedColor();
}
if (detectedLinkColor) {
setDetectedColor();
}
return;
}
if (!ref.current) {
return;
}
setDetectedColor(getComputedStyle(ref.current).color);
const firstLinkElement = (_ref$current = ref.current) === null || _ref$current === void 0 ? void 0 : _ref$current.querySelector('a');
if (firstLinkElement && !!firstLinkElement.innerText) {
setDetectedLinkColor(getComputedStyle(firstLinkElement).color);
}
let backgroundColorNode = ref.current;
let backgroundColor = getComputedStyle(backgroundColorNode).backgroundColor;
while (backgroundColor === 'rgba(0, 0, 0, 0)' && backgroundColorNode.parentNode && backgroundColorNode.parentNode.nodeType === backgroundColorNode.parentNode.ELEMENT_NODE) {
backgroundColorNode = backgroundColorNode.parentNode;
backgroundColor = getComputedStyle(backgroundColorNode).backgroundColor;
}
setDetectedBackgroundColor(backgroundColor);
});
const colorGradientSettings = useMultipleOriginColorsAndGradients();
return (0,external_wp_element_namespaceObject.createElement)(inspector_controls, {
group: "color"
}, (0,external_wp_element_namespaceObject.createElement)(ColorGradientSettingsDropdown, _extends({
enableAlpha: enableAlpha,
panelId: clientId,
settings: settings,
__experimentalIsItemGroup: false,
__experimentalIsRenderedInSidebar: true
}, colorGradientSettings)), enableContrastChecking && (0,external_wp_element_namespaceObject.createElement)(contrast_checker, {
backgroundColor: detectedBackgroundColor,
textColor: detectedColor,
enableAlphaChecker: enableAlpha,
linkColor: detectedLinkColor
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/color.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const color_COLOR_SUPPORT_KEY = 'color';
const color_hasColorSupport = blockType => {
const colorSupport = (0,external_wp_blocks_namespaceObject.getBlockSupport)(blockType, color_COLOR_SUPPORT_KEY);
return colorSupport && (colorSupport.link === true || colorSupport.gradient === true || colorSupport.background !== false || colorSupport.text !== false);
};
const color_hasLinkColorSupport = blockType => {
if (external_wp_element_namespaceObject.Platform.OS !== 'web') {
return false;
}
const colorSupport = (0,external_wp_blocks_namespaceObject.getBlockSupport)(blockType, color_COLOR_SUPPORT_KEY);
return colorSupport !== null && typeof colorSupport === 'object' && !!colorSupport.link;
};
const color_hasGradientSupport = blockType => {
const colorSupport = (0,external_wp_blocks_namespaceObject.getBlockSupport)(blockType, color_COLOR_SUPPORT_KEY);
return colorSupport !== null && typeof colorSupport === 'object' && !!colorSupport.gradients;
};
const color_hasBackgroundColorSupport = blockType => {
const colorSupport = (0,external_wp_blocks_namespaceObject.getBlockSupport)(blockType, color_COLOR_SUPPORT_KEY);
return colorSupport && colorSupport.background !== false;
};
const color_hasTextColorSupport = blockType => {
const colorSupport = (0,external_wp_blocks_namespaceObject.getBlockSupport)(blockType, color_COLOR_SUPPORT_KEY);
return colorSupport && colorSupport.text !== false;
};
/**
* Clears a single color property from a style object.
*
* @param {Array} path Path to color property to clear within styles object.
* @param {Object} style Block attributes style object.
* @return {Object} Styles with the color property omitted.
*/
const clearColorFromStyles = (path, style) => utils_cleanEmptyObject(immutableSet(style, path, undefined));
/**
* Clears text color related properties from supplied attributes.
*
* @param {Object} attributes Block attributes.
* @return {Object} Update block attributes with text color properties omitted.
*/
const resetAllTextFilter = attributes => ({
textColor: undefined,
style: clearColorFromStyles(['color', 'text'], attributes.style)
});
/**
* Clears link color related properties from supplied attributes.
*
* @param {Object} attributes Block attributes.
* @return {Object} Update block attributes with link color properties omitted.
*/
const resetAllLinkFilter = attributes => ({
style: clearColorFromStyles(['elements', 'link', 'color', 'text'], attributes.style)
});
/**
* Clears all background color related properties including gradients from
* supplied block attributes.
*
* @param {Object} attributes Block attributes.
* @return {Object} Block attributes with background and gradient omitted.
*/
const clearBackgroundAndGradient = attributes => {
var _attributes$style;
return {
backgroundColor: undefined,
gradient: undefined,
style: { ...attributes.style,
color: { ...((_attributes$style = attributes.style) === null || _attributes$style === void 0 ? void 0 : _attributes$style.color),
background: undefined,
gradient: undefined
}
}
};
};
/**
* Filters registered block settings, extending attributes to include
* `backgroundColor` and `textColor` attribute.
*
* @param {Object} settings Original block settings.
*
* @return {Object} Filtered block settings.
*/
function color_addAttributes(settings) {
if (!color_hasColorSupport(settings)) {
return settings;
} // Allow blocks to specify their own attribute definition with default values if needed.
if (!settings.attributes.backgroundColor) {
Object.assign(settings.attributes, {
backgroundColor: {
type: 'string'
}
});
}
if (!settings.attributes.textColor) {
Object.assign(settings.attributes, {
textColor: {
type: 'string'
}
});
}
if (color_hasGradientSupport(settings) && !settings.attributes.gradient) {
Object.assign(settings.attributes, {
gradient: {
type: 'string'
}
});
}
return settings;
}
/**
* Override props assigned to save component to inject colors classnames.
*
* @param {Object} props Additional props applied to save element.
* @param {Object} blockType Block type.
* @param {Object} attributes Block attributes.
*
* @return {Object} Filtered props applied to save element.
*/
function color_addSaveProps(props, blockType, attributes) {
var _style$color, _style$color2, _style$color3, _style$color4, _style$elements, _style$elements$link;
if (!color_hasColorSupport(blockType) || shouldSkipSerialization(blockType, color_COLOR_SUPPORT_KEY)) {
return props;
}
const hasGradient = color_hasGradientSupport(blockType); // I'd have preferred to avoid the "style" attribute usage here
const {
backgroundColor,
textColor,
gradient,
style
} = attributes;
const shouldSerialize = feature => !shouldSkipSerialization(blockType, color_COLOR_SUPPORT_KEY, feature); // Primary color classes must come before the `has-text-color`,
// `has-background` and `has-link-color` classes to maintain backwards
// compatibility and avoid block invalidations.
const textClass = shouldSerialize('text') ? getColorClassName('color', textColor) : undefined;
const gradientClass = shouldSerialize('gradients') ? __experimentalGetGradientClass(gradient) : undefined;
const backgroundClass = shouldSerialize('background') ? getColorClassName('background-color', backgroundColor) : undefined;
const serializeHasBackground = shouldSerialize('background') || shouldSerialize('gradients');
const hasBackground = backgroundColor || (style === null || style === void 0 ? void 0 : (_style$color = style.color) === null || _style$color === void 0 ? void 0 : _style$color.background) || hasGradient && (gradient || (style === null || style === void 0 ? void 0 : (_style$color2 = style.color) === null || _style$color2 === void 0 ? void 0 : _style$color2.gradient));
const newClassName = classnames_default()(props.className, textClass, gradientClass, {
// Don't apply the background class if there's a custom gradient.
[backgroundClass]: (!hasGradient || !(style !== null && style !== void 0 && (_style$color3 = style.color) !== null && _style$color3 !== void 0 && _style$color3.gradient)) && !!backgroundClass,
'has-text-color': shouldSerialize('text') && (textColor || (style === null || style === void 0 ? void 0 : (_style$color4 = style.color) === null || _style$color4 === void 0 ? void 0 : _style$color4.text)),
'has-background': serializeHasBackground && hasBackground,
'has-link-color': shouldSerialize('link') && (style === null || style === void 0 ? void 0 : (_style$elements = style.elements) === null || _style$elements === void 0 ? void 0 : (_style$elements$link = _style$elements.link) === null || _style$elements$link === void 0 ? void 0 : _style$elements$link.color)
});
props.className = newClassName ? newClassName : undefined;
return props;
}
/**
* Filters registered block settings to extend the block edit wrapper
* to apply the desired styles and classnames properly.
*
* @param {Object} settings Original block settings.
*
* @return {Object} Filtered block settings.
*/
function color_addEditProps(settings) {
if (!color_hasColorSupport(settings) || shouldSkipSerialization(settings, color_COLOR_SUPPORT_KEY)) {
return settings;
}
const existingGetEditWrapperProps = settings.getEditWrapperProps;
settings.getEditWrapperProps = attributes => {
let props = {};
if (existingGetEditWrapperProps) {
props = existingGetEditWrapperProps(attributes);
}
return color_addSaveProps(props, settings, attributes);
};
return settings;
}
const getLinkColorFromAttributeValue = (colors, value) => {
const attributeParsed = /var:preset\|color\|(.+)/.exec(value);
if (attributeParsed && attributeParsed[1]) {
return getColorObjectByAttributeValues(colors, attributeParsed[1]).color;
}
return value;
};
/**
* Inspector control panel containing the color related configuration
*
* @param {Object} props
*
* @return {WPElement} Color edit element.
*/
function ColorEdit(props) {
var _style$color6, _style$color7, _style$color8, _style$elements2, _style$elements2$link, _style$elements2$link2;
const {
name: blockName,
attributes
} = props; // Some color settings have a special handling for deprecated flags in `useSetting`,
// so we can't unwrap them by doing const { ... } = useSetting('color')
// until https://github.com/WordPress/gutenberg/issues/37094 is fixed.
const userPalette = useSetting('color.palette.custom');
const themePalette = useSetting('color.palette.theme');
const defaultPalette = useSetting('color.palette.default');
const allSolids = (0,external_wp_element_namespaceObject.useMemo)(() => [...(userPalette || []), ...(themePalette || []), ...(defaultPalette || [])], [userPalette, themePalette, defaultPalette]);
const userGradientPalette = useSetting('color.gradients.custom');
const themeGradientPalette = useSetting('color.gradients.theme');
const defaultGradientPalette = useSetting('color.gradients.default');
const allGradients = (0,external_wp_element_namespaceObject.useMemo)(() => [...(userGradientPalette || []), ...(themeGradientPalette || []), ...(defaultGradientPalette || [])], [userGradientPalette, themeGradientPalette, defaultGradientPalette]);
const areCustomSolidsEnabled = useSetting('color.custom');
const areCustomGradientsEnabled = useSetting('color.customGradient');
const isBackgroundEnabled = useSetting('color.background');
const isLinkEnabled = useSetting('color.link');
const isTextEnabled = useSetting('color.text');
const solidsEnabled = areCustomSolidsEnabled || !themePalette || (themePalette === null || themePalette === void 0 ? void 0 : themePalette.length) > 0;
const gradientsEnabled = areCustomGradientsEnabled || !themeGradientPalette || (themeGradientPalette === null || themeGradientPalette === void 0 ? void 0 : themeGradientPalette.length) > 0; // Shouldn't be needed but right now the ColorGradientsPanel
// can trigger both onChangeColor and onChangeBackground
// synchronously causing our two callbacks to override changes
// from each other.
const localAttributes = (0,external_wp_element_namespaceObject.useRef)(attributes);
(0,external_wp_element_namespaceObject.useEffect)(() => {
localAttributes.current = attributes;
}, [attributes]);
if (!color_hasColorSupport(blockName)) {
return null;
}
const hasLinkColor = color_hasLinkColorSupport(blockName) && isLinkEnabled && solidsEnabled;
const hasTextColor = color_hasTextColorSupport(blockName) && isTextEnabled && solidsEnabled;
const hasBackgroundColor = color_hasBackgroundColorSupport(blockName) && isBackgroundEnabled && solidsEnabled;
const hasGradientColor = color_hasGradientSupport(blockName) && gradientsEnabled;
if (!hasLinkColor && !hasTextColor && !hasBackgroundColor && !hasGradientColor) {
return null;
}
const {
style,
textColor,
backgroundColor,
gradient
} = attributes;
let gradientValue;
if (hasGradientColor && gradient) {
gradientValue = getGradientValueBySlug(allGradients, gradient);
} else if (hasGradientColor) {
var _style$color5;
gradientValue = style === null || style === void 0 ? void 0 : (_style$color5 = style.color) === null || _style$color5 === void 0 ? void 0 : _style$color5.gradient;
}
const onChangeColor = name => value => {
var _localAttributes$curr, _localAttributes$curr2;
const colorObject = getColorObjectByColorValue(allSolids, value);
const attributeName = name + 'Color';
const newStyle = { ...localAttributes.current.style,
color: { ...((_localAttributes$curr = localAttributes.current) === null || _localAttributes$curr === void 0 ? void 0 : (_localAttributes$curr2 = _localAttributes$curr.style) === null || _localAttributes$curr2 === void 0 ? void 0 : _localAttributes$curr2.color),
[name]: colorObject !== null && colorObject !== void 0 && colorObject.slug ? undefined : value
}
};
const newNamedColor = colorObject !== null && colorObject !== void 0 && colorObject.slug ? colorObject.slug : undefined;
const newAttributes = {
style: utils_cleanEmptyObject(newStyle),
[attributeName]: newNamedColor
};
props.setAttributes(newAttributes);
localAttributes.current = { ...localAttributes.current,
...newAttributes
};
};
const onChangeGradient = value => {
const slug = getGradientSlugByValue(allGradients, value);
let newAttributes;
if (slug) {
var _localAttributes$curr3, _localAttributes$curr4, _localAttributes$curr5;
const newStyle = { ...((_localAttributes$curr3 = localAttributes.current) === null || _localAttributes$curr3 === void 0 ? void 0 : _localAttributes$curr3.style),
color: { ...((_localAttributes$curr4 = localAttributes.current) === null || _localAttributes$curr4 === void 0 ? void 0 : (_localAttributes$curr5 = _localAttributes$curr4.style) === null || _localAttributes$curr5 === void 0 ? void 0 : _localAttributes$curr5.color),
gradient: undefined
}
};
newAttributes = {
style: utils_cleanEmptyObject(newStyle),
gradient: slug
};
} else {
var _localAttributes$curr6, _localAttributes$curr7, _localAttributes$curr8;
const newStyle = { ...((_localAttributes$curr6 = localAttributes.current) === null || _localAttributes$curr6 === void 0 ? void 0 : _localAttributes$curr6.style),
color: { ...((_localAttributes$curr7 = localAttributes.current) === null || _localAttributes$curr7 === void 0 ? void 0 : (_localAttributes$curr8 = _localAttributes$curr7.style) === null || _localAttributes$curr8 === void 0 ? void 0 : _localAttributes$curr8.color),
gradient: value
}
};
newAttributes = {
style: utils_cleanEmptyObject(newStyle),
gradient: undefined
};
}
props.setAttributes(newAttributes);
localAttributes.current = { ...localAttributes.current,
...newAttributes
};
};
const onChangeLinkColor = value => {
var _localAttributes$curr9;
const colorObject = getColorObjectByColorValue(allSolids, value);
const newLinkColorValue = colorObject !== null && colorObject !== void 0 && colorObject.slug ? `var:preset|color|${colorObject.slug}` : value;
const newStyle = utils_cleanEmptyObject(immutableSet((_localAttributes$curr9 = localAttributes.current) === null || _localAttributes$curr9 === void 0 ? void 0 : _localAttributes$curr9.style, ['elements', 'link', 'color', 'text'], newLinkColorValue));
props.setAttributes({
style: newStyle
});
localAttributes.current = { ...localAttributes.current,
...{
style: newStyle
}
};
};
const defaultColorControls = (0,external_wp_blocks_namespaceObject.getBlockSupport)(props.name, [color_COLOR_SUPPORT_KEY, '__experimentalDefaultControls']);
const enableContrastChecking = external_wp_element_namespaceObject.Platform.OS === 'web' && !gradient && !(style !== null && style !== void 0 && (_style$color6 = style.color) !== null && _style$color6 !== void 0 && _style$color6.gradient) && hasBackgroundColor && (hasLinkColor || hasTextColor) && // Contrast checking is enabled by default.
// Deactivating it requires `enableContrastChecker` to have
// an explicit value of `false`.
false !== (0,external_wp_blocks_namespaceObject.getBlockSupport)(props.name, [color_COLOR_SUPPORT_KEY, 'enableContrastChecker']);
return (0,external_wp_element_namespaceObject.createElement)(ColorPanel, {
enableContrastChecking: enableContrastChecking,
clientId: props.clientId,
enableAlpha: true,
settings: [...(hasTextColor ? [{
label: (0,external_wp_i18n_namespaceObject.__)('Text'),
onColorChange: onChangeColor('text'),
colorValue: getColorObjectByAttributeValues(allSolids, textColor, style === null || style === void 0 ? void 0 : (_style$color7 = style.color) === null || _style$color7 === void 0 ? void 0 : _style$color7.text).color,
isShownByDefault: defaultColorControls === null || defaultColorControls === void 0 ? void 0 : defaultColorControls.text,
resetAllFilter: resetAllTextFilter
}] : []), ...(hasBackgroundColor || hasGradientColor ? [{
label: (0,external_wp_i18n_namespaceObject.__)('Background'),
onColorChange: hasBackgroundColor ? onChangeColor('background') : undefined,
colorValue: getColorObjectByAttributeValues(allSolids, backgroundColor, style === null || style === void 0 ? void 0 : (_style$color8 = style.color) === null || _style$color8 === void 0 ? void 0 : _style$color8.background).color,
gradientValue,
onGradientChange: hasGradientColor ? onChangeGradient : undefined,
isShownByDefault: defaultColorControls === null || defaultColorControls === void 0 ? void 0 : defaultColorControls.background,
resetAllFilter: clearBackgroundAndGradient
}] : []), ...(hasLinkColor ? [{
label: (0,external_wp_i18n_namespaceObject.__)('Link'),
onColorChange: onChangeLinkColor,
colorValue: getLinkColorFromAttributeValue(allSolids, style === null || style === void 0 ? void 0 : (_style$elements2 = style.elements) === null || _style$elements2 === void 0 ? void 0 : (_style$elements2$link = _style$elements2.link) === null || _style$elements2$link === void 0 ? void 0 : (_style$elements2$link2 = _style$elements2$link.color) === null || _style$elements2$link2 === void 0 ? void 0 : _style$elements2$link2.text),
isShownByDefault: defaultColorControls === null || defaultColorControls === void 0 ? void 0 : defaultColorControls.link,
resetAllFilter: resetAllLinkFilter
}] : [])]
});
}
/**
* This adds inline styles for color palette colors.
* Ideally, this is not needed and themes should load their palettes on the editor.
*
* @param {Function} BlockListBlock Original component.
*
* @return {Function} Wrapped component.
*/
const withColorPaletteStyles = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(BlockListBlock => props => {
var _props$wrapperProps;
const {
name,
attributes
} = props;
const {
backgroundColor,
textColor
} = attributes;
const userPalette = useSetting('color.palette.custom');
const themePalette = useSetting('color.palette.theme');
const defaultPalette = useSetting('color.palette.default');
const colors = (0,external_wp_element_namespaceObject.useMemo)(() => [...(userPalette || []), ...(themePalette || []), ...(defaultPalette || [])], [userPalette, themePalette, defaultPalette]);
if (!color_hasColorSupport(name) || shouldSkipSerialization(name, color_COLOR_SUPPORT_KEY)) {
return (0,external_wp_element_namespaceObject.createElement)(BlockListBlock, props);
}
const extraStyles = {};
if (textColor && !shouldSkipSerialization(name, color_COLOR_SUPPORT_KEY, 'text')) {
var _getColorObjectByAttr;
extraStyles.color = (_getColorObjectByAttr = getColorObjectByAttributeValues(colors, textColor)) === null || _getColorObjectByAttr === void 0 ? void 0 : _getColorObjectByAttr.color;
}
if (backgroundColor && !shouldSkipSerialization(name, color_COLOR_SUPPORT_KEY, 'background')) {
var _getColorObjectByAttr2;
extraStyles.backgroundColor = (_getColorObjectByAttr2 = getColorObjectByAttributeValues(colors, backgroundColor)) === null || _getColorObjectByAttr2 === void 0 ? void 0 : _getColorObjectByAttr2.color;
}
let wrapperProps = props.wrapperProps;
wrapperProps = { ...props.wrapperProps,
style: { ...extraStyles,
...((_props$wrapperProps = props.wrapperProps) === null || _props$wrapperProps === void 0 ? void 0 : _props$wrapperProps.style)
}
};
return (0,external_wp_element_namespaceObject.createElement)(BlockListBlock, _extends({}, props, {
wrapperProps: wrapperProps
}));
});
const MIGRATION_PATHS = {
linkColor: [['style', 'elements', 'link', 'color', 'text']],
textColor: [['textColor'], ['style', 'color', 'text']],
backgroundColor: [['backgroundColor'], ['style', 'color', 'background']],
gradient: [['gradient'], ['style', 'color', 'gradient']]
};
function color_addTransforms(result, source, index, results) {
const destinationBlockType = result.name;
const activeSupports = {
linkColor: color_hasLinkColorSupport(destinationBlockType),
textColor: color_hasTextColorSupport(destinationBlockType),
backgroundColor: color_hasBackgroundColorSupport(destinationBlockType),
gradient: color_hasGradientSupport(destinationBlockType)
};
return transformStyles(activeSupports, MIGRATION_PATHS, result, source, index, results);
}
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'core/color/addAttribute', color_addAttributes);
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.getSaveContent.extraProps', 'core/color/addSaveProps', color_addSaveProps);
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'core/color/addEditProps', color_addEditProps);
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockListBlock', 'core/color/with-color-palette-styles', withColorPaletteStyles);
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.switchToBlockType.transformedBlock', 'core/color/addTransforms', color_addTransforms);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/font-appearance-control/index.js
/**
* WordPress dependencies
*/
const FONT_STYLES = [{
name: (0,external_wp_i18n_namespaceObject._x)('Regular', 'font style'),
value: 'normal'
}, {
name: (0,external_wp_i18n_namespaceObject._x)('Italic', 'font style'),
value: 'italic'
}];
const FONT_WEIGHTS = [{
name: (0,external_wp_i18n_namespaceObject._x)('Thin', 'font weight'),
value: '100'
}, {
name: (0,external_wp_i18n_namespaceObject._x)('Extra Light', 'font weight'),
value: '200'
}, {
name: (0,external_wp_i18n_namespaceObject._x)('Light', 'font weight'),
value: '300'
}, {
name: (0,external_wp_i18n_namespaceObject._x)('Regular', 'font weight'),
value: '400'
}, {
name: (0,external_wp_i18n_namespaceObject._x)('Medium', 'font weight'),
value: '500'
}, {
name: (0,external_wp_i18n_namespaceObject._x)('Semi Bold', 'font weight'),
value: '600'
}, {
name: (0,external_wp_i18n_namespaceObject._x)('Bold', 'font weight'),
value: '700'
}, {
name: (0,external_wp_i18n_namespaceObject._x)('Extra Bold', 'font weight'),
value: '800'
}, {
name: (0,external_wp_i18n_namespaceObject._x)('Black', 'font weight'),
value: '900'
}];
/**
* Adjusts font appearance field label in case either font styles or weights
* are disabled.
*
* @param {boolean} hasFontStyles Whether font styles are enabled and present.
* @param {boolean} hasFontWeights Whether font weights are enabled and present.
* @return {string} A label representing what font appearance is being edited.
*/
const getFontAppearanceLabel = (hasFontStyles, hasFontWeights) => {
if (!hasFontStyles) {
return (0,external_wp_i18n_namespaceObject.__)('Font weight');
}
if (!hasFontWeights) {
return (0,external_wp_i18n_namespaceObject.__)('Font style');
}
return (0,external_wp_i18n_namespaceObject.__)('Appearance');
};
/**
* Control to display unified font style and weight options.
*
* @param {Object} props Component props.
*
* @return {WPElement} Font appearance control.
*/
function FontAppearanceControl(props) {
const {
onChange,
hasFontStyles = true,
hasFontWeights = true,
value: {
fontStyle,
fontWeight
},
...otherProps
} = props;
const hasStylesOrWeights = hasFontStyles || hasFontWeights;
const label = getFontAppearanceLabel(hasFontStyles, hasFontWeights);
const defaultOption = {
key: 'default',
name: (0,external_wp_i18n_namespaceObject.__)('Default'),
style: {
fontStyle: undefined,
fontWeight: undefined
}
}; // Combines both font style and weight options into a single dropdown.
const combineOptions = () => {
const combinedOptions = [defaultOption];
FONT_STYLES.forEach(_ref => {
let {
name: styleName,
value: styleValue
} = _ref;
FONT_WEIGHTS.forEach(_ref2 => {
let {
name: weightName,
value: weightValue
} = _ref2;
const optionName = styleValue === 'normal' ? weightName : (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: 1: Font weight name. 2: Font style name. */
(0,external_wp_i18n_namespaceObject.__)('%1$s %2$s'), weightName, styleName);
combinedOptions.push({
key: `${styleValue}-${weightValue}`,
name: optionName,
style: {
fontStyle: styleValue,
fontWeight: weightValue
}
});
});
});
return combinedOptions;
}; // Generates select options for font styles only.
const styleOptions = () => {
const combinedOptions = [defaultOption];
FONT_STYLES.forEach(_ref3 => {
let {
name,
value
} = _ref3;
combinedOptions.push({
key: value,
name,
style: {
fontStyle: value,
fontWeight: undefined
}
});
});
return combinedOptions;
}; // Generates select options for font weights only.
const weightOptions = () => {
const combinedOptions = [defaultOption];
FONT_WEIGHTS.forEach(_ref4 => {
let {
name,
value
} = _ref4;
combinedOptions.push({
key: value,
name,
style: {
fontStyle: undefined,
fontWeight: value
}
});
});
return combinedOptions;
}; // Map font styles and weights to select options.
const selectOptions = (0,external_wp_element_namespaceObject.useMemo)(() => {
if (hasFontStyles && hasFontWeights) {
return combineOptions();
}
return hasFontStyles ? styleOptions() : weightOptions();
}, [props.options]); // Find current selection by comparing font style & weight against options,
// and fall back to the Default option if there is no matching option.
const currentSelection = selectOptions.find(option => option.style.fontStyle === fontStyle && option.style.fontWeight === fontWeight) || selectOptions[0]; // Adjusts screen reader description based on styles or weights.
const getDescribedBy = () => {
if (!currentSelection) {
return (0,external_wp_i18n_namespaceObject.__)('No selected font appearance');
}
if (!hasFontStyles) {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: Currently selected font weight.
(0,external_wp_i18n_namespaceObject.__)('Currently selected font weight: %s'), currentSelection.name);
}
if (!hasFontWeights) {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: Currently selected font style.
(0,external_wp_i18n_namespaceObject.__)('Currently selected font style: %s'), currentSelection.name);
}
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: Currently selected font appearance.
(0,external_wp_i18n_namespaceObject.__)('Currently selected font appearance: %s'), currentSelection.name);
};
return hasStylesOrWeights && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.CustomSelectControl, _extends({}, otherProps, {
className: "components-font-appearance-control",
label: label,
describedBy: getDescribedBy(),
options: selectOptions,
value: currentSelection,
onChange: _ref5 => {
let {
selectedItem
} = _ref5;
return onChange(selectedItem.style);
},
__nextUnconstrainedWidth: true
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/line-height-control/utils.js
const BASE_DEFAULT_VALUE = 1.5;
const STEP = 0.1;
/**
* There are varying value types within LineHeightControl:
*
* {undefined} Initial value. No changes from the user.
* {string} Input value. Value consumed/outputted by the input. Empty would be ''.
* {number} Block attribute type. Input value needs to be converted for attribute setting.
*
* Note: If the value is undefined, the input requires it to be an empty string ('')
* in order to be considered "controlled" by props (rather than internal state).
*/
const RESET_VALUE = '';
/**
* Determines if the lineHeight attribute has been properly defined.
*
* @param {any} lineHeight The value to check.
*
* @return {boolean} Whether the lineHeight attribute is valid.
*/
function isLineHeightDefined(lineHeight) {
return lineHeight !== undefined && lineHeight !== RESET_VALUE;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/line-height-control/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const LineHeightControl = _ref => {
let {
value: lineHeight,
onChange,
/** Start opting into the new margin-free styles that will become the default in a future version. */
__nextHasNoMarginBottom = false,
__unstableInputWidth = '60px',
...otherProps
} = _ref;
const isDefined = isLineHeightDefined(lineHeight);
const adjustNextValue = (nextValue, wasTypedOrPasted) => {
// Set the next value without modification if lineHeight has been defined.
if (isDefined) return nextValue;
/**
* The following logic handles the initial step up/down action
* (from an undefined value state) so that the next values are better suited for
* line-height rendering. For example, the first step up should immediately
* go to 1.6, rather than the normally expected 0.1.
*
* Step up/down actions can be triggered by keydowns of the up/down arrow keys,
* or by clicking the spin buttons.
*/
switch (`${nextValue}`) {
case `${STEP}`:
// Increment by step value.
return BASE_DEFAULT_VALUE + STEP;
case '0':
{
// This means the user explicitly input '0', rather than stepped down
// from an undefined value state.
if (wasTypedOrPasted) return nextValue; // Decrement by step value.
return BASE_DEFAULT_VALUE - STEP;
}
case '':
return BASE_DEFAULT_VALUE;
default:
return nextValue;
}
};
const stateReducer = (state, action) => {
var _action$payload$event;
// Be careful when changing this — cross-browser behavior of the
// `inputType` field in `input` events are inconsistent.
// For example, Firefox emits an input event with inputType="insertReplacementText"
// on spin button clicks, while other browsers do not even emit an input event.
const wasTypedOrPasted = ['insertText', 'insertFromPaste'].includes((_action$payload$event = action.payload.event.nativeEvent) === null || _action$payload$event === void 0 ? void 0 : _action$payload$event.inputType);
const value = adjustNextValue(state.value, wasTypedOrPasted);
return { ...state,
value
};
};
const value = isDefined ? lineHeight : RESET_VALUE;
if (!__nextHasNoMarginBottom) {
external_wp_deprecated_default()('Bottom margin styles for wp.blockEditor.LineHeightControl', {
since: '6.0',
version: '6.4',
hint: 'Set the `__nextHasNoMarginBottom` prop to true to start opting into the new styles, which will become the default in a future version'
});
}
const deprecatedStyles = __nextHasNoMarginBottom ? undefined : {
marginBottom: 24
};
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-line-height-control",
style: deprecatedStyles
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalNumberControl, _extends({}, otherProps, {
__unstableInputWidth: __unstableInputWidth,
__unstableStateReducer: stateReducer,
onChange: onChange,
label: (0,external_wp_i18n_namespaceObject.__)('Line height'),
placeholder: BASE_DEFAULT_VALUE,
step: STEP,
value: value,
min: 0,
spinControls: "custom"
})));
};
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/line-height-control/README.md
*/
/* harmony default export */ var line_height_control = (LineHeightControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/line-height.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const line_height_LINE_HEIGHT_SUPPORT_KEY = 'typography.lineHeight';
/**
* Inspector control panel containing the line height related configuration
*
* @param {Object} props
*
* @return {WPElement} Line height edit element.
*/
function LineHeightEdit(props) {
var _style$typography;
const {
attributes: {
style
},
setAttributes
} = props;
const onChange = newLineHeightValue => {
const newStyle = { ...style,
typography: { ...(style === null || style === void 0 ? void 0 : style.typography),
lineHeight: newLineHeightValue
}
};
setAttributes({
style: utils_cleanEmptyObject(newStyle)
});
};
return (0,external_wp_element_namespaceObject.createElement)(line_height_control, {
__unstableInputWidth: "100%",
__nextHasNoMarginBottom: true,
value: style === null || style === void 0 ? void 0 : (_style$typography = style.typography) === null || _style$typography === void 0 ? void 0 : _style$typography.lineHeight,
onChange: onChange,
size: "__unstable-large"
});
}
/**
* Custom hook that checks if line-height settings have been disabled.
*
* @param {string} name The name of the block.
* @return {boolean} Whether setting is disabled.
*/
function useIsLineHeightDisabled() {
let {
name: blockName
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const isDisabled = !useSetting('typography.lineHeight');
return !(0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockName, line_height_LINE_HEIGHT_SUPPORT_KEY) || isDisabled;
}
/**
* Checks if there is a current value set for the line height block support.
*
* @param {Object} props Block props.
* @return {boolean} Whether or not the block has a line height value set.
*/
function hasLineHeightValue(props) {
var _props$attributes$sty, _props$attributes$sty2;
return !!((_props$attributes$sty = props.attributes.style) !== null && _props$attributes$sty !== void 0 && (_props$attributes$sty2 = _props$attributes$sty.typography) !== null && _props$attributes$sty2 !== void 0 && _props$attributes$sty2.lineHeight);
}
/**
* Resets the line height block support attribute. This can be used when
* disabling the line height support controls for a block via a progressive
* discovery panel.
*
* @param {Object} props Block props.
* @param {Object} props.attributes Block's attributes.
* @param {Object} props.setAttributes Function to set block's attributes.
*/
function resetLineHeight(_ref) {
let {
attributes = {},
setAttributes
} = _ref;
const {
style
} = attributes;
setAttributes({
style: utils_cleanEmptyObject({ ...style,
typography: { ...(style === null || style === void 0 ? void 0 : style.typography),
lineHeight: undefined
}
})
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/font-appearance.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Key within block settings' support array indicating support for font style.
*/
const font_appearance_FONT_STYLE_SUPPORT_KEY = 'typography.__experimentalFontStyle';
/**
* Key within block settings' support array indicating support for font weight.
*/
const font_appearance_FONT_WEIGHT_SUPPORT_KEY = 'typography.__experimentalFontWeight';
/**
* Inspector control panel containing the font appearance options.
*
* @param {Object} props Block properties.
*
* @return {WPElement} Font appearance edit element.
*/
function FontAppearanceEdit(props) {
var _style$typography, _style$typography2;
const {
attributes: {
style
},
setAttributes
} = props;
const hasFontStyles = !useIsFontStyleDisabled(props);
const hasFontWeights = !useIsFontWeightDisabled(props);
const onChange = newStyles => {
setAttributes({
style: utils_cleanEmptyObject({ ...style,
typography: { ...(style === null || style === void 0 ? void 0 : style.typography),
fontStyle: newStyles.fontStyle,
fontWeight: newStyles.fontWeight
}
})
});
};
const fontStyle = style === null || style === void 0 ? void 0 : (_style$typography = style.typography) === null || _style$typography === void 0 ? void 0 : _style$typography.fontStyle;
const fontWeight = style === null || style === void 0 ? void 0 : (_style$typography2 = style.typography) === null || _style$typography2 === void 0 ? void 0 : _style$typography2.fontWeight;
return (0,external_wp_element_namespaceObject.createElement)(FontAppearanceControl, {
onChange: onChange,
hasFontStyles: hasFontStyles,
hasFontWeights: hasFontWeights,
value: {
fontStyle,
fontWeight
},
size: "__unstable-large"
});
}
/**
* Checks if font style support has been disabled either by not opting in for
* support or by failing to provide preset styles.
*
* @param {Object} props Block properties.
* @param {string} props.name Name for the block type.
*
* @return {boolean} Whether font style support has been disabled.
*/
function useIsFontStyleDisabled() {
let {
name: blockName
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const styleSupport = (0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockName, font_appearance_FONT_STYLE_SUPPORT_KEY);
const hasFontStyles = useSetting('typography.fontStyle');
return !styleSupport || !hasFontStyles;
}
/**
* Checks if font weight support has been disabled either by not opting in for
* support or by failing to provide preset weights.
*
* @param {Object} props Block properties.
* @param {string} props.name Name for the block type.
*
* @return {boolean} Whether font weight support has been disabled.
*/
function useIsFontWeightDisabled() {
let {
name: blockName
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const weightSupport = (0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockName, font_appearance_FONT_WEIGHT_SUPPORT_KEY);
const hasFontWeights = useSetting('typography.fontWeight');
return !weightSupport || !hasFontWeights;
}
/**
* Checks if font appearance support has been disabled.
*
* @param {Object} props Block properties.
*
* @return {boolean} Whether font appearance support has been disabled.
*/
function useIsFontAppearanceDisabled(props) {
const stylesDisabled = useIsFontStyleDisabled(props);
const weightsDisabled = useIsFontWeightDisabled(props);
return stylesDisabled && weightsDisabled;
}
/**
* Checks if there is either a font style or weight value set within the
* typography styles.
*
* @param {Object} props Block props.
* @return {boolean} Whether or not the block has a font style or weight.
*/
function hasFontAppearanceValue(props) {
var _props$attributes$sty;
const {
fontStyle,
fontWeight
} = ((_props$attributes$sty = props.attributes.style) === null || _props$attributes$sty === void 0 ? void 0 : _props$attributes$sty.typography) || {};
return !!fontStyle || !!fontWeight;
}
/**
* Resets the font style and weight block support attributes. This can be used
* when disabling the font appearance support controls for a block via a
* progressive discovery panel.
*
* @param {Object} props Block props.
* @param {Object} props.attributes Block's attributes.
* @param {Object} props.setAttributes Function to set block's attributes.
*/
function resetFontAppearance(_ref) {
let {
attributes = {},
setAttributes
} = _ref;
const {
style
} = attributes;
setAttributes({
style: utils_cleanEmptyObject({ ...style,
typography: { ...(style === null || style === void 0 ? void 0 : style.typography),
fontStyle: undefined,
fontWeight: undefined
}
})
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/font-family/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function FontFamilyControl(_ref) {
let {
value = '',
onChange,
fontFamilies,
...props
} = _ref;
const blockLevelFontFamilies = useSetting('typography.fontFamilies');
if (!fontFamilies) {
fontFamilies = blockLevelFontFamilies;
}
if (!fontFamilies || fontFamilies.length === 0) {
return null;
}
const options = [{
value: '',
label: (0,external_wp_i18n_namespaceObject.__)('Default')
}, ...fontFamilies.map(_ref2 => {
let {
fontFamily,
name
} = _ref2;
return {
value: fontFamily,
label: name || fontFamily
};
})];
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SelectControl, _extends({
label: (0,external_wp_i18n_namespaceObject.__)('Font'),
options: options,
value: value,
onChange: onChange,
labelPosition: "top"
}, props));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/font-family.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const font_family_FONT_FAMILY_SUPPORT_KEY = 'typography.__experimentalFontFamily';
/**
* Filters registered block settings, extending attributes to include
* the `fontFamily` attribute.
*
* @param {Object} settings Original block settings
* @return {Object} Filtered block settings
*/
function font_family_addAttributes(settings) {
if (!(0,external_wp_blocks_namespaceObject.hasBlockSupport)(settings, font_family_FONT_FAMILY_SUPPORT_KEY)) {
return settings;
} // Allow blocks to specify a default value if needed.
if (!settings.attributes.fontFamily) {
Object.assign(settings.attributes, {
fontFamily: {
type: 'string'
}
});
}
return settings;
}
/**
* Override props assigned to save component to inject font family.
*
* @param {Object} props Additional props applied to save element
* @param {Object} blockType Block type
* @param {Object} attributes Block attributes
* @return {Object} Filtered props applied to save element
*/
function font_family_addSaveProps(props, blockType, attributes) {
if (!(0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockType, font_family_FONT_FAMILY_SUPPORT_KEY)) {
return props;
}
if (shouldSkipSerialization(blockType, TYPOGRAPHY_SUPPORT_KEY, 'fontFamily')) {
return props;
}
if (!(attributes !== null && attributes !== void 0 && attributes.fontFamily)) {
return props;
} // Use TokenList to dedupe classes.
const classes = new (external_wp_tokenList_default())(props.className);
classes.add(`has-${(0,external_lodash_namespaceObject.kebabCase)(attributes === null || attributes === void 0 ? void 0 : attributes.fontFamily)}-font-family`);
const newClassName = classes.value;
props.className = newClassName ? newClassName : undefined;
return props;
}
/**
* Filters registered block settings to expand the block edit wrapper
* by applying the desired styles and classnames.
*
* @param {Object} settings Original block settings.
*
* @return {Object} Filtered block settings.
*/
function font_family_addEditProps(settings) {
if (!(0,external_wp_blocks_namespaceObject.hasBlockSupport)(settings, font_family_FONT_FAMILY_SUPPORT_KEY)) {
return settings;
}
const existingGetEditWrapperProps = settings.getEditWrapperProps;
settings.getEditWrapperProps = attributes => {
let props = {};
if (existingGetEditWrapperProps) {
props = existingGetEditWrapperProps(attributes);
}
return font_family_addSaveProps(props, settings, attributes);
};
return settings;
}
function FontFamilyEdit(_ref) {
var _fontFamilies$find;
let {
setAttributes,
attributes: {
fontFamily
}
} = _ref;
const fontFamilies = useSetting('typography.fontFamilies');
const value = fontFamilies === null || fontFamilies === void 0 ? void 0 : (_fontFamilies$find = fontFamilies.find(_ref2 => {
let {
slug
} = _ref2;
return fontFamily === slug;
})) === null || _fontFamilies$find === void 0 ? void 0 : _fontFamilies$find.fontFamily;
function onChange(newValue) {
const predefinedFontFamily = fontFamilies === null || fontFamilies === void 0 ? void 0 : fontFamilies.find(_ref3 => {
let {
fontFamily: f
} = _ref3;
return f === newValue;
});
setAttributes({
fontFamily: predefinedFontFamily === null || predefinedFontFamily === void 0 ? void 0 : predefinedFontFamily.slug
});
}
return (0,external_wp_element_namespaceObject.createElement)(FontFamilyControl, {
className: "block-editor-hooks-font-family-control",
fontFamilies: fontFamilies,
value: value,
onChange: onChange,
size: "__unstable-large",
__nextHasNoMarginBottom: true
});
}
/**
* Custom hook that checks if font-family functionality is disabled.
*
* @param {string} name The name of the block.
* @return {boolean} Whether setting is disabled.
*/
function useIsFontFamilyDisabled(_ref4) {
let {
name
} = _ref4;
const fontFamilies = useSetting('typography.fontFamilies');
return !fontFamilies || fontFamilies.length === 0 || !(0,external_wp_blocks_namespaceObject.hasBlockSupport)(name, font_family_FONT_FAMILY_SUPPORT_KEY);
}
/**
* Checks if there is a current value set for the font family block support.
*
* @param {Object} props Block props.
* @return {boolean} Whether or not the block has a font family value set.
*/
function hasFontFamilyValue(props) {
return !!props.attributes.fontFamily;
}
/**
* Resets the font family block support attribute. This can be used when
* disabling the font family support controls for a block via a progressive
* discovery panel.
*
* @param {Object} props Block props.
* @param {Object} props.setAttributes Function to set block's attributes.
*/
function resetFontFamily(_ref5) {
let {
setAttributes
} = _ref5;
setAttributes({
fontFamily: undefined
});
}
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'core/fontFamily/addAttribute', font_family_addAttributes);
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.getSaveContent.extraProps', 'core/fontFamily/addSaveProps', font_family_addSaveProps);
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'core/fontFamily/addEditProps', font_family_addEditProps);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/font-sizes/utils.js
/**
* External dependencies
*/
/**
* Returns the font size object based on an array of named font sizes and the namedFontSize and customFontSize values.
* If namedFontSize is undefined or not found in fontSizes an object with just the size value based on customFontSize is returned.
*
* @param {Array} fontSizes Array of font size objects containing at least the "name" and "size" values as properties.
* @param {?string} fontSizeAttribute Content of the font size attribute (slug).
* @param {?number} customFontSizeAttribute Contents of the custom font size attribute (value).
*
* @return {?Object} If fontSizeAttribute is set and an equal slug is found in fontSizes it returns the font size object for that slug.
* Otherwise, an object with just the size value based on customFontSize is returned.
*/
const getFontSize = (fontSizes, fontSizeAttribute, customFontSizeAttribute) => {
if (fontSizeAttribute) {
const fontSizeObject = fontSizes === null || fontSizes === void 0 ? void 0 : fontSizes.find(_ref => {
let {
slug
} = _ref;
return slug === fontSizeAttribute;
});
if (fontSizeObject) {
return fontSizeObject;
}
}
return {
size: customFontSizeAttribute
};
};
/**
* Returns the corresponding font size object for a given value.
*
* @param {Array} fontSizes Array of font size objects.
* @param {number} value Font size value.
*
* @return {Object} Font size object.
*/
function getFontSizeObjectByValue(fontSizes, value) {
const fontSizeObject = fontSizes === null || fontSizes === void 0 ? void 0 : fontSizes.find(_ref2 => {
let {
size
} = _ref2;
return size === value;
});
if (fontSizeObject) {
return fontSizeObject;
}
return {
size: value
};
}
/**
* Returns a class based on fontSizeName.
*
* @param {string} fontSizeSlug Slug of the fontSize.
*
* @return {string | undefined} String with the class corresponding to the fontSize passed.
* The class is generated by appending 'has-' followed by fontSizeSlug in kebabCase and ending with '-font-size'.
*/
function getFontSizeClass(fontSizeSlug) {
if (!fontSizeSlug) {
return;
}
return `has-${(0,external_lodash_namespaceObject.kebabCase)(fontSizeSlug)}-font-size`;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/font-sizes/font-size-picker.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function FontSizePicker(props) {
const fontSizes = useSetting('typography.fontSizes');
const disableCustomFontSizes = !useSetting('typography.customFontSize');
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FontSizePicker, _extends({}, props, {
fontSizes: fontSizes,
disableCustomFontSizes: disableCustomFontSizes
}));
}
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/font-sizes/README.md
*/
/* harmony default export */ var font_size_picker = (FontSizePicker);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/font-sizes/fluid-utils.js
/**
* The fluid utilities must match the backend equivalent.
* See: gutenberg_get_typography_font_size_value() in lib/block-supports/typography.php
* ---------------------------------------------------------------
*/
// Defaults.
const DEFAULT_MAXIMUM_VIEWPORT_WIDTH = '1600px';
const DEFAULT_MINIMUM_VIEWPORT_WIDTH = '768px';
const DEFAULT_SCALE_FACTOR = 1;
const DEFAULT_MINIMUM_FONT_SIZE_FACTOR = 0.75;
const DEFAULT_MINIMUM_FONT_SIZE_LIMIT = '14px';
/**
* Computes a fluid font-size value that uses clamp(). A minimum and maximum
* font size OR a single font size can be specified.
*
* If a single font size is specified, it is scaled up and down by
* minimumFontSizeFactor and maximumFontSizeFactor to arrive at the minimum and
* maximum sizes.
*
* @example
* ```js
* // Calculate fluid font-size value from a minimum and maximum value.
* const fontSize = getComputedFluidTypographyValue( {
* minimumFontSize: '20px',
* maximumFontSize: '45px'
* } );
* // Calculate fluid font-size value from a single font size.
* const fontSize = getComputedFluidTypographyValue( {
* fontSize: '30px',
* } );
* ```
*
* @param {Object} args
* @param {?string} args.minimumViewPortWidth Minimum viewport size from which type will have fluidity. Optional if fontSize is specified.
* @param {?string} args.maximumViewPortWidth Maximum size up to which type will have fluidity. Optional if fontSize is specified.
* @param {string|number} [args.fontSize] Size to derive maximumFontSize and minimumFontSize from, if necessary. Optional if minimumFontSize and maximumFontSize are specified.
* @param {?string} args.maximumFontSize Maximum font size for any clamp() calculation. Optional.
* @param {?string} args.minimumFontSize Minimum font size for any clamp() calculation. Optional.
* @param {?number} args.scaleFactor A scale factor to determine how fast a font scales within boundaries. Optional.
* @param {?number} args.minimumFontSizeFactor How much to scale defaultFontSize by to derive minimumFontSize. Optional.
* @param {?string} args.minimumFontSizeLimit The smallest a calculated font size may be. Optional.
*
* @return {string|null} A font-size value using clamp().
*/
function getComputedFluidTypographyValue(_ref) {
let {
minimumFontSize,
maximumFontSize,
fontSize,
minimumViewPortWidth = DEFAULT_MINIMUM_VIEWPORT_WIDTH,
maximumViewPortWidth = DEFAULT_MAXIMUM_VIEWPORT_WIDTH,
scaleFactor = DEFAULT_SCALE_FACTOR,
minimumFontSizeFactor = DEFAULT_MINIMUM_FONT_SIZE_FACTOR,
minimumFontSizeLimit
} = _ref;
// Validate incoming settings and set defaults.
minimumFontSizeLimit = !!getTypographyValueAndUnit(minimumFontSizeLimit) ? minimumFontSizeLimit : DEFAULT_MINIMUM_FONT_SIZE_LIMIT;
/*
* Calculates missing minimumFontSize and maximumFontSize from
* defaultFontSize if provided.
*/
if (fontSize) {
// Parses default font size.
const fontSizeParsed = getTypographyValueAndUnit(fontSize); // Protect against invalid units.
if (!(fontSizeParsed !== null && fontSizeParsed !== void 0 && fontSizeParsed.unit)) {
return null;
} // Parses the minimum font size limit, so we can perform checks using it.
const minimumFontSizeLimitParsed = getTypographyValueAndUnit(minimumFontSizeLimit, {
coerceTo: fontSizeParsed.unit
}); // Don't enforce minimum font size if a font size has explicitly set a min and max value.
if (!!(minimumFontSizeLimitParsed !== null && minimumFontSizeLimitParsed !== void 0 && minimumFontSizeLimitParsed.value) && !minimumFontSize && !maximumFontSize) {
/*
* If a minimum size was not passed to this function
* and the user-defined font size is lower than $minimum_font_size_limit,
* do not calculate a fluid value.
*/
if ((fontSizeParsed === null || fontSizeParsed === void 0 ? void 0 : fontSizeParsed.value) <= (minimumFontSizeLimitParsed === null || minimumFontSizeLimitParsed === void 0 ? void 0 : minimumFontSizeLimitParsed.value)) {
return null;
}
} // If no fluid max font size is available use the incoming value.
if (!maximumFontSize) {
maximumFontSize = `${fontSizeParsed.value}${fontSizeParsed.unit}`;
}
/*
* If no minimumFontSize is provided, create one using
* the given font size multiplied by the min font size scale factor.
*/
if (!minimumFontSize) {
const calculatedMinimumFontSize = roundToPrecision(fontSizeParsed.value * minimumFontSizeFactor, 3); // Only use calculated min font size if it's > $minimum_font_size_limit value.
if (!!(minimumFontSizeLimitParsed !== null && minimumFontSizeLimitParsed !== void 0 && minimumFontSizeLimitParsed.value) && calculatedMinimumFontSize < (minimumFontSizeLimitParsed === null || minimumFontSizeLimitParsed === void 0 ? void 0 : minimumFontSizeLimitParsed.value)) {
minimumFontSize = `${minimumFontSizeLimitParsed.value}${minimumFontSizeLimitParsed.unit}`;
} else {
minimumFontSize = `${calculatedMinimumFontSize}${fontSizeParsed.unit}`;
}
}
} // Grab the minimum font size and normalize it in order to use the value for calculations.
const minimumFontSizeParsed = getTypographyValueAndUnit(minimumFontSize); // We get a 'preferred' unit to keep units consistent when calculating,
// otherwise the result will not be accurate.
const fontSizeUnit = (minimumFontSizeParsed === null || minimumFontSizeParsed === void 0 ? void 0 : minimumFontSizeParsed.unit) || 'rem'; // Grabs the maximum font size and normalize it in order to use the value for calculations.
const maximumFontSizeParsed = getTypographyValueAndUnit(maximumFontSize, {
coerceTo: fontSizeUnit
}); // Checks for mandatory min and max sizes, and protects against unsupported units.
if (!minimumFontSizeParsed || !maximumFontSizeParsed) {
return null;
} // Uses rem for accessible fluid target font scaling.
const minimumFontSizeRem = getTypographyValueAndUnit(minimumFontSize, {
coerceTo: 'rem'
}); // Viewport widths defined for fluid typography. Normalize units
const maximumViewPortWidthParsed = getTypographyValueAndUnit(maximumViewPortWidth, {
coerceTo: fontSizeUnit
});
const minumumViewPortWidthParsed = getTypographyValueAndUnit(minimumViewPortWidth, {
coerceTo: fontSizeUnit
}); // Protect against unsupported units.
if (!maximumViewPortWidthParsed || !minumumViewPortWidthParsed || !minimumFontSizeRem) {
return null;
} // Build CSS rule.
// Borrowed from https://websemantics.uk/tools/responsive-font-calculator/.
const minViewPortWidthOffsetValue = roundToPrecision(minumumViewPortWidthParsed.value / 100, 3);
const viewPortWidthOffset = roundToPrecision(minViewPortWidthOffsetValue, 3) + fontSizeUnit;
const linearFactor = 100 * ((maximumFontSizeParsed.value - minimumFontSizeParsed.value) / (maximumViewPortWidthParsed.value - minumumViewPortWidthParsed.value));
const linearFactorScaled = roundToPrecision((linearFactor || 1) * scaleFactor, 3);
const fluidTargetFontSize = `${minimumFontSizeRem.value}${minimumFontSizeRem.unit} + ((1vw - ${viewPortWidthOffset}) * ${linearFactorScaled})`;
return `clamp(${minimumFontSize}, ${fluidTargetFontSize}, ${maximumFontSize})`;
}
/**
* Internal method that checks a string for a unit and value and returns an array consisting of `'value'` and `'unit'`, e.g., [ '42', 'rem' ].
* A raw font size of `value + unit` is expected. If the value is an integer, it will convert to `value + 'px'`.
*
* @param {string|number} rawValue Raw size value from theme.json.
* @param {Object|undefined} options Calculation options.
*
* @return {{ unit: string, value: number }|null} An object consisting of `'value'` and `'unit'` properties.
*/
function getTypographyValueAndUnit(rawValue) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (typeof rawValue !== 'string' && typeof rawValue !== 'number') {
return null;
} // Converts numeric values to pixel values by default.
if (isFinite(rawValue)) {
rawValue = `${rawValue}px`;
}
const {
coerceTo,
rootSizeValue,
acceptableUnits
} = {
coerceTo: '',
// Default browser font size. Later we could inject some JS to compute this `getComputedStyle( document.querySelector( "html" ) ).fontSize`.
rootSizeValue: 16,
acceptableUnits: ['rem', 'px', 'em'],
...options
};
const acceptableUnitsGroup = acceptableUnits === null || acceptableUnits === void 0 ? void 0 : acceptableUnits.join('|');
const regexUnits = new RegExp(`^(\\d*\\.?\\d+)(${acceptableUnitsGroup}){1,1}$`);
const matches = rawValue.match(regexUnits); // We need a number value and a unit.
if (!matches || matches.length < 3) {
return null;
}
let [, value, unit] = matches;
let returnValue = parseFloat(value);
if ('px' === coerceTo && ('em' === unit || 'rem' === unit)) {
returnValue = returnValue * rootSizeValue;
unit = coerceTo;
}
if ('px' === unit && ('em' === coerceTo || 'rem' === coerceTo)) {
returnValue = returnValue / rootSizeValue;
unit = coerceTo;
}
/*
* No calculation is required if swapping between em and rem yet,
* since we assume a root size value. Later we might like to differentiate between
* :root font size (rem) and parent element font size (em) relativity.
*/
if (('em' === coerceTo || 'rem' === coerceTo) && ('em' === unit || 'rem' === unit)) {
unit = coerceTo;
}
return {
value: roundToPrecision(returnValue, 3),
unit
};
}
/**
* Returns a value rounded to defined precision.
* Returns `undefined` if the value is not a valid finite number.
*
* @param {number} value Raw value.
* @param {number} digits The number of digits to appear after the decimal point
*
* @return {number|undefined} Value rounded to standard precision.
*/
function roundToPrecision(value) {
let digits = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 3;
const base = Math.pow(10, digits);
return Number.isFinite(value) ? parseFloat(Math.round(value * base) / base) : undefined;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/font-size.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const font_size_FONT_SIZE_SUPPORT_KEY = 'typography.fontSize';
/**
* Filters registered block settings, extending attributes to include
* `fontSize` and `fontWeight` attributes.
*
* @param {Object} settings Original block settings.
*
* @return {Object} Filtered block settings.
*/
function font_size_addAttributes(settings) {
if (!(0,external_wp_blocks_namespaceObject.hasBlockSupport)(settings, font_size_FONT_SIZE_SUPPORT_KEY)) {
return settings;
} // Allow blocks to specify a default value if needed.
if (!settings.attributes.fontSize) {
Object.assign(settings.attributes, {
fontSize: {
type: 'string'
}
});
}
return settings;
}
/**
* Override props assigned to save component to inject font size.
*
* @param {Object} props Additional props applied to save element.
* @param {Object} blockType Block type.
* @param {Object} attributes Block attributes.
*
* @return {Object} Filtered props applied to save element.
*/
function font_size_addSaveProps(props, blockType, attributes) {
if (!(0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockType, font_size_FONT_SIZE_SUPPORT_KEY)) {
return props;
}
if (shouldSkipSerialization(blockType, TYPOGRAPHY_SUPPORT_KEY, 'fontSize')) {
return props;
} // Use TokenList to dedupe classes.
const classes = new (external_wp_tokenList_default())(props.className);
classes.add(getFontSizeClass(attributes.fontSize));
const newClassName = classes.value;
props.className = newClassName ? newClassName : undefined;
return props;
}
/**
* Filters registered block settings to expand the block edit wrapper
* by applying the desired styles and classnames.
*
* @param {Object} settings Original block settings.
*
* @return {Object} Filtered block settings.
*/
function font_size_addEditProps(settings) {
if (!(0,external_wp_blocks_namespaceObject.hasBlockSupport)(settings, font_size_FONT_SIZE_SUPPORT_KEY)) {
return settings;
}
const existingGetEditWrapperProps = settings.getEditWrapperProps;
settings.getEditWrapperProps = attributes => {
let props = {};
if (existingGetEditWrapperProps) {
props = existingGetEditWrapperProps(attributes);
}
return font_size_addSaveProps(props, settings, attributes);
};
return settings;
}
/**
* Inspector control panel containing the font size related configuration
*
* @param {Object} props
*
* @return {WPElement} Font size edit element.
*/
function FontSizeEdit(props) {
var _style$typography, _style$typography2;
const {
attributes: {
fontSize,
style
},
setAttributes
} = props;
const fontSizes = useSetting('typography.fontSizes');
const onChange = value => {
const fontSizeSlug = getFontSizeObjectByValue(fontSizes, value).slug;
setAttributes({
style: utils_cleanEmptyObject({ ...style,
typography: { ...(style === null || style === void 0 ? void 0 : style.typography),
fontSize: fontSizeSlug ? undefined : value
}
}),
fontSize: fontSizeSlug
});
};
const fontSizeObject = getFontSize(fontSizes, fontSize, style === null || style === void 0 ? void 0 : (_style$typography = style.typography) === null || _style$typography === void 0 ? void 0 : _style$typography.fontSize);
const fontSizeValue = (fontSizeObject === null || fontSizeObject === void 0 ? void 0 : fontSizeObject.size) || (style === null || style === void 0 ? void 0 : (_style$typography2 = style.typography) === null || _style$typography2 === void 0 ? void 0 : _style$typography2.fontSize) || fontSize;
return (0,external_wp_element_namespaceObject.createElement)(font_size_picker, {
onChange: onChange,
value: fontSizeValue,
withReset: false,
withSlider: true,
size: "__unstable-large",
__nextHasNoMarginBottom: true
});
}
/**
* Checks if there is a current value set for the font size block support.
*
* @param {Object} props Block props.
* @return {boolean} Whether or not the block has a font size value set.
*/
function hasFontSizeValue(props) {
var _style$typography3;
const {
fontSize,
style
} = props.attributes;
return !!fontSize || !!(style !== null && style !== void 0 && (_style$typography3 = style.typography) !== null && _style$typography3 !== void 0 && _style$typography3.fontSize);
}
/**
* Resets the font size block support attribute. This can be used when
* disabling the font size support controls for a block via a progressive
* discovery panel.
*
* @param {Object} props Block props.
* @param {Object} props.attributes Block's attributes.
* @param {Object} props.setAttributes Function to set block's attributes.
*/
function resetFontSize(_ref) {
let {
attributes = {},
setAttributes
} = _ref;
const {
style
} = attributes;
setAttributes({
fontSize: undefined,
style: utils_cleanEmptyObject({ ...style,
typography: { ...(style === null || style === void 0 ? void 0 : style.typography),
fontSize: undefined
}
})
});
}
/**
* Custom hook that checks if font-size settings have been disabled.
*
* @param {string} name The name of the block.
* @return {boolean} Whether setting is disabled.
*/
function useIsFontSizeDisabled() {
let {
name: blockName
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const fontSizes = useSetting('typography.fontSizes');
const hasFontSizes = !!(fontSizes !== null && fontSizes !== void 0 && fontSizes.length);
return !(0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockName, font_size_FONT_SIZE_SUPPORT_KEY) || !hasFontSizes;
}
/**
* Add inline styles for font sizes.
* Ideally, this is not needed and themes load the font-size classes on the
* editor.
*
* @param {Function} BlockListBlock Original component.
*
* @return {Function} Wrapped component.
*/
const withFontSizeInlineStyles = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(BlockListBlock => props => {
var _style$typography4, _style$typography5;
const fontSizes = useSetting('typography.fontSizes');
const {
name: blockName,
attributes: {
fontSize,
style
},
wrapperProps
} = props; // Only add inline styles if the block supports font sizes,
// doesn't skip serialization of font sizes,
// doesn't already have an inline font size,
// and does have a class to extract the font size from.
if (!(0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockName, font_size_FONT_SIZE_SUPPORT_KEY) || shouldSkipSerialization(blockName, TYPOGRAPHY_SUPPORT_KEY, 'fontSize') || !fontSize || style !== null && style !== void 0 && (_style$typography4 = style.typography) !== null && _style$typography4 !== void 0 && _style$typography4.fontSize) {
return (0,external_wp_element_namespaceObject.createElement)(BlockListBlock, props);
}
const fontSizeValue = getFontSize(fontSizes, fontSize, style === null || style === void 0 ? void 0 : (_style$typography5 = style.typography) === null || _style$typography5 === void 0 ? void 0 : _style$typography5.fontSize).size;
const newProps = { ...props,
wrapperProps: { ...wrapperProps,
style: {
fontSize: fontSizeValue,
...(wrapperProps === null || wrapperProps === void 0 ? void 0 : wrapperProps.style)
}
}
};
return (0,external_wp_element_namespaceObject.createElement)(BlockListBlock, newProps);
}, 'withFontSizeInlineStyles');
const font_size_MIGRATION_PATHS = {
fontSize: [['fontSize'], ['style', 'typography', 'fontSize']]
};
function font_size_addTransforms(result, source, index, results) {
const destinationBlockType = result.name;
const activeSupports = {
fontSize: (0,external_wp_blocks_namespaceObject.hasBlockSupport)(destinationBlockType, font_size_FONT_SIZE_SUPPORT_KEY)
};
return transformStyles(activeSupports, font_size_MIGRATION_PATHS, result, source, index, results);
}
/**
* Allow custom font sizes to appear fluid when fluid typography is enabled at
* the theme level.
*
* Adds a custom getEditWrapperProps() callback to all block types that support
* font sizes. Then, if fluid typography is enabled, this callback will swap any
* custom font size in style.fontSize with a fluid font size (i.e. one that uses
* clamp()).
*
* It's important that this hook runs after 'core/style/addEditProps' sets
* style.fontSize as otherwise fontSize will be overwritten.
*
* @param {Object} blockType Block settings object.
*/
function addEditPropsForFluidCustomFontSizes(blockType) {
if (!(0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockType, font_size_FONT_SIZE_SUPPORT_KEY) || shouldSkipSerialization(blockType, TYPOGRAPHY_SUPPORT_KEY, 'fontSize')) {
return blockType;
}
const existingGetEditWrapperProps = blockType.getEditWrapperProps;
blockType.getEditWrapperProps = attributes => {
var _wrapperProps$style, _select$getSettings$_, _select$getSettings$_2;
const wrapperProps = existingGetEditWrapperProps ? existingGetEditWrapperProps(attributes) : {};
const fontSize = wrapperProps === null || wrapperProps === void 0 ? void 0 : (_wrapperProps$style = wrapperProps.style) === null || _wrapperProps$style === void 0 ? void 0 : _wrapperProps$style.fontSize; // TODO: This sucks! We should be using useSetting( 'typography.fluid' )
// or even useSelect( blockEditorStore ). We can't do either here
// because getEditWrapperProps is a plain JavaScript function called by
// BlockListBlock and not a React component rendered within
// BlockListContext.Provider. If we set fontSize using editor.
// BlockListBlock instead of using getEditWrapperProps then the value is
// clobbered when the core/style/addEditProps filter runs.
const fluidTypographyConfig = (_select$getSettings$_ = (0,external_wp_data_namespaceObject.select)(store).getSettings().__experimentalFeatures) === null || _select$getSettings$_ === void 0 ? void 0 : (_select$getSettings$_2 = _select$getSettings$_.typography) === null || _select$getSettings$_2 === void 0 ? void 0 : _select$getSettings$_2.fluid;
const fluidTypographySettings = typeof fluidTypographyConfig === 'object' ? fluidTypographyConfig : {};
const newFontSize = fontSize && !!fluidTypographyConfig ? getComputedFluidTypographyValue({
fontSize,
minimumFontSizeLimit: fluidTypographySettings === null || fluidTypographySettings === void 0 ? void 0 : fluidTypographySettings.minFontSize
}) : null;
if (newFontSize === null) {
return wrapperProps;
}
return { ...wrapperProps,
style: { ...(wrapperProps === null || wrapperProps === void 0 ? void 0 : wrapperProps.style),
fontSize: newFontSize
}
};
};
return blockType;
}
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'core/font/addAttribute', font_size_addAttributes);
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.getSaveContent.extraProps', 'core/font/addSaveProps', font_size_addSaveProps);
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'core/font/addEditProps', font_size_addEditProps);
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockListBlock', 'core/font-size/with-font-size-inline-styles', withFontSizeInlineStyles);
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.switchToBlockType.transformedBlock', 'core/font-size/addTransforms', font_size_addTransforms);
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'core/font-size/addEditPropsForFluidCustomFontSizes', addEditPropsForFluidCustomFontSizes, // Run after 'core/style/addEditProps' so that the style object has already
// been translated into inline CSS.
11);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/reset.js
/**
* WordPress dependencies
*/
const reset_reset = (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: "M7 11.5h10V13H7z"
}));
/* harmony default export */ var library_reset = (reset_reset);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/format-underline.js
/**
* WordPress dependencies
*/
const formatUnderline = (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: "M7 18v1h10v-1H7zm5-2c1.5 0 2.6-.4 3.4-1.2.8-.8 1.1-2 1.1-3.5V5H15v5.8c0 1.2-.2 2.1-.6 2.8-.4.7-1.2 1-2.4 1s-2-.3-2.4-1c-.4-.7-.6-1.6-.6-2.8V5H7.5v6.2c0 1.5.4 2.7 1.1 3.5.8.9 1.9 1.3 3.4 1.3z"
}));
/* harmony default export */ var format_underline = (formatUnderline);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/format-strikethrough.js
/**
* WordPress dependencies
*/
const formatStrikethrough = (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: "M9.1 9v-.5c0-.6.2-1.1.7-1.4.5-.3 1.2-.5 2-.5.7 0 1.4.1 2.1.3.7.2 1.4.5 2.1.9l.2-1.9c-.6-.3-1.2-.5-1.9-.7-.8-.1-1.6-.2-2.4-.2-1.5 0-2.7.3-3.6 1-.8.7-1.2 1.5-1.2 2.6V9h2zM20 12H4v1h8.3c.3.1.6.2.8.3.5.2.9.5 1.1.8.3.3.4.7.4 1.2 0 .7-.2 1.1-.8 1.5-.5.3-1.2.5-2.1.5-.8 0-1.6-.1-2.4-.3-.8-.2-1.5-.5-2.2-.8L7 18.1c.5.2 1.2.4 2 .6.8.2 1.6.3 2.4.3 1.7 0 3-.3 3.9-1 .9-.7 1.3-1.6 1.3-2.8 0-.9-.2-1.7-.7-2.2H20v-1z"
}));
/* harmony default export */ var format_strikethrough = (formatStrikethrough);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/text-decoration-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
const TEXT_DECORATIONS = [{
name: (0,external_wp_i18n_namespaceObject.__)('None'),
value: 'none',
icon: library_reset
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Underline'),
value: 'underline',
icon: format_underline
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Strikethrough'),
value: 'line-through',
icon: format_strikethrough
}];
/**
* Control to facilitate text decoration selections.
*
* @param {Object} props Component props.
* @param {string} props.value Currently selected text decoration.
* @param {Function} props.onChange Handles change in text decoration selection.
* @param {string} [props.className] Additional class name to apply.
*
* @return {WPElement} Text decoration control.
*/
function TextDecorationControl(_ref) {
let {
value,
onChange,
className
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("fieldset", {
className: classnames_default()('block-editor-text-decoration-control', className)
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.BaseControl.VisualLabel, {
as: "legend"
}, (0,external_wp_i18n_namespaceObject.__)('Decoration')), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-text-decoration-control__buttons"
}, TEXT_DECORATIONS.map(textDecoration => {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
key: textDecoration.value,
icon: textDecoration.icon,
label: textDecoration.name,
isPressed: textDecoration.value === value,
onClick: () => {
onChange(textDecoration.value === value ? undefined : textDecoration.value);
}
});
})));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/text-decoration.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Key within block settings' supports array indicating support for text
* decorations e.g. settings found in `block.json`.
*/
const text_decoration_TEXT_DECORATION_SUPPORT_KEY = 'typography.__experimentalTextDecoration';
/**
* Inspector control panel containing the text decoration options.
*
* @param {Object} props Block properties.
*
* @return {WPElement} Text decoration edit element.
*/
function TextDecorationEdit(props) {
var _style$typography;
const {
attributes: {
style
},
setAttributes
} = props;
function onChange(newDecoration) {
setAttributes({
style: utils_cleanEmptyObject({ ...style,
typography: { ...(style === null || style === void 0 ? void 0 : style.typography),
textDecoration: newDecoration
}
})
});
}
return (0,external_wp_element_namespaceObject.createElement)(TextDecorationControl, {
value: style === null || style === void 0 ? void 0 : (_style$typography = style.typography) === null || _style$typography === void 0 ? void 0 : _style$typography.textDecoration,
onChange: onChange,
size: "__unstable-large"
});
}
/**
* Checks if text-decoration settings have been disabled.
*
* @param {string} name Name of the block.
*
* @return {boolean} Whether or not the setting is disabled.
*/
function useIsTextDecorationDisabled() {
let {
name: blockName
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const notSupported = !(0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockName, text_decoration_TEXT_DECORATION_SUPPORT_KEY);
const hasTextDecoration = useSetting('typography.textDecoration');
return notSupported || !hasTextDecoration;
}
/**
* Checks if there is a current value set for the text decoration block support.
*
* @param {Object} props Block props.
* @return {boolean} Whether or not the block has a text decoration set.
*/
function hasTextDecorationValue(props) {
var _props$attributes$sty, _props$attributes$sty2;
return !!((_props$attributes$sty = props.attributes.style) !== null && _props$attributes$sty !== void 0 && (_props$attributes$sty2 = _props$attributes$sty.typography) !== null && _props$attributes$sty2 !== void 0 && _props$attributes$sty2.textDecoration);
}
/**
* Resets the text decoration block support attribute. This can be used when
* disabling the text decoration support controls for a block via a progressive
* discovery panel.
*
* @param {Object} props Block props.
* @param {Object} props.attributes Block's attributes.
* @param {Object} props.setAttributes Function to set block's attributes.
*/
function resetTextDecoration(_ref) {
let {
attributes = {},
setAttributes
} = _ref;
const {
style
} = attributes;
setAttributes({
style: utils_cleanEmptyObject({ ...style,
typography: { ...(style === null || style === void 0 ? void 0 : style.typography),
textDecoration: undefined
}
})
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/format-uppercase.js
/**
* WordPress dependencies
*/
const formatUppercase = (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: "M6.1 6.8L2.1 18h1.6l1.1-3h4.3l1.1 3h1.6l-4-11.2H6.1zm-.8 6.8L7 8.9l1.7 4.7H5.3zm15.1-.7c-.4-.5-.9-.8-1.6-1 .4-.2.7-.5.8-.9.2-.4.3-.9.3-1.4 0-.9-.3-1.6-.8-2-.6-.5-1.3-.7-2.4-.7h-3.5V18h4.2c1.1 0 2-.3 2.6-.8.6-.6 1-1.4 1-2.4-.1-.8-.3-1.4-.6-1.9zm-5.7-4.7h1.8c.6 0 1.1.1 1.4.4.3.2.5.7.5 1.3 0 .6-.2 1.1-.5 1.3-.3.2-.8.4-1.4.4h-1.8V8.2zm4 8c-.4.3-.9.5-1.5.5h-2.6v-3.8h2.6c1.4 0 2 .6 2 1.9.1.6-.1 1-.5 1.4z"
}));
/* harmony default export */ var format_uppercase = (formatUppercase);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/format-lowercase.js
/**
* WordPress dependencies
*/
const formatLowercase = (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: "M11 16.8c-.1-.1-.2-.3-.3-.5v-2.6c0-.9-.1-1.7-.3-2.2-.2-.5-.5-.9-.9-1.2-.4-.2-.9-.3-1.6-.3-.5 0-1 .1-1.5.2s-.9.3-1.2.6l.2 1.2c.4-.3.7-.4 1.1-.5.3-.1.7-.2 1-.2.6 0 1 .1 1.3.4.3.2.4.7.4 1.4-1.2 0-2.3.2-3.3.7s-1.4 1.1-1.4 2.1c0 .7.2 1.2.7 1.6.4.4 1 .6 1.8.6.9 0 1.7-.4 2.4-1.2.1.3.2.5.4.7.1.2.3.3.6.4.3.1.6.1 1.1.1h.1l.2-1.2h-.1c-.4.1-.6 0-.7-.1zM9.2 16c-.2.3-.5.6-.9.8-.3.1-.7.2-1.1.2-.4 0-.7-.1-.9-.3-.2-.2-.3-.5-.3-.9 0-.6.2-1 .7-1.3.5-.3 1.3-.4 2.5-.5v2zm10.6-3.9c-.3-.6-.7-1.1-1.2-1.5-.6-.4-1.2-.6-1.9-.6-.5 0-.9.1-1.4.3-.4.2-.8.5-1.1.8V6h-1.4v12h1.3l.2-1c.2.4.6.6 1 .8.4.2.9.3 1.4.3.7 0 1.2-.2 1.8-.5.5-.4 1-.9 1.3-1.5.3-.6.5-1.3.5-2.1-.1-.6-.2-1.3-.5-1.9zm-1.7 4c-.4.5-.9.8-1.6.8s-1.2-.2-1.7-.7c-.4-.5-.7-1.2-.7-2.1 0-.9.2-1.6.7-2.1.4-.5 1-.7 1.7-.7s1.2.3 1.6.8c.4.5.6 1.2.6 2s-.2 1.4-.6 2z"
}));
/* harmony default export */ var format_lowercase = (formatLowercase);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/format-capitalize.js
/**
* WordPress dependencies
*/
const formatCapitalize = (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: "M7.1 6.8L3.1 18h1.6l1.1-3h4.3l1.1 3h1.6l-4-11.2H7.1zm-.8 6.8L8 8.9l1.7 4.7H6.3zm14.5-1.5c-.3-.6-.7-1.1-1.2-1.5-.6-.4-1.2-.6-1.9-.6-.5 0-.9.1-1.4.3-.4.2-.8.5-1.1.8V6h-1.4v12h1.3l.2-1c.2.4.6.6 1 .8.4.2.9.3 1.4.3.7 0 1.2-.2 1.8-.5.5-.4 1-.9 1.3-1.5.3-.6.5-1.3.5-2.1-.1-.6-.2-1.3-.5-1.9zm-1.7 4c-.4.5-.9.8-1.6.8s-1.2-.2-1.7-.7c-.4-.5-.7-1.2-.7-2.1 0-.9.2-1.6.7-2.1.4-.5 1-.7 1.7-.7s1.2.3 1.6.8c.4.5.6 1.2.6 2 .1.8-.2 1.4-.6 2z"
}));
/* harmony default export */ var format_capitalize = (formatCapitalize);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/text-transform-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
const TEXT_TRANSFORMS = [{
name: (0,external_wp_i18n_namespaceObject.__)('None'),
value: 'none',
icon: library_reset
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Uppercase'),
value: 'uppercase',
icon: format_uppercase
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Lowercase'),
value: 'lowercase',
icon: format_lowercase
}, {
name: (0,external_wp_i18n_namespaceObject.__)('Capitalize'),
value: 'capitalize',
icon: format_capitalize
}];
/**
* Control to facilitate text transform selections.
*
* @param {Object} props Component props.
* @param {string} props.className Class name to add to the control.
* @param {string} props.value Currently selected text transform.
* @param {Function} props.onChange Handles change in text transform selection.
*
* @return {WPElement} Text transform control.
*/
function TextTransformControl(_ref) {
let {
className,
value,
onChange
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("fieldset", {
className: classnames_default()('block-editor-text-transform-control', className)
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.BaseControl.VisualLabel, {
as: "legend"
}, (0,external_wp_i18n_namespaceObject.__)('Letter case')), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-text-transform-control__buttons"
}, TEXT_TRANSFORMS.map(textTransform => {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
key: textTransform.value,
icon: textTransform.icon,
label: textTransform.name,
isPressed: textTransform.value === value,
onClick: () => {
onChange(textTransform.value === value ? undefined : textTransform.value);
}
});
})));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/text-transform.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Key within block settings' supports array indicating support for text
* transforms e.g. settings found in `block.json`.
*/
const text_transform_TEXT_TRANSFORM_SUPPORT_KEY = 'typography.__experimentalTextTransform';
/**
* Inspector control panel containing the text transform options.
*
* @param {Object} props Block properties.
*
* @return {WPElement} Text transform edit element.
*/
function TextTransformEdit(props) {
var _style$typography;
const {
attributes: {
style
},
setAttributes
} = props;
function onChange(newTransform) {
setAttributes({
style: utils_cleanEmptyObject({ ...style,
typography: { ...(style === null || style === void 0 ? void 0 : style.typography),
textTransform: newTransform
}
})
});
}
return (0,external_wp_element_namespaceObject.createElement)(TextTransformControl, {
value: style === null || style === void 0 ? void 0 : (_style$typography = style.typography) === null || _style$typography === void 0 ? void 0 : _style$typography.textTransform,
onChange: onChange,
size: "__unstable-large"
});
}
/**
* Checks if text-transform settings have been disabled.
*
* @param {string} name Name of the block.
*
* @return {boolean} Whether or not the setting is disabled.
*/
function useIsTextTransformDisabled() {
let {
name: blockName
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const notSupported = !(0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockName, text_transform_TEXT_TRANSFORM_SUPPORT_KEY);
const hasTextTransforms = useSetting('typography.textTransform');
return notSupported || !hasTextTransforms;
}
/**
* Checks if there is a current value set for the text transform block support.
*
* @param {Object} props Block props.
* @return {boolean} Whether or not the block has a text transform set.
*/
function hasTextTransformValue(props) {
var _props$attributes$sty, _props$attributes$sty2;
return !!((_props$attributes$sty = props.attributes.style) !== null && _props$attributes$sty !== void 0 && (_props$attributes$sty2 = _props$attributes$sty.typography) !== null && _props$attributes$sty2 !== void 0 && _props$attributes$sty2.textTransform);
}
/**
* Resets the text transform block support attribute. This can be used when
* disabling the text transform support controls for a block via a progressive
* discovery panel.
*
* @param {Object} props Block props.
* @param {Object} props.attributes Block's attributes.
* @param {Object} props.setAttributes Function to set block's attributes.
*/
function resetTextTransform(_ref) {
let {
attributes = {},
setAttributes
} = _ref;
const {
style
} = attributes;
setAttributes({
style: utils_cleanEmptyObject({ ...style,
typography: { ...(style === null || style === void 0 ? void 0 : style.typography),
textTransform: undefined
}
})
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/letter-spacing-control/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Control for letter-spacing.
*
* @param {Object} props Component props.
* @param {string} props.value Currently selected letter-spacing.
* @param {Function} props.onChange Handles change in letter-spacing selection.
* @param {string|number|undefined} props.__unstableInputWidth Input width to pass through to inner UnitControl. Should be a valid CSS value.
*
* @return {WPElement} Letter-spacing control.
*/
function LetterSpacingControl(_ref) {
let {
value,
onChange,
__unstableInputWidth = '60px',
...otherProps
} = _ref;
const units = (0,external_wp_components_namespaceObject.__experimentalUseCustomUnits)({
availableUnits: useSetting('spacing.units') || ['px', 'em', 'rem'],
defaultValues: {
px: 2,
em: 0.2,
rem: 0.2
}
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalUnitControl, _extends({}, otherProps, {
label: (0,external_wp_i18n_namespaceObject.__)('Letter spacing'),
value: value,
__unstableInputWidth: __unstableInputWidth,
units: units,
onChange: onChange
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/letter-spacing.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Key within block settings' supports array indicating support for letter-spacing
* e.g. settings found in `block.json`.
*/
const letter_spacing_LETTER_SPACING_SUPPORT_KEY = 'typography.__experimentalLetterSpacing';
/**
* Inspector control panel containing the letter-spacing options.
*
* @param {Object} props Block properties.
* @return {WPElement} Letter-spacing edit element.
*/
function LetterSpacingEdit(props) {
var _style$typography;
const {
attributes: {
style
},
setAttributes
} = props;
function onChange(newSpacing) {
setAttributes({
style: utils_cleanEmptyObject({ ...style,
typography: { ...(style === null || style === void 0 ? void 0 : style.typography),
letterSpacing: newSpacing
}
})
});
}
return (0,external_wp_element_namespaceObject.createElement)(LetterSpacingControl, {
value: style === null || style === void 0 ? void 0 : (_style$typography = style.typography) === null || _style$typography === void 0 ? void 0 : _style$typography.letterSpacing,
onChange: onChange,
__unstableInputWidth: '100%',
size: "__unstable-large"
});
}
/**
* Checks if letter-spacing settings have been disabled.
*
* @param {string} name Name of the block.
* @return {boolean} Whether or not the setting is disabled.
*/
function useIsLetterSpacingDisabled() {
let {
name: blockName
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const notSupported = !(0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockName, letter_spacing_LETTER_SPACING_SUPPORT_KEY);
const hasLetterSpacing = useSetting('typography.letterSpacing');
return notSupported || !hasLetterSpacing;
}
/**
* Checks if there is a current value set for the letter spacing block support.
*
* @param {Object} props Block props.
* @return {boolean} Whether or not the block has a letter spacing set.
*/
function hasLetterSpacingValue(props) {
var _props$attributes$sty, _props$attributes$sty2;
return !!((_props$attributes$sty = props.attributes.style) !== null && _props$attributes$sty !== void 0 && (_props$attributes$sty2 = _props$attributes$sty.typography) !== null && _props$attributes$sty2 !== void 0 && _props$attributes$sty2.letterSpacing);
}
/**
* Resets the letter spacing block support attribute. This can be used when
* disabling the letter spacing support controls for a block via a progressive
* discovery panel.
*
* @param {Object} props Block props.
* @param {Object} props.attributes Block's attributes.
* @param {Object} props.setAttributes Function to set block's attributes.
*/
function resetLetterSpacing(_ref) {
let {
attributes = {},
setAttributes
} = _ref;
const {
style
} = attributes;
setAttributes({
style: utils_cleanEmptyObject({ ...style,
typography: { ...(style === null || style === void 0 ? void 0 : style.typography),
letterSpacing: undefined
}
})
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/typography.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const TYPOGRAPHY_SUPPORT_KEY = 'typography';
const typography_TYPOGRAPHY_SUPPORT_KEYS = [line_height_LINE_HEIGHT_SUPPORT_KEY, font_size_FONT_SIZE_SUPPORT_KEY, font_appearance_FONT_STYLE_SUPPORT_KEY, font_appearance_FONT_WEIGHT_SUPPORT_KEY, font_family_FONT_FAMILY_SUPPORT_KEY, text_decoration_TEXT_DECORATION_SUPPORT_KEY, text_transform_TEXT_TRANSFORM_SUPPORT_KEY, letter_spacing_LETTER_SPACING_SUPPORT_KEY];
function TypographyPanel(props) {
const {
clientId
} = props;
const isFontFamilyDisabled = useIsFontFamilyDisabled(props);
const isFontSizeDisabled = useIsFontSizeDisabled(props);
const isFontAppearanceDisabled = useIsFontAppearanceDisabled(props);
const isLineHeightDisabled = useIsLineHeightDisabled(props);
const isTextDecorationDisabled = useIsTextDecorationDisabled(props);
const isTextTransformDisabled = useIsTextTransformDisabled(props);
const isLetterSpacingDisabled = useIsLetterSpacingDisabled(props);
const hasFontStyles = !useIsFontStyleDisabled(props);
const hasFontWeights = !useIsFontWeightDisabled(props);
const isDisabled = useIsTypographyDisabled(props);
const isSupported = hasTypographySupport(props.name);
if (isDisabled || !isSupported) return null;
const defaultControls = (0,external_wp_blocks_namespaceObject.getBlockSupport)(props.name, [TYPOGRAPHY_SUPPORT_KEY, '__experimentalDefaultControls']);
const createResetAllFilter = attribute => newAttributes => {
var _newAttributes$style;
return { ...newAttributes,
style: { ...newAttributes.style,
typography: { ...((_newAttributes$style = newAttributes.style) === null || _newAttributes$style === void 0 ? void 0 : _newAttributes$style.typography),
[attribute]: undefined
}
}
};
};
return (0,external_wp_element_namespaceObject.createElement)(inspector_controls, {
group: "typography"
}, !isFontFamilyDisabled && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToolsPanelItem, {
hasValue: () => hasFontFamilyValue(props),
label: (0,external_wp_i18n_namespaceObject.__)('Font family'),
onDeselect: () => resetFontFamily(props),
isShownByDefault: defaultControls === null || defaultControls === void 0 ? void 0 : defaultControls.fontFamily,
resetAllFilter: newAttributes => ({ ...newAttributes,
fontFamily: undefined
}),
panelId: clientId
}, (0,external_wp_element_namespaceObject.createElement)(FontFamilyEdit, props)), !isFontSizeDisabled && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToolsPanelItem, {
hasValue: () => hasFontSizeValue(props)
/* translators: Ensure translation is distinct from "Letter case" */
,
label: (0,external_wp_i18n_namespaceObject.__)('Font size'),
onDeselect: () => resetFontSize(props),
isShownByDefault: defaultControls === null || defaultControls === void 0 ? void 0 : defaultControls.fontSize,
resetAllFilter: newAttributes => {
var _newAttributes$style2;
return { ...newAttributes,
fontSize: undefined,
style: { ...newAttributes.style,
typography: { ...((_newAttributes$style2 = newAttributes.style) === null || _newAttributes$style2 === void 0 ? void 0 : _newAttributes$style2.typography),
fontSize: undefined
}
}
};
},
panelId: clientId
}, (0,external_wp_element_namespaceObject.createElement)(FontSizeEdit, props)), !isFontAppearanceDisabled && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToolsPanelItem, {
className: "single-column",
hasValue: () => hasFontAppearanceValue(props),
label: getFontAppearanceLabel(hasFontStyles, hasFontWeights),
onDeselect: () => resetFontAppearance(props),
isShownByDefault: defaultControls === null || defaultControls === void 0 ? void 0 : defaultControls.fontAppearance,
resetAllFilter: newAttributes => {
var _newAttributes$style3;
return { ...newAttributes,
style: { ...newAttributes.style,
typography: { ...((_newAttributes$style3 = newAttributes.style) === null || _newAttributes$style3 === void 0 ? void 0 : _newAttributes$style3.typography),
fontStyle: undefined,
fontWeight: undefined
}
}
};
},
panelId: clientId
}, (0,external_wp_element_namespaceObject.createElement)(FontAppearanceEdit, props)), !isLineHeightDisabled && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToolsPanelItem, {
className: "single-column",
hasValue: () => hasLineHeightValue(props),
label: (0,external_wp_i18n_namespaceObject.__)('Line height'),
onDeselect: () => resetLineHeight(props),
isShownByDefault: defaultControls === null || defaultControls === void 0 ? void 0 : defaultControls.lineHeight,
resetAllFilter: createResetAllFilter('lineHeight'),
panelId: clientId
}, (0,external_wp_element_namespaceObject.createElement)(LineHeightEdit, props)), !isLetterSpacingDisabled && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToolsPanelItem, {
className: "single-column",
hasValue: () => hasLetterSpacingValue(props),
label: (0,external_wp_i18n_namespaceObject.__)('Letter spacing'),
onDeselect: () => resetLetterSpacing(props),
isShownByDefault: defaultControls === null || defaultControls === void 0 ? void 0 : defaultControls.letterSpacing,
resetAllFilter: createResetAllFilter('letterSpacing'),
panelId: clientId
}, (0,external_wp_element_namespaceObject.createElement)(LetterSpacingEdit, props)), !isTextDecorationDisabled && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToolsPanelItem, {
className: "single-column",
hasValue: () => hasTextDecorationValue(props),
label: (0,external_wp_i18n_namespaceObject.__)('Decoration'),
onDeselect: () => resetTextDecoration(props),
isShownByDefault: defaultControls === null || defaultControls === void 0 ? void 0 : defaultControls.textDecoration,
resetAllFilter: createResetAllFilter('textDecoration'),
panelId: clientId
}, (0,external_wp_element_namespaceObject.createElement)(TextDecorationEdit, props)), !isTextTransformDisabled && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToolsPanelItem, {
hasValue: () => hasTextTransformValue(props)
/* translators: Ensure translation is distinct from "Font size" */
,
label: (0,external_wp_i18n_namespaceObject.__)('Letter case'),
onDeselect: () => resetTextTransform(props),
isShownByDefault: defaultControls === null || defaultControls === void 0 ? void 0 : defaultControls.textTransform,
resetAllFilter: createResetAllFilter('textTransform'),
panelId: clientId
}, (0,external_wp_element_namespaceObject.createElement)(TextTransformEdit, props)));
}
const hasTypographySupport = blockName => {
return typography_TYPOGRAPHY_SUPPORT_KEYS.some(key => (0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockName, key));
};
function useIsTypographyDisabled() {
let props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const configs = [useIsFontAppearanceDisabled(props), useIsFontSizeDisabled(props), useIsLineHeightDisabled(props), useIsFontFamilyDisabled(props), useIsTextDecorationDisabled(props), useIsTextTransformDisabled(props), useIsLetterSpacingDisabled(props)];
return configs.filter(Boolean).length === configs.length;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/style.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const style_styleSupportKeys = [...typography_TYPOGRAPHY_SUPPORT_KEYS, border_BORDER_SUPPORT_KEY, color_COLOR_SUPPORT_KEY, DIMENSIONS_SUPPORT_KEY, SPACING_SUPPORT_KEY];
const style_hasStyleSupport = blockType => style_styleSupportKeys.some(key => (0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockType, key));
/**
* Returns the inline styles to add depending on the style object
*
* @param {Object} styles Styles configuration.
*
* @return {Object} Flattened CSS variables declaration.
*/
function getInlineStyles() {
let styles = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const output = {}; // The goal is to move everything to server side generated engine styles
// This is temporary as we absorb more and more styles into the engine.
(0,external_wp_styleEngine_namespaceObject.getCSSRules)(styles).forEach(rule => {
output[rule.key] = rule.value;
});
return output;
}
/**
* Filters registered block settings, extending attributes to include `style` attribute.
*
* @param {Object} settings Original block settings.
*
* @return {Object} Filtered block settings.
*/
function style_addAttribute(settings) {
if (!style_hasStyleSupport(settings)) {
return settings;
} // Allow blocks to specify their own attribute definition with default values if needed.
if (!settings.attributes.style) {
Object.assign(settings.attributes, {
style: {
type: 'object'
}
});
}
return settings;
}
/**
* A dictionary of paths to flag skipping block support serialization as the key,
* with values providing the style paths to be omitted from serialization.
*
* @constant
* @type {Record<string, string[]>}
*/
const skipSerializationPathsEdit = {
[`${border_BORDER_SUPPORT_KEY}.__experimentalSkipSerialization`]: ['border'],
[`${color_COLOR_SUPPORT_KEY}.__experimentalSkipSerialization`]: [color_COLOR_SUPPORT_KEY],
[`${TYPOGRAPHY_SUPPORT_KEY}.__experimentalSkipSerialization`]: [TYPOGRAPHY_SUPPORT_KEY],
[`${DIMENSIONS_SUPPORT_KEY}.__experimentalSkipSerialization`]: [DIMENSIONS_SUPPORT_KEY],
[`${SPACING_SUPPORT_KEY}.__experimentalSkipSerialization`]: [SPACING_SUPPORT_KEY]
};
/**
* A dictionary of paths to flag skipping block support serialization as the key,
* with values providing the style paths to be omitted from serialization.
*
* Extends the Edit skip paths to enable skipping additional paths in just
* the Save component. This allows a block support to be serialized within the
* editor, while using an alternate approach, such as server-side rendering, when
* the support is saved.
*
* @constant
* @type {Record<string, string[]>}
*/
const skipSerializationPathsSave = { ...skipSerializationPathsEdit,
[`${SPACING_SUPPORT_KEY}`]: ['spacing.blockGap']
};
/**
* A dictionary used to normalize feature names between support flags, style
* object properties and __experimentSkipSerialization configuration arrays.
*
* This allows not having to provide a migration for a support flag and possible
* backwards compatibility bridges, while still achieving consistency between
* the support flag and the skip serialization array.
*
* @constant
* @type {Record<string, string>}
*/
const renamedFeatures = {
gradients: 'gradient'
};
/**
* A utility function used to remove one or more paths from a style object.
* Works in a way similar to Lodash's `omit()`. See unit tests and examples below.
*
* It supports a single string path:
*
* ```
* omitStyle( { color: 'red' }, 'color' ); // {}
* ```
*
* or an array of paths:
*
* ```
* omitStyle( { color: 'red', background: '#fff' }, [ 'color', 'background' ] ); // {}
* ```
*
* It also allows you to specify paths at multiple levels in a string.
*
* ```
* omitStyle( { typography: { textDecoration: 'underline' } }, 'typography.textDecoration' ); // {}
* ```
*
* You can remove multiple paths at the same time:
*
* ```
* omitStyle(
* {
* typography: {
* textDecoration: 'underline',
* textTransform: 'uppercase',
* }
* },
* [
* 'typography.textDecoration',
* 'typography.textTransform',
* ]
* );
* // {}
* ```
*
* You can also specify nested paths as arrays:
*
* ```
* omitStyle(
* {
* typography: {
* textDecoration: 'underline',
* textTransform: 'uppercase',
* }
* },
* [
* [ 'typography', 'textDecoration' ],
* [ 'typography', 'textTransform' ],
* ]
* );
* // {}
* ```
*
* With regards to nesting of styles, infinite depth is supported:
*
* ```
* omitStyle(
* {
* border: {
* radius: {
* topLeft: '10px',
* topRight: '0.5rem',
* }
* }
* },
* [
* [ 'border', 'radius', 'topRight' ],
* ]
* );
* // { border: { radius: { topLeft: '10px' } } }
* ```
*
* The third argument, `preserveReference`, defines how to treat the input style object.
* It is mostly necessary to properly handle mutation when recursively handling the style object.
* Defaulting to `false`, this will always create a new object, avoiding to mutate `style`.
* However, when recursing, we change that value to `true` in order to work with a single copy
* of the original style object.
*
* @see https://lodash.com/docs/4.17.15#omit
*
* @param {Object} style Styles object.
* @param {Array|string} paths Paths to remove.
* @param {boolean} preserveReference True to mutate the `style` object, false otherwise.
* @return {Object} Styles object with the specified paths removed.
*/
function omitStyle(style, paths) {
let preserveReference = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (!style) {
return style;
}
let newStyle = style;
if (!preserveReference) {
newStyle = JSON.parse(JSON.stringify(style));
}
if (!Array.isArray(paths)) {
paths = [paths];
}
paths.forEach(path => {
if (!Array.isArray(path)) {
path = path.split('.');
}
if (path.length > 1) {
const [firstSubpath, ...restPath] = path;
omitStyle(newStyle[firstSubpath], [restPath], true);
} else if (path.length === 1) {
delete newStyle[path[0]];
}
});
return newStyle;
}
/**
* Override props assigned to save component to inject the CSS variables definition.
*
* @param {Object} props Additional props applied to save element.
* @param {Object} blockType Block type.
* @param {Object} attributes Block attributes.
* @param {?Record<string, string[]>} skipPaths An object of keys and paths to skip serialization.
*
* @return {Object} Filtered props applied to save element.
*/
function style_addSaveProps(props, blockType, attributes) {
let skipPaths = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : skipSerializationPathsSave;
if (!style_hasStyleSupport(blockType)) {
return props;
}
let {
style
} = attributes;
Object.entries(skipPaths).forEach(_ref => {
let [indicator, path] = _ref;
const skipSerialization = (0,external_wp_blocks_namespaceObject.getBlockSupport)(blockType, indicator);
if (skipSerialization === true) {
style = omitStyle(style, path);
}
if (Array.isArray(skipSerialization)) {
skipSerialization.forEach(featureName => {
const feature = renamedFeatures[featureName] || featureName;
style = omitStyle(style, [[...path, feature]]);
});
}
});
props.style = { ...getInlineStyles(style),
...props.style
};
return props;
}
/**
* Filters registered block settings to extend the block edit wrapper
* to apply the desired styles and classnames properly.
*
* @param {Object} settings Original block settings.
*
* @return {Object}.Filtered block settings.
*/
function style_addEditProps(settings) {
if (!style_hasStyleSupport(settings)) {
return settings;
}
const existingGetEditWrapperProps = settings.getEditWrapperProps;
settings.getEditWrapperProps = attributes => {
let props = {};
if (existingGetEditWrapperProps) {
props = existingGetEditWrapperProps(attributes);
}
return style_addSaveProps(props, settings, attributes, skipSerializationPathsEdit);
};
return settings;
}
/**
* Override the default edit UI to include new inspector controls for
* all the custom styles configs.
*
* @param {Function} BlockEdit Original component.
*
* @return {Function} Wrapped component.
*/
const withBlockControls = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(BlockEdit => props => {
const shouldDisplayControls = useDisplayBlockControls();
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, shouldDisplayControls && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(ColorEdit, props), (0,external_wp_element_namespaceObject.createElement)(TypographyPanel, props), (0,external_wp_element_namespaceObject.createElement)(BorderPanel, props), (0,external_wp_element_namespaceObject.createElement)(DimensionsPanel, props)), (0,external_wp_element_namespaceObject.createElement)(BlockEdit, props));
}, 'withToolbarControls');
/**
* Override the default block element to include elements styles.
*
* @param {Function} BlockListBlock Original component
* @return {Function} Wrapped component
*/
const withElementsStyles = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(BlockListBlock => props => {
var _props$attributes$sty2, _props$attributes$sty3;
const blockElementsContainerIdentifier = `wp-elements-${(0,external_wp_compose_namespaceObject.useInstanceId)(BlockListBlock)}`;
const skipLinkColorSerialization = shouldSkipSerialization(props.name, color_COLOR_SUPPORT_KEY, 'link');
const styles = (0,external_wp_element_namespaceObject.useMemo)(() => {
var _props$attributes$sty;
const rawElementsStyles = (_props$attributes$sty = props.attributes.style) === null || _props$attributes$sty === void 0 ? void 0 : _props$attributes$sty.elements;
const elementCssRules = [];
if (rawElementsStyles && Object.keys(rawElementsStyles).length > 0) {
var _rawElementsStyles$li;
// Remove values based on whether serialization has been skipped for a specific style.
const filteredElementsStyles = { ...rawElementsStyles,
link: { ...rawElementsStyles.link,
color: !skipLinkColorSerialization ? (_rawElementsStyles$li = rawElementsStyles.link) === null || _rawElementsStyles$li === void 0 ? void 0 : _rawElementsStyles$li.color : undefined
}
};
for (const [elementName, elementStyles] of Object.entries(filteredElementsStyles)) {
const cssRule = (0,external_wp_styleEngine_namespaceObject.compileCSS)(elementStyles, {
// The .editor-styles-wrapper selector is required on elements styles. As it is
// added to all other editor styles, not providing it causes reset and global
// styles to override element styles because of higher specificity.
selector: `.editor-styles-wrapper .${blockElementsContainerIdentifier} ${external_wp_blocks_namespaceObject.__EXPERIMENTAL_ELEMENTS[elementName]}`
});
if (!!cssRule) {
elementCssRules.push(cssRule);
}
}
}
return elementCssRules.length > 0 ? elementCssRules : undefined;
}, [(_props$attributes$sty2 = props.attributes.style) === null || _props$attributes$sty2 === void 0 ? void 0 : _props$attributes$sty2.elements]);
const element = (0,external_wp_element_namespaceObject.useContext)(BlockList.__unstableElementContext);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, styles && element && (0,external_wp_element_namespaceObject.createPortal)((0,external_wp_element_namespaceObject.createElement)("style", {
dangerouslySetInnerHTML: {
__html: styles
}
}), element), (0,external_wp_element_namespaceObject.createElement)(BlockListBlock, _extends({}, props, {
className: (_props$attributes$sty3 = props.attributes.style) !== null && _props$attributes$sty3 !== void 0 && _props$attributes$sty3.elements ? classnames_default()(props.className, blockElementsContainerIdentifier) : props.className
})));
});
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'core/style/addAttribute', style_addAttribute);
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.getSaveContent.extraProps', 'core/style/addSaveProps', style_addSaveProps);
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'core/style/addEditProps', style_addEditProps);
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockEdit', 'core/style/with-block-controls', withBlockControls);
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockListBlock', 'core/editor/with-elements-styles', withElementsStyles);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/settings.js
/**
* WordPress dependencies
*/
const hasSettingsSupport = blockType => (0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockType, '__experimentalSettings', false);
function settings_addAttribute(settings) {
var _settings$attributes;
if (!hasSettingsSupport(settings)) {
return settings;
} // Allow blocks to specify their own attribute definition with default values if needed.
if (!(settings !== null && settings !== void 0 && (_settings$attributes = settings.attributes) !== null && _settings$attributes !== void 0 && _settings$attributes.settings)) {
settings.attributes = { ...settings.attributes,
settings: {
type: 'object'
}
};
}
return settings;
}
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'core/settings/addAttribute', settings_addAttribute);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/filter.js
/**
* WordPress dependencies
*/
const filter = (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: "M12 4 4 19h16L12 4zm0 3.2 5.5 10.3H12V7.2z"
}));
/* harmony default export */ var library_filter = (filter);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/duotone-control/index.js
/**
* WordPress dependencies
*/
function DuotoneControl(_ref) {
let {
colorPalette,
duotonePalette,
disableCustomColors,
disableCustomDuotone,
value,
onChange
} = _ref;
let toolbarIcon;
if (value === 'unset') {
toolbarIcon = (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ColorIndicator, {
className: "block-editor-duotone-control__unset-indicator"
});
} else if (value) {
toolbarIcon = (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.DuotoneSwatch, {
values: value
});
} else {
toolbarIcon = (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: library_filter
});
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Dropdown, {
popoverProps: {
className: 'block-editor-duotone-control__popover',
headerTitle: (0,external_wp_i18n_namespaceObject.__)('Duotone'),
variant: 'toolbar'
},
renderToggle: _ref2 => {
let {
isOpen,
onToggle
} = _ref2;
const openOnArrowDown = event => {
if (!isOpen && event.keyCode === external_wp_keycodes_namespaceObject.DOWN) {
event.preventDefault();
onToggle();
}
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
showTooltip: true,
onClick: onToggle,
"aria-haspopup": "true",
"aria-expanded": isOpen,
onKeyDown: openOnArrowDown,
label: (0,external_wp_i18n_namespaceObject.__)('Apply duotone filter'),
icon: toolbarIcon
});
},
renderContent: () => (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, {
label: (0,external_wp_i18n_namespaceObject.__)('Duotone')
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-duotone-control__description"
}, (0,external_wp_i18n_namespaceObject.__)('Create a two-tone color effect without losing your original image.')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.DuotonePicker, {
colorPalette: colorPalette,
duotonePalette: duotonePalette,
disableCustomColors: disableCustomColors,
disableCustomDuotone: disableCustomDuotone,
value: value,
onChange: onChange
}))
});
}
/* harmony default export */ var duotone_control = (DuotoneControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/duotone.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const duotone_EMPTY_ARRAY = [];
k([names]);
/**
* SVG and stylesheet needed for rendering the duotone filter.
*
* @param {Object} props Duotone props.
* @param {string} props.selector Selector to apply the filter to.
* @param {string} props.id Unique id for this duotone filter.
* @param {string[]|"unset"} props.colors Array of RGB color strings ordered from dark to light.
*
* @return {WPElement} Duotone element.
*/
function InlineDuotone(_ref) {
let {
selector,
id,
colors
} = _ref;
if (colors === 'unset') {
return (0,external_wp_element_namespaceObject.createElement)(DuotoneUnsetStylesheet, {
selector: selector
});
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(DuotoneFilter, {
id: id,
colors: colors
}), (0,external_wp_element_namespaceObject.createElement)(DuotoneStylesheet, {
id: id,
selector: selector
}));
}
function useMultiOriginPresets(_ref2) {
let {
presetSetting,
defaultSetting
} = _ref2;
const disableDefault = !useSetting(defaultSetting);
const userPresets = useSetting(`${presetSetting}.custom`) || duotone_EMPTY_ARRAY;
const themePresets = useSetting(`${presetSetting}.theme`) || duotone_EMPTY_ARRAY;
const defaultPresets = useSetting(`${presetSetting}.default`) || duotone_EMPTY_ARRAY;
return (0,external_wp_element_namespaceObject.useMemo)(() => [...userPresets, ...themePresets, ...(disableDefault ? duotone_EMPTY_ARRAY : defaultPresets)], [disableDefault, userPresets, themePresets, defaultPresets]);
}
function DuotonePanel(_ref3) {
var _style$color;
let {
attributes,
setAttributes
} = _ref3;
const style = attributes === null || attributes === void 0 ? void 0 : attributes.style;
const duotone = style === null || style === void 0 ? void 0 : (_style$color = style.color) === null || _style$color === void 0 ? void 0 : _style$color.duotone;
const duotonePalette = useMultiOriginPresets({
presetSetting: 'color.duotone',
defaultSetting: 'color.defaultDuotone'
});
const colorPalette = useMultiOriginPresets({
presetSetting: 'color.palette',
defaultSetting: 'color.defaultPalette'
});
const disableCustomColors = !useSetting('color.custom');
const disableCustomDuotone = !useSetting('color.customDuotone') || (colorPalette === null || colorPalette === void 0 ? void 0 : colorPalette.length) === 0 && disableCustomColors;
if ((duotonePalette === null || duotonePalette === void 0 ? void 0 : duotonePalette.length) === 0 && disableCustomDuotone) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(block_controls, {
group: "block",
__experimentalShareWithChildBlocks: true
}, (0,external_wp_element_namespaceObject.createElement)(duotone_control, {
duotonePalette: duotonePalette,
colorPalette: colorPalette,
disableCustomDuotone: disableCustomDuotone,
disableCustomColors: disableCustomColors,
value: duotone,
onChange: newDuotone => {
const newStyle = { ...style,
color: { ...(style === null || style === void 0 ? void 0 : style.color),
duotone: newDuotone
}
};
setAttributes({
style: newStyle
});
}
}));
}
/**
* Filters registered block settings, extending attributes to include
* the `duotone` attribute.
*
* @param {Object} settings Original block settings.
*
* @return {Object} Filtered block settings.
*/
function addDuotoneAttributes(settings) {
if (!(0,external_wp_blocks_namespaceObject.hasBlockSupport)(settings, 'color.__experimentalDuotone')) {
return settings;
} // Allow blocks to specify their own attribute definition with default
// values if needed.
if (!settings.attributes.style) {
Object.assign(settings.attributes, {
style: {
type: 'object'
}
});
}
return settings;
}
/**
* Override the default edit UI to include toolbar controls for duotone if the
* block supports duotone.
*
* @param {Function} BlockEdit Original component.
*
* @return {Function} Wrapped component.
*/
const withDuotoneControls = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(BlockEdit => props => {
const hasDuotoneSupport = (0,external_wp_blocks_namespaceObject.hasBlockSupport)(props.name, 'color.__experimentalDuotone');
const isContentLocked = (0,external_wp_data_namespaceObject.useSelect)(select => {
return select(store).__unstableGetContentLockingParent(props.clientId);
}, [props.clientId]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(BlockEdit, props), hasDuotoneSupport && !isContentLocked && (0,external_wp_element_namespaceObject.createElement)(DuotonePanel, props));
}, 'withDuotoneControls');
/**
* Function that scopes a selector with another one. This works a bit like
* SCSS nesting except the `&` operator isn't supported.
*
* @example
* ```js
* const scope = '.a, .b .c';
* const selector = '> .x, .y';
* const merged = scopeSelector( scope, selector );
* // merged is '.a > .x, .a .y, .b .c > .x, .b .c .y'
* ```
*
* @param {string} scope Selector to scope to.
* @param {string} selector Original selector.
*
* @return {string} Scoped selector.
*/
function scopeSelector(scope, selector) {
const scopes = scope.split(',');
const selectors = selector.split(',');
const selectorsScoped = [];
scopes.forEach(outer => {
selectors.forEach(inner => {
selectorsScoped.push(`${outer.trim()} ${inner.trim()}`);
});
});
return selectorsScoped.join(', ');
}
/**
* Override the default block element to include duotone styles.
*
* @param {Function} BlockListBlock Original component.
*
* @return {Function} Wrapped component.
*/
const withDuotoneStyles = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(BlockListBlock => props => {
var _props$attributes, _props$attributes$sty, _props$attributes$sty2;
const duotoneSupport = (0,external_wp_blocks_namespaceObject.getBlockSupport)(props.name, 'color.__experimentalDuotone');
const colors = props === null || props === void 0 ? void 0 : (_props$attributes = props.attributes) === null || _props$attributes === void 0 ? void 0 : (_props$attributes$sty = _props$attributes.style) === null || _props$attributes$sty === void 0 ? void 0 : (_props$attributes$sty2 = _props$attributes$sty.color) === null || _props$attributes$sty2 === void 0 ? void 0 : _props$attributes$sty2.duotone;
if (!duotoneSupport || !colors) {
return (0,external_wp_element_namespaceObject.createElement)(BlockListBlock, props);
}
const id = `wp-duotone-${(0,external_wp_compose_namespaceObject.useInstanceId)(BlockListBlock)}`; // Extra .editor-styles-wrapper specificity is needed in the editor
// since we're not using inline styles to apply the filter. We need to
// override duotone applied by global styles and theme.json.
const selectorsGroup = scopeSelector(`.editor-styles-wrapper .${id}`, duotoneSupport);
const className = classnames_default()(props === null || props === void 0 ? void 0 : props.className, id);
const element = (0,external_wp_element_namespaceObject.useContext)(BlockList.__unstableElementContext);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, element && (0,external_wp_element_namespaceObject.createPortal)((0,external_wp_element_namespaceObject.createElement)(InlineDuotone, {
selector: selectorsGroup,
id: id,
colors: colors
}), element), (0,external_wp_element_namespaceObject.createElement)(BlockListBlock, _extends({}, props, {
className: className
})));
}, 'withDuotoneStyles');
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'core/editor/duotone/add-attributes', addDuotoneAttributes);
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockEdit', 'core/editor/duotone/with-editor-controls', withDuotoneControls);
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockListBlock', 'core/editor/duotone/with-styles', withDuotoneStyles);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/layout.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const layoutBlockSupportKey = '__experimentalLayout';
/**
* Generates the utility classnames for the given block's layout attributes.
*
* @param { Object } block Block object.
*
* @return { Array } Array of CSS classname strings.
*/
function useLayoutClasses() {
var _globalLayoutSettings, _globalLayoutSettings2;
let block = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const rootPaddingAlignment = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _getSettings$__experi;
const {
getSettings
} = select(store);
return (_getSettings$__experi = getSettings().__experimentalFeatures) === null || _getSettings$__experi === void 0 ? void 0 : _getSettings$__experi.useRootPaddingAwareAlignments;
}, []);
const globalLayoutSettings = useSetting('layout') || {};
const {
attributes = {},
name
} = block;
const {
layout
} = attributes;
const {
default: defaultBlockLayout
} = (0,external_wp_blocks_namespaceObject.getBlockSupport)(name, layoutBlockSupportKey) || {};
const usedLayout = layout !== null && layout !== void 0 && layout.inherit || layout !== null && layout !== void 0 && layout.contentSize || layout !== null && layout !== void 0 && layout.wideSize ? { ...layout,
type: 'constrained'
} : layout || defaultBlockLayout || {};
const layoutClassnames = [];
if (globalLayoutSettings !== null && globalLayoutSettings !== void 0 && (_globalLayoutSettings = globalLayoutSettings.definitions) !== null && _globalLayoutSettings !== void 0 && (_globalLayoutSettings2 = _globalLayoutSettings[(usedLayout === null || usedLayout === void 0 ? void 0 : usedLayout.type) || 'default']) !== null && _globalLayoutSettings2 !== void 0 && _globalLayoutSettings2.className) {
var _globalLayoutSettings3, _globalLayoutSettings4;
layoutClassnames.push(globalLayoutSettings === null || globalLayoutSettings === void 0 ? void 0 : (_globalLayoutSettings3 = globalLayoutSettings.definitions) === null || _globalLayoutSettings3 === void 0 ? void 0 : (_globalLayoutSettings4 = _globalLayoutSettings3[(usedLayout === null || usedLayout === void 0 ? void 0 : usedLayout.type) || 'default']) === null || _globalLayoutSettings4 === void 0 ? void 0 : _globalLayoutSettings4.className);
}
if ((usedLayout !== null && usedLayout !== void 0 && usedLayout.inherit || usedLayout !== null && usedLayout !== void 0 && usedLayout.contentSize || (usedLayout === null || usedLayout === void 0 ? void 0 : usedLayout.type) === 'constrained') && rootPaddingAlignment) {
layoutClassnames.push('has-global-padding');
}
if (usedLayout !== null && usedLayout !== void 0 && usedLayout.orientation) {
layoutClassnames.push(`is-${(0,external_lodash_namespaceObject.kebabCase)(usedLayout.orientation)}`);
}
if (usedLayout !== null && usedLayout !== void 0 && usedLayout.justifyContent) {
layoutClassnames.push(`is-content-justification-${(0,external_lodash_namespaceObject.kebabCase)(usedLayout.justifyContent)}`);
}
if (usedLayout !== null && usedLayout !== void 0 && usedLayout.flexWrap && usedLayout.flexWrap === 'nowrap') {
layoutClassnames.push('is-nowrap');
}
return layoutClassnames;
}
/**
* Generates a CSS rule with the given block's layout styles.
*
* @param { Object } block Block object.
* @param { string } selector A selector to use in generating the CSS rule.
*
* @return { string } CSS rule.
*/
function useLayoutStyles() {
var _fullLayoutType$getLa;
let block = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let selector = arguments.length > 1 ? arguments[1] : undefined;
const {
attributes = {},
name
} = block;
const {
layout = {},
style = {}
} = attributes; // Update type for blocks using legacy layouts.
const usedLayout = layout !== null && layout !== void 0 && layout.inherit || layout !== null && layout !== void 0 && layout.contentSize || layout !== null && layout !== void 0 && layout.wideSize ? { ...layout,
type: 'constrained'
} : layout || {};
const fullLayoutType = getLayoutType((usedLayout === null || usedLayout === void 0 ? void 0 : usedLayout.type) || 'default');
const globalLayoutSettings = useSetting('layout') || {};
const blockGapSupport = useSetting('spacing.blockGap');
const hasBlockGapSupport = blockGapSupport !== null;
const css = fullLayoutType === null || fullLayoutType === void 0 ? void 0 : (_fullLayoutType$getLa = fullLayoutType.getLayoutStyle) === null || _fullLayoutType$getLa === void 0 ? void 0 : _fullLayoutType$getLa.call(fullLayoutType, {
blockName: name,
selector,
layout,
layoutDefinitions: globalLayoutSettings === null || globalLayoutSettings === void 0 ? void 0 : globalLayoutSettings.definitions,
style,
hasBlockGapSupport
});
return css;
}
function LayoutPanel(_ref) {
let {
setAttributes,
attributes,
name: blockName
} = _ref;
const {
layout
} = attributes;
const defaultThemeLayout = useSetting('layout');
const themeSupportsLayout = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getSettings
} = select(store);
return getSettings().supportsLayout;
}, []);
const layoutBlockSupport = (0,external_wp_blocks_namespaceObject.getBlockSupport)(blockName, layoutBlockSupportKey, {});
const {
allowSwitching,
allowEditing = true,
allowInheriting = true,
default: defaultBlockLayout
} = layoutBlockSupport;
if (!allowEditing) {
return null;
} // Only show the inherit toggle if it's supported,
// a default theme layout is set (e.g. one that provides `contentSize` and/or `wideSize` values),
// and either the default / flow or the constrained layout type is in use, as the toggle switches from one to the other.
const showInheritToggle = !!(allowInheriting && !!defaultThemeLayout && (!(layout !== null && layout !== void 0 && layout.type) || (layout === null || layout === void 0 ? void 0 : layout.type) === 'default' || (layout === null || layout === void 0 ? void 0 : layout.type) === 'constrained' || layout !== null && layout !== void 0 && layout.inherit));
const usedLayout = layout || defaultBlockLayout || {};
const {
inherit = false,
type = 'default',
contentSize = null
} = usedLayout;
/**
* `themeSupportsLayout` is only relevant to the `default/flow` or
* `constrained` layouts and it should not be taken into account when other
* `layout` types are used.
*/
if ((type === 'default' || type === 'constrained') && !themeSupportsLayout) {
return null;
}
const layoutType = getLayoutType(type);
const constrainedType = getLayoutType('constrained');
const displayControlsForLegacyLayouts = !usedLayout.type && (contentSize || inherit);
const hasContentSizeOrLegacySettings = !!inherit || !!contentSize;
const onChangeType = newType => setAttributes({
layout: {
type: newType
}
});
const onChangeLayout = newLayout => setAttributes({
layout: newLayout
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(inspector_controls, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelBody, {
title: (0,external_wp_i18n_namespaceObject.__)('Layout')
}, showInheritToggle && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToggleControl, {
className: "block-editor-hooks__toggle-control",
label: (0,external_wp_i18n_namespaceObject.__)('Inner blocks use content width'),
checked: (layoutType === null || layoutType === void 0 ? void 0 : layoutType.name) === 'constrained' || hasContentSizeOrLegacySettings,
onChange: () => setAttributes({
layout: {
type: (layoutType === null || layoutType === void 0 ? void 0 : layoutType.name) === 'constrained' || hasContentSizeOrLegacySettings ? 'default' : 'constrained'
}
}),
help: (layoutType === null || layoutType === void 0 ? void 0 : layoutType.name) === 'constrained' || hasContentSizeOrLegacySettings ? (0,external_wp_i18n_namespaceObject.__)('Nested blocks use content width with options for full and wide widths.') : (0,external_wp_i18n_namespaceObject.__)('Nested blocks will fill the width of this container. Toggle to constrain.')
})), !inherit && allowSwitching && (0,external_wp_element_namespaceObject.createElement)(LayoutTypeSwitcher, {
type: type,
onChange: onChangeType
}), layoutType && layoutType.name !== 'default' && (0,external_wp_element_namespaceObject.createElement)(layoutType.inspectorControls, {
layout: usedLayout,
onChange: onChangeLayout,
layoutBlockSupport: layoutBlockSupport
}), constrainedType && displayControlsForLegacyLayouts && (0,external_wp_element_namespaceObject.createElement)(constrainedType.inspectorControls, {
layout: usedLayout,
onChange: onChangeLayout,
layoutBlockSupport: layoutBlockSupport
}))), !inherit && layoutType && (0,external_wp_element_namespaceObject.createElement)(layoutType.toolBarControls, {
layout: usedLayout,
onChange: onChangeLayout,
layoutBlockSupport: layoutBlockSupport
}));
}
function LayoutTypeSwitcher(_ref2) {
let {
type,
onChange
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ButtonGroup, null, getLayoutTypes().map(_ref3 => {
let {
name,
label
} = _ref3;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
key: name,
isPressed: type === name,
onClick: () => onChange(name)
}, label);
}));
}
/**
* Filters registered block settings, extending attributes to include `layout`.
*
* @param {Object} settings Original block settings.
*
* @return {Object} Filtered block settings.
*/
function layout_addAttribute(settings) {
var _settings$attributes$, _settings$attributes;
if ('type' in ((_settings$attributes$ = (_settings$attributes = settings.attributes) === null || _settings$attributes === void 0 ? void 0 : _settings$attributes.layout) !== null && _settings$attributes$ !== void 0 ? _settings$attributes$ : {})) {
return settings;
}
if ((0,external_wp_blocks_namespaceObject.hasBlockSupport)(settings, layoutBlockSupportKey)) {
settings.attributes = { ...settings.attributes,
layout: {
type: 'object'
}
};
}
return settings;
}
/**
* Override the default edit UI to include layout controls
*
* @param {Function} BlockEdit Original component.
*
* @return {Function} Wrapped component.
*/
const layout_withInspectorControls = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(BlockEdit => props => {
const {
name: blockName
} = props;
const supportLayout = (0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockName, layoutBlockSupportKey);
return [supportLayout && (0,external_wp_element_namespaceObject.createElement)(LayoutPanel, _extends({
key: "layout"
}, props)), (0,external_wp_element_namespaceObject.createElement)(BlockEdit, _extends({
key: "edit"
}, props))];
}, 'withInspectorControls');
/**
* Override the default block element to add the layout styles.
*
* @param {Function} BlockListBlock Original component.
*
* @return {Function} Wrapped component.
*/
const withLayoutStyles = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(BlockListBlock => props => {
const {
name,
attributes,
block
} = props;
const hasLayoutBlockSupport = (0,external_wp_blocks_namespaceObject.hasBlockSupport)(name, layoutBlockSupportKey);
const disableLayoutStyles = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getSettings
} = select(store);
return !!getSettings().disableLayoutStyles;
});
const shouldRenderLayoutStyles = hasLayoutBlockSupport && !disableLayoutStyles;
const id = (0,external_wp_compose_namespaceObject.useInstanceId)(BlockListBlock);
const defaultThemeLayout = useSetting('layout') || {};
const element = (0,external_wp_element_namespaceObject.useContext)(BlockList.__unstableElementContext);
const {
layout
} = attributes;
const {
default: defaultBlockLayout
} = (0,external_wp_blocks_namespaceObject.getBlockSupport)(name, layoutBlockSupportKey) || {};
const usedLayout = layout !== null && layout !== void 0 && layout.inherit || layout !== null && layout !== void 0 && layout.contentSize || layout !== null && layout !== void 0 && layout.wideSize ? { ...layout,
type: 'constrained'
} : layout || defaultBlockLayout || {};
const layoutClasses = hasLayoutBlockSupport ? useLayoutClasses(block) : null; // Higher specificity to override defaults from theme.json.
const selector = `.wp-container-${id}.wp-container-${id}`;
const blockGapSupport = useSetting('spacing.blockGap');
const hasBlockGapSupport = blockGapSupport !== null; // Get CSS string for the current layout type.
// The CSS and `style` element is only output if it is not empty.
let css;
if (shouldRenderLayoutStyles) {
var _fullLayoutType$getLa2;
const fullLayoutType = getLayoutType((usedLayout === null || usedLayout === void 0 ? void 0 : usedLayout.type) || 'default');
css = fullLayoutType === null || fullLayoutType === void 0 ? void 0 : (_fullLayoutType$getLa2 = fullLayoutType.getLayoutStyle) === null || _fullLayoutType$getLa2 === void 0 ? void 0 : _fullLayoutType$getLa2.call(fullLayoutType, {
blockName: name,
selector,
layout: usedLayout,
layoutDefinitions: defaultThemeLayout === null || defaultThemeLayout === void 0 ? void 0 : defaultThemeLayout.definitions,
style: attributes === null || attributes === void 0 ? void 0 : attributes.style,
hasBlockGapSupport
});
} // Attach a `wp-container-` id-based class name as well as a layout class name such as `is-layout-flex`.
const layoutClassNames = classnames_default()({
[`wp-container-${id}`]: shouldRenderLayoutStyles && !!css // Only attach a container class if there is generated CSS to be attached.
}, layoutClasses);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, shouldRenderLayoutStyles && element && !!css && (0,external_wp_element_namespaceObject.createPortal)((0,external_wp_element_namespaceObject.createElement)(LayoutStyle, {
blockName: name,
selector: selector,
css: css,
layout: usedLayout,
style: attributes === null || attributes === void 0 ? void 0 : attributes.style
}), element), (0,external_wp_element_namespaceObject.createElement)(BlockListBlock, _extends({}, props, {
__unstableLayoutClassNames: layoutClassNames
})));
});
/**
* Override the default block element to add the child layout styles.
*
* @param {Function} BlockListBlock Original component.
*
* @return {Function} Wrapped component.
*/
const withChildLayoutStyles = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(BlockListBlock => props => {
const {
attributes
} = props;
const {
style: {
layout = {}
} = {}
} = attributes;
const {
selfStretch,
flexSize
} = layout;
const hasChildLayout = selfStretch || flexSize;
const disableLayoutStyles = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getSettings
} = select(store);
return !!getSettings().disableLayoutStyles;
});
const shouldRenderChildLayoutStyles = hasChildLayout && !disableLayoutStyles;
const element = (0,external_wp_element_namespaceObject.useContext)(BlockList.__unstableElementContext);
const id = (0,external_wp_compose_namespaceObject.useInstanceId)(BlockListBlock);
const selector = `.wp-container-content-${id}`;
let css = '';
if (selfStretch === 'fixed' && flexSize) {
css += `${selector} {
flex-basis: ${flexSize};
box-sizing: border-box;
}`;
} else if (selfStretch === 'fill') {
css += `${selector} {
flex-grow: 1;
}`;
} // Attach a `wp-container-content` id-based classname.
const className = classnames_default()(props === null || props === void 0 ? void 0 : props.className, {
[`wp-container-content-${id}`]: shouldRenderChildLayoutStyles && !!css // Only attach a container class if there is generated CSS to be attached.
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, shouldRenderChildLayoutStyles && element && !!css && (0,external_wp_element_namespaceObject.createPortal)((0,external_wp_element_namespaceObject.createElement)("style", null, css), element), (0,external_wp_element_namespaceObject.createElement)(BlockListBlock, _extends({}, props, {
className: className
})));
});
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'core/layout/addAttribute', layout_addAttribute);
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockListBlock', 'core/editor/layout/with-layout-styles', withLayoutStyles);
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockListBlock', 'core/editor/layout/with-child-layout-styles', withChildLayoutStyles);
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockEdit', 'core/editor/layout/with-inspector-controls', layout_withInspectorControls);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/content-lock-ui.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* External dependencies
*/
function StopEditingAsBlocksOnOutsideSelect(_ref) {
let {
clientId,
stopEditingAsBlock
} = _ref;
const isBlockOrDescendantSelected = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
isBlockSelected,
hasSelectedInnerBlock
} = select(store);
return isBlockSelected(clientId) || hasSelectedInnerBlock(clientId, true);
}, [clientId]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (!isBlockOrDescendantSelected) {
stopEditingAsBlock();
}
}, [isBlockOrDescendantSelected]);
return null;
}
const content_lock_ui_withBlockControls = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(BlockEdit => props => {
const {
getBlockListSettings,
getSettings
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const focusModeToRevert = (0,external_wp_element_namespaceObject.useRef)();
const {
templateLock,
isLockedByParent,
isEditingAsBlocks
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
__unstableGetContentLockingParent,
getTemplateLock,
__unstableGetTemporarilyEditingAsBlocks
} = select(store);
return {
templateLock: getTemplateLock(props.clientId),
isLockedByParent: !!__unstableGetContentLockingParent(props.clientId),
isEditingAsBlocks: __unstableGetTemporarilyEditingAsBlocks() === props.clientId
};
}, [props.clientId]);
const {
updateSettings,
updateBlockListSettings,
__unstableSetTemporarilyEditingAsBlocks
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const isContentLocked = !isLockedByParent && templateLock === 'contentOnly';
const {
__unstableMarkNextChangeAsNotPersistent,
updateBlockAttributes
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const stopEditingAsBlock = (0,external_wp_element_namespaceObject.useCallback)(() => {
__unstableMarkNextChangeAsNotPersistent();
updateBlockAttributes(props.clientId, {
templateLock: 'contentOnly'
});
updateBlockListSettings(props.clientId, { ...getBlockListSettings(props.clientId),
templateLock: 'contentOnly'
});
updateSettings({
focusMode: focusModeToRevert.current
});
__unstableSetTemporarilyEditingAsBlocks();
}, [props.clientId, focusModeToRevert, updateSettings, updateBlockListSettings, getBlockListSettings, __unstableMarkNextChangeAsNotPersistent, updateBlockAttributes, __unstableSetTemporarilyEditingAsBlocks]);
if (!isContentLocked && !isEditingAsBlocks) {
return (0,external_wp_element_namespaceObject.createElement)(BlockEdit, props);
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, isEditingAsBlocks && !isContentLocked && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(StopEditingAsBlocksOnOutsideSelect, {
clientId: props.clientId,
stopEditingAsBlock: stopEditingAsBlock
}), (0,external_wp_element_namespaceObject.createElement)(block_controls, {
group: "other"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
onClick: () => {
stopEditingAsBlock();
}
}, (0,external_wp_i18n_namespaceObject.__)('Done')))), !isEditingAsBlocks && isContentLocked && props.isSelected && (0,external_wp_element_namespaceObject.createElement)(block_settings_menu_controls, null, _ref2 => {
let {
onClose
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
onClick: () => {
__unstableMarkNextChangeAsNotPersistent();
updateBlockAttributes(props.clientId, {
templateLock: undefined
});
updateBlockListSettings(props.clientId, { ...getBlockListSettings(props.clientId),
templateLock: false
});
focusModeToRevert.current = getSettings().focusMode;
updateSettings({
focusMode: true
});
__unstableSetTemporarilyEditingAsBlocks(props.clientId);
onClose();
}
}, (0,external_wp_i18n_namespaceObject.__)('Modify'));
}), (0,external_wp_element_namespaceObject.createElement)(BlockEdit, _extends({}, props, {
className: classnames_default()(props.className, isEditingAsBlocks && 'is-content-locked-editing-as-blocks')
})));
}, 'withToolbarControls');
(0,external_wp_hooks_namespaceObject.addFilter)('editor.BlockEdit', 'core/content-lock-ui/with-block-controls', content_lock_ui_withBlockControls);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/metadata.js
/**
* WordPress dependencies
*/
const META_ATTRIBUTE_NAME = 'metadata';
function hasBlockMetadataSupport(blockType) {
let feature = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
// Only core blocks are allowed to use __experimentalMetadata until the fetaure is stablised.
if (!blockType.name.startsWith('core/')) {
return false;
}
const support = (0,external_wp_blocks_namespaceObject.getBlockSupport)(blockType, '__experimentalMetadata');
return !!(true === support || support !== null && support !== void 0 && support[feature]);
}
/**
* Filters registered block settings, extending attributes to include `metadata`.
*
* see: https://github.com/WordPress/gutenberg/pull/40393/files#r864632012
*
* @param {Object} blockTypeSettings Original block settings.
* @return {Object} Filtered block settings.
*/
function addMetaAttribute(blockTypeSettings) {
var _blockTypeSettings$at, _blockTypeSettings$at2;
// Allow blocks to specify their own attribute definition with default values if needed.
if (blockTypeSettings !== null && blockTypeSettings !== void 0 && (_blockTypeSettings$at = blockTypeSettings.attributes) !== null && _blockTypeSettings$at !== void 0 && (_blockTypeSettings$at2 = _blockTypeSettings$at[META_ATTRIBUTE_NAME]) !== null && _blockTypeSettings$at2 !== void 0 && _blockTypeSettings$at2.type) {
return blockTypeSettings;
}
const supportsBlockNaming = hasBlockMetadataSupport(blockTypeSettings, 'name');
if (supportsBlockNaming) {
blockTypeSettings.attributes = { ...blockTypeSettings.attributes,
[META_ATTRIBUTE_NAME]: {
type: 'object'
}
};
}
return blockTypeSettings;
}
function metadata_addSaveProps(extraProps, blockType, attributes) {
if (hasBlockMetadataSupport(blockType)) {
extraProps[META_ATTRIBUTE_NAME] = attributes[META_ATTRIBUTE_NAME];
}
return extraProps;
}
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'core/metadata/addMetaAttribute', addMetaAttribute);
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.getSaveContent.extraProps', 'core/metadata/save-props', metadata_addSaveProps);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/metadata-name.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Filters registered block settings, adding an `__experimentalLabel` callback if one does not already exist.
*
* @param {Object} settings Original block settings.
*
* @return {Object} Filtered block settings.
*/
function addLabelCallback(settings) {
// If blocks provide their own label callback, do not override it.
if (settings.__experimentalLabel) {
return settings;
}
const supportsBlockNaming = hasBlockMetadataSupport(settings, 'name', false // default value
); // Check whether block metadata is supported before using it.
if (supportsBlockNaming) {
settings.__experimentalLabel = (attributes, _ref) => {
let {
context
} = _ref;
const {
metadata
} = attributes; // In the list view, use the block's name attribute as the label.
if (context === 'list-view' && metadata !== null && metadata !== void 0 && metadata.name) {
return metadata.name;
}
};
}
return settings;
}
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'core/metadata/addLabelCallback', addLabelCallback);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/use-border-props.js
/**
* Internal dependencies
*/
// This utility is intended to assist where the serialization of the border
// block support is being skipped for a block but the border related CSS classes
// & styles still need to be generated so they can be applied to inner elements.
/**
* Provides the CSS class names and inline styles for a block's border support
* attributes.
*
* @param {Object} attributes Block attributes.
* @return {Object} Border block support derived CSS classes & styles.
*/
function getBorderClassesAndStyles(attributes) {
var _attributes$style;
const border = ((_attributes$style = attributes.style) === null || _attributes$style === void 0 ? void 0 : _attributes$style.border) || {};
const className = getBorderClasses(attributes);
return {
className: className || undefined,
style: getInlineStyles({
border
})
};
}
/**
* Derives the border related props for a block from its border block support
* attributes.
*
* Inline styles are forced for named colors to ensure these selections are
* reflected when themes do not load their color stylesheets in the editor.
*
* @param {Object} attributes Block attributes.
*
* @return {Object} ClassName & style props from border block support.
*/
function useBorderProps(attributes) {
const {
colors
} = useMultipleOriginColorsAndGradients();
const borderProps = getBorderClassesAndStyles(attributes);
const {
borderColor
} = attributes; // Force inline styles to apply named border colors when themes do not load
// their color stylesheets in the editor.
if (borderColor) {
const borderColorObject = getMultiOriginColor({
colors,
namedColor: borderColor
});
borderProps.style.borderColor = borderColorObject.color;
}
return borderProps;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/use-color-props.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
// The code in this file has largely been lifted from the color block support
// hook.
//
// This utility is intended to assist where the serialization of the colors
// block support is being skipped for a block but the color related CSS classes
// & styles still need to be generated so they can be applied to inner elements.
/**
* Provides the CSS class names and inline styles for a block's color support
* attributes.
*
* @param {Object} attributes Block attributes.
*
* @return {Object} Color block support derived CSS classes & styles.
*/
function getColorClassesAndStyles(attributes) {
var _style$color, _style$color2, _style$color3, _style$color4, _style$elements, _style$elements$link;
const {
backgroundColor,
textColor,
gradient,
style
} = attributes; // Collect color CSS classes.
const backgroundClass = getColorClassName('background-color', backgroundColor);
const textClass = getColorClassName('color', textColor);
const gradientClass = __experimentalGetGradientClass(gradient);
const hasGradient = gradientClass || (style === null || style === void 0 ? void 0 : (_style$color = style.color) === null || _style$color === void 0 ? void 0 : _style$color.gradient); // Determine color CSS class name list.
const className = classnames_default()(textClass, gradientClass, {
// Don't apply the background class if there's a gradient.
[backgroundClass]: !hasGradient && !!backgroundClass,
'has-text-color': textColor || (style === null || style === void 0 ? void 0 : (_style$color2 = style.color) === null || _style$color2 === void 0 ? void 0 : _style$color2.text),
'has-background': backgroundColor || (style === null || style === void 0 ? void 0 : (_style$color3 = style.color) === null || _style$color3 === void 0 ? void 0 : _style$color3.background) || gradient || (style === null || style === void 0 ? void 0 : (_style$color4 = style.color) === null || _style$color4 === void 0 ? void 0 : _style$color4.gradient),
'has-link-color': style === null || style === void 0 ? void 0 : (_style$elements = style.elements) === null || _style$elements === void 0 ? void 0 : (_style$elements$link = _style$elements.link) === null || _style$elements$link === void 0 ? void 0 : _style$elements$link.color
}); // Collect inline styles for colors.
const colorStyles = (style === null || style === void 0 ? void 0 : style.color) || {};
const styleProp = getInlineStyles({
color: colorStyles
});
return {
className: className || undefined,
style: styleProp
};
}
const use_color_props_EMPTY_OBJECT = {};
/**
* Determines the color related props for a block derived from its color block
* support attributes.
*
* Inline styles are forced for named colors to ensure these selections are
* reflected when themes do not load their color stylesheets in the editor.
*
* @param {Object} attributes Block attributes.
*
* @return {Object} ClassName & style props from colors block support.
*/
function useColorProps(attributes) {
const {
backgroundColor,
textColor,
gradient
} = attributes; // Some color settings have a special handling for deprecated flags in `useSetting`,
// so we can't unwrap them by doing const { ... } = useSetting('color')
// until https://github.com/WordPress/gutenberg/issues/37094 is fixed.
const userPalette = useSetting('color.palette.custom');
const themePalette = useSetting('color.palette.theme');
const defaultPalette = useSetting('color.palette.default');
const gradientsPerOrigin = useSetting('color.gradients') || use_color_props_EMPTY_OBJECT;
const colors = (0,external_wp_element_namespaceObject.useMemo)(() => [...(userPalette || []), ...(themePalette || []), ...(defaultPalette || [])], [userPalette, themePalette, defaultPalette]);
const gradients = (0,external_wp_element_namespaceObject.useMemo)(() => [...((gradientsPerOrigin === null || gradientsPerOrigin === void 0 ? void 0 : gradientsPerOrigin.custom) || []), ...((gradientsPerOrigin === null || gradientsPerOrigin === void 0 ? void 0 : gradientsPerOrigin.theme) || []), ...((gradientsPerOrigin === null || gradientsPerOrigin === void 0 ? void 0 : gradientsPerOrigin.default) || [])], [gradientsPerOrigin]);
const colorProps = getColorClassesAndStyles(attributes); // Force inline styles to apply colors when themes do not load their color
// stylesheets in the editor.
if (backgroundColor) {
const backgroundColorObject = getColorObjectByAttributeValues(colors, backgroundColor);
colorProps.style.backgroundColor = backgroundColorObject.color;
}
if (gradient) {
colorProps.style.background = getGradientValueBySlug(gradients, gradient);
}
if (textColor) {
const textColorObject = getColorObjectByAttributeValues(colors, textColor);
colorProps.style.color = textColorObject.color;
}
return colorProps;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/use-spacing-props.js
/**
* Internal dependencies
*/
// This utility is intended to assist where the serialization of the spacing
// block support is being skipped for a block but the spacing related CSS
// styles still need to be generated so they can be applied to inner elements.
/**
* Provides the CSS class names and inline styles for a block's spacing support
* attributes.
*
* @param {Object} attributes Block attributes.
*
* @return {Object} Spacing block support derived CSS classes & styles.
*/
function getSpacingClassesAndStyles(attributes) {
const {
style
} = attributes; // Collect inline styles for spacing.
const spacingStyles = (style === null || style === void 0 ? void 0 : style.spacing) || {};
const styleProp = getInlineStyles({
spacing: spacingStyles
});
return {
style: styleProp
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/use-typography-props.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
// This utility is intended to assist where the serialization of the typography
// block support is being skipped for a block but the typography related CSS
// styles still need to be generated so they can be applied to inner elements.
/**
* Provides the CSS class names and inline styles for a block's typography support
* attributes.
*
* @param {Object} attributes Block attributes.
* @param {Object|boolean} fluidTypographySettings If boolean, whether the function should try to convert font sizes to fluid values,
* otherwise an object containing theme fluid typography settings.
*
* @return {Object} Typography block support derived CSS classes & styles.
*/
function getTypographyClassesAndStyles(attributes, fluidTypographySettings) {
var _attributes$style;
let typographyStyles = (attributes === null || attributes === void 0 ? void 0 : (_attributes$style = attributes.style) === null || _attributes$style === void 0 ? void 0 : _attributes$style.typography) || {};
if (!!fluidTypographySettings && (true === fluidTypographySettings || Object.keys(fluidTypographySettings).length !== 0)) {
var _attributes$style2, _attributes$style2$ty, _attributes$style3, _attributes$style3$ty;
const newFontSize = getComputedFluidTypographyValue({
fontSize: attributes === null || attributes === void 0 ? void 0 : (_attributes$style2 = attributes.style) === null || _attributes$style2 === void 0 ? void 0 : (_attributes$style2$ty = _attributes$style2.typography) === null || _attributes$style2$ty === void 0 ? void 0 : _attributes$style2$ty.fontSize,
minimumFontSizeLimit: fluidTypographySettings === null || fluidTypographySettings === void 0 ? void 0 : fluidTypographySettings.minFontSize
}) || (attributes === null || attributes === void 0 ? void 0 : (_attributes$style3 = attributes.style) === null || _attributes$style3 === void 0 ? void 0 : (_attributes$style3$ty = _attributes$style3.typography) === null || _attributes$style3$ty === void 0 ? void 0 : _attributes$style3$ty.fontSize);
typographyStyles = { ...typographyStyles,
fontSize: newFontSize
};
}
const style = getInlineStyles({
typography: typographyStyles
});
const fontFamilyClassName = !!(attributes !== null && attributes !== void 0 && attributes.fontFamily) ? `has-${(0,external_lodash_namespaceObject.kebabCase)(attributes.fontFamily)}-font-family` : '';
const className = classnames_default()(fontFamilyClassName, getFontSizeClass(attributes === null || attributes === void 0 ? void 0 : attributes.fontSize));
return {
className,
style
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/use-cached-truthy.js
/**
* WordPress dependencies
*/
/**
* Keeps an up-to-date copy of the passed value and returns it. If value becomes falsy, it will return the last truthy copy.
*
* @param {any} value
* @return {any} value
*/
function useCachedTruthy(value) {
const [cachedValue, setCachedValue] = (0,external_wp_element_namespaceObject.useState)(value);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (value) {
setCachedValue(value);
}
}, [value]);
return cachedValue;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/hooks/index.js
/**
* Internal dependencies
*/
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/colors/with-colors.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Capitalizes the first letter in a string.
*
* @param {string} str The string whose first letter the function will capitalize.
*
* @return {string} Capitalized string.
*/
const upperFirst = _ref => {
let [firstLetter, ...rest] = _ref;
return firstLetter.toUpperCase() + rest.join('');
};
/**
* Higher order component factory for injecting the `colorsArray` argument as
* the colors prop in the `withCustomColors` HOC.
*
* @param {Array} colorsArray An array of color objects.
*
* @return {Function} The higher order component.
*/
const withCustomColorPalette = colorsArray => (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(WrappedComponent => props => (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, _extends({}, props, {
colors: colorsArray
})), 'withCustomColorPalette');
/**
* Higher order component factory for injecting the editor colors as the
* `colors` prop in the `withColors` HOC.
*
* @return {Function} The higher order component.
*/
const withEditorColorPalette = () => (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(WrappedComponent => props => {
// Some color settings have a special handling for deprecated flags in `useSetting`,
// so we can't unwrap them by doing const { ... } = useSetting('color')
// until https://github.com/WordPress/gutenberg/issues/37094 is fixed.
const userPalette = useSetting('color.palette.custom');
const themePalette = useSetting('color.palette.theme');
const defaultPalette = useSetting('color.palette.default');
const allColors = (0,external_wp_element_namespaceObject.useMemo)(() => [...(userPalette || []), ...(themePalette || []), ...(defaultPalette || [])], [userPalette, themePalette, defaultPalette]);
return (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, _extends({}, props, {
colors: allColors
}));
}, 'withEditorColorPalette');
/**
* Helper function used with `createHigherOrderComponent` to create
* higher order components for managing color logic.
*
* @param {Array} colorTypes An array of color types (e.g. 'backgroundColor, borderColor).
* @param {Function} withColorPalette A HOC for injecting the 'colors' prop into the WrappedComponent.
*
* @return {WPComponent} The component that can be used as a HOC.
*/
function createColorHOC(colorTypes, withColorPalette) {
const colorMap = colorTypes.reduce((colorObject, colorType) => {
return { ...colorObject,
...(typeof colorType === 'string' ? {
[colorType]: (0,external_lodash_namespaceObject.kebabCase)(colorType)
} : colorType)
};
}, {});
return (0,external_wp_compose_namespaceObject.compose)([withColorPalette, WrappedComponent => {
return class extends external_wp_element_namespaceObject.Component {
constructor(props) {
super(props);
this.setters = this.createSetters();
this.colorUtils = {
getMostReadableColor: this.getMostReadableColor.bind(this)
};
this.state = {};
}
getMostReadableColor(colorValue) {
const {
colors
} = this.props;
return getMostReadableColor(colors, colorValue);
}
createSetters() {
return Object.keys(colorMap).reduce((settersAccumulator, colorAttributeName) => {
const upperFirstColorAttributeName = upperFirst(colorAttributeName);
const customColorAttributeName = `custom${upperFirstColorAttributeName}`;
settersAccumulator[`set${upperFirstColorAttributeName}`] = this.createSetColor(colorAttributeName, customColorAttributeName);
return settersAccumulator;
}, {});
}
createSetColor(colorAttributeName, customColorAttributeName) {
return colorValue => {
const colorObject = getColorObjectByColorValue(this.props.colors, colorValue);
this.props.setAttributes({
[colorAttributeName]: colorObject && colorObject.slug ? colorObject.slug : undefined,
[customColorAttributeName]: colorObject && colorObject.slug ? undefined : colorValue
});
};
}
static getDerivedStateFromProps(_ref2, previousState) {
let {
attributes,
colors
} = _ref2;
return Object.entries(colorMap).reduce((newState, _ref3) => {
let [colorAttributeName, colorContext] = _ref3;
const colorObject = getColorObjectByAttributeValues(colors, attributes[colorAttributeName], attributes[`custom${upperFirst(colorAttributeName)}`]);
const previousColorObject = previousState[colorAttributeName];
const previousColor = previousColorObject === null || previousColorObject === void 0 ? void 0 : previousColorObject.color;
/**
* The "and previousColorObject" condition checks that a previous color object was already computed.
* At the start previousColorObject and colorValue are both equal to undefined
* bus as previousColorObject does not exist we should compute the object.
*/
if (previousColor === colorObject.color && previousColorObject) {
newState[colorAttributeName] = previousColorObject;
} else {
newState[colorAttributeName] = { ...colorObject,
class: getColorClassName(colorContext, colorObject.slug)
};
}
return newState;
}, {});
}
render() {
return (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, _extends({}, this.props, {
colors: undefined
}, this.state, this.setters, {
colorUtils: this.colorUtils
}));
}
};
}]);
}
/**
* A higher-order component factory for creating a 'withCustomColors' HOC, which handles color logic
* for class generation color value, retrieval and color attribute setting.
*
* Use this higher-order component to work with a custom set of colors.
*
* @example
*
* ```jsx
* const CUSTOM_COLORS = [ { name: 'Red', slug: 'red', color: '#ff0000' }, { name: 'Blue', slug: 'blue', color: '#0000ff' } ];
* const withCustomColors = createCustomColorsHOC( CUSTOM_COLORS );
* // ...
* export default compose(
* withCustomColors( 'backgroundColor', 'borderColor' ),
* MyColorfulComponent,
* );
* ```
*
* @param {Array} colorsArray The array of color objects (name, slug, color, etc... ).
*
* @return {Function} Higher-order component.
*/
function createCustomColorsHOC(colorsArray) {
return function () {
const withColorPalette = withCustomColorPalette(colorsArray);
for (var _len = arguments.length, colorTypes = new Array(_len), _key = 0; _key < _len; _key++) {
colorTypes[_key] = arguments[_key];
}
return (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(createColorHOC(colorTypes, withColorPalette), 'withCustomColors');
};
}
/**
* A higher-order component, which handles color logic for class generation color value, retrieval and color attribute setting.
*
* For use with the default editor/theme color palette.
*
* @example
*
* ```jsx
* export default compose(
* withColors( 'backgroundColor', { textColor: 'color' } ),
* MyColorfulComponent,
* );
* ```
*
* @param {...(Object|string)} colorTypes The arguments can be strings or objects. If the argument is an object,
* it should contain the color attribute name as key and the color context as value.
* If the argument is a string the value should be the color attribute name,
* the color context is computed by applying a kebab case transform to the value.
* Color context represents the context/place where the color is going to be used.
* The class name of the color is generated using 'has' followed by the color name
* and ending with the color context all in kebab case e.g: has-green-background-color.
*
* @return {Function} Higher-order component.
*/
function withColors() {
const withColorPalette = withEditorColorPalette();
for (var _len2 = arguments.length, colorTypes = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
colorTypes[_key2] = arguments[_key2];
}
return (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(createColorHOC(colorTypes, withColorPalette), 'withColors');
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/colors/index.js
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/gradients/index.js
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/font-sizes/with-font-sizes.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const DEFAULT_FONT_SIZES = [];
/**
* Capitalizes the first letter in a string.
*
* @param {string} str The string whose first letter the function will capitalize.
*
* @return {string} Capitalized string.
*/
const with_font_sizes_upperFirst = _ref => {
let [firstLetter, ...rest] = _ref;
return firstLetter.toUpperCase() + rest.join('');
};
/**
* Higher-order component, which handles font size logic for class generation,
* font size value retrieval, and font size change handling.
*
* @param {...(Object|string)} fontSizeNames The arguments should all be strings.
* Each string contains the font size
* attribute name e.g: 'fontSize'.
*
* @return {Function} Higher-order component.
*/
/* harmony default export */ var with_font_sizes = (function () {
for (var _len = arguments.length, fontSizeNames = new Array(_len), _key = 0; _key < _len; _key++) {
fontSizeNames[_key] = arguments[_key];
}
/*
* Computes an object whose key is the font size attribute name as passed in the array,
* and the value is the custom font size attribute name.
* Custom font size is automatically compted by appending custom followed by the font size attribute name in with the first letter capitalized.
*/
const fontSizeAttributeNames = fontSizeNames.reduce((fontSizeAttributeNamesAccumulator, fontSizeAttributeName) => {
fontSizeAttributeNamesAccumulator[fontSizeAttributeName] = `custom${with_font_sizes_upperFirst(fontSizeAttributeName)}`;
return fontSizeAttributeNamesAccumulator;
}, {});
return (0,external_wp_compose_namespaceObject.createHigherOrderComponent)((0,external_wp_compose_namespaceObject.compose)([(0,external_wp_compose_namespaceObject.createHigherOrderComponent)(WrappedComponent => props => {
const fontSizes = useSetting('typography.fontSizes') || DEFAULT_FONT_SIZES;
return (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, _extends({}, props, {
fontSizes: fontSizes
}));
}, 'withFontSizes'), WrappedComponent => {
return class extends external_wp_element_namespaceObject.Component {
constructor(props) {
super(props);
this.setters = this.createSetters();
this.state = {};
}
createSetters() {
return Object.entries(fontSizeAttributeNames).reduce((settersAccumulator, _ref2) => {
let [fontSizeAttributeName, customFontSizeAttributeName] = _ref2;
const upperFirstFontSizeAttributeName = with_font_sizes_upperFirst(fontSizeAttributeName);
settersAccumulator[`set${upperFirstFontSizeAttributeName}`] = this.createSetFontSize(fontSizeAttributeName, customFontSizeAttributeName);
return settersAccumulator;
}, {});
}
createSetFontSize(fontSizeAttributeName, customFontSizeAttributeName) {
return fontSizeValue => {
var _this$props$fontSizes;
const fontSizeObject = (_this$props$fontSizes = this.props.fontSizes) === null || _this$props$fontSizes === void 0 ? void 0 : _this$props$fontSizes.find(_ref3 => {
let {
size
} = _ref3;
return size === Number(fontSizeValue);
});
this.props.setAttributes({
[fontSizeAttributeName]: fontSizeObject && fontSizeObject.slug ? fontSizeObject.slug : undefined,
[customFontSizeAttributeName]: fontSizeObject && fontSizeObject.slug ? undefined : fontSizeValue
});
};
}
static getDerivedStateFromProps(_ref4, previousState) {
let {
attributes,
fontSizes
} = _ref4;
const didAttributesChange = (customFontSizeAttributeName, fontSizeAttributeName) => {
if (previousState[fontSizeAttributeName]) {
// If new font size is name compare with the previous slug.
if (attributes[fontSizeAttributeName]) {
return attributes[fontSizeAttributeName] !== previousState[fontSizeAttributeName].slug;
} // If font size is not named, update when the font size value changes.
return previousState[fontSizeAttributeName].size !== attributes[customFontSizeAttributeName];
} // In this case we need to build the font size object.
return true;
};
if (!Object.values(fontSizeAttributeNames).some(didAttributesChange)) {
return null;
}
const newState = Object.entries(fontSizeAttributeNames).filter(_ref5 => {
let [key, value] = _ref5;
return didAttributesChange(value, key);
}).reduce((newStateAccumulator, _ref6) => {
let [fontSizeAttributeName, customFontSizeAttributeName] = _ref6;
const fontSizeAttributeValue = attributes[fontSizeAttributeName];
const fontSizeObject = getFontSize(fontSizes, fontSizeAttributeValue, attributes[customFontSizeAttributeName]);
newStateAccumulator[fontSizeAttributeName] = { ...fontSizeObject,
class: getFontSizeClass(fontSizeAttributeValue)
};
return newStateAccumulator;
}, {});
return { ...previousState,
...newState
};
}
render() {
return (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, _extends({}, this.props, {
fontSizes: undefined
}, this.state, this.setters));
}
};
}]), 'withFontSizes');
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/font-sizes/index.js
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/duotone/index.js
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/align-left.js
/**
* WordPress dependencies
*/
const alignLeft = (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: "M4 19.8h8.9v-1.5H4v1.5zm8.9-15.6H4v1.5h8.9V4.2zm-8.9 7v1.5h16v-1.5H4z"
}));
/* harmony default export */ var align_left = (alignLeft);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/align-center.js
/**
* WordPress dependencies
*/
const align_center_alignCenter = (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: "M16.4 4.2H7.6v1.5h8.9V4.2zM4 11.2v1.5h16v-1.5H4zm3.6 8.6h8.9v-1.5H7.6v1.5z"
}));
/* harmony default export */ var align_center = (align_center_alignCenter);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/align-right.js
/**
* WordPress dependencies
*/
const alignRight = (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: "M11.1 19.8H20v-1.5h-8.9v1.5zm0-15.6v1.5H20V4.2h-8.9zM4 12.8h16v-1.5H4v1.5z"
}));
/* harmony default export */ var align_right = (alignRight);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/alignment-control/ui.js
/**
* WordPress dependencies
*/
const DEFAULT_ALIGNMENT_CONTROLS = [{
icon: align_left,
title: (0,external_wp_i18n_namespaceObject.__)('Align text left'),
align: 'left'
}, {
icon: align_center,
title: (0,external_wp_i18n_namespaceObject.__)('Align text center'),
align: 'center'
}, {
icon: align_right,
title: (0,external_wp_i18n_namespaceObject.__)('Align text right'),
align: 'right'
}];
const ui_POPOVER_PROPS = {
position: 'bottom right',
variant: 'toolbar'
};
function AlignmentUI(_ref) {
let {
value,
onChange,
alignmentControls = DEFAULT_ALIGNMENT_CONTROLS,
label = (0,external_wp_i18n_namespaceObject.__)('Align text'),
describedBy = (0,external_wp_i18n_namespaceObject.__)('Change text alignment'),
isCollapsed = true,
isToolbar
} = _ref;
function applyOrUnset(align) {
return () => onChange(value === align ? undefined : align);
}
const activeAlignment = alignmentControls.find(control => control.align === value);
function setIcon() {
if (activeAlignment) return activeAlignment.icon;
return (0,external_wp_i18n_namespaceObject.isRTL)() ? align_right : align_left;
}
const UIComponent = isToolbar ? external_wp_components_namespaceObject.ToolbarGroup : external_wp_components_namespaceObject.ToolbarDropdownMenu;
const extraProps = isToolbar ? {
isCollapsed
} : {
toggleProps: {
describedBy
},
popoverProps: ui_POPOVER_PROPS
};
return (0,external_wp_element_namespaceObject.createElement)(UIComponent, _extends({
icon: setIcon(),
label: label,
controls: alignmentControls.map(control => {
const {
align
} = control;
const isActive = value === align;
return { ...control,
isActive,
role: isCollapsed ? 'menuitemradio' : undefined,
onClick: applyOrUnset(align)
};
})
}, extraProps));
}
/* harmony default export */ var alignment_control_ui = (AlignmentUI);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/alignment-control/index.js
/**
* Internal dependencies
*/
const AlignmentControl = props => {
return (0,external_wp_element_namespaceObject.createElement)(alignment_control_ui, _extends({}, props, {
isToolbar: false
}));
};
const AlignmentToolbar = props => {
return (0,external_wp_element_namespaceObject.createElement)(alignment_control_ui, _extends({}, props, {
isToolbar: true
}));
};
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/alignment-control/README.md
*/
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/autocompleters/block.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const block_noop = () => {};
const block_SHOWN_BLOCK_TYPES = 9;
/** @typedef {import('@wordpress/components').WPCompleter} WPCompleter */
/**
* Creates a blocks repeater for replacing the current block with a selected block type.
*
* @return {WPCompleter} A blocks completer.
*/
function createBlockCompleter() {
return {
name: 'blocks',
className: 'block-editor-autocompleters__block',
triggerPrefix: '/',
useItems(filterValue) {
const {
rootClientId,
selectedBlockName
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getSelectedBlockClientId,
getBlockName,
getBlockInsertionPoint
} = select(store);
const selectedBlockClientId = getSelectedBlockClientId();
return {
selectedBlockName: selectedBlockClientId ? getBlockName(selectedBlockClientId) : null,
rootClientId: getBlockInsertionPoint().rootClientId
};
}, []);
const [items, categories, collections] = use_block_types_state(rootClientId, block_noop);
const filteredItems = (0,external_wp_element_namespaceObject.useMemo)(() => {
const initialFilteredItems = !!filterValue.trim() ? searchBlockItems(items, categories, collections, filterValue) : orderBy(items, 'frecency', 'desc');
return initialFilteredItems.filter(item => item.name !== selectedBlockName).slice(0, block_SHOWN_BLOCK_TYPES);
}, [filterValue, selectedBlockName, items, categories, collections]);
const options = (0,external_wp_element_namespaceObject.useMemo)(() => filteredItems.map(blockItem => {
const {
title,
icon,
isDisabled
} = blockItem;
return {
key: `block-${blockItem.id}`,
value: blockItem,
label: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(block_icon, {
key: "icon",
icon: icon,
showColors: true
}), title),
isDisabled
};
}), [filteredItems]);
return [options];
},
allowContext(before, after) {
return !(/\S/.test(before) || /\S/.test(after));
},
getOptionCompletion(inserterItem) {
const {
name,
initialAttributes,
innerBlocks
} = inserterItem;
return {
action: 'replace',
value: (0,external_wp_blocks_namespaceObject.createBlock)(name, initialAttributes, (0,external_wp_blocks_namespaceObject.createBlocksFromInnerBlocksTemplate)(innerBlocks))
};
}
};
}
/**
* Creates a blocks repeater for replacing the current block with a selected block type.
*
* @return {WPCompleter} A blocks completer.
*/
/* harmony default export */ var autocompleters_block = (createBlockCompleter());
;// CONCATENATED MODULE: external ["wp","apiFetch"]
var external_wp_apiFetch_namespaceObject = window["wp"]["apiFetch"];
var external_wp_apiFetch_default = /*#__PURE__*/__webpack_require__.n(external_wp_apiFetch_namespaceObject);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/page.js
/**
* WordPress dependencies
*/
const page = (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: "M7 5.5h10a.5.5 0 01.5.5v12a.5.5 0 01-.5.5H7a.5.5 0 01-.5-.5V6a.5.5 0 01.5-.5zM17 4H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V6a2 2 0 00-2-2zm-1 3.75H8v1.5h8v-1.5zM8 11h8v1.5H8V11zm6 3.25H8v1.5h6v-1.5z"
}));
/* harmony default export */ var library_page = (page);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/post.js
/**
* WordPress dependencies
*/
const post = (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: "m7.3 9.7 1.4 1.4c.2-.2.3-.3.4-.5 0 0 0-.1.1-.1.3-.5.4-1.1.3-1.6L12 7 9 4 7.2 6.5c-.6-.1-1.1 0-1.6.3 0 0-.1 0-.1.1-.3.1-.4.2-.6.4l1.4 1.4L4 11v1h1l2.3-2.3zM4 20h9v-1.5H4V20zm0-5.5V16h16v-1.5H4z"
}));
/* harmony default export */ var library_post = (post);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/autocompleters/link.js
/**
* WordPress dependencies
*/
// Disable Reason: Needs to be refactored.
// eslint-disable-next-line no-restricted-imports
const SHOWN_SUGGESTIONS = 10;
/** @typedef {import('@wordpress/components').WPCompleter} WPCompleter */
/**
* Creates a suggestion list for links to posts or pages.
*
* @return {WPCompleter} A links completer.
*/
function createLinkCompleter() {
return {
name: 'links',
className: 'block-editor-autocompleters__link',
triggerPrefix: '[[',
options: async letters => {
let options = await external_wp_apiFetch_default()({
path: (0,external_wp_url_namespaceObject.addQueryArgs)('/wp/v2/search', {
per_page: SHOWN_SUGGESTIONS,
search: letters,
type: 'post',
order_by: 'menu_order'
})
});
options = options.filter(option => option.title !== '');
return options;
},
getOptionKeywords(item) {
const expansionWords = item.title.split(/\s+/);
return [...expansionWords];
},
getOptionLabel(item) {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
key: "icon",
icon: item.subtype === 'page' ? library_page : library_post
}), item.title);
},
getOptionCompletion(item) {
return (0,external_wp_element_namespaceObject.createElement)("a", {
href: item.url
}, item.title);
}
};
}
/**
* Creates a suggestion list for links to posts or pages..
*
* @return {WPCompleter} A link completer.
*/
/* harmony default export */ var autocompleters_link = (createLinkCompleter());
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/autocomplete/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Shared reference to an empty array for cases where it is important to avoid
* returning a new array reference on every invocation.
*
* @type {Array}
*/
const autocomplete_EMPTY_ARRAY = [];
function useCompleters(_ref) {
let {
completers = autocomplete_EMPTY_ARRAY
} = _ref;
const {
name
} = useBlockEditContext();
return (0,external_wp_element_namespaceObject.useMemo)(() => {
let filteredCompleters = [...completers, autocompleters_link];
if (name === (0,external_wp_blocks_namespaceObject.getDefaultBlockName)() || (0,external_wp_blocks_namespaceObject.getBlockSupport)(name, '__experimentalSlashInserter', false)) {
filteredCompleters = [...filteredCompleters, autocompleters_block];
}
if ((0,external_wp_hooks_namespaceObject.hasFilter)('editor.Autocomplete.completers')) {
// Provide copies so filters may directly modify them.
if (filteredCompleters === completers) {
filteredCompleters = filteredCompleters.map(completer => ({ ...completer
}));
}
filteredCompleters = (0,external_wp_hooks_namespaceObject.applyFilters)('editor.Autocomplete.completers', filteredCompleters, name);
}
return filteredCompleters;
}, [completers, name]);
}
function useBlockEditorAutocompleteProps(props) {
return (0,external_wp_components_namespaceObject.__unstableUseAutocompleteProps)({ ...props,
completers: useCompleters(props)
});
}
/**
* Wrap the default Autocomplete component with one that supports a filter hook
* for customizing its list of autocompleters.
*
* @type {import('react').FC}
*/
function BlockEditorAutocomplete(props) {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Autocomplete, _extends({}, props, {
completers: useCompleters(props)
}));
}
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/autocomplete/README.md
*/
/* harmony default export */ var autocomplete = (BlockEditorAutocomplete);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/fullscreen.js
/**
* WordPress dependencies
*/
const fullscreen = (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: "M4.2 9h1.5V5.8H9V4.2H4.2V9zm14 9.2H15v1.5h4.8V15h-1.5v3.2zM15 4.2v1.5h3.2V9h1.5V4.2H15zM5.8 15H4.2v4.8H9v-1.5H5.8V15z"
}));
/* harmony default export */ var library_fullscreen = (fullscreen);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-full-height-alignment-control/index.js
/**
* WordPress dependencies
*/
function BlockFullHeightAlignmentControl(_ref) {
let {
isActive,
label = (0,external_wp_i18n_namespaceObject.__)('Toggle full height'),
onToggle,
isDisabled
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
isActive: isActive,
icon: library_fullscreen,
label: label,
onClick: () => onToggle(!isActive),
disabled: isDisabled
});
}
/* harmony default export */ var block_full_height_alignment_control = (BlockFullHeightAlignmentControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-alignment-matrix-control/index.js
/**
* WordPress dependencies
*/
const block_alignment_matrix_control_noop = () => {};
function BlockAlignmentMatrixControl(props) {
const {
label = (0,external_wp_i18n_namespaceObject.__)('Change matrix alignment'),
onChange = block_alignment_matrix_control_noop,
value = 'center',
isDisabled
} = props;
const icon = (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalAlignmentMatrixControl.Icon, {
value: value
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Dropdown, {
popoverProps: {
variant: 'toolbar',
placement: 'bottom-start'
},
renderToggle: _ref => {
let {
onToggle,
isOpen
} = _ref;
const openOnArrowDown = event => {
if (!isOpen && event.keyCode === external_wp_keycodes_namespaceObject.DOWN) {
event.preventDefault();
onToggle();
}
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
onClick: onToggle,
"aria-haspopup": "true",
"aria-expanded": isOpen,
onKeyDown: openOnArrowDown,
label: label,
icon: icon,
showTooltip: true,
disabled: isDisabled
});
},
renderContent: () => (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalAlignmentMatrixControl, {
hasFocusBorder: false,
onChange: onChange,
value: value
})
});
}
/* harmony default export */ var block_alignment_matrix_control = (BlockAlignmentMatrixControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/chevron-right-small.js
/**
* WordPress dependencies
*/
const chevronRightSmall = (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: "M10.8622 8.04053L14.2805 12.0286L10.8622 16.0167L9.72327 15.0405L12.3049 12.0286L9.72327 9.01672L10.8622 8.04053Z"
}));
/* harmony default export */ var chevron_right_small = (chevronRightSmall);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-breadcrumb/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Block breadcrumb component, displaying the hierarchy of the current block selection as a breadcrumb.
*
* @param {Object} props Component props.
* @param {string} props.rootLabelText Translated label for the root element of the breadcrumb trail.
* @return {WPElement} Block Breadcrumb.
*/
function BlockBreadcrumb(_ref) {
let {
rootLabelText
} = _ref;
const {
selectBlock,
clearSelectedBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const {
clientId,
parents,
hasSelection
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getSelectionStart,
getSelectedBlockClientId,
getBlockParents
} = select(store);
const selectedBlockClientId = getSelectedBlockClientId();
return {
parents: getBlockParents(selectedBlockClientId),
clientId: selectedBlockClientId,
hasSelection: !!getSelectionStart().clientId
};
}, []);
const rootLabel = rootLabelText || (0,external_wp_i18n_namespaceObject.__)('Document');
/*
* Disable reason: The `list` ARIA role is redundant but
* Safari+VoiceOver won't announce the list otherwise.
*/
/* eslint-disable jsx-a11y/no-redundant-roles */
return (0,external_wp_element_namespaceObject.createElement)("ul", {
className: "block-editor-block-breadcrumb",
role: "list",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Block breadcrumb')
}, (0,external_wp_element_namespaceObject.createElement)("li", {
className: !hasSelection ? 'block-editor-block-breadcrumb__current' : undefined,
"aria-current": !hasSelection ? 'true' : undefined
}, hasSelection && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "block-editor-block-breadcrumb__button",
variant: "tertiary",
onClick: clearSelectedBlock
}, rootLabel), !hasSelection && rootLabel, !!clientId && (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: chevron_right_small,
className: "block-editor-block-breadcrumb__separator"
})), parents.map(parentClientId => (0,external_wp_element_namespaceObject.createElement)("li", {
key: parentClientId
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "block-editor-block-breadcrumb__button",
variant: "tertiary",
onClick: () => selectBlock(parentClientId)
}, (0,external_wp_element_namespaceObject.createElement)(BlockTitle, {
clientId: parentClientId,
maximumLength: 35
})), (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: chevron_right_small,
className: "block-editor-block-breadcrumb__separator"
}))), !!clientId && (0,external_wp_element_namespaceObject.createElement)("li", {
className: "block-editor-block-breadcrumb__current",
"aria-current": "true"
}, (0,external_wp_element_namespaceObject.createElement)(BlockTitle, {
clientId: clientId,
maximumLength: 35
})))
/* eslint-enable jsx-a11y/no-redundant-roles */
;
}
/* harmony default export */ var block_breadcrumb = (BlockBreadcrumb);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/color-style-selector/index.js
/**
* WordPress dependencies
*/
const ColorSelectorSVGIcon = () => (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SVG, {
xmlns: "https://www.w3.org/2000/svg",
viewBox: "0 0 20 20"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Path, {
d: "M7.434 5l3.18 9.16H8.538l-.692-2.184H4.628l-.705 2.184H2L5.18 5h2.254zm-1.13 1.904h-.115l-1.148 3.593H7.44L6.304 6.904zM14.348 7.006c1.853 0 2.9.876 2.9 2.374v4.78h-1.79v-.914h-.114c-.362.64-1.123 1.022-2.031 1.022-1.346 0-2.292-.826-2.292-2.108 0-1.27.972-2.006 2.71-2.107l1.696-.102V9.38c0-.584-.42-.914-1.18-.914-.667 0-1.112.228-1.264.647h-1.701c.12-1.295 1.307-2.107 3.066-2.107zm1.079 4.1l-1.416.09c-.793.056-1.18.342-1.18.844 0 .52.45.837 1.091.837.857 0 1.505-.545 1.505-1.256v-.515z"
}));
/**
* Color Selector Icon component.
*
* @param {Object} props Component properties.
* @param {Object} props.style Style object.
* @param {string} props.className Class name for component.
*
* @return {*} React Icon component.
*/
const ColorSelectorIcon = _ref => {
let {
style,
className
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-library-colors-selector__icon-container"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: `${className} block-library-colors-selector__state-selection`,
style: style
}, (0,external_wp_element_namespaceObject.createElement)(ColorSelectorSVGIcon, null)));
};
/**
* Renders the Colors Selector Toolbar with the icon button.
*
* @param {Object} props Component properties.
* @param {Object} props.TextColor Text color component that wraps icon.
* @param {Object} props.BackgroundColor Background color component that wraps icon.
*
* @return {*} React toggle button component.
*/
const renderToggleComponent = _ref2 => {
let {
TextColor,
BackgroundColor
} = _ref2;
return _ref3 => {
let {
onToggle,
isOpen
} = _ref3;
const openOnArrowDown = event => {
if (!isOpen && event.keyCode === external_wp_keycodes_namespaceObject.DOWN) {
event.preventDefault();
onToggle();
}
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarGroup, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
className: "components-toolbar__control block-library-colors-selector__toggle",
label: (0,external_wp_i18n_namespaceObject.__)('Open Colors Selector'),
onClick: onToggle,
onKeyDown: openOnArrowDown,
icon: (0,external_wp_element_namespaceObject.createElement)(BackgroundColor, null, (0,external_wp_element_namespaceObject.createElement)(TextColor, null, (0,external_wp_element_namespaceObject.createElement)(ColorSelectorIcon, null)))
}));
};
};
const BlockColorsStyleSelector = _ref4 => {
let {
children,
...other
} = _ref4;
external_wp_deprecated_default()(`wp.blockEditor.BlockColorsStyleSelector`, {
alternative: 'block supports API',
since: '6.1',
version: '6.3'
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Dropdown, {
popoverProps: {
placement: 'bottom-start'
},
className: "block-library-colors-selector",
contentClassName: "block-library-colors-selector__popover",
renderToggle: renderToggleComponent(other),
renderContent: () => children
});
};
/* harmony default export */ var color_style_selector = (BlockColorsStyleSelector);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/list-view.js
/**
* WordPress dependencies
*/
const listView = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M13.8 5.2H3v1.5h10.8V5.2zm-3.6 12v1.5H21v-1.5H10.2zm7.2-6H6.6v1.5h10.8v-1.5z"
}));
/* harmony default export */ var list_view = (listView);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/list-view/leaf.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const AnimatedTreeGridRow = animated(external_wp_components_namespaceObject.__experimentalTreeGridRow);
const ListViewLeaf = (0,external_wp_element_namespaceObject.forwardRef)((_ref, ref) => {
let {
isSelected,
position,
level,
rowCount,
children,
className,
path,
...props
} = _ref;
const animationRef = use_moving_animation({
isSelected,
adjustScrolling: false,
enableAnimation: true,
triggerAnimationOnChange: path
});
const mergedRef = (0,external_wp_compose_namespaceObject.useMergeRefs)([ref, animationRef]);
return (0,external_wp_element_namespaceObject.createElement)(AnimatedTreeGridRow, _extends({
ref: mergedRef,
className: classnames_default()('block-editor-list-view-leaf', className),
level: level,
positionInSet: position,
setSize: rowCount
}, props), children);
});
/* harmony default export */ var leaf = (ListViewLeaf);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/list-view/use-list-view-scroll-into-view.js
/**
* WordPress dependencies
*/
function useListViewScrollIntoView(_ref) {
let {
isSelected,
selectedClientIds,
rowItemRef
} = _ref;
const isSingleSelection = selectedClientIds.length === 1;
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
// Skip scrolling into view if this particular block isn't selected,
// or if more than one block is selected overall. This is to avoid
// scrolling the view in a multi selection where the user has intentionally
// selected multiple blocks within the list view, but the initially
// selected block may be out of view.
if (!isSelected || !isSingleSelection || !rowItemRef.current) {
return;
}
const scrollContainer = (0,external_wp_dom_namespaceObject.getScrollContainer)(rowItemRef.current);
const {
ownerDocument
} = rowItemRef.current;
const windowScroll = scrollContainer === ownerDocument.body || scrollContainer === ownerDocument.documentElement; // If the there is no scroll container, of if the scroll container is the window,
// do not scroll into view, as the block is already in view.
if (windowScroll || !scrollContainer) {
return;
}
const rowRect = rowItemRef.current.getBoundingClientRect();
const scrollContainerRect = scrollContainer.getBoundingClientRect(); // If the selected block is not currently visible, scroll to it.
if (rowRect.top < scrollContainerRect.top || rowRect.bottom > scrollContainerRect.bottom) {
rowItemRef.current.scrollIntoView();
}
}, [isSelected, isSingleSelection, rowItemRef]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/lock-small.js
/**
* WordPress dependencies
*/
const lockSmall = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
fillRule: "evenodd",
clipRule: "evenodd",
d: "M15 11h-.2V9c0-1.5-1.2-2.8-2.8-2.8S9.2 7.5 9.2 9v2H9c-.6 0-1 .4-1 1v4c0 .6.4 1 1 1h6c.6 0 1-.4 1-1v-4c0-.6-.4-1-1-1zm-1.8 0h-2.5V9c0-.7.6-1.2 1.2-1.2s1.2.6 1.2 1.2v2z"
}));
/* harmony default export */ var lock_small = (lockSmall);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/chevron-left-small.js
/**
* WordPress dependencies
*/
const chevronLeftSmall = (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: "m13.1 16-3.4-4 3.4-4 1.1 1-2.6 3 2.6 3-1.1 1z"
}));
/* harmony default export */ var chevron_left_small = (chevronLeftSmall);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/list-view/expander.js
/**
* WordPress dependencies
*/
function ListViewExpander(_ref) {
let {
onClick
} = _ref;
return (// Keyboard events are handled by TreeGrid see: components/src/tree-grid/index.js
//
// The expander component is implemented as a pseudo element in the w3 example
// https://www.w3.org/TR/wai-aria-practices/examples/treegrid/treegrid-1.html
//
// We've mimicked this by adding an icon with aria-hidden set to true to hide this from the accessibility tree.
// For the current tree grid implementation, please do not try to make this a button.
//
// eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
(0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-list-view__expander",
onClick: event => onClick(event, {
forceToggle: true
}),
"aria-hidden": "true"
}, (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: (0,external_wp_i18n_namespaceObject.isRTL)() ? chevron_left_small : chevron_right_small
}))
);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/list-view/block-select-button.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ListViewBlockSelectButton(_ref, ref) {
let {
className,
block: {
clientId
},
onClick,
onToggleExpanded,
tabIndex,
onFocus,
onDragStart,
onDragEnd,
draggable
} = _ref;
const blockInformation = useBlockDisplayInformation(clientId);
const blockTitle = useBlockDisplayTitle({
clientId,
context: 'list-view'
});
const {
isLocked
} = useBlockLock(clientId); // The `href` attribute triggers the browser's native HTML drag operations.
// When the link is dragged, the element's outerHTML is set in DataTransfer object as text/html.
// We need to clear any HTML drag data to prevent `pasteHandler` from firing
// inside the `useOnBlockDrop` hook.
const onDragStartHandler = event => {
event.dataTransfer.clearData();
onDragStart === null || onDragStart === void 0 ? void 0 : onDragStart(event);
};
function onKeyDownHandler(event) {
if (event.keyCode === external_wp_keycodes_namespaceObject.ENTER || event.keyCode === external_wp_keycodes_namespaceObject.SPACE) {
onClick(event);
}
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: classnames_default()('block-editor-list-view-block-select-button', className),
onClick: onClick,
onKeyDown: onKeyDownHandler,
ref: ref,
tabIndex: tabIndex,
onFocus: onFocus,
onDragStart: onDragStartHandler,
onDragEnd: onDragEnd,
draggable: draggable,
href: `#block-${clientId}`,
"aria-hidden": true
}, (0,external_wp_element_namespaceObject.createElement)(ListViewExpander, {
onClick: onToggleExpanded
}), (0,external_wp_element_namespaceObject.createElement)(block_icon, {
icon: blockInformation === null || blockInformation === void 0 ? void 0 : blockInformation.icon,
showColors: true
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalHStack, {
alignment: "center",
className: "block-editor-list-view-block-select-button__label-wrapper",
justify: "flex-start",
spacing: 1
}, (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-list-view-block-select-button__title"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalTruncate, {
ellipsizeMode: "auto"
}, blockTitle)), (blockInformation === null || blockInformation === void 0 ? void 0 : blockInformation.anchor) && (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-list-view-block-select-button__anchor-wrapper"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalTruncate, {
className: "block-editor-list-view-block-select-button__anchor",
ellipsizeMode: "auto"
}, blockInformation.anchor)), isLocked && (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-list-view-block-select-button__lock"
}, (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: lock_small
})))));
}
/* harmony default export */ var block_select_button = ((0,external_wp_element_namespaceObject.forwardRef)(ListViewBlockSelectButton));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/list-view/block-contents.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const ListViewBlockContents = (0,external_wp_element_namespaceObject.forwardRef)((_ref, ref) => {
let {
onClick,
onToggleExpanded,
block,
isSelected,
position,
siblingBlockCount,
level,
isExpanded,
selectedClientIds,
...props
} = _ref;
const {
clientId
} = block;
const {
blockMovingClientId,
selectedBlockInBlockEditor
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
hasBlockMovingClientId,
getSelectedBlockClientId
} = select(store);
return {
blockMovingClientId: hasBlockMovingClientId(),
selectedBlockInBlockEditor: getSelectedBlockClientId()
};
}, [clientId]);
const isBlockMoveTarget = blockMovingClientId && selectedBlockInBlockEditor === clientId;
const className = classnames_default()('block-editor-list-view-block-contents', {
'is-dropping-before': isBlockMoveTarget
}); // Only include all selected blocks if the currently clicked on block
// is one of the selected blocks. This ensures that if a user attempts
// to drag a block that isn't part of the selection, they're still able
// to drag it and rearrange its position.
const draggableClientIds = selectedClientIds.includes(clientId) ? selectedClientIds : [clientId];
return (0,external_wp_element_namespaceObject.createElement)(block_draggable, {
clientIds: draggableClientIds
}, _ref2 => {
let {
draggable,
onDragStart,
onDragEnd
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(block_select_button, _extends({
ref: ref,
className: className,
block: block,
onClick: onClick,
onToggleExpanded: onToggleExpanded,
isSelected: isSelected,
position: position,
siblingBlockCount: siblingBlockCount,
level: level,
draggable: draggable,
onDragStart: onDragStart,
onDragEnd: onDragEnd,
isExpanded: isExpanded
}, props));
});
});
/* harmony default export */ var block_contents = (ListViewBlockContents);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/list-view/context.js
/**
* WordPress dependencies
*/
const ListViewContext = (0,external_wp_element_namespaceObject.createContext)({});
const useListViewContext = () => (0,external_wp_element_namespaceObject.useContext)(ListViewContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/list-view/utils.js
/**
* WordPress dependencies
*/
const getBlockPositionDescription = (position, siblingCount, level) => (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: 1: The numerical position of the block. 2: The total number of blocks. 3. The level of nesting for the block. */
(0,external_wp_i18n_namespaceObject.__)('Block %1$d of %2$d, Level %3$d'), position, siblingCount, level);
/**
* Returns true if the client ID occurs within the block selection or multi-selection,
* or false otherwise.
*
* @param {string} clientId Block client ID.
* @param {string|string[]} selectedBlockClientIds Selected block client ID, or an array of multi-selected blocks client IDs.
*
* @return {boolean} Whether the block is in multi-selection set.
*/
const isClientIdSelected = (clientId, selectedBlockClientIds) => Array.isArray(selectedBlockClientIds) && selectedBlockClientIds.length ? selectedBlockClientIds.indexOf(clientId) !== -1 : selectedBlockClientIds === clientId;
/**
* From a start and end clientId of potentially different nesting levels,
* return the nearest-depth ids that have a common level of depth in the
* nesting hierarchy. For multiple block selection, this ensure that the
* selection is always at the same nesting level, and not split across
* separate levels.
*
* @param {string} startId The first id of a selection.
* @param {string} endId The end id of a selection, usually one that has been clicked on.
* @param {string[]} startParents An array of ancestor ids for the start id, in descending order.
* @param {string[]} endParents An array of ancestor ids for the end id, in descending order.
* @return {Object} An object containing the start and end ids.
*/
function getCommonDepthClientIds(startId, endId, startParents, endParents) {
const startPath = [...startParents, startId];
const endPath = [...endParents, endId];
const depth = Math.min(startPath.length, endPath.length) - 1;
const start = startPath[depth];
const end = endPath[depth];
return {
start,
end
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/list-view/block.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ListViewBlock(_ref) {
let {
block,
isDragged,
isSelected,
isBranchSelected,
selectBlock,
position,
level,
rowCount,
siblingBlockCount,
showBlockMovers,
path,
isExpanded,
selectedClientIds,
preventAnnouncement,
isSyncedBranch
} = _ref;
const cellRef = (0,external_wp_element_namespaceObject.useRef)(null);
const rowRef = (0,external_wp_element_namespaceObject.useRef)(null);
const [isHovered, setIsHovered] = (0,external_wp_element_namespaceObject.useState)(false);
const {
clientId
} = block;
const {
isLocked,
isContentLocked,
canEdit
} = useBlockLock(clientId);
const forceSelectionContentLock = (0,external_wp_data_namespaceObject.useSelect)(select => {
if (isSelected) {
return false;
}
if (!isContentLocked) {
return false;
}
return select(store).hasSelectedInnerBlock(clientId, true);
}, [isContentLocked, clientId, isSelected]);
const canExpand = isContentLocked ? false : canEdit;
const isFirstSelectedBlock = forceSelectionContentLock || isSelected && selectedClientIds[0] === clientId;
const isLastSelectedBlock = forceSelectionContentLock || isSelected && selectedClientIds[selectedClientIds.length - 1] === clientId;
const {
toggleBlockHighlight
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const blockInformation = useBlockDisplayInformation(clientId);
const blockName = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).getBlockName(clientId), [clientId]); // When a block hides its toolbar it also hides the block settings menu,
// since that menu is part of the toolbar in the editor canvas.
// List View respects this by also hiding the block settings menu.
const showBlockActions = (0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockName, '__experimentalToolbar', true);
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(ListViewBlock);
const descriptionId = `list-view-block-select-button__${instanceId}`;
const blockPositionDescription = getBlockPositionDescription(position, siblingBlockCount, level);
let blockAriaLabel = (0,external_wp_i18n_namespaceObject.__)('Link');
if (blockInformation) {
blockAriaLabel = isLocked ? (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The title of the block. This string indicates a link to select the locked block.
(0,external_wp_i18n_namespaceObject.__)('%s link (locked)'), blockInformation.title) : (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The title of the block. This string indicates a link to select the block.
(0,external_wp_i18n_namespaceObject.__)('%s link'), blockInformation.title);
}
const settingsAriaLabel = blockInformation ? (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The title of the block.
(0,external_wp_i18n_namespaceObject.__)('Options for %s block'), blockInformation.title) : (0,external_wp_i18n_namespaceObject.__)('Options');
const {
isTreeGridMounted,
expand,
collapse
} = useListViewContext();
const hasSiblings = siblingBlockCount > 0;
const hasRenderedMovers = showBlockMovers && hasSiblings;
const moverCellClassName = classnames_default()('block-editor-list-view-block__mover-cell', {
'is-visible': isHovered || isSelected
});
const listViewBlockSettingsClassName = classnames_default()('block-editor-list-view-block__menu-cell', {
'is-visible': isHovered || isFirstSelectedBlock
}); // If ListView has experimental features related to the Persistent List View,
// only focus the selected list item on mount; otherwise the list would always
// try to steal the focus from the editor canvas.
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (!isTreeGridMounted && isSelected) {
cellRef.current.focus();
}
}, []);
const onMouseEnter = (0,external_wp_element_namespaceObject.useCallback)(() => {
setIsHovered(true);
toggleBlockHighlight(clientId, true);
}, [clientId, setIsHovered, toggleBlockHighlight]);
const onMouseLeave = (0,external_wp_element_namespaceObject.useCallback)(() => {
setIsHovered(false);
toggleBlockHighlight(clientId, false);
}, [clientId, setIsHovered, toggleBlockHighlight]);
const selectEditorBlock = (0,external_wp_element_namespaceObject.useCallback)(event => {
selectBlock(event, clientId);
event.preventDefault();
}, [clientId, selectBlock]);
const updateSelection = (0,external_wp_element_namespaceObject.useCallback)(newClientId => {
selectBlock(undefined, newClientId);
}, [selectBlock]);
const toggleExpanded = (0,external_wp_element_namespaceObject.useCallback)(event => {
// Prevent shift+click from opening link in a new window when toggling.
event.preventDefault();
event.stopPropagation();
if (isExpanded === true) {
collapse(clientId);
} else if (isExpanded === false) {
expand(clientId);
}
}, [clientId, expand, collapse, isExpanded]);
let colSpan;
if (hasRenderedMovers) {
colSpan = 2;
} else if (!showBlockActions) {
colSpan = 3;
}
const classes = classnames_default()({
'is-selected': isSelected || forceSelectionContentLock,
'is-first-selected': isFirstSelectedBlock,
'is-last-selected': isLastSelectedBlock,
'is-branch-selected': isBranchSelected,
'is-synced-branch': isSyncedBranch,
'is-dragging': isDragged,
'has-single-cell': !showBlockActions,
'is-synced': blockInformation === null || blockInformation === void 0 ? void 0 : blockInformation.isSynced
}); // Only include all selected blocks if the currently clicked on block
// is one of the selected blocks. This ensures that if a user attempts
// to alter a block that isn't part of the selection, they're still able
// to do so.
const dropdownClientIds = selectedClientIds.includes(clientId) ? selectedClientIds : [clientId]; // Pass in a ref to the row, so that it can be scrolled
// into view when selected. For long lists, the placeholder for the
// selected block is also observed, within ListViewLeafPlaceholder.
useListViewScrollIntoView({
isSelected,
rowItemRef: rowRef,
selectedClientIds
});
return (0,external_wp_element_namespaceObject.createElement)(leaf, {
className: classes,
onMouseEnter: onMouseEnter,
onMouseLeave: onMouseLeave,
onFocus: onMouseEnter,
onBlur: onMouseLeave,
level: level,
position: position,
rowCount: rowCount,
path: path,
id: `list-view-block-${clientId}`,
"data-block": clientId,
isExpanded: canExpand ? isExpanded : undefined,
"aria-selected": !!isSelected || forceSelectionContentLock,
ref: rowRef
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalTreeGridCell, {
className: "block-editor-list-view-block__contents-cell",
colSpan: colSpan,
ref: cellRef,
"aria-label": blockAriaLabel,
"aria-selected": !!isSelected || forceSelectionContentLock,
"aria-expanded": canExpand ? isExpanded : undefined,
"aria-describedby": descriptionId
}, _ref2 => {
let {
ref,
tabIndex,
onFocus
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-list-view-block__contents-container"
}, (0,external_wp_element_namespaceObject.createElement)(block_contents, {
block: block,
onClick: selectEditorBlock,
onToggleExpanded: toggleExpanded,
isSelected: isSelected,
position: position,
siblingBlockCount: siblingBlockCount,
level: level,
ref: ref,
tabIndex: tabIndex,
onFocus: onFocus,
isExpanded: isExpanded,
selectedClientIds: selectedClientIds,
preventAnnouncement: preventAnnouncement
}), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-list-view-block-select-button__description",
id: descriptionId
}, blockPositionDescription));
}), hasRenderedMovers && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalTreeGridCell, {
className: moverCellClassName,
withoutGridItem: true
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalTreeGridItem, null, _ref3 => {
let {
ref,
tabIndex,
onFocus
} = _ref3;
return (0,external_wp_element_namespaceObject.createElement)(BlockMoverUpButton, {
orientation: "vertical",
clientIds: [clientId],
ref: ref,
tabIndex: tabIndex,
onFocus: onFocus
});
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalTreeGridItem, null, _ref4 => {
let {
ref,
tabIndex,
onFocus
} = _ref4;
return (0,external_wp_element_namespaceObject.createElement)(BlockMoverDownButton, {
orientation: "vertical",
clientIds: [clientId],
ref: ref,
tabIndex: tabIndex,
onFocus: onFocus
});
}))), showBlockActions && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalTreeGridCell, {
className: listViewBlockSettingsClassName,
"aria-selected": !!isSelected || forceSelectionContentLock
}, _ref5 => {
let {
ref,
tabIndex,
onFocus
} = _ref5;
return (0,external_wp_element_namespaceObject.createElement)(block_settings_dropdown, {
clientIds: dropdownClientIds,
icon: more_vertical,
label: settingsAriaLabel,
toggleProps: {
ref,
className: 'block-editor-list-view-block__menu',
tabIndex,
onFocus
},
disableOpenOnArrowDown: true,
__experimentalSelectBlock: updateSelection
});
}));
}
/* harmony default export */ var list_view_block = ((0,external_wp_element_namespaceObject.memo)(ListViewBlock));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/list-view/branch.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Given a block, returns the total number of blocks in that subtree. This is used to help determine
* the list position of a block.
*
* When a block is collapsed, we do not count their children as part of that total. In the current drag
* implementation dragged blocks and their children are not counted.
*
* @param {Object} block block tree
* @param {Object} expandedState state that notes which branches are collapsed
* @param {Array} draggedClientIds a list of dragged client ids
* @param {boolean} isExpandedByDefault flag to determine the default fallback expanded state.
* @return {number} block count
*/
function countBlocks(block, expandedState, draggedClientIds, isExpandedByDefault) {
var _expandedState$block$;
const isDragged = draggedClientIds === null || draggedClientIds === void 0 ? void 0 : draggedClientIds.includes(block.clientId);
if (isDragged) {
return 0;
}
const isExpanded = (_expandedState$block$ = expandedState[block.clientId]) !== null && _expandedState$block$ !== void 0 ? _expandedState$block$ : isExpandedByDefault;
if (isExpanded) {
return 1 + block.innerBlocks.reduce(countReducer(expandedState, draggedClientIds, isExpandedByDefault), 0);
}
return 1;
}
const countReducer = (expandedState, draggedClientIds, isExpandedByDefault) => (count, block) => {
var _expandedState$block$2;
const isDragged = draggedClientIds === null || draggedClientIds === void 0 ? void 0 : draggedClientIds.includes(block.clientId);
if (isDragged) {
return count;
}
const isExpanded = (_expandedState$block$2 = expandedState[block.clientId]) !== null && _expandedState$block$2 !== void 0 ? _expandedState$block$2 : isExpandedByDefault;
if (isExpanded && block.innerBlocks.length > 0) {
return count + countBlocks(block, expandedState, draggedClientIds, isExpandedByDefault);
}
return count + 1;
};
const branch_noop = () => {};
function ListViewBranch(props) {
const {
blocks,
selectBlock = branch_noop,
showBlockMovers,
selectedClientIds,
level = 1,
path = '',
isBranchSelected = false,
listPosition = 0,
fixedListWindow,
isExpanded,
parentId,
shouldShowInnerBlocks = true,
isSyncedBranch = false
} = props;
const parentBlockInformation = useBlockDisplayInformation(parentId);
const syncedBranch = isSyncedBranch || !!(parentBlockInformation !== null && parentBlockInformation !== void 0 && parentBlockInformation.isSynced);
const canParentExpand = (0,external_wp_data_namespaceObject.useSelect)(select => {
if (!parentId) {
return true;
}
const isContentLocked = select(store).getTemplateLock(parentId) === 'contentOnly';
const canEdit = select(store).canEditBlock(parentId);
return isContentLocked ? false : canEdit;
}, [parentId]);
const {
expandedState,
draggedClientIds
} = useListViewContext();
if (!canParentExpand) {
return null;
}
const filteredBlocks = blocks.filter(Boolean);
const blockCount = filteredBlocks.length;
let nextPosition = listPosition;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, filteredBlocks.map((block, index) => {
var _expandedState$client;
const {
clientId,
innerBlocks
} = block;
if (index > 0) {
nextPosition += countBlocks(filteredBlocks[index - 1], expandedState, draggedClientIds, isExpanded);
}
const {
itemInView
} = fixedListWindow;
const blockInView = itemInView(nextPosition);
const position = index + 1;
const updatedPath = path.length > 0 ? `${path}_${position}` : `${position}`;
const hasNestedBlocks = !!(innerBlocks !== null && innerBlocks !== void 0 && innerBlocks.length);
const shouldExpand = hasNestedBlocks && shouldShowInnerBlocks ? (_expandedState$client = expandedState[clientId]) !== null && _expandedState$client !== void 0 ? _expandedState$client : isExpanded : undefined;
const isDragged = !!(draggedClientIds !== null && draggedClientIds !== void 0 && draggedClientIds.includes(clientId)); // Make updates to the selected or dragged blocks synchronous,
// but asynchronous for any other block.
const isSelected = isClientIdSelected(clientId, selectedClientIds);
const isSelectedBranch = isBranchSelected || isSelected && hasNestedBlocks;
const showBlock = isDragged || blockInView || isSelected;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_data_namespaceObject.AsyncModeProvider, {
key: clientId,
value: !isSelected
}, showBlock && (0,external_wp_element_namespaceObject.createElement)(list_view_block, {
block: block,
selectBlock: selectBlock,
isSelected: isSelected,
isBranchSelected: isSelectedBranch,
isDragged: isDragged,
level: level,
position: position,
rowCount: blockCount,
siblingBlockCount: blockCount,
showBlockMovers: showBlockMovers,
path: updatedPath,
isExpanded: shouldExpand,
listPosition: nextPosition,
selectedClientIds: selectedClientIds,
isSyncedBranch: syncedBranch
}), !showBlock && (0,external_wp_element_namespaceObject.createElement)("tr", null, (0,external_wp_element_namespaceObject.createElement)("td", {
className: "block-editor-list-view-placeholder"
})), hasNestedBlocks && shouldExpand && !isDragged && (0,external_wp_element_namespaceObject.createElement)(ListViewBranch, {
parentId: clientId,
blocks: innerBlocks,
selectBlock: selectBlock,
showBlockMovers: showBlockMovers,
level: level + 1,
path: updatedPath,
listPosition: nextPosition + 1,
fixedListWindow: fixedListWindow,
isBranchSelected: isSelectedBranch,
selectedClientIds: selectedClientIds,
isExpanded: isExpanded,
isSyncedBranch: syncedBranch
}));
}));
}
/* harmony default export */ var branch = ((0,external_wp_element_namespaceObject.memo)(ListViewBranch));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/list-view/drop-indicator.js
/**
* WordPress dependencies
*/
function ListViewDropIndicator(_ref) {
let {
listViewRef,
blockDropTarget
} = _ref;
const {
rootClientId,
clientId,
dropPosition
} = blockDropTarget || {};
const [rootBlockElement, blockElement] = (0,external_wp_element_namespaceObject.useMemo)(() => {
if (!listViewRef.current) {
return [];
} // The rootClientId will be defined whenever dropping into inner
// block lists, but is undefined when dropping at the root level.
const _rootBlockElement = rootClientId ? listViewRef.current.querySelector(`[data-block="${rootClientId}"]`) : undefined; // The clientId represents the sibling block, the dragged block will
// usually be inserted adjacent to it. It will be undefined when
// dropping a block into an empty block list.
const _blockElement = clientId ? listViewRef.current.querySelector(`[data-block="${clientId}"]`) : undefined;
return [_rootBlockElement, _blockElement];
}, [rootClientId, clientId]); // The targetElement is the element that the drop indicator will appear
// before or after. When dropping into an empty block list, blockElement
// is undefined, so the indicator will appear after the rootBlockElement.
const targetElement = blockElement || rootBlockElement;
const getDropIndicatorIndent = (0,external_wp_element_namespaceObject.useCallback)(() => {
if (!rootBlockElement) {
return 0;
} // Calculate the indent using the block icon of the root block.
// Using a classname selector here might be flaky and could be
// improved.
const targetElementRect = targetElement.getBoundingClientRect();
const rootBlockIconElement = rootBlockElement.querySelector('.block-editor-block-icon');
const rootBlockIconRect = rootBlockIconElement.getBoundingClientRect();
return rootBlockIconRect.right - targetElementRect.left;
}, [rootBlockElement, targetElement]);
const style = (0,external_wp_element_namespaceObject.useMemo)(() => {
if (!targetElement) {
return {};
}
const indent = getDropIndicatorIndent();
return {
width: targetElement.offsetWidth - indent
};
}, [getDropIndicatorIndent, targetElement]);
const popoverAnchor = (0,external_wp_element_namespaceObject.useMemo)(() => {
const isValidDropPosition = dropPosition === 'top' || dropPosition === 'bottom' || dropPosition === 'inside';
if (!targetElement || !isValidDropPosition) {
return undefined;
}
return {
ownerDocument: targetElement.ownerDocument,
getBoundingClientRect() {
const rect = targetElement.getBoundingClientRect();
const indent = getDropIndicatorIndent();
const left = rect.left + indent;
const right = rect.right;
let top = 0;
let bottom = 0;
if (dropPosition === 'top') {
top = rect.top;
bottom = rect.top;
} else {
// `dropPosition` is either `bottom` or `inside`
top = rect.bottom;
bottom = rect.bottom;
}
const width = right - left;
const height = bottom - top;
return new window.DOMRect(left, top, width, height);
}
};
}, [targetElement, dropPosition, getDropIndicatorIndent]);
if (!targetElement) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Popover, {
animate: false,
anchor: popoverAnchor,
focusOnMount: false,
className: "block-editor-list-view-drop-indicator",
variant: "unstyled"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
style: style,
className: "block-editor-list-view-drop-indicator__line"
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/list-view/use-block-selection.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useBlockSelection() {
const {
clearSelectedBlock,
multiSelect,
selectBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const {
getBlockName,
getBlockParents,
getBlockSelectionStart,
getBlockSelectionEnd,
getSelectedBlockClientIds,
hasMultiSelection,
hasSelectedBlock
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const {
getBlockType
} = (0,external_wp_data_namespaceObject.useSelect)(external_wp_blocks_namespaceObject.store);
const updateBlockSelection = (0,external_wp_element_namespaceObject.useCallback)(async (event, clientId, destinationClientId) => {
if (!(event !== null && event !== void 0 && event.shiftKey)) {
selectBlock(clientId);
return;
} // To handle multiple block selection via the `SHIFT` key, prevent
// the browser default behavior of opening the link in a new window.
event.preventDefault();
const isKeyPress = event.type === 'keydown' && (event.keyCode === external_wp_keycodes_namespaceObject.UP || event.keyCode === external_wp_keycodes_namespaceObject.DOWN || event.keyCode === external_wp_keycodes_namespaceObject.HOME || event.keyCode === external_wp_keycodes_namespaceObject.END); // Handle clicking on a block when no blocks are selected, and return early.
if (!isKeyPress && !hasSelectedBlock() && !hasMultiSelection()) {
selectBlock(clientId, null);
return;
}
const selectedBlocks = getSelectedBlockClientIds();
const clientIdWithParents = [...getBlockParents(clientId), clientId];
if (isKeyPress && !selectedBlocks.some(blockId => clientIdWithParents.includes(blockId))) {
// Ensure that shift-selecting blocks via the keyboard only
// expands the current selection if focusing over already
// selected blocks. Otherwise, clear the selection so that
// a user can create a new selection entirely by keyboard.
await clearSelectedBlock();
}
let startTarget = getBlockSelectionStart();
let endTarget = clientId; // Handle keyboard behavior for selecting multiple blocks.
if (isKeyPress) {
if (!hasSelectedBlock() && !hasMultiSelection()) {
// Set the starting point of the selection to the currently
// focused block, if there are no blocks currently selected.
// This ensures that as the selection is expanded or contracted,
// the starting point of the selection is anchored to that block.
startTarget = clientId;
}
if (destinationClientId) {
// If the user presses UP or DOWN, we want to ensure that the block they're
// moving to is the target for selection, and not the currently focused one.
endTarget = destinationClientId;
}
}
const startParents = getBlockParents(startTarget);
const endParents = getBlockParents(endTarget);
const {
start,
end
} = getCommonDepthClientIds(startTarget, endTarget, startParents, endParents);
await multiSelect(start, end, null); // Announce deselected block, or number of deselected blocks if
// the total number of blocks deselected is greater than one.
const updatedSelectedBlocks = getSelectedBlockClientIds(); // If the selection is greater than 1 and the Home or End keys
// were used to generate the selection, then skip announcing the
// deselected blocks.
if ((event.keyCode === external_wp_keycodes_namespaceObject.HOME || event.keyCode === external_wp_keycodes_namespaceObject.END) && updatedSelectedBlocks.length > 1) {
return;
}
const selectionDiff = selectedBlocks.filter(blockId => !updatedSelectedBlocks.includes(blockId));
let label;
if (selectionDiff.length === 1) {
var _getBlockType;
const title = (_getBlockType = getBlockType(getBlockName(selectionDiff[0]))) === null || _getBlockType === void 0 ? void 0 : _getBlockType.title;
if (title) {
label = (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: block name */
(0,external_wp_i18n_namespaceObject.__)('%s deselected.'), title);
}
} else if (selectionDiff.length > 1) {
label = (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: number of deselected blocks */
(0,external_wp_i18n_namespaceObject.__)('%s blocks deselected.'), selectionDiff.length);
}
if (label) {
(0,external_wp_a11y_namespaceObject.speak)(label);
}
}, [clearSelectedBlock, getBlockName, getBlockType, getBlockParents, getBlockSelectionStart, getBlockSelectionEnd, getSelectedBlockClientIds, hasMultiSelection, hasSelectedBlock, multiSelect, selectBlock]);
return {
updateBlockSelection
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/list-view/use-list-view-client-ids.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useListViewClientIds(blocks) {
return (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getDraggedBlockClientIds,
getSelectedBlockClientIds,
__unstableGetClientIdsTree
} = select(store);
return {
selectedClientIds: getSelectedBlockClientIds(),
draggedClientIds: getDraggedBlockClientIds(),
clientIdsTree: blocks ? blocks : __unstableGetClientIdsTree()
};
}, [blocks]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/list-view/use-list-view-drop-zone.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/** @typedef {import('../../utils/math').WPPoint} WPPoint */
/**
* The type of a drag event.
*
* @typedef {'default'|'file'|'html'} WPDragEventType
*/
/**
* An array representing data for blocks in the DOM used by drag and drop.
*
* @typedef {Object} WPListViewDropZoneBlocks
* @property {string} clientId The client id for the block.
* @property {string} rootClientId The root client id for the block.
* @property {number} blockIndex The block's index.
* @property {Element} element The DOM element representing the block.
* @property {number} innerBlockCount The number of inner blocks the block has.
* @property {boolean} isDraggedBlock Whether the block is currently being dragged.
* @property {boolean} canInsertDraggedBlocksAsSibling Whether the dragged block can be a sibling of this block.
* @property {boolean} canInsertDraggedBlocksAsChild Whether the dragged block can be a child of this block.
*/
/**
* An object containing details of a drop target.
*
* @typedef {Object} WPListViewDropZoneTarget
* @property {string} blockIndex The insertion index.
* @property {string} rootClientId The root client id for the block.
* @property {string|undefined} clientId The client id for the block.
* @property {'top'|'bottom'|'inside'} dropPosition The position relative to the block that the user is dropping to.
* 'inside' refers to nesting as an inner block.
*/
/**
* Determines whether the user positioning the dragged block to nest as an
* inner block.
*
* Presently this is determined by whether the cursor is on the right hand side
* of the block.
*
* @param {WPPoint} point The point representing the cursor position when dragging.
* @param {DOMRect} rect The rectangle.
*/
function isNestingGesture(point, rect) {
const blockCenterX = rect.left + rect.width / 2;
return point.x > blockCenterX;
} // Block navigation is always a vertical list, so only allow dropping
// to the above or below a block.
const ALLOWED_DROP_EDGES = ['top', 'bottom'];
/**
* Given blocks data and the cursor position, compute the drop target.
*
* @param {WPListViewDropZoneBlocks} blocksData Data about the blocks in list view.
* @param {WPPoint} position The point representing the cursor position when dragging.
*
* @return {WPListViewDropZoneTarget | undefined} An object containing data about the drop target.
*/
function getListViewDropTarget(blocksData, position) {
let candidateEdge;
let candidateBlockData;
let candidateDistance;
let candidateRect;
for (const blockData of blocksData) {
if (blockData.isDraggedBlock) {
continue;
}
const rect = blockData.element.getBoundingClientRect();
const [distance, edge] = getDistanceToNearestEdge(position, rect, ALLOWED_DROP_EDGES);
const isCursorWithinBlock = isPointContainedByRect(position, rect);
if (candidateDistance === undefined || distance < candidateDistance || isCursorWithinBlock) {
candidateDistance = distance;
const index = blocksData.indexOf(blockData);
const previousBlockData = blocksData[index - 1]; // If dragging near the top of a block and the preceding block
// is at the same level, use the preceding block as the candidate
// instead, as later it makes determining a nesting drop easier.
if (edge === 'top' && previousBlockData && previousBlockData.rootClientId === blockData.rootClientId && !previousBlockData.isDraggedBlock) {
candidateBlockData = previousBlockData;
candidateEdge = 'bottom';
candidateRect = previousBlockData.element.getBoundingClientRect();
} else {
candidateBlockData = blockData;
candidateEdge = edge;
candidateRect = rect;
} // If the mouse position is within the block, break early
// as the user would intend to drop either before or after
// this block.
//
// This solves an issue where some rows in the list view
// tree overlap slightly due to sub-pixel rendering.
if (isCursorWithinBlock) {
break;
}
}
}
if (!candidateBlockData) {
return;
}
const isDraggingBelow = candidateEdge === 'bottom'; // If the user is dragging towards the bottom of the block check whether
// they might be trying to nest the block as a child.
// If the block already has inner blocks, this should always be treated
// as nesting since the next block in the tree will be the first child.
if (isDraggingBelow && candidateBlockData.canInsertDraggedBlocksAsChild && (candidateBlockData.innerBlockCount > 0 || isNestingGesture(position, candidateRect))) {
return {
rootClientId: candidateBlockData.clientId,
blockIndex: 0,
dropPosition: 'inside'
};
} // If dropping as a sibling, but block cannot be inserted in
// this context, return early.
if (!candidateBlockData.canInsertDraggedBlocksAsSibling) {
return;
}
const offset = isDraggingBelow ? 1 : 0;
return {
rootClientId: candidateBlockData.rootClientId,
clientId: candidateBlockData.clientId,
blockIndex: candidateBlockData.blockIndex + offset,
dropPosition: candidateEdge
};
}
/**
* A react hook for implementing a drop zone in list view.
*
* @return {WPListViewDropZoneTarget} The drop target.
*/
function useListViewDropZone() {
const {
getBlockRootClientId,
getBlockIndex,
getBlockCount,
getDraggedBlockClientIds,
canInsertBlocks
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const [target, setTarget] = (0,external_wp_element_namespaceObject.useState)();
const {
rootClientId: targetRootClientId,
blockIndex: targetBlockIndex
} = target || {};
const onBlockDrop = useOnBlockDrop(targetRootClientId, targetBlockIndex);
const draggedBlockClientIds = getDraggedBlockClientIds();
const throttled = (0,external_wp_compose_namespaceObject.useThrottle)((0,external_wp_element_namespaceObject.useCallback)((event, currentTarget) => {
const position = {
x: event.clientX,
y: event.clientY
};
const isBlockDrag = !!(draggedBlockClientIds !== null && draggedBlockClientIds !== void 0 && draggedBlockClientIds.length);
const blockElements = Array.from(currentTarget.querySelectorAll('[data-block]'));
const blocksData = blockElements.map(blockElement => {
const clientId = blockElement.dataset.block;
const rootClientId = getBlockRootClientId(clientId);
return {
clientId,
rootClientId,
blockIndex: getBlockIndex(clientId),
element: blockElement,
isDraggedBlock: isBlockDrag ? draggedBlockClientIds.includes(clientId) : false,
innerBlockCount: getBlockCount(clientId),
canInsertDraggedBlocksAsSibling: isBlockDrag ? canInsertBlocks(draggedBlockClientIds, rootClientId) : true,
canInsertDraggedBlocksAsChild: isBlockDrag ? canInsertBlocks(draggedBlockClientIds, clientId) : true
};
});
const newTarget = getListViewDropTarget(blocksData, position);
if (newTarget) {
setTarget(newTarget);
}
}, [draggedBlockClientIds]), 200);
const ref = (0,external_wp_compose_namespaceObject.__experimentalUseDropZone)({
onDrop: onBlockDrop,
onDragOver(event) {
// `currentTarget` is only available while the event is being
// handled, so get it now and pass it to the thottled function.
// https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget
throttled(event, event.currentTarget);
},
onDragEnd() {
throttled.cancel();
setTarget(null);
}
});
return {
ref,
target
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/list-view/use-list-view-expand-selected-item.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useListViewExpandSelectedItem(_ref) {
let {
firstSelectedBlockClientId,
setExpandedState
} = _ref;
const [selectedTreeId, setSelectedTreeId] = (0,external_wp_element_namespaceObject.useState)(null);
const {
selectedBlockParentClientIds
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlockParents
} = select(store);
return {
selectedBlockParentClientIds: getBlockParents(firstSelectedBlockClientId, false)
};
}, [firstSelectedBlockClientId]);
const parentClientIds = Array.isArray(selectedBlockParentClientIds) && selectedBlockParentClientIds.length ? selectedBlockParentClientIds : null; // Expand tree when a block is selected.
(0,external_wp_element_namespaceObject.useEffect)(() => {
// If the selectedTreeId is the same as the selected block,
// it means that the block was selected using the block list tree.
if (selectedTreeId === firstSelectedBlockClientId) {
return;
} // If the selected block has parents, get the top-level parent.
if (parentClientIds) {
// If the selected block has parents,
// expand the tree branch.
setExpandedState({
type: 'expand',
clientIds: selectedBlockParentClientIds
});
}
}, [firstSelectedBlockClientId]);
return {
setSelectedTreeId
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/list-view/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const expanded = (state, action) => {
if (Array.isArray(action.clientIds)) {
return { ...state,
...action.clientIds.reduce((newState, id) => ({ ...newState,
[id]: action.type === 'expand'
}), {})
};
}
return state;
};
const BLOCK_LIST_ITEM_HEIGHT = 36;
/**
* Show a hierarchical list of blocks.
*
* @param {Object} props Components props.
* @param {string} props.id An HTML element id for the root element of ListView.
* @param {Array} props.blocks Custom subset of block client IDs to be used instead of the default hierarchy.
* @param {boolean} props.showBlockMovers Flag to enable block movers
* @param {boolean} props.isExpanded Flag to determine whether nested levels are expanded by default.
* @param {Object} ref Forwarded ref
*/
function ListView(_ref, ref) {
let {
id,
blocks,
showBlockMovers = false,
isExpanded = false
} = _ref;
const {
clientIdsTree,
draggedClientIds,
selectedClientIds
} = useListViewClientIds(blocks);
const {
visibleBlockCount,
shouldShowInnerBlocks
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getGlobalBlockCount,
getClientIdsOfDescendants,
__unstableGetEditorMode
} = select(store);
const draggedBlockCount = (draggedClientIds === null || draggedClientIds === void 0 ? void 0 : draggedClientIds.length) > 0 ? getClientIdsOfDescendants(draggedClientIds).length + 1 : 0;
return {
visibleBlockCount: getGlobalBlockCount() - draggedBlockCount,
shouldShowInnerBlocks: __unstableGetEditorMode() !== 'zoom-out'
};
}, [draggedClientIds]);
const {
updateBlockSelection
} = useBlockSelection();
const [expandedState, setExpandedState] = (0,external_wp_element_namespaceObject.useReducer)(expanded, {});
const {
ref: dropZoneRef,
target: blockDropTarget
} = useListViewDropZone();
const elementRef = (0,external_wp_element_namespaceObject.useRef)();
const treeGridRef = (0,external_wp_compose_namespaceObject.useMergeRefs)([elementRef, dropZoneRef, ref]);
const isMounted = (0,external_wp_element_namespaceObject.useRef)(false);
const {
setSelectedTreeId
} = useListViewExpandSelectedItem({
firstSelectedBlockClientId: selectedClientIds[0],
setExpandedState
});
const selectEditorBlock = (0,external_wp_element_namespaceObject.useCallback)((event, clientId) => {
updateBlockSelection(event, clientId);
setSelectedTreeId(clientId);
}, [setSelectedTreeId, updateBlockSelection]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
isMounted.current = true;
}, []); // List View renders a fixed number of items and relies on each having a fixed item height of 36px.
// If this value changes, we should also change the itemHeight value set in useFixedWindowList.
// See: https://github.com/WordPress/gutenberg/pull/35230 for additional context.
const [fixedListWindow] = (0,external_wp_compose_namespaceObject.__experimentalUseFixedWindowList)(elementRef, BLOCK_LIST_ITEM_HEIGHT, visibleBlockCount, {
useWindowing: true,
windowOverscan: 40
});
const expand = (0,external_wp_element_namespaceObject.useCallback)(clientId => {
if (!clientId) {
return;
}
setExpandedState({
type: 'expand',
clientIds: [clientId]
});
}, [setExpandedState]);
const collapse = (0,external_wp_element_namespaceObject.useCallback)(clientId => {
if (!clientId) {
return;
}
setExpandedState({
type: 'collapse',
clientIds: [clientId]
});
}, [setExpandedState]);
const expandRow = (0,external_wp_element_namespaceObject.useCallback)(row => {
var _row$dataset;
expand(row === null || row === void 0 ? void 0 : (_row$dataset = row.dataset) === null || _row$dataset === void 0 ? void 0 : _row$dataset.block);
}, [expand]);
const collapseRow = (0,external_wp_element_namespaceObject.useCallback)(row => {
var _row$dataset2;
collapse(row === null || row === void 0 ? void 0 : (_row$dataset2 = row.dataset) === null || _row$dataset2 === void 0 ? void 0 : _row$dataset2.block);
}, [collapse]);
const focusRow = (0,external_wp_element_namespaceObject.useCallback)((event, startRow, endRow) => {
if (event.shiftKey) {
var _startRow$dataset, _endRow$dataset;
updateBlockSelection(event, startRow === null || startRow === void 0 ? void 0 : (_startRow$dataset = startRow.dataset) === null || _startRow$dataset === void 0 ? void 0 : _startRow$dataset.block, endRow === null || endRow === void 0 ? void 0 : (_endRow$dataset = endRow.dataset) === null || _endRow$dataset === void 0 ? void 0 : _endRow$dataset.block);
}
}, [updateBlockSelection]);
const contextValue = (0,external_wp_element_namespaceObject.useMemo)(() => ({
isTreeGridMounted: isMounted.current,
draggedClientIds,
expandedState,
expand,
collapse
}), [isMounted.current, draggedClientIds, expandedState, expand, collapse]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_data_namespaceObject.AsyncModeProvider, {
value: true
}, (0,external_wp_element_namespaceObject.createElement)(ListViewDropIndicator, {
listViewRef: elementRef,
blockDropTarget: blockDropTarget
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalTreeGrid, {
id: id,
className: "block-editor-list-view-tree",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Block navigation structure'),
ref: treeGridRef,
onCollapseRow: collapseRow,
onExpandRow: expandRow,
onFocusRow: focusRow,
applicationAriaLabel: (0,external_wp_i18n_namespaceObject.__)('Block navigation structure')
}, (0,external_wp_element_namespaceObject.createElement)(ListViewContext.Provider, {
value: contextValue
}, (0,external_wp_element_namespaceObject.createElement)(branch, {
blocks: clientIdsTree,
selectBlock: selectEditorBlock,
showBlockMovers: showBlockMovers,
fixedListWindow: fixedListWindow,
selectedClientIds: selectedClientIds,
isExpanded: isExpanded,
shouldShowInnerBlocks: shouldShowInnerBlocks
}))));
}
/* harmony default export */ var components_list_view = ((0,external_wp_element_namespaceObject.forwardRef)(ListView));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-navigation/dropdown.js
/**
* WordPress dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function BlockNavigationDropdownToggle(_ref) {
let {
isEnabled,
onToggle,
isOpen,
innerRef,
...props
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, _extends({}, props, {
ref: innerRef,
icon: list_view,
"aria-expanded": isOpen,
"aria-haspopup": "true",
onClick: isEnabled ? onToggle : undefined
/* translators: button label text should, if possible, be under 16 characters. */
,
label: (0,external_wp_i18n_namespaceObject.__)('List view'),
className: "block-editor-block-navigation",
"aria-disabled": !isEnabled
}));
}
function BlockNavigationDropdown(_ref2, ref) {
let {
isDisabled,
...props
} = _ref2;
external_wp_deprecated_default()('wp.blockEditor.BlockNavigationDropdown', {
since: '6.1',
alternative: 'wp.components.Dropdown and wp.blockEditor.ListView'
});
const hasBlocks = (0,external_wp_data_namespaceObject.useSelect)(select => !!select(store).getBlockCount(), []);
const isEnabled = hasBlocks && !isDisabled;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Dropdown, {
contentClassName: "block-editor-block-navigation__popover",
popoverProps: {
placement: 'bottom-start'
},
renderToggle: _ref3 => {
let {
isOpen,
onToggle
} = _ref3;
return (0,external_wp_element_namespaceObject.createElement)(BlockNavigationDropdownToggle, _extends({}, props, {
innerRef: ref,
isOpen: isOpen,
onToggle: onToggle,
isEnabled: isEnabled
}));
},
renderContent: () => (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-navigation__container"
}, (0,external_wp_element_namespaceObject.createElement)("p", {
className: "block-editor-block-navigation__label"
}, (0,external_wp_i18n_namespaceObject.__)('List view')), (0,external_wp_element_namespaceObject.createElement)(components_list_view, null))
});
}
/* harmony default export */ var dropdown = ((0,external_wp_element_namespaceObject.forwardRef)(BlockNavigationDropdown));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-styles/preview-panel.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function BlockStylesPreviewPanel(_ref) {
var _getBlockType;
let {
genericPreviewBlock,
style,
className,
activeStyle
} = _ref;
const example = (_getBlockType = (0,external_wp_blocks_namespaceObject.getBlockType)(genericPreviewBlock.name)) === null || _getBlockType === void 0 ? void 0 : _getBlockType.example;
const styleClassName = replaceActiveStyle(className, activeStyle, style);
const previewBlocks = (0,external_wp_element_namespaceObject.useMemo)(() => {
return { ...genericPreviewBlock,
title: style.label || style.name,
description: style.description,
initialAttributes: { ...genericPreviewBlock.attributes,
className: styleClassName + ' block-editor-block-styles__block-preview-container'
},
example
};
}, [genericPreviewBlock, styleClassName]);
return (0,external_wp_element_namespaceObject.createElement)(preview_panel, {
item: previewBlocks,
isStylePreview: true
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-styles/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const block_styles_noop = () => {}; // Block Styles component for the Settings Sidebar.
function BlockStyles(_ref) {
let {
clientId,
onSwitch = block_styles_noop,
onHoverClassName = block_styles_noop
} = _ref;
const {
onSelect,
stylesToRender,
activeStyle,
genericPreviewBlock,
className: previewClassName
} = useStylesForBlocks({
clientId,
onSwitch
});
const [hoveredStyle, setHoveredStyle] = (0,external_wp_element_namespaceObject.useState)(null);
const isMobileViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('medium', '<');
if (!stylesToRender || stylesToRender.length === 0) {
return null;
}
const debouncedSetHoveredStyle = (0,external_wp_compose_namespaceObject.debounce)(setHoveredStyle, 250);
const onSelectStylePreview = style => {
onSelect(style);
onHoverClassName(null);
setHoveredStyle(null);
debouncedSetHoveredStyle.cancel();
};
const styleItemHandler = item => {
var _item$name;
if (hoveredStyle === item) {
debouncedSetHoveredStyle.cancel();
return;
}
debouncedSetHoveredStyle(item);
onHoverClassName((_item$name = item === null || item === void 0 ? void 0 : item.name) !== null && _item$name !== void 0 ? _item$name : null);
};
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-styles"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-styles__variants"
}, stylesToRender.map(style => {
const buttonText = style.isDefault ? (0,external_wp_i18n_namespaceObject.__)('Default') : style.label || style.name;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: classnames_default()('block-editor-block-styles__item', {
'is-active': activeStyle.name === style.name
}),
key: style.name,
variant: "secondary",
label: buttonText,
onMouseEnter: () => styleItemHandler(style),
onFocus: () => styleItemHandler(style),
onMouseLeave: () => styleItemHandler(null),
onBlur: () => styleItemHandler(null),
onClick: () => onSelectStylePreview(style),
"aria-current": activeStyle.name === style.name
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalTruncate, {
numberOfLines: 1,
className: "block-editor-block-styles__item-text"
}, buttonText));
})), hoveredStyle && !isMobileViewport && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Popover, {
placement: "left-start",
offset: 20
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-styles__preview-panel",
onMouseLeave: () => styleItemHandler(null)
}, (0,external_wp_element_namespaceObject.createElement)(BlockStylesPreviewPanel, {
activeStyle: activeStyle,
className: previewClassName,
genericPreviewBlock: genericPreviewBlock,
style: hoveredStyle
}))));
}
/* harmony default export */ var block_styles = (BlockStyles);
BlockStyles.Slot = () => {
external_wp_deprecated_default()('BlockStyles.Slot', {
version: '6.4',
since: '6.2'
});
return null;
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/layout.js
/**
* WordPress dependencies
*/
const layout = (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: "M18 5.5H6a.5.5 0 00-.5.5v3h13V6a.5.5 0 00-.5-.5zm.5 5H10v8h8a.5.5 0 00.5-.5v-7.5zm-10 0h-3V18a.5.5 0 00.5.5h2.5v-8zM6 4h12a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2z"
}));
/* harmony default export */ var library_layout = (layout);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-variation-picker/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
function BlockVariationPicker(_ref) {
let {
icon = library_layout,
label = (0,external_wp_i18n_namespaceObject.__)('Choose variation'),
instructions = (0,external_wp_i18n_namespaceObject.__)('Select a variation to start with.'),
variations,
onSelect,
allowSkip
} = _ref;
const classes = classnames_default()('block-editor-block-variation-picker', {
'has-many-variations': variations.length > 4
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Placeholder, {
icon: icon,
label: label,
instructions: instructions,
className: classes
}, (0,external_wp_element_namespaceObject.createElement)("ul", {
className: "block-editor-block-variation-picker__variations",
role: "list",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Block variations')
}, variations.map(variation => (0,external_wp_element_namespaceObject.createElement)("li", {
key: variation.name
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "secondary",
icon: variation.icon && variation.icon.src ? variation.icon.src : variation.icon,
iconSize: 48,
onClick: () => onSelect(variation),
className: "block-editor-block-variation-picker__variation",
label: variation.description || variation.title
}), (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-block-variation-picker__variation-label"
}, variation.title)))), allowSkip && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-variation-picker__skip"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "link",
onClick: () => onSelect()
}, (0,external_wp_i18n_namespaceObject.__)('Skip'))));
}
/* harmony default export */ var block_variation_picker = (BlockVariationPicker);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/grid.js
/**
* WordPress dependencies
*/
const grid = (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 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7.8 16.5H5c-.3 0-.5-.2-.5-.5v-6.2h6.8v6.7zm0-8.3H4.5V5c0-.3.2-.5.5-.5h6.2v6.7zm8.3 7.8c0 .3-.2.5-.5.5h-6.2v-6.8h6.8V19zm0-7.8h-6.8V4.5H19c.3 0 .5.2.5.5v6.2z",
fillRule: "evenodd",
clipRule: "evenodd"
}));
/* harmony default export */ var library_grid = (grid);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-pattern-setup/constants.js
const VIEWMODES = {
carousel: 'carousel',
grid: 'grid'
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-pattern-setup/setup-toolbar.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const Actions = _ref => {
let {
onBlockPatternSelect
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-pattern-setup__actions"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "primary",
onClick: onBlockPatternSelect
}, (0,external_wp_i18n_namespaceObject.__)('Choose')));
};
const CarouselNavigation = _ref2 => {
let {
handlePrevious,
handleNext,
activeSlide,
totalSlides
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-pattern-setup__navigation"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
icon: chevron_left,
label: (0,external_wp_i18n_namespaceObject.__)('Previous pattern'),
onClick: handlePrevious,
disabled: activeSlide === 0
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
icon: chevron_right,
label: (0,external_wp_i18n_namespaceObject.__)('Next pattern'),
onClick: handleNext,
disabled: activeSlide === totalSlides - 1
}));
};
const SetupToolbar = _ref3 => {
let {
viewMode,
setViewMode,
handlePrevious,
handleNext,
activeSlide,
totalSlides,
onBlockPatternSelect
} = _ref3;
const isCarouselView = viewMode === VIEWMODES.carousel;
const displayControls = (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-pattern-setup__display-controls"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
icon: stretch_full_width,
label: (0,external_wp_i18n_namespaceObject.__)('Carousel view'),
onClick: () => setViewMode(VIEWMODES.carousel),
isPressed: isCarouselView
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
icon: library_grid,
label: (0,external_wp_i18n_namespaceObject.__)('Grid view'),
onClick: () => setViewMode(VIEWMODES.grid),
isPressed: viewMode === VIEWMODES.grid
}));
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-pattern-setup__toolbar"
}, isCarouselView && (0,external_wp_element_namespaceObject.createElement)(CarouselNavigation, {
handlePrevious: handlePrevious,
handleNext: handleNext,
activeSlide: activeSlide,
totalSlides: totalSlides
}), displayControls, isCarouselView && (0,external_wp_element_namespaceObject.createElement)(Actions, {
onBlockPatternSelect: onBlockPatternSelect
}));
};
/* harmony default export */ var setup_toolbar = (SetupToolbar);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-pattern-setup/use-patterns-setup.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function usePatternsSetup(clientId, blockName, filterPatternsFn) {
return (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlockRootClientId,
getPatternsByBlockTypes,
__experimentalGetAllowedPatterns
} = select(store);
const rootClientId = getBlockRootClientId(clientId);
if (filterPatternsFn) {
return __experimentalGetAllowedPatterns(rootClientId).filter(filterPatternsFn);
}
return getPatternsByBlockTypes(blockName, rootClientId);
}, [clientId, blockName, filterPatternsFn]);
}
/* harmony default export */ var use_patterns_setup = (usePatternsSetup);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-pattern-setup/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const SetupContent = _ref => {
let {
viewMode,
activeSlide,
patterns,
onBlockPatternSelect,
showTitles
} = _ref;
const composite = (0,external_wp_components_namespaceObject.__unstableUseCompositeState)();
const containerClass = 'block-editor-block-pattern-setup__container';
if (viewMode === VIEWMODES.carousel) {
const slideClass = new Map([[activeSlide, 'active-slide'], [activeSlide - 1, 'previous-slide'], [activeSlide + 1, 'next-slide']]);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-pattern-setup__carousel"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: containerClass
}, (0,external_wp_element_namespaceObject.createElement)("ul", {
className: "carousel-container"
}, patterns.map((pattern, index) => (0,external_wp_element_namespaceObject.createElement)(BlockPatternSlide, {
className: slideClass.get(index) || '',
key: pattern.name,
pattern: pattern
})))));
}
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-pattern-setup__grid"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableComposite, _extends({}, composite, {
role: "listbox",
className: containerClass,
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Patterns list')
}), patterns.map(pattern => (0,external_wp_element_namespaceObject.createElement)(block_pattern_setup_BlockPattern, {
key: pattern.name,
pattern: pattern,
onSelect: onBlockPatternSelect,
composite: composite,
showTitles: showTitles
}))));
};
function block_pattern_setup_BlockPattern(_ref2) {
let {
pattern,
onSelect,
composite,
showTitles
} = _ref2;
const baseClassName = 'block-editor-block-pattern-setup-list';
const {
blocks,
description,
viewportWidth = 700
} = pattern;
const descriptionId = (0,external_wp_compose_namespaceObject.useInstanceId)(block_pattern_setup_BlockPattern, `${baseClassName}__item-description`);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: `${baseClassName}__list-item`,
"aria-label": pattern.title,
"aria-describedby": pattern.description ? descriptionId : undefined
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableCompositeItem, _extends({
role: "option",
as: "div"
}, composite, {
className: `${baseClassName}__item`,
onClick: () => onSelect(blocks)
}), (0,external_wp_element_namespaceObject.createElement)(block_preview, {
blocks: blocks,
viewportWidth: viewportWidth
}), showTitles && (0,external_wp_element_namespaceObject.createElement)("div", {
className: `${baseClassName}__item-title`
}, pattern.title), !!description && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.VisuallyHidden, {
id: descriptionId
}, description)));
}
function BlockPatternSlide(_ref3) {
let {
className,
pattern,
minHeight
} = _ref3;
const {
blocks,
title,
description
} = pattern;
const descriptionId = (0,external_wp_compose_namespaceObject.useInstanceId)(BlockPatternSlide, 'block-editor-block-pattern-setup-list__item-description');
return (0,external_wp_element_namespaceObject.createElement)("li", {
className: `pattern-slide ${className}`,
"aria-label": title,
"aria-describedby": description ? descriptionId : undefined
}, (0,external_wp_element_namespaceObject.createElement)(block_preview, {
blocks: blocks,
minHeight: minHeight
}), !!description && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.VisuallyHidden, {
id: descriptionId
}, description));
}
const BlockPatternSetup = _ref4 => {
let {
clientId,
blockName,
filterPatternsFn,
onBlockPatternSelect,
initialViewMode = VIEWMODES.carousel,
showTitles = false
} = _ref4;
const [viewMode, setViewMode] = (0,external_wp_element_namespaceObject.useState)(initialViewMode);
const [activeSlide, setActiveSlide] = (0,external_wp_element_namespaceObject.useState)(0);
const {
replaceBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const patterns = use_patterns_setup(clientId, blockName, filterPatternsFn);
if (!(patterns !== null && patterns !== void 0 && patterns.length)) {
return null;
}
const onBlockPatternSelectDefault = blocks => {
const clonedBlocks = blocks.map(block => (0,external_wp_blocks_namespaceObject.cloneBlock)(block));
replaceBlock(clientId, clonedBlocks);
};
const onPatternSelectCallback = onBlockPatternSelect || onBlockPatternSelectDefault;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("div", {
className: `block-editor-block-pattern-setup view-mode-${viewMode}`
}, (0,external_wp_element_namespaceObject.createElement)(SetupContent, {
viewMode: viewMode,
activeSlide: activeSlide,
patterns: patterns,
onBlockPatternSelect: onPatternSelectCallback,
showTitles: showTitles
}), (0,external_wp_element_namespaceObject.createElement)(setup_toolbar, {
viewMode: viewMode,
setViewMode: setViewMode,
activeSlide: activeSlide,
totalSlides: patterns.length,
handleNext: () => {
setActiveSlide(active => active + 1);
},
handlePrevious: () => {
setActiveSlide(active => active - 1);
},
onBlockPatternSelect: () => {
onPatternSelectCallback(patterns[activeSlide].blocks);
}
})));
};
/* harmony default export */ var block_pattern_setup = (BlockPatternSetup);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-variation-transforms/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function VariationsButtons(_ref) {
let {
className,
onSelectVariation,
selectedValue,
variations
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("fieldset", {
className: className
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.VisuallyHidden, {
as: "legend"
}, (0,external_wp_i18n_namespaceObject.__)('Transform to variation')), variations.map(variation => (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
key: variation.name,
icon: (0,external_wp_element_namespaceObject.createElement)(block_icon, {
icon: variation.icon,
showColors: true
}),
isPressed: selectedValue === variation.name,
label: selectedValue === variation.name ? variation.title : (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: Name of the block variation */
(0,external_wp_i18n_namespaceObject.__)('Transform to %s'), variation.title),
onClick: () => onSelectVariation(variation.name),
"aria-label": variation.title,
showTooltip: true
})));
}
function VariationsDropdown(_ref2) {
let {
className,
onSelectVariation,
selectedValue,
variations
} = _ref2;
const selectOptions = variations.map(_ref3 => {
let {
name,
title,
description
} = _ref3;
return {
value: name,
label: title,
info: description
};
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.DropdownMenu, {
className: className,
label: (0,external_wp_i18n_namespaceObject.__)('Transform to variation'),
text: (0,external_wp_i18n_namespaceObject.__)('Transform to variation'),
popoverProps: {
position: 'bottom center',
className: `${className}__popover`
},
icon: chevron_down,
toggleProps: {
iconPosition: 'right'
}
}, () => (0,external_wp_element_namespaceObject.createElement)("div", {
className: `${className}__container`
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItemsChoice, {
choices: selectOptions,
value: selectedValue,
onSelect: onSelectVariation
}))));
}
function __experimentalBlockVariationTransforms(_ref4) {
let {
blockClientId
} = _ref4;
const {
updateBlockAttributes
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const {
activeBlockVariation,
variations
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getActiveBlockVariation,
getBlockVariations
} = select(external_wp_blocks_namespaceObject.store);
const {
getBlockName,
getBlockAttributes
} = select(store);
const name = blockClientId && getBlockName(blockClientId);
return {
activeBlockVariation: getActiveBlockVariation(name, getBlockAttributes(blockClientId)),
variations: name && getBlockVariations(name, 'transform')
};
}, [blockClientId]);
const selectedValue = activeBlockVariation === null || activeBlockVariation === void 0 ? void 0 : activeBlockVariation.name; // Check if each variation has a unique icon.
const hasUniqueIcons = (0,external_wp_element_namespaceObject.useMemo)(() => {
const variationIcons = new Set();
if (!variations) {
return false;
}
variations.forEach(variation => {
if (variation.icon) {
var _variation$icon;
variationIcons.add(((_variation$icon = variation.icon) === null || _variation$icon === void 0 ? void 0 : _variation$icon.src) || variation.icon);
}
});
return variationIcons.size === variations.length;
}, [variations]);
const onSelectVariation = variationName => {
updateBlockAttributes(blockClientId, { ...variations.find(_ref5 => {
let {
name
} = _ref5;
return name === variationName;
}).attributes
});
};
const baseClass = 'block-editor-block-variation-transforms'; // Skip rendering if there are no variations
if (!(variations !== null && variations !== void 0 && variations.length)) return null;
const Component = hasUniqueIcons ? VariationsButtons : VariationsDropdown;
return (0,external_wp_element_namespaceObject.createElement)(Component, {
className: baseClass,
onSelectVariation: onSelectVariation,
selectedValue: selectedValue,
variations: variations
});
}
/* harmony default export */ var block_variation_transforms = (__experimentalBlockVariationTransforms);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/color-palette/with-color-context.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/* harmony default export */ var with_color_context = ((0,external_wp_compose_namespaceObject.createHigherOrderComponent)(WrappedComponent => {
return props => {
const colorsFeature = useSetting('color.palette');
const disableCustomColorsFeature = !useSetting('color.custom');
const colors = props.colors === undefined ? colorsFeature : props.colors;
const disableCustomColors = props.disableCustomColors === undefined ? disableCustomColorsFeature : props.disableCustomColors;
const hasColorsToChoose = !(0,external_lodash_namespaceObject.isEmpty)(colors) || !disableCustomColors;
return (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, _extends({}, props, {
colors,
disableCustomColors,
hasColorsToChoose
}));
};
}, 'withColorContext'));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/color-palette/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/* harmony default export */ var color_palette = (with_color_context(external_wp_components_namespaceObject.ColorPalette));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/color-palette/control.js
/**
* Internal dependencies
*/
function ColorPaletteControl(_ref) {
let {
onChange,
value,
...otherProps
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(control, _extends({}, otherProps, {
onColorChange: onChange,
colorValue: value,
gradients: [],
disableCustomGradients: true
}));
}
;// CONCATENATED MODULE: external ["wp","date"]
var external_wp_date_namespaceObject = window["wp"]["date"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/date-format-picker/index.js
/**
* WordPress dependencies
*/
// So that we can illustrate the different formats in the dropdown properly,
// show a date that has a day greater than 12 and a month with more than three
// letters. Here we're using 2022-01-25 which is when WordPress 5.9 was
// released.
const EXAMPLE_DATE = new Date(2022, 0, 25);
/**
* The `DateFormatPicker` component renders controls that let the user choose a
* _date format_. That is, how they want their dates to be formatted.
*
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/date-format-picker/README.md
*
* @param {Object} props
* @param {string|null} props.format The selected date
* format. If
* `null`,
* _Default_ is
* selected.
* @param {string} props.defaultFormat The date format that
* will be used if the
* user selects
* 'Default'.
* @param {( format: string|null ) => void} props.onChange Called when a
* selection is
* made. If `null`,
* _Default_ is
* selected.
*/
function DateFormatPicker(_ref) {
let {
format,
defaultFormat,
onChange
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("fieldset", {
className: "block-editor-date-format-picker"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.VisuallyHidden, {
as: "legend"
}, (0,external_wp_i18n_namespaceObject.__)('Date format')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToggleControl, {
label: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_i18n_namespaceObject.__)('Default format'), (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-date-format-picker__default-format-toggle-control__hint"
}, (0,external_wp_date_namespaceObject.dateI18n)(defaultFormat, EXAMPLE_DATE))),
checked: !format,
onChange: checked => onChange(checked ? null : defaultFormat)
}), format && (0,external_wp_element_namespaceObject.createElement)(NonDefaultControls, {
format: format,
onChange: onChange
}));
}
function NonDefaultControls(_ref2) {
var _suggestedOptions$fin;
let {
format,
onChange
} = _ref2;
// Suggest a short format, medium format, long format, and a standardised
// (YYYY-MM-DD) format. The short, medium, and long formats are localised as
// different languages have different ways of writing these. For example, 'F
// j, Y' (April 20, 2022) in American English (en_US) is 'j. F Y' (20. April
// 2022) in German (de). The resultant array is de-duplicated as some
// languages will use the same format string for short, medium, and long
// formats.
const suggestedFormats = [...new Set(['Y-m-d', (0,external_wp_i18n_namespaceObject._x)('n/j/Y', 'short date format'), (0,external_wp_i18n_namespaceObject._x)('n/j/Y g:i A', 'short date format with time'), (0,external_wp_i18n_namespaceObject._x)('M j, Y', 'medium date format'), (0,external_wp_i18n_namespaceObject._x)('M j, Y g:i A', 'medium date format with time'), (0,external_wp_i18n_namespaceObject._x)('F j, Y', 'long date format'), (0,external_wp_i18n_namespaceObject._x)('M j', 'short date format without the year')])];
const suggestedOptions = suggestedFormats.map((suggestedFormat, index) => ({
key: `suggested-${index}`,
name: (0,external_wp_date_namespaceObject.dateI18n)(suggestedFormat, EXAMPLE_DATE),
format: suggestedFormat
}));
const customOption = {
key: 'custom',
name: (0,external_wp_i18n_namespaceObject.__)('Custom'),
className: 'block-editor-date-format-picker__custom-format-select-control__custom-option',
__experimentalHint: (0,external_wp_i18n_namespaceObject.__)('Enter your own date format')
};
const [isCustom, setIsCustom] = (0,external_wp_element_namespaceObject.useState)(() => !!format && !suggestedFormats.includes(format));
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalVStack, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.CustomSelectControl, {
__nextUnconstrainedWidth: true,
label: (0,external_wp_i18n_namespaceObject.__)('Choose a format'),
options: [...suggestedOptions, customOption],
value: isCustom ? customOption : (_suggestedOptions$fin = suggestedOptions.find(option => option.format === format)) !== null && _suggestedOptions$fin !== void 0 ? _suggestedOptions$fin : customOption,
onChange: _ref3 => {
let {
selectedItem
} = _ref3;
if (selectedItem === customOption) {
setIsCustom(true);
} else {
setIsCustom(false);
onChange(selectedItem.format);
}
}
}), isCustom && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.TextControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Custom format'),
hideLabelFromVision: true,
help: (0,external_wp_element_namespaceObject.createInterpolateElement)((0,external_wp_i18n_namespaceObject.__)('Enter a date or time <Link>format string</Link>.'), {
Link: (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ExternalLink, {
href: (0,external_wp_i18n_namespaceObject.__)('https://wordpress.org/support/article/formatting-date-and-time/')
})
}),
value: format,
onChange: value => onChange(value)
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/colors-gradients/panel-color-gradient-settings.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const panel_color_gradient_settings_colorsAndGradientKeys = ['colors', 'disableCustomColors', 'gradients', 'disableCustomGradients'];
const PanelColorGradientSettingsInner = _ref => {
let {
className,
colors,
gradients,
disableCustomColors,
disableCustomGradients,
children,
settings,
title,
showTitle = true,
__experimentalIsRenderedInSidebar,
enableAlpha
} = _ref;
const panelId = (0,external_wp_compose_namespaceObject.useInstanceId)(PanelColorGradientSettingsInner);
const {
batch
} = (0,external_wp_data_namespaceObject.useRegistry)();
if ((0,external_lodash_namespaceObject.isEmpty)(colors) && (0,external_lodash_namespaceObject.isEmpty)(gradients) && disableCustomColors && disableCustomGradients && settings !== null && settings !== void 0 && settings.every(setting => (0,external_lodash_namespaceObject.isEmpty)(setting.colors) && (0,external_lodash_namespaceObject.isEmpty)(setting.gradients) && (setting.disableCustomColors === undefined || setting.disableCustomColors) && (setting.disableCustomGradients === undefined || setting.disableCustomGradients))) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalToolsPanel, {
className: classnames_default()('block-editor-panel-color-gradient-settings', className),
label: showTitle ? title : undefined,
resetAll: () => {
batch(() => {
settings.forEach(_ref2 => {
let {
colorValue,
gradientValue,
onColorChange,
onGradientChange
} = _ref2;
if (colorValue) {
onColorChange();
} else if (gradientValue) {
onGradientChange();
}
});
});
},
panelId: panelId,
__experimentalFirstVisibleItemClass: "first",
__experimentalLastVisibleItemClass: "last"
}, (0,external_wp_element_namespaceObject.createElement)(ColorGradientSettingsDropdown, {
settings: settings,
panelId: panelId,
colors,
gradients,
disableCustomColors,
disableCustomGradients,
__experimentalIsRenderedInSidebar,
enableAlpha
}), !!children && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalSpacer, {
marginY: 4
}), " ", children));
};
const PanelColorGradientSettingsSelect = props => {
const colorGradientSettings = useMultipleOriginColorsAndGradients();
return (0,external_wp_element_namespaceObject.createElement)(PanelColorGradientSettingsInner, _extends({}, colorGradientSettings, props));
};
const PanelColorGradientSettings = props => {
if (panel_color_gradient_settings_colorsAndGradientKeys.every(key => props.hasOwnProperty(key))) {
return (0,external_wp_element_namespaceObject.createElement)(PanelColorGradientSettingsInner, props);
}
return (0,external_wp_element_namespaceObject.createElement)(PanelColorGradientSettingsSelect, props);
};
/* harmony default export */ var panel_color_gradient_settings = (PanelColorGradientSettings);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/image-editor/use-save-image.js
/**
* WordPress dependencies
*/
// Disable Reason: Needs to be refactored.
// eslint-disable-next-line no-restricted-imports
function useSaveImage(_ref) {
let {
crop,
rotation,
height,
width,
aspect,
url,
id,
onSaveImage,
onFinishEditing
} = _ref;
const {
createErrorNotice
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_notices_namespaceObject.store);
const [isInProgress, setIsInProgress] = (0,external_wp_element_namespaceObject.useState)(false);
const cancel = (0,external_wp_element_namespaceObject.useCallback)(() => {
setIsInProgress(false);
onFinishEditing();
}, [setIsInProgress, onFinishEditing]);
const apply = (0,external_wp_element_namespaceObject.useCallback)(() => {
setIsInProgress(true);
let attrs = {}; // The crop script may return some very small, sub-pixel values when the image was not cropped.
// Crop only when the new size has changed by more than 0.1%.
if (crop.width < 99.9 || crop.height < 99.9) {
attrs = crop;
}
if (rotation > 0) {
attrs.rotation = rotation;
}
attrs.src = url;
external_wp_apiFetch_default()({
path: `/wp/v2/media/${id}/edit`,
method: 'POST',
data: attrs
}).then(response => {
onSaveImage({
id: response.id,
url: response.source_url,
height: height && width ? width / aspect : undefined
});
}).catch(error => {
createErrorNotice((0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: 1. Error message */
(0,external_wp_i18n_namespaceObject.__)('Could not edit image. %s'), (0,external_wp_dom_namespaceObject.__unstableStripHTML)(error.message)), {
id: 'image-editing-error',
type: 'snackbar'
});
}).finally(() => {
setIsInProgress(false);
onFinishEditing();
});
}, [setIsInProgress, crop, rotation, height, width, aspect, url, onSaveImage, createErrorNotice, setIsInProgress, onFinishEditing]);
return (0,external_wp_element_namespaceObject.useMemo)(() => ({
isInProgress,
apply,
cancel
}), [isInProgress, apply, cancel]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/image-editor/use-transform-image.js
/**
* WordPress dependencies
*/
function useTransformImage(_ref) {
let {
url,
naturalWidth,
naturalHeight
} = _ref;
const [editedUrl, setEditedUrl] = (0,external_wp_element_namespaceObject.useState)();
const [crop, setCrop] = (0,external_wp_element_namespaceObject.useState)();
const [position, setPosition] = (0,external_wp_element_namespaceObject.useState)({
x: 0,
y: 0
});
const [zoom, setZoom] = (0,external_wp_element_namespaceObject.useState)(100);
const [rotation, setRotation] = (0,external_wp_element_namespaceObject.useState)(0);
const defaultAspect = naturalWidth / naturalHeight;
const [aspect, setAspect] = (0,external_wp_element_namespaceObject.useState)(defaultAspect);
const rotateClockwise = (0,external_wp_element_namespaceObject.useCallback)(() => {
const angle = (rotation + 90) % 360;
let naturalAspectRatio = defaultAspect;
if (rotation % 180 === 90) {
naturalAspectRatio = 1 / defaultAspect;
}
if (angle === 0) {
setEditedUrl();
setRotation(angle);
setAspect(defaultAspect);
setPosition({
x: -(position.y * naturalAspectRatio),
y: position.x * naturalAspectRatio
});
return;
}
function editImage(event) {
const canvas = document.createElement('canvas');
let translateX = 0;
let translateY = 0;
if (angle % 180) {
canvas.width = event.target.height;
canvas.height = event.target.width;
} else {
canvas.width = event.target.width;
canvas.height = event.target.height;
}
if (angle === 90 || angle === 180) {
translateX = canvas.width;
}
if (angle === 270 || angle === 180) {
translateY = canvas.height;
}
const context = canvas.getContext('2d');
context.translate(translateX, translateY);
context.rotate(angle * Math.PI / 180);
context.drawImage(event.target, 0, 0);
canvas.toBlob(blob => {
setEditedUrl(URL.createObjectURL(blob));
setRotation(angle);
setAspect(canvas.width / canvas.height);
setPosition({
x: -(position.y * naturalAspectRatio),
y: position.x * naturalAspectRatio
});
});
}
const el = new window.Image();
el.src = url;
el.onload = editImage;
const imgCrossOrigin = (0,external_wp_hooks_namespaceObject.applyFilters)('media.crossOrigin', undefined, url);
if (typeof imgCrossOrigin === 'string') {
el.crossOrigin = imgCrossOrigin;
}
}, [rotation, defaultAspect]);
return (0,external_wp_element_namespaceObject.useMemo)(() => ({
editedUrl,
setEditedUrl,
crop,
setCrop,
position,
setPosition,
zoom,
setZoom,
rotation,
setRotation,
rotateClockwise,
aspect,
setAspect,
defaultAspect
}), [editedUrl, crop, position, zoom, rotation, rotateClockwise, aspect, defaultAspect]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/image-editor/context.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const ImageEditingContext = (0,external_wp_element_namespaceObject.createContext)({});
const useImageEditingContext = () => (0,external_wp_element_namespaceObject.useContext)(ImageEditingContext);
function ImageEditingProvider(_ref) {
let {
id,
url,
naturalWidth,
naturalHeight,
onFinishEditing,
onSaveImage,
children
} = _ref;
const transformImage = useTransformImage({
url,
naturalWidth,
naturalHeight
});
const saveImage = useSaveImage({
id,
url,
onSaveImage,
onFinishEditing,
...transformImage
});
const providerValue = (0,external_wp_element_namespaceObject.useMemo)(() => ({ ...transformImage,
...saveImage
}), [transformImage, saveImage]);
return (0,external_wp_element_namespaceObject.createElement)(ImageEditingContext.Provider, {
value: providerValue
}, children);
}
;// CONCATENATED MODULE: ./node_modules/react-easy-crop/node_modules/tslib/tslib.es6.js
/*! *****************************************************************************
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 */
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) {
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 __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 (_) 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;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (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;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
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 __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: n === "return" } : 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, privateMap) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to get private field on non-instance");
}
return privateMap.get(receiver);
}
function __classPrivateFieldSet(receiver, privateMap, value) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to set private field on non-instance");
}
privateMap.set(receiver, value);
return value;
}
// EXTERNAL MODULE: ./node_modules/normalize-wheel/index.js
var normalize_wheel = __webpack_require__(7970);
var normalize_wheel_default = /*#__PURE__*/__webpack_require__.n(normalize_wheel);
;// CONCATENATED MODULE: ./node_modules/react-easy-crop/index.module.js
/**
* Compute the dimension of the crop area based on media size,
* aspect ratio and optionally rotation
*/
function getCropSize(mediaWidth, mediaHeight, containerWidth, containerHeight, aspect, rotation) {
if (rotation === void 0) {
rotation = 0;
}
var _a = rotateSize(mediaWidth, mediaHeight, rotation),
width = _a.width,
height = _a.height;
var fittingWidth = Math.min(width, containerWidth);
var fittingHeight = Math.min(height, containerHeight);
if (fittingWidth > fittingHeight * aspect) {
return {
width: fittingHeight * aspect,
height: fittingHeight
};
}
return {
width: fittingWidth,
height: fittingWidth / aspect
};
}
/**
* Compute media zoom.
* We fit the media into the container with "max-width: 100%; max-height: 100%;"
*/
function getMediaZoom(mediaSize) {
// Take the axis with more pixels to improve accuracy
return mediaSize.width > mediaSize.height ? mediaSize.width / mediaSize.naturalWidth : mediaSize.height / mediaSize.naturalHeight;
}
/**
* Ensure a new media position stays in the crop area.
*/
function restrictPosition(position, mediaSize, cropSize, zoom, rotation) {
if (rotation === void 0) {
rotation = 0;
}
var _a = rotateSize(mediaSize.width, mediaSize.height, rotation),
width = _a.width,
height = _a.height;
return {
x: restrictPositionCoord(position.x, width, cropSize.width, zoom),
y: restrictPositionCoord(position.y, height, cropSize.height, zoom)
};
}
function restrictPositionCoord(position, mediaSize, cropSize, zoom) {
var maxPosition = mediaSize * zoom / 2 - cropSize / 2;
return index_module_clamp(position, -maxPosition, maxPosition);
}
function getDistanceBetweenPoints(pointA, pointB) {
return Math.sqrt(Math.pow(pointA.y - pointB.y, 2) + Math.pow(pointA.x - pointB.x, 2));
}
function getRotationBetweenPoints(pointA, pointB) {
return Math.atan2(pointB.y - pointA.y, pointB.x - pointA.x) * 180 / Math.PI;
}
/**
* Compute the output cropped area of the media in percentages and pixels.
* x/y are the top-left coordinates on the src media
*/
function computeCroppedArea(crop, mediaSize, cropSize, aspect, zoom, rotation, restrictPosition) {
if (rotation === void 0) {
rotation = 0;
}
if (restrictPosition === void 0) {
restrictPosition = true;
}
// if the media is rotated by the user, we cannot limit the position anymore
// as it might need to be negative.
var limitAreaFn = restrictPosition ? limitArea : noOp;
var mediaBBoxSize = rotateSize(mediaSize.width, mediaSize.height, rotation);
var mediaNaturalBBoxSize = rotateSize(mediaSize.naturalWidth, mediaSize.naturalHeight, rotation);
// calculate the crop area in percentages
// in the rotated space
var croppedAreaPercentages = {
x: limitAreaFn(100, ((mediaBBoxSize.width - cropSize.width / zoom) / 2 - crop.x / zoom) / mediaBBoxSize.width * 100),
y: limitAreaFn(100, ((mediaBBoxSize.height - cropSize.height / zoom) / 2 - crop.y / zoom) / mediaBBoxSize.height * 100),
width: limitAreaFn(100, cropSize.width / mediaBBoxSize.width * 100 / zoom),
height: limitAreaFn(100, cropSize.height / mediaBBoxSize.height * 100 / zoom)
};
// we compute the pixels size naively
var widthInPixels = Math.round(limitAreaFn(mediaNaturalBBoxSize.width, croppedAreaPercentages.width * mediaNaturalBBoxSize.width / 100));
var heightInPixels = Math.round(limitAreaFn(mediaNaturalBBoxSize.height, croppedAreaPercentages.height * mediaNaturalBBoxSize.height / 100));
var isImgWiderThanHigh = mediaNaturalBBoxSize.width >= mediaNaturalBBoxSize.height * aspect;
// then we ensure the width and height exactly match the aspect (to avoid rounding approximations)
// if the media is wider than high, when zoom is 0, the crop height will be equals to image height
// thus we want to compute the width from the height and aspect for accuracy.
// Otherwise, we compute the height from width and aspect.
var sizePixels = isImgWiderThanHigh ? {
width: Math.round(heightInPixels * aspect),
height: heightInPixels
} : {
width: widthInPixels,
height: Math.round(widthInPixels / aspect)
};
var croppedAreaPixels = __assign(__assign({}, sizePixels), {
x: Math.round(limitAreaFn(mediaNaturalBBoxSize.width - sizePixels.width, croppedAreaPercentages.x * mediaNaturalBBoxSize.width / 100)),
y: Math.round(limitAreaFn(mediaNaturalBBoxSize.height - sizePixels.height, croppedAreaPercentages.y * mediaNaturalBBoxSize.height / 100))
});
return {
croppedAreaPercentages: croppedAreaPercentages,
croppedAreaPixels: croppedAreaPixels
};
}
/**
* Ensure the returned value is between 0 and max
*/
function limitArea(max, value) {
return Math.min(max, Math.max(0, value));
}
function noOp(_max, value) {
return value;
}
/**
* Compute crop and zoom from the croppedAreaPercentages.
*/
function getInitialCropFromCroppedAreaPercentages(croppedAreaPercentages, mediaSize, rotation, cropSize, minZoom, maxZoom) {
var mediaBBoxSize = rotateSize(mediaSize.width, mediaSize.height, rotation);
// This is the inverse process of computeCroppedArea
var zoom = index_module_clamp(cropSize.width / mediaBBoxSize.width * (100 / croppedAreaPercentages.width), minZoom, maxZoom);
var crop = {
x: zoom * mediaBBoxSize.width / 2 - cropSize.width / 2 - mediaBBoxSize.width * zoom * (croppedAreaPercentages.x / 100),
y: zoom * mediaBBoxSize.height / 2 - cropSize.height / 2 - mediaBBoxSize.height * zoom * (croppedAreaPercentages.y / 100)
};
return {
crop: crop,
zoom: zoom
};
}
/**
* Compute zoom from the croppedAreaPixels
*/
function getZoomFromCroppedAreaPixels(croppedAreaPixels, mediaSize, cropSize) {
var mediaZoom = getMediaZoom(mediaSize);
return cropSize.height > cropSize.width ? cropSize.height / (croppedAreaPixels.height * mediaZoom) : cropSize.width / (croppedAreaPixels.width * mediaZoom);
}
/**
* Compute crop and zoom from the croppedAreaPixels
*/
function getInitialCropFromCroppedAreaPixels(croppedAreaPixels, mediaSize, rotation, cropSize, minZoom, maxZoom) {
if (rotation === void 0) {
rotation = 0;
}
var mediaNaturalBBoxSize = rotateSize(mediaSize.naturalWidth, mediaSize.naturalHeight, rotation);
var zoom = index_module_clamp(getZoomFromCroppedAreaPixels(croppedAreaPixels, mediaSize, cropSize), minZoom, maxZoom);
var cropZoom = cropSize.height > cropSize.width ? cropSize.height / croppedAreaPixels.height : cropSize.width / croppedAreaPixels.width;
var crop = {
x: ((mediaNaturalBBoxSize.width - croppedAreaPixels.width) / 2 - croppedAreaPixels.x) * cropZoom,
y: ((mediaNaturalBBoxSize.height - croppedAreaPixels.height) / 2 - croppedAreaPixels.y) * cropZoom
};
return {
crop: crop,
zoom: zoom
};
}
/**
* Return the point that is the center of point a and b
*/
function getCenter(a, b) {
return {
x: (b.x + a.x) / 2,
y: (b.y + a.y) / 2
};
}
function getRadianAngle(degreeValue) {
return degreeValue * Math.PI / 180;
}
/**
* Returns the new bounding area of a rotated rectangle.
*/
function rotateSize(width, height, rotation) {
var rotRad = getRadianAngle(rotation);
return {
width: Math.abs(Math.cos(rotRad) * width) + Math.abs(Math.sin(rotRad) * height),
height: Math.abs(Math.sin(rotRad) * width) + Math.abs(Math.cos(rotRad) * height)
};
}
/**
* Clamp value between min and max
*/
function index_module_clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
/**
* Combine multiple class names into a single string.
*/
function classNames() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return args.filter(function (value) {
if (typeof value === 'string' && value.length > 0) {
return true;
}
return false;
}).join(' ').trim();
}
var css_248z = ".reactEasyCrop_Container {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n overflow: hidden;\n user-select: none;\n touch-action: none;\n cursor: move;\n display: flex;\n justify-content: center;\n align-items: center;\n}\n\n.reactEasyCrop_Image,\n.reactEasyCrop_Video {\n will-change: transform; /* this improves performances and prevent painting issues on iOS Chrome */\n}\n\n.reactEasyCrop_Contain {\n max-width: 100%;\n max-height: 100%;\n margin: auto;\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n}\n.reactEasyCrop_Cover_Horizontal {\n width: 100%;\n height: auto;\n}\n.reactEasyCrop_Cover_Vertical {\n width: auto;\n height: 100%;\n}\n\n.reactEasyCrop_CropArea {\n position: absolute;\n left: 50%;\n top: 50%;\n transform: translate(-50%, -50%);\n border: 1px solid rgba(255, 255, 255, 0.5);\n box-sizing: border-box;\n box-shadow: 0 0 0 9999em;\n color: rgba(0, 0, 0, 0.5);\n overflow: hidden;\n}\n\n.reactEasyCrop_CropAreaRound {\n border-radius: 50%;\n}\n\n.reactEasyCrop_CropAreaGrid::before {\n content: ' ';\n box-sizing: border-box;\n position: absolute;\n border: 1px solid rgba(255, 255, 255, 0.5);\n top: 0;\n bottom: 0;\n left: 33.33%;\n right: 33.33%;\n border-top: 0;\n border-bottom: 0;\n}\n\n.reactEasyCrop_CropAreaGrid::after {\n content: ' ';\n box-sizing: border-box;\n position: absolute;\n border: 1px solid rgba(255, 255, 255, 0.5);\n top: 33.33%;\n bottom: 33.33%;\n left: 0;\n right: 0;\n border-left: 0;\n border-right: 0;\n}\n";
var MIN_ZOOM = 1;
var MAX_ZOOM = 3;
var Cropper = /** @class */function (_super) {
__extends(Cropper, _super);
function Cropper() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.imageRef = external_React_default().createRef();
_this.videoRef = external_React_default().createRef();
_this.containerRef = null;
_this.styleRef = null;
_this.containerRect = null;
_this.mediaSize = {
width: 0,
height: 0,
naturalWidth: 0,
naturalHeight: 0
};
_this.dragStartPosition = {
x: 0,
y: 0
};
_this.dragStartCrop = {
x: 0,
y: 0
};
_this.gestureZoomStart = 0;
_this.gestureRotationStart = 0;
_this.isTouching = false;
_this.lastPinchDistance = 0;
_this.lastPinchRotation = 0;
_this.rafDragTimeout = null;
_this.rafPinchTimeout = null;
_this.wheelTimer = null;
_this.currentDoc = typeof document !== 'undefined' ? document : null;
_this.currentWindow = typeof window !== 'undefined' ? window : null;
_this.resizeObserver = null;
_this.state = {
cropSize: null,
hasWheelJustStarted: false
};
_this.initResizeObserver = function () {
if (typeof window.ResizeObserver === 'undefined' || !_this.containerRef) {
return;
}
var isFirstResize = true;
_this.resizeObserver = new window.ResizeObserver(function (entries) {
if (isFirstResize) {
isFirstResize = false; // observe() is called on mount, we don't want to trigger a recompute on mount
return;
}
_this.computeSizes();
});
_this.resizeObserver.observe(_this.containerRef);
};
// this is to prevent Safari on iOS >= 10 to zoom the page
_this.preventZoomSafari = function (e) {
return e.preventDefault();
};
_this.cleanEvents = function () {
if (!_this.currentDoc) return;
_this.currentDoc.removeEventListener('mousemove', _this.onMouseMove);
_this.currentDoc.removeEventListener('mouseup', _this.onDragStopped);
_this.currentDoc.removeEventListener('touchmove', _this.onTouchMove);
_this.currentDoc.removeEventListener('touchend', _this.onDragStopped);
_this.currentDoc.removeEventListener('gesturemove', _this.onGestureMove);
_this.currentDoc.removeEventListener('gestureend', _this.onGestureEnd);
};
_this.clearScrollEvent = function () {
if (_this.containerRef) _this.containerRef.removeEventListener('wheel', _this.onWheel);
if (_this.wheelTimer) {
clearTimeout(_this.wheelTimer);
}
};
_this.onMediaLoad = function () {
var cropSize = _this.computeSizes();
if (cropSize) {
_this.emitCropData();
_this.setInitialCrop(cropSize);
}
if (_this.props.onMediaLoaded) {
_this.props.onMediaLoaded(_this.mediaSize);
}
};
_this.setInitialCrop = function (cropSize) {
if (_this.props.initialCroppedAreaPercentages) {
var _a = getInitialCropFromCroppedAreaPercentages(_this.props.initialCroppedAreaPercentages, _this.mediaSize, _this.props.rotation, cropSize, _this.props.minZoom, _this.props.maxZoom),
crop = _a.crop,
zoom = _a.zoom;
_this.props.onCropChange(crop);
_this.props.onZoomChange && _this.props.onZoomChange(zoom);
} else if (_this.props.initialCroppedAreaPixels) {
var _b = getInitialCropFromCroppedAreaPixels(_this.props.initialCroppedAreaPixels, _this.mediaSize, _this.props.rotation, cropSize, _this.props.minZoom, _this.props.maxZoom),
crop = _b.crop,
zoom = _b.zoom;
_this.props.onCropChange(crop);
_this.props.onZoomChange && _this.props.onZoomChange(zoom);
}
};
_this.computeSizes = function () {
var _a, _b, _c, _d, _e, _f;
var mediaRef = _this.imageRef.current || _this.videoRef.current;
if (mediaRef && _this.containerRef) {
_this.containerRect = _this.containerRef.getBoundingClientRect();
var containerAspect = _this.containerRect.width / _this.containerRect.height;
var naturalWidth = ((_a = _this.imageRef.current) === null || _a === void 0 ? void 0 : _a.naturalWidth) || ((_b = _this.videoRef.current) === null || _b === void 0 ? void 0 : _b.videoWidth) || 0;
var naturalHeight = ((_c = _this.imageRef.current) === null || _c === void 0 ? void 0 : _c.naturalHeight) || ((_d = _this.videoRef.current) === null || _d === void 0 ? void 0 : _d.videoHeight) || 0;
var isMediaScaledDown = mediaRef.offsetWidth < naturalWidth || mediaRef.offsetHeight < naturalHeight;
var mediaAspect = naturalWidth / naturalHeight;
// We do not rely on the offsetWidth/offsetHeight if the media is scaled down
// as the values they report are rounded. That will result in precision losses
// when calculating zoom. We use the fact that the media is positionned relative
// to the container. That allows us to use the container's dimensions
// and natural aspect ratio of the media to calculate accurate media size.
// However, for this to work, the container should not be rotated
var renderedMediaSize = void 0;
if (isMediaScaledDown) {
switch (_this.props.objectFit) {
default:
case 'contain':
renderedMediaSize = containerAspect > mediaAspect ? {
width: _this.containerRect.height * mediaAspect,
height: _this.containerRect.height
} : {
width: _this.containerRect.width,
height: _this.containerRect.width / mediaAspect
};
break;
case 'horizontal-cover':
renderedMediaSize = {
width: _this.containerRect.width,
height: _this.containerRect.width / mediaAspect
};
break;
case 'vertical-cover':
renderedMediaSize = {
width: _this.containerRect.height * mediaAspect,
height: _this.containerRect.height
};
break;
case 'auto-cover':
renderedMediaSize = naturalWidth > naturalHeight ? {
width: _this.containerRect.width,
height: _this.containerRect.width / mediaAspect
} : {
width: _this.containerRect.height * mediaAspect,
height: _this.containerRect.height
};
break;
}
} else {
renderedMediaSize = {
width: mediaRef.offsetWidth,
height: mediaRef.offsetHeight
};
}
_this.mediaSize = __assign(__assign({}, renderedMediaSize), {
naturalWidth: naturalWidth,
naturalHeight: naturalHeight
});
// set media size in the parent
if (_this.props.setMediaSize) {
_this.props.setMediaSize(_this.mediaSize);
}
var cropSize = _this.props.cropSize ? _this.props.cropSize : getCropSize(_this.mediaSize.width, _this.mediaSize.height, _this.containerRect.width, _this.containerRect.height, _this.props.aspect, _this.props.rotation);
if (((_e = _this.state.cropSize) === null || _e === void 0 ? void 0 : _e.height) !== cropSize.height || ((_f = _this.state.cropSize) === null || _f === void 0 ? void 0 : _f.width) !== cropSize.width) {
_this.props.onCropSizeChange && _this.props.onCropSizeChange(cropSize);
}
_this.setState({
cropSize: cropSize
}, _this.recomputeCropPosition);
// pass crop size to parent
if (_this.props.setCropSize) {
_this.props.setCropSize(cropSize);
}
return cropSize;
}
};
_this.onMouseDown = function (e) {
if (!_this.currentDoc) return;
e.preventDefault();
_this.currentDoc.addEventListener('mousemove', _this.onMouseMove);
_this.currentDoc.addEventListener('mouseup', _this.onDragStopped);
_this.onDragStart(Cropper.getMousePoint(e));
};
_this.onMouseMove = function (e) {
return _this.onDrag(Cropper.getMousePoint(e));
};
_this.onTouchStart = function (e) {
if (!_this.currentDoc) return;
_this.isTouching = true;
if (_this.props.onTouchRequest && !_this.props.onTouchRequest(e)) {
return;
}
_this.currentDoc.addEventListener('touchmove', _this.onTouchMove, {
passive: false
}); // iOS 11 now defaults to passive: true
_this.currentDoc.addEventListener('touchend', _this.onDragStopped);
if (e.touches.length === 2) {
_this.onPinchStart(e);
} else if (e.touches.length === 1) {
_this.onDragStart(Cropper.getTouchPoint(e.touches[0]));
}
};
_this.onTouchMove = function (e) {
// Prevent whole page from scrolling on iOS.
e.preventDefault();
if (e.touches.length === 2) {
_this.onPinchMove(e);
} else if (e.touches.length === 1) {
_this.onDrag(Cropper.getTouchPoint(e.touches[0]));
}
};
_this.onGestureStart = function (e) {
if (!_this.currentDoc) return;
e.preventDefault();
_this.currentDoc.addEventListener('gesturechange', _this.onGestureMove);
_this.currentDoc.addEventListener('gestureend', _this.onGestureEnd);
_this.gestureZoomStart = _this.props.zoom;
_this.gestureRotationStart = _this.props.rotation;
};
_this.onGestureMove = function (e) {
e.preventDefault();
if (_this.isTouching) {
// this is to avoid conflict between gesture and touch events
return;
}
var point = Cropper.getMousePoint(e);
var newZoom = _this.gestureZoomStart - 1 + e.scale;
_this.setNewZoom(newZoom, point, {
shouldUpdatePosition: true
});
if (_this.props.onRotationChange) {
var newRotation = _this.gestureRotationStart + e.rotation;
_this.props.onRotationChange(newRotation);
}
};
_this.onGestureEnd = function (e) {
_this.cleanEvents();
};
_this.onDragStart = function (_a) {
var _b, _c;
var x = _a.x,
y = _a.y;
_this.dragStartPosition = {
x: x,
y: y
};
_this.dragStartCrop = __assign({}, _this.props.crop);
(_c = (_b = _this.props).onInteractionStart) === null || _c === void 0 ? void 0 : _c.call(_b);
};
_this.onDrag = function (_a) {
var x = _a.x,
y = _a.y;
if (!_this.currentWindow) return;
if (_this.rafDragTimeout) _this.currentWindow.cancelAnimationFrame(_this.rafDragTimeout);
_this.rafDragTimeout = _this.currentWindow.requestAnimationFrame(function () {
if (!_this.state.cropSize) return;
if (x === undefined || y === undefined) return;
var offsetX = x - _this.dragStartPosition.x;
var offsetY = y - _this.dragStartPosition.y;
var requestedPosition = {
x: _this.dragStartCrop.x + offsetX,
y: _this.dragStartCrop.y + offsetY
};
var newPosition = _this.props.restrictPosition ? restrictPosition(requestedPosition, _this.mediaSize, _this.state.cropSize, _this.props.zoom, _this.props.rotation) : requestedPosition;
_this.props.onCropChange(newPosition);
});
};
_this.onDragStopped = function () {
var _a, _b;
_this.isTouching = false;
_this.cleanEvents();
_this.emitCropData();
(_b = (_a = _this.props).onInteractionEnd) === null || _b === void 0 ? void 0 : _b.call(_a);
};
_this.onWheel = function (e) {
if (!_this.currentWindow) return;
if (_this.props.onWheelRequest && !_this.props.onWheelRequest(e)) {
return;
}
e.preventDefault();
var point = Cropper.getMousePoint(e);
var pixelY = normalize_wheel_default()(e).pixelY;
var newZoom = _this.props.zoom - pixelY * _this.props.zoomSpeed / 200;
_this.setNewZoom(newZoom, point, {
shouldUpdatePosition: true
});
if (!_this.state.hasWheelJustStarted) {
_this.setState({
hasWheelJustStarted: true
}, function () {
var _a, _b;
return (_b = (_a = _this.props).onInteractionStart) === null || _b === void 0 ? void 0 : _b.call(_a);
});
}
if (_this.wheelTimer) {
clearTimeout(_this.wheelTimer);
}
_this.wheelTimer = _this.currentWindow.setTimeout(function () {
return _this.setState({
hasWheelJustStarted: false
}, function () {
var _a, _b;
return (_b = (_a = _this.props).onInteractionEnd) === null || _b === void 0 ? void 0 : _b.call(_a);
});
}, 250);
};
_this.getPointOnContainer = function (_a) {
var x = _a.x,
y = _a.y;
if (!_this.containerRect) {
throw new Error('The Cropper is not mounted');
}
return {
x: _this.containerRect.width / 2 - (x - _this.containerRect.left),
y: _this.containerRect.height / 2 - (y - _this.containerRect.top)
};
};
_this.getPointOnMedia = function (_a) {
var x = _a.x,
y = _a.y;
var _b = _this.props,
crop = _b.crop,
zoom = _b.zoom;
return {
x: (x + crop.x) / zoom,
y: (y + crop.y) / zoom
};
};
_this.setNewZoom = function (zoom, point, _a) {
var _b = _a === void 0 ? {} : _a,
_c = _b.shouldUpdatePosition,
shouldUpdatePosition = _c === void 0 ? true : _c;
if (!_this.state.cropSize || !_this.props.onZoomChange) return;
var newZoom = index_module_clamp(zoom, _this.props.minZoom, _this.props.maxZoom);
if (shouldUpdatePosition) {
var zoomPoint = _this.getPointOnContainer(point);
var zoomTarget = _this.getPointOnMedia(zoomPoint);
var requestedPosition = {
x: zoomTarget.x * newZoom - zoomPoint.x,
y: zoomTarget.y * newZoom - zoomPoint.y
};
var newPosition = _this.props.restrictPosition ? restrictPosition(requestedPosition, _this.mediaSize, _this.state.cropSize, newZoom, _this.props.rotation) : requestedPosition;
_this.props.onCropChange(newPosition);
}
_this.props.onZoomChange(newZoom);
};
_this.getCropData = function () {
if (!_this.state.cropSize) {
return null;
}
// this is to ensure the crop is correctly restricted after a zoom back (https://github.com/ValentinH/react-easy-crop/issues/6)
var restrictedPosition = _this.props.restrictPosition ? restrictPosition(_this.props.crop, _this.mediaSize, _this.state.cropSize, _this.props.zoom, _this.props.rotation) : _this.props.crop;
return computeCroppedArea(restrictedPosition, _this.mediaSize, _this.state.cropSize, _this.getAspect(), _this.props.zoom, _this.props.rotation, _this.props.restrictPosition);
};
_this.emitCropData = function () {
var cropData = _this.getCropData();
if (!cropData) return;
var croppedAreaPercentages = cropData.croppedAreaPercentages,
croppedAreaPixels = cropData.croppedAreaPixels;
if (_this.props.onCropComplete) {
_this.props.onCropComplete(croppedAreaPercentages, croppedAreaPixels);
}
if (_this.props.onCropAreaChange) {
_this.props.onCropAreaChange(croppedAreaPercentages, croppedAreaPixels);
}
};
_this.emitCropAreaChange = function () {
var cropData = _this.getCropData();
if (!cropData) return;
var croppedAreaPercentages = cropData.croppedAreaPercentages,
croppedAreaPixels = cropData.croppedAreaPixels;
if (_this.props.onCropAreaChange) {
_this.props.onCropAreaChange(croppedAreaPercentages, croppedAreaPixels);
}
};
_this.recomputeCropPosition = function () {
if (!_this.state.cropSize) return;
var newPosition = _this.props.restrictPosition ? restrictPosition(_this.props.crop, _this.mediaSize, _this.state.cropSize, _this.props.zoom, _this.props.rotation) : _this.props.crop;
_this.props.onCropChange(newPosition);
_this.emitCropData();
};
return _this;
}
Cropper.prototype.componentDidMount = function () {
if (!this.currentDoc || !this.currentWindow) return;
if (this.containerRef) {
if (this.containerRef.ownerDocument) {
this.currentDoc = this.containerRef.ownerDocument;
}
if (this.currentDoc.defaultView) {
this.currentWindow = this.currentDoc.defaultView;
}
this.initResizeObserver();
// only add window resize listener if ResizeObserver is not supported. Otherwise, it would be redundant
if (typeof window.ResizeObserver === 'undefined') {
this.currentWindow.addEventListener('resize', this.computeSizes);
}
this.props.zoomWithScroll && this.containerRef.addEventListener('wheel', this.onWheel, {
passive: false
});
this.containerRef.addEventListener('gesturestart', this.onGestureStart);
}
if (!this.props.disableAutomaticStylesInjection) {
this.styleRef = this.currentDoc.createElement('style');
this.styleRef.setAttribute('type', 'text/css');
if (this.props.nonce) {
this.styleRef.setAttribute('nonce', this.props.nonce);
}
this.styleRef.innerHTML = css_248z;
this.currentDoc.head.appendChild(this.styleRef);
}
// when rendered via SSR, the image can already be loaded and its onLoad callback will never be called
if (this.imageRef.current && this.imageRef.current.complete) {
this.onMediaLoad();
}
// set image and video refs in the parent if the callbacks exist
if (this.props.setImageRef) {
this.props.setImageRef(this.imageRef);
}
if (this.props.setVideoRef) {
this.props.setVideoRef(this.videoRef);
}
};
Cropper.prototype.componentWillUnmount = function () {
var _a, _b;
if (!this.currentDoc || !this.currentWindow) return;
if (typeof window.ResizeObserver === 'undefined') {
this.currentWindow.removeEventListener('resize', this.computeSizes);
}
(_a = this.resizeObserver) === null || _a === void 0 ? void 0 : _a.disconnect();
if (this.containerRef) {
this.containerRef.removeEventListener('gesturestart', this.preventZoomSafari);
}
if (this.styleRef) {
(_b = this.styleRef.parentNode) === null || _b === void 0 ? void 0 : _b.removeChild(this.styleRef);
}
this.cleanEvents();
this.props.zoomWithScroll && this.clearScrollEvent();
};
Cropper.prototype.componentDidUpdate = function (prevProps) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
if (prevProps.rotation !== this.props.rotation) {
this.computeSizes();
this.recomputeCropPosition();
} else if (prevProps.aspect !== this.props.aspect) {
this.computeSizes();
} else if (prevProps.zoom !== this.props.zoom) {
this.recomputeCropPosition();
} else if (((_a = prevProps.cropSize) === null || _a === void 0 ? void 0 : _a.height) !== ((_b = this.props.cropSize) === null || _b === void 0 ? void 0 : _b.height) || ((_c = prevProps.cropSize) === null || _c === void 0 ? void 0 : _c.width) !== ((_d = this.props.cropSize) === null || _d === void 0 ? void 0 : _d.width)) {
this.computeSizes();
} else if (((_e = prevProps.crop) === null || _e === void 0 ? void 0 : _e.x) !== ((_f = this.props.crop) === null || _f === void 0 ? void 0 : _f.x) || ((_g = prevProps.crop) === null || _g === void 0 ? void 0 : _g.y) !== ((_h = this.props.crop) === null || _h === void 0 ? void 0 : _h.y)) {
this.emitCropAreaChange();
}
if (prevProps.zoomWithScroll !== this.props.zoomWithScroll && this.containerRef) {
this.props.zoomWithScroll ? this.containerRef.addEventListener('wheel', this.onWheel, {
passive: false
}) : this.clearScrollEvent();
}
if (prevProps.video !== this.props.video) {
(_j = this.videoRef.current) === null || _j === void 0 ? void 0 : _j.load();
}
};
Cropper.prototype.getAspect = function () {
var _a = this.props,
cropSize = _a.cropSize,
aspect = _a.aspect;
if (cropSize) {
return cropSize.width / cropSize.height;
}
return aspect;
};
Cropper.prototype.onPinchStart = function (e) {
var pointA = Cropper.getTouchPoint(e.touches[0]);
var pointB = Cropper.getTouchPoint(e.touches[1]);
this.lastPinchDistance = getDistanceBetweenPoints(pointA, pointB);
this.lastPinchRotation = getRotationBetweenPoints(pointA, pointB);
this.onDragStart(getCenter(pointA, pointB));
};
Cropper.prototype.onPinchMove = function (e) {
var _this = this;
if (!this.currentDoc || !this.currentWindow) return;
var pointA = Cropper.getTouchPoint(e.touches[0]);
var pointB = Cropper.getTouchPoint(e.touches[1]);
var center = getCenter(pointA, pointB);
this.onDrag(center);
if (this.rafPinchTimeout) this.currentWindow.cancelAnimationFrame(this.rafPinchTimeout);
this.rafPinchTimeout = this.currentWindow.requestAnimationFrame(function () {
var distance = getDistanceBetweenPoints(pointA, pointB);
var newZoom = _this.props.zoom * (distance / _this.lastPinchDistance);
_this.setNewZoom(newZoom, center, {
shouldUpdatePosition: false
});
_this.lastPinchDistance = distance;
var rotation = getRotationBetweenPoints(pointA, pointB);
var newRotation = _this.props.rotation + (rotation - _this.lastPinchRotation);
_this.props.onRotationChange && _this.props.onRotationChange(newRotation);
_this.lastPinchRotation = rotation;
});
};
Cropper.prototype.render = function () {
var _this = this;
var _a = this.props,
image = _a.image,
video = _a.video,
mediaProps = _a.mediaProps,
transform = _a.transform,
_b = _a.crop,
x = _b.x,
y = _b.y,
rotation = _a.rotation,
zoom = _a.zoom,
cropShape = _a.cropShape,
showGrid = _a.showGrid,
_c = _a.style,
containerStyle = _c.containerStyle,
cropAreaStyle = _c.cropAreaStyle,
mediaStyle = _c.mediaStyle,
_d = _a.classes,
containerClassName = _d.containerClassName,
cropAreaClassName = _d.cropAreaClassName,
mediaClassName = _d.mediaClassName,
objectFit = _a.objectFit;
return external_React_default().createElement("div", {
onMouseDown: this.onMouseDown,
onTouchStart: this.onTouchStart,
ref: function ref(el) {
return _this.containerRef = el;
},
"data-testid": "container",
style: containerStyle,
className: classNames('reactEasyCrop_Container', containerClassName)
}, image ? external_React_default().createElement("img", __assign({
alt: "",
className: classNames('reactEasyCrop_Image', objectFit === 'contain' && 'reactEasyCrop_Contain', objectFit === 'horizontal-cover' && 'reactEasyCrop_Cover_Horizontal', objectFit === 'vertical-cover' && 'reactEasyCrop_Cover_Vertical', objectFit === 'auto-cover' && (this.mediaSize.naturalWidth > this.mediaSize.naturalHeight ? 'reactEasyCrop_Cover_Horizontal' : 'reactEasyCrop_Cover_Vertical'), mediaClassName)
}, mediaProps, {
src: image,
ref: this.imageRef,
style: __assign(__assign({}, mediaStyle), {
transform: transform || "translate(".concat(x, "px, ").concat(y, "px) rotate(").concat(rotation, "deg) scale(").concat(zoom, ")")
}),
onLoad: this.onMediaLoad
})) : video && external_React_default().createElement("video", __assign({
autoPlay: true,
loop: true,
muted: true,
className: classNames('reactEasyCrop_Video', objectFit === 'contain' && 'reactEasyCrop_Contain', objectFit === 'horizontal-cover' && 'reactEasyCrop_Cover_Horizontal', objectFit === 'vertical-cover' && 'reactEasyCrop_Cover_Vertical', objectFit === 'auto-cover' && (this.mediaSize.naturalWidth > this.mediaSize.naturalHeight ? 'reactEasyCrop_Cover_Horizontal' : 'reactEasyCrop_Cover_Vertical'), mediaClassName)
}, mediaProps, {
ref: this.videoRef,
onLoadedMetadata: this.onMediaLoad,
style: __assign(__assign({}, mediaStyle), {
transform: transform || "translate(".concat(x, "px, ").concat(y, "px) rotate(").concat(rotation, "deg) scale(").concat(zoom, ")")
}),
controls: false
}), (Array.isArray(video) ? video : [{
src: video
}]).map(function (item) {
return external_React_default().createElement("source", __assign({
key: item.src
}, item));
})), this.state.cropSize && external_React_default().createElement("div", {
style: __assign(__assign({}, cropAreaStyle), {
width: this.state.cropSize.width,
height: this.state.cropSize.height
}),
"data-testid": "cropper",
className: classNames('reactEasyCrop_CropArea', cropShape === 'round' && 'reactEasyCrop_CropAreaRound', showGrid && 'reactEasyCrop_CropAreaGrid', cropAreaClassName)
}));
};
Cropper.defaultProps = {
zoom: 1,
rotation: 0,
aspect: 4 / 3,
maxZoom: MAX_ZOOM,
minZoom: MIN_ZOOM,
cropShape: 'rect',
objectFit: 'contain',
showGrid: true,
style: {},
classes: {},
mediaProps: {},
zoomSpeed: 1,
restrictPosition: true,
zoomWithScroll: true
};
Cropper.getMousePoint = function (e) {
return {
x: Number(e.clientX),
y: Number(e.clientY)
};
};
Cropper.getTouchPoint = function (touch) {
return {
x: Number(touch.clientX),
y: Number(touch.clientY)
};
};
return Cropper;
}((external_React_default()).Component);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/image-editor/constants.js
const constants_MIN_ZOOM = 100;
const constants_MAX_ZOOM = 300;
const constants_POPOVER_PROPS = {
placement: 'bottom-start',
variant: 'toolbar'
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/image-editor/cropper.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ImageCropper(_ref) {
let {
url,
width,
height,
clientWidth,
naturalHeight,
naturalWidth,
borderProps
} = _ref;
const {
isInProgress,
editedUrl,
position,
zoom,
aspect,
setPosition,
setCrop,
setZoom,
rotation
} = useImageEditingContext();
let editedHeight = height || clientWidth * naturalHeight / naturalWidth;
if (rotation % 180 === 90) {
editedHeight = clientWidth * naturalWidth / naturalHeight;
}
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('wp-block-image__crop-area', borderProps === null || borderProps === void 0 ? void 0 : borderProps.className, {
'is-applying': isInProgress
}),
style: { ...(borderProps === null || borderProps === void 0 ? void 0 : borderProps.style),
width: width || clientWidth,
height: editedHeight
}
}, (0,external_wp_element_namespaceObject.createElement)(Cropper, {
image: editedUrl || url,
disabled: isInProgress,
minZoom: constants_MIN_ZOOM / 100,
maxZoom: constants_MAX_ZOOM / 100,
crop: position,
zoom: zoom / 100,
aspect: aspect,
onCropChange: pos => {
setPosition(pos);
},
onCropComplete: newCropPercent => {
setCrop(newCropPercent);
},
onZoomChange: newZoom => {
setZoom(newZoom * 100);
}
}), isInProgress && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Spinner, null));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/search.js
/**
* WordPress dependencies
*/
const search = (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: "M13.5 6C10.5 6 8 8.5 8 11.5c0 1.1.3 2.1.9 3l-3.4 3 1 1.1 3.4-2.9c1 .9 2.2 1.4 3.6 1.4 3 0 5.5-2.5 5.5-5.5C19 8.5 16.5 6 13.5 6zm0 9.5c-2.2 0-4-1.8-4-4s1.8-4 4-4 4 1.8 4 4-1.8 4-4 4z"
}));
/* harmony default export */ var library_search = (search);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/image-editor/zoom-dropdown.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ZoomDropdown() {
const {
isInProgress,
zoom,
setZoom
} = useImageEditingContext();
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Dropdown, {
contentClassName: "wp-block-image__zoom",
popoverProps: constants_POPOVER_PROPS,
renderToggle: _ref => {
let {
isOpen,
onToggle
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
icon: library_search,
label: (0,external_wp_i18n_namespaceObject.__)('Zoom'),
onClick: onToggle,
"aria-expanded": isOpen,
disabled: isInProgress
});
},
renderContent: () => (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.RangeControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Zoom'),
min: constants_MIN_ZOOM,
max: constants_MAX_ZOOM,
value: Math.round(zoom),
onChange: setZoom
})
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/aspect-ratio.js
/**
* WordPress dependencies
*/
const aspectRatio = (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: "M18.5 5.5h-13c-1.1 0-2 .9-2 2v9c0 1.1.9 2 2 2h13c1.1 0 2-.9 2-2v-9c0-1.1-.9-2-2-2zm.5 11c0 .3-.2.5-.5.5h-13c-.3 0-.5-.2-.5-.5v-9c0-.3.2-.5.5-.5h13c.3 0 .5.2.5.5v9zM6.5 12H8v-2h2V8.5H6.5V12zm9.5 2h-2v1.5h3.5V12H16v2z"
}));
/* harmony default export */ var aspect_ratio = (aspectRatio);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/image-editor/aspect-ratio-dropdown.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function AspectGroup(_ref) {
let {
aspectRatios,
isDisabled,
label,
onClick,
value
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, {
label: label
}, aspectRatios.map(_ref2 => {
let {
title,
aspect
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
key: aspect,
disabled: isDisabled,
onClick: () => {
onClick(aspect);
},
role: "menuitemradio",
isSelected: aspect === value,
icon: aspect === value ? library_check : undefined
}, title);
}));
}
function AspectRatioDropdown(_ref3) {
let {
toggleProps
} = _ref3;
const {
isInProgress,
aspect,
setAspect,
defaultAspect
} = useImageEditingContext();
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.DropdownMenu, {
icon: aspect_ratio,
label: (0,external_wp_i18n_namespaceObject.__)('Aspect Ratio'),
popoverProps: constants_POPOVER_PROPS,
toggleProps: toggleProps,
className: "wp-block-image__aspect-ratio"
}, _ref4 => {
let {
onClose
} = _ref4;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(AspectGroup, {
isDisabled: isInProgress,
onClick: newAspect => {
setAspect(newAspect);
onClose();
},
value: aspect,
aspectRatios: [{
title: (0,external_wp_i18n_namespaceObject.__)('Original'),
aspect: defaultAspect
}, {
title: (0,external_wp_i18n_namespaceObject.__)('Square'),
aspect: 1
}]
}), (0,external_wp_element_namespaceObject.createElement)(AspectGroup, {
label: (0,external_wp_i18n_namespaceObject.__)('Landscape'),
isDisabled: isInProgress,
onClick: newAspect => {
setAspect(newAspect);
onClose();
},
value: aspect,
aspectRatios: [{
title: (0,external_wp_i18n_namespaceObject.__)('16:10'),
aspect: 16 / 10
}, {
title: (0,external_wp_i18n_namespaceObject.__)('16:9'),
aspect: 16 / 9
}, {
title: (0,external_wp_i18n_namespaceObject.__)('4:3'),
aspect: 4 / 3
}, {
title: (0,external_wp_i18n_namespaceObject.__)('3:2'),
aspect: 3 / 2
}]
}), (0,external_wp_element_namespaceObject.createElement)(AspectGroup, {
label: (0,external_wp_i18n_namespaceObject.__)('Portrait'),
isDisabled: isInProgress,
onClick: newAspect => {
setAspect(newAspect);
onClose();
},
value: aspect,
aspectRatios: [{
title: (0,external_wp_i18n_namespaceObject.__)('10:16'),
aspect: 10 / 16
}, {
title: (0,external_wp_i18n_namespaceObject.__)('9:16'),
aspect: 9 / 16
}, {
title: (0,external_wp_i18n_namespaceObject.__)('3:4'),
aspect: 3 / 4
}, {
title: (0,external_wp_i18n_namespaceObject.__)('2:3'),
aspect: 2 / 3
}]
}));
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/rotate-right.js
/**
* WordPress dependencies
*/
const rotateRight = (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: "M15.1 4.8l-3-2.5V4c-4.4 0-8 3.6-8 8 0 3.7 2.5 6.9 6 7.7.3.1.6.1 1 .2l.2-1.5c-.4 0-.7-.1-1.1-.2l-.1.2v-.2c-2.6-.8-4.5-3.3-4.5-6.2 0-3.6 2.9-6.5 6.5-6.5v1.8l3-2.5zM20 11c-.2-1.4-.7-2.7-1.6-3.8l-1.2.8c.7.9 1.1 2 1.3 3.1L20 11zm-1.5 1.8c-.1.5-.2 1.1-.4 1.6s-.5 1-.8 1.5l1.2.9c.4-.5.8-1.1 1-1.8s.5-1.3.5-2l-1.5-.2zm-5.6 5.6l.2 1.5c1.4-.2 2.7-.7 3.8-1.6l-.9-1.1c-.9.7-2 1.1-3.1 1.2z"
}));
/* harmony default export */ var rotate_right = (rotateRight);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/image-editor/rotation-button.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function RotationButton() {
const {
isInProgress,
rotateClockwise
} = useImageEditingContext();
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
icon: rotate_right,
label: (0,external_wp_i18n_namespaceObject.__)('Rotate'),
onClick: rotateClockwise,
disabled: isInProgress
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/image-editor/form-controls.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function FormControls() {
const {
isInProgress,
apply,
cancel
} = useImageEditingContext();
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
onClick: apply,
disabled: isInProgress
}, (0,external_wp_i18n_namespaceObject.__)('Apply')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
onClick: cancel
}, (0,external_wp_i18n_namespaceObject.__)('Cancel')));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/image-editor/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ImageEditor(_ref) {
let {
id,
url,
width,
height,
clientWidth,
naturalHeight,
naturalWidth,
onSaveImage,
onFinishEditing,
borderProps
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(ImageEditingProvider, {
id: id,
url: url,
naturalWidth: naturalWidth,
naturalHeight: naturalHeight,
onSaveImage: onSaveImage,
onFinishEditing: onFinishEditing
}, (0,external_wp_element_namespaceObject.createElement)(ImageCropper, {
borderProps: borderProps,
url: url,
width: width,
height: height,
clientWidth: clientWidth,
naturalHeight: naturalHeight,
naturalWidth: naturalWidth
}), (0,external_wp_element_namespaceObject.createElement)(block_controls, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarGroup, null, (0,external_wp_element_namespaceObject.createElement)(ZoomDropdown, null), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarItem, null, toggleProps => (0,external_wp_element_namespaceObject.createElement)(AspectRatioDropdown, {
toggleProps: toggleProps
})), (0,external_wp_element_namespaceObject.createElement)(RotationButton, null)), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarGroup, null, (0,external_wp_element_namespaceObject.createElement)(FormControls, null))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/image-size-control/use-dimension-handler.js
/**
* WordPress dependencies
*/
function useDimensionHandler(customHeight, customWidth, defaultHeight, defaultWidth, onChange) {
var _ref, _ref2;
const [currentWidth, setCurrentWidth] = (0,external_wp_element_namespaceObject.useState)((_ref = customWidth !== null && customWidth !== void 0 ? customWidth : defaultWidth) !== null && _ref !== void 0 ? _ref : '');
const [currentHeight, setCurrentHeight] = (0,external_wp_element_namespaceObject.useState)((_ref2 = customHeight !== null && customHeight !== void 0 ? customHeight : defaultHeight) !== null && _ref2 !== void 0 ? _ref2 : ''); // When an image is first inserted, the default dimensions are initially
// undefined. This effect updates the dimensions when the default values
// come through.
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (customWidth === undefined && defaultWidth !== undefined) {
setCurrentWidth(defaultWidth);
}
if (customHeight === undefined && defaultHeight !== undefined) {
setCurrentHeight(defaultHeight);
}
}, [defaultWidth, defaultHeight]); // If custom values change, it means an outsider has resized the image using some other method (eg resize box)
// this keeps track of these values too. We need to parse before comparing; custom values can be strings.
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (customWidth !== undefined && Number.parseInt(customWidth) !== Number.parseInt(currentWidth)) {
setCurrentWidth(customWidth);
}
if (customHeight !== undefined && Number.parseInt(customHeight) !== Number.parseInt(currentHeight)) {
setCurrentHeight(customHeight);
}
}, [customWidth, customHeight]);
const updateDimension = (dimension, value) => {
if (dimension === 'width') {
setCurrentWidth(value);
} else {
setCurrentHeight(value);
}
onChange({
[dimension]: value === '' ? undefined : parseInt(value, 10)
});
};
const updateDimensions = (nextHeight, nextWidth) => {
setCurrentHeight(nextHeight !== null && nextHeight !== void 0 ? nextHeight : defaultHeight);
setCurrentWidth(nextWidth !== null && nextWidth !== void 0 ? nextWidth : defaultWidth);
onChange({
height: nextHeight,
width: nextWidth
});
};
return {
currentHeight,
currentWidth,
updateDimension,
updateDimensions
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/image-size-control/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const IMAGE_SIZE_PRESETS = [25, 50, 75, 100];
const image_size_control_noop = () => {};
function ImageSizeControl(_ref) {
let {
imageSizeHelp,
imageWidth,
imageHeight,
imageSizeOptions = [],
isResizable = true,
slug,
width,
height,
onChange,
onChangeImage = image_size_control_noop
} = _ref;
const {
currentHeight,
currentWidth,
updateDimension,
updateDimensions
} = useDimensionHandler(height, width, imageHeight, imageWidth, onChange);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, imageSizeOptions && imageSizeOptions.length > 0 && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SelectControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Image size'),
value: slug,
options: imageSizeOptions,
onChange: onChangeImage,
help: imageSizeHelp
}), isResizable && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-image-size-control"
}, (0,external_wp_element_namespaceObject.createElement)("p", {
className: "block-editor-image-size-control__row"
}, (0,external_wp_i18n_namespaceObject.__)('Image dimensions')), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-image-size-control__row"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.TextControl, {
type: "number",
className: "block-editor-image-size-control__width",
label: (0,external_wp_i18n_namespaceObject.__)('Width'),
value: currentWidth,
min: 1,
onChange: value => updateDimension('width', value)
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.TextControl, {
type: "number",
className: "block-editor-image-size-control__height",
label: (0,external_wp_i18n_namespaceObject.__)('Height'),
value: currentHeight,
min: 1,
onChange: value => updateDimension('height', value)
})), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-image-size-control__row"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ButtonGroup, {
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Image size presets')
}, IMAGE_SIZE_PRESETS.map(scale => {
const scaledWidth = Math.round(imageWidth * (scale / 100));
const scaledHeight = Math.round(imageHeight * (scale / 100));
const isCurrent = currentWidth === scaledWidth && currentHeight === scaledHeight;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
key: scale,
isSmall: true,
variant: isCurrent ? 'primary' : undefined,
isPressed: isCurrent,
onClick: () => updateDimensions(scaledHeight, scaledWidth)
}, scale, "%");
})), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
isSmall: true,
onClick: () => updateDimensions()
}, (0,external_wp_i18n_namespaceObject.__)('Reset')))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/keyboard-return.js
/**
* WordPress dependencies
*/
const keyboardReturn = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "-2 -2 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M6.734 16.106l2.176-2.38-1.093-1.028-3.846 4.158 3.846 4.157 1.093-1.027-2.176-2.38h2.811c1.125 0 2.25.03 3.374 0 1.428-.001 3.362-.25 4.963-1.277 1.66-1.065 2.868-2.906 2.868-5.859 0-2.479-1.327-4.896-3.65-5.93-1.82-.813-3.044-.8-4.806-.788l-.567.002v1.5c.184 0 .368 0 .553-.002 1.82-.007 2.704-.014 4.21.657 1.854.827 2.76 2.657 2.76 4.561 0 2.472-.973 3.824-2.178 4.596-1.258.807-2.864 1.04-4.163 1.04h-.02c-1.115.03-2.229 0-3.344 0H6.734z"
}));
/* harmony default export */ var keyboard_return = (keyboardReturn);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/link-control/settings-drawer.js
/**
* WordPress dependencies
*/
const settings_drawer_noop = () => {};
const LinkControlSettingsDrawer = _ref => {
let {
value,
onChange = settings_drawer_noop,
settings
} = _ref;
if (!settings || !settings.length) {
return null;
}
const handleSettingChange = setting => newValue => {
onChange({ ...value,
[setting.id]: newValue
});
};
const theSettings = settings.map(setting => (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToggleControl, {
className: "block-editor-link-control__setting",
key: setting.id,
label: setting.title,
onChange: handleSettingChange(setting),
checked: value ? !!value[setting.id] : false
}));
return (0,external_wp_element_namespaceObject.createElement)("fieldset", {
className: "block-editor-link-control__settings"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.VisuallyHidden, {
as: "legend"
}, (0,external_wp_i18n_namespaceObject.__)('Currently selected link settings')), theSettings);
};
/* harmony default export */ var settings_drawer = (LinkControlSettingsDrawer);
// EXTERNAL MODULE: ./node_modules/dom-scroll-into-view/lib/index.js
var dom_scroll_into_view_lib = __webpack_require__(5425);
var lib_default = /*#__PURE__*/__webpack_require__.n(dom_scroll_into_view_lib);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/url-input/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Whether the argument is a function.
*
* @param {*} maybeFunc The argument to check.
* @return {boolean} True if the argument is a function, false otherwise.
*/
function isFunction(maybeFunc) {
return typeof maybeFunc === 'function';
}
class URLInput extends external_wp_element_namespaceObject.Component {
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
this.onFocus = this.onFocus.bind(this);
this.onKeyDown = this.onKeyDown.bind(this);
this.selectLink = this.selectLink.bind(this);
this.handleOnClick = this.handleOnClick.bind(this);
this.bindSuggestionNode = this.bindSuggestionNode.bind(this);
this.autocompleteRef = props.autocompleteRef || (0,external_wp_element_namespaceObject.createRef)();
this.inputRef = (0,external_wp_element_namespaceObject.createRef)();
this.updateSuggestions = (0,external_wp_compose_namespaceObject.debounce)(this.updateSuggestions.bind(this), 200);
this.suggestionNodes = [];
this.suggestionsRequest = null;
this.state = {
suggestions: [],
showSuggestions: false,
isUpdatingSuggestions: false,
suggestionsValue: null,
selectedSuggestion: null,
suggestionsListboxId: '',
suggestionOptionIdPrefix: ''
};
}
componentDidUpdate(prevProps) {
const {
showSuggestions,
selectedSuggestion
} = this.state;
const {
value,
__experimentalShowInitialSuggestions = false
} = this.props; // Only have to worry about scrolling selected suggestion into view
// when already expanded.
if (showSuggestions && selectedSuggestion !== null && this.suggestionNodes[selectedSuggestion] && !this.scrollingIntoView) {
this.scrollingIntoView = true;
lib_default()(this.suggestionNodes[selectedSuggestion], this.autocompleteRef.current, {
onlyScrollIfNeeded: true
});
this.props.setTimeout(() => {
this.scrollingIntoView = false;
}, 100);
} // Update suggestions when the value changes.
if (prevProps.value !== value && !this.props.disableSuggestions && !this.state.isUpdatingSuggestions) {
if (value !== null && value !== void 0 && value.length) {
// If the new value is not empty we need to update with suggestions for it.
this.updateSuggestions(value);
} else if (__experimentalShowInitialSuggestions) {
// If the new value is empty and we can show initial suggestions, then show initial suggestions.
this.updateSuggestions();
}
}
}
componentDidMount() {
if (this.shouldShowInitialSuggestions()) {
this.updateSuggestions();
}
}
componentWillUnmount() {
var _this$suggestionsRequ, _this$suggestionsRequ2;
(_this$suggestionsRequ = this.suggestionsRequest) === null || _this$suggestionsRequ === void 0 ? void 0 : (_this$suggestionsRequ2 = _this$suggestionsRequ.cancel) === null || _this$suggestionsRequ2 === void 0 ? void 0 : _this$suggestionsRequ2.call(_this$suggestionsRequ);
this.suggestionsRequest = null;
}
bindSuggestionNode(index) {
return ref => {
this.suggestionNodes[index] = ref;
};
}
shouldShowInitialSuggestions() {
const {
__experimentalShowInitialSuggestions = false,
value
} = this.props;
return __experimentalShowInitialSuggestions && !(value && value.length);
}
updateSuggestions() {
var _value;
let value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
const {
__experimentalFetchLinkSuggestions: fetchLinkSuggestions,
__experimentalHandleURLSuggestions: handleURLSuggestions
} = this.props;
if (!fetchLinkSuggestions) {
return;
} // Initial suggestions may only show if there is no value
// (note: this includes whitespace).
const isInitialSuggestions = !((_value = value) !== null && _value !== void 0 && _value.length); // Trim only now we've determined whether or not it originally had a "length"
// (even if that value was all whitespace).
value = value.trim(); // Allow a suggestions request if:
// - there are at least 2 characters in the search input (except manual searches where
// search input length is not required to trigger a fetch)
// - this is a direct entry (eg: a URL)
if (!isInitialSuggestions && (value.length < 2 || !handleURLSuggestions && (0,external_wp_url_namespaceObject.isURL)(value))) {
var _this$suggestionsRequ3, _this$suggestionsRequ4;
(_this$suggestionsRequ3 = this.suggestionsRequest) === null || _this$suggestionsRequ3 === void 0 ? void 0 : (_this$suggestionsRequ4 = _this$suggestionsRequ3.cancel) === null || _this$suggestionsRequ4 === void 0 ? void 0 : _this$suggestionsRequ4.call(_this$suggestionsRequ3);
this.suggestionsRequest = null;
this.setState({
suggestions: [],
showSuggestions: false,
suggestionsValue: value,
selectedSuggestion: null,
loading: false
});
return;
}
this.setState({
isUpdatingSuggestions: true,
selectedSuggestion: null,
loading: true
});
const request = fetchLinkSuggestions(value, {
isInitialSuggestions
});
request.then(suggestions => {
// A fetch Promise doesn't have an abort option. It's mimicked by
// comparing the request reference in on the instance, which is
// reset or deleted on subsequent requests or unmounting.
if (this.suggestionsRequest !== request) {
return;
}
this.setState({
suggestions,
isUpdatingSuggestions: false,
suggestionsValue: value,
loading: false,
showSuggestions: !!suggestions.length
});
if (!!suggestions.length) {
this.props.debouncedSpeak((0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: number of results. */
(0,external_wp_i18n_namespaceObject._n)('%d result found, use up and down arrow keys to navigate.', '%d results found, use up and down arrow keys to navigate.', suggestions.length), suggestions.length), 'assertive');
} else {
this.props.debouncedSpeak((0,external_wp_i18n_namespaceObject.__)('No results.'), 'assertive');
}
}).catch(() => {
if (this.suggestionsRequest !== request) {
return;
}
this.setState({
isUpdatingSuggestions: false,
loading: false
});
}); // Note that this assignment is handled *before* the async search request
// as a Promise always resolves on the next tick of the event loop.
this.suggestionsRequest = request;
}
onChange(event) {
this.props.onChange(event.target.value);
}
onFocus() {
const {
suggestions
} = this.state;
const {
disableSuggestions,
value
} = this.props; // When opening the link editor, if there's a value present, we want to load the suggestions pane with the results for this input search value
// Don't re-run the suggestions on focus if there are already suggestions present (prevents searching again when tabbing between the input and buttons)
if (value && !disableSuggestions && !this.state.isUpdatingSuggestions && !(suggestions && suggestions.length)) {
// Ensure the suggestions are updated with the current input value.
this.updateSuggestions(value);
}
}
onKeyDown(event) {
const {
showSuggestions,
selectedSuggestion,
suggestions,
loading
} = this.state; // If the suggestions are not shown or loading, we shouldn't handle the arrow keys
// We shouldn't preventDefault to allow block arrow keys navigation.
if (!showSuggestions || !suggestions.length || loading) {
// In the Windows version of Firefox the up and down arrows don't move the caret
// within an input field like they do for Mac Firefox/Chrome/Safari. This causes
// a form of focus trapping that is disruptive to the user experience. This disruption
// only happens if the caret is not in the first or last position in the text input.
// See: https://github.com/WordPress/gutenberg/issues/5693#issuecomment-436684747
switch (event.keyCode) {
// When UP is pressed, if the caret is at the start of the text, move it to the 0
// position.
case external_wp_keycodes_namespaceObject.UP:
{
if (0 !== event.target.selectionStart) {
event.preventDefault(); // Set the input caret to position 0.
event.target.setSelectionRange(0, 0);
}
break;
}
// When DOWN is pressed, if the caret is not at the end of the text, move it to the
// last position.
case external_wp_keycodes_namespaceObject.DOWN:
{
if (this.props.value.length !== event.target.selectionStart) {
event.preventDefault(); // Set the input caret to the last position.
event.target.setSelectionRange(this.props.value.length, this.props.value.length);
}
break;
}
// Submitting while loading should trigger onSubmit.
case external_wp_keycodes_namespaceObject.ENTER:
{
event.preventDefault();
if (this.props.onSubmit) {
this.props.onSubmit(null, event);
}
break;
}
}
return;
}
const suggestion = this.state.suggestions[this.state.selectedSuggestion];
switch (event.keyCode) {
case external_wp_keycodes_namespaceObject.UP:
{
event.preventDefault();
const previousIndex = !selectedSuggestion ? suggestions.length - 1 : selectedSuggestion - 1;
this.setState({
selectedSuggestion: previousIndex
});
break;
}
case external_wp_keycodes_namespaceObject.DOWN:
{
event.preventDefault();
const nextIndex = selectedSuggestion === null || selectedSuggestion === suggestions.length - 1 ? 0 : selectedSuggestion + 1;
this.setState({
selectedSuggestion: nextIndex
});
break;
}
case external_wp_keycodes_namespaceObject.TAB:
{
if (this.state.selectedSuggestion !== null) {
this.selectLink(suggestion); // Announce a link has been selected when tabbing away from the input field.
this.props.speak((0,external_wp_i18n_namespaceObject.__)('Link selected.'));
}
break;
}
case external_wp_keycodes_namespaceObject.ENTER:
{
event.preventDefault();
if (this.state.selectedSuggestion !== null) {
this.selectLink(suggestion);
if (this.props.onSubmit) {
this.props.onSubmit(suggestion, event);
}
} else if (this.props.onSubmit) {
this.props.onSubmit(null, event);
}
break;
}
}
}
selectLink(suggestion) {
this.props.onChange(suggestion.url, suggestion);
this.setState({
selectedSuggestion: null,
showSuggestions: false
});
}
handleOnClick(suggestion) {
this.selectLink(suggestion); // Move focus to the input field when a link suggestion is clicked.
this.inputRef.current.focus();
}
static getDerivedStateFromProps(_ref, _ref2) {
let {
value,
instanceId,
disableSuggestions,
__experimentalShowInitialSuggestions = false
} = _ref;
let {
showSuggestions
} = _ref2;
let shouldShowSuggestions = showSuggestions;
const hasValue = value && value.length;
if (!__experimentalShowInitialSuggestions && !hasValue) {
shouldShowSuggestions = false;
}
if (disableSuggestions === true) {
shouldShowSuggestions = false;
}
return {
showSuggestions: shouldShowSuggestions,
suggestionsListboxId: `block-editor-url-input-suggestions-${instanceId}`,
suggestionOptionIdPrefix: `block-editor-url-input-suggestion-${instanceId}`
};
}
render() {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, this.renderControl(), this.renderSuggestions());
}
renderControl() {
const {
/** Start opting into the new margin-free styles that will become the default in a future version. */
__nextHasNoMarginBottom = false,
label = null,
className,
isFullWidth,
instanceId,
placeholder = (0,external_wp_i18n_namespaceObject.__)('Paste URL or type to search'),
__experimentalRenderControl: renderControl,
value = ''
} = this.props;
const {
loading,
showSuggestions,
selectedSuggestion,
suggestionsListboxId,
suggestionOptionIdPrefix
} = this.state;
const inputId = `url-input-control-${instanceId}`;
const controlProps = {
id: inputId,
// Passes attribute to label for the for attribute
label,
className: classnames_default()('block-editor-url-input', className, {
'is-full-width': isFullWidth
})
};
const inputProps = {
id: inputId,
value,
required: true,
className: 'block-editor-url-input__input',
type: 'text',
onChange: this.onChange,
onFocus: this.onFocus,
placeholder,
onKeyDown: this.onKeyDown,
role: 'combobox',
'aria-label': label ? undefined : (0,external_wp_i18n_namespaceObject.__)('URL'),
// Ensure input always has an accessible label
'aria-expanded': showSuggestions,
'aria-autocomplete': 'list',
'aria-controls': suggestionsListboxId,
'aria-activedescendant': selectedSuggestion !== null ? `${suggestionOptionIdPrefix}-${selectedSuggestion}` : undefined,
ref: this.inputRef
};
if (renderControl) {
return renderControl(controlProps, inputProps, loading);
}
if (!__nextHasNoMarginBottom) {
external_wp_deprecated_default()('Bottom margin styles for wp.blockEditor.URLInput', {
since: '6.2',
version: '6.5',
hint: 'Set the `__nextHasNoMarginBottom` prop to true to start opting into the new styles, which will become the default in a future version'
});
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.BaseControl, _extends({
__nextHasNoMarginBottom: __nextHasNoMarginBottom
}, controlProps), (0,external_wp_element_namespaceObject.createElement)("input", inputProps), loading && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Spinner, null));
}
renderSuggestions() {
const {
className,
__experimentalRenderSuggestions: renderSuggestions
} = this.props;
const {
showSuggestions,
suggestions,
suggestionsValue,
selectedSuggestion,
suggestionsListboxId,
suggestionOptionIdPrefix,
loading
} = this.state;
if (!showSuggestions || suggestions.length === 0) {
return null;
}
const suggestionsListProps = {
id: suggestionsListboxId,
ref: this.autocompleteRef,
role: 'listbox'
};
const buildSuggestionItemProps = (suggestion, index) => {
return {
role: 'option',
tabIndex: '-1',
id: `${suggestionOptionIdPrefix}-${index}`,
ref: this.bindSuggestionNode(index),
'aria-selected': index === selectedSuggestion
};
};
if (isFunction(renderSuggestions)) {
return renderSuggestions({
suggestions,
selectedSuggestion,
suggestionsListProps,
buildSuggestionItemProps,
isLoading: loading,
handleSuggestionClick: this.handleOnClick,
isInitialSuggestions: !(suggestionsValue !== null && suggestionsValue !== void 0 && suggestionsValue.length),
currentInputValue: suggestionsValue
});
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Popover, {
placement: "bottom",
focusOnMount: false
}, (0,external_wp_element_namespaceObject.createElement)("div", _extends({}, suggestionsListProps, {
className: classnames_default()('block-editor-url-input__suggestions', `${className}__suggestions`)
}), suggestions.map((suggestion, index) => (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, _extends({}, buildSuggestionItemProps(suggestion, index), {
key: suggestion.id,
className: classnames_default()('block-editor-url-input__suggestion', {
'is-selected': index === selectedSuggestion
}),
onClick: () => this.handleOnClick(suggestion)
}), suggestion.title))));
}
}
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/url-input/README.md
*/
/* harmony default export */ var url_input = ((0,external_wp_compose_namespaceObject.compose)(external_wp_compose_namespaceObject.withSafeTimeout, external_wp_components_namespaceObject.withSpokenMessages, external_wp_compose_namespaceObject.withInstanceId, (0,external_wp_data_namespaceObject.withSelect)((select, props) => {
// If a link suggestions handler is already provided then
// bail.
if (isFunction(props.__experimentalFetchLinkSuggestions)) {
return;
}
const {
getSettings
} = select(store);
return {
__experimentalFetchLinkSuggestions: getSettings().__experimentalFetchLinkSuggestions
};
}))(URLInput));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/link-control/search-create-button.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
const LinkControlSearchCreate = _ref => {
let {
searchTerm,
onClick,
itemProps,
isSelected,
buttonText
} = _ref;
if (!searchTerm) {
return null;
}
let text;
if (buttonText) {
text = typeof buttonText === 'function' ? buttonText(searchTerm) : buttonText;
} else {
text = (0,external_wp_element_namespaceObject.createInterpolateElement)((0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: search term. */
(0,external_wp_i18n_namespaceObject.__)('Create: <mark>%s</mark>'), searchTerm), {
mark: (0,external_wp_element_namespaceObject.createElement)("mark", null)
});
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, _extends({}, itemProps, {
className: classnames_default()('block-editor-link-control__search-create block-editor-link-control__search-item', {
'is-selected': isSelected
}),
onClick: onClick
}), (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
className: "block-editor-link-control__search-item-icon",
icon: library_plus
}), (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-link-control__search-item-header"
}, (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-link-control__search-item-title"
}, text)));
};
/* harmony default export */ var search_create_button = (LinkControlSearchCreate);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/post-list.js
/**
* WordPress dependencies
*/
const postList = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M18 4H6c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm.5 14c0 .3-.2.5-.5.5H6c-.3 0-.5-.2-.5-.5V6c0-.3.2-.5.5-.5h12c.3 0 .5.2.5.5v12zM7 11h2V9H7v2zm0 4h2v-2H7v2zm3-4h7V9h-7v2zm0 4h7v-2h-7v2z"
}));
/* harmony default export */ var post_list = (postList);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/tag.js
/**
* WordPress dependencies
*/
const tag = (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: "M20.1 11.2l-6.7-6.7c-.1-.1-.3-.2-.5-.2H5c-.4-.1-.8.3-.8.7v7.8c0 .2.1.4.2.5l6.7 6.7c.2.2.5.4.7.5s.6.2.9.2c.3 0 .6-.1.9-.2.3-.1.5-.3.8-.5l5.6-5.6c.4-.4.7-1 .7-1.6.1-.6-.2-1.2-.6-1.6zM19 13.4L13.4 19c-.1.1-.2.1-.3.2-.2.1-.4.1-.6 0-.1 0-.2-.1-.3-.2l-6.5-6.5V5.8h6.8l6.5 6.5c.2.2.2.4.2.6 0 .1 0 .3-.2.5zM9 8c-.6 0-1 .4-1 1s.4 1 1 1 1-.4 1-1-.4-1-1-1z"
}));
/* harmony default export */ var library_tag = (tag);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/category.js
/**
* WordPress dependencies
*/
const category = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M6 5.5h3a.5.5 0 01.5.5v3a.5.5 0 01-.5.5H6a.5.5 0 01-.5-.5V6a.5.5 0 01.5-.5zM4 6a2 2 0 012-2h3a2 2 0 012 2v3a2 2 0 01-2 2H6a2 2 0 01-2-2V6zm11-.5h3a.5.5 0 01.5.5v3a.5.5 0 01-.5.5h-3a.5.5 0 01-.5-.5V6a.5.5 0 01.5-.5zM13 6a2 2 0 012-2h3a2 2 0 012 2v3a2 2 0 01-2 2h-3a2 2 0 01-2-2V6zm5 8.5h-3a.5.5 0 00-.5.5v3a.5.5 0 00.5.5h3a.5.5 0 00.5-.5v-3a.5.5 0 00-.5-.5zM15 13a2 2 0 00-2 2v3a2 2 0 002 2h3a2 2 0 002-2v-3a2 2 0 00-2-2h-3zm-9 1.5h3a.5.5 0 01.5.5v3a.5.5 0 01-.5.5H6a.5.5 0 01-.5-.5v-3a.5.5 0 01.5-.5zM4 15a2 2 0 012-2h3a2 2 0 012 2v3a2 2 0 01-2 2H6a2 2 0 01-2-2v-3z",
fillRule: "evenodd",
clipRule: "evenodd"
}));
/* harmony default export */ var library_category = (category);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/file.js
/**
* WordPress dependencies
*/
const file = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M19 6.2h-5.9l-.6-1.1c-.3-.7-1-1.1-1.8-1.1H5c-1.1 0-2 .9-2 2v11.8c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V8.2c0-1.1-.9-2-2-2zm.5 11.6c0 .3-.2.5-.5.5H5c-.3 0-.5-.2-.5-.5V6c0-.3.2-.5.5-.5h5.8c.2 0 .4.1.4.3l1 2H19c.3 0 .5.2.5.5v9.5z"
}));
/* harmony default export */ var library_file = (file);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/globe.js
/**
* WordPress dependencies
*/
const globe = (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: "M12 3.3c-4.8 0-8.8 3.9-8.8 8.8 0 4.8 3.9 8.8 8.8 8.8 4.8 0 8.8-3.9 8.8-8.8s-4-8.8-8.8-8.8zm6.5 5.5h-2.6C15.4 7.3 14.8 6 14 5c2 .6 3.6 2 4.5 3.8zm.7 3.2c0 .6-.1 1.2-.2 1.8h-2.9c.1-.6.1-1.2.1-1.8s-.1-1.2-.1-1.8H19c.2.6.2 1.2.2 1.8zM12 18.7c-1-.7-1.8-1.9-2.3-3.5h4.6c-.5 1.6-1.3 2.9-2.3 3.5zm-2.6-4.9c-.1-.6-.1-1.1-.1-1.8 0-.6.1-1.2.1-1.8h5.2c.1.6.1 1.1.1 1.8s-.1 1.2-.1 1.8H9.4zM4.8 12c0-.6.1-1.2.2-1.8h2.9c-.1.6-.1 1.2-.1 1.8 0 .6.1 1.2.1 1.8H5c-.2-.6-.2-1.2-.2-1.8zM12 5.3c1 .7 1.8 1.9 2.3 3.5H9.7c.5-1.6 1.3-2.9 2.3-3.5zM10 5c-.8 1-1.4 2.3-1.8 3.8H5.5C6.4 7 8 5.6 10 5zM5.5 15.3h2.6c.4 1.5 1 2.8 1.8 3.7-1.8-.6-3.5-2-4.4-3.7zM14 19c.8-1 1.4-2.2 1.8-3.7h2.6C17.6 17 16 18.4 14 19z"
}));
/* harmony default export */ var library_globe = (globe);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/link-control/search-item.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
const ICONS_MAP = {
post: post_list,
page: library_page,
post_tag: library_tag,
category: library_category,
attachment: library_file
};
function SearchItemIcon(_ref) {
let {
isURL,
suggestion
} = _ref;
let icon = null;
if (isURL) {
icon = library_globe;
} else if (suggestion.type in ICONS_MAP) {
icon = ICONS_MAP[suggestion.type];
}
if (icon) {
return (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
className: "block-editor-link-control__search-item-icon",
icon: icon
});
}
return null;
}
const LinkControlSearchItem = _ref2 => {
let {
itemProps,
suggestion,
isSelected = false,
onClick,
isURL = false,
searchTerm = '',
shouldShowType = false
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, _extends({}, itemProps, {
onClick: onClick,
className: classnames_default()('block-editor-link-control__search-item', {
'is-selected': isSelected,
'is-url': isURL,
'is-entity': !isURL
})
}), (0,external_wp_element_namespaceObject.createElement)(SearchItemIcon, {
suggestion: suggestion,
isURL: isURL
}), (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-link-control__search-item-header"
}, (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-link-control__search-item-title"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.TextHighlight, {
text: suggestion.title,
highlight: searchTerm
})), (0,external_wp_element_namespaceObject.createElement)("span", {
"aria-hidden": !isURL,
className: "block-editor-link-control__search-item-info"
}, !isURL && ((0,external_wp_url_namespaceObject.filterURLForDisplay)((0,external_wp_url_namespaceObject.safeDecodeURI)(suggestion.url)) || ''), isURL && (0,external_wp_i18n_namespaceObject.__)('Press ENTER to add this link'))), shouldShowType && suggestion.type && (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-link-control__search-item-type"
}, getVisualTypeName(suggestion)));
};
function getVisualTypeName(suggestion) {
if (suggestion.isFrontPage) {
return 'front page';
} // Rename 'post_tag' to 'tag'. Ideally, the API would return the localised CPT or taxonomy label.
return suggestion.type === 'post_tag' ? 'tag' : suggestion.type;
}
/* harmony default export */ var search_item = (LinkControlSearchItem);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/link-control/constants.js
/**
* WordPress dependencies
*/
// Used as a unique identifier for the "Create" option within search results.
// Used to help distinguish the "Create" suggestion within the search results in
// order to handle it as a unique case.
const CREATE_TYPE = '__CREATE__';
const TEL_TYPE = 'tel';
const URL_TYPE = 'URL';
const MAILTO_TYPE = 'mailto';
const INTERNAL_TYPE = 'internal';
const LINK_ENTRY_TYPES = [URL_TYPE, MAILTO_TYPE, TEL_TYPE, INTERNAL_TYPE];
const DEFAULT_LINK_SETTINGS = [{
id: 'opensInNewTab',
title: (0,external_wp_i18n_namespaceObject.__)('Open in new tab')
}];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/link-control/search-results.js
/**
* WordPress dependencies
*/
/**
* External dependencies
*/
/**
* Internal dependencies
*/
function LinkControlSearchResults(_ref) {
let {
instanceId,
withCreateSuggestion,
currentInputValue,
handleSuggestionClick,
suggestionsListProps,
buildSuggestionItemProps,
suggestions,
selectedSuggestion,
isLoading,
isInitialSuggestions,
createSuggestionButtonText,
suggestionsQuery
} = _ref;
const resultsListClasses = classnames_default()('block-editor-link-control__search-results', {
'is-loading': isLoading
});
const isSingleDirectEntryResult = suggestions.length === 1 && LINK_ENTRY_TYPES.includes(suggestions[0].type);
const shouldShowCreateSuggestion = withCreateSuggestion && !isSingleDirectEntryResult && !isInitialSuggestions; // If the query has a specified type, then we can skip showing them in the result. See #24839.
const shouldShowSuggestionsTypes = !(suggestionsQuery !== null && suggestionsQuery !== void 0 && suggestionsQuery.type); // According to guidelines aria-label should be added if the label
// itself is not visible.
// See: https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/listbox_role
const searchResultsLabelId = `block-editor-link-control-search-results-label-${instanceId}`;
const labelText = isInitialSuggestions ? (0,external_wp_i18n_namespaceObject.__)('Recently updated') : (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: search term. */
(0,external_wp_i18n_namespaceObject.__)('Search results for "%s"'), currentInputValue); // VisuallyHidden rightly doesn't accept custom classNames
// so we conditionally render it as a wrapper to visually hide the label
// when that is required.
const searchResultsLabel = (0,external_wp_element_namespaceObject.createElement)(isInitialSuggestions ? external_wp_element_namespaceObject.Fragment : external_wp_components_namespaceObject.VisuallyHidden, {}, // Empty props.
(0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-link-control__search-results-label",
id: searchResultsLabelId
}, labelText));
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-link-control__search-results-wrapper"
}, searchResultsLabel, (0,external_wp_element_namespaceObject.createElement)("div", _extends({}, suggestionsListProps, {
className: resultsListClasses,
"aria-labelledby": searchResultsLabelId
}), suggestions.map((suggestion, index) => {
if (shouldShowCreateSuggestion && CREATE_TYPE === suggestion.type) {
return (0,external_wp_element_namespaceObject.createElement)(search_create_button, {
searchTerm: currentInputValue,
buttonText: createSuggestionButtonText,
onClick: () => handleSuggestionClick(suggestion) // Intentionally only using `type` here as
// the constant is enough to uniquely
// identify the single "CREATE" suggestion.
,
key: suggestion.type,
itemProps: buildSuggestionItemProps(suggestion, index),
isSelected: index === selectedSuggestion
});
} // If we're not handling "Create" suggestions above then
// we don't want them in the main results so exit early.
if (CREATE_TYPE === suggestion.type) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(search_item, {
key: `${suggestion.id}-${suggestion.type}`,
itemProps: buildSuggestionItemProps(suggestion, index),
suggestion: suggestion,
index: index,
onClick: () => {
handleSuggestionClick(suggestion);
},
isSelected: index === selectedSuggestion,
isURL: LINK_ENTRY_TYPES.includes(suggestion.type),
searchTerm: currentInputValue,
shouldShowType: shouldShowSuggestionsTypes,
isFrontPage: suggestion === null || suggestion === void 0 ? void 0 : suggestion.isFrontPage
});
})));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/link-control/is-url-like.js
/**
* WordPress dependencies
*/
/**
* Determines whether a given value could be a URL. Note this does not
* guarantee the value is a URL only that it looks like it might be one. For
* example, just because a string has `www.` in it doesn't make it a URL,
* but it does make it highly likely that it will be so in the context of
* creating a link it makes sense to treat it like one.
*
* @param {string} val the candidate for being URL-like (or not).
*
* @return {boolean} whether or not the value is potentially a URL.
*/
function isURLLike(val) {
const isInternal = val === null || val === void 0 ? void 0 : val.startsWith('#');
return (0,external_wp_url_namespaceObject.isURL)(val) || val && val.includes('www.') || isInternal;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/link-control/use-search-handler.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const handleNoop = () => Promise.resolve([]);
const handleDirectEntry = val => {
let type = URL_TYPE;
const protocol = (0,external_wp_url_namespaceObject.getProtocol)(val) || '';
if (protocol.includes('mailto')) {
type = MAILTO_TYPE;
}
if (protocol.includes('tel')) {
type = TEL_TYPE;
}
if (val !== null && val !== void 0 && val.startsWith('#')) {
type = INTERNAL_TYPE;
}
return Promise.resolve([{
id: val,
title: val,
url: type === 'URL' ? (0,external_wp_url_namespaceObject.prependHTTP)(val) : val,
type
}]);
};
const handleEntitySearch = async (val, suggestionsQuery, fetchSearchSuggestions, directEntryHandler, withCreateSuggestion, withURLSuggestion, pageOnFront) => {
const {
isInitialSuggestions
} = suggestionsQuery;
let resultsIncludeFrontPage = false;
let results = await Promise.all([fetchSearchSuggestions(val, suggestionsQuery), directEntryHandler(val)]); // Identify front page and update type to match.
results[0] = results[0].map(result => {
if (Number(result.id) === pageOnFront) {
resultsIncludeFrontPage = true;
result.isFrontPage = true;
return result;
}
return result;
});
const couldBeURL = !val.includes(' '); // If it's potentially a URL search then concat on a URL search suggestion
// just for good measure. That way once the actual results run out we always
// have a URL option to fallback on.
if (!resultsIncludeFrontPage && couldBeURL && withURLSuggestion && !isInitialSuggestions) {
results = results[0].concat(results[1]);
} else {
results = results[0];
} // If displaying initial suggestions just return plain results.
if (isInitialSuggestions) {
return results;
} // Here we append a faux suggestion to represent a "CREATE" option. This
// is detected in the rendering of the search results and handled as a
// special case. This is currently necessary because the suggestions
// dropdown will only appear if there are valid suggestions and
// therefore unless the create option is a suggestion it will not
// display in scenarios where there are no results returned from the
// API. In addition promoting CREATE to a first class suggestion affords
// the a11y benefits afforded by `URLInput` to all suggestions (eg:
// keyboard handling, ARIA roles...etc).
//
// Note also that the value of the `title` and `url` properties must correspond
// to the text value of the `<input>`. This is because `title` is used
// when creating the suggestion. Similarly `url` is used when using keyboard to select
// the suggestion (the <form> `onSubmit` handler falls-back to `url`).
return isURLLike(val) || !withCreateSuggestion ? results : results.concat({
// the `id` prop is intentionally ommitted here because it
// is never exposed as part of the component's public API.
// see: https://github.com/WordPress/gutenberg/pull/19775#discussion_r378931316.
title: val,
// Must match the existing `<input>`s text value.
url: val,
// Must match the existing `<input>`s text value.
type: CREATE_TYPE
});
};
function useSearchHandler(suggestionsQuery, allowDirectEntry, withCreateSuggestion, withURLSuggestion) {
const {
fetchSearchSuggestions,
pageOnFront
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getSettings
} = select(store);
return {
pageOnFront: getSettings().pageOnFront,
fetchSearchSuggestions: getSettings().__experimentalFetchLinkSuggestions
};
}, []);
const directEntryHandler = allowDirectEntry ? handleDirectEntry : handleNoop;
return (0,external_wp_element_namespaceObject.useCallback)((val, _ref) => {
let {
isInitialSuggestions
} = _ref;
return isURLLike(val) ? directEntryHandler(val, {
isInitialSuggestions
}) : handleEntitySearch(val, { ...suggestionsQuery,
isInitialSuggestions
}, fetchSearchSuggestions, directEntryHandler, withCreateSuggestion, withURLSuggestion, pageOnFront);
}, [directEntryHandler, fetchSearchSuggestions, withCreateSuggestion]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/link-control/search-input.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
// Must be a function as otherwise URLInput will default
// to the fetchLinkSuggestions passed in block editor settings
// which will cause an unintended http request.
const noopSearchHandler = () => Promise.resolve([]);
const search_input_noop = () => {};
const LinkControlSearchInput = (0,external_wp_element_namespaceObject.forwardRef)((_ref, ref) => {
let {
value,
children,
currentLink = {},
className = null,
placeholder = null,
withCreateSuggestion = false,
onCreateSuggestion = search_input_noop,
onChange = search_input_noop,
onSelect = search_input_noop,
showSuggestions = true,
renderSuggestions = props => (0,external_wp_element_namespaceObject.createElement)(LinkControlSearchResults, props),
fetchSuggestions = null,
allowDirectEntry = true,
showInitialSuggestions = false,
suggestionsQuery = {},
withURLSuggestion = true,
createSuggestionButtonText,
useLabel = false
} = _ref;
const genericSearchHandler = useSearchHandler(suggestionsQuery, allowDirectEntry, withCreateSuggestion, withURLSuggestion);
const searchHandler = showSuggestions ? fetchSuggestions || genericSearchHandler : noopSearchHandler;
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(LinkControlSearchInput);
const [focusedSuggestion, setFocusedSuggestion] = (0,external_wp_element_namespaceObject.useState)();
/**
* Handles the user moving between different suggestions. Does not handle
* choosing an individual item.
*
* @param {string} selection the url of the selected suggestion.
* @param {Object} suggestion the suggestion object.
*/
const onInputChange = (selection, suggestion) => {
onChange(selection);
setFocusedSuggestion(suggestion);
};
const handleRenderSuggestions = props => renderSuggestions({ ...props,
instanceId,
withCreateSuggestion,
createSuggestionButtonText,
suggestionsQuery,
handleSuggestionClick: suggestion => {
if (props.handleSuggestionClick) {
props.handleSuggestionClick(suggestion);
}
onSuggestionSelected(suggestion);
}
});
const onSuggestionSelected = async selectedSuggestion => {
let suggestion = selectedSuggestion;
if (CREATE_TYPE === selectedSuggestion.type) {
// Create a new page and call onSelect with the output from the onCreateSuggestion callback.
try {
var _suggestion;
suggestion = await onCreateSuggestion(selectedSuggestion.title);
if ((_suggestion = suggestion) !== null && _suggestion !== void 0 && _suggestion.url) {
onSelect(suggestion);
}
} catch (e) {}
return;
}
if (allowDirectEntry || suggestion && Object.keys(suggestion).length >= 1) {
const {
id,
url,
...restLinkProps
} = currentLink !== null && currentLink !== void 0 ? currentLink : {};
onSelect( // Some direct entries don't have types or IDs, and we still need to clear the previous ones.
{ ...restLinkProps,
...suggestion
}, suggestion);
}
};
const inputClasses = classnames_default()(className, {
'has-no-label': !useLabel
});
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-link-control__search-input-container"
}, (0,external_wp_element_namespaceObject.createElement)(url_input, {
__nextHasNoMarginBottom: true,
label: useLabel ? 'URL' : undefined,
className: inputClasses,
value: value,
onChange: onInputChange,
placeholder: placeholder !== null && placeholder !== void 0 ? placeholder : (0,external_wp_i18n_namespaceObject.__)('Search or type url'),
__experimentalRenderSuggestions: showSuggestions ? handleRenderSuggestions : null,
__experimentalFetchLinkSuggestions: searchHandler,
__experimentalHandleURLSuggestions: true,
__experimentalShowInitialSuggestions: showInitialSuggestions,
onSubmit: (suggestion, event) => {
var _value$trim;
const hasSuggestion = suggestion || focusedSuggestion; // If there is no suggestion and the value (ie: any manually entered URL) is empty
// then don't allow submission otherwise we get empty links.
if (!hasSuggestion && !(value !== null && value !== void 0 && (_value$trim = value.trim()) !== null && _value$trim !== void 0 && _value$trim.length)) {
event.preventDefault();
} else {
onSuggestionSelected(hasSuggestion || {
url: value
});
}
},
ref: ref
}), children);
});
/* harmony default export */ var search_input = (LinkControlSearchInput);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/info.js
/**
* WordPress dependencies
*/
const info = (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: "M12 3.2c-4.8 0-8.8 3.9-8.8 8.8 0 4.8 3.9 8.8 8.8 8.8 4.8 0 8.8-3.9 8.8-8.8 0-4.8-4-8.8-8.8-8.8zm0 16c-4 0-7.2-3.3-7.2-7.2C4.8 8 8 4.8 12 4.8s7.2 3.3 7.2 7.2c0 4-3.2 7.2-7.2 7.2zM11 17h2v-6h-2v6zm0-8h2V7h-2v2z"
}));
/* harmony default export */ var library_info = (info);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/pencil.js
/**
* WordPress dependencies
*/
const pencil = (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: "M20.1 5.1L16.9 2 6.2 12.7l-1.3 4.4 4.5-1.3L20.1 5.1zM4 20.8h8v-1.5H4v1.5z"
}));
/* harmony default export */ var library_pencil = (pencil);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/edit.js
/**
* Internal dependencies
*/
/* harmony default export */ var library_edit = (library_pencil);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/link-control/viewer-slot.js
/**
* WordPress dependencies
*/
const {
Slot: ViewerSlot,
Fill: ViewerFill
} = (0,external_wp_components_namespaceObject.createSlotFill)('BlockEditorLinkControlViewer');
/* harmony default export */ var viewer_slot = ((/* unused pure expression or super */ null && (ViewerSlot)));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/link-control/use-rich-url-data.js
/**
* Internal dependencies
*/
/**
* WordPress dependencies
*/
function use_rich_url_data_reducer(state, action) {
switch (action.type) {
case 'RESOLVED':
return { ...state,
isFetching: false,
richData: action.richData
};
case 'ERROR':
return { ...state,
isFetching: false,
richData: null
};
case 'LOADING':
return { ...state,
isFetching: true
};
default:
throw new Error(`Unexpected action type ${action.type}`);
}
}
function useRemoteUrlData(url) {
const [state, dispatch] = (0,external_wp_element_namespaceObject.useReducer)(use_rich_url_data_reducer, {
richData: null,
isFetching: false
});
const {
fetchRichUrlData
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getSettings
} = select(store);
return {
fetchRichUrlData: getSettings().__experimentalFetchRichUrlData
};
}, []);
(0,external_wp_element_namespaceObject.useEffect)(() => {
// Only make the request if we have an actual URL
// and the fetching util is available. In some editors
// there may not be such a util.
if (url !== null && url !== void 0 && url.length && fetchRichUrlData && typeof AbortController !== 'undefined') {
dispatch({
type: 'LOADING'
});
const controller = new window.AbortController();
const signal = controller.signal;
fetchRichUrlData(url, {
signal
}).then(urlData => {
dispatch({
type: 'RESOLVED',
richData: urlData
});
}).catch(() => {
// Avoid setting state on unmounted component
if (!signal.aborted) {
dispatch({
type: 'ERROR'
});
}
}); // Cleanup: when the URL changes the abort the current request.
return () => {
controller.abort();
};
}
}, [url]);
return state;
}
/* harmony default export */ var use_rich_url_data = (useRemoteUrlData);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/link-control/link-preview.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function LinkPreview(_ref) {
var _value$url;
let {
value,
onEditClick,
hasRichPreviews = false,
hasUnlinkControl = false,
onRemove
} = _ref;
// Avoid fetching if rich previews are not desired.
const showRichPreviews = hasRichPreviews ? value === null || value === void 0 ? void 0 : value.url : null;
const {
richData,
isFetching
} = use_rich_url_data(showRichPreviews); // Rich data may be an empty object so test for that.
const hasRichData = richData && Object.keys(richData).length;
const displayURL = value && (0,external_wp_url_namespaceObject.filterURLForDisplay)((0,external_wp_url_namespaceObject.safeDecodeURI)(value.url), 16) || '';
const displayTitle = (richData === null || richData === void 0 ? void 0 : richData.title) || (value === null || value === void 0 ? void 0 : value.title) || displayURL; // url can be undefined if the href attribute is unset
const isEmptyURL = !(value !== null && value !== void 0 && (_value$url = value.url) !== null && _value$url !== void 0 && _value$url.length);
let icon;
if (richData !== null && richData !== void 0 && richData.icon) {
icon = (0,external_wp_element_namespaceObject.createElement)("img", {
src: richData === null || richData === void 0 ? void 0 : richData.icon,
alt: ""
});
} else if (isEmptyURL) {
icon = (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: library_info,
size: 32
});
} else {
icon = (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: library_globe
});
}
return (0,external_wp_element_namespaceObject.createElement)("div", {
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Currently selected'),
className: classnames_default()('block-editor-link-control__search-item', {
'is-current': true,
'is-rich': hasRichData,
'is-fetching': !!isFetching,
'is-preview': true,
'is-error': isEmptyURL
})
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-link-control__search-item-top"
}, (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-link-control__search-item-header"
}, (0,external_wp_element_namespaceObject.createElement)("span", {
className: classnames_default()('block-editor-link-control__search-item-icon', {
'is-image': richData === null || richData === void 0 ? void 0 : richData.icon
})
}, icon), (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-link-control__search-item-details"
}, !isEmptyURL ? (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ExternalLink, {
className: "block-editor-link-control__search-item-title",
href: value.url
}, (0,external_wp_dom_namespaceObject.__unstableStripHTML)(displayTitle)), (value === null || value === void 0 ? void 0 : value.url) && (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-link-control__search-item-info"
}, displayURL)) : (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-link-control__search-item-error-notice"
}, (0,external_wp_i18n_namespaceObject.__)('Link is empty')))), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
icon: library_edit,
label: (0,external_wp_i18n_namespaceObject.__)('Edit'),
className: "block-editor-link-control__search-item-action",
onClick: onEditClick,
iconSize: 24
}), hasUnlinkControl && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
icon: link_off,
label: (0,external_wp_i18n_namespaceObject.__)('Unlink'),
className: "block-editor-link-control__search-item-action block-editor-link-control__unlink",
onClick: onRemove,
iconSize: 24
}), (0,external_wp_element_namespaceObject.createElement)(ViewerSlot, {
fillProps: value
})), !!(hasRichData && (richData !== null && richData !== void 0 && richData.image || richData !== null && richData !== void 0 && richData.description) || isFetching) && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-link-control__search-item-bottom"
}, ((richData === null || richData === void 0 ? void 0 : richData.image) || isFetching) && (0,external_wp_element_namespaceObject.createElement)("div", {
"aria-hidden": !(richData !== null && richData !== void 0 && richData.image),
className: classnames_default()('block-editor-link-control__search-item-image', {
'is-placeholder': !(richData !== null && richData !== void 0 && richData.image)
})
}, (richData === null || richData === void 0 ? void 0 : richData.image) && (0,external_wp_element_namespaceObject.createElement)("img", {
src: richData === null || richData === void 0 ? void 0 : richData.image,
alt: ""
})), ((richData === null || richData === void 0 ? void 0 : richData.description) || isFetching) && (0,external_wp_element_namespaceObject.createElement)("div", {
"aria-hidden": !(richData !== null && richData !== void 0 && richData.description),
className: classnames_default()('block-editor-link-control__search-item-description', {
'is-placeholder': !(richData !== null && richData !== void 0 && richData.description)
})
}, (richData === null || richData === void 0 ? void 0 : richData.description) && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalText, {
truncate: true,
numberOfLines: "2"
}, richData.description))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/link-control/use-create-page.js
/**
* WordPress dependencies
*/
function useCreatePage(handleCreatePage) {
const cancelableCreateSuggestion = (0,external_wp_element_namespaceObject.useRef)();
const [isCreatingPage, setIsCreatingPage] = (0,external_wp_element_namespaceObject.useState)(false);
const [errorMessage, setErrorMessage] = (0,external_wp_element_namespaceObject.useState)(null);
const createPage = async function (suggestionTitle) {
setIsCreatingPage(true);
setErrorMessage(null);
try {
// Make cancellable in order that we can avoid setting State
// if the component unmounts during the call to `createSuggestion`
cancelableCreateSuggestion.current = makeCancelable( // Using Promise.resolve to allow createSuggestion to return a
// non-Promise based value.
Promise.resolve(handleCreatePage(suggestionTitle)));
return await cancelableCreateSuggestion.current.promise;
} catch (error) {
if (error && error.isCanceled) {
return; // bail if canceled to avoid setting state
}
setErrorMessage(error.message || (0,external_wp_i18n_namespaceObject.__)('An unknown error occurred during creation. Please try again.'));
throw error;
} finally {
setIsCreatingPage(false);
}
};
/**
* Handles cancelling any pending Promises that have been made cancelable.
*/
(0,external_wp_element_namespaceObject.useEffect)(() => {
return () => {
// componentDidUnmount
if (cancelableCreateSuggestion.current) {
cancelableCreateSuggestion.current.cancel();
}
};
}, []);
return {
createPage,
isCreatingPage,
errorMessage
};
}
/**
* Creates a wrapper around a promise which allows it to be programmatically
* cancelled.
* See: https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html
*
* @param {Promise} promise the Promise to make cancelable
*/
const makeCancelable = promise => {
let hasCanceled_ = false;
const wrappedPromise = new Promise((resolve, reject) => {
promise.then(val => hasCanceled_ ? reject({
isCanceled: true
}) : resolve(val), error => hasCanceled_ ? reject({
isCanceled: true
}) : reject(error));
});
return {
promise: wrappedPromise,
cancel() {
hasCanceled_ = true;
}
};
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/link-control/use-internal-input-value.js
/**
* WordPress dependencies
*/
function useInternalInputValue(value) {
const [internalInputValue, setInternalInputValue] = (0,external_wp_element_namespaceObject.useState)(value || '');
(0,external_wp_element_namespaceObject.useEffect)(() => {
/**
* If the value changes then sync this
* back up with state.
*/
if (value && value !== internalInputValue) {
setInternalInputValue(value);
}
}, [value]);
return [internalInputValue, setInternalInputValue];
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/link-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Default properties associated with a link control value.
*
* @typedef WPLinkControlDefaultValue
*
* @property {string} url Link URL.
* @property {string=} title Link title.
* @property {boolean=} opensInNewTab Whether link should open in a new browser
* tab. This value is only assigned if not
* providing a custom `settings` prop.
*/
/* eslint-disable jsdoc/valid-types */
/**
* Custom settings values associated with a link.
*
* @typedef {{[setting:string]:any}} WPLinkControlSettingsValue
*/
/* eslint-enable */
/**
* Custom settings values associated with a link.
*
* @typedef WPLinkControlSetting
*
* @property {string} id Identifier to use as property for setting value.
* @property {string} title Human-readable label to show in user interface.
*/
/**
* Properties associated with a link control value, composed as a union of the
* default properties and any custom settings values.
*
* @typedef {WPLinkControlDefaultValue&WPLinkControlSettingsValue} WPLinkControlValue
*/
/** @typedef {(nextValue:WPLinkControlValue)=>void} WPLinkControlOnChangeProp */
/**
* Properties associated with a search suggestion used within the LinkControl.
*
* @typedef WPLinkControlSuggestion
*
* @property {string} id Identifier to use to uniquely identify the suggestion.
* @property {string} type Identifies the type of the suggestion (eg: `post`,
* `page`, `url`...etc)
* @property {string} title Human-readable label to show in user interface.
* @property {string} url A URL for the suggestion.
*/
/** @typedef {(title:string)=>WPLinkControlSuggestion} WPLinkControlCreateSuggestionProp */
/**
* @typedef WPLinkControlProps
*
* @property {(WPLinkControlSetting[])=} settings An array of settings objects. Each object will used to
* render a `ToggleControl` for that setting.
* @property {boolean=} forceIsEditingLink If passed as either `true` or `false`, controls the
* internal editing state of the component to respective
* show or not show the URL input field.
* @property {WPLinkControlValue=} value Current link value.
* @property {WPLinkControlOnChangeProp=} onChange Value change handler, called with the updated value if
* the user selects a new link or updates settings.
* @property {boolean=} noDirectEntry Whether to allow turning a URL-like search query directly into a link.
* @property {boolean=} showSuggestions Whether to present suggestions when typing the URL.
* @property {boolean=} showInitialSuggestions Whether to present initial suggestions immediately.
* @property {boolean=} withCreateSuggestion Whether to allow creation of link value from suggestion.
* @property {Object=} suggestionsQuery Query parameters to pass along to wp.blockEditor.__experimentalFetchLinkSuggestions.
* @property {boolean=} noURLSuggestion Whether to add a fallback suggestion which treats the search query as a URL.
* @property {boolean=} hasTextControl Whether to add a text field to the UI to update the value.title.
* @property {string|Function|undefined} createSuggestionButtonText The text to use in the button that calls createSuggestion.
* @property {Function} renderControlBottom Optional controls to be rendered at the bottom of the component.
*/
const link_control_noop = () => {};
/**
* Renders a link control. A link control is a controlled input which maintains
* a value associated with a link (HTML anchor element) and relevant settings
* for how that link is expected to behave.
*
* @param {WPLinkControlProps} props Component props.
*/
function LinkControl(_ref) {
var _currentUrlInputValue, _value$url, _value$url$trim;
let {
searchInputPlaceholder,
value,
settings = DEFAULT_LINK_SETTINGS,
onChange = link_control_noop,
onRemove,
noDirectEntry = false,
showSuggestions = true,
showInitialSuggestions,
forceIsEditingLink,
createSuggestion,
withCreateSuggestion,
inputValue: propInputValue = '',
suggestionsQuery = {},
noURLSuggestion = false,
createSuggestionButtonText,
hasRichPreviews = false,
hasTextControl = false,
renderControlBottom = null
} = _ref;
if (withCreateSuggestion === undefined && createSuggestion) {
withCreateSuggestion = true;
}
const isMounting = (0,external_wp_element_namespaceObject.useRef)(true);
const wrapperNode = (0,external_wp_element_namespaceObject.useRef)();
const textInputRef = (0,external_wp_element_namespaceObject.useRef)();
const isEndingEditWithFocus = (0,external_wp_element_namespaceObject.useRef)(false);
const [internalUrlInputValue, setInternalUrlInputValue] = useInternalInputValue((value === null || value === void 0 ? void 0 : value.url) || '');
const [internalTextInputValue, setInternalTextInputValue] = useInternalInputValue((value === null || value === void 0 ? void 0 : value.title) || '');
const [isEditingLink, setIsEditingLink] = (0,external_wp_element_namespaceObject.useState)(forceIsEditingLink !== undefined ? forceIsEditingLink : !value || !value.url);
const {
createPage,
isCreatingPage,
errorMessage
} = useCreatePage(createSuggestion);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (forceIsEditingLink !== undefined && forceIsEditingLink !== isEditingLink) {
setIsEditingLink(forceIsEditingLink);
}
}, [forceIsEditingLink]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
// We don't auto focus into the Link UI on mount
// because otherwise using the keyboard to select text
// *within* the link format is not possible.
if (isMounting.current) {
isMounting.current = false;
return;
} // Unless we are mounting, we always want to focus either:
// - the URL input
// - the first focusable element in the Link UI.
// But in editing mode if there is a text input present then
// the URL input is at index 1. If not then it is at index 0.
const whichFocusTargetIndex = textInputRef !== null && textInputRef !== void 0 && textInputRef.current ? 1 : 0; // Scenario - when:
// - switching between editable and non editable LinkControl
// - clicking on a link
// ...then move focus to the *first* element to avoid focus loss
// and to ensure focus is *within* the Link UI.
const nextFocusTarget = external_wp_dom_namespaceObject.focus.focusable.find(wrapperNode.current)[whichFocusTargetIndex] || wrapperNode.current;
nextFocusTarget.focus();
isEndingEditWithFocus.current = false;
}, [isEditingLink, isCreatingPage]);
/**
* Cancels editing state and marks that focus may need to be restored after
* the next render, if focus was within the wrapper when editing finished.
*/
const stopEditing = () => {
var _wrapperNode$current;
isEndingEditWithFocus.current = !!((_wrapperNode$current = wrapperNode.current) !== null && _wrapperNode$current !== void 0 && _wrapperNode$current.contains(wrapperNode.current.ownerDocument.activeElement));
setIsEditingLink(false);
};
const handleSelectSuggestion = updatedValue => {
onChange({ ...updatedValue,
title: internalTextInputValue || (updatedValue === null || updatedValue === void 0 ? void 0 : updatedValue.title)
});
stopEditing();
};
const handleSubmit = () => {
if (currentUrlInputValue !== (value === null || value === void 0 ? void 0 : value.url) || internalTextInputValue !== (value === null || value === void 0 ? void 0 : value.title)) {
onChange({ ...value,
url: currentUrlInputValue,
title: internalTextInputValue
});
}
stopEditing();
};
const handleSubmitWithEnter = event => {
const {
keyCode
} = event;
if (keyCode === external_wp_keycodes_namespaceObject.ENTER && !currentInputIsEmpty // Disallow submitting empty values.
) {
event.preventDefault();
handleSubmit();
}
};
const currentUrlInputValue = propInputValue || internalUrlInputValue;
const currentInputIsEmpty = !(currentUrlInputValue !== null && currentUrlInputValue !== void 0 && (_currentUrlInputValue = currentUrlInputValue.trim()) !== null && _currentUrlInputValue !== void 0 && _currentUrlInputValue.length);
const shownUnlinkControl = onRemove && value && !isEditingLink && !isCreatingPage;
const showSettingsDrawer = !!(settings !== null && settings !== void 0 && settings.length); // Only show text control once a URL value has been committed
// and it isn't just empty whitespace.
// See https://github.com/WordPress/gutenberg/pull/33849/#issuecomment-932194927.
const showTextControl = (value === null || value === void 0 ? void 0 : (_value$url = value.url) === null || _value$url === void 0 ? void 0 : (_value$url$trim = _value$url.trim()) === null || _value$url$trim === void 0 ? void 0 : _value$url$trim.length) > 0 && hasTextControl;
return (0,external_wp_element_namespaceObject.createElement)("div", {
tabIndex: -1,
ref: wrapperNode,
className: "block-editor-link-control"
}, isCreatingPage && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-link-control__loading"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Spinner, null), " ", (0,external_wp_i18n_namespaceObject.__)('Creating'), "\u2026"), (isEditingLink || !value) && !isCreatingPage && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()({
'block-editor-link-control__search-input-wrapper': true,
'has-text-control': showTextControl
})
}, showTextControl && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.TextControl, {
__nextHasNoMarginBottom: true,
ref: textInputRef,
className: "block-editor-link-control__field block-editor-link-control__text-content",
label: "Text",
value: internalTextInputValue,
onChange: setInternalTextInputValue,
onKeyDown: handleSubmitWithEnter
}), (0,external_wp_element_namespaceObject.createElement)(search_input, {
currentLink: value,
className: "block-editor-link-control__field block-editor-link-control__search-input",
placeholder: searchInputPlaceholder,
value: currentUrlInputValue,
withCreateSuggestion: withCreateSuggestion,
onCreateSuggestion: createPage,
onChange: setInternalUrlInputValue,
onSelect: handleSelectSuggestion,
showInitialSuggestions: showInitialSuggestions,
allowDirectEntry: !noDirectEntry,
showSuggestions: showSuggestions,
suggestionsQuery: suggestionsQuery,
withURLSuggestion: !noURLSuggestion,
createSuggestionButtonText: createSuggestionButtonText,
useLabel: showTextControl
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-link-control__search-actions"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
onClick: handleSubmit,
label: (0,external_wp_i18n_namespaceObject.__)('Submit'),
icon: keyboard_return,
className: "block-editor-link-control__search-submit",
disabled: currentInputIsEmpty // Disallow submitting empty values.
})))), errorMessage && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Notice, {
className: "block-editor-link-control__search-error",
status: "error",
isDismissible: false
}, errorMessage)), value && !isEditingLink && !isCreatingPage && (0,external_wp_element_namespaceObject.createElement)(LinkPreview, {
key: value === null || value === void 0 ? void 0 : value.url // force remount when URL changes to avoid race conditions for rich previews
,
value: value,
onEditClick: () => setIsEditingLink(true),
hasRichPreviews: hasRichPreviews,
hasUnlinkControl: shownUnlinkControl,
onRemove: onRemove
}), showSettingsDrawer && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-link-control__tools"
}, (0,external_wp_element_namespaceObject.createElement)(settings_drawer, {
value: value,
settings: settings,
onChange: onChange
})), renderControlBottom && renderControlBottom());
}
LinkControl.ViewerFill = ViewerFill;
/* harmony default export */ var link_control = (LinkControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/media.js
/**
* WordPress dependencies
*/
const media = (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: "M18.7 3H5.3C4 3 3 4 3 5.3v13.4C3 20 4 21 5.3 21h13.4c1.3 0 2.3-1 2.3-2.3V5.3C21 4 20 3 18.7 3zm.8 15.7c0 .4-.4.8-.8.8H5.3c-.4 0-.8-.4-.8-.8V5.3c0-.4.4-.8.8-.8h13.4c.4 0 .8.4.8.8v13.4zM10 15l5-3-5-3v6z"
}));
/* harmony default export */ var library_media = (media);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/upload.js
/**
* WordPress dependencies
*/
const upload = (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: "M18.5 15v3.5H13V6.7l4.5 4.1 1-1.1-6.2-5.8-5.8 5.8 1 1.1 4-4v11.7h-6V15H4v5h16v-5z"
}));
/* harmony default export */ var library_upload = (upload);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/post-featured-image.js
/**
* WordPress dependencies
*/
const postFeaturedImage = (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 3H5c-.6 0-1 .4-1 1v7c0 .5.4 1 1 1h14c.5 0 1-.4 1-1V4c0-.6-.4-1-1-1zM5.5 10.5v-.4l1.8-1.3 1.3.8c.3.2.7.2.9-.1L11 8.1l2.4 2.4H5.5zm13 0h-2.9l-4-4c-.3-.3-.8-.3-1.1 0L8.9 8l-1.2-.8c-.3-.2-.6-.2-.9 0l-1.3 1V4.5h13v6zM4 20h9v-1.5H4V20zm0-4h16v-1.5H4V16z"
}));
/* harmony default export */ var post_featured_image = (postFeaturedImage);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/media-replace-flow/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const media_replace_flow_noop = () => {};
let uniqueId = 0;
const MediaReplaceFlow = _ref => {
let {
mediaURL,
mediaId,
mediaIds,
allowedTypes,
accept,
onError,
onSelect,
onSelectURL,
onToggleFeaturedImage,
useFeaturedImage,
onFilesUpload = media_replace_flow_noop,
name = (0,external_wp_i18n_namespaceObject.__)('Replace'),
createNotice,
removeNotice,
children,
multiple = false,
addToGallery,
handleUpload = true
} = _ref;
const mediaUpload = (0,external_wp_data_namespaceObject.useSelect)(select => {
return select(store).getSettings().mediaUpload;
}, []);
const editMediaButtonRef = (0,external_wp_element_namespaceObject.useRef)();
const errorNoticeID = `block-editor/media-replace-flow/error-notice/${++uniqueId}`;
const onUploadError = message => {
const safeMessage = (0,external_wp_dom_namespaceObject.__unstableStripHTML)(message);
if (onError) {
onError(safeMessage);
return;
} // We need to set a timeout for showing the notice
// so that VoiceOver and possibly other screen readers
// can announce the error afer the toolbar button
// regains focus once the upload dialog closes.
// Otherwise VO simply skips over the notice and announces
// the focused element and the open menu.
setTimeout(() => {
createNotice('error', safeMessage, {
speak: true,
id: errorNoticeID,
isDismissible: true
});
}, 1000);
};
const selectMedia = (media, closeMenu) => {
if (useFeaturedImage && onToggleFeaturedImage) {
onToggleFeaturedImage();
}
closeMenu(); // Calling `onSelect` after the state update since it might unmount the component.
onSelect(media);
(0,external_wp_a11y_namespaceObject.speak)((0,external_wp_i18n_namespaceObject.__)('The media file has been replaced'));
removeNotice(errorNoticeID);
};
const uploadFiles = (event, closeMenu) => {
const files = event.target.files;
if (!handleUpload) {
closeMenu();
return onSelect(files);
}
onFilesUpload(files);
mediaUpload({
allowedTypes,
filesList: files,
onFileChange: _ref2 => {
let [media] = _ref2;
selectMedia(media, closeMenu);
},
onError: onUploadError
});
};
const openOnArrowDown = event => {
if (event.keyCode === external_wp_keycodes_namespaceObject.DOWN) {
event.preventDefault();
event.target.click();
}
};
const onlyAllowsImages = () => {
if (!allowedTypes || allowedTypes.length === 0) {
return false;
}
return allowedTypes.every(allowedType => allowedType === 'image' || allowedType.startsWith('image/'));
};
const gallery = multiple && onlyAllowsImages();
const POPOVER_PROPS = {
variant: 'toolbar'
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Dropdown, {
popoverProps: POPOVER_PROPS,
contentClassName: "block-editor-media-replace-flow__options",
renderToggle: _ref3 => {
let {
isOpen,
onToggle
} = _ref3;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
ref: editMediaButtonRef,
"aria-expanded": isOpen,
"aria-haspopup": "true",
onClick: onToggle,
onKeyDown: openOnArrowDown
}, name);
},
renderContent: _ref4 => {
let {
onClose
} = _ref4;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.NavigableMenu, {
className: "block-editor-media-replace-flow__media-upload-menu"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(media_upload, {
gallery: gallery,
addToGallery: addToGallery,
multiple: multiple,
value: multiple ? mediaIds : mediaId,
onSelect: media => selectMedia(media, onClose),
allowedTypes: allowedTypes,
render: _ref5 => {
let {
open
} = _ref5;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
icon: library_media,
onClick: open
}, (0,external_wp_i18n_namespaceObject.__)('Open Media Library'));
}
}), (0,external_wp_element_namespaceObject.createElement)(check, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FormFileUpload, {
onChange: event => {
uploadFiles(event, onClose);
},
accept: accept,
multiple: multiple,
render: _ref6 => {
let {
openFileDialog
} = _ref6;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
icon: library_upload,
onClick: () => {
openFileDialog();
}
}, (0,external_wp_i18n_namespaceObject.__)('Upload'));
}
}))), onToggleFeaturedImage && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
icon: post_featured_image,
onClick: onToggleFeaturedImage,
isPressed: useFeaturedImage
}, (0,external_wp_i18n_namespaceObject.__)('Use featured image')), children), onSelectURL && // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions
(0,external_wp_element_namespaceObject.createElement)("form", {
className: "block-editor-media-flow__url-input"
}, (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-media-replace-flow__image-url-label"
}, (0,external_wp_i18n_namespaceObject.__)('Current media URL:')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Tooltip, {
text: mediaURL,
position: "bottom"
}, (0,external_wp_element_namespaceObject.createElement)("div", null, (0,external_wp_element_namespaceObject.createElement)(link_control, {
value: {
url: mediaURL
},
settings: [],
showSuggestions: false,
onChange: _ref7 => {
let {
url
} = _ref7;
onSelectURL(url);
editMediaButtonRef.current.focus();
}
})))));
}
});
};
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/media-replace-flow/README.md
*/
/* harmony default export */ var media_replace_flow = ((0,external_wp_compose_namespaceObject.compose)([(0,external_wp_data_namespaceObject.withDispatch)(dispatch => {
const {
createNotice,
removeNotice
} = dispatch(external_wp_notices_namespaceObject.store);
return {
createNotice,
removeNotice
};
}), (0,external_wp_components_namespaceObject.withFilters)('editor.MediaReplaceFlow')])(MediaReplaceFlow));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/url-popover/link-viewer-url.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
function LinkViewerURL(_ref) {
let {
url,
urlLabel,
className
} = _ref;
const linkClassName = classnames_default()(className, 'block-editor-url-popover__link-viewer-url');
if (!url) {
return (0,external_wp_element_namespaceObject.createElement)("span", {
className: linkClassName
});
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ExternalLink, {
className: linkClassName,
href: url
}, urlLabel || (0,external_wp_url_namespaceObject.filterURLForDisplay)((0,external_wp_url_namespaceObject.safeDecodeURI)(url)));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/url-popover/link-viewer.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function LinkViewer(_ref) {
let {
className,
linkClassName,
onEditLinkClick,
url,
urlLabel,
...props
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("div", _extends({
className: classnames_default()('block-editor-url-popover__link-viewer', className)
}, props), (0,external_wp_element_namespaceObject.createElement)(LinkViewerURL, {
url: url,
urlLabel: urlLabel,
className: linkClassName
}), onEditLinkClick && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
icon: library_edit,
label: (0,external_wp_i18n_namespaceObject.__)('Edit'),
onClick: onEditLinkClick
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/url-popover/link-editor.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function LinkEditor(_ref) {
let {
autocompleteRef,
className,
onChangeInputValue,
value,
...props
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("form", _extends({
className: classnames_default()('block-editor-url-popover__link-editor', className)
}, props), (0,external_wp_element_namespaceObject.createElement)(url_input, {
__nextHasNoMarginBottom: true,
value: value,
onChange: onChangeInputValue,
autocompleteRef: autocompleteRef
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
icon: keyboard_return,
label: (0,external_wp_i18n_namespaceObject.__)('Apply'),
type: "submit"
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/url-popover/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const {
__experimentalPopoverLegacyPositionToPlacement
} = unlock(external_wp_components_namespaceObject.privateApis);
const DEFAULT_PLACEMENT = 'bottom';
function URLPopover(_ref) {
let {
additionalControls,
children,
renderSettings,
// The DEFAULT_PLACEMENT value is assigned inside the function's body
placement,
focusOnMount = 'firstElement',
// Deprecated
position,
// Rest
...popoverProps
} = _ref;
if (position !== undefined) {
external_wp_deprecated_default()('`position` prop in wp.blockEditor.URLPopover', {
since: '6.2',
alternative: '`placement` prop'
});
} // Compute popover's placement:
// - give priority to `placement` prop, if defined
// - otherwise, compute it from the legacy `position` prop (if defined)
// - finally, fallback to the DEFAULT_PLACEMENT.
let computedPlacement;
if (placement !== undefined) {
computedPlacement = placement;
} else if (position !== undefined) {
computedPlacement = __experimentalPopoverLegacyPositionToPlacement(position);
}
computedPlacement = computedPlacement || DEFAULT_PLACEMENT;
const [isSettingsExpanded, setIsSettingsExpanded] = (0,external_wp_element_namespaceObject.useState)(false);
const showSettings = !!renderSettings && isSettingsExpanded;
const toggleSettingsVisibility = () => {
setIsSettingsExpanded(!isSettingsExpanded);
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Popover, _extends({
className: "block-editor-url-popover",
focusOnMount: focusOnMount,
placement: computedPlacement,
shift: true
}, popoverProps), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-url-popover__input-container"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-url-popover__row"
}, children, !!renderSettings && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "block-editor-url-popover__settings-toggle",
icon: chevron_down,
label: (0,external_wp_i18n_namespaceObject.__)('Link settings'),
onClick: toggleSettingsVisibility,
"aria-expanded": isSettingsExpanded
})), showSettings && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-url-popover__row block-editor-url-popover__settings"
}, renderSettings())), additionalControls && !showSettings && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-url-popover__additional-controls"
}, additionalControls));
}
URLPopover.LinkEditor = LinkEditor;
URLPopover.LinkViewer = LinkViewer;
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/url-popover/README.md
*/
/* harmony default export */ var url_popover = (URLPopover);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/media-placeholder/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const media_placeholder_noop = () => {};
const InsertFromURLPopover = _ref => {
let {
src,
onChange,
onSubmit,
onClose
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(url_popover, {
onClose: onClose
}, (0,external_wp_element_namespaceObject.createElement)("form", {
className: "block-editor-media-placeholder__url-input-form",
onSubmit: onSubmit
}, (0,external_wp_element_namespaceObject.createElement)("input", {
className: "block-editor-media-placeholder__url-input-field",
type: "text",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('URL'),
placeholder: (0,external_wp_i18n_namespaceObject.__)('Paste or type URL'),
onChange: onChange,
value: src
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "block-editor-media-placeholder__url-input-submit-button",
icon: keyboard_return,
label: (0,external_wp_i18n_namespaceObject.__)('Apply'),
type: "submit"
})));
};
function MediaPlaceholder(_ref2) {
let {
value = {},
allowedTypes,
className,
icon,
labels = {},
mediaPreview,
notices,
isAppender,
accept,
addToGallery,
multiple = false,
handleUpload = true,
disableDropZone,
disableMediaButtons,
onError,
onSelect,
onCancel,
onSelectURL,
onToggleFeaturedImage,
onDoubleClick,
onFilesPreUpload = media_placeholder_noop,
onHTMLDrop = media_placeholder_noop,
children,
mediaLibraryButton,
placeholder,
style
} = _ref2;
const mediaUpload = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getSettings
} = select(store);
return getSettings().mediaUpload;
}, []);
const [src, setSrc] = (0,external_wp_element_namespaceObject.useState)('');
const [isURLInputVisible, setIsURLInputVisible] = (0,external_wp_element_namespaceObject.useState)(false);
(0,external_wp_element_namespaceObject.useEffect)(() => {
var _value$src;
setSrc((_value$src = value === null || value === void 0 ? void 0 : value.src) !== null && _value$src !== void 0 ? _value$src : '');
}, [value === null || value === void 0 ? void 0 : value.src]);
const onlyAllowsImages = () => {
if (!allowedTypes || allowedTypes.length === 0) {
return false;
}
return allowedTypes.every(allowedType => allowedType === 'image' || allowedType.startsWith('image/'));
};
const onChangeSrc = event => {
setSrc(event.target.value);
};
const openURLInput = () => {
setIsURLInputVisible(true);
};
const closeURLInput = () => {
setIsURLInputVisible(false);
};
const onSubmitSrc = event => {
event.preventDefault();
if (src && onSelectURL) {
onSelectURL(src);
closeURLInput();
}
};
const onFilesUpload = files => {
if (!handleUpload) {
return onSelect(files);
}
onFilesPreUpload(files);
let setMedia;
if (multiple) {
if (addToGallery) {
// Since the setMedia function runs multiple times per upload group
// and is passed newMedia containing every item in its group each time, we must
// filter out whatever this upload group had previously returned to the
// gallery before adding and returning the image array with replacement newMedia
// values.
// Define an array to store urls from newMedia between subsequent function calls.
let lastMediaPassed = [];
setMedia = newMedia => {
// Remove any images this upload group is responsible for (lastMediaPassed).
// Their replacements are contained in newMedia.
const filteredMedia = (value !== null && value !== void 0 ? value : []).filter(item => {
// If Item has id, only remove it if lastMediaPassed has an item with that id.
if (item.id) {
return !lastMediaPassed.some( // Be sure to convert to number for comparison.
_ref3 => {
let {
id
} = _ref3;
return Number(id) === Number(item.id);
});
} // Compare transient images via .includes since gallery may append extra info onto the url.
return !lastMediaPassed.some(_ref4 => {
let {
urlSlug
} = _ref4;
return item.url.includes(urlSlug);
});
}); // Return the filtered media array along with newMedia.
onSelect(filteredMedia.concat(newMedia)); // Reset lastMediaPassed and set it with ids and urls from newMedia.
lastMediaPassed = newMedia.map(media => {
// Add everything up to '.fileType' to compare via .includes.
const cutOffIndex = media.url.lastIndexOf('.');
const urlSlug = media.url.slice(0, cutOffIndex);
return {
id: media.id,
urlSlug
};
});
};
} else {
setMedia = onSelect;
}
} else {
setMedia = _ref5 => {
let [media] = _ref5;
return onSelect(media);
};
}
mediaUpload({
allowedTypes,
filesList: files,
onFileChange: setMedia,
onError
});
};
const onUpload = event => {
onFilesUpload(event.target.files);
};
const defaultRenderPlaceholder = content => {
let {
instructions,
title
} = labels;
if (!mediaUpload && !onSelectURL) {
instructions = (0,external_wp_i18n_namespaceObject.__)('To edit this block, you need permission to upload media.');
}
if (instructions === undefined || title === undefined) {
const typesAllowed = allowedTypes !== null && allowedTypes !== void 0 ? allowedTypes : [];
const [firstAllowedType] = typesAllowed;
const isOneType = 1 === typesAllowed.length;
const isAudio = isOneType && 'audio' === firstAllowedType;
const isImage = isOneType && 'image' === firstAllowedType;
const isVideo = isOneType && 'video' === firstAllowedType;
if (instructions === undefined && mediaUpload) {
instructions = (0,external_wp_i18n_namespaceObject.__)('Upload a media file or pick one from your media library.');
if (isAudio) {
instructions = (0,external_wp_i18n_namespaceObject.__)('Upload an audio file, pick one from your media library, or add one with a URL.');
} else if (isImage) {
instructions = (0,external_wp_i18n_namespaceObject.__)('Upload an image file, pick one from your media library, or add one with a URL.');
} else if (isVideo) {
instructions = (0,external_wp_i18n_namespaceObject.__)('Upload a video file, pick one from your media library, or add one with a URL.');
}
}
if (title === undefined) {
title = (0,external_wp_i18n_namespaceObject.__)('Media');
if (isAudio) {
title = (0,external_wp_i18n_namespaceObject.__)('Audio');
} else if (isImage) {
title = (0,external_wp_i18n_namespaceObject.__)('Image');
} else if (isVideo) {
title = (0,external_wp_i18n_namespaceObject.__)('Video');
}
}
}
const placeholderClassName = classnames_default()('block-editor-media-placeholder', className, {
'is-appender': isAppender
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Placeholder, {
icon: icon,
label: title,
instructions: instructions,
className: placeholderClassName,
notices: notices,
onDoubleClick: onDoubleClick,
preview: mediaPreview,
style: style
}, content, children);
};
const renderPlaceholder = placeholder !== null && placeholder !== void 0 ? placeholder : defaultRenderPlaceholder;
const renderDropZone = () => {
if (disableDropZone) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.DropZone, {
onFilesDrop: onFilesUpload,
onHTMLDrop: onHTMLDrop
});
};
const renderCancelLink = () => {
return onCancel && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "block-editor-media-placeholder__cancel-button",
title: (0,external_wp_i18n_namespaceObject.__)('Cancel'),
variant: "link",
onClick: onCancel
}, (0,external_wp_i18n_namespaceObject.__)('Cancel'));
};
const renderUrlSelectionUI = () => {
return onSelectURL && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-media-placeholder__url-input-container"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "block-editor-media-placeholder__button",
onClick: openURLInput,
isPressed: isURLInputVisible,
variant: "tertiary"
}, (0,external_wp_i18n_namespaceObject.__)('Insert from URL')), isURLInputVisible && (0,external_wp_element_namespaceObject.createElement)(InsertFromURLPopover, {
src: src,
onChange: onChangeSrc,
onSubmit: onSubmitSrc,
onClose: closeURLInput
}));
};
const renderFeaturedImageToggle = () => {
return onToggleFeaturedImage && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-media-placeholder__url-input-container"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "block-editor-media-placeholder__button",
onClick: onToggleFeaturedImage,
variant: "tertiary"
}, (0,external_wp_i18n_namespaceObject.__)('Use featured image')));
};
const renderMediaUploadChecked = () => {
const defaultButton = _ref6 => {
let {
open
} = _ref6;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "tertiary",
onClick: () => {
open();
}
}, (0,external_wp_i18n_namespaceObject.__)('Media Library'));
};
const libraryButton = mediaLibraryButton !== null && mediaLibraryButton !== void 0 ? mediaLibraryButton : defaultButton;
const uploadMediaLibraryButton = (0,external_wp_element_namespaceObject.createElement)(media_upload, {
addToGallery: addToGallery,
gallery: multiple && onlyAllowsImages(),
multiple: multiple,
onSelect: onSelect,
allowedTypes: allowedTypes,
mode: 'browse',
value: Array.isArray(value) ? value.map(_ref7 => {
let {
id
} = _ref7;
return id;
}) : value.id,
render: libraryButton
});
if (mediaUpload && isAppender) {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, renderDropZone(), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FormFileUpload, {
onChange: onUpload,
accept: accept,
multiple: multiple,
render: _ref8 => {
let {
openFileDialog
} = _ref8;
const content = (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "primary",
className: classnames_default()('block-editor-media-placeholder__button', 'block-editor-media-placeholder__upload-button'),
onClick: openFileDialog
}, (0,external_wp_i18n_namespaceObject.__)('Upload')), uploadMediaLibraryButton, renderUrlSelectionUI(), renderFeaturedImageToggle(), renderCancelLink());
return renderPlaceholder(content);
}
}));
}
if (mediaUpload) {
const content = (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, renderDropZone(), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FormFileUpload, {
variant: "primary",
className: classnames_default()('block-editor-media-placeholder__button', 'block-editor-media-placeholder__upload-button'),
onChange: onUpload,
accept: accept,
multiple: multiple
}, (0,external_wp_i18n_namespaceObject.__)('Upload')), uploadMediaLibraryButton, renderUrlSelectionUI(), renderFeaturedImageToggle(), renderCancelLink());
return renderPlaceholder(content);
}
return renderPlaceholder(uploadMediaLibraryButton);
};
if (disableMediaButtons) {
return (0,external_wp_element_namespaceObject.createElement)(check, null, renderDropZone());
}
return (0,external_wp_element_namespaceObject.createElement)(check, {
fallback: renderPlaceholder(renderUrlSelectionUI())
}, renderMediaUploadChecked());
}
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/media-placeholder/README.md
*/
/* harmony default export */ var media_placeholder = ((0,external_wp_components_namespaceObject.withFilters)('editor.MediaPlaceholder')(MediaPlaceholder));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/panel-color-settings/index.js
/**
* Internal dependencies
*/
const PanelColorSettings = _ref => {
let {
colorSettings,
...props
} = _ref;
const settings = colorSettings.map(setting => {
if (!setting) {
return setting;
}
const {
value,
onChange,
...otherSettings
} = setting;
return { ...otherSettings,
colorValue: value,
onColorChange: onChange
};
});
return (0,external_wp_element_namespaceObject.createElement)(panel_color_gradient_settings, _extends({
settings: settings,
gradients: [],
disableCustomGradients: true
}, props));
};
/* harmony default export */ var panel_color_settings = (PanelColorSettings);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/rich-text/format-toolbar/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const format_toolbar_POPOVER_PROPS = {
position: 'bottom right',
variant: 'toolbar'
};
const FormatToolbar = () => {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, ['bold', 'italic', 'link', 'unknown'].map(format => (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Slot, {
name: `RichText.ToolbarControls.${format}`,
key: format
})), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Slot, {
name: "RichText.ToolbarControls"
}, fills => {
if (!fills.length) {
return null;
}
const allProps = fills.map(_ref => {
let [{
props
}] = _ref;
return props;
});
const hasActive = allProps.some(_ref2 => {
let {
isActive
} = _ref2;
return isActive;
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarItem, null, toggleProps => (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.DropdownMenu, {
icon: chevron_down
/* translators: button label text should, if possible, be under 16 characters. */
,
label: (0,external_wp_i18n_namespaceObject.__)('More'),
toggleProps: { ...toggleProps,
className: classnames_default()(toggleProps.className, {
'is-pressed': hasActive
}),
describedBy: (0,external_wp_i18n_namespaceObject.__)('Displays more block tools')
},
controls: orderBy(fills.map(_ref3 => {
let [{
props
}] = _ref3;
return props;
}), 'title'),
popoverProps: format_toolbar_POPOVER_PROPS
}));
}));
};
/* harmony default export */ var format_toolbar = (FormatToolbar);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/rich-text/format-toolbar-container.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function InlineSelectionToolbar(_ref) {
let {
value,
editableContentElement,
activeFormats
} = _ref;
const lastFormat = activeFormats[activeFormats.length - 1];
const lastFormatType = lastFormat === null || lastFormat === void 0 ? void 0 : lastFormat.type;
const settings = (0,external_wp_data_namespaceObject.useSelect)(select => select(external_wp_richText_namespaceObject.store).getFormatType(lastFormatType), [lastFormatType]);
const popoverAnchor = (0,external_wp_richText_namespaceObject.useAnchor)({
editableContentElement,
value,
settings
});
return (0,external_wp_element_namespaceObject.createElement)(InlineToolbar, {
popoverAnchor: popoverAnchor
});
}
function InlineToolbar(_ref2) {
let {
popoverAnchor
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Popover, {
placement: "top",
focusOnMount: false,
anchor: popoverAnchor,
className: "block-editor-rich-text__inline-format-toolbar",
__unstableSlotName: "block-toolbar"
}, (0,external_wp_element_namespaceObject.createElement)(navigable_toolbar, {
className: "block-editor-rich-text__inline-format-toolbar-group"
/* translators: accessibility text for the inline format toolbar */
,
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Format tools')
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarGroup, null, (0,external_wp_element_namespaceObject.createElement)(format_toolbar, null))));
}
const FormatToolbarContainer = _ref3 => {
let {
inline,
editableContentElement,
value
} = _ref3;
const hasInlineToolbar = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).getSettings().hasInlineToolbar, []);
if (inline) {
return (0,external_wp_element_namespaceObject.createElement)(InlineToolbar, {
popoverAnchor: editableContentElement
});
}
if (hasInlineToolbar) {
const activeFormats = (0,external_wp_richText_namespaceObject.getActiveFormats)(value);
if ((0,external_wp_richText_namespaceObject.isCollapsed)(value) && !activeFormats.length) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(InlineSelectionToolbar, {
editableContentElement: editableContentElement,
value: value,
activeFormats: activeFormats
});
} // Render regular toolbar.
return (0,external_wp_element_namespaceObject.createElement)(block_controls, {
group: "inline"
}, (0,external_wp_element_namespaceObject.createElement)(format_toolbar, null));
};
/* harmony default export */ var format_toolbar_container = (FormatToolbarContainer);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/rich-text/use-undo-automatic-change.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useUndoAutomaticChange() {
const {
didAutomaticChange,
getSettings
} = (0,external_wp_data_namespaceObject.useSelect)(store);
return (0,external_wp_compose_namespaceObject.useRefEffect)(element => {
function onKeyDown(event) {
const {
keyCode
} = event;
if (event.defaultPrevented) {
return;
}
if (keyCode !== external_wp_keycodes_namespaceObject.DELETE && keyCode !== external_wp_keycodes_namespaceObject.BACKSPACE && keyCode !== external_wp_keycodes_namespaceObject.ESCAPE) {
return;
}
const {
__experimentalUndo
} = getSettings();
if (!__experimentalUndo) {
return;
}
if (!didAutomaticChange()) {
return;
}
event.preventDefault();
__experimentalUndo();
}
element.addEventListener('keydown', onKeyDown);
return () => {
element.removeEventListener('keydown', onKeyDown);
};
}, []);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/rich-text/use-mark-persistent.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useMarkPersistent(_ref) {
let {
html,
value
} = _ref;
const previousText = (0,external_wp_element_namespaceObject.useRef)();
const hasActiveFormats = value.activeFormats && !!value.activeFormats.length;
const {
__unstableMarkLastChangeAsPersistent
} = (0,external_wp_data_namespaceObject.useDispatch)(store); // Must be set synchronously to make sure it applies to the last change.
(0,external_wp_element_namespaceObject.useLayoutEffect)(() => {
// Ignore mount.
if (!previousText.current) {
previousText.current = value.text;
return;
} // Text input, so don't create an undo level for every character.
// Create an undo level after 1 second of no input.
if (previousText.current !== value.text) {
const timeout = window.setTimeout(() => {
__unstableMarkLastChangeAsPersistent();
}, 1000);
previousText.current = value.text;
return () => {
window.clearTimeout(timeout);
};
}
__unstableMarkLastChangeAsPersistent();
}, [html, hasActiveFormats]);
}
;// CONCATENATED MODULE: external ["wp","shortcode"]
var external_wp_shortcode_namespaceObject = window["wp"]["shortcode"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/rich-text/utils.js
/**
* WordPress dependencies
*/
function addActiveFormats(value, activeFormats) {
if (activeFormats !== null && activeFormats !== void 0 && activeFormats.length) {
let index = value.formats.length;
while (index--) {
value.formats[index] = [...activeFormats, ...(value.formats[index] || [])];
}
}
}
/**
* Get the multiline tag based on the multiline prop.
*
* @param {?(string|boolean)} multiline The multiline prop.
*
* @return {string | undefined} The multiline tag.
*/
function getMultilineTag(multiline) {
if (multiline !== true && multiline !== 'p' && multiline !== 'li') {
return;
}
return multiline === true ? 'p' : multiline;
}
function getAllowedFormats(_ref) {
let {
allowedFormats,
disableFormats
} = _ref;
if (disableFormats) {
return getAllowedFormats.EMPTY_ARRAY;
}
return allowedFormats;
}
getAllowedFormats.EMPTY_ARRAY = [];
const isShortcode = text => (0,external_wp_shortcode_namespaceObject.regexp)('.*').test(text);
/**
* Creates a link from pasted URL.
* Creates a paragraph block containing a link to the URL, and calls `onReplace`.
*
* @param {string} url The URL that could not be embedded.
* @param {Function} onReplace Function to call with the created fallback block.
*/
function createLinkInParagraph(url, onReplace) {
const link = createElement("a", {
href: url
}, url);
onReplace(createBlock('core/paragraph', {
content: renderToString(link)
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/rich-text/split-value.js
/**
* WordPress dependencies
*/
/*
* Signals to the RichText owner that the block can be replaced with two blocks
* as a result of splitting the block by pressing enter, or with blocks as a
* result of splitting the block by pasting block content in the instance.
*/
function splitValue(_ref) {
let {
value,
pastedBlocks = [],
onReplace,
onSplit,
onSplitMiddle,
multilineTag
} = _ref;
if (!onReplace || !onSplit) {
return;
} // Ensure the value has a selection. This might happen when trying to split
// an empty value before there was a `selectionchange` event.
const {
start = 0,
end = 0
} = value;
const valueWithEnsuredSelection = { ...value,
start,
end
};
const blocks = [];
const [before, after] = (0,external_wp_richText_namespaceObject.split)(valueWithEnsuredSelection);
const hasPastedBlocks = pastedBlocks.length > 0;
let lastPastedBlockIndex = -1; // Consider the after value to be the original it is not empty and the
// before value *is* empty.
const isAfterOriginal = (0,external_wp_richText_namespaceObject.isEmpty)(before) && !(0,external_wp_richText_namespaceObject.isEmpty)(after); // Create a block with the content before the caret if there's no pasted
// blocks, or if there are pasted blocks and the value is not empty. We do
// not want a leading empty block on paste, but we do if split with e.g. the
// enter key.
if (!hasPastedBlocks || !(0,external_wp_richText_namespaceObject.isEmpty)(before)) {
blocks.push(onSplit((0,external_wp_richText_namespaceObject.toHTMLString)({
value: before,
multilineTag
}), !isAfterOriginal));
lastPastedBlockIndex += 1;
}
if (hasPastedBlocks) {
blocks.push(...pastedBlocks);
lastPastedBlockIndex += pastedBlocks.length;
} else if (onSplitMiddle) {
blocks.push(onSplitMiddle());
} // If there's pasted blocks, append a block with non empty content / after
// the caret. Otherwise, do append an empty block if there is no
// `onSplitMiddle` prop, but if there is and the content is empty, the
// middle block is enough to set focus in.
if (hasPastedBlocks ? !(0,external_wp_richText_namespaceObject.isEmpty)(after) : !onSplitMiddle || !(0,external_wp_richText_namespaceObject.isEmpty)(after)) {
blocks.push(onSplit((0,external_wp_richText_namespaceObject.toHTMLString)({
value: after,
multilineTag
}), isAfterOriginal));
} // If there are pasted blocks, set the selection to the last one. Otherwise,
// set the selection to the second block.
const indexToSelect = hasPastedBlocks ? lastPastedBlockIndex : 1; // If there are pasted blocks, move the caret to the end of the selected
// block Otherwise, retain the default value.
const initialPosition = hasPastedBlocks ? -1 : 0;
onReplace(blocks, indexToSelect, initialPosition);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/rich-text/use-paste-handler.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/** @typedef {import('@wordpress/rich-text').RichTextValue} RichTextValue */
/**
* Replaces line separators with line breaks if not multiline.
* Replaces line breaks with line separators if multiline.
*
* @param {RichTextValue} value Value to adjust.
* @param {boolean} isMultiline Whether to adjust to multiline or not.
*
* @return {RichTextValue} Adjusted value.
*/
function adjustLines(value, isMultiline) {
if (isMultiline) {
return (0,external_wp_richText_namespaceObject.replace)(value, /\n+/g, external_wp_richText_namespaceObject.__UNSTABLE_LINE_SEPARATOR);
}
return (0,external_wp_richText_namespaceObject.replace)(value, new RegExp(external_wp_richText_namespaceObject.__UNSTABLE_LINE_SEPARATOR, 'g'), '\n');
}
function usePasteHandler(props) {
const propsRef = (0,external_wp_element_namespaceObject.useRef)(props);
propsRef.current = props;
return (0,external_wp_compose_namespaceObject.useRefEffect)(element => {
function _onPaste(event) {
const {
isSelected,
disableFormats,
onChange,
value,
formatTypes,
tagName,
onReplace,
onSplit,
onSplitMiddle,
__unstableEmbedURLOnPaste,
multilineTag,
preserveWhiteSpace,
pastePlainText
} = propsRef.current;
if (!isSelected) {
return;
}
const {
clipboardData
} = event;
let plainText = '';
let html = ''; // IE11 only supports `Text` as an argument for `getData` and will
// otherwise throw an invalid argument error, so we try the standard
// arguments first, then fallback to `Text` if they fail.
try {
plainText = clipboardData.getData('text/plain');
html = clipboardData.getData('text/html');
} catch (error1) {
try {
html = clipboardData.getData('Text');
} catch (error2) {
// Some browsers like UC Browser paste plain text by default and
// don't support clipboardData at all, so allow default
// behaviour.
return;
}
} // Remove Windows-specific metadata appended within copied HTML text.
html = removeWindowsFragments(html); // Strip meta tag.
html = removeCharsetMetaTag(html);
event.preventDefault(); // Allows us to ask for this information when we get a report.
window.console.log('Received HTML:\n\n', html);
window.console.log('Received plain text:\n\n', plainText);
if (disableFormats) {
onChange((0,external_wp_richText_namespaceObject.insert)(value, plainText));
return;
}
const transformed = formatTypes.reduce((accumlator, _ref) => {
let {
__unstablePasteRule
} = _ref;
// Only allow one transform.
if (__unstablePasteRule && accumlator === value) {
accumlator = __unstablePasteRule(value, {
html,
plainText
});
}
return accumlator;
}, value);
if (transformed !== value) {
onChange(transformed);
return;
}
const files = [...(0,external_wp_dom_namespaceObject.getFilesFromDataTransfer)(clipboardData)];
const isInternal = clipboardData.getData('rich-text') === 'true'; // If the data comes from a rich text instance, we can directly use it
// without filtering the data. The filters are only meant for externally
// pasted content and remove inline styles.
if (isInternal) {
const pastedMultilineTag = clipboardData.getData('rich-text-multi-line-tag') || undefined;
let pastedValue = (0,external_wp_richText_namespaceObject.create)({
html,
multilineTag: pastedMultilineTag,
multilineWrapperTags: pastedMultilineTag === 'li' ? ['ul', 'ol'] : undefined,
preserveWhiteSpace
});
pastedValue = adjustLines(pastedValue, !!multilineTag);
addActiveFormats(pastedValue, value.activeFormats);
onChange((0,external_wp_richText_namespaceObject.insert)(value, pastedValue));
return;
}
if (pastePlainText) {
onChange((0,external_wp_richText_namespaceObject.insert)(value, (0,external_wp_richText_namespaceObject.create)({
text: plainText
})));
return;
}
if (files !== null && files !== void 0 && files.length) {
// Allows us to ask for this information when we get a report.
// eslint-disable-next-line no-console
window.console.log('Received items:\n\n', files);
} // Process any attached files, unless we infer that the files in
// question are redundant "screenshots" of the actual HTML payload,
// as created by certain office-type programs.
//
// @see shouldDismissPastedFiles
if (files !== null && files !== void 0 && files.length && !shouldDismissPastedFiles(files, html, plainText)) {
const fromTransforms = (0,external_wp_blocks_namespaceObject.getBlockTransforms)('from');
const blocks = files.reduce((accumulator, file) => {
const transformation = (0,external_wp_blocks_namespaceObject.findTransform)(fromTransforms, transform => transform.type === 'files' && transform.isMatch([file]));
if (transformation) {
accumulator.push(transformation.transform([file]));
}
return accumulator;
}, []).flat();
if (!blocks.length) {
return;
}
if (onReplace && (0,external_wp_richText_namespaceObject.isEmpty)(value)) {
onReplace(blocks);
} else {
splitValue({
value,
pastedBlocks: blocks,
onReplace,
onSplit,
onSplitMiddle,
multilineTag
});
}
return;
}
let mode = onReplace && onSplit ? 'AUTO' : 'INLINE'; // Force the blocks mode when the user is pasting
// on a new line & the content resembles a shortcode.
// Otherwise it's going to be detected as inline
// and the shortcode won't be replaced.
if (mode === 'AUTO' && (0,external_wp_richText_namespaceObject.isEmpty)(value) && isShortcode(plainText)) {
mode = 'BLOCKS';
}
if (__unstableEmbedURLOnPaste && (0,external_wp_richText_namespaceObject.isEmpty)(value) && (0,external_wp_url_namespaceObject.isURL)(plainText.trim())) {
mode = 'BLOCKS';
}
const content = (0,external_wp_blocks_namespaceObject.pasteHandler)({
HTML: html,
plainText,
mode,
tagName,
preserveWhiteSpace
});
if (typeof content === 'string') {
let valueToInsert = (0,external_wp_richText_namespaceObject.create)({
html: content
}); // If the content should be multiline, we should process text
// separated by a line break as separate lines.
valueToInsert = adjustLines(valueToInsert, !!multilineTag);
addActiveFormats(valueToInsert, value.activeFormats);
onChange((0,external_wp_richText_namespaceObject.insert)(value, valueToInsert));
} else if (content.length > 0) {
if (onReplace && (0,external_wp_richText_namespaceObject.isEmpty)(value)) {
onReplace(content, content.length - 1, -1);
} else {
splitValue({
value,
pastedBlocks: content,
onReplace,
onSplit,
onSplitMiddle,
multilineTag
});
}
}
}
element.addEventListener('paste', _onPaste);
return () => {
element.removeEventListener('paste', _onPaste);
};
}, []);
}
/**
* Normalizes a given string of HTML to remove the Windows-specific "Fragment"
* comments and any preceding and trailing content.
*
* @param {string} html the html to be normalized
* @return {string} the normalized html
*/
function removeWindowsFragments(html) {
const startStr = '<!--StartFragment-->';
const startIdx = html.indexOf(startStr);
if (startIdx > -1) {
html = html.substring(startIdx + startStr.length);
} else {
// No point looking for EndFragment
return html;
}
const endStr = '<!--EndFragment-->';
const endIdx = html.indexOf(endStr);
if (endIdx > -1) {
html = html.substring(0, endIdx);
}
return html;
}
/**
* Removes the charset meta tag inserted by Chromium.
* See:
* - https://github.com/WordPress/gutenberg/issues/33585
* - https://bugs.chromium.org/p/chromium/issues/detail?id=1264616#c4
*
* @param {string} html the html to be stripped of the meta tag.
* @return {string} the cleaned html
*/
function removeCharsetMetaTag(html) {
const metaTag = `<meta charset='utf-8'>`;
if (html.startsWith(metaTag)) {
return html.slice(metaTag.length);
}
return html;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/rich-text/use-before-input-rules.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* When typing over a selection, the selection will we wrapped by a matching
* character pair. The second character is optional, it defaults to the first
* character.
*
* @type {string[]} Array of character pairs.
*/
const wrapSelectionSettings = ['`', '"', "'", '“”', '‘’'];
function useBeforeInputRules(props) {
const {
__unstableMarkLastChangeAsPersistent,
__unstableMarkAutomaticChange
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const propsRef = (0,external_wp_element_namespaceObject.useRef)(props);
propsRef.current = props;
return (0,external_wp_compose_namespaceObject.useRefEffect)(element => {
function onInput(event) {
const {
inputType,
data
} = event;
const {
value,
onChange
} = propsRef.current; // Only run the rules when inserting text.
if (inputType !== 'insertText') {
return;
}
if ((0,external_wp_richText_namespaceObject.isCollapsed)(value)) {
return;
}
const pair = (0,external_wp_hooks_namespaceObject.applyFilters)('blockEditor.wrapSelectionSettings', wrapSelectionSettings).find(_ref => {
let [startChar, endChar] = _ref;
return startChar === data || endChar === data;
});
if (!pair) {
return;
}
const [startChar, endChar = startChar] = pair;
const start = value.start;
const end = value.end + startChar.length;
let newValue = (0,external_wp_richText_namespaceObject.insert)(value, startChar, start, start);
newValue = (0,external_wp_richText_namespaceObject.insert)(newValue, endChar, end, end);
__unstableMarkLastChangeAsPersistent();
onChange(newValue);
__unstableMarkAutomaticChange();
const init = {};
for (const key in event) {
init[key] = event[key];
}
init.data = endChar;
const {
ownerDocument
} = element;
const {
defaultView
} = ownerDocument;
const newEvent = new defaultView.InputEvent('input', init); // Dispatch an `input` event with the new data. This will trigger the
// input rules.
// Postpone the `input` to the next event loop tick so that the dispatch
// doesn't happen synchronously in the middle of `beforeinput` dispatch.
// This is closer to how native `input` event would be timed, and also
// makes sure that the `input` event is dispatched only after the `onChange`
// call few lines above has fully updated the data store state and rerendered
// all affected components.
window.queueMicrotask(() => {
event.target.dispatchEvent(newEvent);
});
event.preventDefault();
}
element.addEventListener('beforeinput', onInput);
return () => {
element.removeEventListener('beforeinput', onInput);
};
}, []);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/rich-text/prevent-event-discovery.js
/**
* WordPress dependencies
*/
function preventEventDiscovery(value) {
const searchText = 'tales of gutenberg';
const addText = ' 🐡🐢🦀🐤🦋🐘🐧🐹🦁🦄🦍🐼🐿🎃🐴🐝🐆🦕🦔🌱🍇π🍌🐉💧🥨🌌🍂🍠🥦🥚🥝🎟🥥🥒🛵🥖🍒🍯🎾🎲🐺🐚🐮⌛️';
const {
start,
text
} = value;
if (start < searchText.length) {
return value;
}
const charactersBefore = text.slice(start - searchText.length, start);
if (charactersBefore.toLowerCase() !== searchText) {
return value;
}
return (0,external_wp_richText_namespaceObject.insert)(value, addText);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/rich-text/use-input-rules.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function findSelection(blocks) {
let i = blocks.length;
while (i--) {
const attributeKey = retrieveSelectedAttribute(blocks[i].attributes);
if (attributeKey) {
blocks[i].attributes[attributeKey] = blocks[i].attributes[attributeKey].replace(START_OF_SELECTED_AREA, '');
return blocks[i].clientId;
}
const nestedSelection = findSelection(blocks[i].innerBlocks);
if (nestedSelection) {
return nestedSelection;
}
}
}
function useInputRules(props) {
const {
__unstableMarkLastChangeAsPersistent,
__unstableMarkAutomaticChange
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const propsRef = (0,external_wp_element_namespaceObject.useRef)(props);
propsRef.current = props;
return (0,external_wp_compose_namespaceObject.useRefEffect)(element => {
function inputRule() {
const {
getValue,
onReplace,
selectionChange
} = propsRef.current;
if (!onReplace) {
return;
} // We must use getValue() here because value may be update
// asynchronously.
const value = getValue();
const {
start,
text
} = value;
const characterBefore = text.slice(start - 1, start); // The character right before the caret must be a plain space.
if (characterBefore !== ' ') {
return;
}
const trimmedTextBefore = text.slice(0, start).trim();
const prefixTransforms = (0,external_wp_blocks_namespaceObject.getBlockTransforms)('from').filter(_ref => {
let {
type
} = _ref;
return type === 'prefix';
});
const transformation = (0,external_wp_blocks_namespaceObject.findTransform)(prefixTransforms, _ref2 => {
let {
prefix
} = _ref2;
return trimmedTextBefore === prefix;
});
if (!transformation) {
return;
}
const content = (0,external_wp_richText_namespaceObject.toHTMLString)({
value: (0,external_wp_richText_namespaceObject.insert)(value, START_OF_SELECTED_AREA, 0, start)
});
const block = transformation.transform(content);
selectionChange(findSelection([block]));
onReplace([block]);
__unstableMarkAutomaticChange();
}
function onInput(event) {
const {
inputType,
type
} = event;
const {
getValue,
onChange,
__unstableAllowPrefixTransformations,
formatTypes
} = propsRef.current; // Only run input rules when inserting text.
if (inputType !== 'insertText' && type !== 'compositionend') {
return;
}
if (__unstableAllowPrefixTransformations && inputRule) {
inputRule();
}
const value = getValue();
const transformed = formatTypes.reduce((accumlator, _ref3) => {
let {
__unstableInputRule
} = _ref3;
if (__unstableInputRule) {
accumlator = __unstableInputRule(accumlator);
}
return accumlator;
}, preventEventDiscovery(value));
if (transformed !== value) {
__unstableMarkLastChangeAsPersistent();
onChange({ ...transformed,
activeFormats: value.activeFormats
});
__unstableMarkAutomaticChange();
}
}
element.addEventListener('input', onInput);
element.addEventListener('compositionend', onInput);
return () => {
element.removeEventListener('input', onInput);
element.removeEventListener('compositionend', onInput);
};
}, []);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/rich-text/use-enter.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useEnter(props) {
const {
__unstableMarkAutomaticChange
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const propsRef = (0,external_wp_element_namespaceObject.useRef)(props);
propsRef.current = props;
return (0,external_wp_compose_namespaceObject.useRefEffect)(element => {
function onKeyDown(event) {
if (event.defaultPrevented) {
return;
}
if (event.keyCode !== external_wp_keycodes_namespaceObject.ENTER) {
return;
}
const {
removeEditorOnlyFormats,
value,
onReplace,
onSplit,
onSplitMiddle,
multilineTag,
onChange,
disableLineBreaks,
onSplitAtEnd
} = propsRef.current;
event.preventDefault();
const _value = { ...value
};
_value.formats = removeEditorOnlyFormats(value);
const canSplit = onReplace && onSplit;
if (onReplace) {
const transforms = (0,external_wp_blocks_namespaceObject.getBlockTransforms)('from').filter(_ref => {
let {
type
} = _ref;
return type === 'enter';
});
const transformation = (0,external_wp_blocks_namespaceObject.findTransform)(transforms, item => {
return item.regExp.test(_value.text);
});
if (transformation) {
onReplace([transformation.transform({
content: _value.text
})]);
__unstableMarkAutomaticChange();
}
}
if (multilineTag) {
if (event.shiftKey) {
if (!disableLineBreaks) {
onChange((0,external_wp_richText_namespaceObject.insert)(_value, '\n'));
}
} else if (canSplit && (0,external_wp_richText_namespaceObject.__unstableIsEmptyLine)(_value)) {
splitValue({
value: _value,
onReplace,
onSplit,
onSplitMiddle,
multilineTag
});
} else {
onChange((0,external_wp_richText_namespaceObject.__unstableInsertLineSeparator)(_value));
}
} else {
const {
text,
start,
end
} = _value;
const canSplitAtEnd = onSplitAtEnd && start === end && end === text.length;
if (event.shiftKey || !canSplit && !canSplitAtEnd) {
if (!disableLineBreaks) {
onChange((0,external_wp_richText_namespaceObject.insert)(_value, '\n'));
}
} else if (!canSplit && canSplitAtEnd) {
onSplitAtEnd();
} else if (canSplit) {
splitValue({
value: _value,
onReplace,
onSplit,
onSplitMiddle,
multilineTag
});
}
}
}
element.addEventListener('keydown', onKeyDown);
return () => {
element.removeEventListener('keydown', onKeyDown);
};
}, []);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/rich-text/use-format-types.js
/**
* WordPress dependencies
*/
function formatTypesSelector(select) {
return select(external_wp_richText_namespaceObject.store).getFormatTypes();
}
/**
* Set of all interactive content tags.
*
* @see https://html.spec.whatwg.org/multipage/dom.html#interactive-content
*/
const interactiveContentTags = new Set(['a', 'audio', 'button', 'details', 'embed', 'iframe', 'input', 'label', 'select', 'textarea', 'video']);
function prefixSelectKeys(selected, prefix) {
if (typeof selected !== 'object') return {
[prefix]: selected
};
return Object.fromEntries(Object.entries(selected).map(_ref => {
let [key, value] = _ref;
return [`${prefix}.${key}`, value];
}));
}
function getPrefixedSelectKeys(selected, prefix) {
if (selected[prefix]) return selected[prefix];
return Object.keys(selected).filter(key => key.startsWith(prefix + '.')).reduce((accumulator, key) => {
accumulator[key.slice(prefix.length + 1)] = selected[key];
return accumulator;
}, {});
}
/**
* This hook provides RichText with the `formatTypes` and its derived props from
* experimental format type settings.
*
* @param {Object} $0 Options
* @param {string} $0.clientId Block client ID.
* @param {string} $0.identifier Block attribute.
* @param {boolean} $0.withoutInteractiveFormatting Whether to clean the interactive formattings or not.
* @param {Array} $0.allowedFormats Allowed formats
*/
function useFormatTypes(_ref2) {
let {
clientId,
identifier,
withoutInteractiveFormatting,
allowedFormats
} = _ref2;
const allFormatTypes = (0,external_wp_data_namespaceObject.useSelect)(formatTypesSelector, []);
const formatTypes = (0,external_wp_element_namespaceObject.useMemo)(() => {
return allFormatTypes.filter(_ref3 => {
let {
name,
tagName
} = _ref3;
if (allowedFormats && !allowedFormats.includes(name)) {
return false;
}
if (withoutInteractiveFormatting && interactiveContentTags.has(tagName)) {
return false;
}
return true;
});
}, [allFormatTypes, allowedFormats, interactiveContentTags]);
const keyedSelected = (0,external_wp_data_namespaceObject.useSelect)(select => formatTypes.reduce((accumulator, type) => {
if (!type.__experimentalGetPropsForEditableTreePreparation) {
return accumulator;
}
return { ...accumulator,
...prefixSelectKeys(type.__experimentalGetPropsForEditableTreePreparation(select, {
richTextIdentifier: identifier,
blockClientId: clientId
}), type.name)
};
}, {}), [formatTypes, clientId, identifier]);
const dispatch = (0,external_wp_data_namespaceObject.useDispatch)();
const prepareHandlers = [];
const valueHandlers = [];
const changeHandlers = [];
const dependencies = [];
for (const key in keyedSelected) {
dependencies.push(keyedSelected[key]);
}
formatTypes.forEach(type => {
if (type.__experimentalCreatePrepareEditableTree) {
const handler = type.__experimentalCreatePrepareEditableTree(getPrefixedSelectKeys(keyedSelected, type.name), {
richTextIdentifier: identifier,
blockClientId: clientId
});
if (type.__experimentalCreateOnChangeEditableValue) {
valueHandlers.push(handler);
} else {
prepareHandlers.push(handler);
}
}
if (type.__experimentalCreateOnChangeEditableValue) {
let dispatchers = {};
if (type.__experimentalGetPropsForEditableTreeChangeHandler) {
dispatchers = type.__experimentalGetPropsForEditableTreeChangeHandler(dispatch, {
richTextIdentifier: identifier,
blockClientId: clientId
});
}
const selected = getPrefixedSelectKeys(keyedSelected, type.name);
changeHandlers.push(type.__experimentalCreateOnChangeEditableValue({ ...(typeof selected === 'object' ? selected : {}),
...dispatchers
}, {
richTextIdentifier: identifier,
blockClientId: clientId
}));
}
});
return {
formatTypes,
prepareHandlers,
valueHandlers,
changeHandlers,
dependencies
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/rich-text/use-remove-browser-shortcuts.js
/**
* WordPress dependencies
*/
/**
* Hook to prevent default behaviors for key combinations otherwise handled
* internally by RichText.
*
* @return {import('react').RefObject} The component to be rendered.
*/
function useRemoveBrowserShortcuts() {
return (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
function onKeydown(event) {
if (external_wp_keycodes_namespaceObject.isKeyboardEvent.primary(event, 'z') || external_wp_keycodes_namespaceObject.isKeyboardEvent.primary(event, 'y') || external_wp_keycodes_namespaceObject.isKeyboardEvent.primaryShift(event, 'z')) {
event.preventDefault();
}
}
node.addEventListener('keydown', onKeydown);
return () => {
node.addEventListener('keydown', onKeydown);
};
}, []);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/rich-text/use-shortcuts.js
/**
* WordPress dependencies
*/
function useShortcuts(keyboardShortcuts) {
return (0,external_wp_compose_namespaceObject.useRefEffect)(element => {
function onKeyDown(event) {
for (const keyboardShortcut of keyboardShortcuts.current) {
keyboardShortcut(event);
}
}
element.addEventListener('keydown', onKeyDown);
return () => {
element.removeEventListener('keydown', onKeyDown);
};
}, []);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/rich-text/use-input-events.js
/**
* WordPress dependencies
*/
function useInputEvents(inputEvents) {
return (0,external_wp_compose_namespaceObject.useRefEffect)(element => {
function onInput(event) {
for (const keyboardShortcut of inputEvents.current) {
keyboardShortcut(event);
}
}
element.addEventListener('input', onInput);
return () => {
element.removeEventListener('input', onInput);
};
}, []);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/rich-text/use-insert-replacement-text.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* When the browser is about to auto correct, add an undo level so the user can
* revert the change.
*/
function useInsertReplacementText() {
const {
__unstableMarkLastChangeAsPersistent
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
return (0,external_wp_compose_namespaceObject.useRefEffect)(element => {
function onInput(event) {
if (event.inputType === 'insertReplacementText') {
__unstableMarkLastChangeAsPersistent();
}
}
element.addEventListener('beforeinput', onInput);
return () => {
element.removeEventListener('beforeinput', onInput);
};
}, []);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/rich-text/use-firefox-compat.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useFirefoxCompat() {
const {
isMultiSelecting
} = (0,external_wp_data_namespaceObject.useSelect)(store);
return (0,external_wp_compose_namespaceObject.useRefEffect)(element => {
function onFocus() {
if (!isMultiSelecting()) {
return;
} // This is a little hack to work around focus issues with nested
// editable elements in Firefox. For some reason the editable child
// element sometimes regains focus, while it should not be focusable
// and focus should remain on the editable parent element.
// To do: try to find the cause of the shifting focus.
const parentEditable = element.parentElement.closest('[contenteditable="true"]');
if (parentEditable) {
parentEditable.focus();
}
}
element.addEventListener('focus', onFocus);
return () => {
element.removeEventListener('focus', onFocus);
};
}, []);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/rich-text/format-edit.js
/**
* WordPress dependencies
*/
function FormatEdit(_ref) {
let {
formatTypes,
onChange,
onFocus,
value,
forwardedRef
} = _ref;
return formatTypes.map(settings => {
const {
name,
edit: Edit
} = settings;
if (!Edit) {
return null;
}
const activeFormat = (0,external_wp_richText_namespaceObject.getActiveFormat)(value, name);
let isActive = activeFormat !== undefined;
const activeObject = (0,external_wp_richText_namespaceObject.getActiveObject)(value);
const isObjectActive = activeObject !== undefined && activeObject.type === name; // Edge case: un-collapsed link formats.
// If there is a missing link format at either end of the selection
// then we shouldn't show the Edit UI because the selection has exceeded
// the bounds of the link format.
// Also if the format objects don't match then we're dealing with two separate
// links so we should not allow the link to be modified over the top.
if (name === 'core/link' && !(0,external_wp_richText_namespaceObject.isCollapsed)(value)) {
var _formats$value$start, _formats;
const formats = value.formats;
const linkFormatAtStart = (_formats$value$start = formats[value.start]) === null || _formats$value$start === void 0 ? void 0 : _formats$value$start.find(_ref2 => {
let {
type
} = _ref2;
return type === 'core/link';
});
const linkFormatAtEnd = (_formats = formats[value.end - 1]) === null || _formats === void 0 ? void 0 : _formats.find(_ref3 => {
let {
type
} = _ref3;
return type === 'core/link';
});
if (!linkFormatAtStart || !linkFormatAtEnd || linkFormatAtStart !== linkFormatAtEnd) {
isActive = false;
}
}
return (0,external_wp_element_namespaceObject.createElement)(Edit, {
key: name,
isActive: isActive,
activeAttributes: isActive ? activeFormat.attributes || {} : {},
isObjectActive: isObjectActive,
activeObjectAttributes: isObjectActive ? activeObject.attributes || {} : {},
value: value,
onChange: onChange,
onFocus: onFocus,
contentRef: forwardedRef
});
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/rich-text/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const keyboardShortcutContext = (0,external_wp_element_namespaceObject.createContext)();
const inputEventContext = (0,external_wp_element_namespaceObject.createContext)();
/**
* Removes props used for the native version of RichText so that they are not
* passed to the DOM element and log warnings.
*
* @param {Object} props Props to filter.
*
* @return {Object} Filtered props.
*/
function removeNativeProps(props) {
const {
__unstableMobileNoFocusOnMount,
deleteEnter,
placeholderTextColor,
textAlign,
selectionColor,
tagsToEliminate,
rootTagsToEliminate,
disableEditingMenu,
fontSize,
fontFamily,
fontWeight,
fontStyle,
minWidth,
maxWidth,
setRef,
disableSuggestions,
disableAutocorrection,
...restProps
} = props;
return restProps;
}
function RichTextWrapper(_ref, forwardedRef) {
let {
children,
tagName = 'div',
value: originalValue = '',
onChange: originalOnChange,
isSelected: originalIsSelected,
multiline,
inlineToolbar,
wrapperClassName,
autocompleters,
onReplace,
placeholder,
allowedFormats,
withoutInteractiveFormatting,
onRemove,
onMerge,
onSplit,
__unstableOnSplitAtEnd: onSplitAtEnd,
__unstableOnSplitMiddle: onSplitMiddle,
identifier,
preserveWhiteSpace,
__unstablePastePlainText: pastePlainText,
__unstableEmbedURLOnPaste,
__unstableDisableFormats: disableFormats,
disableLineBreaks,
unstableOnFocus,
__unstableAllowPrefixTransformations,
...props
} = _ref;
if (multiline) {
external_wp_deprecated_default()('wp.blockEditor.RichText multiline prop', {
since: '6.1',
version: '6.3',
alternative: 'nested blocks (InnerBlocks)',
link: 'https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/nested-blocks-inner-blocks/'
});
}
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(RichTextWrapper);
identifier = identifier || instanceId;
props = removeNativeProps(props);
const anchorRef = (0,external_wp_element_namespaceObject.useRef)();
const {
clientId
} = useBlockEditContext();
const selector = select => {
const {
getSelectionStart,
getSelectionEnd
} = select(store);
const selectionStart = getSelectionStart();
const selectionEnd = getSelectionEnd();
let isSelected;
if (originalIsSelected === undefined) {
isSelected = selectionStart.clientId === clientId && selectionEnd.clientId === clientId && selectionStart.attributeKey === identifier;
} else if (originalIsSelected) {
isSelected = selectionStart.clientId === clientId;
}
return {
selectionStart: isSelected ? selectionStart.offset : undefined,
selectionEnd: isSelected ? selectionEnd.offset : undefined,
isSelected
};
}; // This selector must run on every render so the right selection state is
// retreived from the store on merge.
// To do: fix this somehow.
const {
selectionStart,
selectionEnd,
isSelected
} = (0,external_wp_data_namespaceObject.useSelect)(selector);
const {
getSelectionStart,
getSelectionEnd,
getBlockRootClientId
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const {
selectionChange
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const multilineTag = getMultilineTag(multiline);
const adjustedAllowedFormats = getAllowedFormats({
allowedFormats,
disableFormats
});
const hasFormats = !adjustedAllowedFormats || adjustedAllowedFormats.length > 0;
let adjustedValue = originalValue;
let adjustedOnChange = originalOnChange; // Handle deprecated format.
if (Array.isArray(originalValue)) {
external_wp_deprecated_default()('wp.blockEditor.RichText value prop as children type', {
since: '6.1',
version: '6.3',
alternative: 'value prop as string',
link: 'https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/introducing-attributes-and-editable-fields/'
});
adjustedValue = external_wp_blocks_namespaceObject.children.toHTML(originalValue);
adjustedOnChange = newValue => originalOnChange(external_wp_blocks_namespaceObject.children.fromDOM((0,external_wp_richText_namespaceObject.__unstableCreateElement)(document, newValue).childNodes));
}
const onSelectionChange = (0,external_wp_element_namespaceObject.useCallback)((start, end) => {
const selection = {};
const unset = start === undefined && end === undefined;
if (typeof start === 'number' || unset) {
// If we are only setting the start (or the end below), which
// means a partial selection, and we're not updating a selection
// with the same client ID, abort. This means the selected block
// is a parent block.
if (end === undefined && getBlockRootClientId(clientId) !== getBlockRootClientId(getSelectionEnd().clientId)) {
return;
}
selection.start = {
clientId,
attributeKey: identifier,
offset: start
};
}
if (typeof end === 'number' || unset) {
if (start === undefined && getBlockRootClientId(clientId) !== getBlockRootClientId(getSelectionStart().clientId)) {
return;
}
selection.end = {
clientId,
attributeKey: identifier,
offset: end
};
}
selectionChange(selection);
}, [clientId, identifier]);
const {
formatTypes,
prepareHandlers,
valueHandlers,
changeHandlers,
dependencies
} = useFormatTypes({
clientId,
identifier,
withoutInteractiveFormatting,
allowedFormats: adjustedAllowedFormats
});
function addEditorOnlyFormats(value) {
return valueHandlers.reduce((accumulator, fn) => fn(accumulator, value.text), value.formats);
}
function removeEditorOnlyFormats(value) {
formatTypes.forEach(formatType => {
// Remove formats created by prepareEditableTree, because they are editor only.
if (formatType.__experimentalCreatePrepareEditableTree) {
value = (0,external_wp_richText_namespaceObject.removeFormat)(value, formatType.name, 0, value.text.length);
}
});
return value.formats;
}
function addInvisibleFormats(value) {
return prepareHandlers.reduce((accumulator, fn) => fn(accumulator, value.text), value.formats);
}
const {
value,
getValue,
onChange,
ref: richTextRef
} = (0,external_wp_richText_namespaceObject.__unstableUseRichText)({
value: adjustedValue,
onChange(html, _ref2) {
let {
__unstableFormats,
__unstableText
} = _ref2;
adjustedOnChange(html);
Object.values(changeHandlers).forEach(changeHandler => {
changeHandler(__unstableFormats, __unstableText);
});
},
selectionStart,
selectionEnd,
onSelectionChange,
placeholder,
__unstableIsSelected: isSelected,
__unstableMultilineTag: multilineTag,
__unstableDisableFormats: disableFormats,
preserveWhiteSpace,
__unstableDependencies: [...dependencies, tagName],
__unstableAfterParse: addEditorOnlyFormats,
__unstableBeforeSerialize: removeEditorOnlyFormats,
__unstableAddInvisibleFormats: addInvisibleFormats
});
const autocompleteProps = useBlockEditorAutocompleteProps({
onReplace,
completers: autocompleters,
record: value,
onChange
});
useMarkPersistent({
html: adjustedValue,
value
});
const keyboardShortcuts = (0,external_wp_element_namespaceObject.useRef)(new Set());
const inputEvents = (0,external_wp_element_namespaceObject.useRef)(new Set());
function onKeyDown(event) {
const {
keyCode
} = event;
if (event.defaultPrevented) {
return;
}
if (keyCode === external_wp_keycodes_namespaceObject.DELETE || keyCode === external_wp_keycodes_namespaceObject.BACKSPACE) {
const {
start,
end,
text
} = value;
const isReverse = keyCode === external_wp_keycodes_namespaceObject.BACKSPACE;
const hasActiveFormats = value.activeFormats && !!value.activeFormats.length; // Only process delete if the key press occurs at an uncollapsed edge.
if (!(0,external_wp_richText_namespaceObject.isCollapsed)(value) || hasActiveFormats || isReverse && start !== 0 || !isReverse && end !== text.length) {
return;
}
if (onMerge) {
onMerge(!isReverse);
} // Only handle remove on Backspace. This serves dual-purpose of being
// an intentional user interaction distinguishing between Backspace and
// Delete to remove the empty field, but also to avoid merge & remove
// causing destruction of two fields (merge, then removed merged).
if (onRemove && (0,external_wp_richText_namespaceObject.isEmpty)(value) && isReverse) {
onRemove(!isReverse);
}
event.preventDefault();
}
}
function onFocus() {
var _anchorRef$current;
(_anchorRef$current = anchorRef.current) === null || _anchorRef$current === void 0 ? void 0 : _anchorRef$current.focus();
}
const TagName = tagName;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, isSelected && (0,external_wp_element_namespaceObject.createElement)(keyboardShortcutContext.Provider, {
value: keyboardShortcuts
}, (0,external_wp_element_namespaceObject.createElement)(inputEventContext.Provider, {
value: inputEvents
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Popover.__unstableSlotNameProvider, {
value: "__unstable-block-tools-after"
}, children && children({
value,
onChange,
onFocus
}), (0,external_wp_element_namespaceObject.createElement)(FormatEdit, {
value: value,
onChange: onChange,
onFocus: onFocus,
formatTypes: formatTypes,
forwardedRef: anchorRef
})))), isSelected && hasFormats && (0,external_wp_element_namespaceObject.createElement)(format_toolbar_container, {
inline: inlineToolbar,
editableContentElement: anchorRef.current,
value: value
}), (0,external_wp_element_namespaceObject.createElement)(TagName // Overridable props.
, _extends({
role: "textbox",
"aria-multiline": !disableLineBreaks,
"aria-label": placeholder
}, props, autocompleteProps, {
ref: (0,external_wp_compose_namespaceObject.useMergeRefs)([forwardedRef, autocompleteProps.ref, props.ref, richTextRef, useBeforeInputRules({
value,
onChange
}), useInputRules({
getValue,
onChange,
__unstableAllowPrefixTransformations,
formatTypes,
onReplace,
selectionChange
}), useInsertReplacementText(), useRemoveBrowserShortcuts(), useShortcuts(keyboardShortcuts), useInputEvents(inputEvents), useUndoAutomaticChange(), usePasteHandler({
isSelected,
disableFormats,
onChange,
value,
formatTypes,
tagName,
onReplace,
onSplit,
onSplitMiddle,
__unstableEmbedURLOnPaste,
multilineTag,
preserveWhiteSpace,
pastePlainText
}), useEnter({
removeEditorOnlyFormats,
value,
onReplace,
onSplit,
onSplitMiddle,
multilineTag,
onChange,
disableLineBreaks,
onSplitAtEnd
}), useFirefoxCompat(), anchorRef]),
contentEditable: true,
suppressContentEditableWarning: true,
className: classnames_default()('block-editor-rich-text__editable', props.className, 'rich-text'),
onFocus: unstableOnFocus,
onKeyDown: onKeyDown
})));
}
const ForwardedRichTextContainer = (0,external_wp_element_namespaceObject.forwardRef)(RichTextWrapper);
ForwardedRichTextContainer.Content = _ref3 => {
let {
value,
tagName: Tag,
multiline,
...props
} = _ref3;
// Handle deprecated `children` and `node` sources.
if (Array.isArray(value)) {
external_wp_deprecated_default()('wp.blockEditor.RichText value prop as children type', {
since: '6.1',
version: '6.3',
alternative: 'value prop as string',
link: 'https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/introducing-attributes-and-editable-fields/'
});
value = external_wp_blocks_namespaceObject.children.toHTML(value);
}
const MultilineTag = getMultilineTag(multiline);
if (!value && MultilineTag) {
value = `<${MultilineTag}></${MultilineTag}>`;
}
const content = (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.RawHTML, null, value);
if (Tag) {
const {
format,
...restProps
} = props;
return (0,external_wp_element_namespaceObject.createElement)(Tag, restProps, content);
}
return content;
};
ForwardedRichTextContainer.isEmpty = value => {
return !value || value.length === 0;
};
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/rich-text/README.md
*/
/* harmony default export */ var rich_text = (ForwardedRichTextContainer);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/editable-text/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const EditableText = (0,external_wp_element_namespaceObject.forwardRef)((props, ref) => {
return (0,external_wp_element_namespaceObject.createElement)(rich_text, _extends({
ref: ref
}, props, {
__unstableDisableFormats: true,
preserveWhiteSpace: true
}));
});
EditableText.Content = _ref => {
let {
value = '',
tagName: Tag = 'div',
...props
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(Tag, props, value);
};
/**
* Renders an editable text input in which text formatting is not allowed.
*/
/* harmony default export */ var editable_text = (EditableText);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/plain-text/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/plain-text/README.md
*/
const PlainText = (0,external_wp_element_namespaceObject.forwardRef)((_ref, ref) => {
let {
__experimentalVersion,
...props
} = _ref;
if (__experimentalVersion === 2) {
return (0,external_wp_element_namespaceObject.createElement)(editable_text, _extends({
ref: ref
}, props));
}
const {
className,
onChange,
...remainingProps
} = props;
return (0,external_wp_element_namespaceObject.createElement)(lib/* default */.Z, _extends({
ref: ref,
className: classnames_default()('block-editor-plain-text', className),
onChange: event => onChange(event.target.value)
}, remainingProps));
});
/* harmony default export */ var plain_text = (PlainText);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/responsive-block-control/label.js
/**
* WordPress dependencies
*/
function ResponsiveBlockControlLabel(_ref) {
let {
property,
viewport,
desc
} = _ref;
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(ResponsiveBlockControlLabel);
const accessibleLabel = desc || (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: 1: property name. 2: viewport name. */
(0,external_wp_i18n_namespaceObject._x)('Controls the %1$s property for %2$s viewports.', 'Text labelling a interface as controlling a given layout property (eg: margin) for a given screen size.'), property, viewport.label);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("span", {
"aria-describedby": `rbc-desc-${instanceId}`
}, viewport.label), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.VisuallyHidden, {
as: "span",
id: `rbc-desc-${instanceId}`
}, accessibleLabel));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/responsive-block-control/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ResponsiveBlockControl(props) {
const {
title,
property,
toggleLabel,
onIsResponsiveChange,
renderDefaultControl,
renderResponsiveControls,
isResponsive = false,
defaultLabel = {
id: 'all',
/* translators: 'Label. Used to signify a layout property (eg: margin, padding) will apply uniformly to all screensizes.' */
label: (0,external_wp_i18n_namespaceObject.__)('All')
},
viewports = [{
id: 'small',
label: (0,external_wp_i18n_namespaceObject.__)('Small screens')
}, {
id: 'medium',
label: (0,external_wp_i18n_namespaceObject.__)('Medium screens')
}, {
id: 'large',
label: (0,external_wp_i18n_namespaceObject.__)('Large screens')
}]
} = props;
if (!title || !property || !renderDefaultControl) {
return null;
}
const toggleControlLabel = toggleLabel || (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: 'Toggle control label. Should the property be the same across all screen sizes or unique per screen size.'. %s property value for the control (eg: margin, padding...etc) */
(0,external_wp_i18n_namespaceObject.__)('Use the same %s on all screensizes.'), property);
/* translators: 'Help text for the responsive mode toggle control.' */
const toggleHelpText = (0,external_wp_i18n_namespaceObject.__)('Toggle between using the same value for all screen sizes or using a unique value per screen size.');
const defaultControl = renderDefaultControl((0,external_wp_element_namespaceObject.createElement)(ResponsiveBlockControlLabel, {
property: property,
viewport: defaultLabel
}), defaultLabel);
const defaultResponsiveControls = () => {
return viewports.map(viewport => (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, {
key: viewport.id
}, renderDefaultControl((0,external_wp_element_namespaceObject.createElement)(ResponsiveBlockControlLabel, {
property: property,
viewport: viewport
}), viewport)));
};
return (0,external_wp_element_namespaceObject.createElement)("fieldset", {
className: "block-editor-responsive-block-control"
}, (0,external_wp_element_namespaceObject.createElement)("legend", {
className: "block-editor-responsive-block-control__title"
}, title), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-responsive-block-control__inner"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToggleControl, {
className: "block-editor-responsive-block-control__toggle",
label: toggleControlLabel,
checked: !isResponsive,
onChange: onIsResponsiveChange,
help: toggleHelpText
}), (0,external_wp_element_namespaceObject.createElement)("div", {
className: classnames_default()('block-editor-responsive-block-control__group', {
'is-responsive': isResponsive
})
}, !isResponsive && defaultControl, isResponsive && (renderResponsiveControls ? renderResponsiveControls(viewports) : defaultResponsiveControls()))));
}
/* harmony default export */ var responsive_block_control = (ResponsiveBlockControl);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/rich-text/shortcut.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function RichTextShortcut(_ref) {
let {
character,
type,
onUse
} = _ref;
const keyboardShortcuts = (0,external_wp_element_namespaceObject.useContext)(keyboardShortcutContext);
const onUseRef = (0,external_wp_element_namespaceObject.useRef)();
onUseRef.current = onUse;
(0,external_wp_element_namespaceObject.useEffect)(() => {
function callback(event) {
if (external_wp_keycodes_namespaceObject.isKeyboardEvent[type](event, character)) {
onUseRef.current();
event.preventDefault();
}
}
keyboardShortcuts.current.add(callback);
return () => {
keyboardShortcuts.current.delete(callback);
};
}, [character, type]);
return null;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/rich-text/toolbar-button.js
/**
* WordPress dependencies
*/
function RichTextToolbarButton(_ref) {
let {
name,
shortcutType,
shortcutCharacter,
...props
} = _ref;
let shortcut;
let fillName = 'RichText.ToolbarControls';
if (name) {
fillName += `.${name}`;
}
if (shortcutType && shortcutCharacter) {
shortcut = external_wp_keycodes_namespaceObject.displayShortcut[shortcutType](shortcutCharacter);
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Fill, {
name: fillName
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, _extends({}, props, {
shortcut: shortcut
})));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/rich-text/input-event.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function __unstableRichTextInputEvent(_ref) {
let {
inputType,
onInput
} = _ref;
const callbacks = (0,external_wp_element_namespaceObject.useContext)(inputEventContext);
const onInputRef = (0,external_wp_element_namespaceObject.useRef)();
onInputRef.current = onInput;
(0,external_wp_element_namespaceObject.useEffect)(() => {
function callback(event) {
if (event.inputType === inputType) {
onInputRef.current();
event.preventDefault();
}
}
callbacks.current.add(callback);
return () => {
callbacks.current.delete(callback);
};
}, [inputType]);
return null;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/tool-selector/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const selectIcon = (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
width: "24",
height: "24",
viewBox: "0 0 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Path, {
d: "M9.4 20.5L5.2 3.8l14.6 9-2 .3c-.2 0-.4.1-.7.1-.9.2-1.6.3-2.2.5-.8.3-1.4.5-1.8.8-.4.3-.8.8-1.3 1.5-.4.5-.8 1.2-1.2 2l-.3.6-.9 1.9zM7.6 7.1l2.4 9.3c.2-.4.5-.8.7-1.1.6-.8 1.1-1.4 1.6-1.8.5-.4 1.3-.8 2.2-1.1l1.2-.3-8.1-5z"
}));
function ToolSelector(props, ref) {
const mode = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).__unstableGetEditorMode(), []);
const {
__unstableSetEditorMode
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Dropdown, {
renderToggle: _ref => {
let {
isOpen,
onToggle
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, _extends({}, props, {
ref: ref,
icon: mode === 'navigation' ? selectIcon : library_edit,
"aria-expanded": isOpen,
"aria-haspopup": "true",
onClick: onToggle
/* translators: button label text should, if possible, be under 16 characters. */
,
label: (0,external_wp_i18n_namespaceObject.__)('Tools')
}));
},
popoverProps: {
placement: 'bottom-start'
},
renderContent: () => (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.NavigableMenu, {
role: "menu",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Tools')
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItemsChoice, {
value: mode === 'navigation' ? 'navigation' : 'edit',
onSelect: __unstableSetEditorMode,
choices: [{
value: 'edit',
label: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: library_edit
}), (0,external_wp_i18n_namespaceObject.__)('Edit'))
}, {
value: 'navigation',
label: (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, selectIcon, (0,external_wp_i18n_namespaceObject.__)('Select'))
}]
})), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-tool-selector__help"
}, (0,external_wp_i18n_namespaceObject.__)('Tools provide different interactions for selecting, navigating, and editing blocks. Toggle between select and edit by pressing Escape and Enter.')))
});
}
/* harmony default export */ var tool_selector = ((0,external_wp_element_namespaceObject.forwardRef)(ToolSelector));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/unit-control/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function UnitControl(_ref) {
let {
units: unitsProp,
...props
} = _ref;
const units = (0,external_wp_components_namespaceObject.__experimentalUseCustomUnits)({
availableUnits: useSetting('spacing.units') || ['%', 'px', 'em', 'rem', 'vw'],
units: unitsProp
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalUnitControl, _extends({
units: units
}, props));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/arrow-left.js
/**
* WordPress dependencies
*/
const arrowLeft = (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: "M20 11.2H6.8l3.7-3.7-1-1L3.9 12l5.6 5.5 1-1-3.7-3.7H20z"
}));
/* harmony default export */ var arrow_left = (arrowLeft);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/url-input/button.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
class URLInputButton extends external_wp_element_namespaceObject.Component {
constructor() {
super(...arguments);
this.toggle = this.toggle.bind(this);
this.submitLink = this.submitLink.bind(this);
this.state = {
expanded: false
};
}
toggle() {
this.setState({
expanded: !this.state.expanded
});
}
submitLink(event) {
event.preventDefault();
this.toggle();
}
render() {
const {
url,
onChange
} = this.props;
const {
expanded
} = this.state;
const buttonLabel = url ? (0,external_wp_i18n_namespaceObject.__)('Edit link') : (0,external_wp_i18n_namespaceObject.__)('Insert link');
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-url-input__button"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
icon: library_link,
label: buttonLabel,
onClick: this.toggle,
className: "components-toolbar__control",
isPressed: !!url
}), expanded && (0,external_wp_element_namespaceObject.createElement)("form", {
className: "block-editor-url-input__button-modal",
onSubmit: this.submitLink
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-url-input__button-modal-line"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "block-editor-url-input__back",
icon: arrow_left,
label: (0,external_wp_i18n_namespaceObject.__)('Close'),
onClick: this.toggle
}), (0,external_wp_element_namespaceObject.createElement)(url_input, {
__nextHasNoMarginBottom: true,
value: url || '',
onChange: onChange
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
icon: keyboard_return,
label: (0,external_wp_i18n_namespaceObject.__)('Submit'),
type: "submit"
}))));
}
}
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/url-input/README.md
*/
/* harmony default export */ var url_input_button = (URLInputButton);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/close.js
/**
* WordPress dependencies
*/
const close_close = (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: "M13 11.8l6.1-6.3-1-1-6.1 6.2-6.1-6.2-1 1 6.1 6.3-6.5 6.7 1 1 6.5-6.6 6.5 6.6 1-1z"
}));
/* harmony default export */ var library_close = (close_close);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/url-popover/image-url-input-ui.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const LINK_DESTINATION_NONE = 'none';
const LINK_DESTINATION_CUSTOM = 'custom';
const LINK_DESTINATION_MEDIA = 'media';
const LINK_DESTINATION_ATTACHMENT = 'attachment';
const NEW_TAB_REL = ['noreferrer', 'noopener'];
const icon = (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Path, {
d: "M0,0h24v24H0V0z",
fill: "none"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Path, {
d: "m19 5v14h-14v-14h14m0-2h-14c-1.1 0-2 0.9-2 2v14c0 1.1 0.9 2 2 2h14c1.1 0 2-0.9 2-2v-14c0-1.1-0.9-2-2-2z"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Path, {
d: "m14.14 11.86l-3 3.87-2.14-2.59-3 3.86h12l-3.86-5.14z"
}));
const ImageURLInputUI = _ref => {
let {
linkDestination,
onChangeUrl,
url,
mediaType = 'image',
mediaUrl,
mediaLink,
linkTarget,
linkClass,
rel
} = _ref;
const [isOpen, setIsOpen] = (0,external_wp_element_namespaceObject.useState)(false); // Use internal state instead of a ref to make sure that the component
// re-renders when the popover's anchor updates.
const [popoverAnchor, setPopoverAnchor] = (0,external_wp_element_namespaceObject.useState)(null);
const openLinkUI = (0,external_wp_element_namespaceObject.useCallback)(() => {
setIsOpen(true);
});
const [isEditingLink, setIsEditingLink] = (0,external_wp_element_namespaceObject.useState)(false);
const [urlInput, setUrlInput] = (0,external_wp_element_namespaceObject.useState)(null);
const autocompleteRef = (0,external_wp_element_namespaceObject.useRef)(null);
const startEditLink = (0,external_wp_element_namespaceObject.useCallback)(() => {
if (linkDestination === LINK_DESTINATION_MEDIA || linkDestination === LINK_DESTINATION_ATTACHMENT) {
setUrlInput('');
}
setIsEditingLink(true);
});
const stopEditLink = (0,external_wp_element_namespaceObject.useCallback)(() => {
setIsEditingLink(false);
});
const closeLinkUI = (0,external_wp_element_namespaceObject.useCallback)(() => {
setUrlInput(null);
stopEditLink();
setIsOpen(false);
});
const getUpdatedLinkTargetSettings = value => {
const newLinkTarget = value ? '_blank' : undefined;
let updatedRel;
if (newLinkTarget) {
const rels = (rel !== null && rel !== void 0 ? rel : '').split(' ');
NEW_TAB_REL.forEach(relVal => {
if (!rels.includes(relVal)) {
rels.push(relVal);
}
});
updatedRel = rels.join(' ');
} else {
const rels = (rel !== null && rel !== void 0 ? rel : '').split(' ').filter(relVal => NEW_TAB_REL.includes(relVal) === false);
updatedRel = rels.length ? rels.join(' ') : undefined;
}
return {
linkTarget: newLinkTarget,
rel: updatedRel
};
};
const onFocusOutside = (0,external_wp_element_namespaceObject.useCallback)(() => {
return event => {
// The autocomplete suggestions list renders in a separate popover (in a portal),
// so onFocusOutside fails to detect that a click on a suggestion occurred in the
// LinkContainer. Detect clicks on autocomplete suggestions using a ref here, and
// return to avoid the popover being closed.
const autocompleteElement = autocompleteRef.current;
if (autocompleteElement && autocompleteElement.contains(event.target)) {
return;
}
setIsOpen(false);
setUrlInput(null);
stopEditLink();
};
});
const onSubmitLinkChange = (0,external_wp_element_namespaceObject.useCallback)(() => {
return event => {
if (urlInput) {
var _getLinkDestinations$;
// It is possible the entered URL actually matches a named link destination.
// This check will ensure our link destination is correct.
const selectedDestination = ((_getLinkDestinations$ = getLinkDestinations().find(destination => destination.url === urlInput)) === null || _getLinkDestinations$ === void 0 ? void 0 : _getLinkDestinations$.linkDestination) || LINK_DESTINATION_CUSTOM;
onChangeUrl({
href: urlInput,
linkDestination: selectedDestination
});
}
stopEditLink();
setUrlInput(null);
event.preventDefault();
};
});
const onLinkRemove = (0,external_wp_element_namespaceObject.useCallback)(() => {
onChangeUrl({
linkDestination: LINK_DESTINATION_NONE,
href: ''
});
});
const getLinkDestinations = () => {
const linkDestinations = [{
linkDestination: LINK_DESTINATION_MEDIA,
title: (0,external_wp_i18n_namespaceObject.__)('Media File'),
url: mediaType === 'image' ? mediaUrl : undefined,
icon
}];
if (mediaType === 'image' && mediaLink) {
linkDestinations.push({
linkDestination: LINK_DESTINATION_ATTACHMENT,
title: (0,external_wp_i18n_namespaceObject.__)('Attachment Page'),
url: mediaType === 'image' ? mediaLink : undefined,
icon: (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Path, {
d: "M0 0h24v24H0V0z",
fill: "none"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Path, {
d: "M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zM6 20V4h7v5h5v11H6z"
}))
});
}
return linkDestinations;
};
const onSetHref = value => {
const linkDestinations = getLinkDestinations();
let linkDestinationInput;
if (!value) {
linkDestinationInput = LINK_DESTINATION_NONE;
} else {
linkDestinationInput = (linkDestinations.find(destination => {
return destination.url === value;
}) || {
linkDestination: LINK_DESTINATION_CUSTOM
}).linkDestination;
}
onChangeUrl({
linkDestination: linkDestinationInput,
href: value
});
};
const onSetNewTab = value => {
const updatedLinkTarget = getUpdatedLinkTargetSettings(value);
onChangeUrl(updatedLinkTarget);
};
const onSetLinkRel = value => {
onChangeUrl({
rel: value
});
};
const onSetLinkClass = value => {
onChangeUrl({
linkClass: value
});
};
const advancedOptions = (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalVStack, {
spacing: "3"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToggleControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Open in new tab'),
onChange: onSetNewTab,
checked: linkTarget === '_blank'
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.TextControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Link rel'),
value: rel !== null && rel !== void 0 ? rel : '',
onChange: onSetLinkRel
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.TextControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Link CSS Class'),
value: linkClass || '',
onChange: onSetLinkClass
}));
const linkEditorValue = urlInput !== null ? urlInput : url;
const urlLabel = (getLinkDestinations().find(destination => destination.linkDestination === linkDestination) || {}).title;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ToolbarButton, {
icon: library_link,
className: "components-toolbar__control",
label: url ? (0,external_wp_i18n_namespaceObject.__)('Edit link') : (0,external_wp_i18n_namespaceObject.__)('Insert link'),
"aria-expanded": isOpen,
onClick: openLinkUI,
ref: setPopoverAnchor
}), isOpen && (0,external_wp_element_namespaceObject.createElement)(url_popover, {
anchor: popoverAnchor,
onFocusOutside: onFocusOutside(),
onClose: closeLinkUI,
renderSettings: () => advancedOptions,
additionalControls: !linkEditorValue && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.NavigableMenu, null, getLinkDestinations().map(link => (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
key: link.linkDestination,
icon: link.icon,
onClick: () => {
setUrlInput(null);
onSetHref(link.url);
stopEditLink();
}
}, link.title)))
}, (!url || isEditingLink) && (0,external_wp_element_namespaceObject.createElement)(url_popover.LinkEditor, {
className: "block-editor-format-toolbar__link-container-content",
value: linkEditorValue,
onChangeInputValue: setUrlInput,
onSubmit: onSubmitLinkChange(),
autocompleteRef: autocompleteRef
}), url && !isEditingLink && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(url_popover.LinkViewer, {
className: "block-editor-format-toolbar__link-container-content",
url: url,
onEditLinkClick: startEditLink,
urlLabel: urlLabel
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
icon: library_close,
label: (0,external_wp_i18n_namespaceObject.__)('Remove link'),
onClick: onLinkRemove
}))));
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/preview-options/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
function PreviewOptions(_ref) {
let {
children,
viewLabel,
className,
isEnabled = true,
deviceType,
setDeviceType
} = _ref;
const isMobile = (0,external_wp_compose_namespaceObject.useViewportMatch)('small', '<');
if (isMobile) return null;
const popoverProps = {
className: classnames_default()(className, 'block-editor-post-preview__dropdown-content'),
position: 'bottom left'
};
const toggleProps = {
variant: 'tertiary',
className: 'block-editor-post-preview__button-toggle',
disabled: !isEnabled,
children: viewLabel
};
const menuProps = {
'aria-label': (0,external_wp_i18n_namespaceObject.__)('View options')
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.DropdownMenu, {
className: "block-editor-post-preview__dropdown",
popoverProps: popoverProps,
toggleProps: toggleProps,
menuProps: menuProps,
icon: null
}, () => (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
className: "block-editor-post-preview__button-resize",
onClick: () => setDeviceType('Desktop'),
icon: deviceType === 'Desktop' && library_check
}, (0,external_wp_i18n_namespaceObject.__)('Desktop')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
className: "block-editor-post-preview__button-resize",
onClick: () => setDeviceType('Tablet'),
icon: deviceType === 'Tablet' && library_check
}, (0,external_wp_i18n_namespaceObject.__)('Tablet')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
className: "block-editor-post-preview__button-resize",
onClick: () => setDeviceType('Mobile'),
icon: deviceType === 'Mobile' && library_check
}, (0,external_wp_i18n_namespaceObject.__)('Mobile'))), children));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/use-resize-canvas/index.js
/**
* WordPress dependencies
*/
/**
* Function to resize the editor window.
*
* @param {string} deviceType Used for determining the size of the container (e.g. Desktop, Tablet, Mobile)
*
* @return {Object} Inline styles to be added to resizable container.
*/
function useResizeCanvas(deviceType) {
const [actualWidth, updateActualWidth] = (0,external_wp_element_namespaceObject.useState)(window.innerWidth);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (deviceType === 'Desktop') {
return;
}
const resizeListener = () => updateActualWidth(window.innerWidth);
window.addEventListener('resize', resizeListener);
return () => {
window.removeEventListener('resize', resizeListener);
};
}, [deviceType]);
const getCanvasWidth = device => {
let deviceWidth;
switch (device) {
case 'Tablet':
deviceWidth = 780;
break;
case 'Mobile':
deviceWidth = 360;
break;
default:
return null;
}
return deviceWidth < actualWidth ? deviceWidth : actualWidth;
};
const marginValue = () => window.innerHeight < 800 ? 36 : 72;
const contentInlineStyles = device => {
const height = device === 'Mobile' ? '768px' : '1024px';
switch (device) {
case 'Tablet':
case 'Mobile':
return {
width: getCanvasWidth(device),
margin: marginValue() + 'px auto',
height,
borderRadius: '2px 2px 2px 2px',
border: '1px solid #ddd',
overflowY: 'auto'
};
default:
return null;
}
};
return contentInlineStyles(deviceType);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/skip-to-selected-block/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const SkipToSelectedBlock = _ref => {
let {
selectedBlockClientId
} = _ref;
const ref = useBlockRef(selectedBlockClientId);
const onClick = () => {
ref.current.focus();
};
return selectedBlockClientId ? (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "secondary",
className: "block-editor-skip-to-selected-block",
onClick: onClick
}, (0,external_wp_i18n_namespaceObject.__)('Skip to the selected block')) : null;
};
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/skip-to-selected-block/README.md
*/
/* harmony default export */ var skip_to_selected_block = ((0,external_wp_data_namespaceObject.withSelect)(select => {
return {
selectedBlockClientId: select(store).getBlockSelectionStart()
};
})(SkipToSelectedBlock));
;// CONCATENATED MODULE: external ["wp","wordcount"]
var external_wp_wordcount_namespaceObject = window["wp"]["wordcount"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/multi-selection-inspector/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function MultiSelectionInspector(_ref) {
let {
blocks
} = _ref;
const words = (0,external_wp_wordcount_namespaceObject.count)((0,external_wp_blocks_namespaceObject.serialize)(blocks), 'words');
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-multi-selection-inspector__card"
}, (0,external_wp_element_namespaceObject.createElement)(block_icon, {
icon: library_copy,
showColors: true
}), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-multi-selection-inspector__card-content"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-multi-selection-inspector__card-title"
}, (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %d: number of blocks */
(0,external_wp_i18n_namespaceObject._n)('%d block', '%d blocks', blocks.length), blocks.length)), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-multi-selection-inspector__card-description"
}, (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %d: number of words */
(0,external_wp_i18n_namespaceObject._n)('%d word', '%d words', words), words))));
}
/* harmony default export */ var multi_selection_inspector = ((0,external_wp_data_namespaceObject.withSelect)(select => {
const {
getMultiSelectedBlocks
} = select(store);
return {
blocks: getMultiSelectedBlocks()
};
})(MultiSelectionInspector));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/default-style-picker/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function DefaultStylePicker(_ref) {
let {
blockName
} = _ref;
const {
preferredStyle,
onUpdatePreferredStyleVariations,
styles
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _preferredStyleVariat, _preferredStyleVariat2;
const settings = select(store).getSettings();
const preferredStyleVariations = settings.__experimentalPreferredStyleVariations;
return {
preferredStyle: preferredStyleVariations === null || preferredStyleVariations === void 0 ? void 0 : (_preferredStyleVariat = preferredStyleVariations.value) === null || _preferredStyleVariat === void 0 ? void 0 : _preferredStyleVariat[blockName],
onUpdatePreferredStyleVariations: (_preferredStyleVariat2 = preferredStyleVariations === null || preferredStyleVariations === void 0 ? void 0 : preferredStyleVariations.onChange) !== null && _preferredStyleVariat2 !== void 0 ? _preferredStyleVariat2 : null,
styles: select(external_wp_blocks_namespaceObject.store).getBlockStyles(blockName)
};
}, [blockName]);
const selectOptions = (0,external_wp_element_namespaceObject.useMemo)(() => [{
label: (0,external_wp_i18n_namespaceObject.__)('Not set'),
value: ''
}, ...styles.map(_ref2 => {
let {
label,
name
} = _ref2;
return {
label,
value: name
};
})], [styles]);
const defaultStyleName = (0,external_wp_element_namespaceObject.useMemo)(() => {
var _getDefaultStyle;
return (_getDefaultStyle = getDefaultStyle(styles)) === null || _getDefaultStyle === void 0 ? void 0 : _getDefaultStyle.name;
}, [styles]);
const selectOnChange = (0,external_wp_element_namespaceObject.useCallback)(blockStyle => {
onUpdatePreferredStyleVariations(blockName, blockStyle);
}, [blockName, onUpdatePreferredStyleVariations]); // Until the functionality is migrated to global styles,
// only show the default style picker if a non-default style has already been selected.
if (!preferredStyle || preferredStyle === defaultStyleName) {
return null;
}
return onUpdatePreferredStyleVariations && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "default-style-picker__default-switcher"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SelectControl, {
__nextHasNoMarginBottom: true,
options: selectOptions,
value: preferredStyle || '',
label: (0,external_wp_i18n_namespaceObject.__)('Default Style'),
onChange: selectOnChange
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/cog.js
/**
* WordPress dependencies
*/
const cog = (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, {
fillRule: "evenodd",
d: "M10.289 4.836A1 1 0 0111.275 4h1.306a1 1 0 01.987.836l.244 1.466c.787.26 1.503.679 2.108 1.218l1.393-.522a1 1 0 011.216.437l.653 1.13a1 1 0 01-.23 1.273l-1.148.944a6.025 6.025 0 010 2.435l1.149.946a1 1 0 01.23 1.272l-.653 1.13a1 1 0 01-1.216.437l-1.394-.522c-.605.54-1.32.958-2.108 1.218l-.244 1.466a1 1 0 01-.987.836h-1.306a1 1 0 01-.986-.836l-.244-1.466a5.995 5.995 0 01-2.108-1.218l-1.394.522a1 1 0 01-1.217-.436l-.653-1.131a1 1 0 01.23-1.272l1.149-.946a6.026 6.026 0 010-2.435l-1.148-.944a1 1 0 01-.23-1.272l.653-1.131a1 1 0 011.217-.437l1.393.522a5.994 5.994 0 012.108-1.218l.244-1.466zM14.929 12a3 3 0 11-6 0 3 3 0 016 0z",
clipRule: "evenodd"
}));
/* harmony default export */ var library_cog = (cog);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/styles.js
/**
* WordPress dependencies
*/
const styles = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
viewBox: "0 0 24 24",
xmlns: "http://www.w3.org/2000/svg"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M12 4c-4.4 0-8 3.6-8 8v.1c0 4.1 3.2 7.5 7.2 7.9h.8c4.4 0 8-3.6 8-8s-3.6-8-8-8zm0 15V5c3.9 0 7 3.1 7 7s-3.1 7-7 7z"
}));
/* harmony default export */ var library_styles = (styles);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inspector-controls-tabs/utils.js
/**
* WordPress dependencies
*/
const TAB_SETTINGS = {
name: 'settings',
title: 'Settings',
value: 'settings',
icon: library_cog,
className: 'block-editor-block-inspector__tab-item'
};
const TAB_STYLES = {
name: 'styles',
title: 'Styles',
value: 'styles',
icon: library_styles,
className: 'block-editor-block-inspector__tab-item'
};
const TAB_LIST_VIEW = {
name: 'list',
title: 'List View',
value: 'list-view',
icon: list_view,
className: 'block-editor-block-inspector__tab-item'
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inspector-controls-tabs/advanced-controls-panel.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const AdvancedControls = () => {
const fills = (0,external_wp_components_namespaceObject.__experimentalUseSlotFills)(InspectorAdvancedControls.slotName);
const hasFills = Boolean(fills && fills.length);
if (!hasFills) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelBody, {
className: "block-editor-block-inspector__advanced",
title: (0,external_wp_i18n_namespaceObject.__)('Advanced'),
initialOpen: false
}, (0,external_wp_element_namespaceObject.createElement)(inspector_controls.Slot, {
group: "advanced"
}));
};
/* harmony default export */ var advanced_controls_panel = (AdvancedControls);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inspector-controls-tabs/position-controls-panel.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const PositionControls = () => {
const fills = (0,external_wp_components_namespaceObject.__experimentalUseSlotFills)(inspector_controls_groups.position.Slot.__unstableName);
const hasFills = Boolean(fills && fills.length);
if (!hasFills) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelBody, {
className: "block-editor-block-inspector__position",
title: (0,external_wp_i18n_namespaceObject.__)('Position'),
initialOpen: false
}, (0,external_wp_element_namespaceObject.createElement)(inspector_controls.Slot, {
group: "position"
}));
};
/* harmony default export */ var position_controls_panel = (PositionControls);
;// CONCATENATED MODULE: external ["wp","preferences"]
var external_wp_preferences_namespaceObject = window["wp"]["preferences"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inspector-controls-tabs/settings-tab-hint.js
/**
* WordPress dependencies
*/
const PREFERENCE_NAME = 'isInspectorControlsTabsHintVisible';
function InspectorControlsTabsHint() {
const isInspectorControlsTabsHintVisible = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _select$get;
return (_select$get = select(external_wp_preferences_namespaceObject.store).get('core', PREFERENCE_NAME)) !== null && _select$get !== void 0 ? _select$get : true;
}, []);
const ref = (0,external_wp_element_namespaceObject.useRef)();
const {
set: setPreference
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_preferences_namespaceObject.store);
if (!isInspectorControlsTabsHintVisible) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)("div", {
ref: ref,
className: "block-editor-inspector-controls-tabs__hint"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-inspector-controls-tabs__hint-content"
}, (0,external_wp_i18n_namespaceObject.__)("Looking for other block settings? They've moved to the styles tab.")), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "block-editor-inspector-controls-tabs__hint-dismiss",
icon: library_close,
iconSize: "16",
label: (0,external_wp_i18n_namespaceObject.__)('Dismiss hint'),
onClick: () => {
// Retain focus when dismissing the element.
const previousElement = external_wp_dom_namespaceObject.focus.tabbable.findPrevious(ref.current);
previousElement === null || previousElement === void 0 ? void 0 : previousElement.focus();
setPreference('core', PREFERENCE_NAME, false);
},
showTooltip: false
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inspector-controls-tabs/settings-tab.js
/**
* Internal dependencies
*/
const SettingsTab = _ref => {
let {
showAdvancedControls = false
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(inspector_controls.Slot, null), (0,external_wp_element_namespaceObject.createElement)(position_controls_panel, null), showAdvancedControls && (0,external_wp_element_namespaceObject.createElement)("div", null, (0,external_wp_element_namespaceObject.createElement)(advanced_controls_panel, null)), (0,external_wp_element_namespaceObject.createElement)(InspectorControlsTabsHint, null));
};
/* harmony default export */ var settings_tab = (SettingsTab);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inspector-controls-tabs/styles-tab.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const StylesTab = _ref => {
let {
blockName,
clientId,
hasBlockStyles
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, hasBlockStyles && (0,external_wp_element_namespaceObject.createElement)("div", null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelBody, {
title: (0,external_wp_i18n_namespaceObject.__)('Styles')
}, (0,external_wp_element_namespaceObject.createElement)(block_styles, {
clientId: clientId
}), (0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockName, 'defaultStylePicker', true) && (0,external_wp_element_namespaceObject.createElement)(DefaultStylePicker, {
blockName: blockName
}))), (0,external_wp_element_namespaceObject.createElement)(inspector_controls.Slot, {
group: "color",
label: (0,external_wp_i18n_namespaceObject.__)('Color'),
className: "color-block-support-panel__inner-wrapper"
}), (0,external_wp_element_namespaceObject.createElement)(inspector_controls.Slot, {
group: "typography",
label: (0,external_wp_i18n_namespaceObject.__)('Typography')
}), (0,external_wp_element_namespaceObject.createElement)(inspector_controls.Slot, {
group: "dimensions",
label: (0,external_wp_i18n_namespaceObject.__)('Dimensions')
}), (0,external_wp_element_namespaceObject.createElement)(inspector_controls.Slot, {
group: "border",
label: (0,external_wp_i18n_namespaceObject.__)('Border')
}), (0,external_wp_element_namespaceObject.createElement)(inspector_controls.Slot, {
group: "styles"
}));
};
/* harmony default export */ var styles_tab = (StylesTab);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inspector-controls-tabs/use-is-list-view-tab-disabled.js
// List view tab restricts the blocks that may render to it via the
// allowlist below.
const allowlist = ['core/navigation'];
const useIsListViewTabDisabled = blockName => {
return !allowlist.includes(blockName);
};
/* harmony default export */ var use_is_list_view_tab_disabled = (useIsListViewTabDisabled);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inspector-controls-tabs/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function InspectorControlsTabs(_ref) {
let {
blockName,
clientId,
hasBlockStyles,
tabs
} = _ref;
// The tabs panel will mount before fills are rendered to the list view
// slot. This means the list view tab isn't initially included in the
// available tabs so the panel defaults selection to the settings tab
// which at the time is the first tab. This check allows blocks known to
// include the list view tab to set it as the tab selected by default.
const initialTabName = !use_is_list_view_tab_disabled(blockName) ? TAB_LIST_VIEW.name : undefined;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.TabPanel, {
className: "block-editor-block-inspector__tabs",
tabs: tabs,
initialTabName: initialTabName,
key: clientId
}, tab => {
if (tab.name === TAB_SETTINGS.name) {
return (0,external_wp_element_namespaceObject.createElement)(settings_tab, {
showAdvancedControls: !!blockName
});
}
if (tab.name === TAB_STYLES.name) {
return (0,external_wp_element_namespaceObject.createElement)(styles_tab, {
blockName: blockName,
clientId: clientId,
hasBlockStyles: hasBlockStyles
});
}
if (tab.name === TAB_LIST_VIEW.name) {
return (0,external_wp_element_namespaceObject.createElement)(inspector_controls.Slot, {
group: "list"
});
}
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inspector-controls-tabs/use-inspector-controls-tabs.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const use_inspector_controls_tabs_EMPTY_ARRAY = [];
function getShowTabs(blockName) {
let tabSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
// Block specific setting takes precedence over generic default.
if (tabSettings[blockName] !== undefined) {
return tabSettings[blockName];
} // Use generic default if set over the Gutenberg experiment option.
if (tabSettings.default !== undefined) {
return tabSettings.default;
}
return true;
}
function useInspectorControlsTabs(blockName) {
const tabs = [];
const {
border: borderGroup,
color: colorGroup,
default: defaultGroup,
dimensions: dimensionsGroup,
list: listGroup,
position: positionGroup,
styles: stylesGroup,
typography: typographyGroup
} = inspector_controls_groups; // List View Tab: If there are any fills for the list group add that tab.
const listViewDisabled = use_is_list_view_tab_disabled(blockName);
const listFills = (0,external_wp_components_namespaceObject.__experimentalUseSlotFills)(listGroup.Slot.__unstableName);
const hasListFills = !listViewDisabled && !!listFills && listFills.length; // Styles Tab: Add this tab if there are any fills for block supports
// e.g. border, color, spacing, typography, etc.
const styleFills = [...((0,external_wp_components_namespaceObject.__experimentalUseSlotFills)(borderGroup.Slot.__unstableName) || []), ...((0,external_wp_components_namespaceObject.__experimentalUseSlotFills)(colorGroup.Slot.__unstableName) || []), ...((0,external_wp_components_namespaceObject.__experimentalUseSlotFills)(dimensionsGroup.Slot.__unstableName) || []), ...((0,external_wp_components_namespaceObject.__experimentalUseSlotFills)(stylesGroup.Slot.__unstableName) || []), ...((0,external_wp_components_namespaceObject.__experimentalUseSlotFills)(typographyGroup.Slot.__unstableName) || [])];
const hasStyleFills = styleFills.length; // Settings Tab: If we don't have multiple tabs to display
// (i.e. both list view and styles), check only the default and position
// InspectorControls slots. If we have multiple tabs, we'll need to check
// the advanced controls slot as well to ensure they are rendered.
const advancedFills = (0,external_wp_components_namespaceObject.__experimentalUseSlotFills)(InspectorAdvancedControls.slotName) || [];
const settingsFills = [...((0,external_wp_components_namespaceObject.__experimentalUseSlotFills)(defaultGroup.Slot.__unstableName) || []), ...((0,external_wp_components_namespaceObject.__experimentalUseSlotFills)(positionGroup.Slot.__unstableName) || []), ...(hasListFills && hasStyleFills > 1 ? advancedFills : [])]; // Add the tabs in the order that they will default to if available.
// List View > Settings > Styles.
if (hasListFills) {
tabs.push(TAB_LIST_VIEW);
}
if (settingsFills.length) {
tabs.push(TAB_SETTINGS);
}
if (hasStyleFills) {
tabs.push(TAB_STYLES);
}
const tabSettings = (0,external_wp_data_namespaceObject.useSelect)(select => {
return select(store).getSettings().blockInspectorTabs;
}, []);
const showTabs = getShowTabs(blockName, tabSettings);
return showTabs ? tabs : use_inspector_controls_tabs_EMPTY_ARRAY;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-inspector/useBlockInspectorAnimationSettings.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useBlockInspectorAnimationSettings(blockType, selectedBlockClientId) {
return (0,external_wp_data_namespaceObject.useSelect)(select => {
if (blockType) {
const globalBlockInspectorAnimationSettings = select(store).getSettings().blockInspectorAnimation; // Get the name of the block that will allow it's children to be animated.
const animationParent = globalBlockInspectorAnimationSettings === null || globalBlockInspectorAnimationSettings === void 0 ? void 0 : globalBlockInspectorAnimationSettings.animationParent; // Determine whether the animationParent block is a parent of the selected block.
const {
getSelectedBlockClientId,
getBlockParentsByBlockName
} = select(store);
const _selectedBlockClientId = getSelectedBlockClientId();
const animationParentBlockClientId = getBlockParentsByBlockName(_selectedBlockClientId, animationParent, true)[0]; // If the selected block is not a child of the animationParent block,
// and not an animationParent block itself, don't animate.
if (!animationParentBlockClientId && blockType.name !== animationParent) {
return null;
}
return globalBlockInspectorAnimationSettings === null || globalBlockInspectorAnimationSettings === void 0 ? void 0 : globalBlockInspectorAnimationSettings[blockType.name];
}
return null;
}, [selectedBlockClientId, blockType]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-inspector/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function useContentBlocks(blockTypes, block) {
const contentBlocksObjectAux = (0,external_wp_element_namespaceObject.useMemo)(() => {
return blockTypes.reduce((result, blockType) => {
if (blockType.name !== 'core/list-item' && Object.entries(blockType.attributes).some(_ref => {
let [, {
__experimentalRole
}] = _ref;
return __experimentalRole === 'content';
})) {
result[blockType.name] = true;
}
return result;
}, {});
}, [blockTypes]);
const isContentBlock = (0,external_wp_element_namespaceObject.useCallback)(blockName => {
return !!contentBlocksObjectAux[blockName];
}, [contentBlocksObjectAux]);
return (0,external_wp_element_namespaceObject.useMemo)(() => {
return getContentBlocks([block], isContentBlock);
}, [block, isContentBlock]);
}
function getContentBlocks(blocks, isContentBlock) {
const result = [];
for (const block of blocks) {
if (isContentBlock(block.name)) {
result.push(block);
}
result.push(...getContentBlocks(block.innerBlocks, isContentBlock));
}
return result;
}
function BlockNavigationButton(_ref2) {
let {
blockTypes,
block,
selectedBlock
} = _ref2;
const {
selectBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const blockType = blockTypes.find(_ref3 => {
let {
name
} = _ref3;
return name === block.name;
});
const isSelected = selectedBlock && selectedBlock.clientId === block.clientId;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
isPressed: isSelected,
onClick: () => selectBlock(block.clientId)
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalHStack, {
justify: "flex-start"
}, (0,external_wp_element_namespaceObject.createElement)(block_icon, {
icon: blockType.icon
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexItem, null, blockType.title)));
}
function BlockInspectorLockedBlocks(_ref4) {
let {
topLevelLockedBlock
} = _ref4;
const {
blockTypes,
block,
selectedBlock
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
return {
blockTypes: select(external_wp_blocks_namespaceObject.store).getBlockTypes(),
block: select(store).getBlock(topLevelLockedBlock),
selectedBlock: select(store).getSelectedBlock()
};
}, [topLevelLockedBlock]);
const blockInformation = useBlockDisplayInformation(topLevelLockedBlock);
const contentBlocks = useContentBlocks(blockTypes, block);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-inspector"
}, (0,external_wp_element_namespaceObject.createElement)(block_card, _extends({}, blockInformation, {
className: blockInformation.isSynced && 'is-synced'
})), (0,external_wp_element_namespaceObject.createElement)(block_variation_transforms, {
blockClientId: topLevelLockedBlock
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalVStack, {
spacing: 1,
padding: 4,
className: "block-editor-block-inspector__block-buttons-container"
}, (0,external_wp_element_namespaceObject.createElement)("h2", {
className: "block-editor-block-card__title"
}, (0,external_wp_i18n_namespaceObject.__)('Content')), contentBlocks.map(contentBlock => (0,external_wp_element_namespaceObject.createElement)(BlockNavigationButton, {
selectedBlock: selectedBlock,
key: contentBlock.clientId,
block: contentBlock,
blockTypes: blockTypes
}))));
}
const BlockInspector = _ref5 => {
let {
showNoBlockSelectedMessage = true
} = _ref5;
const {
count,
selectedBlockName,
selectedBlockClientId,
blockType,
topLevelLockedBlock
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getSelectedBlockClientId,
getSelectedBlockCount,
getBlockName,
__unstableGetContentLockingParent,
getTemplateLock
} = select(store);
const _selectedBlockClientId = getSelectedBlockClientId();
const _selectedBlockName = _selectedBlockClientId && getBlockName(_selectedBlockClientId);
const _blockType = _selectedBlockName && (0,external_wp_blocks_namespaceObject.getBlockType)(_selectedBlockName);
return {
count: getSelectedBlockCount(),
selectedBlockClientId: _selectedBlockClientId,
selectedBlockName: _selectedBlockName,
blockType: _blockType,
topLevelLockedBlock: __unstableGetContentLockingParent(_selectedBlockClientId) || (getTemplateLock(_selectedBlockClientId) === 'contentOnly' ? _selectedBlockClientId : undefined)
};
}, []);
const availableTabs = useInspectorControlsTabs(blockType === null || blockType === void 0 ? void 0 : blockType.name);
const showTabs = (availableTabs === null || availableTabs === void 0 ? void 0 : availableTabs.length) > 1; // The block inspector animation settings will be completely
// removed in the future to create an API which allows the block
// inspector to transition between what it
// displays based on the relationship between the selected block
// and its parent, and only enable it if the parent is controlling
// its children blocks.
const blockInspectorAnimationSettings = useBlockInspectorAnimationSettings(blockType, selectedBlockClientId);
if (count > 1) {
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-inspector"
}, (0,external_wp_element_namespaceObject.createElement)(multi_selection_inspector, null), showTabs ? (0,external_wp_element_namespaceObject.createElement)(InspectorControlsTabs, {
tabs: availableTabs
}) : (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(inspector_controls.Slot, null), (0,external_wp_element_namespaceObject.createElement)(inspector_controls.Slot, {
group: "color",
label: (0,external_wp_i18n_namespaceObject.__)('Color'),
className: "color-block-support-panel__inner-wrapper"
}), (0,external_wp_element_namespaceObject.createElement)(inspector_controls.Slot, {
group: "typography",
label: (0,external_wp_i18n_namespaceObject.__)('Typography')
}), (0,external_wp_element_namespaceObject.createElement)(inspector_controls.Slot, {
group: "dimensions",
label: (0,external_wp_i18n_namespaceObject.__)('Dimensions')
}), (0,external_wp_element_namespaceObject.createElement)(inspector_controls.Slot, {
group: "border",
label: (0,external_wp_i18n_namespaceObject.__)('Border')
}), (0,external_wp_element_namespaceObject.createElement)(inspector_controls.Slot, {
group: "styles"
})));
}
const isSelectedBlockUnregistered = selectedBlockName === (0,external_wp_blocks_namespaceObject.getUnregisteredTypeHandlerName)();
/*
* If the selected block is of an unregistered type, avoid showing it as an actual selection
* because we want the user to focus on the unregistered block warning, not block settings.
*/
if (!blockType || !selectedBlockClientId || isSelectedBlockUnregistered) {
if (showNoBlockSelectedMessage) {
return (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-block-inspector__no-blocks"
}, (0,external_wp_i18n_namespaceObject.__)('No block selected.'));
}
return null;
}
if (topLevelLockedBlock) {
return (0,external_wp_element_namespaceObject.createElement)(BlockInspectorLockedBlocks, {
topLevelLockedBlock: topLevelLockedBlock
});
}
return (0,external_wp_element_namespaceObject.createElement)(BlockInspectorSingleBlockWrapper, {
animate: blockInspectorAnimationSettings,
wrapper: children => (0,external_wp_element_namespaceObject.createElement)(AnimatedContainer, {
blockInspectorAnimationSettings: blockInspectorAnimationSettings,
selectedBlockClientId: selectedBlockClientId
}, children)
}, (0,external_wp_element_namespaceObject.createElement)(BlockInspectorSingleBlock, {
clientId: selectedBlockClientId,
blockName: blockType.name
}));
};
const BlockInspectorSingleBlockWrapper = _ref6 => {
let {
animate,
wrapper,
children
} = _ref6;
return animate ? wrapper(children) : children;
};
const AnimatedContainer = _ref7 => {
let {
blockInspectorAnimationSettings,
selectedBlockClientId,
children
} = _ref7;
const animationOrigin = blockInspectorAnimationSettings && blockInspectorAnimationSettings.enterDirection === 'leftToRight' ? -50 : 50;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__unstableMotion.div, {
animate: {
x: 0,
opacity: 1,
transition: {
ease: 'easeInOut',
duration: 0.14
}
},
initial: {
x: animationOrigin,
opacity: 0
},
key: selectedBlockClientId
}, children);
};
const BlockInspectorSingleBlock = _ref8 => {
let {
clientId,
blockName
} = _ref8;
const availableTabs = useInspectorControlsTabs(blockName);
const showTabs = (availableTabs === null || availableTabs === void 0 ? void 0 : availableTabs.length) > 1;
const hasBlockStyles = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlockStyles
} = select(external_wp_blocks_namespaceObject.store);
const blockStyles = getBlockStyles(blockName);
return blockStyles && blockStyles.length > 0;
}, [blockName]);
const blockInformation = useBlockDisplayInformation(clientId);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-inspector"
}, (0,external_wp_element_namespaceObject.createElement)(block_card, _extends({}, blockInformation, {
className: blockInformation.isSynced && 'is-synced'
})), (0,external_wp_element_namespaceObject.createElement)(block_variation_transforms, {
blockClientId: clientId
}), showTabs && (0,external_wp_element_namespaceObject.createElement)(InspectorControlsTabs, {
hasBlockStyles: hasBlockStyles,
clientId: clientId,
blockName: blockName,
tabs: availableTabs
}), !showTabs && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, hasBlockStyles && (0,external_wp_element_namespaceObject.createElement)("div", null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelBody, {
title: (0,external_wp_i18n_namespaceObject.__)('Styles')
}, (0,external_wp_element_namespaceObject.createElement)(block_styles, {
clientId: clientId
}), (0,external_wp_blocks_namespaceObject.hasBlockSupport)(blockName, 'defaultStylePicker', true) && (0,external_wp_element_namespaceObject.createElement)(DefaultStylePicker, {
blockName: blockName
}))), (0,external_wp_element_namespaceObject.createElement)(inspector_controls.Slot, null), (0,external_wp_element_namespaceObject.createElement)(inspector_controls.Slot, {
group: "color",
label: (0,external_wp_i18n_namespaceObject.__)('Color'),
className: "color-block-support-panel__inner-wrapper"
}), (0,external_wp_element_namespaceObject.createElement)(inspector_controls.Slot, {
group: "typography",
label: (0,external_wp_i18n_namespaceObject.__)('Typography')
}), (0,external_wp_element_namespaceObject.createElement)(inspector_controls.Slot, {
group: "dimensions",
label: (0,external_wp_i18n_namespaceObject.__)('Dimensions')
}), (0,external_wp_element_namespaceObject.createElement)(inspector_controls.Slot, {
group: "border",
label: (0,external_wp_i18n_namespaceObject.__)('Border')
}), (0,external_wp_element_namespaceObject.createElement)(inspector_controls.Slot, {
group: "styles"
}), (0,external_wp_element_namespaceObject.createElement)(position_controls_panel, null), (0,external_wp_element_namespaceObject.createElement)("div", null, (0,external_wp_element_namespaceObject.createElement)(advanced_controls_panel, null))), (0,external_wp_element_namespaceObject.createElement)(skip_to_selected_block, {
key: "back"
}));
};
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/block-inspector/README.md
*/
/* harmony default export */ var block_inspector = (BlockInspector);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-tools/zoom-out-mode-inserters.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ZoomOutModeInserters(_ref) {
let {
__unstableContentRef
} = _ref;
const [isReady, setIsReady] = (0,external_wp_element_namespaceObject.useState)(false);
const blockOrder = (0,external_wp_data_namespaceObject.useSelect)(select => {
return select(store).getBlockOrder();
}, []); // Defer the initial rendering to avoid the jumps due to the animation.
(0,external_wp_element_namespaceObject.useEffect)(() => {
const timeout = setTimeout(() => {
setIsReady(true);
}, 500);
return () => {
clearTimeout(timeout);
};
}, []);
if (!isReady) {
return null;
}
return blockOrder.map((clientId, index) => {
if (index === blockOrder.length - 1) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(inbetween, {
key: clientId,
previousClientId: clientId,
nextClientId: blockOrder[index + 1],
__unstableContentRef: __unstableContentRef
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-block-list__insertion-point-inserter is-with-inserter"
}, (0,external_wp_element_namespaceObject.createElement)(inserter, {
position: "bottom center",
clientId: blockOrder[index + 1],
__experimentalIsQuick: true
})));
});
}
/* harmony default export */ var zoom_out_mode_inserters = (ZoomOutModeInserters);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/block-tools/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function block_tools_selector(select) {
const {
__unstableGetEditorMode,
getSettings,
isTyping
} = select(store);
return {
isZoomOutMode: __unstableGetEditorMode() === 'zoom-out',
hasFixedToolbar: getSettings().hasFixedToolbar,
isTyping: isTyping()
};
}
/**
* Renders block tools (the block toolbar, select/navigation mode toolbar, the
* insertion point and a slot for the inline rich text toolbar). Must be wrapped
* around the block content and editor styles wrapper or iframe.
*
* @param {Object} $0 Props.
* @param {Object} $0.children The block content and style container.
* @param {Object} $0.__unstableContentRef Ref holding the content scroll container.
*/
function BlockTools(_ref) {
let {
children,
__unstableContentRef,
...props
} = _ref;
const isLargeViewport = (0,external_wp_compose_namespaceObject.useViewportMatch)('medium');
const {
hasFixedToolbar,
isZoomOutMode,
isTyping
} = (0,external_wp_data_namespaceObject.useSelect)(block_tools_selector, []);
const isMatch = (0,external_wp_keyboardShortcuts_namespaceObject.__unstableUseShortcutEventMatch)();
const {
getSelectedBlockClientIds,
getBlockRootClientId
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const {
duplicateBlocks,
removeBlocks,
insertAfterBlock,
insertBeforeBlock,
clearSelectedBlock,
moveBlocksUp,
moveBlocksDown
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
function onKeyDown(event) {
if (event.defaultPrevented) return;
if (isMatch('core/block-editor/move-up', event)) {
const clientIds = getSelectedBlockClientIds();
if (clientIds.length) {
event.preventDefault();
const rootClientId = getBlockRootClientId(clientIds[0]);
moveBlocksUp(clientIds, rootClientId);
}
} else if (isMatch('core/block-editor/move-down', event)) {
const clientIds = getSelectedBlockClientIds();
if (clientIds.length) {
event.preventDefault();
const rootClientId = getBlockRootClientId(clientIds[0]);
moveBlocksDown(clientIds, rootClientId);
}
} else if (isMatch('core/block-editor/duplicate', event)) {
const clientIds = getSelectedBlockClientIds();
if (clientIds.length) {
event.preventDefault();
duplicateBlocks(clientIds);
}
} else if (isMatch('core/block-editor/remove', event)) {
const clientIds = getSelectedBlockClientIds();
if (clientIds.length) {
event.preventDefault();
removeBlocks(clientIds);
}
} else if (isMatch('core/block-editor/insert-after', event)) {
const clientIds = getSelectedBlockClientIds();
if (clientIds.length) {
event.preventDefault();
insertAfterBlock(clientIds[clientIds.length - 1]);
}
} else if (isMatch('core/block-editor/insert-before', event)) {
const clientIds = getSelectedBlockClientIds();
if (clientIds.length) {
event.preventDefault();
insertBeforeBlock(clientIds[0]);
}
} else if (isMatch('core/block-editor/unselect', event)) {
const clientIds = getSelectedBlockClientIds();
if (clientIds.length) {
event.preventDefault();
clearSelectedBlock();
event.target.ownerDocument.defaultView.getSelection().removeAllRanges();
__unstableContentRef === null || __unstableContentRef === void 0 ? void 0 : __unstableContentRef.current.focus();
}
}
}
const blockToolbarRef = use_popover_scroll(__unstableContentRef);
const blockToolbarAfterRef = use_popover_scroll(__unstableContentRef);
return (// eslint-disable-next-line jsx-a11y/no-static-element-interactions
(0,external_wp_element_namespaceObject.createElement)("div", _extends({}, props, {
onKeyDown: onKeyDown
}), (0,external_wp_element_namespaceObject.createElement)(insertion_point_InsertionPointOpenRef.Provider, {
value: (0,external_wp_element_namespaceObject.useRef)(false)
}, !isTyping && (0,external_wp_element_namespaceObject.createElement)(InsertionPoint, {
__unstableContentRef: __unstableContentRef
}), !isZoomOutMode && (hasFixedToolbar || !isLargeViewport) && (0,external_wp_element_namespaceObject.createElement)(block_contextual_toolbar, {
isFixed: true
}), (0,external_wp_element_namespaceObject.createElement)(WrappedBlockPopover, {
__unstableContentRef: __unstableContentRef
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Popover.Slot, {
name: "block-toolbar",
ref: blockToolbarRef
}), children, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Popover.Slot, {
name: "__unstable-block-tools-after",
ref: blockToolbarAfterRef
}), isZoomOutMode && (0,external_wp_element_namespaceObject.createElement)(zoom_out_mode_inserters, {
__unstableContentRef: __unstableContentRef
})))
);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inserter/library.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const library_noop = () => {};
function InserterLibrary(_ref, ref) {
let {
rootClientId,
clientId,
isAppender,
showInserterHelpPanel,
showMostUsedBlocks = false,
__experimentalInsertionIndex,
__experimentalFilterValue,
onSelect = library_noop,
shouldFocusBlock = false
} = _ref;
const {
destinationRootClientId,
prioritizePatterns
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlockRootClientId,
getSettings
} = select(store);
const _rootClientId = rootClientId || getBlockRootClientId(clientId) || undefined;
return {
destinationRootClientId: _rootClientId,
prioritizePatterns: getSettings().__experimentalPreferPatternsOnRoot
};
}, [clientId, rootClientId]);
return (0,external_wp_element_namespaceObject.createElement)(menu, {
onSelect: onSelect,
rootClientId: destinationRootClientId,
clientId: clientId,
isAppender: isAppender,
showInserterHelpPanel: showInserterHelpPanel,
showMostUsedBlocks: showMostUsedBlocks,
__experimentalInsertionIndex: __experimentalInsertionIndex,
__experimentalFilterValue: __experimentalFilterValue,
shouldFocusBlock: shouldFocusBlock,
prioritizePatterns: prioritizePatterns,
ref: ref
});
}
/* harmony default export */ var library = ((0,external_wp_element_namespaceObject.forwardRef)(InserterLibrary));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/keyboard-shortcuts/index.js
/**
* WordPress dependencies
*/
function KeyboardShortcuts() {
return null;
}
function KeyboardShortcutsRegister() {
// Registering the shortcuts.
const {
registerShortcut
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_keyboardShortcuts_namespaceObject.store);
(0,external_wp_element_namespaceObject.useEffect)(() => {
registerShortcut({
name: 'core/block-editor/duplicate',
category: 'block',
description: (0,external_wp_i18n_namespaceObject.__)('Duplicate the selected block(s).'),
keyCombination: {
modifier: 'primaryShift',
character: 'd'
}
});
registerShortcut({
name: 'core/block-editor/remove',
category: 'block',
description: (0,external_wp_i18n_namespaceObject.__)('Remove the selected block(s).'),
keyCombination: {
modifier: 'access',
character: 'z'
}
});
registerShortcut({
name: 'core/block-editor/insert-before',
category: 'block',
description: (0,external_wp_i18n_namespaceObject.__)('Insert a new block before the selected block(s).'),
keyCombination: {
modifier: 'primaryAlt',
character: 't'
}
});
registerShortcut({
name: 'core/block-editor/insert-after',
category: 'block',
description: (0,external_wp_i18n_namespaceObject.__)('Insert a new block after the selected block(s).'),
keyCombination: {
modifier: 'primaryAlt',
character: 'y'
}
});
registerShortcut({
name: 'core/block-editor/delete-multi-selection',
category: 'block',
description: (0,external_wp_i18n_namespaceObject.__)('Delete selection.'),
keyCombination: {
character: 'del'
},
aliases: [{
character: 'backspace'
}]
});
registerShortcut({
name: 'core/block-editor/select-all',
category: 'selection',
description: (0,external_wp_i18n_namespaceObject.__)('Select all text when typing. Press again to select all blocks.'),
keyCombination: {
modifier: 'primary',
character: 'a'
}
});
registerShortcut({
name: 'core/block-editor/unselect',
category: 'selection',
description: (0,external_wp_i18n_namespaceObject.__)('Clear selection.'),
keyCombination: {
character: 'escape'
}
});
registerShortcut({
name: 'core/block-editor/focus-toolbar',
category: 'global',
description: (0,external_wp_i18n_namespaceObject.__)('Navigate to the nearest toolbar.'),
keyCombination: {
modifier: 'alt',
character: 'F10'
}
});
registerShortcut({
name: 'core/block-editor/move-up',
category: 'block',
description: (0,external_wp_i18n_namespaceObject.__)('Move the selected block(s) up.'),
keyCombination: {
modifier: 'secondary',
character: 't'
}
});
registerShortcut({
name: 'core/block-editor/move-down',
category: 'block',
description: (0,external_wp_i18n_namespaceObject.__)('Move the selected block(s) down.'),
keyCombination: {
modifier: 'secondary',
character: 'y'
}
});
}, [registerShortcut]);
return null;
}
KeyboardShortcuts.Register = KeyboardShortcutsRegister;
/* harmony default export */ var keyboard_shortcuts = (KeyboardShortcuts);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/selection-scroll-into-view/index.js
/**
* WordPress dependencies
*/
/**
* Scrolls the multi block selection end into view if not in view already. This
* is important to do after selection by keyboard.
*
* @deprecated
*/
function MultiSelectScrollIntoView() {
external_wp_deprecated_default()('wp.blockEditor.MultiSelectScrollIntoView', {
hint: 'This behaviour is now built-in.',
since: '5.8'
});
return null;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/observe-typing/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Set of key codes upon which typing is to be initiated on a keydown event.
*
* @type {Set<number>}
*/
const KEY_DOWN_ELIGIBLE_KEY_CODES = new Set([external_wp_keycodes_namespaceObject.UP, external_wp_keycodes_namespaceObject.RIGHT, external_wp_keycodes_namespaceObject.DOWN, external_wp_keycodes_namespaceObject.LEFT, external_wp_keycodes_namespaceObject.ENTER, external_wp_keycodes_namespaceObject.BACKSPACE]);
/**
* Returns true if a given keydown event can be inferred as intent to start
* typing, or false otherwise. A keydown is considered eligible if it is a
* text navigation without shift active.
*
* @param {KeyboardEvent} event Keydown event to test.
*
* @return {boolean} Whether event is eligible to start typing.
*/
function isKeyDownEligibleForStartTyping(event) {
const {
keyCode,
shiftKey
} = event;
return !shiftKey && KEY_DOWN_ELIGIBLE_KEY_CODES.has(keyCode);
}
/**
* Removes the `isTyping` flag when the mouse moves in the document of the given
* element.
*/
function useMouseMoveTypingReset() {
const isTyping = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).isTyping(), []);
const {
stopTyping
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
return (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
if (!isTyping) {
return;
}
const {
ownerDocument
} = node;
let lastClientX;
let lastClientY;
/**
* On mouse move, unset typing flag if user has moved cursor.
*
* @param {MouseEvent} event Mousemove event.
*/
function stopTypingOnMouseMove(event) {
const {
clientX,
clientY
} = event; // We need to check that the mouse really moved because Safari
// triggers mousemove events when shift or ctrl are pressed.
if (lastClientX && lastClientY && (lastClientX !== clientX || lastClientY !== clientY)) {
stopTyping();
}
lastClientX = clientX;
lastClientY = clientY;
}
ownerDocument.addEventListener('mousemove', stopTypingOnMouseMove);
return () => {
ownerDocument.removeEventListener('mousemove', stopTypingOnMouseMove);
};
}, [isTyping, stopTyping]);
}
/**
* Sets and removes the `isTyping` flag based on user actions:
*
* - Sets the flag if the user types within the given element.
* - Removes the flag when the user selects some text, focusses a non-text
* field, presses ESC or TAB, or moves the mouse in the document.
*/
function useTypingObserver() {
const {
isTyping,
hasInlineToolbar
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
isTyping: _isTyping,
getSettings
} = select(store);
return {
isTyping: _isTyping(),
hasInlineToolbar: getSettings().hasInlineToolbar
};
}, []);
const {
startTyping,
stopTyping
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const ref1 = useMouseMoveTypingReset();
const ref2 = (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
const {
ownerDocument
} = node;
const {
defaultView
} = ownerDocument;
const selection = defaultView.getSelection(); // Listeners to stop typing should only be added when typing.
// Listeners to start typing should only be added when not typing.
if (isTyping) {
let timerId;
/**
* Stops typing when focus transitions to a non-text field element.
*
* @param {FocusEvent} event Focus event.
*/
function stopTypingOnNonTextField(event) {
const {
target
} = event; // Since focus to a non-text field via arrow key will trigger
// before the keydown event, wait until after current stack
// before evaluating whether typing is to be stopped. Otherwise,
// typing will re-start.
timerId = defaultView.setTimeout(() => {
if (!(0,external_wp_dom_namespaceObject.isTextField)(target)) {
stopTyping();
}
});
}
/**
* Unsets typing flag if user presses Escape while typing flag is
* active.
*
* @param {KeyboardEvent} event Keypress or keydown event to
* interpret.
*/
function stopTypingOnEscapeKey(event) {
const {
keyCode
} = event;
if (keyCode === external_wp_keycodes_namespaceObject.ESCAPE || keyCode === external_wp_keycodes_namespaceObject.TAB) {
stopTyping();
}
}
/**
* On selection change, unset typing flag if user has made an
* uncollapsed (shift) selection.
*/
function stopTypingOnSelectionUncollapse() {
if (!selection.isCollapsed) {
stopTyping();
}
}
node.addEventListener('focus', stopTypingOnNonTextField);
node.addEventListener('keydown', stopTypingOnEscapeKey);
if (!hasInlineToolbar) {
ownerDocument.addEventListener('selectionchange', stopTypingOnSelectionUncollapse);
}
return () => {
defaultView.clearTimeout(timerId);
node.removeEventListener('focus', stopTypingOnNonTextField);
node.removeEventListener('keydown', stopTypingOnEscapeKey);
ownerDocument.removeEventListener('selectionchange', stopTypingOnSelectionUncollapse);
};
}
/**
* Handles a keypress or keydown event to infer intention to start
* typing.
*
* @param {KeyboardEvent} event Keypress or keydown event to interpret.
*/
function startTypingInTextField(event) {
const {
type,
target
} = event; // Abort early if already typing, or key press is incurred outside a
// text field (e.g. arrow-ing through toolbar buttons).
// Ignore typing if outside the current DOM container
if (!(0,external_wp_dom_namespaceObject.isTextField)(target) || !node.contains(target)) {
return;
} // Special-case keydown because certain keys do not emit a keypress
// event. Conversely avoid keydown as the canonical event since
// there are many keydown which are explicitly not targeted for
// typing.
if (type === 'keydown' && !isKeyDownEligibleForStartTyping(event)) {
return;
}
startTyping();
}
node.addEventListener('keypress', startTypingInTextField);
node.addEventListener('keydown', startTypingInTextField);
return () => {
node.removeEventListener('keypress', startTypingInTextField);
node.removeEventListener('keydown', startTypingInTextField);
};
}, [isTyping, hasInlineToolbar, startTyping, stopTyping]);
return (0,external_wp_compose_namespaceObject.useMergeRefs)([ref1, ref2]);
}
function ObserveTyping(_ref) {
let {
children
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("div", {
ref: useTypingObserver()
}, children);
}
/**
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/block-editor/src/components/observe-typing/README.md
*/
/* harmony default export */ var observe_typing = (ObserveTyping);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/typewriter/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const isIE = window.navigator.userAgent.indexOf('Trident') !== -1;
const arrowKeyCodes = new Set([external_wp_keycodes_namespaceObject.UP, external_wp_keycodes_namespaceObject.DOWN, external_wp_keycodes_namespaceObject.LEFT, external_wp_keycodes_namespaceObject.RIGHT]);
const initialTriggerPercentage = 0.75;
function useTypewriter() {
const hasSelectedBlock = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).hasSelectedBlock(), []);
return (0,external_wp_compose_namespaceObject.useRefEffect)(node => {
if (!hasSelectedBlock) {
return;
}
const {
ownerDocument
} = node;
const {
defaultView
} = ownerDocument;
let scrollResizeRafId;
let onKeyDownRafId;
let caretRect;
function onScrollResize() {
if (scrollResizeRafId) {
return;
}
scrollResizeRafId = defaultView.requestAnimationFrame(() => {
computeCaretRectangle();
scrollResizeRafId = null;
});
}
function onKeyDown(event) {
// Ensure the any remaining request is cancelled.
if (onKeyDownRafId) {
defaultView.cancelAnimationFrame(onKeyDownRafId);
} // Use an animation frame for a smooth result.
onKeyDownRafId = defaultView.requestAnimationFrame(() => {
maintainCaretPosition(event);
onKeyDownRafId = null;
});
}
/**
* Maintains the scroll position after a selection change caused by a
* keyboard event.
*
* @param {KeyboardEvent} event Keyboard event.
*/
function maintainCaretPosition(_ref) {
let {
keyCode
} = _ref;
if (!isSelectionEligibleForScroll()) {
return;
}
const currentCaretRect = (0,external_wp_dom_namespaceObject.computeCaretRect)(defaultView);
if (!currentCaretRect) {
return;
} // If for some reason there is no position set to be scrolled to, let
// this be the position to be scrolled to in the future.
if (!caretRect) {
caretRect = currentCaretRect;
return;
} // Even though enabling the typewriter effect for arrow keys results in
// a pleasant experience, it may not be the case for everyone, so, for
// now, let's disable it.
if (arrowKeyCodes.has(keyCode)) {
// Reset the caret position to maintain.
caretRect = currentCaretRect;
return;
}
const diff = currentCaretRect.top - caretRect.top;
if (diff === 0) {
return;
}
const scrollContainer = (0,external_wp_dom_namespaceObject.getScrollContainer)(node); // The page must be scrollable.
if (!scrollContainer) {
return;
}
const windowScroll = scrollContainer === ownerDocument.body || scrollContainer === ownerDocument.documentElement;
const scrollY = windowScroll ? defaultView.scrollY : scrollContainer.scrollTop;
const scrollContainerY = windowScroll ? 0 : scrollContainer.getBoundingClientRect().top;
const relativeScrollPosition = windowScroll ? caretRect.top / defaultView.innerHeight : (caretRect.top - scrollContainerY) / (defaultView.innerHeight - scrollContainerY); // If the scroll position is at the start, the active editable element
// is the last one, and the caret is positioned within the initial
// trigger percentage of the page, do not scroll the page.
// The typewriter effect should not kick in until an empty page has been
// filled with the initial trigger percentage or the user scrolls
// intentionally down.
if (scrollY === 0 && relativeScrollPosition < initialTriggerPercentage && isLastEditableNode()) {
// Reset the caret position to maintain.
caretRect = currentCaretRect;
return;
}
const scrollContainerHeight = windowScroll ? defaultView.innerHeight : scrollContainer.clientHeight; // Abort if the target scroll position would scroll the caret out of
// view.
if ( // The caret is under the lower fold.
caretRect.top + caretRect.height > scrollContainerY + scrollContainerHeight || // The caret is above the upper fold.
caretRect.top < scrollContainerY) {
// Reset the caret position to maintain.
caretRect = currentCaretRect;
return;
}
if (windowScroll) {
defaultView.scrollBy(0, diff);
} else {
scrollContainer.scrollTop += diff;
}
}
/**
* Adds a `selectionchange` listener to reset the scroll position to be
* maintained.
*/
function addSelectionChangeListener() {
ownerDocument.addEventListener('selectionchange', computeCaretRectOnSelectionChange);
}
/**
* Resets the scroll position to be maintained during a `selectionchange`
* event. Also removes the listener, so it acts as a one-time listener.
*/
function computeCaretRectOnSelectionChange() {
ownerDocument.removeEventListener('selectionchange', computeCaretRectOnSelectionChange);
computeCaretRectangle();
}
/**
* Resets the scroll position to be maintained.
*/
function computeCaretRectangle() {
if (isSelectionEligibleForScroll()) {
caretRect = (0,external_wp_dom_namespaceObject.computeCaretRect)(defaultView);
}
}
/**
* Checks if the current situation is elegible for scroll:
* - There should be one and only one block selected.
* - The component must contain the selection.
* - The active element must be contenteditable.
*/
function isSelectionEligibleForScroll() {
return node.contains(ownerDocument.activeElement) && ownerDocument.activeElement.isContentEditable;
}
function isLastEditableNode() {
const editableNodes = node.querySelectorAll('[contenteditable="true"]');
const lastEditableNode = editableNodes[editableNodes.length - 1];
return lastEditableNode === ownerDocument.activeElement;
} // When the user scrolls or resizes, the scroll position should be
// reset.
defaultView.addEventListener('scroll', onScrollResize, true);
defaultView.addEventListener('resize', onScrollResize, true);
node.addEventListener('keydown', onKeyDown);
node.addEventListener('keyup', maintainCaretPosition);
node.addEventListener('mousedown', addSelectionChangeListener);
node.addEventListener('touchstart', addSelectionChangeListener);
return () => {
defaultView.removeEventListener('scroll', onScrollResize, true);
defaultView.removeEventListener('resize', onScrollResize, true);
node.removeEventListener('keydown', onKeyDown);
node.removeEventListener('keyup', maintainCaretPosition);
node.removeEventListener('mousedown', addSelectionChangeListener);
node.removeEventListener('touchstart', addSelectionChangeListener);
ownerDocument.removeEventListener('selectionchange', computeCaretRectOnSelectionChange);
defaultView.cancelAnimationFrame(scrollResizeRafId);
defaultView.cancelAnimationFrame(onKeyDownRafId);
};
}, [hasSelectedBlock]);
}
function Typewriter(_ref2) {
let {
children
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)("div", {
ref: useTypewriter(),
className: "block-editor__typewriter"
}, children);
}
/**
* The exported component. The implementation of Typewriter faced technical
* challenges in Internet Explorer, and is simply skipped, rendering the given
* props children instead.
*
* @type {WPComponent}
*/
const TypewriterOrIEBypass = isIE ? props => props.children : Typewriter;
/**
* Ensures that the text selection keeps the same vertical distance from the
* viewport during keyboard events within this component. The vertical distance
* can vary. It is the last clicked or scrolled to position.
*/
/* harmony default export */ var typewriter = (TypewriterOrIEBypass);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/recursion-provider/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const RenderedRefsContext = (0,external_wp_element_namespaceObject.createContext)({});
/**
* Immutably adds an unique identifier to a set scoped for a given block type.
*
* @param {Object} renderedBlocks Rendered blocks grouped by block name
* @param {string} blockName Name of the block.
* @param {*} uniqueId Any value that acts as a unique identifier for a block instance.
*
* @return {Object} The list of rendered blocks grouped by block name.
*/
function addToBlockType(renderedBlocks, blockName, uniqueId) {
const result = { ...renderedBlocks,
[blockName]: renderedBlocks[blockName] ? new Set(renderedBlocks[blockName]) : new Set()
};
result[blockName].add(uniqueId);
return result;
}
/**
* A React context provider for use with the `useHasRecursion` hook to prevent recursive
* renders.
*
* Wrap block content with this provider and provide the same `uniqueId` prop as used
* with `useHasRecursion`.
*
* @param {Object} props
* @param {*} props.uniqueId Any value that acts as a unique identifier for a block instance.
* @param {string} props.blockName Optional block name.
* @param {JSX.Element} props.children React children.
*
* @return {JSX.Element} A React element.
*/
function RecursionProvider(_ref) {
let {
children,
uniqueId,
blockName = ''
} = _ref;
const previouslyRenderedBlocks = (0,external_wp_element_namespaceObject.useContext)(RenderedRefsContext);
const {
name
} = useBlockEditContext();
blockName = blockName || name;
const newRenderedBlocks = (0,external_wp_element_namespaceObject.useMemo)(() => addToBlockType(previouslyRenderedBlocks, blockName, uniqueId), [previouslyRenderedBlocks, blockName, uniqueId]);
return (0,external_wp_element_namespaceObject.createElement)(RenderedRefsContext.Provider, {
value: newRenderedBlocks
}, children);
}
/**
* A React hook for keeping track of blocks previously rendered up in the block
* tree. Blocks susceptible to recursion can use this hook in their `Edit`
* function to prevent said recursion.
*
* Use this with the `RecursionProvider` component, using the same `uniqueId` value
* for both the hook and the provider.
*
* @param {*} uniqueId Any value that acts as a unique identifier for a block instance.
* @param {string} blockName Optional block name.
*
* @return {boolean} A boolean describing whether the provided id has already been rendered.
*/
function useHasRecursion(uniqueId) {
var _previouslyRenderedBl;
let blockName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
const previouslyRenderedBlocks = (0,external_wp_element_namespaceObject.useContext)(RenderedRefsContext);
const {
name
} = useBlockEditContext();
blockName = blockName || name;
return Boolean((_previouslyRenderedBl = previouslyRenderedBlocks[blockName]) === null || _previouslyRenderedBl === void 0 ? void 0 : _previouslyRenderedBl.has(uniqueId));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/close-small.js
/**
* WordPress dependencies
*/
const closeSmall = (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: "M12 13.06l3.712 3.713 1.061-1.06L13.061 12l3.712-3.712-1.06-1.06L12 10.938 8.288 7.227l-1.061 1.06L10.939 12l-3.712 3.712 1.06 1.061L12 13.061z"
}));
/* harmony default export */ var close_small = (closeSmall);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/inspector-popover-header/index.js
/**
* WordPress dependencies
*/
function InspectorPopoverHeader(_ref) {
let {
title,
help,
actions = [],
onClose
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalVStack, {
className: "block-editor-inspector-popover-header",
spacing: 4
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalHStack, {
alignment: "center"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalHeading, {
className: "block-editor-inspector-popover-header__heading",
level: 2,
size: 13
}, title), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalSpacer, null), actions.map(_ref2 => {
let {
label,
icon,
onClick
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
key: label,
className: "block-editor-inspector-popover-header__action",
label: label,
icon: icon,
variant: !icon && 'tertiary',
onClick: onClick
}, !icon && label);
}), onClose && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: "block-editor-inspector-popover-header__action",
label: (0,external_wp_i18n_namespaceObject.__)('Close'),
icon: close_small,
onClick: onClose
})), help && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalText, null, help));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/publish-date-time-picker/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PublishDateTimePicker(_ref, ref) {
let {
onClose,
onChange,
...additionalProps
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("div", {
ref: ref,
className: "block-editor-publish-date-time-picker"
}, (0,external_wp_element_namespaceObject.createElement)(InspectorPopoverHeader, {
title: (0,external_wp_i18n_namespaceObject.__)('Publish'),
actions: [{
label: (0,external_wp_i18n_namespaceObject.__)('Now'),
onClick: () => onChange === null || onChange === void 0 ? void 0 : onChange(null)
}],
onClose: onClose
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.DateTimePicker, _extends({
startOfWeek: (0,external_wp_date_namespaceObject.getSettings)().l10n.startOfWeek,
__nextRemoveHelpButton: true,
__nextRemoveResetButton: true,
onChange: onChange
}, additionalProps)));
}
/* harmony default export */ var publish_date_time_picker = ((0,external_wp_element_namespaceObject.forwardRef)(PublishDateTimePicker));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/index.js
/*
* Block Creation Components
*/
/*
* Content Related Components
*/
/*
* State Related Components
*/
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/elements/index.js
const ELEMENT_CLASS_NAMES = {
button: 'wp-element-button',
caption: 'wp-element-caption'
};
const __experimentalGetElementClassName = element => {
return ELEMENT_CLASS_NAMES[element] ? ELEMENT_CLASS_NAMES[element] : '';
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/utils/block-variation-transforms.js
/** @typedef {import('@wordpress/blocks').WPBlockVariation} WPBlockVariation */
function matchesAttributes(blockAttributes, variation) {
return Object.entries(variation).every(_ref => {
let [key, value] = _ref;
if (typeof value === 'object' && typeof blockAttributes[key] === 'object') {
return matchesAttributes(blockAttributes[key], value);
}
return blockAttributes[key] === value;
});
}
/**
* Matches the provided block variations with a block's attributes. If no match
* or more than one matches are found it returns `undefined`. If a single match is
* found it returns it.
*
* This is a simple implementation for now as it takes into account only the attributes
* of a block variation and not `InnerBlocks`.
*
* @param {Object} blockAttributes - The block attributes to try to find a match.
* @param {WPBlockVariation[]} variations - A list of block variations to test for a match.
* @return {WPBlockVariation | undefined} - If a match is found returns it. If not or more than one matches are found returns `undefined`.
*/
const __experimentalGetMatchingVariation = (blockAttributes, variations) => {
if (!variations || !blockAttributes) return;
const matches = variations.filter(_ref2 => {
let {
attributes
} = _ref2;
if (!attributes || !Object.keys(attributes).length) return false;
return matchesAttributes(blockAttributes, attributes);
});
if (matches.length !== 1) return;
return matches[0];
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/utils/parse-css-unit-to-px.js
/**
* Converts string to object { value, unit }.
*
* @param {string} cssUnit
* @return {Object} parsedUnit
*/
function parseUnit(cssUnit) {
const match = cssUnit === null || cssUnit === void 0 ? void 0 : cssUnit.trim().match(/^(0?[-.]?\d*\.?\d+)(r?e[m|x]|v[h|w|min|max]+|p[x|t|c]|[c|m]m|%|in|ch|Q|lh)$/);
if (!isNaN(cssUnit) && !isNaN(parseFloat(cssUnit))) {
return {
value: parseFloat(cssUnit),
unit: 'px'
};
}
return match ? {
value: parseFloat(match[1]) || match[1],
unit: match[2]
} : {
value: cssUnit,
unit: undefined
};
}
/**
* Evaluate a math expression.
*
* @param {string} expression
* @return {number} evaluated expression.
*/
function calculate(expression) {
return Function(`'use strict'; return (${expression})`)();
}
/**
* Calculates the css function value for the supported css functions such as max, min, clamp and calc.
*
* @param {string} functionUnitValue string should be in a particular format (for example min(12px,12px) ) no nested loops.
* @param {Object} options
* @return {string} unit containing the unit in PX.
*/
function getFunctionUnitValue(functionUnitValue, options) {
const functionUnit = functionUnitValue.split(/[(),]/g).filter(Boolean);
const units = functionUnit.slice(1).map(unit => parseUnit(getPxFromCssUnit(unit, options)).value).filter(Boolean);
switch (functionUnit[0]) {
case 'min':
return Math.min(...units) + 'px';
case 'max':
return Math.max(...units) + 'px';
case 'clamp':
if (units.length !== 3) {
return null;
}
if (units[1] < units[0]) {
return units[0] + 'px';
}
if (units[1] > units[2]) {
return units[2] + 'px';
}
return units[1] + 'px';
case 'calc':
return units[0] + 'px';
}
}
/**
* Take a css function such as min, max, calc, clamp and returns parsedUnit
*
* How this works for the nested function is that it first replaces the inner function call.
* Then it tackles the outer onces.
* So for example: min( max(25px, 35px), 40px )
* in the first pass we would replace max(25px, 35px) with 35px.
* then we would try to evaluate min( 35px, 40px )
* and then finally return 35px.
*
* @param {string} cssUnit
* @return {Object} parsedUnit object.
*/
function parseUnitFunction(cssUnit) {
while (true) {
const currentCssUnit = cssUnit;
const regExp = /(max|min|calc|clamp)\(([^()]*)\)/g;
const matches = regExp.exec(cssUnit) || [];
if (matches[0]) {
const functionUnitValue = getFunctionUnitValue(matches[0]);
cssUnit = cssUnit.replace(matches[0], functionUnitValue);
} // If the unit hasn't been modified or we have a single value break free.
if (cssUnit === currentCssUnit || parseFloat(cssUnit)) {
break;
}
}
return parseUnit(cssUnit);
}
/**
* Return true if we think this is a math expression.
*
* @param {string} cssUnit the cssUnit value being evaluted.
* @return {boolean} Whether the cssUnit is a math expression.
*/
function isMathExpression(cssUnit) {
for (let i = 0; i < cssUnit.length; i++) {
if (['+', '-', '/', '*'].includes(cssUnit[i])) {
return true;
}
}
return false;
}
/**
* Evaluates the math expression and return a px value.
*
* @param {string} cssUnit the cssUnit value being evaluted.
* @return {string} return a converfted value to px.
*/
function evalMathExpression(cssUnit) {
let errorFound = false; // Convert every part of the expression to px values.
const cssUnitsBits = cssUnit.split(/(?!^-)[+*\/-](\s?-)?/g).filter(Boolean);
for (const unit of cssUnitsBits) {
// Standardize the unit to px and extract the value.
const parsedUnit = parseUnit(getPxFromCssUnit(unit));
if (!parseFloat(parsedUnit.value)) {
errorFound = true; // End early since we are dealing with a null value.
break;
}
cssUnit = cssUnit.replace(unit, parsedUnit.value);
}
return errorFound ? null : calculate(cssUnit).toFixed(0) + 'px';
}
/**
* Convert a parsedUnit object to px value.
*
* @param {Object} parsedUnit
* @param {Object} options
* @return {string} or {null} returns the converted with in a px value format.
*/
function convertParsedUnitToPx(parsedUnit, options) {
const PIXELS_PER_INCH = 96;
const ONE_PERCENT = 0.01;
const defaultProperties = {
fontSize: 16,
lineHeight: 16,
width: 375,
height: 812,
type: 'font'
};
const setOptions = Object.assign({}, defaultProperties, options);
const relativeUnits = {
em: setOptions.fontSize,
rem: setOptions.fontSize,
vh: setOptions.height * ONE_PERCENT,
vw: setOptions.width * ONE_PERCENT,
vmin: (setOptions.width < setOptions.height ? setOptions.width : setOptions.height) * ONE_PERCENT,
vmax: (setOptions.width > setOptions.height ? setOptions.width : setOptions.height) * ONE_PERCENT,
'%': (setOptions.type === 'font' ? setOptions.fontSize : setOptions.width) * ONE_PERCENT,
ch: 8,
// The advance measure (width) of the glyph "0" of the element's font. Approximate
ex: 7.15625,
// X-height of the element's font. Approximate.
lh: setOptions.lineHeight
};
const absoluteUnits = {
in: PIXELS_PER_INCH,
cm: PIXELS_PER_INCH / 2.54,
mm: PIXELS_PER_INCH / 25.4,
pt: PIXELS_PER_INCH / 72,
pc: PIXELS_PER_INCH / 6,
px: 1,
Q: PIXELS_PER_INCH / 2.54 / 40
};
if (relativeUnits[parsedUnit.unit]) {
return (relativeUnits[parsedUnit.unit] * parsedUnit.value).toFixed(0) + 'px';
}
if (absoluteUnits[parsedUnit.unit]) {
return (absoluteUnits[parsedUnit.unit] * parsedUnit.value).toFixed(0) + 'px';
}
return null;
}
/**
* Returns the px value of a cssUnit.
*
* @param {string} cssUnit
* @param {Object} options
* @return {string} returns the cssUnit value in a simple px format.
*/
function getPxFromCssUnit(cssUnit) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (Number.isFinite(cssUnit)) {
return cssUnit.toFixed(0) + 'px';
}
if (cssUnit === undefined) {
return null;
}
let parsedUnit = parseUnit(cssUnit);
if (!parsedUnit.unit) {
parsedUnit = parseUnitFunction(cssUnit);
}
if (isMathExpression(cssUnit) && !parsedUnit.unit) {
return evalMathExpression(cssUnit);
}
return convertParsedUnitToPx(parsedUnit, options);
} // Use simple cache.
const cache = {};
/**
* Returns the px value of a cssUnit. The memoized version of getPxFromCssUnit;
*
* @param {string} cssUnit
* @param {Object} options
* @return {string} returns the cssUnit value in a simple px format.
*/
function memoizedGetPxFromCssUnit(cssUnit) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const hash = cssUnit + hashOptions(options);
if (!cache[hash]) {
cache[hash] = getPxFromCssUnit(cssUnit, options);
}
return cache[hash];
}
function hashOptions(options) {
let hash = '';
if (options.hasOwnProperty('fontSize')) {
hash = ':' + options.width;
}
if (options.hasOwnProperty('lineHeight')) {
hash = ':' + options.lineHeight;
}
if (options.hasOwnProperty('width')) {
hash = ':' + options.width;
}
if (options.hasOwnProperty('height')) {
hash = ':' + options.height;
}
if (options.hasOwnProperty('type')) {
hash = ':' + options.type;
}
return hash;
}
/* harmony default export */ var parse_css_unit_to_px = (memoizedGetPxFromCssUnit);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/utils/index.js
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/global-styles/typography-utils.js
/**
* The fluid utilities must match the backend equivalent.
* See: gutenberg_get_typography_font_size_value() in lib/block-supports/typography.php
* ---------------------------------------------------------------
*/
/**
* Internal dependencies
*/
/**
* @typedef {Object} FluidPreset
* @property {string|undefined} max A maximum font size value.
* @property {?string|undefined} min A minimum font size value.
*/
/**
* @typedef {Object} Preset
* @property {?string|?number} size A default font size.
* @property {string} name A font size name, displayed in the UI.
* @property {string} slug A font size slug
* @property {boolean|FluidPreset|undefined} fluid A font size slug
*/
/**
* @typedef {Object} TypographySettings
* @property {?string|?number} size A default font size.
* @property {?string} minViewPortWidth Minimum viewport size from which type will have fluidity. Optional if size is specified.
* @property {?string} maxViewPortWidth Maximum size up to which type will have fluidity. Optional if size is specified.
* @property {?number} scaleFactor A scale factor to determine how fast a font scales within boundaries. Optional.
* @property {?number} minFontSizeFactor How much to scale defaultFontSize by to derive minimumFontSize. Optional.
* @property {?string} minFontSize The smallest a calculated font size may be. Optional.
*/
/**
* Returns a font-size value based on a given font-size preset.
* Takes into account fluid typography parameters and attempts to return a css formula depending on available, valid values.
*
* @param {Preset} preset
* @param {Object} typographySettings
* @param {boolean|TypographySettings} typographySettings.fluid Whether fluid typography is enabled, and, optionally, fluid font size options.
*
* @return {string|*} A font-size value or the value of preset.size.
*/
function getTypographyFontSizeValue(preset, typographySettings) {
var _preset$fluid, _preset$fluid2;
const {
size: defaultSize
} = preset;
/*
* Catches falsy values and 0/'0'.
* Fluid calculations cannot be performed on 0.
*/
if (!defaultSize || '0' === defaultSize) {
return defaultSize;
}
if (!(typographySettings !== null && typographySettings !== void 0 && typographySettings.fluid) || typeof (typographySettings === null || typographySettings === void 0 ? void 0 : typographySettings.fluid) === 'object' && Object.keys(typographySettings.fluid).length === 0) {
return defaultSize;
} // A font size has explicitly bypassed fluid calculations.
if (false === (preset === null || preset === void 0 ? void 0 : preset.fluid)) {
return defaultSize;
}
const fluidTypographySettings = typeof (typographySettings === null || typographySettings === void 0 ? void 0 : typographySettings.fluid) === 'object' ? typographySettings === null || typographySettings === void 0 ? void 0 : typographySettings.fluid : {};
const fluidFontSizeValue = getComputedFluidTypographyValue({
minimumFontSize: preset === null || preset === void 0 ? void 0 : (_preset$fluid = preset.fluid) === null || _preset$fluid === void 0 ? void 0 : _preset$fluid.min,
maximumFontSize: preset === null || preset === void 0 ? void 0 : (_preset$fluid2 = preset.fluid) === null || _preset$fluid2 === void 0 ? void 0 : _preset$fluid2.max,
fontSize: defaultSize,
minimumFontSizeLimit: fluidTypographySettings === null || fluidTypographySettings === void 0 ? void 0 : fluidTypographySettings.minFontSize
});
if (!!fluidFontSizeValue) {
return fluidFontSizeValue;
}
return defaultSize;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/global-styles/utils.js
/**
* External dependencies
*/
/**
* Internal dependencies
*/
/* Supporting data. */
const ROOT_BLOCK_NAME = 'root';
const ROOT_BLOCK_SELECTOR = 'body';
const ROOT_BLOCK_SUPPORTS = (/* unused pure expression or super */ null && (['background', 'backgroundColor', 'color', 'linkColor', 'buttonColor', 'fontFamily', 'fontSize', 'fontStyle', 'fontWeight', 'lineHeight', 'textDecoration', 'textTransform', 'padding']));
const PRESET_METADATA = [{
path: ['color', 'palette'],
valueKey: 'color',
cssVarInfix: 'color',
classes: [{
classSuffix: 'color',
propertyName: 'color'
}, {
classSuffix: 'background-color',
propertyName: 'background-color'
}, {
classSuffix: 'border-color',
propertyName: 'border-color'
}]
}, {
path: ['color', 'gradients'],
valueKey: 'gradient',
cssVarInfix: 'gradient',
classes: [{
classSuffix: 'gradient-background',
propertyName: 'background'
}]
}, {
path: ['color', 'duotone'],
cssVarInfix: 'duotone',
valueFunc: _ref => {
let {
slug
} = _ref;
return `url( '#wp-duotone-${slug}' )`;
},
classes: []
}, {
path: ['shadow', 'presets'],
valueKey: 'shadow',
cssVarInfix: 'shadow',
classes: []
}, {
path: ['typography', 'fontSizes'],
valueFunc: (preset, _ref2) => {
let {
typography: typographySettings
} = _ref2;
return getTypographyFontSizeValue(preset, typographySettings);
},
valueKey: 'size',
cssVarInfix: 'font-size',
classes: [{
classSuffix: 'font-size',
propertyName: 'font-size'
}]
}, {
path: ['typography', 'fontFamilies'],
valueKey: 'fontFamily',
cssVarInfix: 'font-family',
classes: [{
classSuffix: 'font-family',
propertyName: 'font-family'
}]
}, {
path: ['spacing', 'spacingSizes'],
valueKey: 'size',
cssVarInfix: 'spacing',
valueFunc: _ref3 => {
let {
size
} = _ref3;
return size;
},
classes: []
}];
const STYLE_PATH_TO_CSS_VAR_INFIX = {
'color.background': 'color',
'color.text': 'color',
'elements.link.color.text': 'color',
'elements.link.:hover.color.text': 'color',
'elements.link.typography.fontFamily': 'font-family',
'elements.link.typography.fontSize': 'font-size',
'elements.button.color.text': 'color',
'elements.button.color.background': 'color',
'elements.button.typography.fontFamily': 'font-family',
'elements.button.typography.fontSize': 'font-size',
'elements.heading.color': 'color',
'elements.heading.color.background': 'color',
'elements.heading.typography.fontFamily': 'font-family',
'elements.heading.gradient': 'gradient',
'elements.heading.color.gradient': 'gradient',
'elements.h1.color': 'color',
'elements.h1.color.background': 'color',
'elements.h1.typography.fontFamily': 'font-family',
'elements.h1.color.gradient': 'gradient',
'elements.h2.color': 'color',
'elements.h2.color.background': 'color',
'elements.h2.typography.fontFamily': 'font-family',
'elements.h2.color.gradient': 'gradient',
'elements.h3.color': 'color',
'elements.h3.color.background': 'color',
'elements.h3.typography.fontFamily': 'font-family',
'elements.h3.color.gradient': 'gradient',
'elements.h4.color': 'color',
'elements.h4.color.background': 'color',
'elements.h4.typography.fontFamily': 'font-family',
'elements.h4.color.gradient': 'gradient',
'elements.h5.color': 'color',
'elements.h5.color.background': 'color',
'elements.h5.typography.fontFamily': 'font-family',
'elements.h5.color.gradient': 'gradient',
'elements.h6.color': 'color',
'elements.h6.color.background': 'color',
'elements.h6.typography.fontFamily': 'font-family',
'elements.h6.color.gradient': 'gradient',
'color.gradient': 'gradient',
shadow: 'shadow',
'typography.fontSize': 'font-size',
'typography.fontFamily': 'font-family'
}; // A static list of block attributes that store global style preset slugs.
const STYLE_PATH_TO_PRESET_BLOCK_ATTRIBUTE = {
'color.background': 'backgroundColor',
'color.text': 'textColor',
'color.gradient': 'gradient',
'typography.fontSize': 'fontSize',
'typography.fontFamily': 'fontFamily'
};
function findInPresetsBy(features, blockName, presetPath, presetProperty, presetValueValue) {
// Block presets take priority above root level presets.
const orderedPresetsByOrigin = [(0,external_lodash_namespaceObject.get)(features, ['blocks', blockName, ...presetPath]), (0,external_lodash_namespaceObject.get)(features, presetPath)];
for (const presetByOrigin of orderedPresetsByOrigin) {
if (presetByOrigin) {
// Preset origins ordered by priority.
const origins = ['custom', 'theme', 'default'];
for (const origin of origins) {
const presets = presetByOrigin[origin];
if (presets) {
const presetObject = presets.find(preset => preset[presetProperty] === presetValueValue);
if (presetObject) {
if (presetProperty === 'slug') {
return presetObject;
} // If there is a highest priority preset with the same slug but different value the preset we found was overwritten and should be ignored.
const highestPresetObjectWithSameSlug = findInPresetsBy(features, blockName, presetPath, 'slug', presetObject.slug);
if (highestPresetObjectWithSameSlug[presetProperty] === presetObject[presetProperty]) {
return presetObject;
}
return undefined;
}
}
}
}
}
}
function getPresetVariableFromValue(features, blockName, variableStylePath, presetPropertyValue) {
if (!presetPropertyValue) {
return presetPropertyValue;
}
const cssVarInfix = STYLE_PATH_TO_CSS_VAR_INFIX[variableStylePath];
const metadata = PRESET_METADATA.find(data => data.cssVarInfix === cssVarInfix);
if (!metadata) {
// The property doesn't have preset data
// so the value should be returned as it is.
return presetPropertyValue;
}
const {
valueKey,
path
} = metadata;
const presetObject = findInPresetsBy(features, blockName, path, valueKey, presetPropertyValue);
if (!presetObject) {
// Value wasn't found in the presets,
// so it must be a custom value.
return presetPropertyValue;
}
return `var:preset|${cssVarInfix}|${presetObject.slug}`;
}
function getValueFromPresetVariable(features, blockName, variable, _ref4) {
let [presetType, slug] = _ref4;
const metadata = PRESET_METADATA.find(data => data.cssVarInfix === presetType);
if (!metadata) {
return variable;
}
const presetObject = findInPresetsBy(features.settings, blockName, metadata.path, 'slug', slug);
if (presetObject) {
const {
valueKey
} = metadata;
const result = presetObject[valueKey];
return getValueFromVariable(features, blockName, result);
}
return variable;
}
function getValueFromCustomVariable(features, blockName, variable, path) {
var _get;
const result = (_get = (0,external_lodash_namespaceObject.get)(features.settings, ['blocks', blockName, 'custom', ...path])) !== null && _get !== void 0 ? _get : (0,external_lodash_namespaceObject.get)(features.settings, ['custom', ...path]);
if (!result) {
return variable;
} // A variable may reference another variable so we need recursion until we find the value.
return getValueFromVariable(features, blockName, result);
}
/**
* Attempts to fetch the value of a theme.json CSS variable.
*
* @param {Object} features GlobalStylesContext config, e.g., user, base or merged. Represents the theme.json tree.
* @param {string} blockName The name of a block as represented in the styles property. E.g., 'root' for root-level, and 'core/${blockName}' for blocks.
* @param {string|*} variable An incoming style value. A CSS var value is expected, but it could be any value.
* @return {string|*|{ref}} The value of the CSS var, if found. If not found, the passed variable argument.
*/
function getValueFromVariable(features, blockName, variable) {
if (!variable || typeof variable !== 'string') {
var _variable, _variable2;
if ((_variable = variable) !== null && _variable !== void 0 && _variable.ref && typeof ((_variable2 = variable) === null || _variable2 === void 0 ? void 0 : _variable2.ref) === 'string') {
var _variable3;
const refPath = variable.ref.split('.');
variable = (0,external_lodash_namespaceObject.get)(features, refPath); // Presence of another ref indicates a reference to another dynamic value.
// Pointing to another dynamic value is not supported.
if (!variable || !!((_variable3 = variable) !== null && _variable3 !== void 0 && _variable3.ref)) {
return variable;
}
} else {
return variable;
}
}
const USER_VALUE_PREFIX = 'var:';
const THEME_VALUE_PREFIX = 'var(--wp--';
const THEME_VALUE_SUFFIX = ')';
let parsedVar;
if (variable.startsWith(USER_VALUE_PREFIX)) {
parsedVar = variable.slice(USER_VALUE_PREFIX.length).split('|');
} else if (variable.startsWith(THEME_VALUE_PREFIX) && variable.endsWith(THEME_VALUE_SUFFIX)) {
parsedVar = variable.slice(THEME_VALUE_PREFIX.length, -THEME_VALUE_SUFFIX.length).split('--');
} else {
// We don't know how to parse the value: either is raw of uses complex CSS such as `calc(1px * var(--wp--variable) )`
return variable;
}
const [type, ...path] = parsedVar;
if (type === 'preset') {
return getValueFromPresetVariable(features, blockName, variable, path);
}
if (type === 'custom') {
return getValueFromCustomVariable(features, blockName, variable, path);
}
return variable;
}
/**
* Function that scopes a selector with another one. This works a bit like
* SCSS nesting except the `&` operator isn't supported.
*
* @example
* ```js
* const scope = '.a, .b .c';
* const selector = '> .x, .y';
* const merged = scopeSelector( scope, selector );
* // merged is '.a > .x, .a .y, .b .c > .x, .b .c .y'
* ```
*
* @param {string} scope Selector to scope to.
* @param {string} selector Original selector.
*
* @return {string} Scoped selector.
*/
function utils_scopeSelector(scope, selector) {
const scopes = scope.split(',');
const selectors = selector.split(',');
const selectorsScoped = [];
scopes.forEach(outer => {
selectors.forEach(inner => {
selectorsScoped.push(`${outer.trim()} ${inner.trim()}`);
});
});
return selectorsScoped.join(', ');
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/global-styles/context.js
/**
* WordPress dependencies
*/
const DEFAULT_GLOBAL_STYLES_CONTEXT = {
user: {},
base: {},
merged: {},
setUserConfig: () => {}
};
const GlobalStylesContext = (0,external_wp_element_namespaceObject.createContext)(DEFAULT_GLOBAL_STYLES_CONTEXT);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/global-styles/hooks.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const EMPTY_CONFIG = {
settings: {},
styles: {}
};
const useGlobalStylesReset = () => {
const {
user: config,
setUserConfig
} = (0,external_wp_element_namespaceObject.useContext)(GlobalStylesContext);
const canReset = !!config && !es6_default()(config, EMPTY_CONFIG);
return [canReset, (0,external_wp_element_namespaceObject.useCallback)(() => setUserConfig(() => EMPTY_CONFIG), [setUserConfig])];
};
function useGlobalSetting(path, blockName) {
var _getSettingValueForCo;
let source = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'all';
const {
merged: mergedConfig,
base: baseConfig,
user: userConfig,
setUserConfig
} = (0,external_wp_element_namespaceObject.useContext)(GlobalStylesContext);
const fullPath = !blockName ? `settings.${path}` : `settings.blocks.${blockName}.${path}`;
const setSetting = newValue => {
setUserConfig(currentConfig => {
// Deep clone `currentConfig` to avoid mutating it later.
const newUserConfig = JSON.parse(JSON.stringify(currentConfig));
(0,external_lodash_namespaceObject.set)(newUserConfig, fullPath, newValue);
return newUserConfig;
});
};
const getSettingValueForContext = name => {
const currentPath = !name ? `settings.${path}` : `settings.blocks.${name}.${path}`;
let result;
switch (source) {
case 'all':
result = (0,external_lodash_namespaceObject.get)(mergedConfig, currentPath);
break;
case 'user':
result = (0,external_lodash_namespaceObject.get)(userConfig, currentPath);
break;
case 'base':
result = (0,external_lodash_namespaceObject.get)(baseConfig, currentPath);
break;
default:
throw 'Unsupported source';
}
return result;
}; // Unlike styles settings get inherited from top level settings.
const resultWithFallback = (_getSettingValueForCo = getSettingValueForContext(blockName)) !== null && _getSettingValueForCo !== void 0 ? _getSettingValueForCo : getSettingValueForContext();
return [resultWithFallback, setSetting];
}
function useGlobalStyle(path, blockName) {
var _get;
let source = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'all';
const {
merged: mergedConfig,
base: baseConfig,
user: userConfig,
setUserConfig
} = (0,external_wp_element_namespaceObject.useContext)(GlobalStylesContext);
const finalPath = !blockName ? `styles.${path}` : `styles.blocks.${blockName}.${path}`;
const setStyle = newValue => {
setUserConfig(currentConfig => {
// Deep clone `currentConfig` to avoid mutating it later.
const newUserConfig = JSON.parse(JSON.stringify(currentConfig));
(0,external_lodash_namespaceObject.set)(newUserConfig, finalPath, getPresetVariableFromValue(mergedConfig.settings, blockName, path, newValue));
return newUserConfig;
});
};
let result;
switch (source) {
case 'all':
result = getValueFromVariable(mergedConfig, blockName, // The stlyes.css path is allowed to be empty, so don't revert to base if undefined.
finalPath === 'styles.css' ? (0,external_lodash_namespaceObject.get)(userConfig, finalPath) : (_get = (0,external_lodash_namespaceObject.get)(userConfig, finalPath)) !== null && _get !== void 0 ? _get : (0,external_lodash_namespaceObject.get)(baseConfig, finalPath));
break;
case 'user':
result = getValueFromVariable(mergedConfig, blockName, (0,external_lodash_namespaceObject.get)(userConfig, finalPath));
break;
case 'base':
result = getValueFromVariable(baseConfig, blockName, (0,external_lodash_namespaceObject.get)(baseConfig, finalPath));
break;
default:
throw 'Unsupported source';
}
return [result, setStyle];
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/global-styles/use-global-styles-output.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
// List of block support features that can have their related styles
// generated under their own feature level selector rather than the block's.
const BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS = {
__experimentalBorder: 'border',
color: 'color',
spacing: 'spacing',
typography: 'typography'
};
function compileStyleValue(uncompiledValue) {
var _uncompiledValue$star;
const VARIABLE_REFERENCE_PREFIX = 'var:';
const VARIABLE_PATH_SEPARATOR_TOKEN_ATTRIBUTE = '|';
const VARIABLE_PATH_SEPARATOR_TOKEN_STYLE = '--';
if (uncompiledValue !== null && uncompiledValue !== void 0 && (_uncompiledValue$star = uncompiledValue.startsWith) !== null && _uncompiledValue$star !== void 0 && _uncompiledValue$star.call(uncompiledValue, VARIABLE_REFERENCE_PREFIX)) {
const variable = uncompiledValue.slice(VARIABLE_REFERENCE_PREFIX.length).split(VARIABLE_PATH_SEPARATOR_TOKEN_ATTRIBUTE).join(VARIABLE_PATH_SEPARATOR_TOKEN_STYLE);
return `var(--wp--${variable})`;
}
return uncompiledValue;
}
/**
* Transform given preset tree into a set of style declarations.
*
* @param {Object} blockPresets
* @param {Object} mergedSettings Merged theme.json settings.
*
* @return {Array<Object>} An array of style declarations.
*/
function getPresetsDeclarations() {
let blockPresets = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let mergedSettings = arguments.length > 1 ? arguments[1] : undefined;
return PRESET_METADATA.reduce((declarations, _ref) => {
let {
path,
valueKey,
valueFunc,
cssVarInfix
} = _ref;
const presetByOrigin = (0,external_lodash_namespaceObject.get)(blockPresets, path, []);
['default', 'theme', 'custom'].forEach(origin => {
if (presetByOrigin[origin]) {
presetByOrigin[origin].forEach(value => {
if (valueKey && !valueFunc) {
declarations.push(`--wp--preset--${cssVarInfix}--${(0,external_lodash_namespaceObject.kebabCase)(value.slug)}: ${value[valueKey]}`);
} else if (valueFunc && typeof valueFunc === 'function') {
declarations.push(`--wp--preset--${cssVarInfix}--${(0,external_lodash_namespaceObject.kebabCase)(value.slug)}: ${valueFunc(value, mergedSettings)}`);
}
});
}
});
return declarations;
}, []);
}
/**
* Transform given preset tree into a set of preset class declarations.
*
* @param {string} blockSelector
* @param {Object} blockPresets
* @return {string} CSS declarations for the preset classes.
*/
function getPresetsClasses(blockSelector) {
let blockPresets = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return PRESET_METADATA.reduce((declarations, _ref2) => {
let {
path,
cssVarInfix,
classes
} = _ref2;
if (!classes) {
return declarations;
}
const presetByOrigin = (0,external_lodash_namespaceObject.get)(blockPresets, path, []);
['default', 'theme', 'custom'].forEach(origin => {
if (presetByOrigin[origin]) {
presetByOrigin[origin].forEach(_ref3 => {
let {
slug
} = _ref3;
classes.forEach(_ref4 => {
let {
classSuffix,
propertyName
} = _ref4;
const classSelectorToUse = `.has-${(0,external_lodash_namespaceObject.kebabCase)(slug)}-${classSuffix}`;
const selectorToUse = blockSelector.split(',') // Selector can be "h1, h2, h3"
.map(selector => `${selector}${classSelectorToUse}`).join(',');
const value = `var(--wp--preset--${cssVarInfix}--${(0,external_lodash_namespaceObject.kebabCase)(slug)})`;
declarations += `${selectorToUse}{${propertyName}: ${value} !important;}`;
});
});
}
});
return declarations;
}, '');
}
function getPresetsSvgFilters() {
let blockPresets = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return PRESET_METADATA.filter( // Duotone are the only type of filters for now.
metadata => metadata.path.at(-1) === 'duotone').flatMap(metadata => {
const presetByOrigin = (0,external_lodash_namespaceObject.get)(blockPresets, metadata.path, {});
return ['default', 'theme'].filter(origin => presetByOrigin[origin]).flatMap(origin => presetByOrigin[origin].map(preset => (0,external_wp_element_namespaceObject.createElement)(PresetDuotoneFilter, {
preset: preset,
key: preset.slug
})));
});
}
function flattenTree() {
let input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let prefix = arguments.length > 1 ? arguments[1] : undefined;
let token = arguments.length > 2 ? arguments[2] : undefined;
let result = [];
Object.keys(input).forEach(key => {
const newKey = prefix + (0,external_lodash_namespaceObject.kebabCase)(key.replace('/', '-'));
const newLeaf = input[key];
if (newLeaf instanceof Object) {
const newPrefix = newKey + token;
result = [...result, ...flattenTree(newLeaf, newPrefix, token)];
} else {
result.push(`${newKey}: ${newLeaf}`);
}
});
return result;
}
/**
* Gets variation selector string from feature selector.
*
* @param {string} featureSelector The feature selector.
*
* @param {string} styleVariationSelector The style variation selector.
* @return {string} Combined selector string.
*
*/
function concatFeatureVariationSelectorString(featureSelector, styleVariationSelector) {
const featureSelectors = featureSelector.split(',');
const combinedSelectors = [];
featureSelectors.forEach(selector => {
combinedSelectors.push(`${styleVariationSelector.trim()}${selector.trim()}`);
});
return combinedSelectors.join(', ');
}
/**
* Transform given style tree into a set of style declarations.
*
* @param {Object} blockStyles Block styles.
*
* @param {string} selector The selector these declarations should attach to.
*
* @param {boolean} useRootPaddingAlign Whether to use CSS custom properties in root selector.
*
* @param {Object} tree A theme.json tree containing layout definitions.
*
* @return {Array} An array of style declarations.
*/
function getStylesDeclarations() {
let blockStyles = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let selector = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
let useRootPaddingAlign = arguments.length > 2 ? arguments[2] : undefined;
let tree = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
const isRoot = ROOT_BLOCK_SELECTOR === selector;
const output = Object.entries(external_wp_blocks_namespaceObject.__EXPERIMENTAL_STYLE_PROPERTY).reduce((declarations, _ref5) => {
let [key, {
value,
properties,
useEngine,
rootOnly
}] = _ref5;
if (rootOnly && !isRoot) {
return declarations;
}
const pathToValue = value;
if (pathToValue[0] === 'elements' || useEngine) {
return declarations;
}
const styleValue = (0,external_lodash_namespaceObject.get)(blockStyles, pathToValue); // Root-level padding styles don't currently support strings with CSS shorthand values.
// This may change: https://github.com/WordPress/gutenberg/issues/40132.
if (key === '--wp--style--root--padding' && (typeof styleValue === 'string' || !useRootPaddingAlign)) {
return declarations;
}
if (!!properties && typeof styleValue !== 'string') {
Object.entries(properties).forEach(entry => {
const [name, prop] = entry;
if (!(0,external_lodash_namespaceObject.get)(styleValue, [prop], false)) {
// Do not create a declaration
// for sub-properties that don't have any value.
return;
}
const cssProperty = name.startsWith('--') ? name : (0,external_lodash_namespaceObject.kebabCase)(name);
declarations.push(`${cssProperty}: ${compileStyleValue((0,external_lodash_namespaceObject.get)(styleValue, [prop]))}`);
});
} else if ((0,external_lodash_namespaceObject.get)(blockStyles, pathToValue, false)) {
const cssProperty = key.startsWith('--') ? key : (0,external_lodash_namespaceObject.kebabCase)(key);
declarations.push(`${cssProperty}: ${compileStyleValue((0,external_lodash_namespaceObject.get)(blockStyles, pathToValue))}`);
}
return declarations;
}, []); // The goal is to move everything to server side generated engine styles
// This is temporary as we absorb more and more styles into the engine.
const extraRules = (0,external_wp_styleEngine_namespaceObject.getCSSRules)(blockStyles);
extraRules.forEach(rule => {
var _ruleValue;
// Don't output padding properties if padding variables are set.
if (isRoot && useRootPaddingAlign && rule.key.startsWith('padding')) {
return;
}
const cssProperty = rule.key.startsWith('--') ? rule.key : (0,external_lodash_namespaceObject.kebabCase)(rule.key);
let ruleValue = rule.value;
if (typeof ruleValue !== 'string' && (_ruleValue = ruleValue) !== null && _ruleValue !== void 0 && _ruleValue.ref) {
var _ruleValue2;
const refPath = ruleValue.ref.split('.');
ruleValue = (0,external_lodash_namespaceObject.get)(tree, refPath); // Presence of another ref indicates a reference to another dynamic value.
// Pointing to another dynamic value is not supported.
if (!ruleValue || !!((_ruleValue2 = ruleValue) !== null && _ruleValue2 !== void 0 && _ruleValue2.ref)) {
return;
}
} // Calculate fluid typography rules where available.
if (cssProperty === 'font-size') {
var _tree$settings;
/*
* getTypographyFontSizeValue() will check
* if fluid typography has been activated and also
* whether the incoming value can be converted to a fluid value.
* Values that already have a "clamp()" function will not pass the test,
* and therefore the original $value will be returned.
*/
ruleValue = getTypographyFontSizeValue({
size: ruleValue
}, tree === null || tree === void 0 ? void 0 : (_tree$settings = tree.settings) === null || _tree$settings === void 0 ? void 0 : _tree$settings.typography);
}
output.push(`${cssProperty}: ${ruleValue}`);
});
return output;
}
/**
* Get generated CSS for layout styles by looking up layout definitions provided
* in theme.json, and outputting common layout styles, and specific blockGap values.
*
* @param {Object} props
* @param {Object} props.tree A theme.json tree containing layout definitions.
* @param {Object} props.style A style object containing spacing values.
* @param {string} props.selector Selector used to group together layout styling rules.
* @param {boolean} props.hasBlockGapSupport Whether or not the theme opts-in to blockGap support.
* @param {boolean} props.hasFallbackGapSupport Whether or not the theme allows fallback gap styles.
* @param {?string} props.fallbackGapValue An optional fallback gap value if no real gap value is available.
* @return {string} Generated CSS rules for the layout styles.
*/
function getLayoutStyles(_ref6) {
var _style$spacing, _tree$settings2, _tree$settings2$layou, _tree$settings3, _tree$settings3$layou;
let {
tree,
style,
selector,
hasBlockGapSupport,
hasFallbackGapSupport,
fallbackGapValue
} = _ref6;
let ruleset = '';
let gapValue = hasBlockGapSupport ? getGapCSSValue(style === null || style === void 0 ? void 0 : (_style$spacing = style.spacing) === null || _style$spacing === void 0 ? void 0 : _style$spacing.blockGap) : ''; // Ensure a fallback gap value for the root layout definitions,
// and use a fallback value if one is provided for the current block.
if (hasFallbackGapSupport) {
if (selector === ROOT_BLOCK_SELECTOR) {
gapValue = !gapValue ? '0.5em' : gapValue;
} else if (!hasBlockGapSupport && fallbackGapValue) {
gapValue = fallbackGapValue;
}
}
if (gapValue && tree !== null && tree !== void 0 && (_tree$settings2 = tree.settings) !== null && _tree$settings2 !== void 0 && (_tree$settings2$layou = _tree$settings2.layout) !== null && _tree$settings2$layou !== void 0 && _tree$settings2$layou.definitions) {
Object.values(tree.settings.layout.definitions).forEach(_ref7 => {
let {
className,
name,
spacingStyles
} = _ref7;
// Allow outputting fallback gap styles for flex layout type when block gap support isn't available.
if (!hasBlockGapSupport && 'flex' !== name) {
return;
}
if (spacingStyles !== null && spacingStyles !== void 0 && spacingStyles.length) {
spacingStyles.forEach(spacingStyle => {
const declarations = [];
if (spacingStyle.rules) {
Object.entries(spacingStyle.rules).forEach(_ref8 => {
let [cssProperty, cssValue] = _ref8;
declarations.push(`${cssProperty}: ${cssValue ? cssValue : gapValue}`);
});
}
if (declarations.length) {
let combinedSelector = '';
if (!hasBlockGapSupport) {
// For fallback gap styles, use lower specificity, to ensure styles do not unintentionally override theme styles.
combinedSelector = selector === ROOT_BLOCK_SELECTOR ? `:where(.${className}${(spacingStyle === null || spacingStyle === void 0 ? void 0 : spacingStyle.selector) || ''})` : `:where(${selector}.${className}${(spacingStyle === null || spacingStyle === void 0 ? void 0 : spacingStyle.selector) || ''})`;
} else {
combinedSelector = selector === ROOT_BLOCK_SELECTOR ? `${selector} .${className}${(spacingStyle === null || spacingStyle === void 0 ? void 0 : spacingStyle.selector) || ''}` : `${selector}.${className}${(spacingStyle === null || spacingStyle === void 0 ? void 0 : spacingStyle.selector) || ''}`;
}
ruleset += `${combinedSelector} { ${declarations.join('; ')}; }`;
}
});
}
}); // For backwards compatibility, ensure the legacy block gap CSS variable is still available.
if (selector === ROOT_BLOCK_SELECTOR && hasBlockGapSupport) {
ruleset += `${selector} { --wp--style--block-gap: ${gapValue}; }`;
}
} // Output base styles
if (selector === ROOT_BLOCK_SELECTOR && tree !== null && tree !== void 0 && (_tree$settings3 = tree.settings) !== null && _tree$settings3 !== void 0 && (_tree$settings3$layou = _tree$settings3.layout) !== null && _tree$settings3$layou !== void 0 && _tree$settings3$layou.definitions) {
const validDisplayModes = ['block', 'flex', 'grid'];
Object.values(tree.settings.layout.definitions).forEach(_ref9 => {
let {
className,
displayMode,
baseStyles
} = _ref9;
if (displayMode && validDisplayModes.includes(displayMode)) {
ruleset += `${selector} .${className} { display:${displayMode}; }`;
}
if (baseStyles !== null && baseStyles !== void 0 && baseStyles.length) {
baseStyles.forEach(baseStyle => {
const declarations = [];
if (baseStyle.rules) {
Object.entries(baseStyle.rules).forEach(_ref10 => {
let [cssProperty, cssValue] = _ref10;
declarations.push(`${cssProperty}: ${cssValue}`);
});
}
if (declarations.length) {
const combinedSelector = `${selector} .${className}${(baseStyle === null || baseStyle === void 0 ? void 0 : baseStyle.selector) || ''}`;
ruleset += `${combinedSelector} { ${declarations.join('; ')}; }`;
}
});
}
});
}
return ruleset;
}
const getNodesWithStyles = (tree, blockSelectors) => {
var _tree$styles$blocks, _tree$styles3;
const nodes = [];
if (!(tree !== null && tree !== void 0 && tree.styles)) {
return nodes;
}
const pickStyleKeys = treeToPickFrom => Object.fromEntries(Object.entries(treeToPickFrom !== null && treeToPickFrom !== void 0 ? treeToPickFrom : {}).filter(_ref11 => {
let [key] = _ref11;
return ['border', 'color', 'dimensions', 'spacing', 'typography', 'filter', 'outline', 'shadow'].includes(key);
})); // Top-level.
const styles = pickStyleKeys(tree.styles);
if (!!styles) {
nodes.push({
styles,
selector: ROOT_BLOCK_SELECTOR
});
}
Object.entries(external_wp_blocks_namespaceObject.__EXPERIMENTAL_ELEMENTS).forEach(_ref12 => {
var _tree$styles;
let [name, selector] = _ref12;
if (!!((_tree$styles = tree.styles) !== null && _tree$styles !== void 0 && _tree$styles.elements[name])) {
var _tree$styles2;
nodes.push({
styles: (_tree$styles2 = tree.styles) === null || _tree$styles2 === void 0 ? void 0 : _tree$styles2.elements[name],
selector
});
}
}); // Iterate over blocks: they can have styles & elements.
Object.entries((_tree$styles$blocks = (_tree$styles3 = tree.styles) === null || _tree$styles3 === void 0 ? void 0 : _tree$styles3.blocks) !== null && _tree$styles$blocks !== void 0 ? _tree$styles$blocks : {}).forEach(_ref13 => {
var _blockSelectors$block, _node$elements;
let [blockName, node] = _ref13;
const blockStyles = pickStyleKeys(node);
if (node !== null && node !== void 0 && node.variations) {
const variations = {};
Object.keys(node.variations).forEach(variation => {
variations[variation] = pickStyleKeys(node.variations[variation]);
});
blockStyles.variations = variations;
}
if (!!blockStyles && !!(blockSelectors !== null && blockSelectors !== void 0 && (_blockSelectors$block = blockSelectors[blockName]) !== null && _blockSelectors$block !== void 0 && _blockSelectors$block.selector)) {
nodes.push({
duotoneSelector: blockSelectors[blockName].duotoneSelector,
fallbackGapValue: blockSelectors[blockName].fallbackGapValue,
hasLayoutSupport: blockSelectors[blockName].hasLayoutSupport,
selector: blockSelectors[blockName].selector,
styles: blockStyles,
featureSelectors: blockSelectors[blockName].featureSelectors,
styleVariationSelectors: blockSelectors[blockName].styleVariationSelectors
});
}
Object.entries((_node$elements = node === null || node === void 0 ? void 0 : node.elements) !== null && _node$elements !== void 0 ? _node$elements : {}).forEach(_ref14 => {
let [elementName, value] = _ref14;
if (!!value && !!(blockSelectors !== null && blockSelectors !== void 0 && blockSelectors[blockName]) && !!(external_wp_blocks_namespaceObject.__EXPERIMENTAL_ELEMENTS !== null && external_wp_blocks_namespaceObject.__EXPERIMENTAL_ELEMENTS !== void 0 && external_wp_blocks_namespaceObject.__EXPERIMENTAL_ELEMENTS[elementName])) {
nodes.push({
styles: value,
selector: blockSelectors[blockName].selector.split(',').map(sel => {
const elementSelectors = external_wp_blocks_namespaceObject.__EXPERIMENTAL_ELEMENTS[elementName].split(',');
return elementSelectors.map(elementSelector => sel + ' ' + elementSelector);
}).join(',')
});
}
});
});
return nodes;
};
const getNodesWithSettings = (tree, blockSelectors) => {
var _tree$settings4, _tree$settings$blocks, _tree$settings5;
const nodes = [];
if (!(tree !== null && tree !== void 0 && tree.settings)) {
return nodes;
}
const pickPresets = treeToPickFrom => {
const presets = {};
PRESET_METADATA.forEach(_ref15 => {
let {
path
} = _ref15;
const value = (0,external_lodash_namespaceObject.get)(treeToPickFrom, path, false);
if (value !== false) {
(0,external_lodash_namespaceObject.set)(presets, path, value);
}
});
return presets;
}; // Top-level.
const presets = pickPresets(tree.settings);
const custom = (_tree$settings4 = tree.settings) === null || _tree$settings4 === void 0 ? void 0 : _tree$settings4.custom;
if (!(0,external_lodash_namespaceObject.isEmpty)(presets) || !!custom) {
nodes.push({
presets,
custom,
selector: ROOT_BLOCK_SELECTOR
});
} // Blocks.
Object.entries((_tree$settings$blocks = (_tree$settings5 = tree.settings) === null || _tree$settings5 === void 0 ? void 0 : _tree$settings5.blocks) !== null && _tree$settings$blocks !== void 0 ? _tree$settings$blocks : {}).forEach(_ref16 => {
let [blockName, node] = _ref16;
const blockPresets = pickPresets(node);
const blockCustom = node.custom;
if (!(0,external_lodash_namespaceObject.isEmpty)(blockPresets) || !!blockCustom) {
nodes.push({
presets: blockPresets,
custom: blockCustom,
selector: blockSelectors[blockName].selector
});
}
});
return nodes;
};
const toCustomProperties = (tree, blockSelectors) => {
const settings = getNodesWithSettings(tree, blockSelectors);
let ruleset = '';
settings.forEach(_ref17 => {
let {
presets,
custom,
selector
} = _ref17;
const declarations = getPresetsDeclarations(presets, tree === null || tree === void 0 ? void 0 : tree.settings);
const customProps = flattenTree(custom, '--wp--custom--', '--');
if (customProps.length > 0) {
declarations.push(...customProps);
}
if (declarations.length > 0) {
ruleset = ruleset + `${selector}{${declarations.join(';')};}`;
}
});
return ruleset;
};
const toStyles = function (tree, blockSelectors, hasBlockGapSupport, hasFallbackGapSupport) {
var _tree$settings6, _tree$settings7;
let disableLayoutStyles = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
const nodesWithStyles = getNodesWithStyles(tree, blockSelectors);
const nodesWithSettings = getNodesWithSettings(tree, blockSelectors);
const useRootPaddingAlign = tree === null || tree === void 0 ? void 0 : (_tree$settings6 = tree.settings) === null || _tree$settings6 === void 0 ? void 0 : _tree$settings6.useRootPaddingAwareAlignments;
const {
contentSize,
wideSize
} = (tree === null || tree === void 0 ? void 0 : (_tree$settings7 = tree.settings) === null || _tree$settings7 === void 0 ? void 0 : _tree$settings7.layout) || {};
/*
* Reset default browser margin on the root body element.
* This is set on the root selector **before** generating the ruleset
* from the `theme.json`. This is to ensure that if the `theme.json` declares
* `margin` in its `spacing` declaration for the `body` element then these
* user-generated values take precedence in the CSS cascade.
* @link https://github.com/WordPress/gutenberg/issues/36147.
*/
let ruleset = 'body {margin: 0;';
if (contentSize) {
ruleset += ` --wp--style--global--content-size: ${contentSize};`;
}
if (wideSize) {
ruleset += ` --wp--style--global--wide-size: ${wideSize};`;
}
if (useRootPaddingAlign) {
ruleset += `padding-right: 0; padding-left: 0; padding-top: var(--wp--style--root--padding-top); padding-bottom: var(--wp--style--root--padding-bottom) }
.has-global-padding { padding-right: var(--wp--style--root--padding-right); padding-left: var(--wp--style--root--padding-left); }
.has-global-padding :where(.has-global-padding) { padding-right: 0; padding-left: 0; }
.has-global-padding > .alignfull { margin-right: calc(var(--wp--style--root--padding-right) * -1); margin-left: calc(var(--wp--style--root--padding-left) * -1); }
.has-global-padding :where(.has-global-padding) > .alignfull { margin-right: 0; margin-left: 0; }
.has-global-padding > .alignfull:where(:not(.has-global-padding)) > :where([class*="wp-block-"]:not(.alignfull):not([class*="__"]),p,h1,h2,h3,h4,h5,h6,ul,ol) { padding-right: var(--wp--style--root--padding-right); padding-left: var(--wp--style--root--padding-left); }
.has-global-padding :where(.has-global-padding) > .alignfull:where(:not(.has-global-padding)) > :where([class*="wp-block-"]:not(.alignfull):not([class*="__"]),p,h1,h2,h3,h4,h5,h6,ul,ol) { padding-right: 0; padding-left: 0;`;
}
ruleset += '}';
nodesWithStyles.forEach(_ref18 => {
let {
selector,
duotoneSelector,
styles,
fallbackGapValue,
hasLayoutSupport,
featureSelectors,
styleVariationSelectors
} = _ref18;
// Process styles for block support features with custom feature level
// CSS selectors set.
if (featureSelectors) {
Object.entries(featureSelectors).forEach(_ref19 => {
let [featureName, featureSelector] = _ref19;
if (styles !== null && styles !== void 0 && styles[featureName]) {
const featureStyles = {
[featureName]: styles[featureName]
};
const featureDeclarations = getStylesDeclarations(featureStyles);
delete styles[featureName];
if (!!featureDeclarations.length) {
ruleset = ruleset + `${featureSelector}{${featureDeclarations.join(';')} }`;
}
}
});
}
if (styleVariationSelectors) {
Object.entries(styleVariationSelectors).forEach(_ref20 => {
var _styles$variations;
let [styleVariationName, styleVariationSelector] = _ref20;
if (styles !== null && styles !== void 0 && (_styles$variations = styles.variations) !== null && _styles$variations !== void 0 && _styles$variations[styleVariationName]) {
var _styles$variations3;
// If the block uses any custom selectors for block support, add those first.
if (featureSelectors) {
Object.entries(featureSelectors).forEach(_ref21 => {
var _styles$variations2, _styles$variations2$s;
let [featureName, featureSelector] = _ref21;
if (styles !== null && styles !== void 0 && (_styles$variations2 = styles.variations) !== null && _styles$variations2 !== void 0 && (_styles$variations2$s = _styles$variations2[styleVariationName]) !== null && _styles$variations2$s !== void 0 && _styles$variations2$s[featureName]) {
const featureStyles = {
[featureName]: styles.variations[styleVariationName][featureName]
};
const featureDeclarations = getStylesDeclarations(featureStyles);
delete styles.variations[styleVariationName][featureName];
if (!!featureDeclarations.length) {
ruleset = ruleset + `${concatFeatureVariationSelectorString(featureSelector, styleVariationSelector)}{${featureDeclarations.join(';')} }`;
}
}
});
} // Otherwise add regular selectors.
const styleVariationDeclarations = getStylesDeclarations(styles === null || styles === void 0 ? void 0 : (_styles$variations3 = styles.variations) === null || _styles$variations3 === void 0 ? void 0 : _styles$variations3[styleVariationName], styleVariationSelector, useRootPaddingAlign, tree);
if (!!styleVariationDeclarations.length) {
ruleset = ruleset + `${styleVariationSelector}{${styleVariationDeclarations.join(';')}}`;
}
}
});
}
const duotoneStyles = {};
if (styles !== null && styles !== void 0 && styles.filter) {
duotoneStyles.filter = styles.filter;
delete styles.filter;
} // Process duotone styles (they use color.__experimentalDuotone selector).
if (duotoneSelector) {
const duotoneDeclarations = getStylesDeclarations(duotoneStyles);
if (duotoneDeclarations.length > 0) {
ruleset = ruleset + `${duotoneSelector}{${duotoneDeclarations.join(';')};}`;
}
} // Process blockGap and layout styles.
if (!disableLayoutStyles && (ROOT_BLOCK_SELECTOR === selector || hasLayoutSupport)) {
ruleset += getLayoutStyles({
tree,
style: styles,
selector,
hasBlockGapSupport,
hasFallbackGapSupport,
fallbackGapValue
});
} // Process the remaining block styles (they use either normal block class or __experimentalSelector).
const declarations = getStylesDeclarations(styles, selector, useRootPaddingAlign, tree);
if (declarations !== null && declarations !== void 0 && declarations.length) {
ruleset = ruleset + `${selector}{${declarations.join(';')};}`;
} // Check for pseudo selector in `styles` and handle separately.
const pseudoSelectorStyles = Object.entries(styles).filter(_ref22 => {
let [key] = _ref22;
return key.startsWith(':');
});
if (pseudoSelectorStyles !== null && pseudoSelectorStyles !== void 0 && pseudoSelectorStyles.length) {
pseudoSelectorStyles.forEach(_ref23 => {
let [pseudoKey, pseudoStyle] = _ref23;
const pseudoDeclarations = getStylesDeclarations(pseudoStyle);
if (!(pseudoDeclarations !== null && pseudoDeclarations !== void 0 && pseudoDeclarations.length)) {
return;
} // `selector` maybe provided in a form
// where block level selectors have sub element
// selectors appended to them as a comma separated
// string.
// e.g. `h1 a,h2 a,h3 a,h4 a,h5 a,h6 a`;
// Split and append pseudo selector to create
// the proper rules to target the elements.
const _selector = selector.split(',').map(sel => sel + pseudoKey).join(',');
const pseudoRule = `${_selector}{${pseudoDeclarations.join(';')};}`;
ruleset = ruleset + pseudoRule;
});
}
});
/* Add alignment / layout styles */
ruleset = ruleset + '.wp-site-blocks > .alignleft { float: left; margin-right: 2em; }';
ruleset = ruleset + '.wp-site-blocks > .alignright { float: right; margin-left: 2em; }';
ruleset = ruleset + '.wp-site-blocks > .aligncenter { justify-content: center; margin-left: auto; margin-right: auto; }';
if (hasBlockGapSupport) {
var _tree$styles4, _tree$styles4$spacing;
// Use fallback of `0.5em` just in case, however if there is blockGap support, there should nearly always be a real value.
const gapValue = getGapCSSValue(tree === null || tree === void 0 ? void 0 : (_tree$styles4 = tree.styles) === null || _tree$styles4 === void 0 ? void 0 : (_tree$styles4$spacing = _tree$styles4.spacing) === null || _tree$styles4$spacing === void 0 ? void 0 : _tree$styles4$spacing.blockGap) || '0.5em';
ruleset = ruleset + '.wp-site-blocks > * { margin-block-start: 0; margin-block-end: 0; }';
ruleset = ruleset + `.wp-site-blocks > * + * { margin-block-start: ${gapValue}; }`;
}
nodesWithSettings.forEach(_ref24 => {
let {
selector,
presets
} = _ref24;
if (ROOT_BLOCK_SELECTOR === selector) {
// Do not add extra specificity for top-level classes.
selector = '';
}
const classes = getPresetsClasses(selector, presets);
if (!(0,external_lodash_namespaceObject.isEmpty)(classes)) {
ruleset = ruleset + classes;
}
});
return ruleset;
};
function toSvgFilters(tree, blockSelectors) {
const nodesWithSettings = getNodesWithSettings(tree, blockSelectors);
return nodesWithSettings.flatMap(_ref25 => {
let {
presets
} = _ref25;
return getPresetsSvgFilters(presets);
});
}
const getBlockSelectors = (blockTypes, getBlockStyles) => {
const result = {};
blockTypes.forEach(blockType => {
var _blockType$supports$_, _blockType$supports, _blockType$supports$c, _blockType$supports2, _blockType$supports2$, _blockType$supports3, _blockType$supports4, _blockType$supports4$, _blockType$supports4$2;
const name = blockType.name;
const selector = (_blockType$supports$_ = blockType === null || blockType === void 0 ? void 0 : (_blockType$supports = blockType.supports) === null || _blockType$supports === void 0 ? void 0 : _blockType$supports.__experimentalSelector) !== null && _blockType$supports$_ !== void 0 ? _blockType$supports$_ : '.wp-block-' + name.replace('core/', '').replace('/', '-');
const duotoneSelector = (_blockType$supports$c = blockType === null || blockType === void 0 ? void 0 : (_blockType$supports2 = blockType.supports) === null || _blockType$supports2 === void 0 ? void 0 : (_blockType$supports2$ = _blockType$supports2.color) === null || _blockType$supports2$ === void 0 ? void 0 : _blockType$supports2$.__experimentalDuotone) !== null && _blockType$supports$c !== void 0 ? _blockType$supports$c : null;
const hasLayoutSupport = !!(blockType !== null && blockType !== void 0 && (_blockType$supports3 = blockType.supports) !== null && _blockType$supports3 !== void 0 && _blockType$supports3.__experimentalLayout);
const fallbackGapValue = blockType === null || blockType === void 0 ? void 0 : (_blockType$supports4 = blockType.supports) === null || _blockType$supports4 === void 0 ? void 0 : (_blockType$supports4$ = _blockType$supports4.spacing) === null || _blockType$supports4$ === void 0 ? void 0 : (_blockType$supports4$2 = _blockType$supports4$.blockGap) === null || _blockType$supports4$2 === void 0 ? void 0 : _blockType$supports4$2.__experimentalDefault;
const blockStyleVariations = getBlockStyles(name);
const styleVariationSelectors = {};
if (blockStyleVariations !== null && blockStyleVariations !== void 0 && blockStyleVariations.length) {
blockStyleVariations.forEach(variation => {
const styleVariationSelector = `.is-style-${variation.name}${selector}`;
styleVariationSelectors[variation.name] = styleVariationSelector;
});
} // For each block support feature add any custom selectors.
const featureSelectors = {};
Object.entries(BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS).forEach(_ref26 => {
var _blockType$supports5, _blockType$supports5$;
let [featureKey, featureName] = _ref26;
const featureSelector = blockType === null || blockType === void 0 ? void 0 : (_blockType$supports5 = blockType.supports) === null || _blockType$supports5 === void 0 ? void 0 : (_blockType$supports5$ = _blockType$supports5[featureKey]) === null || _blockType$supports5$ === void 0 ? void 0 : _blockType$supports5$.__experimentalSelector;
if (featureSelector) {
featureSelectors[featureName] = utils_scopeSelector(selector, featureSelector);
}
});
result[name] = {
duotoneSelector,
fallbackGapValue,
featureSelectors: Object.keys(featureSelectors).length ? featureSelectors : undefined,
hasLayoutSupport,
name,
selector,
styleVariationSelectors: Object.keys(styleVariationSelectors).length ? styleVariationSelectors : undefined
};
});
return result;
};
/**
* If there is a separator block whose color is defined in theme.json via background,
* update the separator color to the same value by using border color.
*
* @param {Object} config Theme.json configuration file object.
* @return {Object} configTheme.json configuration file object updated.
*/
function updateConfigWithSeparator(config) {
var _config$styles, _config$styles2, _config$styles2$block, _config$styles3, _config$styles3$block, _config$styles4, _config$styles4$block;
const needsSeparatorStyleUpdate = ((_config$styles = config.styles) === null || _config$styles === void 0 ? void 0 : _config$styles.blocks['core/separator']) && ((_config$styles2 = config.styles) === null || _config$styles2 === void 0 ? void 0 : (_config$styles2$block = _config$styles2.blocks['core/separator'].color) === null || _config$styles2$block === void 0 ? void 0 : _config$styles2$block.background) && !((_config$styles3 = config.styles) !== null && _config$styles3 !== void 0 && (_config$styles3$block = _config$styles3.blocks['core/separator'].color) !== null && _config$styles3$block !== void 0 && _config$styles3$block.text) && !((_config$styles4 = config.styles) !== null && _config$styles4 !== void 0 && (_config$styles4$block = _config$styles4.blocks['core/separator'].border) !== null && _config$styles4$block !== void 0 && _config$styles4$block.color);
if (needsSeparatorStyleUpdate) {
var _config$styles5;
return { ...config,
styles: { ...config.styles,
blocks: { ...config.styles.blocks,
'core/separator': { ...config.styles.blocks['core/separator'],
color: { ...config.styles.blocks['core/separator'].color,
text: (_config$styles5 = config.styles) === null || _config$styles5 === void 0 ? void 0 : _config$styles5.blocks['core/separator'].color.background
}
}
}
}
};
}
return config;
}
const processCSSNesting = (css, blockSelector) => {
let processedCSS = ''; // Split CSS nested rules.
const parts = css.split('&');
parts.forEach(part => {
processedCSS += !part.includes('{') ? blockSelector + '{' + part + '}' // If the part doesn't contain braces, it applies to the root level.
: blockSelector + part; // Prepend the selector, which effectively replaces the "&" character.
});
return processedCSS;
};
function useGlobalStylesOutput() {
let {
merged: mergedConfig
} = (0,external_wp_element_namespaceObject.useContext)(GlobalStylesContext);
const [blockGap] = useGlobalSetting('spacing.blockGap');
const hasBlockGapSupport = blockGap !== null;
const hasFallbackGapSupport = !hasBlockGapSupport; // This setting isn't useful yet: it exists as a placeholder for a future explicit fallback styles support.
const disableLayoutStyles = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getSettings
} = select(store);
return !!getSettings().disableLayoutStyles;
});
const getBlockStyles = (0,external_wp_data_namespaceObject.useSelect)(select => {
return select(external_wp_blocks_namespaceObject.store).getBlockStyles;
}, []);
return (0,external_wp_element_namespaceObject.useMemo)(() => {
var _mergedConfig, _mergedConfig2, _mergedConfig$styles$;
if (!((_mergedConfig = mergedConfig) !== null && _mergedConfig !== void 0 && _mergedConfig.styles) || !((_mergedConfig2 = mergedConfig) !== null && _mergedConfig2 !== void 0 && _mergedConfig2.settings)) {
return [];
}
mergedConfig = updateConfigWithSeparator(mergedConfig);
const blockSelectors = getBlockSelectors((0,external_wp_blocks_namespaceObject.getBlockTypes)(), getBlockStyles);
const customProperties = toCustomProperties(mergedConfig, blockSelectors);
const globalStyles = toStyles(mergedConfig, blockSelectors, hasBlockGapSupport, hasFallbackGapSupport, disableLayoutStyles);
const filters = toSvgFilters(mergedConfig, blockSelectors);
const stylesheets = [{
css: customProperties,
isGlobalStyles: true
}, {
css: globalStyles,
isGlobalStyles: true
}, // Load custom CSS in own stylesheet so that any invalid CSS entered in the input won't break all the global styles in the editor.
{
css: (_mergedConfig$styles$ = mergedConfig.styles.css) !== null && _mergedConfig$styles$ !== void 0 ? _mergedConfig$styles$ : '',
isGlobalStyles: true
}]; // Loop through the blocks to check if there are custom CSS values.
// If there are, get the block selector and push the selector together with
// the CSS value to the 'stylesheets' array.
(0,external_wp_blocks_namespaceObject.getBlockTypes)().forEach(blockType => {
var _mergedConfig$styles$2;
if ((_mergedConfig$styles$2 = mergedConfig.styles.blocks[blockType.name]) !== null && _mergedConfig$styles$2 !== void 0 && _mergedConfig$styles$2.css) {
var _mergedConfig$styles$3;
const selector = blockSelectors[blockType.name].selector;
stylesheets.push({
css: processCSSNesting((_mergedConfig$styles$3 = mergedConfig.styles.blocks[blockType.name]) === null || _mergedConfig$styles$3 === void 0 ? void 0 : _mergedConfig$styles$3.css, selector),
isGlobalStyles: true
});
}
});
return [stylesheets, mergedConfig.settings, filters];
}, [hasBlockGapSupport, hasFallbackGapSupport, mergedConfig, disableLayoutStyles]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/global-styles/index.js
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/off-canvas-editor/appender.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const prioritizedInserterBlocks = ['core/navigation-link/page', 'core/navigation-link'];
const Appender = (0,external_wp_element_namespaceObject.forwardRef)((_ref, ref) => {
let {
nestingLevel,
blockCount,
...props
} = _ref;
const [insertedBlock, setInsertedBlock] = (0,external_wp_element_namespaceObject.useState)(null);
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(Appender);
const {
hideInserter,
clientId
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getTemplateLock,
__unstableGetEditorMode,
getSelectedBlockClientId
} = select(store);
const _clientId = getSelectedBlockClientId();
return {
clientId: getSelectedBlockClientId(),
hideInserter: !!getTemplateLock(_clientId) || __unstableGetEditorMode() === 'zoom-out'
};
}, []);
const blockTitle = useBlockDisplayTitle({
clientId,
context: 'list-view'
});
const insertedBlockTitle = useBlockDisplayTitle({
clientId: insertedBlock === null || insertedBlock === void 0 ? void 0 : insertedBlock.clientId,
context: 'list-view'
});
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (!(insertedBlockTitle !== null && insertedBlockTitle !== void 0 && insertedBlockTitle.length)) {
return;
}
(0,external_wp_a11y_namespaceObject.speak)((0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: name of block being inserted (i.e. Paragraph, Image, Group etc)
(0,external_wp_i18n_namespaceObject.__)('%s block inserted'), insertedBlockTitle), 'assertive');
}, [insertedBlockTitle]);
const orderInitialBlockItems = (0,external_wp_element_namespaceObject.useCallback)(items => {
items.sort((_ref2, _ref3) => {
let {
id: aName
} = _ref2;
let {
id: bName
} = _ref3;
// Sort block items according to `prioritizedInserterBlocks`.
let aIndex = prioritizedInserterBlocks.indexOf(aName);
let bIndex = prioritizedInserterBlocks.indexOf(bName); // All other block items should come after that.
if (aIndex < 0) aIndex = prioritizedInserterBlocks.length;
if (bIndex < 0) bIndex = prioritizedInserterBlocks.length;
return aIndex - bIndex;
});
return items;
}, []);
if (hideInserter) {
return null;
}
const {
PrivateInserter
} = unlock(privateApis);
const descriptionId = `off-canvas-editor-appender__${instanceId}`;
const description = (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: 1: The name of the block. 2: The numerical position of the block. 3: The level of nesting for the block. */
(0,external_wp_i18n_namespaceObject.__)('Append to %1$s block at position %2$d, Level %3$d'), blockTitle, blockCount + 1, nestingLevel);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "offcanvas-editor-appender"
}, (0,external_wp_element_namespaceObject.createElement)(PrivateInserter, _extends({
ref: ref,
rootClientId: clientId,
position: "bottom right",
isAppender: true,
selectBlockOnInsert: false,
shouldDirectInsert: false,
__experimentalIsQuick: true
}, props, {
toggleProps: {
'aria-describedby': descriptionId
},
onSelectOrClose: maybeInsertedBlock => {
if (maybeInsertedBlock !== null && maybeInsertedBlock !== void 0 && maybeInsertedBlock.clientId) {
setInsertedBlock(maybeInsertedBlock);
}
},
orderInitialBlockItems: orderInitialBlockItems
})), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "offcanvas-editor-appender__description",
id: descriptionId
}, description));
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/off-canvas-editor/leaf.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const leaf_AnimatedTreeGridRow = animated(external_wp_components_namespaceObject.__experimentalTreeGridRow);
function leaf_ListViewLeaf(_ref) {
let {
isSelected,
position,
level,
rowCount,
children,
className,
path,
...props
} = _ref;
const ref = use_moving_animation({
isSelected,
adjustScrolling: false,
enableAnimation: true,
triggerAnimationOnChange: path
});
return (0,external_wp_element_namespaceObject.createElement)(leaf_AnimatedTreeGridRow, _extends({
ref: ref,
className: classnames_default()('block-editor-list-view-leaf', 'offcanvas-editor-list-view-leaf', className),
level: level,
positionInSet: position,
setSize: rowCount
}, props), children);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/off-canvas-editor/expander.js
/**
* WordPress dependencies
*/
function expander_ListViewExpander(_ref) {
let {
onClick
} = _ref;
return (// Keyboard events are handled by TreeGrid see: components/src/tree-grid/index.js
//
// The expander component is implemented as a pseudo element in the w3 example
// https://www.w3.org/TR/wai-aria-practices/examples/treegrid/treegrid-1.html
//
// We've mimicked this by adding an icon with aria-hidden set to true to hide this from the accessibility tree.
// For the current tree grid implementation, please do not try to make this a button.
//
// eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
(0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-list-view__expander",
onClick: event => onClick(event, {
forceToggle: true
}),
"aria-hidden": "true"
}, (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: (0,external_wp_i18n_namespaceObject.isRTL)() ? chevron_left_small : chevron_right_small
}))
);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/off-canvas-editor/block-select-button.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function block_select_button_ListViewBlockSelectButton(_ref, ref) {
let {
className,
block,
onClick,
onToggleExpanded,
tabIndex,
onFocus,
onDragStart,
onDragEnd,
draggable
} = _ref;
const {
clientId
} = block;
const blockInformation = useBlockDisplayInformation(clientId);
const blockTitle = useBlockDisplayTitle({
clientId,
context: 'list-view'
});
const {
isLocked
} = useBlockLock(clientId); // The `href` attribute triggers the browser's native HTML drag operations.
// When the link is dragged, the element's outerHTML is set in DataTransfer object as text/html.
// We need to clear any HTML drag data to prevent `pasteHandler` from firing
// inside the `useOnBlockDrop` hook.
const onDragStartHandler = event => {
event.dataTransfer.clearData();
onDragStart === null || onDragStart === void 0 ? void 0 : onDragStart(event);
};
function onKeyDownHandler(event) {
if (event.keyCode === external_wp_keycodes_namespaceObject.ENTER || event.keyCode === external_wp_keycodes_namespaceObject.SPACE) {
onClick(event);
}
}
const editAriaLabel = blockInformation ? (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The title of the block.
(0,external_wp_i18n_namespaceObject.__)('Edit %s block'), blockInformation.title) : (0,external_wp_i18n_namespaceObject.__)('Edit');
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: classnames_default()('block-editor-list-view-block-select-button', className),
onClick: onClick,
onKeyDown: onKeyDownHandler,
ref: ref,
tabIndex: tabIndex,
onFocus: onFocus,
onDragStart: onDragStartHandler,
onDragEnd: onDragEnd,
draggable: draggable,
href: `#block-${clientId}`,
"aria-hidden": true,
title: editAriaLabel
}, (0,external_wp_element_namespaceObject.createElement)(expander_ListViewExpander, {
onClick: onToggleExpanded
}), (0,external_wp_element_namespaceObject.createElement)(block_icon, {
icon: blockInformation === null || blockInformation === void 0 ? void 0 : blockInformation.icon,
showColors: true,
context: "list-view"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalHStack, {
alignment: "center",
className: "block-editor-list-view-block-select-button__label-wrapper",
justify: "flex-start",
spacing: 1
}, (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-list-view-block-select-button__title"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalTruncate, {
ellipsizeMode: "auto"
}, blockTitle)), (blockInformation === null || blockInformation === void 0 ? void 0 : blockInformation.anchor) && (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-list-view-block-select-button__anchor-wrapper"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalTruncate, {
className: "block-editor-list-view-block-select-button__anchor",
ellipsizeMode: "auto"
}, blockInformation.anchor)), isLocked && (0,external_wp_element_namespaceObject.createElement)("span", {
className: "block-editor-list-view-block-select-button__lock"
}, (0,external_wp_element_namespaceObject.createElement)(build_module_icon, {
icon: lock_small
})))));
}
/* harmony default export */ var off_canvas_editor_block_select_button = ((0,external_wp_element_namespaceObject.forwardRef)(block_select_button_ListViewBlockSelectButton));
;// CONCATENATED MODULE: external ["wp","escapeHtml"]
var external_wp_escapeHtml_namespaceObject = window["wp"]["escapeHtml"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/off-canvas-editor/update-attributes.js
/**
* WordPress dependencies
*/
/**
* @typedef {'post-type'|'custom'|'taxonomy'|'post-type-archive'} WPNavigationLinkKind
*/
/**
* Navigation Link Block Attributes
*
* @typedef {Object} WPNavigationLinkBlockAttributes
*
* @property {string} [label] Link text.
* @property {WPNavigationLinkKind} [kind] Kind is used to differentiate between term and post ids to check post draft status.
* @property {string} [type] The type such as post, page, tag, category and other custom types.
* @property {string} [rel] The relationship of the linked URL.
* @property {number} [id] A post or term id.
* @property {boolean} [opensInNewTab] Sets link target to _blank when true.
* @property {string} [url] Link href.
* @property {string} [title] Link title attribute.
*/
/**
* Link Control onChange handler that updates block attributes when a setting is changed.
*
* @param {Object} updatedValue New block attributes to update.
* @param {Function} setAttributes Block attribute update function.
* @param {WPNavigationLinkBlockAttributes} blockAttributes Current block attributes.
*
*/
const updateAttributes = function () {
let updatedValue = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let setAttributes = arguments.length > 1 ? arguments[1] : undefined;
let blockAttributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
const {
label: originalLabel = '',
kind: originalKind = '',
type: originalType = ''
} = blockAttributes;
const {
title: newLabel = '',
// the title of any provided Post.
url: newUrl = '',
opensInNewTab,
id,
kind: newKind = originalKind,
type: newType = originalType
} = updatedValue;
const newLabelWithoutHttp = newLabel.replace(/http(s?):\/\//gi, '');
const newUrlWithoutHttp = newUrl.replace(/http(s?):\/\//gi, '');
const useNewLabel = newLabel && newLabel !== originalLabel && // LinkControl without the title field relies
// on the check below. Specifically, it assumes that
// the URL is the same as a title.
// This logic a) looks suspicious and b) should really
// live in the LinkControl and not here. It's a great
// candidate for future refactoring.
newLabelWithoutHttp !== newUrlWithoutHttp; // Unfortunately this causes the escaping model to be inverted.
// The escaped content is stored in the block attributes (and ultimately in the database),
// and then the raw data is "recovered" when outputting into the DOM.
// It would be preferable to store the **raw** data in the block attributes and escape it in JS.
// Why? Because there isn't one way to escape data. Depending on the context, you need to do
// different transforms. It doesn't make sense to me to choose one of them for the purposes of storage.
// See also:
// - https://github.com/WordPress/gutenberg/pull/41063
// - https://github.com/WordPress/gutenberg/pull/18617.
const label = useNewLabel ? (0,external_wp_escapeHtml_namespaceObject.escapeHTML)(newLabel) : originalLabel || (0,external_wp_escapeHtml_namespaceObject.escapeHTML)(newUrlWithoutHttp); // In https://github.com/WordPress/gutenberg/pull/24670 we decided to use "tag" in favor of "post_tag"
const type = newType === 'post_tag' ? 'tag' : newType.replace('-', '_');
const isBuiltInType = ['post', 'page', 'tag', 'category'].indexOf(type) > -1;
const isCustomLink = !newKind && !isBuiltInType || newKind === 'custom';
const kind = isCustomLink ? 'custom' : newKind;
setAttributes({ // Passed `url` may already be encoded. To prevent double encoding, decodeURI is executed to revert to the original string.
...(newUrl && {
url: encodeURI((0,external_wp_url_namespaceObject.safeDecodeURI)(newUrl))
}),
...(label && {
label
}),
...(undefined !== opensInNewTab && {
opensInNewTab
}),
...(id && Number.isInteger(id) && {
id
}),
...(kind && {
kind
}),
...(type && type !== 'URL' && {
type
})
});
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/off-canvas-editor/link-ui.js
// Note: this file is copied directly from packages/block-library/src/navigation-link/link-ui.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Given the Link block's type attribute, return the query params to give to
* /wp/v2/search.
*
* @param {string} type Link block's type attribute.
* @param {string} kind Link block's entity of kind (post-type|taxonomy)
* @return {{ type?: string, subtype?: string }} Search query params.
*/
function getSuggestionsQuery(type, kind) {
switch (type) {
case 'post':
case 'page':
return {
type: 'post',
subtype: type
};
case 'category':
return {
type: 'term',
subtype: 'category'
};
case 'tag':
return {
type: 'term',
subtype: 'post_tag'
};
case 'post_format':
return {
type: 'post-format'
};
default:
if (kind === 'taxonomy') {
return {
type: 'term',
subtype: type
};
}
if (kind === 'post-type') {
return {
type: 'post',
subtype: type
};
}
return {};
}
}
/**
* Add transforms to Link Control
*
* @param {Object} props Component props.
* @param {string} props.clientId Block client ID.
*/
function LinkControlTransforms(_ref) {
let {
clientId
} = _ref;
const {
getBlock,
blockTransforms
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlock: _getBlock,
getBlockRootClientId,
getBlockTransformItems
} = select(store);
return {
getBlock: _getBlock,
blockTransforms: getBlockTransformItems(_getBlock(clientId), getBlockRootClientId(clientId))
};
}, [clientId]);
const {
replaceBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const featuredBlocks = ['core/page-list', 'core/site-logo', 'core/social-links', 'core/search'];
const transforms = blockTransforms.filter(item => {
return featuredBlocks.includes(item.name);
});
if (!(transforms !== null && transforms !== void 0 && transforms.length)) {
return null;
}
if (!clientId) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "link-control-transform"
}, (0,external_wp_element_namespaceObject.createElement)("h3", {
className: "link-control-transform__subheading"
}, (0,external_wp_i18n_namespaceObject.__)('Transform')), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "link-control-transform__items"
}, transforms.map(item => {
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
key: `transform-${item.name}`,
onClick: () => replaceBlock(clientId, (0,external_wp_blocks_namespaceObject.switchToBlockType)(getBlock(clientId), item.name)),
className: "link-control-transform__item"
}, (0,external_wp_element_namespaceObject.createElement)(block_icon, {
icon: item.icon
}), item.title);
})));
}
function LinkUI(props) {
const {
label,
url,
opensInNewTab,
type,
kind
} = props.link;
const link = {
url,
opensInNewTab,
title: label && (0,external_wp_dom_namespaceObject.__unstableStripHTML)(label)
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Popover, {
placement: "bottom",
onClose: props.onClose,
anchor: props.anchor,
shift: true
}, (0,external_wp_element_namespaceObject.createElement)(link_control, {
hasTextControl: true,
hasRichPreviews: true,
className: props.className,
value: link,
showInitialSuggestions: true,
withCreateSuggestion: props.hasCreateSuggestion,
noDirectEntry: !!type,
noURLSuggestion: !!type,
suggestionsQuery: getSuggestionsQuery(type, kind),
onChange: props.onChange,
onRemove: props.onRemove,
renderControlBottom: !url ? () => (0,external_wp_element_namespaceObject.createElement)(LinkControlTransforms, {
clientId: props.clientId
}) : null
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/off-canvas-editor/use-inserted-block.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const useInsertedBlock = insertedBlockClientId => {
const {
insertedBlockAttributes,
insertedBlockName
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlockName,
getBlockAttributes
} = select(store);
return {
insertedBlockAttributes: getBlockAttributes(insertedBlockClientId),
insertedBlockName: getBlockName(insertedBlockClientId)
};
}, [insertedBlockClientId]);
const {
updateBlockAttributes
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const setInsertedBlockAttributes = _updatedAttributes => {
if (!insertedBlockClientId) return;
updateBlockAttributes(insertedBlockClientId, _updatedAttributes);
};
if (!insertedBlockClientId) {
return {
insertedBlockAttributes: undefined,
insertedBlockName: undefined,
setInsertedBlockAttributes
};
}
return {
insertedBlockAttributes,
insertedBlockName,
setInsertedBlockAttributes
};
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/off-canvas-editor/block-contents.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const BLOCKS_WITH_LINK_UI_SUPPORT = ['core/navigation-link', 'core/navigation-submenu'];
const block_contents_ListViewBlockContents = (0,external_wp_element_namespaceObject.forwardRef)((_ref, ref) => {
let {
onClick,
onToggleExpanded,
block,
isSelected,
position,
siblingBlockCount,
level,
isExpanded,
selectedClientIds,
...props
} = _ref;
const {
clientId
} = block;
const [isLinkUIOpen, setIsLinkUIOpen] = (0,external_wp_element_namespaceObject.useState)();
const {
blockMovingClientId,
selectedBlockInBlockEditor,
lastInsertedBlockClientId
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
hasBlockMovingClientId,
getSelectedBlockClientId,
getLastInsertedBlocksClientIds
} = unlock(select(store));
const lastInsertedBlocksClientIds = getLastInsertedBlocksClientIds();
return {
blockMovingClientId: hasBlockMovingClientId(),
selectedBlockInBlockEditor: getSelectedBlockClientId(),
lastInsertedBlockClientId: lastInsertedBlocksClientIds && lastInsertedBlocksClientIds[0]
};
}, [clientId]);
const {
insertedBlockAttributes,
insertedBlockName,
setInsertedBlockAttributes
} = useInsertedBlock(lastInsertedBlockClientId);
const hasExistingLinkValue = insertedBlockAttributes === null || insertedBlockAttributes === void 0 ? void 0 : insertedBlockAttributes.url;
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (clientId === lastInsertedBlockClientId && BLOCKS_WITH_LINK_UI_SUPPORT !== null && BLOCKS_WITH_LINK_UI_SUPPORT !== void 0 && BLOCKS_WITH_LINK_UI_SUPPORT.includes(insertedBlockName) && !hasExistingLinkValue // don't re-show the Link UI if the block already has a link value.
) {
setIsLinkUIOpen(true);
}
}, [lastInsertedBlockClientId, clientId, insertedBlockName, hasExistingLinkValue]);
const isBlockMoveTarget = blockMovingClientId && selectedBlockInBlockEditor === clientId;
const className = classnames_default()('block-editor-list-view-block-contents', {
'is-dropping-before': isBlockMoveTarget
}); // Only include all selected blocks if the currently clicked on block
// is one of the selected blocks. This ensures that if a user attempts
// to drag a block that isn't part of the selection, they're still able
// to drag it and rearrange its position.
const draggableClientIds = selectedClientIds.includes(clientId) ? selectedClientIds : [clientId];
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, isLinkUIOpen && (0,external_wp_element_namespaceObject.createElement)(LinkUI, {
clientId: lastInsertedBlockClientId,
link: insertedBlockAttributes,
onClose: () => setIsLinkUIOpen(false),
hasCreateSuggestion: false,
onChange: updatedValue => {
updateAttributes(updatedValue, setInsertedBlockAttributes, insertedBlockAttributes);
setIsLinkUIOpen(false);
}
}), (0,external_wp_element_namespaceObject.createElement)(block_draggable, {
clientIds: draggableClientIds
}, _ref2 => {
let {
draggable,
onDragStart,
onDragEnd
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(off_canvas_editor_block_select_button, _extends({
ref: ref,
className: className,
block: block,
onClick: onClick,
onToggleExpanded: onToggleExpanded,
isSelected: isSelected,
position: position,
siblingBlockCount: siblingBlockCount,
level: level,
draggable: draggable,
onDragStart: onDragStart,
onDragEnd: onDragEnd,
isExpanded: isExpanded
}, props));
}));
});
/* harmony default export */ var off_canvas_editor_block_contents = (block_contents_ListViewBlockContents);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/off-canvas-editor/context.js
/**
* WordPress dependencies
*/
const context_ListViewContext = (0,external_wp_element_namespaceObject.createContext)({});
const context_useListViewContext = () => (0,external_wp_element_namespaceObject.useContext)(context_ListViewContext);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/off-canvas-editor/utils.js
/**
* WordPress dependencies
*/
const utils_getBlockPositionDescription = (position, siblingCount, level) => (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: 1: The numerical position of the block. 2: The total number of blocks. 3. The level of nesting for the block. */
(0,external_wp_i18n_namespaceObject.__)('Block %1$d of %2$d, Level %3$d'), position, siblingCount, level);
/**
* Returns true if the client ID occurs within the block selection or multi-selection,
* or false otherwise.
*
* @param {string} clientId Block client ID.
* @param {string|string[]} selectedBlockClientIds Selected block client ID, or an array of multi-selected blocks client IDs.
*
* @return {boolean} Whether the block is in multi-selection set.
*/
const utils_isClientIdSelected = (clientId, selectedBlockClientIds) => Array.isArray(selectedBlockClientIds) && selectedBlockClientIds.length ? selectedBlockClientIds.indexOf(clientId) !== -1 : selectedBlockClientIds === clientId;
/**
* From a start and end clientId of potentially different nesting levels,
* return the nearest-depth ids that have a common level of depth in the
* nesting hierarchy. For multiple block selection, this ensure that the
* selection is always at the same nesting level, and not split across
* separate levels.
*
* @param {string} startId The first id of a selection.
* @param {string} endId The end id of a selection, usually one that has been clicked on.
* @param {string[]} startParents An array of ancestor ids for the start id, in descending order.
* @param {string[]} endParents An array of ancestor ids for the end id, in descending order.
* @return {Object} An object containing the start and end ids.
*/
function utils_getCommonDepthClientIds(startId, endId, startParents, endParents) {
const startPath = [...startParents, startId];
const endPath = [...endParents, endId];
const depth = Math.min(startPath.length, endPath.length) - 1;
const start = startPath[depth];
const end = endPath[depth];
return {
start,
end
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/off-canvas-editor/block.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function block_ListViewBlock(_ref) {
let {
block: {
clientId
},
isDragged,
isSelected,
isBranchSelected,
selectBlock,
position,
level,
rowCount,
siblingBlockCount,
showBlockMovers,
path,
isExpanded,
selectedClientIds,
preventAnnouncement
} = _ref;
const cellRef = (0,external_wp_element_namespaceObject.useRef)(null);
const [isHovered, setIsHovered] = (0,external_wp_element_namespaceObject.useState)(false);
const {
isLocked,
isContentLocked
} = useBlockLock(clientId);
const forceSelectionContentLock = (0,external_wp_data_namespaceObject.useSelect)(select => {
if (isSelected) {
return false;
}
if (!isContentLocked) {
return false;
}
return select(store).hasSelectedInnerBlock(clientId, true);
}, [isContentLocked, clientId, isSelected]);
const isFirstSelectedBlock = forceSelectionContentLock || isSelected && selectedClientIds[0] === clientId;
const isLastSelectedBlock = forceSelectionContentLock || isSelected && selectedClientIds[selectedClientIds.length - 1] === clientId;
const {
toggleBlockHighlight
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const blockInformation = useBlockDisplayInformation(clientId);
const block = (0,external_wp_data_namespaceObject.useSelect)(select => select(store).getBlock(clientId), [clientId]); // If ListView has experimental features related to the Persistent List View,
// only focus the selected list item on mount; otherwise the list would always
// try to steal the focus from the editor canvas.
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (!isTreeGridMounted && isSelected) {
cellRef.current.focus();
}
}, []);
const onMouseEnter = (0,external_wp_element_namespaceObject.useCallback)(() => {
setIsHovered(true);
toggleBlockHighlight(clientId, true);
}, [clientId, setIsHovered, toggleBlockHighlight]);
const onMouseLeave = (0,external_wp_element_namespaceObject.useCallback)(() => {
setIsHovered(false);
toggleBlockHighlight(clientId, false);
}, [clientId, setIsHovered, toggleBlockHighlight]);
const selectEditorBlock = (0,external_wp_element_namespaceObject.useCallback)(event => {
selectBlock(event, clientId);
event.preventDefault();
}, [clientId, selectBlock]);
const updateSelection = (0,external_wp_element_namespaceObject.useCallback)(newClientId => {
selectBlock(undefined, newClientId);
}, [selectBlock]);
const {
isTreeGridMounted,
expand,
collapse,
LeafMoreMenu
} = context_useListViewContext();
const toggleExpanded = (0,external_wp_element_namespaceObject.useCallback)(event => {
// Prevent shift+click from opening link in a new window when toggling.
event.preventDefault();
event.stopPropagation();
if (isExpanded === true) {
collapse(clientId);
} else if (isExpanded === false) {
expand(clientId);
}
}, [clientId, expand, collapse, isExpanded]);
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(block_ListViewBlock);
if (!block) {
return null;
} // When a block hides its toolbar it also hides the block settings menu,
// since that menu is part of the toolbar in the editor canvas.
// List View respects this by also hiding the block settings menu.
const showBlockActions = !!block && (0,external_wp_blocks_namespaceObject.hasBlockSupport)(block.name, '__experimentalToolbar', true);
const descriptionId = `list-view-block-select-button__${instanceId}`;
const blockPositionDescription = utils_getBlockPositionDescription(position, siblingBlockCount, level);
let blockAriaLabel = (0,external_wp_i18n_namespaceObject.__)('Link');
if (blockInformation) {
blockAriaLabel = isLocked ? (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The title of the block. This string indicates a link to select the locked block.
(0,external_wp_i18n_namespaceObject.__)('%s link (locked)'), blockInformation.title) : (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The title of the block. This string indicates a link to select the block.
(0,external_wp_i18n_namespaceObject.__)('%s link'), blockInformation.title);
}
const settingsAriaLabel = blockInformation ? (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: The title of the block.
(0,external_wp_i18n_namespaceObject.__)('Options for %s block'), blockInformation.title) : (0,external_wp_i18n_namespaceObject.__)('Options');
const hasSiblings = siblingBlockCount > 0;
const hasRenderedMovers = showBlockMovers && hasSiblings;
const moverCellClassName = classnames_default()('block-editor-list-view-block__mover-cell', {
'is-visible': isHovered || isSelected
});
const listViewBlockSettingsClassName = classnames_default()('block-editor-list-view-block__menu-cell', {
'is-visible': isHovered || isFirstSelectedBlock
});
let colSpan;
if (hasRenderedMovers) {
colSpan = 1;
} else if (!showBlockActions) {
colSpan = 2;
}
const classes = classnames_default()({
'is-selected': isSelected || forceSelectionContentLock,
'is-first-selected': isFirstSelectedBlock,
'is-last-selected': isLastSelectedBlock,
'is-branch-selected': isBranchSelected,
'is-dragging': isDragged,
'has-single-cell': !showBlockActions
}); // Only include all selected blocks if the currently clicked on block
// is one of the selected blocks. This ensures that if a user attempts
// to alter a block that isn't part of the selection, they're still able
// to do so.
const dropdownClientIds = selectedClientIds.includes(clientId) ? selectedClientIds : [clientId];
const MoreMenuComponent = LeafMoreMenu ? LeafMoreMenu : block_settings_dropdown;
return (0,external_wp_element_namespaceObject.createElement)(leaf_ListViewLeaf, {
className: classes,
onMouseEnter: onMouseEnter,
onMouseLeave: onMouseLeave,
onFocus: onMouseEnter,
onBlur: onMouseLeave,
level: level,
position: position,
rowCount: rowCount,
path: path,
id: `list-view-block-${clientId}`,
"data-block": clientId,
isExpanded: isContentLocked ? undefined : isExpanded,
"aria-selected": !!isSelected || forceSelectionContentLock
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalTreeGridCell, {
className: "block-editor-list-view-block__contents-cell",
colSpan: colSpan,
ref: cellRef,
"aria-label": blockAriaLabel,
"aria-selected": !!isSelected || forceSelectionContentLock,
"aria-expanded": isContentLocked ? undefined : isExpanded,
"aria-describedby": descriptionId
}, _ref2 => {
let {
ref,
tabIndex,
onFocus
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-list-view-block__contents-container"
}, (0,external_wp_element_namespaceObject.createElement)(off_canvas_editor_block_contents, {
block: block,
onClick: selectEditorBlock,
onToggleExpanded: toggleExpanded,
isSelected: isSelected,
position: position,
siblingBlockCount: siblingBlockCount,
level: level,
ref: ref,
tabIndex: tabIndex,
onFocus: onFocus,
isExpanded: isExpanded,
selectedClientIds: selectedClientIds,
preventAnnouncement: preventAnnouncement
}), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "block-editor-list-view-block-select-button__description",
id: descriptionId
}, blockPositionDescription));
}), hasRenderedMovers && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalTreeGridCell, {
className: moverCellClassName,
withoutGridItem: true
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalTreeGridItem, null, _ref3 => {
let {
ref,
tabIndex,
onFocus
} = _ref3;
return (0,external_wp_element_namespaceObject.createElement)(BlockMoverUpButton, {
orientation: "vertical",
clientIds: [clientId],
ref: ref,
tabIndex: tabIndex,
onFocus: onFocus
});
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalTreeGridItem, null, _ref4 => {
let {
ref,
tabIndex,
onFocus
} = _ref4;
return (0,external_wp_element_namespaceObject.createElement)(BlockMoverDownButton, {
orientation: "vertical",
clientIds: [clientId],
ref: ref,
tabIndex: tabIndex,
onFocus: onFocus
});
}))), showBlockActions && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalTreeGridCell, {
className: listViewBlockSettingsClassName,
"aria-selected": !!isSelected || forceSelectionContentLock
}, _ref5 => {
let {
ref,
tabIndex,
onFocus
} = _ref5;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(MoreMenuComponent, {
clientIds: dropdownClientIds,
block: block,
clientId: clientId,
icon: more_vertical,
label: settingsAriaLabel,
toggleProps: {
ref,
className: 'block-editor-list-view-block__menu',
tabIndex,
onFocus
},
disableOpenOnArrowDown: true,
__experimentalSelectBlock: updateSelection
}));
})));
}
/* harmony default export */ var off_canvas_editor_block = ((0,external_wp_element_namespaceObject.memo)(block_ListViewBlock));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/off-canvas-editor/branch.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Given a block, returns the total number of blocks in that subtree. This is used to help determine
* the list position of a block.
*
* When a block is collapsed, we do not count their children as part of that total. In the current drag
* implementation dragged blocks and their children are not counted.
*
* @param {Object} block block tree
* @param {Object} expandedState state that notes which branches are collapsed
* @param {Array} draggedClientIds a list of dragged client ids
* @param {boolean} isExpandedByDefault flag to determine the default fallback expanded state.
* @return {number} block count
*/
function branch_countBlocks(block, expandedState, draggedClientIds, isExpandedByDefault) {
var _expandedState$block$;
const isDragged = draggedClientIds === null || draggedClientIds === void 0 ? void 0 : draggedClientIds.includes(block.clientId);
if (isDragged) {
return 0;
}
const isExpanded = (_expandedState$block$ = expandedState[block.clientId]) !== null && _expandedState$block$ !== void 0 ? _expandedState$block$ : isExpandedByDefault;
if (isExpanded) {
return 1 + block.innerBlocks.reduce(branch_countReducer(expandedState, draggedClientIds, isExpandedByDefault), 0);
}
return 1;
}
const branch_countReducer = (expandedState, draggedClientIds, isExpandedByDefault) => (count, block) => {
var _expandedState$block$2;
const isDragged = draggedClientIds === null || draggedClientIds === void 0 ? void 0 : draggedClientIds.includes(block.clientId);
if (isDragged) {
return count;
}
const isExpanded = (_expandedState$block$2 = expandedState[block.clientId]) !== null && _expandedState$block$2 !== void 0 ? _expandedState$block$2 : isExpandedByDefault;
if (isExpanded && block.innerBlocks.length > 0) {
return count + branch_countBlocks(block, expandedState, draggedClientIds, isExpandedByDefault);
}
return count + 1;
};
const off_canvas_editor_branch_noop = () => {};
function branch_ListViewBranch(props) {
const {
blocks,
selectBlock = off_canvas_editor_branch_noop,
showBlockMovers,
selectedClientIds,
level = 1,
path = '',
isBranchSelected = false,
listPosition = 0,
fixedListWindow,
isExpanded,
parentId,
shouldShowInnerBlocks = true,
showAppender: showAppenderProp = true
} = props;
const isContentLocked = (0,external_wp_data_namespaceObject.useSelect)(select => {
return !!(parentId && select(store).getTemplateLock(parentId) === 'contentOnly');
}, [parentId]);
const {
expandedState,
draggedClientIds
} = context_useListViewContext();
if (isContentLocked) {
return null;
} // Only show the appender at the first level.
const showAppender = showAppenderProp && level === 1;
const filteredBlocks = blocks.filter(Boolean);
const blockCount = filteredBlocks.length; // The appender means an extra row in List View, so add 1 to the row count.
const rowCount = showAppender ? blockCount + 1 : blockCount;
let nextPosition = listPosition;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, filteredBlocks.map((block, index) => {
var _expandedState$client;
const {
clientId,
innerBlocks
} = block;
if (index > 0) {
nextPosition += branch_countBlocks(filteredBlocks[index - 1], expandedState, draggedClientIds, isExpanded);
}
const {
itemInView
} = fixedListWindow;
const blockInView = itemInView(nextPosition);
const position = index + 1;
const updatedPath = path.length > 0 ? `${path}_${position}` : `${position}`;
const hasNestedBlocks = !!(innerBlocks !== null && innerBlocks !== void 0 && innerBlocks.length);
const shouldExpand = hasNestedBlocks && shouldShowInnerBlocks ? (_expandedState$client = expandedState[clientId]) !== null && _expandedState$client !== void 0 ? _expandedState$client : isExpanded : undefined;
const isDragged = !!(draggedClientIds !== null && draggedClientIds !== void 0 && draggedClientIds.includes(clientId));
const showBlock = isDragged || blockInView; // Make updates to the selected or dragged blocks synchronous,
// but asynchronous for any other block.
const isSelected = utils_isClientIdSelected(clientId, selectedClientIds);
const isSelectedBranch = isBranchSelected || isSelected && hasNestedBlocks;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_data_namespaceObject.AsyncModeProvider, {
key: clientId,
value: !isSelected
}, showBlock && (0,external_wp_element_namespaceObject.createElement)(off_canvas_editor_block, {
block: block,
selectBlock: selectBlock,
isSelected: isSelected,
isBranchSelected: isSelectedBranch,
isDragged: isDragged,
level: level,
position: position,
rowCount: rowCount,
siblingBlockCount: blockCount,
showBlockMovers: showBlockMovers,
path: updatedPath,
isExpanded: shouldExpand,
listPosition: nextPosition,
selectedClientIds: selectedClientIds
}), !showBlock && (0,external_wp_element_namespaceObject.createElement)("tr", null, (0,external_wp_element_namespaceObject.createElement)("td", {
className: "block-editor-list-view-placeholder"
})), hasNestedBlocks && shouldExpand && !isDragged && (0,external_wp_element_namespaceObject.createElement)(branch_ListViewBranch, {
parentId: clientId,
blocks: innerBlocks,
selectBlock: selectBlock,
showBlockMovers: showBlockMovers,
level: level + 1,
path: updatedPath,
listPosition: nextPosition + 1,
fixedListWindow: fixedListWindow,
isBranchSelected: isSelectedBranch,
selectedClientIds: selectedClientIds,
isExpanded: isExpanded,
showAppender: showAppenderProp
}));
}), showAppender && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalTreeGridRow, {
level: level,
setSize: rowCount,
positionInSet: rowCount,
isExpanded: true
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalTreeGridCell, null, treeGridCellProps => (0,external_wp_element_namespaceObject.createElement)(Appender, _extends({
nestingLevel: level,
blockCount: blockCount
}, treeGridCellProps)))));
}
/* harmony default export */ var off_canvas_editor_branch = ((0,external_wp_element_namespaceObject.memo)(branch_ListViewBranch));
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/off-canvas-editor/drop-indicator.js
/**
* WordPress dependencies
*/
function drop_indicator_ListViewDropIndicator(_ref) {
let {
listViewRef,
blockDropTarget
} = _ref;
const {
rootClientId,
clientId,
dropPosition
} = blockDropTarget || {};
const [rootBlockElement, blockElement] = (0,external_wp_element_namespaceObject.useMemo)(() => {
if (!listViewRef.current) {
return [];
} // The rootClientId will be defined whenever dropping into inner
// block lists, but is undefined when dropping at the root level.
const _rootBlockElement = rootClientId ? listViewRef.current.querySelector(`[data-block="${rootClientId}"]`) : undefined; // The clientId represents the sibling block, the dragged block will
// usually be inserted adjacent to it. It will be undefined when
// dropping a block into an empty block list.
const _blockElement = clientId ? listViewRef.current.querySelector(`[data-block="${clientId}"]`) : undefined;
return [_rootBlockElement, _blockElement];
}, [rootClientId, clientId]); // The targetElement is the element that the drop indicator will appear
// before or after. When dropping into an empty block list, blockElement
// is undefined, so the indicator will appear after the rootBlockElement.
const targetElement = blockElement || rootBlockElement;
const getDropIndicatorIndent = (0,external_wp_element_namespaceObject.useCallback)(() => {
if (!rootBlockElement) {
return 0;
} // Calculate the indent using the block icon of the root block.
// Using a classname selector here might be flaky and could be
// improved.
const targetElementRect = targetElement.getBoundingClientRect();
const rootBlockIconElement = rootBlockElement.querySelector('.block-editor-block-icon');
const rootBlockIconRect = rootBlockIconElement.getBoundingClientRect();
return rootBlockIconRect.right - targetElementRect.left;
}, [rootBlockElement, targetElement]);
const style = (0,external_wp_element_namespaceObject.useMemo)(() => {
if (!targetElement) {
return {};
}
const indent = getDropIndicatorIndent();
return {
width: targetElement.offsetWidth - indent
};
}, [getDropIndicatorIndent, targetElement]);
const popoverAnchor = (0,external_wp_element_namespaceObject.useMemo)(() => {
const isValidDropPosition = dropPosition === 'top' || dropPosition === 'bottom' || dropPosition === 'inside';
if (!targetElement || !isValidDropPosition) {
return undefined;
}
return {
ownerDocument: targetElement.ownerDocument,
getBoundingClientRect() {
const rect = targetElement.getBoundingClientRect();
const indent = getDropIndicatorIndent();
const left = rect.left + indent;
const right = rect.right;
let top = 0;
let bottom = 0;
if (dropPosition === 'top') {
top = rect.top;
bottom = rect.top;
} else {
// `dropPosition` is either `bottom` or `inside`
top = rect.bottom;
bottom = rect.bottom;
}
const width = right - left;
const height = bottom - top;
return new window.DOMRect(left, top, width, height);
}
};
}, [targetElement, dropPosition, getDropIndicatorIndent]);
if (!targetElement) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Popover, {
animate: false,
anchor: popoverAnchor,
focusOnMount: false,
className: "block-editor-list-view-drop-indicator",
variant: "unstyled"
}, (0,external_wp_element_namespaceObject.createElement)("div", {
style: style,
className: "block-editor-list-view-drop-indicator__line"
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/off-canvas-editor/use-block-selection.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function use_block_selection_useBlockSelection() {
const {
clearSelectedBlock,
multiSelect,
selectBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const {
getBlockName,
getBlockParents,
getBlockSelectionStart,
getBlockSelectionEnd,
getSelectedBlockClientIds,
hasMultiSelection,
hasSelectedBlock
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const {
getBlockType
} = (0,external_wp_data_namespaceObject.useSelect)(external_wp_blocks_namespaceObject.store);
const updateBlockSelection = (0,external_wp_element_namespaceObject.useCallback)(async (event, clientId, destinationClientId) => {
if (!(event !== null && event !== void 0 && event.shiftKey)) {
selectBlock(clientId);
return;
} // To handle multiple block selection via the `SHIFT` key, prevent
// the browser default behavior of opening the link in a new window.
event.preventDefault();
const isKeyPress = event.type === 'keydown' && (event.keyCode === external_wp_keycodes_namespaceObject.UP || event.keyCode === external_wp_keycodes_namespaceObject.DOWN || event.keyCode === external_wp_keycodes_namespaceObject.HOME || event.keyCode === external_wp_keycodes_namespaceObject.END); // Handle clicking on a block when no blocks are selected, and return early.
if (!isKeyPress && !hasSelectedBlock() && !hasMultiSelection()) {
selectBlock(clientId, null);
return;
}
const selectedBlocks = getSelectedBlockClientIds();
const clientIdWithParents = [...getBlockParents(clientId), clientId];
if (isKeyPress && !selectedBlocks.some(blockId => clientIdWithParents.includes(blockId))) {
// Ensure that shift-selecting blocks via the keyboard only
// expands the current selection if focusing over already
// selected blocks. Otherwise, clear the selection so that
// a user can create a new selection entirely by keyboard.
await clearSelectedBlock();
}
let startTarget = getBlockSelectionStart();
let endTarget = clientId; // Handle keyboard behavior for selecting multiple blocks.
if (isKeyPress) {
if (!hasSelectedBlock() && !hasMultiSelection()) {
// Set the starting point of the selection to the currently
// focused block, if there are no blocks currently selected.
// This ensures that as the selection is expanded or contracted,
// the starting point of the selection is anchored to that block.
startTarget = clientId;
}
if (destinationClientId) {
// If the user presses UP or DOWN, we want to ensure that the block they're
// moving to is the target for selection, and not the currently focused one.
endTarget = destinationClientId;
}
}
const startParents = getBlockParents(startTarget);
const endParents = getBlockParents(endTarget);
const {
start,
end
} = utils_getCommonDepthClientIds(startTarget, endTarget, startParents, endParents);
await multiSelect(start, end, null); // Announce deselected block, or number of deselected blocks if
// the total number of blocks deselected is greater than one.
const updatedSelectedBlocks = getSelectedBlockClientIds(); // If the selection is greater than 1 and the Home or End keys
// were used to generate the selection, then skip announcing the
// deselected blocks.
if ((event.keyCode === external_wp_keycodes_namespaceObject.HOME || event.keyCode === external_wp_keycodes_namespaceObject.END) && updatedSelectedBlocks.length > 1) {
return;
}
const selectionDiff = selectedBlocks.filter(blockId => !updatedSelectedBlocks.includes(blockId));
let label;
if (selectionDiff.length === 1) {
var _getBlockType;
const title = (_getBlockType = getBlockType(getBlockName(selectionDiff[0]))) === null || _getBlockType === void 0 ? void 0 : _getBlockType.title;
if (title) {
label = (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: block name */
(0,external_wp_i18n_namespaceObject.__)('%s deselected.'), title);
}
} else if (selectionDiff.length > 1) {
label = (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: number of deselected blocks */
(0,external_wp_i18n_namespaceObject.__)('%s blocks deselected.'), selectionDiff.length);
}
if (label) {
(0,external_wp_a11y_namespaceObject.speak)(label);
}
}, [clearSelectedBlock, getBlockName, getBlockType, getBlockParents, getBlockSelectionStart, getBlockSelectionEnd, getSelectedBlockClientIds, hasMultiSelection, hasSelectedBlock, multiSelect, selectBlock]);
return {
updateBlockSelection
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/off-canvas-editor/use-list-view-client-ids.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function use_list_view_client_ids_useListViewClientIds(blocks) {
return (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getDraggedBlockClientIds,
getSelectedBlockClientIds,
__unstableGetClientIdsTree
} = select(store);
return {
selectedClientIds: getSelectedBlockClientIds(),
draggedClientIds: getDraggedBlockClientIds(),
clientIdsTree: blocks ? blocks : __unstableGetClientIdsTree()
};
}, [blocks]);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/off-canvas-editor/use-list-view-drop-zone.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/** @typedef {import('../../utils/math').WPPoint} WPPoint */
/**
* The type of a drag event.
*
* @typedef {'default'|'file'|'html'} WPDragEventType
*/
/**
* An array representing data for blocks in the DOM used by drag and drop.
*
* @typedef {Object} WPListViewDropZoneBlocks
* @property {string} clientId The client id for the block.
* @property {string} rootClientId The root client id for the block.
* @property {number} blockIndex The block's index.
* @property {Element} element The DOM element representing the block.
* @property {number} innerBlockCount The number of inner blocks the block has.
* @property {boolean} isDraggedBlock Whether the block is currently being dragged.
* @property {boolean} canInsertDraggedBlocksAsSibling Whether the dragged block can be a sibling of this block.
* @property {boolean} canInsertDraggedBlocksAsChild Whether the dragged block can be a child of this block.
*/
/**
* An object containing details of a drop target.
*
* @typedef {Object} WPListViewDropZoneTarget
* @property {string} blockIndex The insertion index.
* @property {string} rootClientId The root client id for the block.
* @property {string|undefined} clientId The client id for the block.
* @property {'top'|'bottom'|'inside'} dropPosition The position relative to the block that the user is dropping to.
* 'inside' refers to nesting as an inner block.
*/
/**
* Determines whether the user positioning the dragged block to nest as an
* inner block.
*
* Presently this is determined by whether the cursor is on the right hand side
* of the block.
*
* @param {WPPoint} point The point representing the cursor position when dragging.
* @param {DOMRect} rect The rectangle.
*/
function use_list_view_drop_zone_isNestingGesture(point, rect) {
const blockCenterX = rect.left + rect.width / 2;
return point.x > blockCenterX;
} // Block navigation is always a vertical list, so only allow dropping
// to the above or below a block.
const use_list_view_drop_zone_ALLOWED_DROP_EDGES = ['top', 'bottom'];
/**
* Given blocks data and the cursor position, compute the drop target.
*
* @param {WPListViewDropZoneBlocks} blocksData Data about the blocks in list view.
* @param {WPPoint} position The point representing the cursor position when dragging.
*
* @return {WPListViewDropZoneTarget | undefined} An object containing data about the drop target.
*/
function use_list_view_drop_zone_getListViewDropTarget(blocksData, position) {
let candidateEdge;
let candidateBlockData;
let candidateDistance;
let candidateRect;
for (const blockData of blocksData) {
if (blockData.isDraggedBlock) {
continue;
}
const rect = blockData.element.getBoundingClientRect();
const [distance, edge] = getDistanceToNearestEdge(position, rect, use_list_view_drop_zone_ALLOWED_DROP_EDGES);
const isCursorWithinBlock = isPointContainedByRect(position, rect);
if (candidateDistance === undefined || distance < candidateDistance || isCursorWithinBlock) {
candidateDistance = distance;
const index = blocksData.indexOf(blockData);
const previousBlockData = blocksData[index - 1]; // If dragging near the top of a block and the preceding block
// is at the same level, use the preceding block as the candidate
// instead, as later it makes determining a nesting drop easier.
if (edge === 'top' && previousBlockData && previousBlockData.rootClientId === blockData.rootClientId && !previousBlockData.isDraggedBlock) {
candidateBlockData = previousBlockData;
candidateEdge = 'bottom';
candidateRect = previousBlockData.element.getBoundingClientRect();
} else {
candidateBlockData = blockData;
candidateEdge = edge;
candidateRect = rect;
} // If the mouse position is within the block, break early
// as the user would intend to drop either before or after
// this block.
//
// This solves an issue where some rows in the list view
// tree overlap slightly due to sub-pixel rendering.
if (isCursorWithinBlock) {
break;
}
}
}
if (!candidateBlockData) {
return;
}
const isDraggingBelow = candidateEdge === 'bottom'; // If the user is dragging towards the bottom of the block check whether
// they might be trying to nest the block as a child.
// If the block already has inner blocks, this should always be treated
// as nesting since the next block in the tree will be the first child.
if (isDraggingBelow && candidateBlockData.canInsertDraggedBlocksAsChild && (candidateBlockData.innerBlockCount > 0 || use_list_view_drop_zone_isNestingGesture(position, candidateRect))) {
return {
rootClientId: candidateBlockData.clientId,
blockIndex: 0,
dropPosition: 'inside'
};
} // If dropping as a sibling, but block cannot be inserted in
// this context, return early.
if (!candidateBlockData.canInsertDraggedBlocksAsSibling) {
return;
}
const offset = isDraggingBelow ? 1 : 0;
return {
rootClientId: candidateBlockData.rootClientId,
clientId: candidateBlockData.clientId,
blockIndex: candidateBlockData.blockIndex + offset,
dropPosition: candidateEdge
};
}
/**
* A react hook for implementing a drop zone in list view.
*
* @return {WPListViewDropZoneTarget} The drop target.
*/
function use_list_view_drop_zone_useListViewDropZone() {
const {
getBlockRootClientId,
getBlockIndex,
getBlockCount,
getDraggedBlockClientIds,
canInsertBlocks
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const [target, setTarget] = (0,external_wp_element_namespaceObject.useState)();
const {
rootClientId: targetRootClientId,
blockIndex: targetBlockIndex
} = target || {};
const onBlockDrop = useOnBlockDrop(targetRootClientId, targetBlockIndex);
const draggedBlockClientIds = getDraggedBlockClientIds();
const throttled = (0,external_wp_compose_namespaceObject.useThrottle)((0,external_wp_element_namespaceObject.useCallback)((event, currentTarget) => {
const position = {
x: event.clientX,
y: event.clientY
};
const isBlockDrag = !!(draggedBlockClientIds !== null && draggedBlockClientIds !== void 0 && draggedBlockClientIds.length);
const blockElements = Array.from(currentTarget.querySelectorAll('[data-block]'));
const blocksData = blockElements.map(blockElement => {
const clientId = blockElement.dataset.block;
const rootClientId = getBlockRootClientId(clientId);
return {
clientId,
rootClientId,
blockIndex: getBlockIndex(clientId),
element: blockElement,
isDraggedBlock: isBlockDrag ? draggedBlockClientIds.includes(clientId) : false,
innerBlockCount: getBlockCount(clientId),
canInsertDraggedBlocksAsSibling: isBlockDrag ? canInsertBlocks(draggedBlockClientIds, rootClientId) : true,
canInsertDraggedBlocksAsChild: isBlockDrag ? canInsertBlocks(draggedBlockClientIds, clientId) : true
};
});
const newTarget = use_list_view_drop_zone_getListViewDropTarget(blocksData, position);
if (newTarget) {
setTarget(newTarget);
}
}, [draggedBlockClientIds]), 200);
const ref = (0,external_wp_compose_namespaceObject.__experimentalUseDropZone)({
onDrop: onBlockDrop,
onDragOver(event) {
// `currentTarget` is only available while the event is being
// handled, so get it now and pass it to the thottled function.
// https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget
throttled(event, event.currentTarget);
},
onDragEnd() {
throttled.cancel();
setTarget(null);
}
});
return {
ref,
target
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/off-canvas-editor/use-list-view-expand-selected-item.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function use_list_view_expand_selected_item_useListViewExpandSelectedItem(_ref) {
let {
firstSelectedBlockClientId,
setExpandedState
} = _ref;
const [selectedTreeId, setSelectedTreeId] = (0,external_wp_element_namespaceObject.useState)(null);
const {
selectedBlockParentClientIds
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getBlockParents
} = select(store);
return {
selectedBlockParentClientIds: getBlockParents(firstSelectedBlockClientId, false)
};
}, [firstSelectedBlockClientId]);
const parentClientIds = Array.isArray(selectedBlockParentClientIds) && selectedBlockParentClientIds.length ? selectedBlockParentClientIds : null; // Expand tree when a block is selected.
(0,external_wp_element_namespaceObject.useEffect)(() => {
// If the selectedTreeId is the same as the selected block,
// it means that the block was selected using the block list tree.
if (selectedTreeId === firstSelectedBlockClientId) {
return;
} // If the selected block has parents, get the top-level parent.
if (parentClientIds) {
// If the selected block has parents,
// expand the tree branch.
setExpandedState({
type: 'expand',
clientIds: selectedBlockParentClientIds
});
}
}, [firstSelectedBlockClientId]);
return {
setSelectedTreeId
};
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/off-canvas-editor/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const off_canvas_editor_expanded = (state, action) => {
if (Array.isArray(action.clientIds)) {
return { ...state,
...action.clientIds.reduce((newState, id) => ({ ...newState,
[id]: action.type === 'expand'
}), {})
};
}
return state;
};
const off_canvas_editor_BLOCK_LIST_ITEM_HEIGHT = 36;
/**
* Show a hierarchical list of blocks.
*
* @param {Object} props Components props.
* @param {string} props.id An HTML element id for the root element of ListView.
* @param {string} props.parentClientId The client id of the parent block.
* @param {Array} props.blocks Custom subset of block client IDs to be used instead of the default hierarchy.
* @param {boolean} props.showBlockMovers Flag to enable block movers
* @param {boolean} props.isExpanded Flag to determine whether nested levels are expanded by default.
* @param {Object} props.LeafMoreMenu Optional more menu substitution.
* @param {string} props.description Optional accessible description for the tree grid component.
* @param {string} props.onSelect Optional callback to be invoked when a block is selected.
* @param {string} props.showAppender Flag to show or hide the block appender.
* @param {Object} ref Forwarded ref
*/
function OffCanvasEditor(_ref, ref) {
let {
id,
parentClientId,
blocks,
showBlockMovers = false,
isExpanded = false,
showAppender = true,
LeafMoreMenu,
description = (0,external_wp_i18n_namespaceObject.__)('Block navigation structure'),
onSelect
} = _ref;
const {
getBlock
} = (0,external_wp_data_namespaceObject.useSelect)(store);
const {
clientIdsTree,
draggedClientIds,
selectedClientIds
} = use_list_view_client_ids_useListViewClientIds(blocks);
const {
visibleBlockCount,
shouldShowInnerBlocks
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getGlobalBlockCount,
getClientIdsOfDescendants,
__unstableGetEditorMode
} = select(store);
const draggedBlockCount = (draggedClientIds === null || draggedClientIds === void 0 ? void 0 : draggedClientIds.length) > 0 ? getClientIdsOfDescendants(draggedClientIds).length + 1 : 0;
return {
visibleBlockCount: getGlobalBlockCount() - draggedBlockCount,
shouldShowInnerBlocks: __unstableGetEditorMode() !== 'zoom-out'
};
}, [draggedClientIds]);
const {
updateBlockSelection
} = use_block_selection_useBlockSelection();
const [expandedState, setExpandedState] = (0,external_wp_element_namespaceObject.useReducer)(off_canvas_editor_expanded, {});
const {
ref: dropZoneRef,
target: blockDropTarget
} = use_list_view_drop_zone_useListViewDropZone();
const elementRef = (0,external_wp_element_namespaceObject.useRef)();
const treeGridRef = (0,external_wp_compose_namespaceObject.useMergeRefs)([elementRef, dropZoneRef, ref]);
const isMounted = (0,external_wp_element_namespaceObject.useRef)(false);
const {
setSelectedTreeId
} = use_list_view_expand_selected_item_useListViewExpandSelectedItem({
firstSelectedBlockClientId: selectedClientIds[0],
setExpandedState
});
const selectEditorBlock = (0,external_wp_element_namespaceObject.useCallback)((event, blockClientId) => {
updateBlockSelection(event, blockClientId);
setSelectedTreeId(blockClientId);
if (onSelect) {
onSelect(getBlock(blockClientId));
}
}, [setSelectedTreeId, updateBlockSelection, onSelect, getBlock]);
(0,external_wp_element_namespaceObject.useEffect)(() => {
isMounted.current = true;
}, []); // List View renders a fixed number of items and relies on each having a fixed item height of 36px.
// If this value changes, we should also change the itemHeight value set in useFixedWindowList.
// See: https://github.com/WordPress/gutenberg/pull/35230 for additional context.
const [fixedListWindow] = (0,external_wp_compose_namespaceObject.__experimentalUseFixedWindowList)(elementRef, off_canvas_editor_BLOCK_LIST_ITEM_HEIGHT, visibleBlockCount, {
useWindowing: true,
windowOverscan: 40
});
const expand = (0,external_wp_element_namespaceObject.useCallback)(blockClientId => {
if (!blockClientId) {
return;
}
setExpandedState({
type: 'expand',
clientIds: [blockClientId]
});
}, [setExpandedState]);
const collapse = (0,external_wp_element_namespaceObject.useCallback)(blockClientId => {
if (!blockClientId) {
return;
}
setExpandedState({
type: 'collapse',
clientIds: [blockClientId]
});
}, [setExpandedState]);
const expandRow = (0,external_wp_element_namespaceObject.useCallback)(row => {
var _row$dataset;
expand(row === null || row === void 0 ? void 0 : (_row$dataset = row.dataset) === null || _row$dataset === void 0 ? void 0 : _row$dataset.block);
}, [expand]);
const collapseRow = (0,external_wp_element_namespaceObject.useCallback)(row => {
var _row$dataset2;
collapse(row === null || row === void 0 ? void 0 : (_row$dataset2 = row.dataset) === null || _row$dataset2 === void 0 ? void 0 : _row$dataset2.block);
}, [collapse]);
const focusRow = (0,external_wp_element_namespaceObject.useCallback)((event, startRow, endRow) => {
if (event.shiftKey) {
var _startRow$dataset, _endRow$dataset;
updateBlockSelection(event, startRow === null || startRow === void 0 ? void 0 : (_startRow$dataset = startRow.dataset) === null || _startRow$dataset === void 0 ? void 0 : _startRow$dataset.block, endRow === null || endRow === void 0 ? void 0 : (_endRow$dataset = endRow.dataset) === null || _endRow$dataset === void 0 ? void 0 : _endRow$dataset.block);
}
}, [updateBlockSelection]);
const contextValue = (0,external_wp_element_namespaceObject.useMemo)(() => ({
isTreeGridMounted: isMounted.current,
draggedClientIds,
expandedState,
expand,
collapse,
LeafMoreMenu
}), [isMounted.current, draggedClientIds, expandedState, expand, collapse, LeafMoreMenu]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_data_namespaceObject.AsyncModeProvider, {
value: true
}, (0,external_wp_element_namespaceObject.createElement)(drop_indicator_ListViewDropIndicator, {
listViewRef: elementRef,
blockDropTarget: blockDropTarget
}), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "offcanvas-editor-list-view-tree-wrapper"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalTreeGrid, {
id: id,
className: "block-editor-list-view-tree",
"aria-label": (0,external_wp_i18n_namespaceObject.__)('Block navigation structure'),
ref: treeGridRef,
onCollapseRow: collapseRow,
onExpandRow: expandRow,
onFocusRow: focusRow // eslint-disable-next-line jsx-a11y/aria-props
,
"aria-description": description
}, (0,external_wp_element_namespaceObject.createElement)(context_ListViewContext.Provider, {
value: contextValue
}, (0,external_wp_element_namespaceObject.createElement)(off_canvas_editor_branch, {
parentId: parentClientId,
blocks: clientIdsTree,
selectBlock: selectEditorBlock,
showBlockMovers: showBlockMovers,
fixedListWindow: fixedListWindow,
selectedClientIds: selectedClientIds,
isExpanded: isExpanded,
shouldShowInnerBlocks: shouldShowInnerBlocks,
showAppender: showAppender
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalTreeGridRow, {
level: 1,
setSize: 1,
positionInSet: 1,
isExpanded: true
}, !clientIdsTree.length && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalTreeGridCell, {
withoutGridItem: true
}, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "offcanvas-editor-list-view-is-empty"
}, (0,external_wp_i18n_namespaceObject.__)('Your menu is currently empty. Add your first menu item to get started.'))))))));
}
/* harmony default export */ var off_canvas_editor = ((0,external_wp_element_namespaceObject.forwardRef)(OffCanvasEditor));
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/add-submenu.js
/**
* WordPress dependencies
*/
const addSubmenu = (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: "M2 12c0 3.6 2.4 5.5 6 5.5h.5V19l3-2.5-3-2.5v2H8c-2.5 0-4.5-1.5-4.5-4s2-4.5 4.5-4.5h3.5V6H8c-3.6 0-6 2.4-6 6zm19.5-1h-8v1.5h8V11zm0 5h-8v1.5h8V16zm0-10h-8v1.5h8V6z"
}));
/* harmony default export */ var add_submenu = (addSubmenu);
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/components/off-canvas-editor/leaf-more-menu.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const leaf_more_menu_POPOVER_PROPS = {
className: 'block-editor-block-settings-menu__popover',
position: 'bottom right',
variant: 'toolbar'
};
const BLOCKS_THAT_CAN_BE_CONVERTED_TO_SUBMENU = ['core/navigation-link', 'core/navigation-submenu'];
function AddSubmenuItem(_ref) {
let {
block,
onClose
} = _ref;
const {
expandedState,
expand
} = context_useListViewContext();
const {
insertBlock,
replaceBlock,
replaceInnerBlocks
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const clientId = block.clientId;
const isDisabled = !BLOCKS_THAT_CAN_BE_CONVERTED_TO_SUBMENU.includes(block.name);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
icon: add_submenu,
disabled: isDisabled,
onClick: () => {
const updateSelectionOnInsert = false;
const newLink = (0,external_wp_blocks_namespaceObject.createBlock)('core/navigation-link');
if (block.name === 'core/navigation-submenu') {
insertBlock(newLink, block.innerBlocks.length, clientId, updateSelectionOnInsert);
} else {
// Convert to a submenu if the block currently isn't one.
const newSubmenu = (0,external_wp_blocks_namespaceObject.createBlock)('core/navigation-submenu', block.attributes, block.innerBlocks); // The following must happen as two independent actions.
// Why? Because the offcanvas editor relies on the getLastInsertedBlocksClientIds
// selector to determine which block is "active". As the UX needs the newLink to be
// the "active" block it must be the last block to be inserted.
// Therefore the Submenu is first created and **then** the newLink is inserted
// thus ensuring it is the last inserted block.
replaceBlock(clientId, newSubmenu);
replaceInnerBlocks(newSubmenu.clientId, [newLink], updateSelectionOnInsert);
}
if (!expandedState[block.clientId]) {
expand(block.clientId);
}
onClose();
}
}, (0,external_wp_i18n_namespaceObject.__)('Add submenu link'));
}
function LeafMoreMenu(props) {
const {
clientId,
block
} = props;
const {
removeBlocks
} = (0,external_wp_data_namespaceObject.useDispatch)(store);
const label = (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: block name */
(0,external_wp_i18n_namespaceObject.__)('Remove %s'), BlockTitle({
clientId,
maximumLength: 25
}));
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.DropdownMenu, _extends({
icon: more_vertical,
label: (0,external_wp_i18n_namespaceObject.__)('Options'),
className: "block-editor-block-settings-menu",
popoverProps: leaf_more_menu_POPOVER_PROPS,
noIcons: true
}, props), _ref2 => {
let {
onClose
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuGroup, null, (0,external_wp_element_namespaceObject.createElement)(AddSubmenuItem, {
block: block,
onClose: onClose
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.MenuItem, {
onClick: () => {
removeBlocks([clientId], false);
onClose();
}
}, label));
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/private-apis.js
/**
* Internal dependencies
*/
/**
* Private @wordpress/block-editor APIs.
*/
const privateApis = {};
lock(privateApis, { ...global_styles_namespaceObject,
ExperimentalBlockEditorProvider: ExperimentalBlockEditorProvider,
LeafMoreMenu: LeafMoreMenu,
OffCanvasEditor: off_canvas_editor,
PrivateInserter: ComposedPrivateInserter
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/block-editor/build-module/index.js
/**
* Internal dependencies
*/
}();
(window.wp = window.wp || {}).blockEditor = __webpack_exports__;
/******/ })()
; vendor/wp-polyfill.js 0000666 00000170072 15123355174 0010676 0 ustar 00 /**
* core-js 3.19.1
* https://github.com/zloirock/core-js
* License: http://rock.mit-license.org
* © 2023 Denis Pushkarev (zloirock.ru)
*/
!function (undefined) { 'use strict'; /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ var __webpack_require__ = function (moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(1);
__webpack_require__(67);
__webpack_require__(68);
__webpack_require__(72);
module.exports = __webpack_require__(79);
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(2);
var toObject = __webpack_require__(36);
var lengthOfArrayLike = __webpack_require__(57);
var toIntegerOrInfinity = __webpack_require__(56);
var addToUnscopables = __webpack_require__(62);
// `Array.prototype.at` method
// https://github.com/tc39/proposal-relative-indexing-method
$({ target: 'Array', proto: true }, {
at: function at(index) {
var O = toObject(this);
var len = lengthOfArrayLike(O);
var relativeIndex = toIntegerOrInfinity(index);
var k = relativeIndex >= 0 ? relativeIndex : len + relativeIndex;
return (k < 0 || k >= len) ? undefined : O[k];
}
});
addToUnscopables('at');
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
var getOwnPropertyDescriptor = __webpack_require__(4).f;
var createNonEnumerableProperty = __webpack_require__(40);
var redefine = __webpack_require__(43);
var setGlobal = __webpack_require__(34);
var copyConstructorProperties = __webpack_require__(50);
var isForced = __webpack_require__(61);
/*
options.target - name of the target object
options.global - target is the global object
options.stat - export as static methods of target
options.proto - export as prototype methods of target
options.real - real prototype method for the `pure` version
options.forced - export even if the native feature is available
options.bind - bind methods to the target, required for the `pure` version
options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
options.unsafe - use the simple assignment of property instead of delete + defineProperty
options.sham - add a flag to not completely full polyfills
options.enumerable - export as enumerable property
options.noTargetGet - prevent calling a getter on target
options.name - the .name of the function if it does not match the key
*/
module.exports = function (options, source) {
var TARGET = options.target;
var GLOBAL = options.global;
var STATIC = options.stat;
var FORCED, target, key, targetProperty, sourceProperty, descriptor;
if (GLOBAL) {
target = global;
} else if (STATIC) {
target = global[TARGET] || setGlobal(TARGET, {});
} else {
target = (global[TARGET] || {}).prototype;
}
if (target) for (key in source) {
sourceProperty = source[key];
if (options.noTargetGet) {
descriptor = getOwnPropertyDescriptor(target, key);
targetProperty = descriptor && descriptor.value;
} else targetProperty = target[key];
FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
// contained in target
if (!FORCED && targetProperty !== undefined) {
if (typeof sourceProperty == typeof targetProperty) continue;
copyConstructorProperties(sourceProperty, targetProperty);
}
// add a flag to not completely full polyfills
if (options.sham || (targetProperty && targetProperty.sham)) {
createNonEnumerableProperty(sourceProperty, 'sham', true);
}
// extend global
redefine(target, key, sourceProperty, options);
}
};
/***/ }),
/* 3 */
/***/ (function(module, exports) {
var check = function (it) {
return it && it.Math == Math && it;
};
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
module.exports =
// eslint-disable-next-line es/no-global-this -- safe
check(typeof globalThis == 'object' && globalThis) ||
check(typeof window == 'object' && window) ||
// eslint-disable-next-line no-restricted-globals -- safe
check(typeof self == 'object' && self) ||
check(typeof global == 'object' && global) ||
// eslint-disable-next-line no-new-func -- fallback
(function () { return this; })() || Function('return this')();
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
var DESCRIPTORS = __webpack_require__(5);
var call = __webpack_require__(7);
var propertyIsEnumerableModule = __webpack_require__(8);
var createPropertyDescriptor = __webpack_require__(9);
var toIndexedObject = __webpack_require__(10);
var toPropertyKey = __webpack_require__(15);
var hasOwn = __webpack_require__(35);
var IE8_DOM_DEFINE = __webpack_require__(38);
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// `Object.getOwnPropertyDescriptor` method
// https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
exports.f = DESCRIPTORS ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
O = toIndexedObject(O);
P = toPropertyKey(P);
if (IE8_DOM_DEFINE) try {
return $getOwnPropertyDescriptor(O, P);
} catch (error) { /* empty */ }
if (hasOwn(O, P)) return createPropertyDescriptor(!call(propertyIsEnumerableModule.f, O, P), O[P]);
};
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
var fails = __webpack_require__(6);
// Detect IE8's incomplete defineProperty implementation
module.exports = !fails(function () {
// eslint-disable-next-line es/no-object-defineproperty -- required for testing
return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7;
});
/***/ }),
/* 6 */
/***/ (function(module, exports) {
module.exports = function (exec) {
try {
return !!exec();
} catch (error) {
return true;
}
};
/***/ }),
/* 7 */
/***/ (function(module, exports) {
var call = Function.prototype.call;
module.exports = call.bind ? call.bind(call) : function () {
return call.apply(call, arguments);
};
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $propertyIsEnumerable = {}.propertyIsEnumerable;
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// Nashorn ~ JDK8 bug
var NASHORN_BUG = getOwnPropertyDescriptor && !$propertyIsEnumerable.call({ 1: 2 }, 1);
// `Object.prototype.propertyIsEnumerable` method implementation
// https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
var descriptor = getOwnPropertyDescriptor(this, V);
return !!descriptor && descriptor.enumerable;
} : $propertyIsEnumerable;
/***/ }),
/* 9 */
/***/ (function(module, exports) {
module.exports = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
// toObject with fallback for non-array-like ES3 strings
var IndexedObject = __webpack_require__(11);
var requireObjectCoercible = __webpack_require__(14);
module.exports = function (it) {
return IndexedObject(requireObjectCoercible(it));
};
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
var uncurryThis = __webpack_require__(12);
var fails = __webpack_require__(6);
var classof = __webpack_require__(13);
var Object = global.Object;
var split = uncurryThis(''.split);
// fallback for non-array-like ES3 and non-enumerable old V8 strings
module.exports = fails(function () {
// throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
// eslint-disable-next-line no-prototype-builtins -- safe
return !Object('z').propertyIsEnumerable(0);
}) ? function (it) {
return classof(it) == 'String' ? split(it, '') : Object(it);
} : Object;
/***/ }),
/* 12 */
/***/ (function(module, exports) {
var FunctionPrototype = Function.prototype;
var bind = FunctionPrototype.bind;
var call = FunctionPrototype.call;
var callBind = bind && bind.bind(call);
module.exports = bind ? function (fn) {
return fn && callBind(call, fn);
} : function (fn) {
return fn && function () {
return call.apply(fn, arguments);
};
};
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
var uncurryThis = __webpack_require__(12);
var toString = uncurryThis({}.toString);
var stringSlice = uncurryThis(''.slice);
module.exports = function (it) {
return stringSlice(toString(it), 8, -1);
};
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
var TypeError = global.TypeError;
// `RequireObjectCoercible` abstract operation
// https://tc39.es/ecma262/#sec-requireobjectcoercible
module.exports = function (it) {
if (it == undefined) throw TypeError("Can't call method on " + it);
return it;
};
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
var toPrimitive = __webpack_require__(16);
var isSymbol = __webpack_require__(19);
// `ToPropertyKey` abstract operation
// https://tc39.es/ecma262/#sec-topropertykey
module.exports = function (argument) {
var key = toPrimitive(argument, 'string');
return isSymbol(key) ? key : key + '';
};
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
var call = __webpack_require__(7);
var isObject = __webpack_require__(17);
var isSymbol = __webpack_require__(19);
var getMethod = __webpack_require__(26);
var ordinaryToPrimitive = __webpack_require__(29);
var wellKnownSymbol = __webpack_require__(30);
var TypeError = global.TypeError;
var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
// `ToPrimitive` abstract operation
// https://tc39.es/ecma262/#sec-toprimitive
module.exports = function (input, pref) {
if (!isObject(input) || isSymbol(input)) return input;
var exoticToPrim = getMethod(input, TO_PRIMITIVE);
var result;
if (exoticToPrim) {
if (pref === undefined) pref = 'default';
result = call(exoticToPrim, input, pref);
if (!isObject(result) || isSymbol(result)) return result;
throw TypeError("Can't convert object to primitive value");
}
if (pref === undefined) pref = 'number';
return ordinaryToPrimitive(input, pref);
};
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
var isCallable = __webpack_require__(18);
module.exports = function (it) {
return typeof it == 'object' ? it !== null : isCallable(it);
};
/***/ }),
/* 18 */
/***/ (function(module, exports) {
// `IsCallable` abstract operation
// https://tc39.es/ecma262/#sec-iscallable
module.exports = function (argument) {
return typeof argument == 'function';
};
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
var getBuiltIn = __webpack_require__(20);
var isCallable = __webpack_require__(18);
var isPrototypeOf = __webpack_require__(21);
var USE_SYMBOL_AS_UID = __webpack_require__(22);
var Object = global.Object;
module.exports = USE_SYMBOL_AS_UID ? function (it) {
return typeof it == 'symbol';
} : function (it) {
var $Symbol = getBuiltIn('Symbol');
return isCallable($Symbol) && isPrototypeOf($Symbol.prototype, Object(it));
};
/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
var isCallable = __webpack_require__(18);
var aFunction = function (argument) {
return isCallable(argument) ? argument : undefined;
};
module.exports = function (namespace, method) {
return arguments.length < 2 ? aFunction(global[namespace]) : global[namespace] && global[namespace][method];
};
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
var uncurryThis = __webpack_require__(12);
module.exports = uncurryThis({}.isPrototypeOf);
/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {
/* eslint-disable es/no-symbol -- required for testing */
var NATIVE_SYMBOL = __webpack_require__(23);
module.exports = NATIVE_SYMBOL
&& !Symbol.sham
&& typeof Symbol.iterator == 'symbol';
/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {
/* eslint-disable es/no-symbol -- required for testing */
var V8_VERSION = __webpack_require__(24);
var fails = __webpack_require__(6);
// eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing
module.exports = !!Object.getOwnPropertySymbols && !fails(function () {
var symbol = Symbol();
// Chrome 38 Symbol has incorrect toString conversion
// `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances
return !String(symbol) || !(Object(symbol) instanceof Symbol) ||
// Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances
!Symbol.sham && V8_VERSION && V8_VERSION < 41;
});
/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
var userAgent = __webpack_require__(25);
var process = global.process;
var Deno = global.Deno;
var versions = process && process.versions || Deno && Deno.version;
var v8 = versions && versions.v8;
var match, version;
if (v8) {
match = v8.split('.');
// in old Chrome, versions of V8 isn't V8 = Chrome / 10
// but their correct versions are not interesting for us
version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]);
}
// BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0`
// so check `userAgent` even if `.v8` exists, but 0
if (!version && userAgent) {
match = userAgent.match(/Edge\/(\d+)/);
if (!match || match[1] >= 74) {
match = userAgent.match(/Chrome\/(\d+)/);
if (match) version = +match[1];
}
}
module.exports = version;
/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {
var getBuiltIn = __webpack_require__(20);
module.exports = getBuiltIn('navigator', 'userAgent') || '';
/***/ }),
/* 26 */
/***/ (function(module, exports, __webpack_require__) {
var aCallable = __webpack_require__(27);
// `GetMethod` abstract operation
// https://tc39.es/ecma262/#sec-getmethod
module.exports = function (V, P) {
var func = V[P];
return func == null ? undefined : aCallable(func);
};
/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
var isCallable = __webpack_require__(18);
var tryToString = __webpack_require__(28);
var TypeError = global.TypeError;
// `Assert: IsCallable(argument) is true`
module.exports = function (argument) {
if (isCallable(argument)) return argument;
throw TypeError(tryToString(argument) + ' is not a function');
};
/***/ }),
/* 28 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
var String = global.String;
module.exports = function (argument) {
try {
return String(argument);
} catch (error) {
return 'Object';
}
};
/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
var call = __webpack_require__(7);
var isCallable = __webpack_require__(18);
var isObject = __webpack_require__(17);
var TypeError = global.TypeError;
// `OrdinaryToPrimitive` abstract operation
// https://tc39.es/ecma262/#sec-ordinarytoprimitive
module.exports = function (input, pref) {
var fn, val;
if (pref === 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
if (isCallable(fn = input.valueOf) && !isObject(val = call(fn, input))) return val;
if (pref !== 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
throw TypeError("Can't convert object to primitive value");
};
/***/ }),
/* 30 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
var shared = __webpack_require__(31);
var hasOwn = __webpack_require__(35);
var uid = __webpack_require__(37);
var NATIVE_SYMBOL = __webpack_require__(23);
var USE_SYMBOL_AS_UID = __webpack_require__(22);
var WellKnownSymbolsStore = shared('wks');
var Symbol = global.Symbol;
var symbolFor = Symbol && Symbol['for'];
var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol : Symbol && Symbol.withoutSetter || uid;
module.exports = function (name) {
if (!hasOwn(WellKnownSymbolsStore, name) || !(NATIVE_SYMBOL || typeof WellKnownSymbolsStore[name] == 'string')) {
var description = 'Symbol.' + name;
if (NATIVE_SYMBOL && hasOwn(Symbol, name)) {
WellKnownSymbolsStore[name] = Symbol[name];
} else if (USE_SYMBOL_AS_UID && symbolFor) {
WellKnownSymbolsStore[name] = symbolFor(description);
} else {
WellKnownSymbolsStore[name] = createWellKnownSymbol(description);
}
} return WellKnownSymbolsStore[name];
};
/***/ }),
/* 31 */
/***/ (function(module, exports, __webpack_require__) {
var IS_PURE = __webpack_require__(32);
var store = __webpack_require__(33);
(module.exports = function (key, value) {
return store[key] || (store[key] = value !== undefined ? value : {});
})('versions', []).push({
version: '3.19.1',
mode: IS_PURE ? 'pure' : 'global',
copyright: '© 2021 Denis Pushkarev (zloirock.ru)'
});
/***/ }),
/* 32 */
/***/ (function(module, exports) {
module.exports = false;
/***/ }),
/* 33 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
var setGlobal = __webpack_require__(34);
var SHARED = '__core-js_shared__';
var store = global[SHARED] || setGlobal(SHARED, {});
module.exports = store;
/***/ }),
/* 34 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
// eslint-disable-next-line es/no-object-defineproperty -- safe
var defineProperty = Object.defineProperty;
module.exports = function (key, value) {
try {
defineProperty(global, key, { value: value, configurable: true, writable: true });
} catch (error) {
global[key] = value;
} return value;
};
/***/ }),
/* 35 */
/***/ (function(module, exports, __webpack_require__) {
var uncurryThis = __webpack_require__(12);
var toObject = __webpack_require__(36);
var hasOwnProperty = uncurryThis({}.hasOwnProperty);
// `HasOwnProperty` abstract operation
// https://tc39.es/ecma262/#sec-hasownproperty
module.exports = Object.hasOwn || function hasOwn(it, key) {
return hasOwnProperty(toObject(it), key);
};
/***/ }),
/* 36 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
var requireObjectCoercible = __webpack_require__(14);
var Object = global.Object;
// `ToObject` abstract operation
// https://tc39.es/ecma262/#sec-toobject
module.exports = function (argument) {
return Object(requireObjectCoercible(argument));
};
/***/ }),
/* 37 */
/***/ (function(module, exports, __webpack_require__) {
var uncurryThis = __webpack_require__(12);
var id = 0;
var postfix = Math.random();
var toString = uncurryThis(1.0.toString);
module.exports = function (key) {
return 'Symbol(' + (key === undefined ? '' : key) + ')_' + toString(++id + postfix, 36);
};
/***/ }),
/* 38 */
/***/ (function(module, exports, __webpack_require__) {
var DESCRIPTORS = __webpack_require__(5);
var fails = __webpack_require__(6);
var createElement = __webpack_require__(39);
// Thank's IE8 for his funny defineProperty
module.exports = !DESCRIPTORS && !fails(function () {
// eslint-disable-next-line es/no-object-defineproperty -- requied for testing
return Object.defineProperty(createElement('div'), 'a', {
get: function () { return 7; }
}).a != 7;
});
/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
var isObject = __webpack_require__(17);
var document = global.document;
// typeof document.createElement is 'object' in old IE
var EXISTS = isObject(document) && isObject(document.createElement);
module.exports = function (it) {
return EXISTS ? document.createElement(it) : {};
};
/***/ }),
/* 40 */
/***/ (function(module, exports, __webpack_require__) {
var DESCRIPTORS = __webpack_require__(5);
var definePropertyModule = __webpack_require__(41);
var createPropertyDescriptor = __webpack_require__(9);
module.exports = DESCRIPTORS ? function (object, key, value) {
return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));
} : function (object, key, value) {
object[key] = value;
return object;
};
/***/ }),
/* 41 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
var DESCRIPTORS = __webpack_require__(5);
var IE8_DOM_DEFINE = __webpack_require__(38);
var anObject = __webpack_require__(42);
var toPropertyKey = __webpack_require__(15);
var TypeError = global.TypeError;
// eslint-disable-next-line es/no-object-defineproperty -- safe
var $defineProperty = Object.defineProperty;
// `Object.defineProperty` method
// https://tc39.es/ecma262/#sec-object.defineproperty
exports.f = DESCRIPTORS ? $defineProperty : function defineProperty(O, P, Attributes) {
anObject(O);
P = toPropertyKey(P);
anObject(Attributes);
if (IE8_DOM_DEFINE) try {
return $defineProperty(O, P, Attributes);
} catch (error) { /* empty */ }
if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
/***/ }),
/* 42 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
var isObject = __webpack_require__(17);
var String = global.String;
var TypeError = global.TypeError;
// `Assert: Type(argument) is Object`
module.exports = function (argument) {
if (isObject(argument)) return argument;
throw TypeError(String(argument) + ' is not an object');
};
/***/ }),
/* 43 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
var isCallable = __webpack_require__(18);
var hasOwn = __webpack_require__(35);
var createNonEnumerableProperty = __webpack_require__(40);
var setGlobal = __webpack_require__(34);
var inspectSource = __webpack_require__(44);
var InternalStateModule = __webpack_require__(45);
var CONFIGURABLE_FUNCTION_NAME = __webpack_require__(49).CONFIGURABLE;
var getInternalState = InternalStateModule.get;
var enforceInternalState = InternalStateModule.enforce;
var TEMPLATE = String(String).split('String');
(module.exports = function (O, key, value, options) {
var unsafe = options ? !!options.unsafe : false;
var simple = options ? !!options.enumerable : false;
var noTargetGet = options ? !!options.noTargetGet : false;
var name = options && options.name !== undefined ? options.name : key;
var state;
if (isCallable(value)) {
if (String(name).slice(0, 7) === 'Symbol(') {
name = '[' + String(name).replace(/^Symbol\(([^)]*)\)/, '$1') + ']';
}
if (!hasOwn(value, 'name') || (CONFIGURABLE_FUNCTION_NAME && value.name !== name)) {
createNonEnumerableProperty(value, 'name', name);
}
state = enforceInternalState(value);
if (!state.source) {
state.source = TEMPLATE.join(typeof name == 'string' ? name : '');
}
}
if (O === global) {
if (simple) O[key] = value;
else setGlobal(key, value);
return;
} else if (!unsafe) {
delete O[key];
} else if (!noTargetGet && O[key]) {
simple = true;
}
if (simple) O[key] = value;
else createNonEnumerableProperty(O, key, value);
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, 'toString', function toString() {
return isCallable(this) && getInternalState(this).source || inspectSource(this);
});
/***/ }),
/* 44 */
/***/ (function(module, exports, __webpack_require__) {
var uncurryThis = __webpack_require__(12);
var isCallable = __webpack_require__(18);
var store = __webpack_require__(33);
var functionToString = uncurryThis(Function.toString);
// this helper broken in `core-js@3.4.1-3.4.4`, so we can't use `shared` helper
if (!isCallable(store.inspectSource)) {
store.inspectSource = function (it) {
return functionToString(it);
};
}
module.exports = store.inspectSource;
/***/ }),
/* 45 */
/***/ (function(module, exports, __webpack_require__) {
var NATIVE_WEAK_MAP = __webpack_require__(46);
var global = __webpack_require__(3);
var uncurryThis = __webpack_require__(12);
var isObject = __webpack_require__(17);
var createNonEnumerableProperty = __webpack_require__(40);
var hasOwn = __webpack_require__(35);
var shared = __webpack_require__(33);
var sharedKey = __webpack_require__(47);
var hiddenKeys = __webpack_require__(48);
var OBJECT_ALREADY_INITIALIZED = 'Object already initialized';
var TypeError = global.TypeError;
var WeakMap = global.WeakMap;
var set, get, has;
var enforce = function (it) {
return has(it) ? get(it) : set(it, {});
};
var getterFor = function (TYPE) {
return function (it) {
var state;
if (!isObject(it) || (state = get(it)).type !== TYPE) {
throw TypeError('Incompatible receiver, ' + TYPE + ' required');
} return state;
};
};
if (NATIVE_WEAK_MAP || shared.state) {
var store = shared.state || (shared.state = new WeakMap());
var wmget = uncurryThis(store.get);
var wmhas = uncurryThis(store.has);
var wmset = uncurryThis(store.set);
set = function (it, metadata) {
if (wmhas(store, it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
metadata.facade = it;
wmset(store, it, metadata);
return metadata;
};
get = function (it) {
return wmget(store, it) || {};
};
has = function (it) {
return wmhas(store, it);
};
} else {
var STATE = sharedKey('state');
hiddenKeys[STATE] = true;
set = function (it, metadata) {
if (hasOwn(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
metadata.facade = it;
createNonEnumerableProperty(it, STATE, metadata);
return metadata;
};
get = function (it) {
return hasOwn(it, STATE) ? it[STATE] : {};
};
has = function (it) {
return hasOwn(it, STATE);
};
}
module.exports = {
set: set,
get: get,
has: has,
enforce: enforce,
getterFor: getterFor
};
/***/ }),
/* 46 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
var isCallable = __webpack_require__(18);
var inspectSource = __webpack_require__(44);
var WeakMap = global.WeakMap;
module.exports = isCallable(WeakMap) && /native code/.test(inspectSource(WeakMap));
/***/ }),
/* 47 */
/***/ (function(module, exports, __webpack_require__) {
var shared = __webpack_require__(31);
var uid = __webpack_require__(37);
var keys = shared('keys');
module.exports = function (key) {
return keys[key] || (keys[key] = uid(key));
};
/***/ }),
/* 48 */
/***/ (function(module, exports) {
module.exports = {};
/***/ }),
/* 49 */
/***/ (function(module, exports, __webpack_require__) {
var DESCRIPTORS = __webpack_require__(5);
var hasOwn = __webpack_require__(35);
var FunctionPrototype = Function.prototype;
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
var getDescriptor = DESCRIPTORS && Object.getOwnPropertyDescriptor;
var EXISTS = hasOwn(FunctionPrototype, 'name');
// additional protection from minified / mangled / dropped function names
var PROPER = EXISTS && (function something() { /* empty */ }).name === 'something';
var CONFIGURABLE = EXISTS && (!DESCRIPTORS || (DESCRIPTORS && getDescriptor(FunctionPrototype, 'name').configurable));
module.exports = {
EXISTS: EXISTS,
PROPER: PROPER,
CONFIGURABLE: CONFIGURABLE
};
/***/ }),
/* 50 */
/***/ (function(module, exports, __webpack_require__) {
var hasOwn = __webpack_require__(35);
var ownKeys = __webpack_require__(51);
var getOwnPropertyDescriptorModule = __webpack_require__(4);
var definePropertyModule = __webpack_require__(41);
module.exports = function (target, source) {
var keys = ownKeys(source);
var defineProperty = definePropertyModule.f;
var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!hasOwn(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key));
}
};
/***/ }),
/* 51 */
/***/ (function(module, exports, __webpack_require__) {
var getBuiltIn = __webpack_require__(20);
var uncurryThis = __webpack_require__(12);
var getOwnPropertyNamesModule = __webpack_require__(52);
var getOwnPropertySymbolsModule = __webpack_require__(60);
var anObject = __webpack_require__(42);
var concat = uncurryThis([].concat);
// all object keys, includes non-enumerable and symbols
module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
var keys = getOwnPropertyNamesModule.f(anObject(it));
var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
return getOwnPropertySymbols ? concat(keys, getOwnPropertySymbols(it)) : keys;
};
/***/ }),
/* 52 */
/***/ (function(module, exports, __webpack_require__) {
var internalObjectKeys = __webpack_require__(53);
var enumBugKeys = __webpack_require__(59);
var hiddenKeys = enumBugKeys.concat('length', 'prototype');
// `Object.getOwnPropertyNames` method
// https://tc39.es/ecma262/#sec-object.getownpropertynames
// eslint-disable-next-line es/no-object-getownpropertynames -- safe
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
return internalObjectKeys(O, hiddenKeys);
};
/***/ }),
/* 53 */
/***/ (function(module, exports, __webpack_require__) {
var uncurryThis = __webpack_require__(12);
var hasOwn = __webpack_require__(35);
var toIndexedObject = __webpack_require__(10);
var indexOf = __webpack_require__(54).indexOf;
var hiddenKeys = __webpack_require__(48);
var push = uncurryThis([].push);
module.exports = function (object, names) {
var O = toIndexedObject(object);
var i = 0;
var result = [];
var key;
for (key in O) !hasOwn(hiddenKeys, key) && hasOwn(O, key) && push(result, key);
// Don't enum bug & hidden keys
while (names.length > i) if (hasOwn(O, key = names[i++])) {
~indexOf(result, key) || push(result, key);
}
return result;
};
/***/ }),
/* 54 */
/***/ (function(module, exports, __webpack_require__) {
var toIndexedObject = __webpack_require__(10);
var toAbsoluteIndex = __webpack_require__(55);
var lengthOfArrayLike = __webpack_require__(57);
// `Array.prototype.{ indexOf, includes }` methods implementation
var createMethod = function (IS_INCLUDES) {
return function ($this, el, fromIndex) {
var O = toIndexedObject($this);
var length = lengthOfArrayLike(O);
var index = toAbsoluteIndex(fromIndex, length);
var value;
// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare -- NaN check
if (IS_INCLUDES && el != el) while (length > index) {
value = O[index++];
// eslint-disable-next-line no-self-compare -- NaN check
if (value != value) return true;
// Array#indexOf ignores holes, Array#includes - not
} else for (;length > index; index++) {
if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
module.exports = {
// `Array.prototype.includes` method
// https://tc39.es/ecma262/#sec-array.prototype.includes
includes: createMethod(true),
// `Array.prototype.indexOf` method
// https://tc39.es/ecma262/#sec-array.prototype.indexof
indexOf: createMethod(false)
};
/***/ }),
/* 55 */
/***/ (function(module, exports, __webpack_require__) {
var toIntegerOrInfinity = __webpack_require__(56);
var max = Math.max;
var min = Math.min;
// Helper for a popular repeating case of the spec:
// Let integer be ? ToInteger(index).
// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
module.exports = function (index, length) {
var integer = toIntegerOrInfinity(index);
return integer < 0 ? max(integer + length, 0) : min(integer, length);
};
/***/ }),
/* 56 */
/***/ (function(module, exports) {
var ceil = Math.ceil;
var floor = Math.floor;
// `ToIntegerOrInfinity` abstract operation
// https://tc39.es/ecma262/#sec-tointegerorinfinity
module.exports = function (argument) {
var number = +argument;
// eslint-disable-next-line no-self-compare -- safe
return number !== number || number === 0 ? 0 : (number > 0 ? floor : ceil)(number);
};
/***/ }),
/* 57 */
/***/ (function(module, exports, __webpack_require__) {
var toLength = __webpack_require__(58);
// `LengthOfArrayLike` abstract operation
// https://tc39.es/ecma262/#sec-lengthofarraylike
module.exports = function (obj) {
return toLength(obj.length);
};
/***/ }),
/* 58 */
/***/ (function(module, exports, __webpack_require__) {
var toIntegerOrInfinity = __webpack_require__(56);
var min = Math.min;
// `ToLength` abstract operation
// https://tc39.es/ecma262/#sec-tolength
module.exports = function (argument) {
return argument > 0 ? min(toIntegerOrInfinity(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
};
/***/ }),
/* 59 */
/***/ (function(module, exports) {
// IE8- don't enum bug keys
module.exports = [
'constructor',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toLocaleString',
'toString',
'valueOf'
];
/***/ }),
/* 60 */
/***/ (function(module, exports) {
// eslint-disable-next-line es/no-object-getownpropertysymbols -- safe
exports.f = Object.getOwnPropertySymbols;
/***/ }),
/* 61 */
/***/ (function(module, exports, __webpack_require__) {
var fails = __webpack_require__(6);
var isCallable = __webpack_require__(18);
var replacement = /#|\.prototype\./;
var isForced = function (feature, detection) {
var value = data[normalize(feature)];
return value == POLYFILL ? true
: value == NATIVE ? false
: isCallable(detection) ? fails(detection)
: !!detection;
};
var normalize = isForced.normalize = function (string) {
return String(string).replace(replacement, '.').toLowerCase();
};
var data = isForced.data = {};
var NATIVE = isForced.NATIVE = 'N';
var POLYFILL = isForced.POLYFILL = 'P';
module.exports = isForced;
/***/ }),
/* 62 */
/***/ (function(module, exports, __webpack_require__) {
var wellKnownSymbol = __webpack_require__(30);
var create = __webpack_require__(63);
var definePropertyModule = __webpack_require__(41);
var UNSCOPABLES = wellKnownSymbol('unscopables');
var ArrayPrototype = Array.prototype;
// Array.prototype[@@unscopables]
// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
if (ArrayPrototype[UNSCOPABLES] == undefined) {
definePropertyModule.f(ArrayPrototype, UNSCOPABLES, {
configurable: true,
value: create(null)
});
}
// add a key to Array.prototype[@@unscopables]
module.exports = function (key) {
ArrayPrototype[UNSCOPABLES][key] = true;
};
/***/ }),
/* 63 */
/***/ (function(module, exports, __webpack_require__) {
/* global ActiveXObject -- old IE, WSH */
var anObject = __webpack_require__(42);
var defineProperties = __webpack_require__(64);
var enumBugKeys = __webpack_require__(59);
var hiddenKeys = __webpack_require__(48);
var html = __webpack_require__(66);
var documentCreateElement = __webpack_require__(39);
var sharedKey = __webpack_require__(47);
var GT = '>';
var LT = '<';
var PROTOTYPE = 'prototype';
var SCRIPT = 'script';
var IE_PROTO = sharedKey('IE_PROTO');
var EmptyConstructor = function () { /* empty */ };
var scriptTag = function (content) {
return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;
};
// Create object with fake `null` prototype: use ActiveX Object with cleared prototype
var NullProtoObjectViaActiveX = function (activeXDocument) {
activeXDocument.write(scriptTag(''));
activeXDocument.close();
var temp = activeXDocument.parentWindow.Object;
activeXDocument = null; // avoid memory leak
return temp;
};
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var NullProtoObjectViaIFrame = function () {
// Thrash, waste and sodomy: IE GC bug
var iframe = documentCreateElement('iframe');
var JS = 'java' + SCRIPT + ':';
var iframeDocument;
iframe.style.display = 'none';
html.appendChild(iframe);
// https://github.com/zloirock/core-js/issues/475
iframe.src = String(JS);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(scriptTag('document.F=Object'));
iframeDocument.close();
return iframeDocument.F;
};
// Check for document.domain and active x support
// No need to use active x approach when document.domain is not set
// see https://github.com/es-shims/es5-shim/issues/150
// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
// avoid IE GC bug
var activeXDocument;
var NullProtoObject = function () {
try {
activeXDocument = new ActiveXObject('htmlfile');
} catch (error) { /* ignore */ }
NullProtoObject = typeof document != 'undefined'
? document.domain && activeXDocument
? NullProtoObjectViaActiveX(activeXDocument) // old IE
: NullProtoObjectViaIFrame()
: NullProtoObjectViaActiveX(activeXDocument); // WSH
var length = enumBugKeys.length;
while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];
return NullProtoObject();
};
hiddenKeys[IE_PROTO] = true;
// `Object.create` method
// https://tc39.es/ecma262/#sec-object.create
module.exports = Object.create || function create(O, Properties) {
var result;
if (O !== null) {
EmptyConstructor[PROTOTYPE] = anObject(O);
result = new EmptyConstructor();
EmptyConstructor[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = NullProtoObject();
return Properties === undefined ? result : defineProperties(result, Properties);
};
/***/ }),
/* 64 */
/***/ (function(module, exports, __webpack_require__) {
var DESCRIPTORS = __webpack_require__(5);
var definePropertyModule = __webpack_require__(41);
var anObject = __webpack_require__(42);
var toIndexedObject = __webpack_require__(10);
var objectKeys = __webpack_require__(65);
// `Object.defineProperties` method
// https://tc39.es/ecma262/#sec-object.defineproperties
// eslint-disable-next-line es/no-object-defineproperties -- safe
module.exports = DESCRIPTORS ? Object.defineProperties : function defineProperties(O, Properties) {
anObject(O);
var props = toIndexedObject(Properties);
var keys = objectKeys(Properties);
var length = keys.length;
var index = 0;
var key;
while (length > index) definePropertyModule.f(O, key = keys[index++], props[key]);
return O;
};
/***/ }),
/* 65 */
/***/ (function(module, exports, __webpack_require__) {
var internalObjectKeys = __webpack_require__(53);
var enumBugKeys = __webpack_require__(59);
// `Object.keys` method
// https://tc39.es/ecma262/#sec-object.keys
// eslint-disable-next-line es/no-object-keys -- safe
module.exports = Object.keys || function keys(O) {
return internalObjectKeys(O, enumBugKeys);
};
/***/ }),
/* 66 */
/***/ (function(module, exports, __webpack_require__) {
var getBuiltIn = __webpack_require__(20);
module.exports = getBuiltIn('document', 'documentElement');
/***/ }),
/* 67 */
/***/ (function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2);
var hasOwn = __webpack_require__(35);
// `Object.hasOwn` method
// https://github.com/tc39/proposal-accessible-object-hasownproperty
$({ target: 'Object', stat: true }, {
hasOwn: hasOwn
});
/***/ }),
/* 68 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(2);
var uncurryThis = __webpack_require__(12);
var requireObjectCoercible = __webpack_require__(14);
var toIntegerOrInfinity = __webpack_require__(56);
var toString = __webpack_require__(69);
var fails = __webpack_require__(6);
var charAt = uncurryThis(''.charAt);
var FORCED = fails(function () {
return '𠮷'.at(0) !== '\uD842';
});
// `String.prototype.at` method
// https://github.com/tc39/proposal-relative-indexing-method
$({ target: 'String', proto: true, forced: FORCED }, {
at: function at(index) {
var S = toString(requireObjectCoercible(this));
var len = S.length;
var relativeIndex = toIntegerOrInfinity(index);
var k = relativeIndex >= 0 ? relativeIndex : len + relativeIndex;
return (k < 0 || k >= len) ? undefined : charAt(S, k);
}
});
/***/ }),
/* 69 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
var classof = __webpack_require__(70);
var String = global.String;
module.exports = function (argument) {
if (classof(argument) === 'Symbol') throw TypeError('Cannot convert a Symbol value to a string');
return String(argument);
};
/***/ }),
/* 70 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
var TO_STRING_TAG_SUPPORT = __webpack_require__(71);
var isCallable = __webpack_require__(18);
var classofRaw = __webpack_require__(13);
var wellKnownSymbol = __webpack_require__(30);
var TO_STRING_TAG = wellKnownSymbol('toStringTag');
var Object = global.Object;
// ES3 wrong here
var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function (it, key) {
try {
return it[key];
} catch (error) { /* empty */ }
};
// getting tag from ES6+ `Object.prototype.toString`
module.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) {
var O, tag, result;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (tag = tryGet(O = Object(it), TO_STRING_TAG)) == 'string' ? tag
// builtinTag case
: CORRECT_ARGUMENTS ? classofRaw(O)
// ES3 arguments fallback
: (result = classofRaw(O)) == 'Object' && isCallable(O.callee) ? 'Arguments' : result;
};
/***/ }),
/* 71 */
/***/ (function(module, exports, __webpack_require__) {
var wellKnownSymbol = __webpack_require__(30);
var TO_STRING_TAG = wellKnownSymbol('toStringTag');
var test = {};
test[TO_STRING_TAG] = 'z';
module.exports = String(test) === '[object z]';
/***/ }),
/* 72 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var ArrayBufferViewCore = __webpack_require__(73);
var lengthOfArrayLike = __webpack_require__(57);
var toIntegerOrInfinity = __webpack_require__(56);
var aTypedArray = ArrayBufferViewCore.aTypedArray;
var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;
// `%TypedArray%.prototype.at` method
// https://github.com/tc39/proposal-relative-indexing-method
exportTypedArrayMethod('at', function at(index) {
var O = aTypedArray(this);
var len = lengthOfArrayLike(O);
var relativeIndex = toIntegerOrInfinity(index);
var k = relativeIndex >= 0 ? relativeIndex : len + relativeIndex;
return (k < 0 || k >= len) ? undefined : O[k];
});
/***/ }),
/* 73 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var NATIVE_ARRAY_BUFFER = __webpack_require__(74);
var DESCRIPTORS = __webpack_require__(5);
var global = __webpack_require__(3);
var isCallable = __webpack_require__(18);
var isObject = __webpack_require__(17);
var hasOwn = __webpack_require__(35);
var classof = __webpack_require__(70);
var tryToString = __webpack_require__(28);
var createNonEnumerableProperty = __webpack_require__(40);
var redefine = __webpack_require__(43);
var defineProperty = __webpack_require__(41).f;
var isPrototypeOf = __webpack_require__(21);
var getPrototypeOf = __webpack_require__(75);
var setPrototypeOf = __webpack_require__(77);
var wellKnownSymbol = __webpack_require__(30);
var uid = __webpack_require__(37);
var Int8Array = global.Int8Array;
var Int8ArrayPrototype = Int8Array && Int8Array.prototype;
var Uint8ClampedArray = global.Uint8ClampedArray;
var Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype;
var TypedArray = Int8Array && getPrototypeOf(Int8Array);
var TypedArrayPrototype = Int8ArrayPrototype && getPrototypeOf(Int8ArrayPrototype);
var ObjectPrototype = Object.prototype;
var TypeError = global.TypeError;
var TO_STRING_TAG = wellKnownSymbol('toStringTag');
var TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG');
var TYPED_ARRAY_CONSTRUCTOR = uid('TYPED_ARRAY_CONSTRUCTOR');
// Fixing native typed arrays in Opera Presto crashes the browser, see #595
var NATIVE_ARRAY_BUFFER_VIEWS = NATIVE_ARRAY_BUFFER && !!setPrototypeOf && classof(global.opera) !== 'Opera';
var TYPED_ARRAY_TAG_REQIRED = false;
var NAME, Constructor, Prototype;
var TypedArrayConstructorsList = {
Int8Array: 1,
Uint8Array: 1,
Uint8ClampedArray: 1,
Int16Array: 2,
Uint16Array: 2,
Int32Array: 4,
Uint32Array: 4,
Float32Array: 4,
Float64Array: 8
};
var BigIntArrayConstructorsList = {
BigInt64Array: 8,
BigUint64Array: 8
};
var isView = function isView(it) {
if (!isObject(it)) return false;
var klass = classof(it);
return klass === 'DataView'
|| hasOwn(TypedArrayConstructorsList, klass)
|| hasOwn(BigIntArrayConstructorsList, klass);
};
var isTypedArray = function (it) {
if (!isObject(it)) return false;
var klass = classof(it);
return hasOwn(TypedArrayConstructorsList, klass)
|| hasOwn(BigIntArrayConstructorsList, klass);
};
var aTypedArray = function (it) {
if (isTypedArray(it)) return it;
throw TypeError('Target is not a typed array');
};
var aTypedArrayConstructor = function (C) {
if (isCallable(C) && (!setPrototypeOf || isPrototypeOf(TypedArray, C))) return C;
throw TypeError(tryToString(C) + ' is not a typed array constructor');
};
var exportTypedArrayMethod = function (KEY, property, forced) {
if (!DESCRIPTORS) return;
if (forced) for (var ARRAY in TypedArrayConstructorsList) {
var TypedArrayConstructor = global[ARRAY];
if (TypedArrayConstructor && hasOwn(TypedArrayConstructor.prototype, KEY)) try {
delete TypedArrayConstructor.prototype[KEY];
} catch (error) { /* empty */ }
}
if (!TypedArrayPrototype[KEY] || forced) {
redefine(TypedArrayPrototype, KEY, forced ? property
: NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property);
}
};
var exportTypedArrayStaticMethod = function (KEY, property, forced) {
var ARRAY, TypedArrayConstructor;
if (!DESCRIPTORS) return;
if (setPrototypeOf) {
if (forced) for (ARRAY in TypedArrayConstructorsList) {
TypedArrayConstructor = global[ARRAY];
if (TypedArrayConstructor && hasOwn(TypedArrayConstructor, KEY)) try {
delete TypedArrayConstructor[KEY];
} catch (error) { /* empty */ }
}
if (!TypedArray[KEY] || forced) {
// V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable
try {
return redefine(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && TypedArray[KEY] || property);
} catch (error) { /* empty */ }
} else return;
}
for (ARRAY in TypedArrayConstructorsList) {
TypedArrayConstructor = global[ARRAY];
if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) {
redefine(TypedArrayConstructor, KEY, property);
}
}
};
for (NAME in TypedArrayConstructorsList) {
Constructor = global[NAME];
Prototype = Constructor && Constructor.prototype;
if (Prototype) createNonEnumerableProperty(Prototype, TYPED_ARRAY_CONSTRUCTOR, Constructor);
else NATIVE_ARRAY_BUFFER_VIEWS = false;
}
for (NAME in BigIntArrayConstructorsList) {
Constructor = global[NAME];
Prototype = Constructor && Constructor.prototype;
if (Prototype) createNonEnumerableProperty(Prototype, TYPED_ARRAY_CONSTRUCTOR, Constructor);
}
// WebKit bug - typed arrays constructors prototype is Object.prototype
if (!NATIVE_ARRAY_BUFFER_VIEWS || !isCallable(TypedArray) || TypedArray === Function.prototype) {
// eslint-disable-next-line no-shadow -- safe
TypedArray = function TypedArray() {
throw TypeError('Incorrect invocation');
};
if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {
if (global[NAME]) setPrototypeOf(global[NAME], TypedArray);
}
}
if (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype) {
TypedArrayPrototype = TypedArray.prototype;
if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {
if (global[NAME]) setPrototypeOf(global[NAME].prototype, TypedArrayPrototype);
}
}
// WebKit bug - one more object in Uint8ClampedArray prototype chain
if (NATIVE_ARRAY_BUFFER_VIEWS && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) {
setPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype);
}
if (DESCRIPTORS && !hasOwn(TypedArrayPrototype, TO_STRING_TAG)) {
TYPED_ARRAY_TAG_REQIRED = true;
defineProperty(TypedArrayPrototype, TO_STRING_TAG, { get: function () {
return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined;
} });
for (NAME in TypedArrayConstructorsList) if (global[NAME]) {
createNonEnumerableProperty(global[NAME], TYPED_ARRAY_TAG, NAME);
}
}
module.exports = {
NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS,
TYPED_ARRAY_CONSTRUCTOR: TYPED_ARRAY_CONSTRUCTOR,
TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQIRED && TYPED_ARRAY_TAG,
aTypedArray: aTypedArray,
aTypedArrayConstructor: aTypedArrayConstructor,
exportTypedArrayMethod: exportTypedArrayMethod,
exportTypedArrayStaticMethod: exportTypedArrayStaticMethod,
isView: isView,
isTypedArray: isTypedArray,
TypedArray: TypedArray,
TypedArrayPrototype: TypedArrayPrototype
};
/***/ }),
/* 74 */
/***/ (function(module, exports) {
// eslint-disable-next-line es/no-typed-arrays -- safe
module.exports = typeof ArrayBuffer != 'undefined' && typeof DataView != 'undefined';
/***/ }),
/* 75 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
var hasOwn = __webpack_require__(35);
var isCallable = __webpack_require__(18);
var toObject = __webpack_require__(36);
var sharedKey = __webpack_require__(47);
var CORRECT_PROTOTYPE_GETTER = __webpack_require__(76);
var IE_PROTO = sharedKey('IE_PROTO');
var Object = global.Object;
var ObjectPrototype = Object.prototype;
// `Object.getPrototypeOf` method
// https://tc39.es/ecma262/#sec-object.getprototypeof
module.exports = CORRECT_PROTOTYPE_GETTER ? Object.getPrototypeOf : function (O) {
var object = toObject(O);
if (hasOwn(object, IE_PROTO)) return object[IE_PROTO];
var constructor = object.constructor;
if (isCallable(constructor) && object instanceof constructor) {
return constructor.prototype;
} return object instanceof Object ? ObjectPrototype : null;
};
/***/ }),
/* 76 */
/***/ (function(module, exports, __webpack_require__) {
var fails = __webpack_require__(6);
module.exports = !fails(function () {
function F() { /* empty */ }
F.prototype.constructor = null;
// eslint-disable-next-line es/no-object-getprototypeof -- required for testing
return Object.getPrototypeOf(new F()) !== F.prototype;
});
/***/ }),
/* 77 */
/***/ (function(module, exports, __webpack_require__) {
/* eslint-disable no-proto -- safe */
var uncurryThis = __webpack_require__(12);
var anObject = __webpack_require__(42);
var aPossiblePrototype = __webpack_require__(78);
// `Object.setPrototypeOf` method
// https://tc39.es/ecma262/#sec-object.setprototypeof
// Works with __proto__ only. Old v8 can't work with null proto objects.
// eslint-disable-next-line es/no-object-setprototypeof -- safe
module.exports = Object.setPrototypeOf || ('__proto__' in {} ? function () {
var CORRECT_SETTER = false;
var test = {};
var setter;
try {
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
setter = uncurryThis(Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set);
setter(test, []);
CORRECT_SETTER = test instanceof Array;
} catch (error) { /* empty */ }
return function setPrototypeOf(O, proto) {
anObject(O);
aPossiblePrototype(proto);
if (CORRECT_SETTER) setter(O, proto);
else O.__proto__ = proto;
return O;
};
}() : undefined);
/***/ }),
/* 78 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
var isCallable = __webpack_require__(18);
var String = global.String;
var TypeError = global.TypeError;
module.exports = function (argument) {
if (typeof argument == 'object' || isCallable(argument)) return argument;
throw TypeError("Can't set " + String(argument) + ' as a prototype');
};
/***/ }),
/* 79 */
/***/ (function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2);
var global = __webpack_require__(3);
var task = __webpack_require__(80);
var FORCED = !global.setImmediate || !global.clearImmediate;
// http://w3c.github.io/setImmediate/
$({ global: true, bind: true, enumerable: true, forced: FORCED }, {
// `setImmediate` method
// http://w3c.github.io/setImmediate/#si-setImmediate
setImmediate: task.set,
// `clearImmediate` method
// http://w3c.github.io/setImmediate/#si-clearImmediate
clearImmediate: task.clear
});
/***/ }),
/* 80 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(3);
var apply = __webpack_require__(81);
var bind = __webpack_require__(82);
var isCallable = __webpack_require__(18);
var hasOwn = __webpack_require__(35);
var fails = __webpack_require__(6);
var html = __webpack_require__(66);
var arraySlice = __webpack_require__(83);
var createElement = __webpack_require__(39);
var IS_IOS = __webpack_require__(84);
var IS_NODE = __webpack_require__(85);
var set = global.setImmediate;
var clear = global.clearImmediate;
var process = global.process;
var Dispatch = global.Dispatch;
var Function = global.Function;
var MessageChannel = global.MessageChannel;
var String = global.String;
var counter = 0;
var queue = {};
var ONREADYSTATECHANGE = 'onreadystatechange';
var location, defer, channel, port;
try {
// Deno throws a ReferenceError on `location` access without `--location` flag
location = global.location;
} catch (error) { /* empty */ }
var run = function (id) {
if (hasOwn(queue, id)) {
var fn = queue[id];
delete queue[id];
fn();
}
};
var runner = function (id) {
return function () {
run(id);
};
};
var listener = function (event) {
run(event.data);
};
var post = function (id) {
// old engines have not location.origin
global.postMessage(String(id), location.protocol + '//' + location.host);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if (!set || !clear) {
set = function setImmediate(fn) {
var args = arraySlice(arguments, 1);
queue[++counter] = function () {
apply(isCallable(fn) ? fn : Function(fn), undefined, args);
};
defer(counter);
return counter;
};
clear = function clearImmediate(id) {
delete queue[id];
};
// Node.js 0.8-
if (IS_NODE) {
defer = function (id) {
process.nextTick(runner(id));
};
// Sphere (JS game engine) Dispatch API
} else if (Dispatch && Dispatch.now) {
defer = function (id) {
Dispatch.now(runner(id));
};
// Browsers with MessageChannel, includes WebWorkers
// except iOS - https://github.com/zloirock/core-js/issues/624
} else if (MessageChannel && !IS_IOS) {
channel = new MessageChannel();
port = channel.port2;
channel.port1.onmessage = listener;
defer = bind(port.postMessage, port);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if (
global.addEventListener &&
isCallable(global.postMessage) &&
!global.importScripts &&
location && location.protocol !== 'file:' &&
!fails(post)
) {
defer = post;
global.addEventListener('message', listener, false);
// IE8-
} else if (ONREADYSTATECHANGE in createElement('script')) {
defer = function (id) {
html.appendChild(createElement('script'))[ONREADYSTATECHANGE] = function () {
html.removeChild(this);
run(id);
};
};
// Rest old browsers
} else {
defer = function (id) {
setTimeout(runner(id), 0);
};
}
}
module.exports = {
set: set,
clear: clear
};
/***/ }),
/* 81 */
/***/ (function(module, exports) {
var FunctionPrototype = Function.prototype;
var apply = FunctionPrototype.apply;
var bind = FunctionPrototype.bind;
var call = FunctionPrototype.call;
// eslint-disable-next-line es/no-reflect -- safe
module.exports = typeof Reflect == 'object' && Reflect.apply || (bind ? call.bind(apply) : function () {
return call.apply(apply, arguments);
});
/***/ }),
/* 82 */
/***/ (function(module, exports, __webpack_require__) {
var uncurryThis = __webpack_require__(12);
var aCallable = __webpack_require__(27);
var bind = uncurryThis(uncurryThis.bind);
// optional / simple context binding
module.exports = function (fn, that) {
aCallable(fn);
return that === undefined ? fn : bind ? bind(fn, that) : function (/* ...args */) {
return fn.apply(that, arguments);
};
};
/***/ }),
/* 83 */
/***/ (function(module, exports, __webpack_require__) {
var uncurryThis = __webpack_require__(12);
module.exports = uncurryThis([].slice);
/***/ }),
/* 84 */
/***/ (function(module, exports, __webpack_require__) {
var userAgent = __webpack_require__(25);
module.exports = /(?:ipad|iphone|ipod).*applewebkit/i.test(userAgent);
/***/ }),
/* 85 */
/***/ (function(module, exports, __webpack_require__) {
var classof = __webpack_require__(13);
var global = __webpack_require__(3);
module.exports = classof(global.process) == 'process';
/***/ })
/******/ ]); }(); vendor/wp-polyfill-node-contains.min.js 0000666 00000000541 15123355174 0014210 0 ustar 00 !function(){function e(e){if(!(0 in arguments))throw new TypeError("1 argument is required");do{if(this===e)return!0}while(e=e&&e.parentNode);return!1}if("HTMLElement"in self&&"contains"in HTMLElement.prototype)try{delete HTMLElement.prototype.contains}catch(e){}"Node"in self?Node.prototype.contains=e:document.contains=Element.prototype.contains=e}(); vendor/react.js 0000666 00000326526 15123355174 0007525 0 ustar 00 /**
* @license React
* react.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.React = {}));
}(this, (function (exports) { 'use strict';
var ReactVersion = '18.2.0';
// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
// The Symbol used to tag the ReactElement-like types.
var REACT_ELEMENT_TYPE = Symbol.for('react.element');
var REACT_PORTAL_TYPE = Symbol.for('react.portal');
var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
var REACT_CONTEXT_TYPE = Symbol.for('react.context');
var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
var REACT_MEMO_TYPE = Symbol.for('react.memo');
var REACT_LAZY_TYPE = Symbol.for('react.lazy');
var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');
var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator';
function getIteratorFn(maybeIterable) {
if (maybeIterable === null || typeof maybeIterable !== 'object') {
return null;
}
var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
if (typeof maybeIterator === 'function') {
return maybeIterator;
}
return null;
}
/**
* Keeps track of the current dispatcher.
*/
var ReactCurrentDispatcher = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
/**
* Keeps track of the current batch's configuration such as how long an update
* should suspend for if it needs to.
*/
var ReactCurrentBatchConfig = {
transition: null
};
var ReactCurrentActQueue = {
current: null,
// Used to reproduce behavior of `batchedUpdates` in legacy mode.
isBatchingLegacy: false,
didScheduleLegacyUpdate: false
};
/**
* Keeps track of the current owner.
*
* The current owner is the component who should own any components that are
* currently being constructed.
*/
var ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
var ReactDebugCurrentFrame = {};
var currentExtraStackFrame = null;
function setExtraStackFrame(stack) {
{
currentExtraStackFrame = stack;
}
}
{
ReactDebugCurrentFrame.setExtraStackFrame = function (stack) {
{
currentExtraStackFrame = stack;
}
}; // Stack implementation injected by the current renderer.
ReactDebugCurrentFrame.getCurrentStack = null;
ReactDebugCurrentFrame.getStackAddendum = function () {
var stack = ''; // Add an extra top frame while an element is being validated
if (currentExtraStackFrame) {
stack += currentExtraStackFrame;
} // Delegate to the injected renderer-specific implementation
var impl = ReactDebugCurrentFrame.getCurrentStack;
if (impl) {
stack += impl() || '';
}
return stack;
};
}
// -----------------------------------------------------------------------------
var enableScopeAPI = false; // Experimental Create Event Handle API.
var enableCacheElement = false;
var enableTransitionTracing = false; // No known bugs, but needs performance testing
var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber
// stuff. Intended to enable React core members to more easily debug scheduling
// issues in DEV builds.
var enableDebugTracing = false; // Track which Fiber(s) schedule render work.
var ReactSharedInternals = {
ReactCurrentDispatcher: ReactCurrentDispatcher,
ReactCurrentBatchConfig: ReactCurrentBatchConfig,
ReactCurrentOwner: ReactCurrentOwner
};
{
ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue;
}
// by calls to these methods by a Babel plugin.
//
// In PROD (or in packages without access to React internals),
// they are left as they are instead.
function warn(format) {
{
{
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
printWarning('warn', format, args);
}
}
}
function error(format) {
{
{
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
printWarning('error', format, args);
}
}
}
function printWarning(level, format, args) {
// When changing this logic, you might want to also
// update consoleWithStackDev.www.js as well.
{
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
var stack = ReactDebugCurrentFrame.getStackAddendum();
if (stack !== '') {
format += '%s';
args = args.concat([stack]);
} // eslint-disable-next-line react-internal/safe-string-coercion
var argsWithFormat = args.map(function (item) {
return String(item);
}); // Careful: RN currently depends on this prefix
argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
// breaks IE9: https://github.com/facebook/react/issues/13610
// eslint-disable-next-line react-internal/no-production-logging
Function.prototype.apply.call(console[level], console, argsWithFormat);
}
}
var didWarnStateUpdateForUnmountedComponent = {};
function warnNoop(publicInstance, callerName) {
{
var _constructor = publicInstance.constructor;
var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass';
var warningKey = componentName + "." + callerName;
if (didWarnStateUpdateForUnmountedComponent[warningKey]) {
return;
}
error("Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName);
didWarnStateUpdateForUnmountedComponent[warningKey] = true;
}
}
/**
* This is the abstract API for an update queue.
*/
var ReactNoopUpdateQueue = {
/**
* Checks whether or not this composite component is mounted.
* @param {ReactClass} publicInstance The instance we want to test.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function (publicInstance) {
return false;
},
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {?function} callback Called after component is updated.
* @param {?string} callerName name of the calling function in the public API.
* @internal
*/
enqueueForceUpdate: function (publicInstance, callback, callerName) {
warnNoop(publicInstance, 'forceUpdate');
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} completeState Next state.
* @param {?function} callback Called after component is updated.
* @param {?string} callerName name of the calling function in the public API.
* @internal
*/
enqueueReplaceState: function (publicInstance, completeState, callback, callerName) {
warnNoop(publicInstance, 'replaceState');
},
/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialState Next partial state to be merged with state.
* @param {?function} callback Called after component is updated.
* @param {?string} Name of the calling function in the public API.
* @internal
*/
enqueueSetState: function (publicInstance, partialState, callback, callerName) {
warnNoop(publicInstance, 'setState');
}
};
var assign = Object.assign;
var emptyObject = {};
{
Object.freeze(emptyObject);
}
/**
* Base class helpers for the updating state of a component.
*/
function Component(props, context, updater) {
this.props = props;
this.context = context; // If a component has string refs, we will assign a different object later.
this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the
// renderer.
this.updater = updater || ReactNoopUpdateQueue;
}
Component.prototype.isReactComponent = {};
/**
* Sets a subset of the state. Always use this to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* There is no guarantee that calls to `setState` will run synchronously,
* as they may eventually be batched together. You can provide an optional
* callback that will be executed when the call to setState is actually
* completed.
*
* When a function is provided to setState, it will be called at some point in
* the future (not synchronously). It will be called with the up to date
* component arguments (state, props, context). These values can be different
* from this.* because your function may be called after receiveProps but before
* shouldComponentUpdate, and this new state, props, and context will not yet be
* assigned to this.
*
* @param {object|function} partialState Next partial state or function to
* produce next partial state to be merged with current state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
Component.prototype.setState = function (partialState, callback) {
if (typeof partialState !== 'object' && typeof partialState !== 'function' && partialState != null) {
throw new Error('setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.');
}
this.updater.enqueueSetState(this, partialState, callback, 'setState');
};
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/
Component.prototype.forceUpdate = function (callback) {
this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
};
/**
* Deprecated APIs. These APIs used to exist on classic React classes but since
* we would like to deprecate them, we're not going to move them over to this
* modern base class. Instead, we define a getter that warns if it's accessed.
*/
{
var deprecatedAPIs = {
isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).']
};
var defineDeprecationWarning = function (methodName, info) {
Object.defineProperty(Component.prototype, methodName, {
get: function () {
warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]);
return undefined;
}
});
};
for (var fnName in deprecatedAPIs) {
if (deprecatedAPIs.hasOwnProperty(fnName)) {
defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
}
}
}
function ComponentDummy() {}
ComponentDummy.prototype = Component.prototype;
/**
* Convenience component with default shallow equality check for sCU.
*/
function PureComponent(props, context, updater) {
this.props = props;
this.context = context; // If a component has string refs, we will assign a different object later.
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
}
var pureComponentPrototype = PureComponent.prototype = new ComponentDummy();
pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods.
assign(pureComponentPrototype, Component.prototype);
pureComponentPrototype.isPureReactComponent = true;
// an immutable object with a single mutable value
function createRef() {
var refObject = {
current: null
};
{
Object.seal(refObject);
}
return refObject;
}
var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
function isArray(a) {
return isArrayImpl(a);
}
/*
* The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
* and Temporal.* types. See https://github.com/facebook/react/pull/22064.
*
* The functions in this module will throw an easier-to-understand,
* easier-to-debug exception with a clear errors message message explaining the
* problem. (Instead of a confusing exception thrown inside the implementation
* of the `value` object).
*/
// $FlowFixMe only called in DEV, so void return is not possible.
function typeName(value) {
{
// toStringTag is needed for namespaced types like Temporal.Instant
var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
return type;
}
} // $FlowFixMe only called in DEV, so void return is not possible.
function willCoercionThrow(value) {
{
try {
testStringCoercion(value);
return false;
} catch (e) {
return true;
}
}
}
function testStringCoercion(value) {
// If you ended up here by following an exception call stack, here's what's
// happened: you supplied an object or symbol value to React (as a prop, key,
// DOM attribute, CSS property, string ref, etc.) and when React tried to
// coerce it to a string using `'' + value`, an exception was thrown.
//
// The most common types that will cause this exception are `Symbol` instances
// and Temporal objects like `Temporal.Instant`. But any object that has a
// `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
// exception. (Library authors do this to prevent users from using built-in
// numeric operators like `+` or comparison operators like `>=` because custom
// methods are needed to perform accurate arithmetic or comparison.)
//
// To fix the problem, coerce this object or symbol value to a string before
// passing it to React. The most reliable way is usually `String(value)`.
//
// To find which value is throwing, check the browser or debugger console.
// Before this exception was thrown, there should be `console.error` output
// that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
// problem and how that type was used: key, atrribute, input value prop, etc.
// In most cases, this console output also shows the component and its
// ancestor components where the exception happened.
//
// eslint-disable-next-line react-internal/safe-string-coercion
return '' + value;
}
function checkKeyStringCoercion(value) {
{
if (willCoercionThrow(value)) {
error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));
return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
}
}
}
function getWrappedName(outerType, innerType, wrapperName) {
var displayName = outerType.displayName;
if (displayName) {
return displayName;
}
var functionName = innerType.displayName || innerType.name || '';
return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
} // Keep in sync with react-reconciler/getComponentNameFromFiber
function getContextName(type) {
return type.displayName || 'Context';
} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.
function getComponentNameFromType(type) {
if (type == null) {
// Host root, text node or just invalid type.
return null;
}
{
if (typeof type.tag === 'number') {
error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
}
}
if (typeof type === 'function') {
return type.displayName || type.name || null;
}
if (typeof type === 'string') {
return type;
}
switch (type) {
case REACT_FRAGMENT_TYPE:
return 'Fragment';
case REACT_PORTAL_TYPE:
return 'Portal';
case REACT_PROFILER_TYPE:
return 'Profiler';
case REACT_STRICT_MODE_TYPE:
return 'StrictMode';
case REACT_SUSPENSE_TYPE:
return 'Suspense';
case REACT_SUSPENSE_LIST_TYPE:
return 'SuspenseList';
}
if (typeof type === 'object') {
switch (type.$$typeof) {
case REACT_CONTEXT_TYPE:
var context = type;
return getContextName(context) + '.Consumer';
case REACT_PROVIDER_TYPE:
var provider = type;
return getContextName(provider._context) + '.Provider';
case REACT_FORWARD_REF_TYPE:
return getWrappedName(type, type.render, 'ForwardRef');
case REACT_MEMO_TYPE:
var outerName = type.displayName || null;
if (outerName !== null) {
return outerName;
}
return getComponentNameFromType(type.type) || 'Memo';
case REACT_LAZY_TYPE:
{
var lazyComponent = type;
var payload = lazyComponent._payload;
var init = lazyComponent._init;
try {
return getComponentNameFromType(init(payload));
} catch (x) {
return null;
}
}
// eslint-disable-next-line no-fallthrough
}
}
return null;
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
var RESERVED_PROPS = {
key: true,
ref: true,
__self: true,
__source: true
};
var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs;
{
didWarnAboutStringRefs = {};
}
function hasValidRef(config) {
{
if (hasOwnProperty.call(config, 'ref')) {
var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.ref !== undefined;
}
function hasValidKey(config) {
{
if (hasOwnProperty.call(config, 'key')) {
var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.key !== undefined;
}
function defineKeyPropWarningGetter(props, displayName) {
var warnAboutAccessingKey = function () {
{
if (!specialPropKeyWarningShown) {
specialPropKeyWarningShown = true;
error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
}
}
};
warnAboutAccessingKey.isReactWarning = true;
Object.defineProperty(props, 'key', {
get: warnAboutAccessingKey,
configurable: true
});
}
function defineRefPropWarningGetter(props, displayName) {
var warnAboutAccessingRef = function () {
{
if (!specialPropRefWarningShown) {
specialPropRefWarningShown = true;
error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
}
}
};
warnAboutAccessingRef.isReactWarning = true;
Object.defineProperty(props, 'ref', {
get: warnAboutAccessingRef,
configurable: true
});
}
function warnIfStringRefCannotBeAutoConverted(config) {
{
if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) {
var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);
if (!didWarnAboutStringRefs[componentName]) {
error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref);
didWarnAboutStringRefs[componentName] = true;
}
}
}
}
/**
* Factory method to create a new React element. This no longer adheres to
* the class pattern, so do not use new to call it. Also, instanceof check
* will not work. Instead test $$typeof field against Symbol.for('react.element') to check
* if something is a React Element.
*
* @param {*} type
* @param {*} props
* @param {*} key
* @param {string|object} ref
* @param {*} owner
* @param {*} self A *temporary* helper to detect places where `this` is
* different from the `owner` when React.createElement is called, so that we
* can warn. We want to get rid of owner and replace string `ref`s with arrow
* functions, and as long as `this` and owner are the same, there will be no
* change in behavior.
* @param {*} source An annotation object (added by a transpiler or otherwise)
* indicating filename, line number, and/or other information.
* @internal
*/
var ReactElement = function (type, key, ref, self, source, owner, props) {
var element = {
// This tag allows us to uniquely identify this as a React Element
$$typeof: REACT_ELEMENT_TYPE,
// Built-in properties that belong on the element
type: type,
key: key,
ref: ref,
props: props,
// Record the component responsible for creating this element.
_owner: owner
};
{
// The validation flag is currently mutative. We put it on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
Object.defineProperty(element._store, 'validated', {
configurable: false,
enumerable: false,
writable: true,
value: false
}); // self and source are DEV only properties.
Object.defineProperty(element, '_self', {
configurable: false,
enumerable: false,
writable: false,
value: self
}); // Two elements created in two different places should be considered
// equal for testing purposes and therefore we hide it from enumeration.
Object.defineProperty(element, '_source', {
configurable: false,
enumerable: false,
writable: false,
value: source
});
if (Object.freeze) {
Object.freeze(element.props);
Object.freeze(element);
}
}
return element;
};
/**
* Create and return a new ReactElement of the given type.
* See https://reactjs.org/docs/react-api.html#createelement
*/
function createElement(type, config, children) {
var propName; // Reserved names are extracted
var props = {};
var key = null;
var ref = null;
var self = null;
var source = null;
if (config != null) {
if (hasValidRef(config)) {
ref = config.ref;
{
warnIfStringRefCannotBeAutoConverted(config);
}
}
if (hasValidKey(config)) {
{
checkKeyStringCoercion(config.key);
}
key = '' + config.key;
}
self = config.__self === undefined ? null : config.__self;
source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object
for (propName in config) {
if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
}
} // Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
{
if (Object.freeze) {
Object.freeze(childArray);
}
}
props.children = childArray;
} // Resolve default props
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (props[propName] === undefined) {
props[propName] = defaultProps[propName];
}
}
}
{
if (key || ref) {
var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
if (key) {
defineKeyPropWarningGetter(props, displayName);
}
if (ref) {
defineRefPropWarningGetter(props, displayName);
}
}
}
return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
}
function cloneAndReplaceKey(oldElement, newKey) {
var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
return newElement;
}
/**
* Clone and return a new ReactElement using element as the starting point.
* See https://reactjs.org/docs/react-api.html#cloneelement
*/
function cloneElement(element, config, children) {
if (element === null || element === undefined) {
throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + ".");
}
var propName; // Original props are copied
var props = assign({}, element.props); // Reserved names are extracted
var key = element.key;
var ref = element.ref; // Self is preserved since the owner is preserved.
var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a
// transpiler, and the original source is probably a better indicator of the
// true owner.
var source = element._source; // Owner will be preserved, unless ref is overridden
var owner = element._owner;
if (config != null) {
if (hasValidRef(config)) {
// Silently steal the ref from the parent.
ref = config.ref;
owner = ReactCurrentOwner.current;
}
if (hasValidKey(config)) {
{
checkKeyStringCoercion(config.key);
}
key = '' + config.key;
} // Remaining properties override existing props
var defaultProps;
if (element.type && element.type.defaultProps) {
defaultProps = element.type.defaultProps;
}
for (propName in config) {
if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
if (config[propName] === undefined && defaultProps !== undefined) {
// Resolve default props
props[propName] = defaultProps[propName];
} else {
props[propName] = config[propName];
}
}
}
} // Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
props.children = childArray;
}
return ReactElement(element.type, key, ref, self, source, owner, props);
}
/**
* Verifies the object is a ReactElement.
* See https://reactjs.org/docs/react-api.html#isvalidelement
* @param {?object} object
* @return {boolean} True if `object` is a ReactElement.
* @final
*/
function isValidElement(object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
var SEPARATOR = '.';
var SUBSEPARATOR = ':';
/**
* Escape and wrap key so it is safe to use as a reactid
*
* @param {string} key to be escaped.
* @return {string} the escaped key.
*/
function escape(key) {
var escapeRegex = /[=:]/g;
var escaperLookup = {
'=': '=0',
':': '=2'
};
var escapedString = key.replace(escapeRegex, function (match) {
return escaperLookup[match];
});
return '$' + escapedString;
}
/**
* TODO: Test that a single child and an array with one item have the same key
* pattern.
*/
var didWarnAboutMaps = false;
var userProvidedKeyEscapeRegex = /\/+/g;
function escapeUserProvidedKey(text) {
return text.replace(userProvidedKeyEscapeRegex, '$&/');
}
/**
* Generate a key string that identifies a element within a set.
*
* @param {*} element A element that could contain a manual key.
* @param {number} index Index that is used if a manual key is not provided.
* @return {string}
*/
function getElementKey(element, index) {
// Do some typechecking here since we call this blindly. We want to ensure
// that we don't block potential future ES APIs.
if (typeof element === 'object' && element !== null && element.key != null) {
// Explicit key
{
checkKeyStringCoercion(element.key);
}
return escape('' + element.key);
} // Implicit key determined by the index in the set
return index.toString(36);
}
function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
var type = typeof children;
if (type === 'undefined' || type === 'boolean') {
// All of the above are perceived as null.
children = null;
}
var invokeCallback = false;
if (children === null) {
invokeCallback = true;
} else {
switch (type) {
case 'string':
case 'number':
invokeCallback = true;
break;
case 'object':
switch (children.$$typeof) {
case REACT_ELEMENT_TYPE:
case REACT_PORTAL_TYPE:
invokeCallback = true;
}
}
}
if (invokeCallback) {
var _child = children;
var mappedChild = callback(_child); // If it's the only child, treat the name as if it was wrapped in an array
// so that it's consistent if the number of children grows:
var childKey = nameSoFar === '' ? SEPARATOR + getElementKey(_child, 0) : nameSoFar;
if (isArray(mappedChild)) {
var escapedChildKey = '';
if (childKey != null) {
escapedChildKey = escapeUserProvidedKey(childKey) + '/';
}
mapIntoArray(mappedChild, array, escapedChildKey, '', function (c) {
return c;
});
} else if (mappedChild != null) {
if (isValidElement(mappedChild)) {
{
// The `if` statement here prevents auto-disabling of the safe
// coercion ESLint rule, so we must manually disable it below.
// $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) {
checkKeyStringCoercion(mappedChild.key);
}
}
mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as
// traverseAllChildren used to do for objects as children
escapedPrefix + ( // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
mappedChild.key && (!_child || _child.key !== mappedChild.key) ? // $FlowFixMe Flow incorrectly thinks existing element's key can be a number
// eslint-disable-next-line react-internal/safe-string-coercion
escapeUserProvidedKey('' + mappedChild.key) + '/' : '') + childKey);
}
array.push(mappedChild);
}
return 1;
}
var child;
var nextName;
var subtreeCount = 0; // Count of children found in the current subtree.
var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;
if (isArray(children)) {
for (var i = 0; i < children.length; i++) {
child = children[i];
nextName = nextNamePrefix + getElementKey(child, i);
subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
}
} else {
var iteratorFn = getIteratorFn(children);
if (typeof iteratorFn === 'function') {
var iterableChildren = children;
{
// Warn about using Maps as children
if (iteratorFn === iterableChildren.entries) {
if (!didWarnAboutMaps) {
warn('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
}
didWarnAboutMaps = true;
}
}
var iterator = iteratorFn.call(iterableChildren);
var step;
var ii = 0;
while (!(step = iterator.next()).done) {
child = step.value;
nextName = nextNamePrefix + getElementKey(child, ii++);
subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
}
} else if (type === 'object') {
// eslint-disable-next-line react-internal/safe-string-coercion
var childrenString = String(children);
throw new Error("Objects are not valid as a React child (found: " + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.');
}
}
return subtreeCount;
}
/**
* Maps children that are typically specified as `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenmap
*
* The provided mapFunction(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func The map function.
* @param {*} context Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/
function mapChildren(children, func, context) {
if (children == null) {
return children;
}
var result = [];
var count = 0;
mapIntoArray(children, result, '', '', function (child) {
return func.call(context, child, count++);
});
return result;
}
/**
* Count the number of children that are typically specified as
* `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrencount
*
* @param {?*} children Children tree container.
* @return {number} The number of children.
*/
function countChildren(children) {
var n = 0;
mapChildren(children, function () {
n++; // Don't return anything
});
return n;
}
/**
* Iterates through children that are typically specified as `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenforeach
*
* The provided forEachFunc(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} forEachFunc
* @param {*} forEachContext Context for forEachContext.
*/
function forEachChildren(children, forEachFunc, forEachContext) {
mapChildren(children, function () {
forEachFunc.apply(this, arguments); // Don't return anything.
}, forEachContext);
}
/**
* Flatten a children object (typically specified as `props.children`) and
* return an array with appropriately re-keyed children.
*
* See https://reactjs.org/docs/react-api.html#reactchildrentoarray
*/
function toArray(children) {
return mapChildren(children, function (child) {
return child;
}) || [];
}
/**
* Returns the first child in a collection of children and verifies that there
* is only one child in the collection.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenonly
*
* The current implementation of this function assumes that a single child gets
* passed without a wrapper, but the purpose of this helper function is to
* abstract away the particular structure of children.
*
* @param {?object} children Child collection structure.
* @return {ReactElement} The first and only `ReactElement` contained in the
* structure.
*/
function onlyChild(children) {
if (!isValidElement(children)) {
throw new Error('React.Children.only expected to receive a single React element child.');
}
return children;
}
function createContext(defaultValue) {
// TODO: Second argument used to be an optional `calculateChangedBits`
// function. Warn to reserve for future use?
var context = {
$$typeof: REACT_CONTEXT_TYPE,
// As a workaround to support multiple concurrent renderers, we categorize
// some renderers as primary and others as secondary. We only expect
// there to be two concurrent renderers at most: React Native (primary) and
// Fabric (secondary); React DOM (primary) and React ART (secondary).
// Secondary renderers store their context values on separate fields.
_currentValue: defaultValue,
_currentValue2: defaultValue,
// Used to track how many concurrent renderers this context currently
// supports within in a single renderer. Such as parallel server rendering.
_threadCount: 0,
// These are circular
Provider: null,
Consumer: null,
// Add these to use same hidden class in VM as ServerContext
_defaultValue: null,
_globalName: null
};
context.Provider = {
$$typeof: REACT_PROVIDER_TYPE,
_context: context
};
var hasWarnedAboutUsingNestedContextConsumers = false;
var hasWarnedAboutUsingConsumerProvider = false;
var hasWarnedAboutDisplayNameOnConsumer = false;
{
// A separate object, but proxies back to the original context object for
// backwards compatibility. It has a different $$typeof, so we can properly
// warn for the incorrect usage of Context as a Consumer.
var Consumer = {
$$typeof: REACT_CONTEXT_TYPE,
_context: context
}; // $FlowFixMe: Flow complains about not setting a value, which is intentional here
Object.defineProperties(Consumer, {
Provider: {
get: function () {
if (!hasWarnedAboutUsingConsumerProvider) {
hasWarnedAboutUsingConsumerProvider = true;
error('Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?');
}
return context.Provider;
},
set: function (_Provider) {
context.Provider = _Provider;
}
},
_currentValue: {
get: function () {
return context._currentValue;
},
set: function (_currentValue) {
context._currentValue = _currentValue;
}
},
_currentValue2: {
get: function () {
return context._currentValue2;
},
set: function (_currentValue2) {
context._currentValue2 = _currentValue2;
}
},
_threadCount: {
get: function () {
return context._threadCount;
},
set: function (_threadCount) {
context._threadCount = _threadCount;
}
},
Consumer: {
get: function () {
if (!hasWarnedAboutUsingNestedContextConsumers) {
hasWarnedAboutUsingNestedContextConsumers = true;
error('Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
}
return context.Consumer;
}
},
displayName: {
get: function () {
return context.displayName;
},
set: function (displayName) {
if (!hasWarnedAboutDisplayNameOnConsumer) {
warn('Setting `displayName` on Context.Consumer has no effect. ' + "You should set it directly on the context with Context.displayName = '%s'.", displayName);
hasWarnedAboutDisplayNameOnConsumer = true;
}
}
}
}); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty
context.Consumer = Consumer;
}
{
context._currentRenderer = null;
context._currentRenderer2 = null;
}
return context;
}
var Uninitialized = -1;
var Pending = 0;
var Resolved = 1;
var Rejected = 2;
function lazyInitializer(payload) {
if (payload._status === Uninitialized) {
var ctor = payload._result;
var thenable = ctor(); // Transition to the next state.
// This might throw either because it's missing or throws. If so, we treat it
// as still uninitialized and try again next time. Which is the same as what
// happens if the ctor or any wrappers processing the ctor throws. This might
// end up fixing it if the resolution was a concurrency bug.
thenable.then(function (moduleObject) {
if (payload._status === Pending || payload._status === Uninitialized) {
// Transition to the next state.
var resolved = payload;
resolved._status = Resolved;
resolved._result = moduleObject;
}
}, function (error) {
if (payload._status === Pending || payload._status === Uninitialized) {
// Transition to the next state.
var rejected = payload;
rejected._status = Rejected;
rejected._result = error;
}
});
if (payload._status === Uninitialized) {
// In case, we're still uninitialized, then we're waiting for the thenable
// to resolve. Set it as pending in the meantime.
var pending = payload;
pending._status = Pending;
pending._result = thenable;
}
}
if (payload._status === Resolved) {
var moduleObject = payload._result;
{
if (moduleObject === undefined) {
error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies.
'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))\n\n" + 'Did you accidentally put curly braces around the import?', moduleObject);
}
}
{
if (!('default' in moduleObject)) {
error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies.
'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))", moduleObject);
}
}
return moduleObject.default;
} else {
throw payload._result;
}
}
function lazy(ctor) {
var payload = {
// We use these fields to store the result.
_status: Uninitialized,
_result: ctor
};
var lazyType = {
$$typeof: REACT_LAZY_TYPE,
_payload: payload,
_init: lazyInitializer
};
{
// In production, this would just set it on the object.
var defaultProps;
var propTypes; // $FlowFixMe
Object.defineProperties(lazyType, {
defaultProps: {
configurable: true,
get: function () {
return defaultProps;
},
set: function (newDefaultProps) {
error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
defaultProps = newDefaultProps; // Match production behavior more closely:
// $FlowFixMe
Object.defineProperty(lazyType, 'defaultProps', {
enumerable: true
});
}
},
propTypes: {
configurable: true,
get: function () {
return propTypes;
},
set: function (newPropTypes) {
error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
propTypes = newPropTypes; // Match production behavior more closely:
// $FlowFixMe
Object.defineProperty(lazyType, 'propTypes', {
enumerable: true
});
}
}
});
}
return lazyType;
}
function forwardRef(render) {
{
if (render != null && render.$$typeof === REACT_MEMO_TYPE) {
error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).');
} else if (typeof render !== 'function') {
error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render);
} else {
if (render.length !== 0 && render.length !== 2) {
error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.');
}
}
if (render != null) {
if (render.defaultProps != null || render.propTypes != null) {
error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?');
}
}
}
var elementType = {
$$typeof: REACT_FORWARD_REF_TYPE,
render: render
};
{
var ownName;
Object.defineProperty(elementType, 'displayName', {
enumerable: false,
configurable: true,
get: function () {
return ownName;
},
set: function (name) {
ownName = name; // The inner component shouldn't inherit this display name in most cases,
// because the component may be used elsewhere.
// But it's nice for anonymous functions to inherit the name,
// so that our component-stack generation logic will display their frames.
// An anonymous function generally suggests a pattern like:
// React.forwardRef((props, ref) => {...});
// This kind of inner function is not used elsewhere so the side effect is okay.
if (!render.name && !render.displayName) {
render.displayName = name;
}
}
});
}
return elementType;
}
var REACT_MODULE_REFERENCE;
{
REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');
}
function isValidElementType(type) {
if (typeof type === 'string' || typeof type === 'function') {
return true;
} // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).
if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing ) {
return true;
}
if (typeof type === 'object' && type !== null) {
if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
// types supported by any Flight configuration anywhere since
// we don't know which Flight build this will end up being used
// with.
type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {
return true;
}
}
return false;
}
function memo(type, compare) {
{
if (!isValidElementType(type)) {
error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type);
}
}
var elementType = {
$$typeof: REACT_MEMO_TYPE,
type: type,
compare: compare === undefined ? null : compare
};
{
var ownName;
Object.defineProperty(elementType, 'displayName', {
enumerable: false,
configurable: true,
get: function () {
return ownName;
},
set: function (name) {
ownName = name; // The inner component shouldn't inherit this display name in most cases,
// because the component may be used elsewhere.
// But it's nice for anonymous functions to inherit the name,
// so that our component-stack generation logic will display their frames.
// An anonymous function generally suggests a pattern like:
// React.memo((props) => {...});
// This kind of inner function is not used elsewhere so the side effect is okay.
if (!type.name && !type.displayName) {
type.displayName = name;
}
}
});
}
return elementType;
}
function resolveDispatcher() {
var dispatcher = ReactCurrentDispatcher.current;
{
if (dispatcher === null) {
error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');
}
} // Will result in a null access error if accessed outside render phase. We
// intentionally don't throw our own error because this is in a hot path.
// Also helps ensure this is inlined.
return dispatcher;
}
function useContext(Context) {
var dispatcher = resolveDispatcher();
{
// TODO: add a more generic warning for invalid values.
if (Context._context !== undefined) {
var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs
// and nobody should be using this in existing code.
if (realContext.Consumer === Context) {
error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?');
} else if (realContext.Provider === Context) {
error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?');
}
}
}
return dispatcher.useContext(Context);
}
function useState(initialState) {
var dispatcher = resolveDispatcher();
return dispatcher.useState(initialState);
}
function useReducer(reducer, initialArg, init) {
var dispatcher = resolveDispatcher();
return dispatcher.useReducer(reducer, initialArg, init);
}
function useRef(initialValue) {
var dispatcher = resolveDispatcher();
return dispatcher.useRef(initialValue);
}
function useEffect(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useEffect(create, deps);
}
function useInsertionEffect(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useInsertionEffect(create, deps);
}
function useLayoutEffect(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useLayoutEffect(create, deps);
}
function useCallback(callback, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useCallback(callback, deps);
}
function useMemo(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useMemo(create, deps);
}
function useImperativeHandle(ref, create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useImperativeHandle(ref, create, deps);
}
function useDebugValue(value, formatterFn) {
{
var dispatcher = resolveDispatcher();
return dispatcher.useDebugValue(value, formatterFn);
}
}
function useTransition() {
var dispatcher = resolveDispatcher();
return dispatcher.useTransition();
}
function useDeferredValue(value) {
var dispatcher = resolveDispatcher();
return dispatcher.useDeferredValue(value);
}
function useId() {
var dispatcher = resolveDispatcher();
return dispatcher.useId();
}
function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
var dispatcher = resolveDispatcher();
return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
}
// Helpers to patch console.logs to avoid logging during side-effect free
// replaying on render function. This currently only patches the object
// lazily which won't cover if the log function was extracted eagerly.
// We could also eagerly patch the method.
var disabledDepth = 0;
var prevLog;
var prevInfo;
var prevWarn;
var prevError;
var prevGroup;
var prevGroupCollapsed;
var prevGroupEnd;
function disabledLog() {}
disabledLog.__reactDisabledLog = true;
function disableLogs() {
{
if (disabledDepth === 0) {
/* eslint-disable react-internal/no-production-logging */
prevLog = console.log;
prevInfo = console.info;
prevWarn = console.warn;
prevError = console.error;
prevGroup = console.group;
prevGroupCollapsed = console.groupCollapsed;
prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099
var props = {
configurable: true,
enumerable: true,
value: disabledLog,
writable: true
}; // $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console, {
info: props,
log: props,
warn: props,
error: props,
group: props,
groupCollapsed: props,
groupEnd: props
});
/* eslint-enable react-internal/no-production-logging */
}
disabledDepth++;
}
}
function reenableLogs() {
{
disabledDepth--;
if (disabledDepth === 0) {
/* eslint-disable react-internal/no-production-logging */
var props = {
configurable: true,
enumerable: true,
writable: true
}; // $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console, {
log: assign({}, props, {
value: prevLog
}),
info: assign({}, props, {
value: prevInfo
}),
warn: assign({}, props, {
value: prevWarn
}),
error: assign({}, props, {
value: prevError
}),
group: assign({}, props, {
value: prevGroup
}),
groupCollapsed: assign({}, props, {
value: prevGroupCollapsed
}),
groupEnd: assign({}, props, {
value: prevGroupEnd
})
});
/* eslint-enable react-internal/no-production-logging */
}
if (disabledDepth < 0) {
error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
}
}
}
var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
var prefix;
function describeBuiltInComponentFrame(name, source, ownerFn) {
{
if (prefix === undefined) {
// Extract the VM specific prefix used by each line.
try {
throw Error();
} catch (x) {
var match = x.stack.trim().match(/\n( *(at )?)/);
prefix = match && match[1] || '';
}
} // We use the prefix to ensure our stacks line up with native stack frames.
return '\n' + prefix + name;
}
}
var reentry = false;
var componentFrameCache;
{
var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
componentFrameCache = new PossiblyWeakMap();
}
function describeNativeComponentFrame(fn, construct) {
// If something asked for a stack inside a fake render, it should get ignored.
if ( !fn || reentry) {
return '';
}
{
var frame = componentFrameCache.get(fn);
if (frame !== undefined) {
return frame;
}
}
var control;
reentry = true;
var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.
Error.prepareStackTrace = undefined;
var previousDispatcher;
{
previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function
// for warnings.
ReactCurrentDispatcher$1.current = null;
disableLogs();
}
try {
// This should throw.
if (construct) {
// Something should be setting the props in the constructor.
var Fake = function () {
throw Error();
}; // $FlowFixMe
Object.defineProperty(Fake.prototype, 'props', {
set: function () {
// We use a throwing setter instead of frozen or non-writable props
// because that won't throw in a non-strict mode function.
throw Error();
}
});
if (typeof Reflect === 'object' && Reflect.construct) {
// We construct a different control for this case to include any extra
// frames added by the construct call.
try {
Reflect.construct(Fake, []);
} catch (x) {
control = x;
}
Reflect.construct(fn, [], Fake);
} else {
try {
Fake.call();
} catch (x) {
control = x;
}
fn.call(Fake.prototype);
}
} else {
try {
throw Error();
} catch (x) {
control = x;
}
fn();
}
} catch (sample) {
// This is inlined manually because closure doesn't do it for us.
if (sample && control && typeof sample.stack === 'string') {
// This extracts the first frame from the sample that isn't also in the control.
// Skipping one frame that we assume is the frame that calls the two.
var sampleLines = sample.stack.split('\n');
var controlLines = control.stack.split('\n');
var s = sampleLines.length - 1;
var c = controlLines.length - 1;
while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
// We expect at least one stack frame to be shared.
// Typically this will be the root most one. However, stack frames may be
// cut off due to maximum stack limits. In this case, one maybe cut off
// earlier than the other. We assume that the sample is longer or the same
// and there for cut off earlier. So we should find the root most frame in
// the sample somewhere in the control.
c--;
}
for (; s >= 1 && c >= 0; s--, c--) {
// Next we find the first one that isn't the same which should be the
// frame that called our sample function and the control.
if (sampleLines[s] !== controlLines[c]) {
// In V8, the first line is describing the message but other VMs don't.
// If we're about to return the first line, and the control is also on the same
// line, that's a pretty good indicator that our sample threw at same line as
// the control. I.e. before we entered the sample frame. So we ignore this result.
// This can happen if you passed a class to function component, or non-function.
if (s !== 1 || c !== 1) {
do {
s--;
c--; // We may still have similar intermediate frames from the construct call.
// The next one that isn't the same should be our match though.
if (c < 0 || sampleLines[s] !== controlLines[c]) {
// V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
// but we have a user-provided "displayName"
// splice it in to make the stack more readable.
if (fn.displayName && _frame.includes('<anonymous>')) {
_frame = _frame.replace('<anonymous>', fn.displayName);
}
{
if (typeof fn === 'function') {
componentFrameCache.set(fn, _frame);
}
} // Return the line we found.
return _frame;
}
} while (s >= 1 && c >= 0);
}
break;
}
}
}
} finally {
reentry = false;
{
ReactCurrentDispatcher$1.current = previousDispatcher;
reenableLogs();
}
Error.prepareStackTrace = previousPrepareStackTrace;
} // Fallback to just using the name if we couldn't make it throw.
var name = fn ? fn.displayName || fn.name : '';
var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
{
if (typeof fn === 'function') {
componentFrameCache.set(fn, syntheticFrame);
}
}
return syntheticFrame;
}
function describeFunctionComponentFrame(fn, source, ownerFn) {
{
return describeNativeComponentFrame(fn, false);
}
}
function shouldConstruct(Component) {
var prototype = Component.prototype;
return !!(prototype && prototype.isReactComponent);
}
function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
if (type == null) {
return '';
}
if (typeof type === 'function') {
{
return describeNativeComponentFrame(type, shouldConstruct(type));
}
}
if (typeof type === 'string') {
return describeBuiltInComponentFrame(type);
}
switch (type) {
case REACT_SUSPENSE_TYPE:
return describeBuiltInComponentFrame('Suspense');
case REACT_SUSPENSE_LIST_TYPE:
return describeBuiltInComponentFrame('SuspenseList');
}
if (typeof type === 'object') {
switch (type.$$typeof) {
case REACT_FORWARD_REF_TYPE:
return describeFunctionComponentFrame(type.render);
case REACT_MEMO_TYPE:
// Memo may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
case REACT_LAZY_TYPE:
{
var lazyComponent = type;
var payload = lazyComponent._payload;
var init = lazyComponent._init;
try {
// Lazy may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
} catch (x) {}
}
}
}
return '';
}
var loggedTypeFailures = {};
var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
function setCurrentlyValidatingElement(element) {
{
if (element) {
var owner = element._owner;
var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
} else {
ReactDebugCurrentFrame$1.setExtraStackFrame(null);
}
}
}
function checkPropTypes(typeSpecs, values, location, componentName, element) {
{
// $FlowFixMe This is okay but Flow doesn't know it.
var has = Function.call.bind(hasOwnProperty);
for (var typeSpecName in typeSpecs) {
if (has(typeSpecs, typeSpecName)) {
var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
if (typeof typeSpecs[typeSpecName] !== 'function') {
// eslint-disable-next-line react-internal/prod-error-codes
var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
err.name = 'Invariant Violation';
throw err;
}
error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
} catch (ex) {
error$1 = ex;
}
if (error$1 && !(error$1 instanceof Error)) {
setCurrentlyValidatingElement(element);
error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);
setCurrentlyValidatingElement(null);
}
if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error$1.message] = true;
setCurrentlyValidatingElement(element);
error('Failed %s type: %s', location, error$1.message);
setCurrentlyValidatingElement(null);
}
}
}
}
}
function setCurrentlyValidatingElement$1(element) {
{
if (element) {
var owner = element._owner;
var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
setExtraStackFrame(stack);
} else {
setExtraStackFrame(null);
}
}
}
var propTypesMisspellWarningShown;
{
propTypesMisspellWarningShown = false;
}
function getDeclarationErrorAddendum() {
if (ReactCurrentOwner.current) {
var name = getComponentNameFromType(ReactCurrentOwner.current.type);
if (name) {
return '\n\nCheck the render method of `' + name + '`.';
}
}
return '';
}
function getSourceInfoErrorAddendum(source) {
if (source !== undefined) {
var fileName = source.fileName.replace(/^.*[\\\/]/, '');
var lineNumber = source.lineNumber;
return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
}
return '';
}
function getSourceInfoErrorAddendumForProps(elementProps) {
if (elementProps !== null && elementProps !== undefined) {
return getSourceInfoErrorAddendum(elementProps.__source);
}
return '';
}
/**
* Warn if there's no key explicitly set on dynamic arrays of children or
* object keys are not valid. This allows us to keep track of children between
* updates.
*/
var ownerHasKeyUseWarning = {};
function getCurrentComponentErrorInfo(parentType) {
var info = getDeclarationErrorAddendum();
if (!info) {
var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
if (parentName) {
info = "\n\nCheck the top-level render call using <" + parentName + ">.";
}
}
return info;
}
/**
* Warn if the element doesn't have an explicit key assigned to it.
* This element is in an array. The array could grow and shrink or be
* reordered. All children that haven't already been validated are required to
* have a "key" property assigned to it. Error statuses are cached so a warning
* will only be shown once.
*
* @internal
* @param {ReactElement} element Element that requires a key.
* @param {*} parentType element's parent's type.
*/
function validateExplicitKey(element, parentType) {
if (!element._store || element._store.validated || element.key != null) {
return;
}
element._store.validated = true;
var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
return;
}
ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
// property, it may be the creator of the child that's responsible for
// assigning it a key.
var childOwner = '';
if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
// Give the component that originally created this child.
childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
}
{
setCurrentlyValidatingElement$1(element);
error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
setCurrentlyValidatingElement$1(null);
}
}
/**
* Ensure that every element either is passed in a static location, in an
* array with an explicit keys property defined, or in an object literal
* with valid key property.
*
* @internal
* @param {ReactNode} node Statically passed child of any type.
* @param {*} parentType node's parent's type.
*/
function validateChildKeys(node, parentType) {
if (typeof node !== 'object') {
return;
}
if (isArray(node)) {
for (var i = 0; i < node.length; i++) {
var child = node[i];
if (isValidElement(child)) {
validateExplicitKey(child, parentType);
}
}
} else if (isValidElement(node)) {
// This element was passed in a valid location.
if (node._store) {
node._store.validated = true;
}
} else if (node) {
var iteratorFn = getIteratorFn(node);
if (typeof iteratorFn === 'function') {
// Entry iterators used to provide implicit keys,
// but now we print a separate warning for them later.
if (iteratorFn !== node.entries) {
var iterator = iteratorFn.call(node);
var step;
while (!(step = iterator.next()).done) {
if (isValidElement(step.value)) {
validateExplicitKey(step.value, parentType);
}
}
}
}
}
}
/**
* Given an element, validate that its props follow the propTypes definition,
* provided by the type.
*
* @param {ReactElement} element
*/
function validatePropTypes(element) {
{
var type = element.type;
if (type === null || type === undefined || typeof type === 'string') {
return;
}
var propTypes;
if (typeof type === 'function') {
propTypes = type.propTypes;
} else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
// Inner props are checked in the reconciler.
type.$$typeof === REACT_MEMO_TYPE)) {
propTypes = type.propTypes;
} else {
return;
}
if (propTypes) {
// Intentionally inside to avoid triggering lazy initializers:
var name = getComponentNameFromType(type);
checkPropTypes(propTypes, element.props, 'prop', name, element);
} else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:
var _name = getComponentNameFromType(type);
error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
}
if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
}
}
}
/**
* Given a fragment, validate that it can only be provided with fragment props
* @param {ReactElement} fragment
*/
function validateFragmentProps(fragment) {
{
var keys = Object.keys(fragment.props);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (key !== 'children' && key !== 'key') {
setCurrentlyValidatingElement$1(fragment);
error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);
setCurrentlyValidatingElement$1(null);
break;
}
}
if (fragment.ref !== null) {
setCurrentlyValidatingElement$1(fragment);
error('Invalid attribute `ref` supplied to `React.Fragment`.');
setCurrentlyValidatingElement$1(null);
}
}
}
function createElementWithValidation(type, props, children) {
var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
// succeed and there will likely be errors in render.
if (!validType) {
var info = '';
if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
}
var sourceInfo = getSourceInfoErrorAddendumForProps(props);
if (sourceInfo) {
info += sourceInfo;
} else {
info += getDeclarationErrorAddendum();
}
var typeString;
if (type === null) {
typeString = 'null';
} else if (isArray(type)) {
typeString = 'array';
} else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />";
info = ' Did you accidentally export a JSX literal instead of a component?';
} else {
typeString = typeof type;
}
{
error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
}
}
var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used.
// TODO: Drop this when these are no longer allowed as the type argument.
if (element == null) {
return element;
} // Skip key warning if the type isn't valid since our key validation logic
// doesn't expect a non-string/function type and can throw confusing errors.
// We don't want exception behavior to differ between dev and prod.
// (Rendering will throw with a helpful message and as soon as the type is
// fixed, the key warnings will appear.)
if (validType) {
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], type);
}
}
if (type === REACT_FRAGMENT_TYPE) {
validateFragmentProps(element);
} else {
validatePropTypes(element);
}
return element;
}
var didWarnAboutDeprecatedCreateFactory = false;
function createFactoryWithValidation(type) {
var validatedFactory = createElementWithValidation.bind(null, type);
validatedFactory.type = type;
{
if (!didWarnAboutDeprecatedCreateFactory) {
didWarnAboutDeprecatedCreateFactory = true;
warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.');
} // Legacy hook: remove it
Object.defineProperty(validatedFactory, 'type', {
enumerable: false,
get: function () {
warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.');
Object.defineProperty(this, 'type', {
value: type
});
return type;
}
});
}
return validatedFactory;
}
function cloneElementWithValidation(element, props, children) {
var newElement = cloneElement.apply(this, arguments);
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], newElement.type);
}
validatePropTypes(newElement);
return newElement;
}
var enableSchedulerDebugging = false;
var enableProfiling = false;
var frameYieldMs = 5;
function push(heap, node) {
var index = heap.length;
heap.push(node);
siftUp(heap, node, index);
}
function peek(heap) {
return heap.length === 0 ? null : heap[0];
}
function pop(heap) {
if (heap.length === 0) {
return null;
}
var first = heap[0];
var last = heap.pop();
if (last !== first) {
heap[0] = last;
siftDown(heap, last, 0);
}
return first;
}
function siftUp(heap, node, i) {
var index = i;
while (index > 0) {
var parentIndex = index - 1 >>> 1;
var parent = heap[parentIndex];
if (compare(parent, node) > 0) {
// The parent is larger. Swap positions.
heap[parentIndex] = node;
heap[index] = parent;
index = parentIndex;
} else {
// The parent is smaller. Exit.
return;
}
}
}
function siftDown(heap, node, i) {
var index = i;
var length = heap.length;
var halfLength = length >>> 1;
while (index < halfLength) {
var leftIndex = (index + 1) * 2 - 1;
var left = heap[leftIndex];
var rightIndex = leftIndex + 1;
var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those.
if (compare(left, node) < 0) {
if (rightIndex < length && compare(right, left) < 0) {
heap[index] = right;
heap[rightIndex] = node;
index = rightIndex;
} else {
heap[index] = left;
heap[leftIndex] = node;
index = leftIndex;
}
} else if (rightIndex < length && compare(right, node) < 0) {
heap[index] = right;
heap[rightIndex] = node;
index = rightIndex;
} else {
// Neither child is smaller. Exit.
return;
}
}
}
function compare(a, b) {
// Compare sort index first, then task id.
var diff = a.sortIndex - b.sortIndex;
return diff !== 0 ? diff : a.id - b.id;
}
// TODO: Use symbols?
var ImmediatePriority = 1;
var UserBlockingPriority = 2;
var NormalPriority = 3;
var LowPriority = 4;
var IdlePriority = 5;
function markTaskErrored(task, ms) {
}
/* eslint-disable no-var */
var getCurrentTime;
var hasPerformanceNow = typeof performance === 'object' && typeof performance.now === 'function';
if (hasPerformanceNow) {
var localPerformance = performance;
getCurrentTime = function () {
return localPerformance.now();
};
} else {
var localDate = Date;
var initialTime = localDate.now();
getCurrentTime = function () {
return localDate.now() - initialTime;
};
} // Max 31 bit integer. The max integer size in V8 for 32-bit systems.
// Math.pow(2, 30) - 1
// 0b111111111111111111111111111111
var maxSigned31BitInt = 1073741823; // Times out immediately
var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out
var USER_BLOCKING_PRIORITY_TIMEOUT = 250;
var NORMAL_PRIORITY_TIMEOUT = 5000;
var LOW_PRIORITY_TIMEOUT = 10000; // Never times out
var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; // Tasks are stored on a min heap
var taskQueue = [];
var timerQueue = []; // Incrementing id counter. Used to maintain insertion order.
var taskIdCounter = 1; // Pausing the scheduler is useful for debugging.
var currentTask = null;
var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrance.
var isPerformingWork = false;
var isHostCallbackScheduled = false;
var isHostTimeoutScheduled = false; // Capture local references to native APIs, in case a polyfill overrides them.
var localSetTimeout = typeof setTimeout === 'function' ? setTimeout : null;
var localClearTimeout = typeof clearTimeout === 'function' ? clearTimeout : null;
var localSetImmediate = typeof setImmediate !== 'undefined' ? setImmediate : null; // IE and Node.js + jsdom
var isInputPending = typeof navigator !== 'undefined' && navigator.scheduling !== undefined && navigator.scheduling.isInputPending !== undefined ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null;
function advanceTimers(currentTime) {
// Check for tasks that are no longer delayed and add them to the queue.
var timer = peek(timerQueue);
while (timer !== null) {
if (timer.callback === null) {
// Timer was cancelled.
pop(timerQueue);
} else if (timer.startTime <= currentTime) {
// Timer fired. Transfer to the task queue.
pop(timerQueue);
timer.sortIndex = timer.expirationTime;
push(taskQueue, timer);
} else {
// Remaining timers are pending.
return;
}
timer = peek(timerQueue);
}
}
function handleTimeout(currentTime) {
isHostTimeoutScheduled = false;
advanceTimers(currentTime);
if (!isHostCallbackScheduled) {
if (peek(taskQueue) !== null) {
isHostCallbackScheduled = true;
requestHostCallback(flushWork);
} else {
var firstTimer = peek(timerQueue);
if (firstTimer !== null) {
requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
}
}
}
}
function flushWork(hasTimeRemaining, initialTime) {
isHostCallbackScheduled = false;
if (isHostTimeoutScheduled) {
// We scheduled a timeout but it's no longer needed. Cancel it.
isHostTimeoutScheduled = false;
cancelHostTimeout();
}
isPerformingWork = true;
var previousPriorityLevel = currentPriorityLevel;
try {
if (enableProfiling) {
try {
return workLoop(hasTimeRemaining, initialTime);
} catch (error) {
if (currentTask !== null) {
var currentTime = getCurrentTime();
markTaskErrored(currentTask, currentTime);
currentTask.isQueued = false;
}
throw error;
}
} else {
// No catch in prod code path.
return workLoop(hasTimeRemaining, initialTime);
}
} finally {
currentTask = null;
currentPriorityLevel = previousPriorityLevel;
isPerformingWork = false;
}
}
function workLoop(hasTimeRemaining, initialTime) {
var currentTime = initialTime;
advanceTimers(currentTime);
currentTask = peek(taskQueue);
while (currentTask !== null && !(enableSchedulerDebugging )) {
if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) {
// This currentTask hasn't expired, and we've reached the deadline.
break;
}
var callback = currentTask.callback;
if (typeof callback === 'function') {
currentTask.callback = null;
currentPriorityLevel = currentTask.priorityLevel;
var didUserCallbackTimeout = currentTask.expirationTime <= currentTime;
var continuationCallback = callback(didUserCallbackTimeout);
currentTime = getCurrentTime();
if (typeof continuationCallback === 'function') {
currentTask.callback = continuationCallback;
} else {
if (currentTask === peek(taskQueue)) {
pop(taskQueue);
}
}
advanceTimers(currentTime);
} else {
pop(taskQueue);
}
currentTask = peek(taskQueue);
} // Return whether there's additional work
if (currentTask !== null) {
return true;
} else {
var firstTimer = peek(timerQueue);
if (firstTimer !== null) {
requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
}
return false;
}
}
function unstable_runWithPriority(priorityLevel, eventHandler) {
switch (priorityLevel) {
case ImmediatePriority:
case UserBlockingPriority:
case NormalPriority:
case LowPriority:
case IdlePriority:
break;
default:
priorityLevel = NormalPriority;
}
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = priorityLevel;
try {
return eventHandler();
} finally {
currentPriorityLevel = previousPriorityLevel;
}
}
function unstable_next(eventHandler) {
var priorityLevel;
switch (currentPriorityLevel) {
case ImmediatePriority:
case UserBlockingPriority:
case NormalPriority:
// Shift down to normal priority
priorityLevel = NormalPriority;
break;
default:
// Anything lower than normal priority should remain at the current level.
priorityLevel = currentPriorityLevel;
break;
}
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = priorityLevel;
try {
return eventHandler();
} finally {
currentPriorityLevel = previousPriorityLevel;
}
}
function unstable_wrapCallback(callback) {
var parentPriorityLevel = currentPriorityLevel;
return function () {
// This is a fork of runWithPriority, inlined for performance.
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = parentPriorityLevel;
try {
return callback.apply(this, arguments);
} finally {
currentPriorityLevel = previousPriorityLevel;
}
};
}
function unstable_scheduleCallback(priorityLevel, callback, options) {
var currentTime = getCurrentTime();
var startTime;
if (typeof options === 'object' && options !== null) {
var delay = options.delay;
if (typeof delay === 'number' && delay > 0) {
startTime = currentTime + delay;
} else {
startTime = currentTime;
}
} else {
startTime = currentTime;
}
var timeout;
switch (priorityLevel) {
case ImmediatePriority:
timeout = IMMEDIATE_PRIORITY_TIMEOUT;
break;
case UserBlockingPriority:
timeout = USER_BLOCKING_PRIORITY_TIMEOUT;
break;
case IdlePriority:
timeout = IDLE_PRIORITY_TIMEOUT;
break;
case LowPriority:
timeout = LOW_PRIORITY_TIMEOUT;
break;
case NormalPriority:
default:
timeout = NORMAL_PRIORITY_TIMEOUT;
break;
}
var expirationTime = startTime + timeout;
var newTask = {
id: taskIdCounter++,
callback: callback,
priorityLevel: priorityLevel,
startTime: startTime,
expirationTime: expirationTime,
sortIndex: -1
};
if (startTime > currentTime) {
// This is a delayed task.
newTask.sortIndex = startTime;
push(timerQueue, newTask);
if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
// All tasks are delayed, and this is the task with the earliest delay.
if (isHostTimeoutScheduled) {
// Cancel an existing timeout.
cancelHostTimeout();
} else {
isHostTimeoutScheduled = true;
} // Schedule a timeout.
requestHostTimeout(handleTimeout, startTime - currentTime);
}
} else {
newTask.sortIndex = expirationTime;
push(taskQueue, newTask);
// wait until the next time we yield.
if (!isHostCallbackScheduled && !isPerformingWork) {
isHostCallbackScheduled = true;
requestHostCallback(flushWork);
}
}
return newTask;
}
function unstable_pauseExecution() {
}
function unstable_continueExecution() {
if (!isHostCallbackScheduled && !isPerformingWork) {
isHostCallbackScheduled = true;
requestHostCallback(flushWork);
}
}
function unstable_getFirstCallbackNode() {
return peek(taskQueue);
}
function unstable_cancelCallback(task) {
// remove from the queue because you can't remove arbitrary nodes from an
// array based heap, only the first one.)
task.callback = null;
}
function unstable_getCurrentPriorityLevel() {
return currentPriorityLevel;
}
var isMessageLoopRunning = false;
var scheduledHostCallback = null;
var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main
// thread, like user events. By default, it yields multiple times per frame.
// It does not attempt to align with frame boundaries, since most tasks don't
// need to be frame aligned; for those that do, use requestAnimationFrame.
var frameInterval = frameYieldMs;
var startTime = -1;
function shouldYieldToHost() {
var timeElapsed = getCurrentTime() - startTime;
if (timeElapsed < frameInterval) {
// The main thread has only been blocked for a really short amount of time;
// smaller than a single frame. Don't yield yet.
return false;
} // The main thread has been blocked for a non-negligible amount of time. We
return true;
}
function requestPaint() {
}
function forceFrameRate(fps) {
if (fps < 0 || fps > 125) {
// Using console['error'] to evade Babel and ESLint
console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing frame rates higher than 125 fps is not supported');
return;
}
if (fps > 0) {
frameInterval = Math.floor(1000 / fps);
} else {
// reset the framerate
frameInterval = frameYieldMs;
}
}
var performWorkUntilDeadline = function () {
if (scheduledHostCallback !== null) {
var currentTime = getCurrentTime(); // Keep track of the start time so we can measure how long the main thread
// has been blocked.
startTime = currentTime;
var hasTimeRemaining = true; // If a scheduler task throws, exit the current browser task so the
// error can be observed.
//
// Intentionally not using a try-catch, since that makes some debugging
// techniques harder. Instead, if `scheduledHostCallback` errors, then
// `hasMoreWork` will remain true, and we'll continue the work loop.
var hasMoreWork = true;
try {
hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);
} finally {
if (hasMoreWork) {
// If there's more work, schedule the next message event at the end
// of the preceding one.
schedulePerformWorkUntilDeadline();
} else {
isMessageLoopRunning = false;
scheduledHostCallback = null;
}
}
} else {
isMessageLoopRunning = false;
} // Yielding to the browser will give it a chance to paint, so we can
};
var schedulePerformWorkUntilDeadline;
if (typeof localSetImmediate === 'function') {
// Node.js and old IE.
// There's a few reasons for why we prefer setImmediate.
//
// Unlike MessageChannel, it doesn't prevent a Node.js process from exiting.
// (Even though this is a DOM fork of the Scheduler, you could get here
// with a mix of Node.js 15+, which has a MessageChannel, and jsdom.)
// https://github.com/facebook/react/issues/20756
//
// But also, it runs earlier which is the semantic we want.
// If other browsers ever implement it, it's better to use it.
// Although both of these would be inferior to native scheduling.
schedulePerformWorkUntilDeadline = function () {
localSetImmediate(performWorkUntilDeadline);
};
} else if (typeof MessageChannel !== 'undefined') {
// DOM and Worker environments.
// We prefer MessageChannel because of the 4ms setTimeout clamping.
var channel = new MessageChannel();
var port = channel.port2;
channel.port1.onmessage = performWorkUntilDeadline;
schedulePerformWorkUntilDeadline = function () {
port.postMessage(null);
};
} else {
// We should only fallback here in non-browser environments.
schedulePerformWorkUntilDeadline = function () {
localSetTimeout(performWorkUntilDeadline, 0);
};
}
function requestHostCallback(callback) {
scheduledHostCallback = callback;
if (!isMessageLoopRunning) {
isMessageLoopRunning = true;
schedulePerformWorkUntilDeadline();
}
}
function requestHostTimeout(callback, ms) {
taskTimeoutID = localSetTimeout(function () {
callback(getCurrentTime());
}, ms);
}
function cancelHostTimeout() {
localClearTimeout(taskTimeoutID);
taskTimeoutID = -1;
}
var unstable_requestPaint = requestPaint;
var unstable_Profiling = null;
var Scheduler = /*#__PURE__*/Object.freeze({
__proto__: null,
unstable_ImmediatePriority: ImmediatePriority,
unstable_UserBlockingPriority: UserBlockingPriority,
unstable_NormalPriority: NormalPriority,
unstable_IdlePriority: IdlePriority,
unstable_LowPriority: LowPriority,
unstable_runWithPriority: unstable_runWithPriority,
unstable_next: unstable_next,
unstable_scheduleCallback: unstable_scheduleCallback,
unstable_cancelCallback: unstable_cancelCallback,
unstable_wrapCallback: unstable_wrapCallback,
unstable_getCurrentPriorityLevel: unstable_getCurrentPriorityLevel,
unstable_shouldYield: shouldYieldToHost,
unstable_requestPaint: unstable_requestPaint,
unstable_continueExecution: unstable_continueExecution,
unstable_pauseExecution: unstable_pauseExecution,
unstable_getFirstCallbackNode: unstable_getFirstCallbackNode,
get unstable_now () { return getCurrentTime; },
unstable_forceFrameRate: forceFrameRate,
unstable_Profiling: unstable_Profiling
});
var ReactSharedInternals$1 = {
ReactCurrentDispatcher: ReactCurrentDispatcher,
ReactCurrentOwner: ReactCurrentOwner,
ReactCurrentBatchConfig: ReactCurrentBatchConfig,
// Re-export the schedule API(s) for UMD bundles.
// This avoids introducing a dependency on a new UMD global in a minor update,
// Since that would be a breaking change (e.g. for all existing CodeSandboxes).
// This re-export is only required for UMD bundles;
// CJS bundles use the shared NPM package.
Scheduler: Scheduler
};
{
ReactSharedInternals$1.ReactCurrentActQueue = ReactCurrentActQueue;
ReactSharedInternals$1.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
}
function startTransition(scope, options) {
var prevTransition = ReactCurrentBatchConfig.transition;
ReactCurrentBatchConfig.transition = {};
var currentTransition = ReactCurrentBatchConfig.transition;
{
ReactCurrentBatchConfig.transition._updatedFibers = new Set();
}
try {
scope();
} finally {
ReactCurrentBatchConfig.transition = prevTransition;
{
if (prevTransition === null && currentTransition._updatedFibers) {
var updatedFibersCount = currentTransition._updatedFibers.size;
if (updatedFibersCount > 10) {
warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.');
}
currentTransition._updatedFibers.clear();
}
}
}
}
var didWarnAboutMessageChannel = false;
var enqueueTaskImpl = null;
function enqueueTask(task) {
if (enqueueTaskImpl === null) {
try {
// read require off the module object to get around the bundlers.
// we don't want them to detect a require and bundle a Node polyfill.
var requireString = ('require' + Math.random()).slice(0, 7);
var nodeRequire = module && module[requireString]; // assuming we're in node, let's try to get node's
// version of setImmediate, bypassing fake timers if any.
enqueueTaskImpl = nodeRequire.call(module, 'timers').setImmediate;
} catch (_err) {
// we're in a browser
// we can't use regular timers because they may still be faked
// so we try MessageChannel+postMessage instead
enqueueTaskImpl = function (callback) {
{
if (didWarnAboutMessageChannel === false) {
didWarnAboutMessageChannel = true;
if (typeof MessageChannel === 'undefined') {
error('This browser does not have a MessageChannel implementation, ' + 'so enqueuing tasks via await act(async () => ...) will fail. ' + 'Please file an issue at https://github.com/facebook/react/issues ' + 'if you encounter this warning.');
}
}
}
var channel = new MessageChannel();
channel.port1.onmessage = callback;
channel.port2.postMessage(undefined);
};
}
}
return enqueueTaskImpl(task);
}
var actScopeDepth = 0;
var didWarnNoAwaitAct = false;
function act(callback) {
{
// `act` calls can be nested, so we track the depth. This represents the
// number of `act` scopes on the stack.
var prevActScopeDepth = actScopeDepth;
actScopeDepth++;
if (ReactCurrentActQueue.current === null) {
// This is the outermost `act` scope. Initialize the queue. The reconciler
// will detect the queue and use it instead of Scheduler.
ReactCurrentActQueue.current = [];
}
var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy;
var result;
try {
// Used to reproduce behavior of `batchedUpdates` in legacy mode. Only
// set to `true` while the given callback is executed, not for updates
// triggered during an async event, because this is how the legacy
// implementation of `act` behaved.
ReactCurrentActQueue.isBatchingLegacy = true;
result = callback(); // Replicate behavior of original `act` implementation in legacy mode,
// which flushed updates immediately after the scope function exits, even
// if it's an async function.
if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) {
var queue = ReactCurrentActQueue.current;
if (queue !== null) {
ReactCurrentActQueue.didScheduleLegacyUpdate = false;
flushActQueue(queue);
}
}
} catch (error) {
popActScope(prevActScopeDepth);
throw error;
} finally {
ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy;
}
if (result !== null && typeof result === 'object' && typeof result.then === 'function') {
var thenableResult = result; // The callback is an async function (i.e. returned a promise). Wait
// for it to resolve before exiting the current scope.
var wasAwaited = false;
var thenable = {
then: function (resolve, reject) {
wasAwaited = true;
thenableResult.then(function (returnValue) {
popActScope(prevActScopeDepth);
if (actScopeDepth === 0) {
// We've exited the outermost act scope. Recursively flush the
// queue until there's no remaining work.
recursivelyFlushAsyncActWork(returnValue, resolve, reject);
} else {
resolve(returnValue);
}
}, function (error) {
// The callback threw an error.
popActScope(prevActScopeDepth);
reject(error);
});
}
};
{
if (!didWarnNoAwaitAct && typeof Promise !== 'undefined') {
// eslint-disable-next-line no-undef
Promise.resolve().then(function () {}).then(function () {
if (!wasAwaited) {
didWarnNoAwaitAct = true;
error('You called act(async () => ...) without await. ' + 'This could lead to unexpected testing behaviour, ' + 'interleaving multiple act calls and mixing their ' + 'scopes. ' + 'You should - await act(async () => ...);');
}
});
}
}
return thenable;
} else {
var returnValue = result; // The callback is not an async function. Exit the current scope
// immediately, without awaiting.
popActScope(prevActScopeDepth);
if (actScopeDepth === 0) {
// Exiting the outermost act scope. Flush the queue.
var _queue = ReactCurrentActQueue.current;
if (_queue !== null) {
flushActQueue(_queue);
ReactCurrentActQueue.current = null;
} // Return a thenable. If the user awaits it, we'll flush again in
// case additional work was scheduled by a microtask.
var _thenable = {
then: function (resolve, reject) {
// Confirm we haven't re-entered another `act` scope, in case
// the user does something weird like await the thenable
// multiple times.
if (ReactCurrentActQueue.current === null) {
// Recursively flush the queue until there's no remaining work.
ReactCurrentActQueue.current = [];
recursivelyFlushAsyncActWork(returnValue, resolve, reject);
} else {
resolve(returnValue);
}
}
};
return _thenable;
} else {
// Since we're inside a nested `act` scope, the returned thenable
// immediately resolves. The outer scope will flush the queue.
var _thenable2 = {
then: function (resolve, reject) {
resolve(returnValue);
}
};
return _thenable2;
}
}
}
}
function popActScope(prevActScopeDepth) {
{
if (prevActScopeDepth !== actScopeDepth - 1) {
error('You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. ');
}
actScopeDepth = prevActScopeDepth;
}
}
function recursivelyFlushAsyncActWork(returnValue, resolve, reject) {
{
var queue = ReactCurrentActQueue.current;
if (queue !== null) {
try {
flushActQueue(queue);
enqueueTask(function () {
if (queue.length === 0) {
// No additional work was scheduled. Finish.
ReactCurrentActQueue.current = null;
resolve(returnValue);
} else {
// Keep flushing work until there's none left.
recursivelyFlushAsyncActWork(returnValue, resolve, reject);
}
});
} catch (error) {
reject(error);
}
} else {
resolve(returnValue);
}
}
}
var isFlushing = false;
function flushActQueue(queue) {
{
if (!isFlushing) {
// Prevent re-entrance.
isFlushing = true;
var i = 0;
try {
for (; i < queue.length; i++) {
var callback = queue[i];
do {
callback = callback(true);
} while (callback !== null);
}
queue.length = 0;
} catch (error) {
// If something throws, leave the remaining callbacks on the queue.
queue = queue.slice(i + 1);
throw error;
} finally {
isFlushing = false;
}
}
}
}
var createElement$1 = createElementWithValidation ;
var cloneElement$1 = cloneElementWithValidation ;
var createFactory = createFactoryWithValidation ;
var Children = {
map: mapChildren,
forEach: forEachChildren,
count: countChildren,
toArray: toArray,
only: onlyChild
};
exports.Children = Children;
exports.Component = Component;
exports.Fragment = REACT_FRAGMENT_TYPE;
exports.Profiler = REACT_PROFILER_TYPE;
exports.PureComponent = PureComponent;
exports.StrictMode = REACT_STRICT_MODE_TYPE;
exports.Suspense = REACT_SUSPENSE_TYPE;
exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals$1;
exports.cloneElement = cloneElement$1;
exports.createContext = createContext;
exports.createElement = createElement$1;
exports.createFactory = createFactory;
exports.createRef = createRef;
exports.forwardRef = forwardRef;
exports.isValidElement = isValidElement;
exports.lazy = lazy;
exports.memo = memo;
exports.startTransition = startTransition;
exports.unstable_act = act;
exports.useCallback = useCallback;
exports.useContext = useContext;
exports.useDebugValue = useDebugValue;
exports.useDeferredValue = useDeferredValue;
exports.useEffect = useEffect;
exports.useId = useId;
exports.useImperativeHandle = useImperativeHandle;
exports.useInsertionEffect = useInsertionEffect;
exports.useLayoutEffect = useLayoutEffect;
exports.useMemo = useMemo;
exports.useReducer = useReducer;
exports.useRef = useRef;
exports.useState = useState;
exports.useSyncExternalStore = useSyncExternalStore;
exports.useTransition = useTransition;
exports.version = ReactVersion;
})));
vendor/react.min.js 0000666 00000024561 15123355174 0010301 0 ustar 00 /**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
!function(){"use strict";var e,t;e=this,t=function(e){function t(e,t,n){this.props=e,this.context=t,this.refs=L,this.updater=n||T}function n(){}function r(e,t,n){this.props=e,this.context=t,this.refs=L,this.updater=n||T}function o(e,t,n){var r,o={},u=null,a=null;if(null!=t)for(r in void 0!==t.ref&&(a=t.ref),void 0!==t.key&&(u=""+t.key),t)D.call(t,r)&&!V.hasOwnProperty(r)&&(o[r]=t[r]);var i=arguments.length-2;if(1===i)o.children=n;else if(1<i){for(var l=Array(i),c=0;c<i;c++)l[c]=arguments[c+2];o.children=l}if(e&&e.defaultProps)for(r in i=e.defaultProps)void 0===o[r]&&(o[r]=i[r]);return{$$typeof:g,type:e,key:u,ref:a,props:o,_owner:U.current}}function u(e){return"object"==typeof e&&null!==e&&e.$$typeof===g}function a(e,t){return"object"==typeof e&&null!==e&&null!=e.key?function(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,(function(e){return t[e]}))}(""+e.key):t.toString(36)}function i(e,t,n,r,o){var l=typeof e;"undefined"!==l&&"boolean"!==l||(e=null);var c=!1;if(null===e)c=!0;else switch(l){case"string":case"number":c=!0;break;case"object":switch(e.$$typeof){case g:case k:c=!0}}if(c)return o=o(c=e),e=""===r?"."+a(c,0):r,M(o)?(n="",null!=e&&(n=e.replace(q,"$&/")+"/"),i(o,t,n,"",(function(e){return e}))):null!=o&&(u(o)&&(o=function(e,t){return{$$typeof:g,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}(o,n+(!o.key||c&&c.key===o.key?"":(""+o.key).replace(q,"$&/")+"/")+e)),t.push(o)),1;if(c=0,r=""===r?".":r+":",M(e))for(var f=0;f<e.length;f++){var s=r+a(l=e[f],f);c+=i(l,t,n,s,o)}else if(s=function(e){return null===e||"object"!=typeof e?null:"function"==typeof(e=j&&e[j]||e["@@iterator"])?e:null}(e),"function"==typeof s)for(e=s.call(e),f=0;!(l=e.next()).done;)c+=i(l=l.value,t,n,s=r+a(l,f++),o);else if("object"===l)throw t=String(e),Error("Objects are not valid as a React child (found: "+("[object Object]"===t?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.");return c}function l(e,t,n){if(null==e)return e;var r=[],o=0;return i(e,r,"","",(function(e){return t.call(n,e,o++)})),r}function c(e){if(-1===e._status){var t=e._result;(t=t()).then((function(t){0!==e._status&&-1!==e._status||(e._status=1,e._result=t)}),(function(t){0!==e._status&&-1!==e._status||(e._status=2,e._result=t)})),-1===e._status&&(e._status=0,e._result=t)}if(1===e._status)return e._result.default;throw e._result}function f(e,t){var n=e.length;e.push(t);e:for(;0<n;){var r=n-1>>>1,o=e[r];if(!(0<y(o,t)))break e;e[r]=t,e[n]=o,n=r}}function s(e){return 0===e.length?null:e[0]}function p(e){if(0===e.length)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;e:for(var r=0,o=e.length,u=o>>>1;r<u;){var a=2*(r+1)-1,i=e[a],l=a+1,c=e[l];if(0>y(i,n))l<o&&0>y(c,i)?(e[r]=c,e[l]=n,r=l):(e[r]=i,e[a]=n,r=a);else{if(!(l<o&&0>y(c,n)))break e;e[r]=c,e[l]=n,r=l}}}return t}function y(e,t){var n=e.sortIndex-t.sortIndex;return 0!==n?n:e.id-t.id}function d(e){for(var t=s(G);null!==t;){if(null===t.callback)p(G);else{if(!(t.startTime<=e))break;p(G),t.sortIndex=t.expirationTime,f(Y,t)}t=s(G)}}function b(e){if(ee=!1,d(e),!Z)if(null!==s(Y))Z=!0,_(v);else{var t=s(G);null!==t&&h(b,t.startTime-e)}}function v(e,t){Z=!1,ee&&(ee=!1,ne(ae),ae=-1),X=!0;var n=Q;try{for(d(t),K=s(Y);null!==K&&(!(K.expirationTime>t)||e&&!m());){var r=K.callback;if("function"==typeof r){K.callback=null,Q=K.priorityLevel;var o=r(K.expirationTime<=t);t=z(),"function"==typeof o?K.callback=o:K===s(Y)&&p(Y),d(t)}else p(Y);K=s(Y)}if(null!==K)var u=!0;else{var a=s(G);null!==a&&h(b,a.startTime-t),u=!1}return u}finally{K=null,Q=n,X=!1}}function m(){return!(z()-le<ie)}function _(e){ue=e,oe||(oe=!0,fe())}function h(e,t){ae=te((function(){e(z())}),t)}var g=Symbol.for("react.element"),k=Symbol.for("react.portal"),w=Symbol.for("react.fragment"),S=Symbol.for("react.strict_mode"),x=Symbol.for("react.profiler"),C=Symbol.for("react.provider"),E=Symbol.for("react.context"),R=Symbol.for("react.forward_ref"),P=Symbol.for("react.suspense"),$=Symbol.for("react.memo"),I=Symbol.for("react.lazy"),j=Symbol.iterator,T={isMounted:function(e){return!1},enqueueForceUpdate:function(e,t,n){},enqueueReplaceState:function(e,t,n,r){},enqueueSetState:function(e,t,n,r){}},O=Object.assign,L={};t.prototype.isReactComponent={},t.prototype.setState=function(e,t){if("object"!=typeof e&&"function"!=typeof e&&null!=e)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},t.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},n.prototype=t.prototype;var F=r.prototype=new n;F.constructor=r,O(F,t.prototype),F.isPureReactComponent=!0;var M=Array.isArray,D=Object.prototype.hasOwnProperty,U={current:null},V={key:!0,ref:!0,__self:!0,__source:!0},q=/\/+/g,A={current:null},N={transition:null};if("object"==typeof performance&&"function"==typeof performance.now)var B=performance,z=function(){return B.now()};else{var H=Date,W=H.now();z=function(){return H.now()-W}}var Y=[],G=[],J=1,K=null,Q=3,X=!1,Z=!1,ee=!1,te="function"==typeof setTimeout?setTimeout:null,ne="function"==typeof clearTimeout?clearTimeout:null,re="undefined"!=typeof setImmediate?setImmediate:null;"undefined"!=typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);var oe=!1,ue=null,ae=-1,ie=5,le=-1,ce=function(){if(null!==ue){var e=z();le=e;var t=!0;try{t=ue(!0,e)}finally{t?fe():(oe=!1,ue=null)}}else oe=!1};if("function"==typeof re)var fe=function(){re(ce)};else if("undefined"!=typeof MessageChannel){var se=(F=new MessageChannel).port2;F.port1.onmessage=ce,fe=function(){se.postMessage(null)}}else fe=function(){te(ce,0)};F={ReactCurrentDispatcher:A,ReactCurrentOwner:U,ReactCurrentBatchConfig:N,Scheduler:{__proto__:null,unstable_ImmediatePriority:1,unstable_UserBlockingPriority:2,unstable_NormalPriority:3,unstable_IdlePriority:5,unstable_LowPriority:4,unstable_runWithPriority:function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=Q;Q=e;try{return t()}finally{Q=n}},unstable_next:function(e){switch(Q){case 1:case 2:case 3:var t=3;break;default:t=Q}var n=Q;Q=t;try{return e()}finally{Q=n}},unstable_scheduleCallback:function(e,t,n){var r=z();switch(n="object"==typeof n&&null!==n&&"number"==typeof(n=n.delay)&&0<n?r+n:r,e){case 1:var o=-1;break;case 2:o=250;break;case 5:o=1073741823;break;case 4:o=1e4;break;default:o=5e3}return e={id:J++,callback:t,priorityLevel:e,startTime:n,expirationTime:o=n+o,sortIndex:-1},n>r?(e.sortIndex=n,f(G,e),null===s(Y)&&e===s(G)&&(ee?(ne(ae),ae=-1):ee=!0,h(b,n-r))):(e.sortIndex=o,f(Y,e),Z||X||(Z=!0,_(v))),e},unstable_cancelCallback:function(e){e.callback=null},unstable_wrapCallback:function(e){var t=Q;return function(){var n=Q;Q=t;try{return e.apply(this,arguments)}finally{Q=n}}},unstable_getCurrentPriorityLevel:function(){return Q},unstable_shouldYield:m,unstable_requestPaint:function(){},unstable_continueExecution:function(){Z||X||(Z=!0,_(v))},unstable_pauseExecution:function(){},unstable_getFirstCallbackNode:function(){return s(Y)},get unstable_now(){return z},unstable_forceFrameRate:function(e){0>e||125<e?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):ie=0<e?Math.floor(1e3/e):5},unstable_Profiling:null}},e.Children={map:l,forEach:function(e,t,n){l(e,(function(){t.apply(this,arguments)}),n)},count:function(e){var t=0;return l(e,(function(){t++})),t},toArray:function(e){return l(e,(function(e){return e}))||[]},only:function(e){if(!u(e))throw Error("React.Children.only expected to receive a single React element child.");return e}},e.Component=t,e.Fragment=w,e.Profiler=x,e.PureComponent=r,e.StrictMode=S,e.Suspense=P,e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=F,e.cloneElement=function(e,t,n){if(null==e)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var r=O({},e.props),o=e.key,u=e.ref,a=e._owner;if(null!=t){if(void 0!==t.ref&&(u=t.ref,a=U.current),void 0!==t.key&&(o=""+t.key),e.type&&e.type.defaultProps)var i=e.type.defaultProps;for(l in t)D.call(t,l)&&!V.hasOwnProperty(l)&&(r[l]=void 0===t[l]&&void 0!==i?i[l]:t[l])}var l=arguments.length-2;if(1===l)r.children=n;else if(1<l){i=Array(l);for(var c=0;c<l;c++)i[c]=arguments[c+2];r.children=i}return{$$typeof:g,type:e.type,key:o,ref:u,props:r,_owner:a}},e.createContext=function(e){return(e={$$typeof:E,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null}).Provider={$$typeof:C,_context:e},e.Consumer=e},e.createElement=o,e.createFactory=function(e){var t=o.bind(null,e);return t.type=e,t},e.createRef=function(){return{current:null}},e.forwardRef=function(e){return{$$typeof:R,render:e}},e.isValidElement=u,e.lazy=function(e){return{$$typeof:I,_payload:{_status:-1,_result:e},_init:c}},e.memo=function(e,t){return{$$typeof:$,type:e,compare:void 0===t?null:t}},e.startTransition=function(e,t){t=N.transition,N.transition={};try{e()}finally{N.transition=t}},e.unstable_act=function(e){throw Error("act(...) is not supported in production builds of React.")},e.useCallback=function(e,t){return A.current.useCallback(e,t)},e.useContext=function(e){return A.current.useContext(e)},e.useDebugValue=function(e,t){},e.useDeferredValue=function(e){return A.current.useDeferredValue(e)},e.useEffect=function(e,t){return A.current.useEffect(e,t)},e.useId=function(){return A.current.useId()},e.useImperativeHandle=function(e,t,n){return A.current.useImperativeHandle(e,t,n)},e.useInsertionEffect=function(e,t){return A.current.useInsertionEffect(e,t)},e.useLayoutEffect=function(e,t){return A.current.useLayoutEffect(e,t)},e.useMemo=function(e,t){return A.current.useMemo(e,t)},e.useReducer=function(e,t,n){return A.current.useReducer(e,t,n)},e.useRef=function(e){return A.current.useRef(e)},e.useState=function(e){return A.current.useState(e)},e.useSyncExternalStore=function(e,t,n){return A.current.useSyncExternalStore(e,t,n)},e.useTransition=function(){return A.current.useTransition()},e.version="18.2.0"},"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e=e||self).React={})}(); vendor/wp-polyfill-inert.js 0000666 00000072743 15123355174 0012023 0 ustar 00 (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory() :
typeof define === 'function' && define.amd ? define('inert', factory) :
(factory());
}(this, (function () { 'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* This work is licensed under the W3C Software and Document License
* (http://www.w3.org/Consortium/Legal/2015/copyright-software-and-document).
*/
(function () {
// Return early if we're not running inside of the browser.
if (typeof window === 'undefined') {
return;
}
// Convenience function for converting NodeLists.
/** @type {typeof Array.prototype.slice} */
var slice = Array.prototype.slice;
/**
* IE has a non-standard name for "matches".
* @type {typeof Element.prototype.matches}
*/
var matches = Element.prototype.matches || Element.prototype.msMatchesSelector;
/** @type {string} */
var _focusableElementsString = ['a[href]', 'area[href]', 'input:not([disabled])', 'select:not([disabled])', 'textarea:not([disabled])', 'button:not([disabled])', 'details', 'summary', 'iframe', 'object', 'embed', '[contenteditable]'].join(',');
/**
* `InertRoot` manages a single inert subtree, i.e. a DOM subtree whose root element has an `inert`
* attribute.
*
* Its main functions are:
*
* - to create and maintain a set of managed `InertNode`s, including when mutations occur in the
* subtree. The `makeSubtreeUnfocusable()` method handles collecting `InertNode`s via registering
* each focusable node in the subtree with the singleton `InertManager` which manages all known
* focusable nodes within inert subtrees. `InertManager` ensures that a single `InertNode`
* instance exists for each focusable node which has at least one inert root as an ancestor.
*
* - to notify all managed `InertNode`s when this subtree stops being inert (i.e. when the `inert`
* attribute is removed from the root node). This is handled in the destructor, which calls the
* `deregister` method on `InertManager` for each managed inert node.
*/
var InertRoot = function () {
/**
* @param {!HTMLElement} rootElement The HTMLElement at the root of the inert subtree.
* @param {!InertManager} inertManager The global singleton InertManager object.
*/
function InertRoot(rootElement, inertManager) {
_classCallCheck(this, InertRoot);
/** @type {!InertManager} */
this._inertManager = inertManager;
/** @type {!HTMLElement} */
this._rootElement = rootElement;
/**
* @type {!Set<!InertNode>}
* All managed focusable nodes in this InertRoot's subtree.
*/
this._managedNodes = new Set();
// Make the subtree hidden from assistive technology
if (this._rootElement.hasAttribute('aria-hidden')) {
/** @type {?string} */
this._savedAriaHidden = this._rootElement.getAttribute('aria-hidden');
} else {
this._savedAriaHidden = null;
}
this._rootElement.setAttribute('aria-hidden', 'true');
// Make all focusable elements in the subtree unfocusable and add them to _managedNodes
this._makeSubtreeUnfocusable(this._rootElement);
// Watch for:
// - any additions in the subtree: make them unfocusable too
// - any removals from the subtree: remove them from this inert root's managed nodes
// - attribute changes: if `tabindex` is added, or removed from an intrinsically focusable
// element, make that node a managed node.
this._observer = new MutationObserver(this._onMutation.bind(this));
this._observer.observe(this._rootElement, { attributes: true, childList: true, subtree: true });
}
/**
* Call this whenever this object is about to become obsolete. This unwinds all of the state
* stored in this object and updates the state of all of the managed nodes.
*/
_createClass(InertRoot, [{
key: 'destructor',
value: function destructor() {
this._observer.disconnect();
if (this._rootElement) {
if (this._savedAriaHidden !== null) {
this._rootElement.setAttribute('aria-hidden', this._savedAriaHidden);
} else {
this._rootElement.removeAttribute('aria-hidden');
}
}
this._managedNodes.forEach(function (inertNode) {
this._unmanageNode(inertNode.node);
}, this);
// Note we cast the nulls to the ANY type here because:
// 1) We want the class properties to be declared as non-null, or else we
// need even more casts throughout this code. All bets are off if an
// instance has been destroyed and a method is called.
// 2) We don't want to cast "this", because we want type-aware optimizations
// to know which properties we're setting.
this._observer = /** @type {?} */null;
this._rootElement = /** @type {?} */null;
this._managedNodes = /** @type {?} */null;
this._inertManager = /** @type {?} */null;
}
/**
* @return {!Set<!InertNode>} A copy of this InertRoot's managed nodes set.
*/
}, {
key: '_makeSubtreeUnfocusable',
/**
* @param {!Node} startNode
*/
value: function _makeSubtreeUnfocusable(startNode) {
var _this2 = this;
composedTreeWalk(startNode, function (node) {
return _this2._visitNode(node);
});
var activeElement = document.activeElement;
if (!document.body.contains(startNode)) {
// startNode may be in shadow DOM, so find its nearest shadowRoot to get the activeElement.
var node = startNode;
/** @type {!ShadowRoot|undefined} */
var root = undefined;
while (node) {
if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
root = /** @type {!ShadowRoot} */node;
break;
}
node = node.parentNode;
}
if (root) {
activeElement = root.activeElement;
}
}
if (startNode.contains(activeElement)) {
activeElement.blur();
// In IE11, if an element is already focused, and then set to tabindex=-1
// calling blur() will not actually move the focus.
// To work around this we call focus() on the body instead.
if (activeElement === document.activeElement) {
document.body.focus();
}
}
}
/**
* @param {!Node} node
*/
}, {
key: '_visitNode',
value: function _visitNode(node) {
if (node.nodeType !== Node.ELEMENT_NODE) {
return;
}
var element = /** @type {!HTMLElement} */node;
// If a descendant inert root becomes un-inert, its descendants will still be inert because of
// this inert root, so all of its managed nodes need to be adopted by this InertRoot.
if (element !== this._rootElement && element.hasAttribute('inert')) {
this._adoptInertRoot(element);
}
if (matches.call(element, _focusableElementsString) || element.hasAttribute('tabindex')) {
this._manageNode(element);
}
}
/**
* Register the given node with this InertRoot and with InertManager.
* @param {!Node} node
*/
}, {
key: '_manageNode',
value: function _manageNode(node) {
var inertNode = this._inertManager.register(node, this);
this._managedNodes.add(inertNode);
}
/**
* Unregister the given node with this InertRoot and with InertManager.
* @param {!Node} node
*/
}, {
key: '_unmanageNode',
value: function _unmanageNode(node) {
var inertNode = this._inertManager.deregister(node, this);
if (inertNode) {
this._managedNodes['delete'](inertNode);
}
}
/**
* Unregister the entire subtree starting at `startNode`.
* @param {!Node} startNode
*/
}, {
key: '_unmanageSubtree',
value: function _unmanageSubtree(startNode) {
var _this3 = this;
composedTreeWalk(startNode, function (node) {
return _this3._unmanageNode(node);
});
}
/**
* If a descendant node is found with an `inert` attribute, adopt its managed nodes.
* @param {!HTMLElement} node
*/
}, {
key: '_adoptInertRoot',
value: function _adoptInertRoot(node) {
var inertSubroot = this._inertManager.getInertRoot(node);
// During initialisation this inert root may not have been registered yet,
// so register it now if need be.
if (!inertSubroot) {
this._inertManager.setInert(node, true);
inertSubroot = this._inertManager.getInertRoot(node);
}
inertSubroot.managedNodes.forEach(function (savedInertNode) {
this._manageNode(savedInertNode.node);
}, this);
}
/**
* Callback used when mutation observer detects subtree additions, removals, or attribute changes.
* @param {!Array<!MutationRecord>} records
* @param {!MutationObserver} self
*/
}, {
key: '_onMutation',
value: function _onMutation(records, self) {
records.forEach(function (record) {
var target = /** @type {!HTMLElement} */record.target;
if (record.type === 'childList') {
// Manage added nodes
slice.call(record.addedNodes).forEach(function (node) {
this._makeSubtreeUnfocusable(node);
}, this);
// Un-manage removed nodes
slice.call(record.removedNodes).forEach(function (node) {
this._unmanageSubtree(node);
}, this);
} else if (record.type === 'attributes') {
if (record.attributeName === 'tabindex') {
// Re-initialise inert node if tabindex changes
this._manageNode(target);
} else if (target !== this._rootElement && record.attributeName === 'inert' && target.hasAttribute('inert')) {
// If a new inert root is added, adopt its managed nodes and make sure it knows about the
// already managed nodes from this inert subroot.
this._adoptInertRoot(target);
var inertSubroot = this._inertManager.getInertRoot(target);
this._managedNodes.forEach(function (managedNode) {
if (target.contains(managedNode.node)) {
inertSubroot._manageNode(managedNode.node);
}
});
}
}
}, this);
}
}, {
key: 'managedNodes',
get: function get() {
return new Set(this._managedNodes);
}
/** @return {boolean} */
}, {
key: 'hasSavedAriaHidden',
get: function get() {
return this._savedAriaHidden !== null;
}
/** @param {?string} ariaHidden */
}, {
key: 'savedAriaHidden',
set: function set(ariaHidden) {
this._savedAriaHidden = ariaHidden;
}
/** @return {?string} */
,
get: function get() {
return this._savedAriaHidden;
}
}]);
return InertRoot;
}();
/**
* `InertNode` initialises and manages a single inert node.
* A node is inert if it is a descendant of one or more inert root elements.
*
* On construction, `InertNode` saves the existing `tabindex` value for the node, if any, and
* either removes the `tabindex` attribute or sets it to `-1`, depending on whether the element
* is intrinsically focusable or not.
*
* `InertNode` maintains a set of `InertRoot`s which are descendants of this `InertNode`. When an
* `InertRoot` is destroyed, and calls `InertManager.deregister()`, the `InertManager` notifies the
* `InertNode` via `removeInertRoot()`, which in turn destroys the `InertNode` if no `InertRoot`s
* remain in the set. On destruction, `InertNode` reinstates the stored `tabindex` if one exists,
* or removes the `tabindex` attribute if the element is intrinsically focusable.
*/
var InertNode = function () {
/**
* @param {!Node} node A focusable element to be made inert.
* @param {!InertRoot} inertRoot The inert root element associated with this inert node.
*/
function InertNode(node, inertRoot) {
_classCallCheck(this, InertNode);
/** @type {!Node} */
this._node = node;
/** @type {boolean} */
this._overrodeFocusMethod = false;
/**
* @type {!Set<!InertRoot>} The set of descendant inert roots.
* If and only if this set becomes empty, this node is no longer inert.
*/
this._inertRoots = new Set([inertRoot]);
/** @type {?number} */
this._savedTabIndex = null;
/** @type {boolean} */
this._destroyed = false;
// Save any prior tabindex info and make this node untabbable
this.ensureUntabbable();
}
/**
* Call this whenever this object is about to become obsolete.
* This makes the managed node focusable again and deletes all of the previously stored state.
*/
_createClass(InertNode, [{
key: 'destructor',
value: function destructor() {
this._throwIfDestroyed();
if (this._node && this._node.nodeType === Node.ELEMENT_NODE) {
var element = /** @type {!HTMLElement} */this._node;
if (this._savedTabIndex !== null) {
element.setAttribute('tabindex', this._savedTabIndex);
} else {
element.removeAttribute('tabindex');
}
// Use `delete` to restore native focus method.
if (this._overrodeFocusMethod) {
delete element.focus;
}
}
// See note in InertRoot.destructor for why we cast these nulls to ANY.
this._node = /** @type {?} */null;
this._inertRoots = /** @type {?} */null;
this._destroyed = true;
}
/**
* @type {boolean} Whether this object is obsolete because the managed node is no longer inert.
* If the object has been destroyed, any attempt to access it will cause an exception.
*/
}, {
key: '_throwIfDestroyed',
/**
* Throw if user tries to access destroyed InertNode.
*/
value: function _throwIfDestroyed() {
if (this.destroyed) {
throw new Error('Trying to access destroyed InertNode');
}
}
/** @return {boolean} */
}, {
key: 'ensureUntabbable',
/** Save the existing tabindex value and make the node untabbable and unfocusable */
value: function ensureUntabbable() {
if (this.node.nodeType !== Node.ELEMENT_NODE) {
return;
}
var element = /** @type {!HTMLElement} */this.node;
if (matches.call(element, _focusableElementsString)) {
if ( /** @type {!HTMLElement} */element.tabIndex === -1 && this.hasSavedTabIndex) {
return;
}
if (element.hasAttribute('tabindex')) {
this._savedTabIndex = /** @type {!HTMLElement} */element.tabIndex;
}
element.setAttribute('tabindex', '-1');
if (element.nodeType === Node.ELEMENT_NODE) {
element.focus = function () {};
this._overrodeFocusMethod = true;
}
} else if (element.hasAttribute('tabindex')) {
this._savedTabIndex = /** @type {!HTMLElement} */element.tabIndex;
element.removeAttribute('tabindex');
}
}
/**
* Add another inert root to this inert node's set of managing inert roots.
* @param {!InertRoot} inertRoot
*/
}, {
key: 'addInertRoot',
value: function addInertRoot(inertRoot) {
this._throwIfDestroyed();
this._inertRoots.add(inertRoot);
}
/**
* Remove the given inert root from this inert node's set of managing inert roots.
* If the set of managing inert roots becomes empty, this node is no longer inert,
* so the object should be destroyed.
* @param {!InertRoot} inertRoot
*/
}, {
key: 'removeInertRoot',
value: function removeInertRoot(inertRoot) {
this._throwIfDestroyed();
this._inertRoots['delete'](inertRoot);
if (this._inertRoots.size === 0) {
this.destructor();
}
}
}, {
key: 'destroyed',
get: function get() {
return (/** @type {!InertNode} */this._destroyed
);
}
}, {
key: 'hasSavedTabIndex',
get: function get() {
return this._savedTabIndex !== null;
}
/** @return {!Node} */
}, {
key: 'node',
get: function get() {
this._throwIfDestroyed();
return this._node;
}
/** @param {?number} tabIndex */
}, {
key: 'savedTabIndex',
set: function set(tabIndex) {
this._throwIfDestroyed();
this._savedTabIndex = tabIndex;
}
/** @return {?number} */
,
get: function get() {
this._throwIfDestroyed();
return this._savedTabIndex;
}
}]);
return InertNode;
}();
/**
* InertManager is a per-document singleton object which manages all inert roots and nodes.
*
* When an element becomes an inert root by having an `inert` attribute set and/or its `inert`
* property set to `true`, the `setInert` method creates an `InertRoot` object for the element.
* The `InertRoot` in turn registers itself as managing all of the element's focusable descendant
* nodes via the `register()` method. The `InertManager` ensures that a single `InertNode` instance
* is created for each such node, via the `_managedNodes` map.
*/
var InertManager = function () {
/**
* @param {!Document} document
*/
function InertManager(document) {
_classCallCheck(this, InertManager);
if (!document) {
throw new Error('Missing required argument; InertManager needs to wrap a document.');
}
/** @type {!Document} */
this._document = document;
/**
* All managed nodes known to this InertManager. In a map to allow looking up by Node.
* @type {!Map<!Node, !InertNode>}
*/
this._managedNodes = new Map();
/**
* All inert roots known to this InertManager. In a map to allow looking up by Node.
* @type {!Map<!Node, !InertRoot>}
*/
this._inertRoots = new Map();
/**
* Observer for mutations on `document.body`.
* @type {!MutationObserver}
*/
this._observer = new MutationObserver(this._watchForInert.bind(this));
// Add inert style.
addInertStyle(document.head || document.body || document.documentElement);
// Wait for document to be loaded.
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', this._onDocumentLoaded.bind(this));
} else {
this._onDocumentLoaded();
}
}
/**
* Set whether the given element should be an inert root or not.
* @param {!HTMLElement} root
* @param {boolean} inert
*/
_createClass(InertManager, [{
key: 'setInert',
value: function setInert(root, inert) {
if (inert) {
if (this._inertRoots.has(root)) {
// element is already inert
return;
}
var inertRoot = new InertRoot(root, this);
root.setAttribute('inert', '');
this._inertRoots.set(root, inertRoot);
// If not contained in the document, it must be in a shadowRoot.
// Ensure inert styles are added there.
if (!this._document.body.contains(root)) {
var parent = root.parentNode;
while (parent) {
if (parent.nodeType === 11) {
addInertStyle(parent);
}
parent = parent.parentNode;
}
}
} else {
if (!this._inertRoots.has(root)) {
// element is already non-inert
return;
}
var _inertRoot = this._inertRoots.get(root);
_inertRoot.destructor();
this._inertRoots['delete'](root);
root.removeAttribute('inert');
}
}
/**
* Get the InertRoot object corresponding to the given inert root element, if any.
* @param {!Node} element
* @return {!InertRoot|undefined}
*/
}, {
key: 'getInertRoot',
value: function getInertRoot(element) {
return this._inertRoots.get(element);
}
/**
* Register the given InertRoot as managing the given node.
* In the case where the node has a previously existing inert root, this inert root will
* be added to its set of inert roots.
* @param {!Node} node
* @param {!InertRoot} inertRoot
* @return {!InertNode} inertNode
*/
}, {
key: 'register',
value: function register(node, inertRoot) {
var inertNode = this._managedNodes.get(node);
if (inertNode !== undefined) {
// node was already in an inert subtree
inertNode.addInertRoot(inertRoot);
} else {
inertNode = new InertNode(node, inertRoot);
}
this._managedNodes.set(node, inertNode);
return inertNode;
}
/**
* De-register the given InertRoot as managing the given inert node.
* Removes the inert root from the InertNode's set of managing inert roots, and remove the inert
* node from the InertManager's set of managed nodes if it is destroyed.
* If the node is not currently managed, this is essentially a no-op.
* @param {!Node} node
* @param {!InertRoot} inertRoot
* @return {?InertNode} The potentially destroyed InertNode associated with this node, if any.
*/
}, {
key: 'deregister',
value: function deregister(node, inertRoot) {
var inertNode = this._managedNodes.get(node);
if (!inertNode) {
return null;
}
inertNode.removeInertRoot(inertRoot);
if (inertNode.destroyed) {
this._managedNodes['delete'](node);
}
return inertNode;
}
/**
* Callback used when document has finished loading.
*/
}, {
key: '_onDocumentLoaded',
value: function _onDocumentLoaded() {
// Find all inert roots in document and make them actually inert.
var inertElements = slice.call(this._document.querySelectorAll('[inert]'));
inertElements.forEach(function (inertElement) {
this.setInert(inertElement, true);
}, this);
// Comment this out to use programmatic API only.
this._observer.observe(this._document.body || this._document.documentElement, { attributes: true, subtree: true, childList: true });
}
/**
* Callback used when mutation observer detects attribute changes.
* @param {!Array<!MutationRecord>} records
* @param {!MutationObserver} self
*/
}, {
key: '_watchForInert',
value: function _watchForInert(records, self) {
var _this = this;
records.forEach(function (record) {
switch (record.type) {
case 'childList':
slice.call(record.addedNodes).forEach(function (node) {
if (node.nodeType !== Node.ELEMENT_NODE) {
return;
}
var inertElements = slice.call(node.querySelectorAll('[inert]'));
if (matches.call(node, '[inert]')) {
inertElements.unshift(node);
}
inertElements.forEach(function (inertElement) {
this.setInert(inertElement, true);
}, _this);
}, _this);
break;
case 'attributes':
if (record.attributeName !== 'inert') {
return;
}
var target = /** @type {!HTMLElement} */record.target;
var inert = target.hasAttribute('inert');
_this.setInert(target, inert);
break;
}
}, this);
}
}]);
return InertManager;
}();
/**
* Recursively walk the composed tree from |node|.
* @param {!Node} node
* @param {(function (!HTMLElement))=} callback Callback to be called for each element traversed,
* before descending into child nodes.
* @param {?ShadowRoot=} shadowRootAncestor The nearest ShadowRoot ancestor, if any.
*/
function composedTreeWalk(node, callback, shadowRootAncestor) {
if (node.nodeType == Node.ELEMENT_NODE) {
var element = /** @type {!HTMLElement} */node;
if (callback) {
callback(element);
}
// Descend into node:
// If it has a ShadowRoot, ignore all child elements - these will be picked
// up by the <content> or <shadow> elements. Descend straight into the
// ShadowRoot.
var shadowRoot = /** @type {!HTMLElement} */element.shadowRoot;
if (shadowRoot) {
composedTreeWalk(shadowRoot, callback, shadowRoot);
return;
}
// If it is a <content> element, descend into distributed elements - these
// are elements from outside the shadow root which are rendered inside the
// shadow DOM.
if (element.localName == 'content') {
var content = /** @type {!HTMLContentElement} */element;
// Verifies if ShadowDom v0 is supported.
var distributedNodes = content.getDistributedNodes ? content.getDistributedNodes() : [];
for (var i = 0; i < distributedNodes.length; i++) {
composedTreeWalk(distributedNodes[i], callback, shadowRootAncestor);
}
return;
}
// If it is a <slot> element, descend into assigned nodes - these
// are elements from outside the shadow root which are rendered inside the
// shadow DOM.
if (element.localName == 'slot') {
var slot = /** @type {!HTMLSlotElement} */element;
// Verify if ShadowDom v1 is supported.
var _distributedNodes = slot.assignedNodes ? slot.assignedNodes({ flatten: true }) : [];
for (var _i = 0; _i < _distributedNodes.length; _i++) {
composedTreeWalk(_distributedNodes[_i], callback, shadowRootAncestor);
}
return;
}
}
// If it is neither the parent of a ShadowRoot, a <content> element, a <slot>
// element, nor a <shadow> element recurse normally.
var child = node.firstChild;
while (child != null) {
composedTreeWalk(child, callback, shadowRootAncestor);
child = child.nextSibling;
}
}
/**
* Adds a style element to the node containing the inert specific styles
* @param {!Node} node
*/
function addInertStyle(node) {
if (node.querySelector('style#inert-style, link#inert-style')) {
return;
}
var style = document.createElement('style');
style.setAttribute('id', 'inert-style');
style.textContent = '\n' + '[inert] {\n' + ' pointer-events: none;\n' + ' cursor: default;\n' + '}\n' + '\n' + '[inert], [inert] * {\n' + ' -webkit-user-select: none;\n' + ' -moz-user-select: none;\n' + ' -ms-user-select: none;\n' + ' user-select: none;\n' + '}\n';
node.appendChild(style);
}
if (!HTMLElement.prototype.hasOwnProperty('inert')) {
/** @type {!InertManager} */
var inertManager = new InertManager(document);
Object.defineProperty(HTMLElement.prototype, 'inert', {
enumerable: true,
/** @this {!HTMLElement} */
get: function get() {
return this.hasAttribute('inert');
},
/** @this {!HTMLElement} */
set: function set(inert) {
inertManager.setInert(this, inert);
}
});
}
})();
})));
vendor/wp-polyfill-url.min.js 0000666 00000133747 15123355174 0012270 0 ustar 00 !function e(t,n,r){function i(o,s){if(!n[o]){if(!t[o]){var l="function"==typeof require&&require;if(!s&&l)return l(o,!0);if(a)return a(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var u=n[o]={exports:{}};t[o][0].call(u.exports,(function(e){return i(t[o][1][e]||e)}),u,u.exports,e,t,n,r)}return n[o].exports}for(var a="function"==typeof require&&require,o=0;o<r.length;o++)i(r[o]);return i}({1:[function(e,t,n){t.exports=function(e){if("function"!=typeof e)throw TypeError(String(e)+" is not a function");return e}},{}],2:[function(e,t,n){var r=e("../internals/is-object");t.exports=function(e){if(!r(e)&&null!==e)throw TypeError("Can't set "+String(e)+" as a prototype");return e}},{"../internals/is-object":37}],3:[function(e,t,n){var r=e("../internals/well-known-symbol"),i=e("../internals/object-create"),a=e("../internals/object-define-property"),o=r("unscopables"),s=Array.prototype;null==s[o]&&a.f(s,o,{configurable:!0,value:i(null)}),t.exports=function(e){s[o][e]=!0}},{"../internals/object-create":45,"../internals/object-define-property":47,"../internals/well-known-symbol":77}],4:[function(e,t,n){t.exports=function(e,t,n){if(!(e instanceof t))throw TypeError("Incorrect "+(n?n+" ":"")+"invocation");return e}},{}],5:[function(e,t,n){var r=e("../internals/is-object");t.exports=function(e){if(!r(e))throw TypeError(String(e)+" is not an object");return e}},{"../internals/is-object":37}],6:[function(e,t,n){"use strict";var r=e("../internals/function-bind-context"),i=e("../internals/to-object"),a=e("../internals/call-with-safe-iteration-closing"),o=e("../internals/is-array-iterator-method"),s=e("../internals/to-length"),l=e("../internals/create-property"),c=e("../internals/get-iterator-method");t.exports=function(e){var t,n,u,f,p,h,b=i(e),d="function"==typeof this?this:Array,y=arguments.length,g=y>1?arguments[1]:void 0,v=void 0!==g,m=c(b),w=0;if(v&&(g=r(g,y>2?arguments[2]:void 0,2)),null==m||d==Array&&o(m))for(n=new d(t=s(b.length));t>w;w++)h=v?g(b[w],w):b[w],l(n,w,h);else for(p=(f=m.call(b)).next,n=new d;!(u=p.call(f)).done;w++)h=v?a(f,g,[u.value,w],!0):u.value,l(n,w,h);return n.length=w,n}},{"../internals/call-with-safe-iteration-closing":8,"../internals/create-property":16,"../internals/function-bind-context":23,"../internals/get-iterator-method":25,"../internals/is-array-iterator-method":35,"../internals/to-length":71,"../internals/to-object":72}],7:[function(e,t,n){var r=e("../internals/to-indexed-object"),i=e("../internals/to-length"),a=e("../internals/to-absolute-index"),o=function(e){return function(t,n,o){var s,l=r(t),c=i(l.length),u=a(o,c);if(e&&n!=n){for(;c>u;)if((s=l[u++])!=s)return!0}else for(;c>u;u++)if((e||u in l)&&l[u]===n)return e||u||0;return!e&&-1}};t.exports={includes:o(!0),indexOf:o(!1)}},{"../internals/to-absolute-index":68,"../internals/to-indexed-object":69,"../internals/to-length":71}],8:[function(e,t,n){var r=e("../internals/an-object");t.exports=function(e,t,n,i){try{return i?t(r(n)[0],n[1]):t(n)}catch(t){var a=e.return;throw void 0!==a&&r(a.call(e)),t}}},{"../internals/an-object":5}],9:[function(e,t,n){var r={}.toString;t.exports=function(e){return r.call(e).slice(8,-1)}},{}],10:[function(e,t,n){var r=e("../internals/to-string-tag-support"),i=e("../internals/classof-raw"),a=e("../internals/well-known-symbol")("toStringTag"),o="Arguments"==i(function(){return arguments}());t.exports=r?i:function(e){var t,n,r;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=function(e,t){try{return e[t]}catch(e){}}(t=Object(e),a))?n:o?i(t):"Object"==(r=i(t))&&"function"==typeof t.callee?"Arguments":r}},{"../internals/classof-raw":9,"../internals/to-string-tag-support":74,"../internals/well-known-symbol":77}],11:[function(e,t,n){var r=e("../internals/has"),i=e("../internals/own-keys"),a=e("../internals/object-get-own-property-descriptor"),o=e("../internals/object-define-property");t.exports=function(e,t){for(var n=i(t),s=o.f,l=a.f,c=0;c<n.length;c++){var u=n[c];r(e,u)||s(e,u,l(t,u))}}},{"../internals/has":28,"../internals/object-define-property":47,"../internals/object-get-own-property-descriptor":48,"../internals/own-keys":56}],12:[function(e,t,n){var r=e("../internals/fails");t.exports=!r((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}))},{"../internals/fails":22}],13:[function(e,t,n){"use strict";var r=e("../internals/iterators-core").IteratorPrototype,i=e("../internals/object-create"),a=e("../internals/create-property-descriptor"),o=e("../internals/set-to-string-tag"),s=e("../internals/iterators"),l=function(){return this};t.exports=function(e,t,n){var c=t+" Iterator";return e.prototype=i(r,{next:a(1,n)}),o(e,c,!1,!0),s[c]=l,e}},{"../internals/create-property-descriptor":15,"../internals/iterators":40,"../internals/iterators-core":39,"../internals/object-create":45,"../internals/set-to-string-tag":62}],14:[function(e,t,n){var r=e("../internals/descriptors"),i=e("../internals/object-define-property"),a=e("../internals/create-property-descriptor");t.exports=r?function(e,t,n){return i.f(e,t,a(1,n))}:function(e,t,n){return e[t]=n,e}},{"../internals/create-property-descriptor":15,"../internals/descriptors":18,"../internals/object-define-property":47}],15:[function(e,t,n){t.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},{}],16:[function(e,t,n){"use strict";var r=e("../internals/to-primitive"),i=e("../internals/object-define-property"),a=e("../internals/create-property-descriptor");t.exports=function(e,t,n){var o=r(t);o in e?i.f(e,o,a(0,n)):e[o]=n}},{"../internals/create-property-descriptor":15,"../internals/object-define-property":47,"../internals/to-primitive":73}],17:[function(e,t,n){"use strict";var r=e("../internals/export"),i=e("../internals/create-iterator-constructor"),a=e("../internals/object-get-prototype-of"),o=e("../internals/object-set-prototype-of"),s=e("../internals/set-to-string-tag"),l=e("../internals/create-non-enumerable-property"),c=e("../internals/redefine"),u=e("../internals/well-known-symbol"),f=e("../internals/is-pure"),p=e("../internals/iterators"),h=e("../internals/iterators-core"),b=h.IteratorPrototype,d=h.BUGGY_SAFARI_ITERATORS,y=u("iterator"),g=function(){return this};t.exports=function(e,t,n,u,h,v,m){i(n,t,u);var w,j,x,k=function(e){if(e===h&&L)return L;if(!d&&e in O)return O[e];switch(e){case"keys":case"values":case"entries":return function(){return new n(this,e)}}return function(){return new n(this)}},S=t+" Iterator",A=!1,O=e.prototype,R=O[y]||O["@@iterator"]||h&&O[h],L=!d&&R||k(h),U="Array"==t&&O.entries||R;if(U&&(w=a(U.call(new e)),b!==Object.prototype&&w.next&&(f||a(w)===b||(o?o(w,b):"function"!=typeof w[y]&&l(w,y,g)),s(w,S,!0,!0),f&&(p[S]=g))),"values"==h&&R&&"values"!==R.name&&(A=!0,L=function(){return R.call(this)}),f&&!m||O[y]===L||l(O,y,L),p[t]=L,h)if(j={values:k("values"),keys:v?L:k("keys"),entries:k("entries")},m)for(x in j)!d&&!A&&x in O||c(O,x,j[x]);else r({target:t,proto:!0,forced:d||A},j);return j}},{"../internals/create-iterator-constructor":13,"../internals/create-non-enumerable-property":14,"../internals/export":21,"../internals/is-pure":38,"../internals/iterators":40,"../internals/iterators-core":39,"../internals/object-get-prototype-of":51,"../internals/object-set-prototype-of":55,"../internals/redefine":59,"../internals/set-to-string-tag":62,"../internals/well-known-symbol":77}],18:[function(e,t,n){var r=e("../internals/fails");t.exports=!r((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]}))},{"../internals/fails":22}],19:[function(e,t,n){var r=e("../internals/global"),i=e("../internals/is-object"),a=r.document,o=i(a)&&i(a.createElement);t.exports=function(e){return o?a.createElement(e):{}}},{"../internals/global":27,"../internals/is-object":37}],20:[function(e,t,n){t.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},{}],21:[function(e,t,n){var r=e("../internals/global"),i=e("../internals/object-get-own-property-descriptor").f,a=e("../internals/create-non-enumerable-property"),o=e("../internals/redefine"),s=e("../internals/set-global"),l=e("../internals/copy-constructor-properties"),c=e("../internals/is-forced");t.exports=function(e,t){var n,u,f,p,h,b=e.target,d=e.global,y=e.stat;if(n=d?r:y?r[b]||s(b,{}):(r[b]||{}).prototype)for(u in t){if(p=t[u],f=e.noTargetGet?(h=i(n,u))&&h.value:n[u],!c(d?u:b+(y?".":"#")+u,e.forced)&&void 0!==f){if(typeof p==typeof f)continue;l(p,f)}(e.sham||f&&f.sham)&&a(p,"sham",!0),o(n,u,p,e)}}},{"../internals/copy-constructor-properties":11,"../internals/create-non-enumerable-property":14,"../internals/global":27,"../internals/is-forced":36,"../internals/object-get-own-property-descriptor":48,"../internals/redefine":59,"../internals/set-global":61}],22:[function(e,t,n){t.exports=function(e){try{return!!e()}catch(e){return!0}}},{}],23:[function(e,t,n){var r=e("../internals/a-function");t.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 0:return function(){return e.call(t)};case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,i){return e.call(t,n,r,i)}}return function(){return e.apply(t,arguments)}}},{"../internals/a-function":1}],24:[function(e,t,n){var r=e("../internals/path"),i=e("../internals/global"),a=function(e){return"function"==typeof e?e:void 0};t.exports=function(e,t){return arguments.length<2?a(r[e])||a(i[e]):r[e]&&r[e][t]||i[e]&&i[e][t]}},{"../internals/global":27,"../internals/path":57}],25:[function(e,t,n){var r=e("../internals/classof"),i=e("../internals/iterators"),a=e("../internals/well-known-symbol")("iterator");t.exports=function(e){if(null!=e)return e[a]||e["@@iterator"]||i[r(e)]}},{"../internals/classof":10,"../internals/iterators":40,"../internals/well-known-symbol":77}],26:[function(e,t,n){var r=e("../internals/an-object"),i=e("../internals/get-iterator-method");t.exports=function(e){var t=i(e);if("function"!=typeof t)throw TypeError(String(e)+" is not iterable");return r(t.call(e))}},{"../internals/an-object":5,"../internals/get-iterator-method":25}],27:[function(e,t,n){(function(e){var n=function(e){return e&&e.Math==Math&&e};t.exports=n("object"==typeof globalThis&&globalThis)||n("object"==typeof window&&window)||n("object"==typeof self&&self)||n("object"==typeof e&&e)||Function("return this")()}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],28:[function(e,t,n){var r={}.hasOwnProperty;t.exports=function(e,t){return r.call(e,t)}},{}],29:[function(e,t,n){t.exports={}},{}],30:[function(e,t,n){var r=e("../internals/get-built-in");t.exports=r("document","documentElement")},{"../internals/get-built-in":24}],31:[function(e,t,n){var r=e("../internals/descriptors"),i=e("../internals/fails"),a=e("../internals/document-create-element");t.exports=!r&&!i((function(){return 7!=Object.defineProperty(a("div"),"a",{get:function(){return 7}}).a}))},{"../internals/descriptors":18,"../internals/document-create-element":19,"../internals/fails":22}],32:[function(e,t,n){var r=e("../internals/fails"),i=e("../internals/classof-raw"),a="".split;t.exports=r((function(){return!Object("z").propertyIsEnumerable(0)}))?function(e){return"String"==i(e)?a.call(e,""):Object(e)}:Object},{"../internals/classof-raw":9,"../internals/fails":22}],33:[function(e,t,n){var r=e("../internals/shared-store"),i=Function.toString;"function"!=typeof r.inspectSource&&(r.inspectSource=function(e){return i.call(e)}),t.exports=r.inspectSource},{"../internals/shared-store":64}],34:[function(e,t,n){var r,i,a,o=e("../internals/native-weak-map"),s=e("../internals/global"),l=e("../internals/is-object"),c=e("../internals/create-non-enumerable-property"),u=e("../internals/has"),f=e("../internals/shared-key"),p=e("../internals/hidden-keys"),h=s.WeakMap;if(o){var b=new h,d=b.get,y=b.has,g=b.set;r=function(e,t){return g.call(b,e,t),t},i=function(e){return d.call(b,e)||{}},a=function(e){return y.call(b,e)}}else{var v=f("state");p[v]=!0,r=function(e,t){return c(e,v,t),t},i=function(e){return u(e,v)?e[v]:{}},a=function(e){return u(e,v)}}t.exports={set:r,get:i,has:a,enforce:function(e){return a(e)?i(e):r(e,{})},getterFor:function(e){return function(t){var n;if(!l(t)||(n=i(t)).type!==e)throw TypeError("Incompatible receiver, "+e+" required");return n}}}},{"../internals/create-non-enumerable-property":14,"../internals/global":27,"../internals/has":28,"../internals/hidden-keys":29,"../internals/is-object":37,"../internals/native-weak-map":43,"../internals/shared-key":63}],35:[function(e,t,n){var r=e("../internals/well-known-symbol"),i=e("../internals/iterators"),a=r("iterator"),o=Array.prototype;t.exports=function(e){return void 0!==e&&(i.Array===e||o[a]===e)}},{"../internals/iterators":40,"../internals/well-known-symbol":77}],36:[function(e,t,n){var r=e("../internals/fails"),i=/#|\.prototype\./,a=function(e,t){var n=s[o(e)];return n==c||n!=l&&("function"==typeof t?r(t):!!t)},o=a.normalize=function(e){return String(e).replace(i,".").toLowerCase()},s=a.data={},l=a.NATIVE="N",c=a.POLYFILL="P";t.exports=a},{"../internals/fails":22}],37:[function(e,t,n){t.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},{}],38:[function(e,t,n){t.exports=!1},{}],39:[function(e,t,n){"use strict";var r,i,a,o=e("../internals/object-get-prototype-of"),s=e("../internals/create-non-enumerable-property"),l=e("../internals/has"),c=e("../internals/well-known-symbol"),u=e("../internals/is-pure"),f=c("iterator"),p=!1;[].keys&&("next"in(a=[].keys())?(i=o(o(a)))!==Object.prototype&&(r=i):p=!0),null==r&&(r={}),u||l(r,f)||s(r,f,(function(){return this})),t.exports={IteratorPrototype:r,BUGGY_SAFARI_ITERATORS:p}},{"../internals/create-non-enumerable-property":14,"../internals/has":28,"../internals/is-pure":38,"../internals/object-get-prototype-of":51,"../internals/well-known-symbol":77}],40:[function(e,t,n){arguments[4][29][0].apply(n,arguments)},{dup:29}],41:[function(e,t,n){var r=e("../internals/fails");t.exports=!!Object.getOwnPropertySymbols&&!r((function(){return!String(Symbol())}))},{"../internals/fails":22}],42:[function(e,t,n){var r=e("../internals/fails"),i=e("../internals/well-known-symbol"),a=e("../internals/is-pure"),o=i("iterator");t.exports=!r((function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,n="";return e.pathname="c%20d",t.forEach((function(e,r){t.delete("b"),n+=r+e})),a&&!e.toJSON||!t.sort||"http://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[o]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==n||"x"!==new URL("http://x",void 0).host}))},{"../internals/fails":22,"../internals/is-pure":38,"../internals/well-known-symbol":77}],43:[function(e,t,n){var r=e("../internals/global"),i=e("../internals/inspect-source"),a=r.WeakMap;t.exports="function"==typeof a&&/native code/.test(i(a))},{"../internals/global":27,"../internals/inspect-source":33}],44:[function(e,t,n){"use strict";var r=e("../internals/descriptors"),i=e("../internals/fails"),a=e("../internals/object-keys"),o=e("../internals/object-get-own-property-symbols"),s=e("../internals/object-property-is-enumerable"),l=e("../internals/to-object"),c=e("../internals/indexed-object"),u=Object.assign,f=Object.defineProperty;t.exports=!u||i((function(){if(r&&1!==u({b:1},u(f({},"a",{enumerable:!0,get:function(){f(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},n=Symbol();return e[n]=7,"abcdefghijklmnopqrst".split("").forEach((function(e){t[e]=e})),7!=u({},e)[n]||"abcdefghijklmnopqrst"!=a(u({},t)).join("")}))?function(e,t){for(var n=l(e),i=arguments.length,u=1,f=o.f,p=s.f;i>u;)for(var h,b=c(arguments[u++]),d=f?a(b).concat(f(b)):a(b),y=d.length,g=0;y>g;)h=d[g++],r&&!p.call(b,h)||(n[h]=b[h]);return n}:u},{"../internals/descriptors":18,"../internals/fails":22,"../internals/indexed-object":32,"../internals/object-get-own-property-symbols":50,"../internals/object-keys":53,"../internals/object-property-is-enumerable":54,"../internals/to-object":72}],45:[function(e,t,n){var r,i=e("../internals/an-object"),a=e("../internals/object-define-properties"),o=e("../internals/enum-bug-keys"),s=e("../internals/hidden-keys"),l=e("../internals/html"),c=e("../internals/document-create-element"),u=e("../internals/shared-key")("IE_PROTO"),f=function(){},p=function(e){return"<script>"+e+"<\/script>"},h=function(){try{r=document.domain&&new ActiveXObject("htmlfile")}catch(e){}var e,t;h=r?function(e){e.write(p("")),e.close();var t=e.parentWindow.Object;return e=null,t}(r):((t=c("iframe")).style.display="none",l.appendChild(t),t.src=String("javascript:"),(e=t.contentWindow.document).open(),e.write(p("document.F=Object")),e.close(),e.F);for(var n=o.length;n--;)delete h.prototype[o[n]];return h()};s[u]=!0,t.exports=Object.create||function(e,t){var n;return null!==e?(f.prototype=i(e),n=new f,f.prototype=null,n[u]=e):n=h(),void 0===t?n:a(n,t)}},{"../internals/an-object":5,"../internals/document-create-element":19,"../internals/enum-bug-keys":20,"../internals/hidden-keys":29,"../internals/html":30,"../internals/object-define-properties":46,"../internals/shared-key":63}],46:[function(e,t,n){var r=e("../internals/descriptors"),i=e("../internals/object-define-property"),a=e("../internals/an-object"),o=e("../internals/object-keys");t.exports=r?Object.defineProperties:function(e,t){a(e);for(var n,r=o(t),s=r.length,l=0;s>l;)i.f(e,n=r[l++],t[n]);return e}},{"../internals/an-object":5,"../internals/descriptors":18,"../internals/object-define-property":47,"../internals/object-keys":53}],47:[function(e,t,n){var r=e("../internals/descriptors"),i=e("../internals/ie8-dom-define"),a=e("../internals/an-object"),o=e("../internals/to-primitive"),s=Object.defineProperty;n.f=r?s:function(e,t,n){if(a(e),t=o(t,!0),a(n),i)try{return s(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported");return"value"in n&&(e[t]=n.value),e}},{"../internals/an-object":5,"../internals/descriptors":18,"../internals/ie8-dom-define":31,"../internals/to-primitive":73}],48:[function(e,t,n){var r=e("../internals/descriptors"),i=e("../internals/object-property-is-enumerable"),a=e("../internals/create-property-descriptor"),o=e("../internals/to-indexed-object"),s=e("../internals/to-primitive"),l=e("../internals/has"),c=e("../internals/ie8-dom-define"),u=Object.getOwnPropertyDescriptor;n.f=r?u:function(e,t){if(e=o(e),t=s(t,!0),c)try{return u(e,t)}catch(e){}if(l(e,t))return a(!i.f.call(e,t),e[t])}},{"../internals/create-property-descriptor":15,"../internals/descriptors":18,"../internals/has":28,"../internals/ie8-dom-define":31,"../internals/object-property-is-enumerable":54,"../internals/to-indexed-object":69,"../internals/to-primitive":73}],49:[function(e,t,n){var r=e("../internals/object-keys-internal"),i=e("../internals/enum-bug-keys").concat("length","prototype");n.f=Object.getOwnPropertyNames||function(e){return r(e,i)}},{"../internals/enum-bug-keys":20,"../internals/object-keys-internal":52}],50:[function(e,t,n){n.f=Object.getOwnPropertySymbols},{}],51:[function(e,t,n){var r=e("../internals/has"),i=e("../internals/to-object"),a=e("../internals/shared-key"),o=e("../internals/correct-prototype-getter"),s=a("IE_PROTO"),l=Object.prototype;t.exports=o?Object.getPrototypeOf:function(e){return e=i(e),r(e,s)?e[s]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?l:null}},{"../internals/correct-prototype-getter":12,"../internals/has":28,"../internals/shared-key":63,"../internals/to-object":72}],52:[function(e,t,n){var r=e("../internals/has"),i=e("../internals/to-indexed-object"),a=e("../internals/array-includes").indexOf,o=e("../internals/hidden-keys");t.exports=function(e,t){var n,s=i(e),l=0,c=[];for(n in s)!r(o,n)&&r(s,n)&&c.push(n);for(;t.length>l;)r(s,n=t[l++])&&(~a(c,n)||c.push(n));return c}},{"../internals/array-includes":7,"../internals/has":28,"../internals/hidden-keys":29,"../internals/to-indexed-object":69}],53:[function(e,t,n){var r=e("../internals/object-keys-internal"),i=e("../internals/enum-bug-keys");t.exports=Object.keys||function(e){return r(e,i)}},{"../internals/enum-bug-keys":20,"../internals/object-keys-internal":52}],54:[function(e,t,n){"use strict";var r={}.propertyIsEnumerable,i=Object.getOwnPropertyDescriptor,a=i&&!r.call({1:2},1);n.f=a?function(e){var t=i(this,e);return!!t&&t.enumerable}:r},{}],55:[function(e,t,n){var r=e("../internals/an-object"),i=e("../internals/a-possible-prototype");t.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,n={};try{(e=Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set).call(n,[]),t=n instanceof Array}catch(e){}return function(n,a){return r(n),i(a),t?e.call(n,a):n.__proto__=a,n}}():void 0)},{"../internals/a-possible-prototype":2,"../internals/an-object":5}],56:[function(e,t,n){var r=e("../internals/get-built-in"),i=e("../internals/object-get-own-property-names"),a=e("../internals/object-get-own-property-symbols"),o=e("../internals/an-object");t.exports=r("Reflect","ownKeys")||function(e){var t=i.f(o(e)),n=a.f;return n?t.concat(n(e)):t}},{"../internals/an-object":5,"../internals/get-built-in":24,"../internals/object-get-own-property-names":49,"../internals/object-get-own-property-symbols":50}],57:[function(e,t,n){var r=e("../internals/global");t.exports=r},{"../internals/global":27}],58:[function(e,t,n){var r=e("../internals/redefine");t.exports=function(e,t,n){for(var i in t)r(e,i,t[i],n);return e}},{"../internals/redefine":59}],59:[function(e,t,n){var r=e("../internals/global"),i=e("../internals/create-non-enumerable-property"),a=e("../internals/has"),o=e("../internals/set-global"),s=e("../internals/inspect-source"),l=e("../internals/internal-state"),c=l.get,u=l.enforce,f=String(String).split("String");(t.exports=function(e,t,n,s){var l=!!s&&!!s.unsafe,c=!!s&&!!s.enumerable,p=!!s&&!!s.noTargetGet;"function"==typeof n&&("string"!=typeof t||a(n,"name")||i(n,"name",t),u(n).source=f.join("string"==typeof t?t:"")),e!==r?(l?!p&&e[t]&&(c=!0):delete e[t],c?e[t]=n:i(e,t,n)):c?e[t]=n:o(t,n)})(Function.prototype,"toString",(function(){return"function"==typeof this&&c(this).source||s(this)}))},{"../internals/create-non-enumerable-property":14,"../internals/global":27,"../internals/has":28,"../internals/inspect-source":33,"../internals/internal-state":34,"../internals/set-global":61}],60:[function(e,t,n){t.exports=function(e){if(null==e)throw TypeError("Can't call method on "+e);return e}},{}],61:[function(e,t,n){var r=e("../internals/global"),i=e("../internals/create-non-enumerable-property");t.exports=function(e,t){try{i(r,e,t)}catch(n){r[e]=t}return t}},{"../internals/create-non-enumerable-property":14,"../internals/global":27}],62:[function(e,t,n){var r=e("../internals/object-define-property").f,i=e("../internals/has"),a=e("../internals/well-known-symbol")("toStringTag");t.exports=function(e,t,n){e&&!i(e=n?e:e.prototype,a)&&r(e,a,{configurable:!0,value:t})}},{"../internals/has":28,"../internals/object-define-property":47,"../internals/well-known-symbol":77}],63:[function(e,t,n){var r=e("../internals/shared"),i=e("../internals/uid"),a=r("keys");t.exports=function(e){return a[e]||(a[e]=i(e))}},{"../internals/shared":65,"../internals/uid":75}],64:[function(e,t,n){var r=e("../internals/global"),i=e("../internals/set-global"),a=r["__core-js_shared__"]||i("__core-js_shared__",{});t.exports=a},{"../internals/global":27,"../internals/set-global":61}],65:[function(e,t,n){var r=e("../internals/is-pure"),i=e("../internals/shared-store");(t.exports=function(e,t){return i[e]||(i[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.6.4",mode:r?"pure":"global",copyright:"© 2020 Denis Pushkarev (zloirock.ru)"})},{"../internals/is-pure":38,"../internals/shared-store":64}],66:[function(e,t,n){var r=e("../internals/to-integer"),i=e("../internals/require-object-coercible"),a=function(e){return function(t,n){var a,o,s=String(i(t)),l=r(n),c=s.length;return l<0||l>=c?e?"":void 0:(a=s.charCodeAt(l))<55296||a>56319||l+1===c||(o=s.charCodeAt(l+1))<56320||o>57343?e?s.charAt(l):a:e?s.slice(l,l+2):o-56320+(a-55296<<10)+65536}};t.exports={codeAt:a(!1),charAt:a(!0)}},{"../internals/require-object-coercible":60,"../internals/to-integer":70}],67:[function(e,t,n){"use strict";var r=/[^\0-\u007E]/,i=/[.\u3002\uFF0E\uFF61]/g,a="Overflow: input needs wider integers to process",o=Math.floor,s=String.fromCharCode,l=function(e){return e+22+75*(e<26)},c=function(e,t,n){var r=0;for(e=n?o(e/700):e>>1,e+=o(e/t);e>455;r+=36)e=o(e/35);return o(r+36*e/(e+38))},u=function(e){var t,n,r=[],i=(e=function(e){for(var t=[],n=0,r=e.length;n<r;){var i=e.charCodeAt(n++);if(i>=55296&&i<=56319&&n<r){var a=e.charCodeAt(n++);56320==(64512&a)?t.push(((1023&i)<<10)+(1023&a)+65536):(t.push(i),n--)}else t.push(i)}return t}(e)).length,u=128,f=0,p=72;for(t=0;t<e.length;t++)(n=e[t])<128&&r.push(s(n));var h=r.length,b=h;for(h&&r.push("-");b<i;){var d=2147483647;for(t=0;t<e.length;t++)(n=e[t])>=u&&n<d&&(d=n);var y=b+1;if(d-u>o((2147483647-f)/y))throw RangeError(a);for(f+=(d-u)*y,u=d,t=0;t<e.length;t++){if((n=e[t])<u&&++f>2147483647)throw RangeError(a);if(n==u){for(var g=f,v=36;;v+=36){var m=v<=p?1:v>=p+26?26:v-p;if(g<m)break;var w=g-m,j=36-m;r.push(s(l(m+w%j))),g=o(w/j)}r.push(s(l(g))),p=c(f,y,b==h),f=0,++b}}++f,++u}return r.join("")};t.exports=function(e){var t,n,a=[],o=e.toLowerCase().replace(i,".").split(".");for(t=0;t<o.length;t++)n=o[t],a.push(r.test(n)?"xn--"+u(n):n);return a.join(".")}},{}],68:[function(e,t,n){var r=e("../internals/to-integer"),i=Math.max,a=Math.min;t.exports=function(e,t){var n=r(e);return n<0?i(n+t,0):a(n,t)}},{"../internals/to-integer":70}],69:[function(e,t,n){var r=e("../internals/indexed-object"),i=e("../internals/require-object-coercible");t.exports=function(e){return r(i(e))}},{"../internals/indexed-object":32,"../internals/require-object-coercible":60}],70:[function(e,t,n){var r=Math.ceil,i=Math.floor;t.exports=function(e){return isNaN(e=+e)?0:(e>0?i:r)(e)}},{}],71:[function(e,t,n){var r=e("../internals/to-integer"),i=Math.min;t.exports=function(e){return e>0?i(r(e),9007199254740991):0}},{"../internals/to-integer":70}],72:[function(e,t,n){var r=e("../internals/require-object-coercible");t.exports=function(e){return Object(r(e))}},{"../internals/require-object-coercible":60}],73:[function(e,t,n){var r=e("../internals/is-object");t.exports=function(e,t){if(!r(e))return e;var n,i;if(t&&"function"==typeof(n=e.toString)&&!r(i=n.call(e)))return i;if("function"==typeof(n=e.valueOf)&&!r(i=n.call(e)))return i;if(!t&&"function"==typeof(n=e.toString)&&!r(i=n.call(e)))return i;throw TypeError("Can't convert object to primitive value")}},{"../internals/is-object":37}],74:[function(e,t,n){var r={};r[e("../internals/well-known-symbol")("toStringTag")]="z",t.exports="[object z]"===String(r)},{"../internals/well-known-symbol":77}],75:[function(e,t,n){var r=0,i=Math.random();t.exports=function(e){return"Symbol("+String(void 0===e?"":e)+")_"+(++r+i).toString(36)}},{}],76:[function(e,t,n){var r=e("../internals/native-symbol");t.exports=r&&!Symbol.sham&&"symbol"==typeof Symbol.iterator},{"../internals/native-symbol":41}],77:[function(e,t,n){var r=e("../internals/global"),i=e("../internals/shared"),a=e("../internals/has"),o=e("../internals/uid"),s=e("../internals/native-symbol"),l=e("../internals/use-symbol-as-uid"),c=i("wks"),u=r.Symbol,f=l?u:u&&u.withoutSetter||o;t.exports=function(e){return a(c,e)||(s&&a(u,e)?c[e]=u[e]:c[e]=f("Symbol."+e)),c[e]}},{"../internals/global":27,"../internals/has":28,"../internals/native-symbol":41,"../internals/shared":65,"../internals/uid":75,"../internals/use-symbol-as-uid":76}],78:[function(e,t,n){"use strict";var r=e("../internals/to-indexed-object"),i=e("../internals/add-to-unscopables"),a=e("../internals/iterators"),o=e("../internals/internal-state"),s=e("../internals/define-iterator"),l=o.set,c=o.getterFor("Array Iterator");t.exports=s(Array,"Array",(function(e,t){l(this,{type:"Array Iterator",target:r(e),index:0,kind:t})}),(function(){var e=c(this),t=e.target,n=e.kind,r=e.index++;return!t||r>=t.length?(e.target=void 0,{value:void 0,done:!0}):"keys"==n?{value:r,done:!1}:"values"==n?{value:t[r],done:!1}:{value:[r,t[r]],done:!1}}),"values"),a.Arguments=a.Array,i("keys"),i("values"),i("entries")},{"../internals/add-to-unscopables":3,"../internals/define-iterator":17,"../internals/internal-state":34,"../internals/iterators":40,"../internals/to-indexed-object":69}],79:[function(e,t,n){"use strict";var r=e("../internals/string-multibyte").charAt,i=e("../internals/internal-state"),a=e("../internals/define-iterator"),o=i.set,s=i.getterFor("String Iterator");a(String,"String",(function(e){o(this,{type:"String Iterator",string:String(e),index:0})}),(function(){var e,t=s(this),n=t.string,i=t.index;return i>=n.length?{value:void 0,done:!0}:(e=r(n,i),t.index+=e.length,{value:e,done:!1})}))},{"../internals/define-iterator":17,"../internals/internal-state":34,"../internals/string-multibyte":66}],80:[function(e,t,n){"use strict";e("../modules/es.array.iterator");var r=e("../internals/export"),i=e("../internals/get-built-in"),a=e("../internals/native-url"),o=e("../internals/redefine"),s=e("../internals/redefine-all"),l=e("../internals/set-to-string-tag"),c=e("../internals/create-iterator-constructor"),u=e("../internals/internal-state"),f=e("../internals/an-instance"),p=e("../internals/has"),h=e("../internals/function-bind-context"),b=e("../internals/classof"),d=e("../internals/an-object"),y=e("../internals/is-object"),g=e("../internals/object-create"),v=e("../internals/create-property-descriptor"),m=e("../internals/get-iterator"),w=e("../internals/get-iterator-method"),j=e("../internals/well-known-symbol"),x=i("fetch"),k=i("Headers"),S=j("iterator"),A=u.set,O=u.getterFor("URLSearchParams"),R=u.getterFor("URLSearchParamsIterator"),L=/\+/g,U=Array(4),P=function(e){return U[e-1]||(U[e-1]=RegExp("((?:%[\\da-f]{2}){"+e+"})","gi"))},I=function(e){try{return decodeURIComponent(e)}catch(t){return e}},q=function(e){var t=e.replace(L," "),n=4;try{return decodeURIComponent(t)}catch(e){for(;n;)t=t.replace(P(n--),I);return t}},E=/[!'()~]|%20/g,_={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},T=function(e){return _[e]},B=function(e){return encodeURIComponent(e).replace(E,T)},F=function(e,t){if(t)for(var n,r,i=t.split("&"),a=0;a<i.length;)(n=i[a++]).length&&(r=n.split("="),e.push({key:q(r.shift()),value:q(r.join("="))}))},C=function(e){this.entries.length=0,F(this.entries,e)},M=function(e,t){if(e<t)throw TypeError("Not enough arguments")},N=c((function(e,t){A(this,{type:"URLSearchParamsIterator",iterator:m(O(e).entries),kind:t})}),"Iterator",(function(){var e=R(this),t=e.kind,n=e.iterator.next(),r=n.value;return n.done||(n.value="keys"===t?r.key:"values"===t?r.value:[r.key,r.value]),n})),D=function(){f(this,D,"URLSearchParams");var e,t,n,r,i,a,o,s,l,c=arguments.length>0?arguments[0]:void 0,u=this,h=[];if(A(u,{type:"URLSearchParams",entries:h,updateURL:function(){},updateSearchParams:C}),void 0!==c)if(y(c))if("function"==typeof(e=w(c)))for(n=(t=e.call(c)).next;!(r=n.call(t)).done;){if((o=(a=(i=m(d(r.value))).next).call(i)).done||(s=a.call(i)).done||!a.call(i).done)throw TypeError("Expected sequence with length 2");h.push({key:o.value+"",value:s.value+""})}else for(l in c)p(c,l)&&h.push({key:l,value:c[l]+""});else F(h,"string"==typeof c?"?"===c.charAt(0)?c.slice(1):c:c+"")},z=D.prototype;s(z,{append:function(e,t){M(arguments.length,2);var n=O(this);n.entries.push({key:e+"",value:t+""}),n.updateURL()},delete:function(e){M(arguments.length,1);for(var t=O(this),n=t.entries,r=e+"",i=0;i<n.length;)n[i].key===r?n.splice(i,1):i++;t.updateURL()},get:function(e){M(arguments.length,1);for(var t=O(this).entries,n=e+"",r=0;r<t.length;r++)if(t[r].key===n)return t[r].value;return null},getAll:function(e){M(arguments.length,1);for(var t=O(this).entries,n=e+"",r=[],i=0;i<t.length;i++)t[i].key===n&&r.push(t[i].value);return r},has:function(e){M(arguments.length,1);for(var t=O(this).entries,n=e+"",r=0;r<t.length;)if(t[r++].key===n)return!0;return!1},set:function(e,t){M(arguments.length,1);for(var n,r=O(this),i=r.entries,a=!1,o=e+"",s=t+"",l=0;l<i.length;l++)(n=i[l]).key===o&&(a?i.splice(l--,1):(a=!0,n.value=s));a||i.push({key:o,value:s}),r.updateURL()},sort:function(){var e,t,n,r=O(this),i=r.entries,a=i.slice();for(i.length=0,n=0;n<a.length;n++){for(e=a[n],t=0;t<n;t++)if(i[t].key>e.key){i.splice(t,0,e);break}t===n&&i.push(e)}r.updateURL()},forEach:function(e){for(var t,n=O(this).entries,r=h(e,arguments.length>1?arguments[1]:void 0,3),i=0;i<n.length;)r((t=n[i++]).value,t.key,this)},keys:function(){return new N(this,"keys")},values:function(){return new N(this,"values")},entries:function(){return new N(this,"entries")}},{enumerable:!0}),o(z,S,z.entries),o(z,"toString",(function(){for(var e,t=O(this).entries,n=[],r=0;r<t.length;)e=t[r++],n.push(B(e.key)+"="+B(e.value));return n.join("&")}),{enumerable:!0}),l(D,"URLSearchParams"),r({global:!0,forced:!a},{URLSearchParams:D}),a||"function"!=typeof x||"function"!=typeof k||r({global:!0,enumerable:!0,forced:!0},{fetch:function(e){var t,n,r,i=[e];return arguments.length>1&&(y(t=arguments[1])&&(n=t.body,"URLSearchParams"===b(n)&&((r=t.headers?new k(t.headers):new k).has("content-type")||r.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),t=g(t,{body:v(0,String(n)),headers:v(0,r)}))),i.push(t)),x.apply(this,i)}}),t.exports={URLSearchParams:D,getState:O}},{"../internals/an-instance":4,"../internals/an-object":5,"../internals/classof":10,"../internals/create-iterator-constructor":13,"../internals/create-property-descriptor":15,"../internals/export":21,"../internals/function-bind-context":23,"../internals/get-built-in":24,"../internals/get-iterator":26,"../internals/get-iterator-method":25,"../internals/has":28,"../internals/internal-state":34,"../internals/is-object":37,"../internals/native-url":42,"../internals/object-create":45,"../internals/redefine":59,"../internals/redefine-all":58,"../internals/set-to-string-tag":62,"../internals/well-known-symbol":77,"../modules/es.array.iterator":78}],81:[function(e,t,n){"use strict";e("../modules/es.string.iterator");var r,i=e("../internals/export"),a=e("../internals/descriptors"),o=e("../internals/native-url"),s=e("../internals/global"),l=e("../internals/object-define-properties"),c=e("../internals/redefine"),u=e("../internals/an-instance"),f=e("../internals/has"),p=e("../internals/object-assign"),h=e("../internals/array-from"),b=e("../internals/string-multibyte").codeAt,d=e("../internals/string-punycode-to-ascii"),y=e("../internals/set-to-string-tag"),g=e("../modules/web.url-search-params"),v=e("../internals/internal-state"),m=s.URL,w=g.URLSearchParams,j=g.getState,x=v.set,k=v.getterFor("URL"),S=Math.floor,A=Math.pow,O=/[A-Za-z]/,R=/[\d+\-.A-Za-z]/,L=/\d/,U=/^(0x|0X)/,P=/^[0-7]+$/,I=/^\d+$/,q=/^[\dA-Fa-f]+$/,E=/[\u0000\u0009\u000A\u000D #%/:?@[\\]]/,_=/[\u0000\u0009\u000A\u000D #/:?@[\\]]/,T=/^[\u0000-\u001F ]+|[\u0000-\u001F ]+$/g,B=/[\u0009\u000A\u000D]/g,F=function(e,t){var n,r,i;if("["==t.charAt(0)){if("]"!=t.charAt(t.length-1))return"Invalid host";if(!(n=M(t.slice(1,-1))))return"Invalid host";e.host=n}else if(Y(e)){if(t=d(t),E.test(t))return"Invalid host";if(null===(n=C(t)))return"Invalid host";e.host=n}else{if(_.test(t))return"Invalid host";for(n="",r=h(t),i=0;i<r.length;i++)n+=$(r[i],D);e.host=n}},C=function(e){var t,n,r,i,a,o,s,l=e.split(".");if(l.length&&""==l[l.length-1]&&l.pop(),(t=l.length)>4)return e;for(n=[],r=0;r<t;r++){if(""==(i=l[r]))return e;if(a=10,i.length>1&&"0"==i.charAt(0)&&(a=U.test(i)?16:8,i=i.slice(8==a?1:2)),""===i)o=0;else{if(!(10==a?I:8==a?P:q).test(i))return e;o=parseInt(i,a)}n.push(o)}for(r=0;r<t;r++)if(o=n[r],r==t-1){if(o>=A(256,5-t))return null}else if(o>255)return null;for(s=n.pop(),r=0;r<n.length;r++)s+=n[r]*A(256,3-r);return s},M=function(e){var t,n,r,i,a,o,s,l=[0,0,0,0,0,0,0,0],c=0,u=null,f=0,p=function(){return e.charAt(f)};if(":"==p()){if(":"!=e.charAt(1))return;f+=2,u=++c}for(;p();){if(8==c)return;if(":"!=p()){for(t=n=0;n<4&&q.test(p());)t=16*t+parseInt(p(),16),f++,n++;if("."==p()){if(0==n)return;if(f-=n,c>6)return;for(r=0;p();){if(i=null,r>0){if(!("."==p()&&r<4))return;f++}if(!L.test(p()))return;for(;L.test(p());){if(a=parseInt(p(),10),null===i)i=a;else{if(0==i)return;i=10*i+a}if(i>255)return;f++}l[c]=256*l[c]+i,2!=++r&&4!=r||c++}if(4!=r)return;break}if(":"==p()){if(f++,!p())return}else if(p())return;l[c++]=t}else{if(null!==u)return;f++,u=++c}}if(null!==u)for(o=c-u,c=7;0!=c&&o>0;)s=l[c],l[c--]=l[u+o-1],l[u+--o]=s;else if(8!=c)return;return l},N=function(e){var t,n,r,i;if("number"==typeof e){for(t=[],n=0;n<4;n++)t.unshift(e%256),e=S(e/256);return t.join(".")}if("object"==typeof e){for(t="",r=function(e){for(var t=null,n=1,r=null,i=0,a=0;a<8;a++)0!==e[a]?(i>n&&(t=r,n=i),r=null,i=0):(null===r&&(r=a),++i);return i>n&&(t=r,n=i),t}(e),n=0;n<8;n++)i&&0===e[n]||(i&&(i=!1),r===n?(t+=n?":":"::",i=!0):(t+=e[n].toString(16),n<7&&(t+=":")));return"["+t+"]"}return e},D={},z=p({},D,{" ":1,'"':1,"<":1,">":1,"`":1}),G=p({},z,{"#":1,"?":1,"{":1,"}":1}),W=p({},G,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),$=function(e,t){var n=b(e,0);return n>32&&n<127&&!f(t,e)?e:encodeURIComponent(e)},J={ftp:21,file:null,http:80,https:443,ws:80,wss:443},Y=function(e){return f(J,e.scheme)},X=function(e){return""!=e.username||""!=e.password},Z=function(e){return!e.host||e.cannotBeABaseURL||"file"==e.scheme},H=function(e,t){var n;return 2==e.length&&O.test(e.charAt(0))&&(":"==(n=e.charAt(1))||!t&&"|"==n)},K=function(e){var t;return e.length>1&&H(e.slice(0,2))&&(2==e.length||"/"===(t=e.charAt(2))||"\\"===t||"?"===t||"#"===t)},V=function(e){var t=e.path,n=t.length;!n||"file"==e.scheme&&1==n&&H(t[0],!0)||t.pop()},Q=function(e){return"."===e||"%2e"===e.toLowerCase()},ee={},te={},ne={},re={},ie={},ae={},oe={},se={},le={},ce={},ue={},fe={},pe={},he={},be={},de={},ye={},ge={},ve={},me={},we={},je=function(e,t,n,i){var a,o,s,l,c,u=n||ee,p=0,b="",d=!1,y=!1,g=!1;for(n||(e.scheme="",e.username="",e.password="",e.host=null,e.port=null,e.path=[],e.query=null,e.fragment=null,e.cannotBeABaseURL=!1,t=t.replace(T,"")),t=t.replace(B,""),a=h(t);p<=a.length;){switch(o=a[p],u){case ee:if(!o||!O.test(o)){if(n)return"Invalid scheme";u=ne;continue}b+=o.toLowerCase(),u=te;break;case te:if(o&&(R.test(o)||"+"==o||"-"==o||"."==o))b+=o.toLowerCase();else{if(":"!=o){if(n)return"Invalid scheme";b="",u=ne,p=0;continue}if(n&&(Y(e)!=f(J,b)||"file"==b&&(X(e)||null!==e.port)||"file"==e.scheme&&!e.host))return;if(e.scheme=b,n)return void(Y(e)&&J[e.scheme]==e.port&&(e.port=null));b="","file"==e.scheme?u=he:Y(e)&&i&&i.scheme==e.scheme?u=re:Y(e)?u=se:"/"==a[p+1]?(u=ie,p++):(e.cannotBeABaseURL=!0,e.path.push(""),u=ve)}break;case ne:if(!i||i.cannotBeABaseURL&&"#"!=o)return"Invalid scheme";if(i.cannotBeABaseURL&&"#"==o){e.scheme=i.scheme,e.path=i.path.slice(),e.query=i.query,e.fragment="",e.cannotBeABaseURL=!0,u=we;break}u="file"==i.scheme?he:ae;continue;case re:if("/"!=o||"/"!=a[p+1]){u=ae;continue}u=le,p++;break;case ie:if("/"==o){u=ce;break}u=ge;continue;case ae:if(e.scheme=i.scheme,o==r)e.username=i.username,e.password=i.password,e.host=i.host,e.port=i.port,e.path=i.path.slice(),e.query=i.query;else if("/"==o||"\\"==o&&Y(e))u=oe;else if("?"==o)e.username=i.username,e.password=i.password,e.host=i.host,e.port=i.port,e.path=i.path.slice(),e.query="",u=me;else{if("#"!=o){e.username=i.username,e.password=i.password,e.host=i.host,e.port=i.port,e.path=i.path.slice(),e.path.pop(),u=ge;continue}e.username=i.username,e.password=i.password,e.host=i.host,e.port=i.port,e.path=i.path.slice(),e.query=i.query,e.fragment="",u=we}break;case oe:if(!Y(e)||"/"!=o&&"\\"!=o){if("/"!=o){e.username=i.username,e.password=i.password,e.host=i.host,e.port=i.port,u=ge;continue}u=ce}else u=le;break;case se:if(u=le,"/"!=o||"/"!=b.charAt(p+1))continue;p++;break;case le:if("/"!=o&&"\\"!=o){u=ce;continue}break;case ce:if("@"==o){d&&(b="%40"+b),d=!0,s=h(b);for(var v=0;v<s.length;v++){var m=s[v];if(":"!=m||g){var w=$(m,W);g?e.password+=w:e.username+=w}else g=!0}b=""}else if(o==r||"/"==o||"?"==o||"#"==o||"\\"==o&&Y(e)){if(d&&""==b)return"Invalid authority";p-=h(b).length+1,b="",u=ue}else b+=o;break;case ue:case fe:if(n&&"file"==e.scheme){u=de;continue}if(":"!=o||y){if(o==r||"/"==o||"?"==o||"#"==o||"\\"==o&&Y(e)){if(Y(e)&&""==b)return"Invalid host";if(n&&""==b&&(X(e)||null!==e.port))return;if(l=F(e,b))return l;if(b="",u=ye,n)return;continue}"["==o?y=!0:"]"==o&&(y=!1),b+=o}else{if(""==b)return"Invalid host";if(l=F(e,b))return l;if(b="",u=pe,n==fe)return}break;case pe:if(!L.test(o)){if(o==r||"/"==o||"?"==o||"#"==o||"\\"==o&&Y(e)||n){if(""!=b){var j=parseInt(b,10);if(j>65535)return"Invalid port";e.port=Y(e)&&j===J[e.scheme]?null:j,b=""}if(n)return;u=ye;continue}return"Invalid port"}b+=o;break;case he:if(e.scheme="file","/"==o||"\\"==o)u=be;else{if(!i||"file"!=i.scheme){u=ge;continue}if(o==r)e.host=i.host,e.path=i.path.slice(),e.query=i.query;else if("?"==o)e.host=i.host,e.path=i.path.slice(),e.query="",u=me;else{if("#"!=o){K(a.slice(p).join(""))||(e.host=i.host,e.path=i.path.slice(),V(e)),u=ge;continue}e.host=i.host,e.path=i.path.slice(),e.query=i.query,e.fragment="",u=we}}break;case be:if("/"==o||"\\"==o){u=de;break}i&&"file"==i.scheme&&!K(a.slice(p).join(""))&&(H(i.path[0],!0)?e.path.push(i.path[0]):e.host=i.host),u=ge;continue;case de:if(o==r||"/"==o||"\\"==o||"?"==o||"#"==o){if(!n&&H(b))u=ge;else if(""==b){if(e.host="",n)return;u=ye}else{if(l=F(e,b))return l;if("localhost"==e.host&&(e.host=""),n)return;b="",u=ye}continue}b+=o;break;case ye:if(Y(e)){if(u=ge,"/"!=o&&"\\"!=o)continue}else if(n||"?"!=o)if(n||"#"!=o){if(o!=r&&(u=ge,"/"!=o))continue}else e.fragment="",u=we;else e.query="",u=me;break;case ge:if(o==r||"/"==o||"\\"==o&&Y(e)||!n&&("?"==o||"#"==o)){if(".."===(c=(c=b).toLowerCase())||"%2e."===c||".%2e"===c||"%2e%2e"===c?(V(e),"/"==o||"\\"==o&&Y(e)||e.path.push("")):Q(b)?"/"==o||"\\"==o&&Y(e)||e.path.push(""):("file"==e.scheme&&!e.path.length&&H(b)&&(e.host&&(e.host=""),b=b.charAt(0)+":"),e.path.push(b)),b="","file"==e.scheme&&(o==r||"?"==o||"#"==o))for(;e.path.length>1&&""===e.path[0];)e.path.shift();"?"==o?(e.query="",u=me):"#"==o&&(e.fragment="",u=we)}else b+=$(o,G);break;case ve:"?"==o?(e.query="",u=me):"#"==o?(e.fragment="",u=we):o!=r&&(e.path[0]+=$(o,D));break;case me:n||"#"!=o?o!=r&&("'"==o&&Y(e)?e.query+="%27":e.query+="#"==o?"%23":$(o,D)):(e.fragment="",u=we);break;case we:o!=r&&(e.fragment+=$(o,z))}p++}},xe=function(e){var t,n,r=u(this,xe,"URL"),i=arguments.length>1?arguments[1]:void 0,o=String(e),s=x(r,{type:"URL"});if(void 0!==i)if(i instanceof xe)t=k(i);else if(n=je(t={},String(i)))throw TypeError(n);if(n=je(s,o,null,t))throw TypeError(n);var l=s.searchParams=new w,c=j(l);c.updateSearchParams(s.query),c.updateURL=function(){s.query=String(l)||null},a||(r.href=Se.call(r),r.origin=Ae.call(r),r.protocol=Oe.call(r),r.username=Re.call(r),r.password=Le.call(r),r.host=Ue.call(r),r.hostname=Pe.call(r),r.port=Ie.call(r),r.pathname=qe.call(r),r.search=Ee.call(r),r.searchParams=_e.call(r),r.hash=Te.call(r))},ke=xe.prototype,Se=function(){var e=k(this),t=e.scheme,n=e.username,r=e.password,i=e.host,a=e.port,o=e.path,s=e.query,l=e.fragment,c=t+":";return null!==i?(c+="//",X(e)&&(c+=n+(r?":"+r:"")+"@"),c+=N(i),null!==a&&(c+=":"+a)):"file"==t&&(c+="//"),c+=e.cannotBeABaseURL?o[0]:o.length?"/"+o.join("/"):"",null!==s&&(c+="?"+s),null!==l&&(c+="#"+l),c},Ae=function(){var e=k(this),t=e.scheme,n=e.port;if("blob"==t)try{return new URL(t.path[0]).origin}catch(e){return"null"}return"file"!=t&&Y(e)?t+"://"+N(e.host)+(null!==n?":"+n:""):"null"},Oe=function(){return k(this).scheme+":"},Re=function(){return k(this).username},Le=function(){return k(this).password},Ue=function(){var e=k(this),t=e.host,n=e.port;return null===t?"":null===n?N(t):N(t)+":"+n},Pe=function(){var e=k(this).host;return null===e?"":N(e)},Ie=function(){var e=k(this).port;return null===e?"":String(e)},qe=function(){var e=k(this),t=e.path;return e.cannotBeABaseURL?t[0]:t.length?"/"+t.join("/"):""},Ee=function(){var e=k(this).query;return e?"?"+e:""},_e=function(){return k(this).searchParams},Te=function(){var e=k(this).fragment;return e?"#"+e:""},Be=function(e,t){return{get:e,set:t,configurable:!0,enumerable:!0}};if(a&&l(ke,{href:Be(Se,(function(e){var t=k(this),n=String(e),r=je(t,n);if(r)throw TypeError(r);j(t.searchParams).updateSearchParams(t.query)})),origin:Be(Ae),protocol:Be(Oe,(function(e){var t=k(this);je(t,String(e)+":",ee)})),username:Be(Re,(function(e){var t=k(this),n=h(String(e));if(!Z(t)){t.username="";for(var r=0;r<n.length;r++)t.username+=$(n[r],W)}})),password:Be(Le,(function(e){var t=k(this),n=h(String(e));if(!Z(t)){t.password="";for(var r=0;r<n.length;r++)t.password+=$(n[r],W)}})),host:Be(Ue,(function(e){var t=k(this);t.cannotBeABaseURL||je(t,String(e),ue)})),hostname:Be(Pe,(function(e){var t=k(this);t.cannotBeABaseURL||je(t,String(e),fe)})),port:Be(Ie,(function(e){var t=k(this);Z(t)||(""==(e=String(e))?t.port=null:je(t,e,pe))})),pathname:Be(qe,(function(e){var t=k(this);t.cannotBeABaseURL||(t.path=[],je(t,e+"",ye))})),search:Be(Ee,(function(e){var t=k(this);""==(e=String(e))?t.query=null:("?"==e.charAt(0)&&(e=e.slice(1)),t.query="",je(t,e,me)),j(t.searchParams).updateSearchParams(t.query)})),searchParams:Be(_e),hash:Be(Te,(function(e){var t=k(this);""!=(e=String(e))?("#"==e.charAt(0)&&(e=e.slice(1)),t.fragment="",je(t,e,we)):t.fragment=null}))}),c(ke,"toJSON",(function(){return Se.call(this)}),{enumerable:!0}),c(ke,"toString",(function(){return Se.call(this)}),{enumerable:!0}),m){var Fe=m.createObjectURL,Ce=m.revokeObjectURL;Fe&&c(xe,"createObjectURL",(function(e){return Fe.apply(m,arguments)})),Ce&&c(xe,"revokeObjectURL",(function(e){return Ce.apply(m,arguments)}))}y(xe,"URL"),i({global:!0,forced:!o,sham:!a},{URL:xe})},{"../internals/an-instance":4,"../internals/array-from":6,"../internals/descriptors":18,"../internals/export":21,"../internals/global":27,"../internals/has":28,"../internals/internal-state":34,"../internals/native-url":42,"../internals/object-assign":44,"../internals/object-define-properties":46,"../internals/redefine":59,"../internals/set-to-string-tag":62,"../internals/string-multibyte":66,"../internals/string-punycode-to-ascii":67,"../modules/es.string.iterator":79,"../modules/web.url-search-params":80}],82:[function(e,t,n){"use strict";e("../internals/export")({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return URL.prototype.toString.call(this)}})},{"../internals/export":21}],83:[function(e,t,n){e("../modules/web.url"),e("../modules/web.url.to-json"),e("../modules/web.url-search-params");var r=e("../internals/path");t.exports=r.URL},{"../internals/path":57,"../modules/web.url":81,"../modules/web.url-search-params":80,"../modules/web.url.to-json":82}]},{},[83]); vendor/wp-polyfill.min.js 0000666 00000042637 15123355174 0011465 0 ustar 00 !function(t){"use strict";var n,r,e;r={},(e=function(t){if(r[t])return r[t].exports;var o=r[t]={i:t,l:!1,exports:{}};return n[t].call(o.exports,o,o.exports,e),o.l=!0,o.exports}).m=n=[function(t,n,r){r(1),r(67),r(68),r(72),t.exports=r(79)},function(n,r,e){var o=e(2),i=e(36),u=e(57),c=e(56);e=e(62);o({target:"Array",proto:!0},{at:function(n){var r=i(this),e=u(r);return(n=0<=(n=c(n))?n:e+n)<0||e<=n?t:r[n]}}),e("at")},function(n,r,e){var o=e(3),i=e(4).f,u=e(40),c=e(43),f=e(34),a=e(50),p=e(61);n.exports=function(n,r){var e,s,l,y=n.target,v=n.global,d=n.stat,b=v?o:d?o[y]||f(y,{}):(o[y]||{}).prototype;if(b)for(e in r){if(s=r[e],l=n.noTargetGet?(l=i(b,e))&&l.value:b[e],!p(v?e:y+(d?".":"#")+e,n.forced)&&l!==t){if(typeof s==typeof l)continue;a(s,l)}(n.sham||l&&l.sham)&&u(s,"sham",!0),c(b,e,s,n)}}},function(t,n){function r(t){return t&&t.Math==Math&&t}t.exports=r("object"==typeof globalThis&&globalThis)||r("object"==typeof window&&window)||r("object"==typeof self&&self)||r("object"==typeof global&&global)||function(){return this}()||Function("return this")()},function(t,n,r){var e=r(5),o=r(7),i=r(8),u=r(9),c=r(10),f=r(15),a=r(35),p=r(38),s=Object.getOwnPropertyDescriptor;n.f=e?s:function(t,n){if(t=c(t),n=f(n),p)try{return s(t,n)}catch(t){}if(a(t,n))return u(!o(i.f,t,n),t[n])}},function(t,n,r){r=r(6),t.exports=!r((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]}))},function(t,n){t.exports=function(t){try{return!!t()}catch(t){return!0}}},function(t,n){var r=Function.prototype.call;t.exports=r.bind?r.bind(r):function(){return r.apply(r,arguments)}},function(t,n,r){var e={}.propertyIsEnumerable,o=Object.getOwnPropertyDescriptor,i=o&&!e.call({1:2},1);n.f=i?function(t){return!!(t=o(this,t))&&t.enumerable}:e},function(t,n){t.exports=function(t,n){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:n}}},function(t,n,r){var e=r(11),o=r(14);t.exports=function(t){return e(o(t))}},function(t,n,r){var e=r(3),o=r(12),i=r(6),u=r(13),c=e.Object,f=o("".split);t.exports=i((function(){return!c("z").propertyIsEnumerable(0)}))?function(t){return"String"==u(t)?f(t,""):c(t)}:c},function(t,n){var r=Function.prototype,e=r.bind,o=r.call,i=e&&e.bind(o);t.exports=e?function(t){return t&&i(o,t)}:function(t){return t&&function(){return o.apply(t,arguments)}}},function(t,n,r){var e=(r=r(12))({}.toString),o=r("".slice);t.exports=function(t){return o(e(t),8,-1)}},function(n,r,e){var o=e(3).TypeError;n.exports=function(n){if(n==t)throw o("Can't call method on "+n);return n}},function(t,n,r){var e=r(16),o=r(19);t.exports=function(t){return t=e(t,"string"),o(t)?t:t+""}},function(n,r,e){var o=e(3),i=e(7),u=e(17),c=e(19),f=e(26),a=e(29),p=(e=e(30),o.TypeError),s=e("toPrimitive");n.exports=function(n,r){if(!u(n)||c(n))return n;var e=f(n,s);if(e){if(e=i(e,n,r=r===t?"default":r),!u(e)||c(e))return e;throw p("Can't convert object to primitive value")}return a(n,r=r===t?"number":r)}},function(t,n,r){var e=r(18);t.exports=function(t){return"object"==typeof t?null!==t:e(t)}},function(t,n){t.exports=function(t){return"function"==typeof t}},function(t,n,r){var e=r(3),o=r(20),i=r(18),u=r(21),c=(r=r(22),e.Object);t.exports=r?function(t){return"symbol"==typeof t}:function(t){var n=o("Symbol");return i(n)&&u(n.prototype,c(t))}},function(n,r,e){var o=e(3),i=e(18);n.exports=function(n,r){return arguments.length<2?(e=o[n],i(e)?e:t):o[n]&&o[n][r];var e}},function(t,n,r){r=r(12),t.exports=r({}.isPrototypeOf)},function(t,n,r){r=r(23),t.exports=r&&!Symbol.sham&&"symbol"==typeof Symbol.iterator},function(t,n,r){var e=r(24);r=r(6);t.exports=!!Object.getOwnPropertySymbols&&!r((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&e&&e<41}))},function(t,n,r){var e,o,i=r(3),u=r(25);r=i.process,i=i.Deno;!(o=(i=(i=r&&r.versions||i&&i.version)&&i.v8)?0<(e=i.split("."))[0]&&e[0]<4?1:+(e[0]+e[1]):o)&&u&&(!(e=u.match(/Edge\/(\d+)/))||74<=e[1])&&(e=u.match(/Chrome\/(\d+)/))&&(o=+e[1]),t.exports=o},function(t,n,r){r=r(20),t.exports=r("navigator","userAgent")||""},function(n,r,e){var o=e(27);n.exports=function(n,r){return null==(r=n[r])?t:o(r)}},function(t,n,r){var e=r(3),o=r(18),i=r(28),u=e.TypeError;t.exports=function(t){if(o(t))return t;throw u(i(t)+" is not a function")}},function(t,n,r){var e=r(3).String;t.exports=function(t){try{return e(t)}catch(t){return"Object"}}},function(t,n,r){var e=r(3),o=r(7),i=r(18),u=r(17),c=e.TypeError;t.exports=function(t,n){var r,e;if("string"===n&&i(r=t.toString)&&!u(e=o(r,t)))return e;if(i(r=t.valueOf)&&!u(e=o(r,t)))return e;if("string"!==n&&i(r=t.toString)&&!u(e=o(r,t)))return e;throw c("Can't convert object to primitive value")}},function(t,n,r){var e=r(3),o=r(31),i=r(35),u=r(37),c=r(23),f=r(22),a=o("wks"),p=e.Symbol,s=p&&p.for,l=f?p:p&&p.withoutSetter||u;t.exports=function(t){var n;return i(a,t)&&(c||"string"==typeof a[t])||(n="Symbol."+t,c&&i(p,t)?a[t]=p[t]:a[t]=(f&&s?s:l)(n)),a[t]}},function(n,r,e){var o=e(32),i=e(33);(n.exports=function(n,r){return i[n]||(i[n]=r!==t?r:{})})("versions",[]).push({version:"3.19.1",mode:o?"pure":"global",copyright:"© 2021 Denis Pushkarev (zloirock.ru)"})},function(t,n){t.exports=!1},function(t,n,r){var e=r(3),o=r(34);r=e[r="__core-js_shared__"]||o(r,{});t.exports=r},function(t,n,r){var e=r(3),o=Object.defineProperty;t.exports=function(t,n){try{o(e,t,{value:n,configurable:!0,writable:!0})}catch(r){e[t]=n}return n}},function(t,n,r){var e=r(12),o=r(36),i=e({}.hasOwnProperty);t.exports=Object.hasOwn||function(t,n){return i(o(t),n)}},function(t,n,r){var e=r(3),o=r(14),i=e.Object;t.exports=function(t){return i(o(t))}},function(n,r,e){e=e(12);var o=0,i=Math.random(),u=e(1..toString);n.exports=function(n){return"Symbol("+(n===t?"":n)+")_"+u(++o+i,36)}},function(t,n,r){var e=r(5),o=r(6),i=r(39);t.exports=!e&&!o((function(){return 7!=Object.defineProperty(i("div"),"a",{get:function(){return 7}}).a}))},function(t,n,r){var e=r(3),o=(r=r(17),e.document),i=r(o)&&r(o.createElement);t.exports=function(t){return i?o.createElement(t):{}}},function(t,n,r){var e=r(5),o=r(41),i=r(9);t.exports=e?function(t,n,r){return o.f(t,n,i(1,r))}:function(t,n,r){return t[n]=r,t}},function(t,n,r){var e=r(3),o=r(5),i=r(38),u=r(42),c=r(15),f=e.TypeError,a=Object.defineProperty;n.f=o?a:function(t,n,r){if(u(t),n=c(n),u(r),i)try{return a(t,n,r)}catch(t){}if("get"in r||"set"in r)throw f("Accessors not supported");return"value"in r&&(t[n]=r.value),t}},function(t,n,r){var e=r(3),o=r(17),i=e.String,u=e.TypeError;t.exports=function(t){if(o(t))return t;throw u(i(t)+" is not an object")}},function(n,r,e){var o=e(3),i=e(18),u=e(35),c=e(40),f=e(34),a=e(44),p=e(45),s=e(49).CONFIGURABLE,l=p.get,y=p.enforce,v=String(String).split("String");(n.exports=function(n,r,e,a){var p=!!a&&!!a.unsafe,l=!!a&&!!a.enumerable,d=!!a&&!!a.noTargetGet,b=a&&a.name!==t?a.name:r;i(e)&&("Symbol("===String(b).slice(0,7)&&(b="["+String(b).replace(/^Symbol\(([^)]*)\)/,"$1")+"]"),(!u(e,"name")||s&&e.name!==b)&&c(e,"name",b),(a=y(e)).source||(a.source=v.join("string"==typeof b?b:""))),n!==o?(p?!d&&n[r]&&(l=!0):delete n[r],l?n[r]=e:c(n,r,e)):l?n[r]=e:f(r,e)})(Function.prototype,"toString",(function(){return i(this)&&l(this).source||a(this)}))},function(t,n,r){var e=r(12),o=r(18),i=(r=r(33),e(Function.toString));o(r.inspectSource)||(r.inspectSource=function(t){return i(t)}),t.exports=r.inspectSource},function(t,n,r){var e,o,i,u,c,f,a,p,s=r(46),l=r(3),y=r(12),v=r(17),d=r(40),b=r(35),g=r(33),m=r(47),h=(r=r(48),"Object already initialized"),x=l.TypeError;l=l.WeakMap;a=s||g.state?(e=g.state||(g.state=new l),o=y(e.get),i=y(e.has),u=y(e.set),c=function(t,n){if(i(e,t))throw new x(h);return n.facade=t,u(e,t,n),n},f=function(t){return o(e,t)||{}},function(t){return i(e,t)}):(r[p=m("state")]=!0,c=function(t,n){if(b(t,p))throw new x(h);return n.facade=t,d(t,p,n),n},f=function(t){return b(t,p)?t[p]:{}},function(t){return b(t,p)}),t.exports={set:c,get:f,has:a,enforce:function(t){return a(t)?f(t):c(t,{})},getterFor:function(t){return function(n){var r;if(!v(n)||(r=f(n)).type!==t)throw x("Incompatible receiver, "+t+" required");return r}}}},function(t,n,r){var e=r(3),o=r(18);r=r(44),e=e.WeakMap;t.exports=o(e)&&/native code/.test(r(e))},function(t,n,r){var e=r(31),o=r(37),i=e("keys");t.exports=function(t){return i[t]||(i[t]=o(t))}},function(t,n){t.exports={}},function(t,n,r){var e=r(5),o=r(35),i=Function.prototype,u=e&&Object.getOwnPropertyDescriptor;o=(r=o(i,"name"))&&"something"===function(){}.name,i=r&&(!e||e&&u(i,"name").configurable);t.exports={EXISTS:r,PROPER:o,CONFIGURABLE:i}},function(t,n,r){var e=r(35),o=r(51),i=r(4),u=r(41);t.exports=function(t,n){for(var r=o(n),c=u.f,f=i.f,a=0;a<r.length;a++){var p=r[a];e(t,p)||c(t,p,f(n,p))}}},function(t,n,r){var e=r(20),o=r(12),i=r(52),u=r(60),c=r(42),f=o([].concat);t.exports=e("Reflect","ownKeys")||function(t){var n=i.f(c(t)),r=u.f;return r?f(n,r(t)):n}},function(t,n,r){var e=r(53),o=r(59).concat("length","prototype");n.f=Object.getOwnPropertyNames||function(t){return e(t,o)}},function(t,n,r){var e=r(12),o=r(35),i=r(10),u=r(54).indexOf,c=r(48),f=e([].push);t.exports=function(t,n){var r,e=i(t),a=0,p=[];for(r in e)!o(c,r)&&o(e,r)&&f(p,r);for(;n.length>a;)o(e,r=n[a++])&&(~u(p,r)||f(p,r));return p}},function(t,n,r){var e=r(10),o=r(55),i=r(57);r=function(t){return function(n,r,u){var c,f=e(n),a=i(f),p=o(u,a);if(t&&r!=r){for(;p<a;)if((c=f[p++])!=c)return!0}else for(;p<a;p++)if((t||p in f)&&f[p]===r)return t||p||0;return!t&&-1}};t.exports={includes:r(!0),indexOf:r(!1)}},function(t,n,r){var e=r(56),o=Math.max,i=Math.min;t.exports=function(t,n){return(t=e(t))<0?o(t+n,0):i(t,n)}},function(t,n){var r=Math.ceil,e=Math.floor;t.exports=function(t){return(t=+t)!=t||0==t?0:(0<t?e:r)(t)}},function(t,n,r){var e=r(58);t.exports=function(t){return e(t.length)}},function(t,n,r){var e=r(56),o=Math.min;t.exports=function(t){return 0<t?o(e(t),9007199254740991):0}},function(t,n){t.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},function(t,n){n.f=Object.getOwnPropertySymbols},function(t,n,r){var e=r(6),o=r(18),i=/#|\.prototype\./,u=(r=function(t,n){return(t=c[u(t)])==a||t!=f&&(o(n)?e(n):!!n)},r.normalize=function(t){return String(t).replace(i,".").toLowerCase()}),c=r.data={},f=r.NATIVE="N",a=r.POLYFILL="P";t.exports=r},function(n,r,e){var o=e(30),i=e(63),u=(e=e(41),o("unscopables")),c=Array.prototype;c[u]==t&&e.f(c,u,{configurable:!0,value:i(null)}),n.exports=function(t){c[u][t]=!0}},function(n,r,e){function o(){}function i(t){return"<script>"+t+"</"+v+">"}var u,c=e(42),f=e(64),a=e(59),p=e(48),s=e(66),l=e(39),y=(e=e(47),"prototype"),v="script",d=e("IE_PROTO"),b=function(){try{u=new ActiveXObject("htmlfile")}catch(t){}var t;b="undefined"==typeof document||document.domain&&u?function(t){t.write(i("")),t.close();var n=t.parentWindow.Object;return t=null,n}(u):((t=l("iframe")).style.display="none",s.appendChild(t),t.src=String("javascript:"),(t=t.contentWindow.document).open(),t.write(i("document.F=Object")),t.close(),t.F);for(var n=a.length;n--;)delete b[y][a[n]];return b()};p[d]=!0,n.exports=Object.create||function(n,r){var e;return null!==n?(o[y]=c(n),e=new o,o[y]=null,e[d]=n):e=b(),r===t?e:f(e,r)}},function(t,n,r){var e=r(5),o=r(41),i=r(42),u=r(10),c=r(65);t.exports=e?Object.defineProperties:function(t,n){i(t);for(var r,e=u(n),f=c(n),a=f.length,p=0;p<a;)o.f(t,r=f[p++],e[r]);return t}},function(t,n,r){var e=r(53),o=r(59);t.exports=Object.keys||function(t){return e(t,o)}},function(t,n,r){r=r(20),t.exports=r("document","documentElement")},function(t,n,r){r(2)({target:"Object",stat:!0},{hasOwn:r(35)})},function(n,r,e){var o=e(2),i=e(12),u=e(14),c=e(56),f=e(69),a=(e=e(6),i("".charAt));o({target:"String",proto:!0,forced:e((function(){return"\ud842"!=="𠮷".at(0)}))},{at:function(n){var r=f(u(this)),e=r.length;return(n=0<=(n=c(n))?n:e+n)<0||e<=n?t:a(r,n)}})},function(t,n,r){var e=r(3),o=r(70),i=e.String;t.exports=function(t){if("Symbol"===o(t))throw TypeError("Cannot convert a Symbol value to a string");return i(t)}},function(n,r,e){var o=e(3),i=e(71),u=e(18),c=e(13),f=e(30)("toStringTag"),a=o.Object,p="Arguments"==c(function(){return arguments}());n.exports=i?c:function(n){var r;return n===t?"Undefined":null===n?"Null":"string"==typeof(n=function(t,n){try{return t[n]}catch(t){}}(r=a(n),f))?n:p?c(r):"Object"==(n=c(r))&&u(r.callee)?"Arguments":n}},function(t,n,r){var e={};e[r(30)("toStringTag")]="z",t.exports="[object z]"===String(e)},function(n,r,e){var o=e(73),i=e(57),u=e(56),c=o.aTypedArray;(0,o.exportTypedArrayMethod)("at",(function(n){var r=c(this),e=i(r);return(n=0<=(n=u(n))?n:e+n)<0||e<=n?t:r[n]}))},function(n,r,e){function o(t){return!!l(t)&&(t=v(t),y(M,t)||y(C,t))}var i,u,c,f=e(74),a=e(5),p=e(3),s=e(18),l=e(17),y=e(35),v=e(70),d=e(28),b=e(40),g=e(43),m=e(41).f,h=e(21),x=e(75),O=e(77),S=e(30),j=e(37),w=(P=p.Int8Array)&&P.prototype,A=(e=(e=p.Uint8ClampedArray)&&e.prototype,P&&x(P)),T=w&&x(w),P=Object.prototype,_=p.TypeError,E=(S=S("toStringTag"),j("TYPED_ARRAY_TAG")),I=j("TYPED_ARRAY_CONSTRUCTOR"),R=f&&!!O&&"Opera"!==v(p.opera),M=(f=!1,{Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8}),C={BigInt64Array:8,BigUint64Array:8};for(i in M)(c=(u=p[i])&&u.prototype)?b(c,I,u):R=!1;for(i in C)(c=(u=p[i])&&u.prototype)&&b(c,I,u);if((!R||!s(A)||A===Function.prototype)&&(A=function(){throw _("Incorrect invocation")},R))for(i in M)p[i]&&O(p[i],A);if((!R||!T||T===P)&&(T=A.prototype,R))for(i in M)p[i]&&O(p[i].prototype,T);if(R&&x(e)!==T&&O(e,T),a&&!y(T,S))for(i in f=!0,m(T,S,{get:function(){return l(this)?this[E]:t}}),M)p[i]&&b(p[i],E,i);n.exports={NATIVE_ARRAY_BUFFER_VIEWS:R,TYPED_ARRAY_CONSTRUCTOR:I,TYPED_ARRAY_TAG:f&&E,aTypedArray:function(t){if(o(t))return t;throw _("Target is not a typed array")},aTypedArrayConstructor:function(t){if(s(t)&&(!O||h(A,t)))return t;throw _(d(t)+" is not a typed array constructor")},exportTypedArrayMethod:function(t,n,r){if(a){if(r)for(var e in M)if((e=p[e])&&y(e.prototype,t))try{delete e.prototype[t]}catch(t){}T[t]&&!r||g(T,t,!r&&R&&w[t]||n)}},exportTypedArrayStaticMethod:function(t,n,r){var e,o;if(a){if(O){if(r)for(e in M)if((o=p[e])&&y(o,t))try{delete o[t]}catch(t){}if(A[t]&&!r)return;try{return g(A,t,!r&&R&&A[t]||n)}catch(t){}}for(e in M)!(o=p[e])||o[t]&&!r||g(o,t,n)}},isView:function(t){return!!l(t)&&("DataView"===(t=v(t))||y(M,t)||y(C,t))},isTypedArray:o,TypedArray:A,TypedArrayPrototype:T}},function(t,n){t.exports="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView},function(t,n,r){var e=r(3),o=r(35),i=r(18),u=r(36),c=r(47),f=(r=r(76),c("IE_PROTO")),a=e.Object,p=a.prototype;t.exports=r?a.getPrototypeOf:function(t){var n=u(t);return o(n,f)?n[f]:(t=n.constructor,i(t)&&n instanceof t?t.prototype:n instanceof a?p:null)}},function(t,n,r){r=r(6),t.exports=!r((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype}))},function(n,r,e){var o=e(12),i=e(42),u=e(78);n.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var t,n=!1,r={};try{(t=o(Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set))(r,[]),n=r instanceof Array}catch(r){}return function(r,e){return i(r),u(e),n?t(r,e):r.__proto__=e,r}}():t)},function(t,n,r){var e=r(3),o=r(18),i=e.String,u=e.TypeError;t.exports=function(t){if("object"==typeof t||o(t))return t;throw u("Can't set "+i(t)+" as a prototype")}},function(t,n,r){var e=r(2),o=r(3);r=r(80);e({global:!0,bind:!0,enumerable:!0,forced:!o.setImmediate||!o.clearImmediate},{setImmediate:r.set,clearImmediate:r.clear})},function(n,r,e){var o,i,u=e(3),c=e(81),f=e(82),a=e(18),p=e(35),s=e(6),l=e(66),y=e(83),v=e(39),d=e(84),b=e(85),g=u.setImmediate,m=u.clearImmediate,h=u.process,x=u.Dispatch,O=u.Function,S=u.MessageChannel,j=u.String,w=0,A={},T="onreadystatechange";try{o=u.location}catch(n){}function P(t){var n;p(A,t)&&(n=A[t],delete A[t],n())}function _(t){return function(){P(t)}}function E(t){P(t.data)}e=function(t){u.postMessage(j(t),o.protocol+"//"+o.host)},g&&m||(g=function(n){var r=y(arguments,1);return A[++w]=function(){c(a(n)?n:O(n),t,r)},i(w),w},m=function(t){delete A[t]},b?i=function(t){h.nextTick(_(t))}:x&&x.now?i=function(t){x.now(_(t))}:S&&!d?(S=(d=new S).port2,d.port1.onmessage=E,i=f(S.postMessage,S)):u.addEventListener&&a(u.postMessage)&&!u.importScripts&&o&&"file:"!==o.protocol&&!s(e)?(i=e,u.addEventListener("message",E,!1)):i=T in v("script")?function(t){l.appendChild(v("script"))[T]=function(){l.removeChild(this),P(t)}}:function(t){setTimeout(_(t),0)}),n.exports={set:g,clear:m}},function(t,n){var r=Function.prototype,e=r.apply,o=r.bind,i=r.call;t.exports="object"==typeof Reflect&&Reflect.apply||(o?i.bind(e):function(){return i.apply(e,arguments)})},function(n,r,e){var o=e(12),i=e(27),u=o(o.bind);n.exports=function(n,r){return i(n),r===t?n:u?u(n,r):function(){return n.apply(r,arguments)}}},function(t,n,r){r=r(12),t.exports=r([].slice)},function(t,n,r){r=r(25),t.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(r)},function(t,n,r){var e=r(13);r=r(3);t.exports="process"==e(r.process)}],e.c=r,e.d=function(t,n,r){e.o(t,n)||Object.defineProperty(t,n,{enumerable:!0,get:r})},e.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},e.t=function(t,n){if(1&n&&(t=e(t)),8&n)return t;if(4&n&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(e.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&n&&"string"!=typeof t)for(var o in t)e.d(r,o,function(n){return t[n]}.bind(null,o));return r},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,n){return Object.prototype.hasOwnProperty.call(t,n)},e.p="",e(e.s=0)}(); vendor/react-dom.js 0000666 00004067436 15123355174 0010310 0 ustar 00 /**
* @license React
* react-dom.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
(global = global || self, factory(global.ReactDOM = {}, global.React));
}(this, (function (exports, React) { 'use strict';
var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
var suppressWarning = false;
function setSuppressWarning(newSuppressWarning) {
{
suppressWarning = newSuppressWarning;
}
} // In DEV, calls to console.warn and console.error get replaced
// by calls to these methods by a Babel plugin.
//
// In PROD (or in packages without access to React internals),
// they are left as they are instead.
function warn(format) {
{
if (!suppressWarning) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
printWarning('warn', format, args);
}
}
}
function error(format) {
{
if (!suppressWarning) {
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
printWarning('error', format, args);
}
}
}
function printWarning(level, format, args) {
// When changing this logic, you might want to also
// update consoleWithStackDev.www.js as well.
{
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
var stack = ReactDebugCurrentFrame.getStackAddendum();
if (stack !== '') {
format += '%s';
args = args.concat([stack]);
} // eslint-disable-next-line react-internal/safe-string-coercion
var argsWithFormat = args.map(function (item) {
return String(item);
}); // Careful: RN currently depends on this prefix
argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
// breaks IE9: https://github.com/facebook/react/issues/13610
// eslint-disable-next-line react-internal/no-production-logging
Function.prototype.apply.call(console[level], console, argsWithFormat);
}
}
var FunctionComponent = 0;
var ClassComponent = 1;
var IndeterminateComponent = 2; // Before we know whether it is function or class
var HostRoot = 3; // Root of a host tree. Could be nested inside another node.
var HostPortal = 4; // A subtree. Could be an entry point to a different renderer.
var HostComponent = 5;
var HostText = 6;
var Fragment = 7;
var Mode = 8;
var ContextConsumer = 9;
var ContextProvider = 10;
var ForwardRef = 11;
var Profiler = 12;
var SuspenseComponent = 13;
var MemoComponent = 14;
var SimpleMemoComponent = 15;
var LazyComponent = 16;
var IncompleteClassComponent = 17;
var DehydratedFragment = 18;
var SuspenseListComponent = 19;
var ScopeComponent = 21;
var OffscreenComponent = 22;
var LegacyHiddenComponent = 23;
var CacheComponent = 24;
var TracingMarkerComponent = 25;
// -----------------------------------------------------------------------------
var enableClientRenderFallbackOnTextMismatch = true; // TODO: Need to review this code one more time before landing
// the react-reconciler package.
var enableNewReconciler = false; // Support legacy Primer support on internal FB www
var enableLazyContextPropagation = false; // FB-only usage. The new API has different semantics.
var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber
var enableSuspenseAvoidThisFallback = false; // Enables unstable_avoidThisFallback feature in Fizz
// React DOM Chopping Block
//
// Similar to main Chopping Block but only flags related to React DOM. These are
// grouped because we will likely batch all of them into a single major release.
// -----------------------------------------------------------------------------
// Disable support for comment nodes as React DOM containers. Already disabled
// in open source, but www codebase still relies on it. Need to remove.
var disableCommentsAsDOMContainers = true; // Disable javascript: URL strings in href for XSS protection.
// and client rendering, mostly to allow JSX attributes to apply to the custom
// element's object properties instead of only HTML attributes.
// https://github.com/facebook/react/issues/11347
var enableCustomElementPropertySupport = false; // Disables children for <textarea> elements
var warnAboutStringRefs = false; // -----------------------------------------------------------------------------
// Debugging and DevTools
// -----------------------------------------------------------------------------
// Adds user timing marks for e.g. state updates, suspense, and work loop stuff,
// for an experimental timeline tool.
var enableSchedulingProfiler = true; // Helps identify side effects in render-phase lifecycle hooks and setState
var enableProfilerTimer = true; // Record durations for commit and passive effects phases.
var enableProfilerCommitHooks = true; // Phase param passed to onRender callback differentiates between an "update" and a "cascading-update".
var allNativeEvents = new Set();
/**
* Mapping from registration name to event name
*/
var registrationNameDependencies = {};
/**
* Mapping from lowercase registration names to the properly cased version,
* used to warn in the case of missing event handlers. Available
* only in true.
* @type {Object}
*/
var possibleRegistrationNames = {} ; // Trust the developer to only use possibleRegistrationNames in true
function registerTwoPhaseEvent(registrationName, dependencies) {
registerDirectEvent(registrationName, dependencies);
registerDirectEvent(registrationName + 'Capture', dependencies);
}
function registerDirectEvent(registrationName, dependencies) {
{
if (registrationNameDependencies[registrationName]) {
error('EventRegistry: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName);
}
}
registrationNameDependencies[registrationName] = dependencies;
{
var lowerCasedName = registrationName.toLowerCase();
possibleRegistrationNames[lowerCasedName] = registrationName;
if (registrationName === 'onDoubleClick') {
possibleRegistrationNames.ondblclick = registrationName;
}
}
for (var i = 0; i < dependencies.length; i++) {
allNativeEvents.add(dependencies[i]);
}
}
var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');
var hasOwnProperty = Object.prototype.hasOwnProperty;
/*
* The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
* and Temporal.* types. See https://github.com/facebook/react/pull/22064.
*
* The functions in this module will throw an easier-to-understand,
* easier-to-debug exception with a clear errors message message explaining the
* problem. (Instead of a confusing exception thrown inside the implementation
* of the `value` object).
*/
// $FlowFixMe only called in DEV, so void return is not possible.
function typeName(value) {
{
// toStringTag is needed for namespaced types like Temporal.Instant
var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
return type;
}
} // $FlowFixMe only called in DEV, so void return is not possible.
function willCoercionThrow(value) {
{
try {
testStringCoercion(value);
return false;
} catch (e) {
return true;
}
}
}
function testStringCoercion(value) {
// If you ended up here by following an exception call stack, here's what's
// happened: you supplied an object or symbol value to React (as a prop, key,
// DOM attribute, CSS property, string ref, etc.) and when React tried to
// coerce it to a string using `'' + value`, an exception was thrown.
//
// The most common types that will cause this exception are `Symbol` instances
// and Temporal objects like `Temporal.Instant`. But any object that has a
// `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
// exception. (Library authors do this to prevent users from using built-in
// numeric operators like `+` or comparison operators like `>=` because custom
// methods are needed to perform accurate arithmetic or comparison.)
//
// To fix the problem, coerce this object or symbol value to a string before
// passing it to React. The most reliable way is usually `String(value)`.
//
// To find which value is throwing, check the browser or debugger console.
// Before this exception was thrown, there should be `console.error` output
// that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
// problem and how that type was used: key, atrribute, input value prop, etc.
// In most cases, this console output also shows the component and its
// ancestor components where the exception happened.
//
// eslint-disable-next-line react-internal/safe-string-coercion
return '' + value;
}
function checkAttributeStringCoercion(value, attributeName) {
{
if (willCoercionThrow(value)) {
error('The provided `%s` attribute is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', attributeName, typeName(value));
return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
}
}
}
function checkKeyStringCoercion(value) {
{
if (willCoercionThrow(value)) {
error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));
return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
}
}
}
function checkPropStringCoercion(value, propName) {
{
if (willCoercionThrow(value)) {
error('The provided `%s` prop is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value));
return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
}
}
}
function checkCSSPropertyStringCoercion(value, propName) {
{
if (willCoercionThrow(value)) {
error('The provided `%s` CSS property is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value));
return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
}
}
}
function checkHtmlStringCoercion(value) {
{
if (willCoercionThrow(value)) {
error('The provided HTML markup uses a value of unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));
return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
}
}
}
function checkFormFieldValueStringCoercion(value) {
{
if (willCoercionThrow(value)) {
error('Form field values (value, checked, defaultValue, or defaultChecked props)' + ' must be strings, not %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));
return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
}
}
}
// A reserved attribute.
// It is handled by React separately and shouldn't be written to the DOM.
var RESERVED = 0; // A simple string attribute.
// Attributes that aren't in the filter are presumed to have this type.
var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called
// "enumerated" attributes with "true" and "false" as possible values.
// When true, it should be set to a "true" string.
// When false, it should be set to a "false" string.
var BOOLEANISH_STRING = 2; // A real boolean attribute.
// When true, it should be present (set either to an empty string or its name).
// When false, it should be omitted.
var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value.
// When true, it should be present (set either to an empty string or its name).
// When false, it should be omitted.
// For any other value, should be present with that value.
var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric.
// When falsy, it should be removed.
var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric.
// When falsy, it should be removed.
var POSITIVE_NUMERIC = 6;
/* eslint-disable max-len */
var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
/* eslint-enable max-len */
var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');
var illegalAttributeNameCache = {};
var validatedAttributeNameCache = {};
function isAttributeNameSafe(attributeName) {
if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
return true;
}
if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
return false;
}
if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
validatedAttributeNameCache[attributeName] = true;
return true;
}
illegalAttributeNameCache[attributeName] = true;
{
error('Invalid attribute name: `%s`', attributeName);
}
return false;
}
function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) {
if (propertyInfo !== null) {
return propertyInfo.type === RESERVED;
}
if (isCustomComponentTag) {
return false;
}
if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
return true;
}
return false;
}
function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
if (propertyInfo !== null && propertyInfo.type === RESERVED) {
return false;
}
switch (typeof value) {
case 'function': // $FlowIssue symbol is perfectly valid here
case 'symbol':
// eslint-disable-line
return true;
case 'boolean':
{
if (isCustomComponentTag) {
return false;
}
if (propertyInfo !== null) {
return !propertyInfo.acceptsBooleans;
} else {
var prefix = name.toLowerCase().slice(0, 5);
return prefix !== 'data-' && prefix !== 'aria-';
}
}
default:
return false;
}
}
function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) {
if (value === null || typeof value === 'undefined') {
return true;
}
if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) {
return true;
}
if (isCustomComponentTag) {
return false;
}
if (propertyInfo !== null) {
switch (propertyInfo.type) {
case BOOLEAN:
return !value;
case OVERLOADED_BOOLEAN:
return value === false;
case NUMERIC:
return isNaN(value);
case POSITIVE_NUMERIC:
return isNaN(value) || value < 1;
}
}
return false;
}
function getPropertyInfo(name) {
return properties.hasOwnProperty(name) ? properties[name] : null;
}
function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL, removeEmptyString) {
this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
this.attributeName = attributeName;
this.attributeNamespace = attributeNamespace;
this.mustUseProperty = mustUseProperty;
this.propertyName = name;
this.type = type;
this.sanitizeURL = sanitizeURL;
this.removeEmptyString = removeEmptyString;
} // When adding attributes to this list, be sure to also add them to
// the `possibleStandardNames` module to ensure casing and incorrect
// name warnings.
var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM.
var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular
// elements (not just inputs). Now that ReactDOMInput assigns to the
// defaultValue property -- do we need this?
'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'];
reservedProps.forEach(function (name) {
properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty
name, // attributeName
null, // attributeNamespace
false, // sanitizeURL
false);
}); // A few React string attributes have a different name.
// This is a mapping from React prop names to the attribute names.
[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {
var name = _ref[0],
attributeName = _ref[1];
properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
attributeName, // attributeName
null, // attributeNamespace
false, // sanitizeURL
false);
}); // These are "enumerated" HTML attributes that accept "true" and "false".
// In React, we let users pass `true` and `false` even though technically
// these aren't boolean attributes (they are coerced to strings).
['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {
properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
name.toLowerCase(), // attributeName
null, // attributeNamespace
false, // sanitizeURL
false);
}); // These are "enumerated" SVG attributes that accept "true" and "false".
// In React, we let users pass `true` and `false` even though technically
// these aren't boolean attributes (they are coerced to strings).
// Since these are SVG attributes, their attribute names are case-sensitive.
['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {
properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
name, // attributeName
null, // attributeNamespace
false, // sanitizeURL
false);
}); // These are HTML boolean attributes.
['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM
// on the client side because the browsers are inconsistent. Instead we call focus().
'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'disableRemotePlayback', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata
'itemScope'].forEach(function (name) {
properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty
name.toLowerCase(), // attributeName
null, // attributeNamespace
false, // sanitizeURL
false);
}); // These are the few React props that we set as DOM properties
// rather than attributes. These are all booleans.
['checked', // Note: `option.selected` is not updated if `select.multiple` is
// disabled with `removeAttribute`. We have special logic for handling this.
'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (name) {
properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty
name, // attributeName
null, // attributeNamespace
false, // sanitizeURL
false);
}); // These are HTML attributes that are "overloaded booleans": they behave like
// booleans, but can also accept a string value.
['capture', 'download' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (name) {
properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty
name, // attributeName
null, // attributeNamespace
false, // sanitizeURL
false);
}); // These are HTML attributes that must be positive numbers.
['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (name) {
properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty
name, // attributeName
null, // attributeNamespace
false, // sanitizeURL
false);
}); // These are HTML attributes that must be numbers.
['rowSpan', 'start'].forEach(function (name) {
properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty
name.toLowerCase(), // attributeName
null, // attributeNamespace
false, // sanitizeURL
false);
});
var CAMELIZE = /[\-\:]([a-z])/g;
var capitalize = function (token) {
return token[1].toUpperCase();
}; // This is a list of all SVG attributes that need special casing, namespacing,
// or boolean value assignment. Regular attributes that just accept strings
// and have the same names are omitted, just like in the HTML attribute filter.
// Some of these attributes can be hard to find. This list was created by
// scraping the MDN documentation.
['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (attributeName) {
var name = attributeName.replace(CAMELIZE, capitalize);
properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
attributeName, null, // attributeNamespace
false, // sanitizeURL
false);
}); // String SVG attributes with the xlink namespace.
['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (attributeName) {
var name = attributeName.replace(CAMELIZE, capitalize);
properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
attributeName, 'http://www.w3.org/1999/xlink', false, // sanitizeURL
false);
}); // String SVG attributes with the xml namespace.
['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list,
// you'll need to set attributeName to name.toLowerCase()
// instead in the assignment below.
].forEach(function (attributeName) {
var name = attributeName.replace(CAMELIZE, capitalize);
properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
attributeName, 'http://www.w3.org/XML/1998/namespace', false, // sanitizeURL
false);
}); // These attribute exists both in HTML and SVG.
// The attribute name is case-sensitive in SVG so we can't just use
// the React name like we do for attributes that exist only in HTML.
['tabIndex', 'crossOrigin'].forEach(function (attributeName) {
properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
attributeName.toLowerCase(), // attributeName
null, // attributeNamespace
false, // sanitizeURL
false);
}); // These attributes accept URLs. These must not allow javascript: URLS.
// These will also need to accept Trusted Types object in the future.
var xlinkHref = 'xlinkHref';
properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty
'xlink:href', 'http://www.w3.org/1999/xlink', true, // sanitizeURL
false);
['src', 'href', 'action', 'formAction'].forEach(function (attributeName) {
properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
attributeName.toLowerCase(), // attributeName
null, // attributeNamespace
true, // sanitizeURL
true);
});
// and any newline or tab are filtered out as if they're not part of the URL.
// https://url.spec.whatwg.org/#url-parsing
// Tab or newline are defined as \r\n\t:
// https://infra.spec.whatwg.org/#ascii-tab-or-newline
// A C0 control is a code point in the range \u0000 NULL to \u001F
// INFORMATION SEPARATOR ONE, inclusive:
// https://infra.spec.whatwg.org/#c0-control-or-space
/* eslint-disable max-len */
var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i;
var didWarn = false;
function sanitizeURL(url) {
{
if (!didWarn && isJavaScriptProtocol.test(url)) {
didWarn = true;
error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url));
}
}
}
/**
* Get the value for a property on a node. Only used in DEV for SSR validation.
* The "expected" argument is used as a hint of what the expected value is.
* Some properties have multiple equivalent values.
*/
function getValueForProperty(node, name, expected, propertyInfo) {
{
if (propertyInfo.mustUseProperty) {
var propertyName = propertyInfo.propertyName;
return node[propertyName];
} else {
// This check protects multiple uses of `expected`, which is why the
// react-internal/safe-string-coercion rule is disabled in several spots
// below.
{
checkAttributeStringCoercion(expected, name);
}
if ( propertyInfo.sanitizeURL) {
// If we haven't fully disabled javascript: URLs, and if
// the hydration is successful of a javascript: URL, we
// still want to warn on the client.
// eslint-disable-next-line react-internal/safe-string-coercion
sanitizeURL('' + expected);
}
var attributeName = propertyInfo.attributeName;
var stringValue = null;
if (propertyInfo.type === OVERLOADED_BOOLEAN) {
if (node.hasAttribute(attributeName)) {
var value = node.getAttribute(attributeName);
if (value === '') {
return true;
}
if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
return value;
} // eslint-disable-next-line react-internal/safe-string-coercion
if (value === '' + expected) {
return expected;
}
return value;
}
} else if (node.hasAttribute(attributeName)) {
if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
// We had an attribute but shouldn't have had one, so read it
// for the error message.
return node.getAttribute(attributeName);
}
if (propertyInfo.type === BOOLEAN) {
// If this was a boolean, it doesn't matter what the value is
// the fact that we have it is the same as the expected.
return expected;
} // Even if this property uses a namespace we use getAttribute
// because we assume its namespaced name is the same as our config.
// To use getAttributeNS we need the local name which we don't have
// in our config atm.
stringValue = node.getAttribute(attributeName);
}
if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
return stringValue === null ? expected : stringValue; // eslint-disable-next-line react-internal/safe-string-coercion
} else if (stringValue === '' + expected) {
return expected;
} else {
return stringValue;
}
}
}
}
/**
* Get the value for a attribute on a node. Only used in DEV for SSR validation.
* The third argument is used as a hint of what the expected value is. Some
* attributes have multiple equivalent values.
*/
function getValueForAttribute(node, name, expected, isCustomComponentTag) {
{
if (!isAttributeNameSafe(name)) {
return;
}
if (!node.hasAttribute(name)) {
return expected === undefined ? undefined : null;
}
var value = node.getAttribute(name);
{
checkAttributeStringCoercion(expected, name);
}
if (value === '' + expected) {
return expected;
}
return value;
}
}
/**
* Sets the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
* @param {*} value
*/
function setValueForProperty(node, name, value, isCustomComponentTag) {
var propertyInfo = getPropertyInfo(name);
if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) {
return;
}
if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) {
value = null;
}
if (isCustomComponentTag || propertyInfo === null) {
if (isAttributeNameSafe(name)) {
var _attributeName = name;
if (value === null) {
node.removeAttribute(_attributeName);
} else {
{
checkAttributeStringCoercion(value, name);
}
node.setAttribute(_attributeName, '' + value);
}
}
return;
}
var mustUseProperty = propertyInfo.mustUseProperty;
if (mustUseProperty) {
var propertyName = propertyInfo.propertyName;
if (value === null) {
var type = propertyInfo.type;
node[propertyName] = type === BOOLEAN ? false : '';
} else {
// Contrary to `setAttribute`, object properties are properly
// `toString`ed by IE8/9.
node[propertyName] = value;
}
return;
} // The rest are treated as attributes with special cases.
var attributeName = propertyInfo.attributeName,
attributeNamespace = propertyInfo.attributeNamespace;
if (value === null) {
node.removeAttribute(attributeName);
} else {
var _type = propertyInfo.type;
var attributeValue;
if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) {
// If attribute type is boolean, we know for sure it won't be an execution sink
// and we won't require Trusted Type here.
attributeValue = '';
} else {
// `setAttribute` with objects becomes only `[object]` in IE8/9,
// ('' + value) makes it output the correct toString()-value.
{
{
checkAttributeStringCoercion(value, attributeName);
}
attributeValue = '' + value;
}
if (propertyInfo.sanitizeURL) {
sanitizeURL(attributeValue.toString());
}
}
if (attributeNamespace) {
node.setAttributeNS(attributeNamespace, attributeName, attributeValue);
} else {
node.setAttribute(attributeName, attributeValue);
}
}
}
// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
// The Symbol used to tag the ReactElement-like types.
var REACT_ELEMENT_TYPE = Symbol.for('react.element');
var REACT_PORTAL_TYPE = Symbol.for('react.portal');
var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
var REACT_CONTEXT_TYPE = Symbol.for('react.context');
var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
var REACT_MEMO_TYPE = Symbol.for('react.memo');
var REACT_LAZY_TYPE = Symbol.for('react.lazy');
var REACT_SCOPE_TYPE = Symbol.for('react.scope');
var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode');
var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');
var REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden');
var REACT_CACHE_TYPE = Symbol.for('react.cache');
var REACT_TRACING_MARKER_TYPE = Symbol.for('react.tracing_marker');
var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator';
function getIteratorFn(maybeIterable) {
if (maybeIterable === null || typeof maybeIterable !== 'object') {
return null;
}
var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
if (typeof maybeIterator === 'function') {
return maybeIterator;
}
return null;
}
var assign = Object.assign;
// Helpers to patch console.logs to avoid logging during side-effect free
// replaying on render function. This currently only patches the object
// lazily which won't cover if the log function was extracted eagerly.
// We could also eagerly patch the method.
var disabledDepth = 0;
var prevLog;
var prevInfo;
var prevWarn;
var prevError;
var prevGroup;
var prevGroupCollapsed;
var prevGroupEnd;
function disabledLog() {}
disabledLog.__reactDisabledLog = true;
function disableLogs() {
{
if (disabledDepth === 0) {
/* eslint-disable react-internal/no-production-logging */
prevLog = console.log;
prevInfo = console.info;
prevWarn = console.warn;
prevError = console.error;
prevGroup = console.group;
prevGroupCollapsed = console.groupCollapsed;
prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099
var props = {
configurable: true,
enumerable: true,
value: disabledLog,
writable: true
}; // $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console, {
info: props,
log: props,
warn: props,
error: props,
group: props,
groupCollapsed: props,
groupEnd: props
});
/* eslint-enable react-internal/no-production-logging */
}
disabledDepth++;
}
}
function reenableLogs() {
{
disabledDepth--;
if (disabledDepth === 0) {
/* eslint-disable react-internal/no-production-logging */
var props = {
configurable: true,
enumerable: true,
writable: true
}; // $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console, {
log: assign({}, props, {
value: prevLog
}),
info: assign({}, props, {
value: prevInfo
}),
warn: assign({}, props, {
value: prevWarn
}),
error: assign({}, props, {
value: prevError
}),
group: assign({}, props, {
value: prevGroup
}),
groupCollapsed: assign({}, props, {
value: prevGroupCollapsed
}),
groupEnd: assign({}, props, {
value: prevGroupEnd
})
});
/* eslint-enable react-internal/no-production-logging */
}
if (disabledDepth < 0) {
error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
}
}
}
var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
var prefix;
function describeBuiltInComponentFrame(name, source, ownerFn) {
{
if (prefix === undefined) {
// Extract the VM specific prefix used by each line.
try {
throw Error();
} catch (x) {
var match = x.stack.trim().match(/\n( *(at )?)/);
prefix = match && match[1] || '';
}
} // We use the prefix to ensure our stacks line up with native stack frames.
return '\n' + prefix + name;
}
}
var reentry = false;
var componentFrameCache;
{
var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
componentFrameCache = new PossiblyWeakMap();
}
function describeNativeComponentFrame(fn, construct) {
// If something asked for a stack inside a fake render, it should get ignored.
if ( !fn || reentry) {
return '';
}
{
var frame = componentFrameCache.get(fn);
if (frame !== undefined) {
return frame;
}
}
var control;
reentry = true;
var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.
Error.prepareStackTrace = undefined;
var previousDispatcher;
{
previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
// for warnings.
ReactCurrentDispatcher.current = null;
disableLogs();
}
try {
// This should throw.
if (construct) {
// Something should be setting the props in the constructor.
var Fake = function () {
throw Error();
}; // $FlowFixMe
Object.defineProperty(Fake.prototype, 'props', {
set: function () {
// We use a throwing setter instead of frozen or non-writable props
// because that won't throw in a non-strict mode function.
throw Error();
}
});
if (typeof Reflect === 'object' && Reflect.construct) {
// We construct a different control for this case to include any extra
// frames added by the construct call.
try {
Reflect.construct(Fake, []);
} catch (x) {
control = x;
}
Reflect.construct(fn, [], Fake);
} else {
try {
Fake.call();
} catch (x) {
control = x;
}
fn.call(Fake.prototype);
}
} else {
try {
throw Error();
} catch (x) {
control = x;
}
fn();
}
} catch (sample) {
// This is inlined manually because closure doesn't do it for us.
if (sample && control && typeof sample.stack === 'string') {
// This extracts the first frame from the sample that isn't also in the control.
// Skipping one frame that we assume is the frame that calls the two.
var sampleLines = sample.stack.split('\n');
var controlLines = control.stack.split('\n');
var s = sampleLines.length - 1;
var c = controlLines.length - 1;
while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
// We expect at least one stack frame to be shared.
// Typically this will be the root most one. However, stack frames may be
// cut off due to maximum stack limits. In this case, one maybe cut off
// earlier than the other. We assume that the sample is longer or the same
// and there for cut off earlier. So we should find the root most frame in
// the sample somewhere in the control.
c--;
}
for (; s >= 1 && c >= 0; s--, c--) {
// Next we find the first one that isn't the same which should be the
// frame that called our sample function and the control.
if (sampleLines[s] !== controlLines[c]) {
// In V8, the first line is describing the message but other VMs don't.
// If we're about to return the first line, and the control is also on the same
// line, that's a pretty good indicator that our sample threw at same line as
// the control. I.e. before we entered the sample frame. So we ignore this result.
// This can happen if you passed a class to function component, or non-function.
if (s !== 1 || c !== 1) {
do {
s--;
c--; // We may still have similar intermediate frames from the construct call.
// The next one that isn't the same should be our match though.
if (c < 0 || sampleLines[s] !== controlLines[c]) {
// V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
// but we have a user-provided "displayName"
// splice it in to make the stack more readable.
if (fn.displayName && _frame.includes('<anonymous>')) {
_frame = _frame.replace('<anonymous>', fn.displayName);
}
{
if (typeof fn === 'function') {
componentFrameCache.set(fn, _frame);
}
} // Return the line we found.
return _frame;
}
} while (s >= 1 && c >= 0);
}
break;
}
}
}
} finally {
reentry = false;
{
ReactCurrentDispatcher.current = previousDispatcher;
reenableLogs();
}
Error.prepareStackTrace = previousPrepareStackTrace;
} // Fallback to just using the name if we couldn't make it throw.
var name = fn ? fn.displayName || fn.name : '';
var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
{
if (typeof fn === 'function') {
componentFrameCache.set(fn, syntheticFrame);
}
}
return syntheticFrame;
}
function describeClassComponentFrame(ctor, source, ownerFn) {
{
return describeNativeComponentFrame(ctor, true);
}
}
function describeFunctionComponentFrame(fn, source, ownerFn) {
{
return describeNativeComponentFrame(fn, false);
}
}
function shouldConstruct(Component) {
var prototype = Component.prototype;
return !!(prototype && prototype.isReactComponent);
}
function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
if (type == null) {
return '';
}
if (typeof type === 'function') {
{
return describeNativeComponentFrame(type, shouldConstruct(type));
}
}
if (typeof type === 'string') {
return describeBuiltInComponentFrame(type);
}
switch (type) {
case REACT_SUSPENSE_TYPE:
return describeBuiltInComponentFrame('Suspense');
case REACT_SUSPENSE_LIST_TYPE:
return describeBuiltInComponentFrame('SuspenseList');
}
if (typeof type === 'object') {
switch (type.$$typeof) {
case REACT_FORWARD_REF_TYPE:
return describeFunctionComponentFrame(type.render);
case REACT_MEMO_TYPE:
// Memo may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
case REACT_LAZY_TYPE:
{
var lazyComponent = type;
var payload = lazyComponent._payload;
var init = lazyComponent._init;
try {
// Lazy may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
} catch (x) {}
}
}
}
return '';
}
function describeFiber(fiber) {
var owner = fiber._debugOwner ? fiber._debugOwner.type : null ;
var source = fiber._debugSource ;
switch (fiber.tag) {
case HostComponent:
return describeBuiltInComponentFrame(fiber.type);
case LazyComponent:
return describeBuiltInComponentFrame('Lazy');
case SuspenseComponent:
return describeBuiltInComponentFrame('Suspense');
case SuspenseListComponent:
return describeBuiltInComponentFrame('SuspenseList');
case FunctionComponent:
case IndeterminateComponent:
case SimpleMemoComponent:
return describeFunctionComponentFrame(fiber.type);
case ForwardRef:
return describeFunctionComponentFrame(fiber.type.render);
case ClassComponent:
return describeClassComponentFrame(fiber.type);
default:
return '';
}
}
function getStackByFiberInDevAndProd(workInProgress) {
try {
var info = '';
var node = workInProgress;
do {
info += describeFiber(node);
node = node.return;
} while (node);
return info;
} catch (x) {
return '\nError generating stack: ' + x.message + '\n' + x.stack;
}
}
function getWrappedName(outerType, innerType, wrapperName) {
var displayName = outerType.displayName;
if (displayName) {
return displayName;
}
var functionName = innerType.displayName || innerType.name || '';
return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
} // Keep in sync with react-reconciler/getComponentNameFromFiber
function getContextName(type) {
return type.displayName || 'Context';
} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.
function getComponentNameFromType(type) {
if (type == null) {
// Host root, text node or just invalid type.
return null;
}
{
if (typeof type.tag === 'number') {
error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
}
}
if (typeof type === 'function') {
return type.displayName || type.name || null;
}
if (typeof type === 'string') {
return type;
}
switch (type) {
case REACT_FRAGMENT_TYPE:
return 'Fragment';
case REACT_PORTAL_TYPE:
return 'Portal';
case REACT_PROFILER_TYPE:
return 'Profiler';
case REACT_STRICT_MODE_TYPE:
return 'StrictMode';
case REACT_SUSPENSE_TYPE:
return 'Suspense';
case REACT_SUSPENSE_LIST_TYPE:
return 'SuspenseList';
}
if (typeof type === 'object') {
switch (type.$$typeof) {
case REACT_CONTEXT_TYPE:
var context = type;
return getContextName(context) + '.Consumer';
case REACT_PROVIDER_TYPE:
var provider = type;
return getContextName(provider._context) + '.Provider';
case REACT_FORWARD_REF_TYPE:
return getWrappedName(type, type.render, 'ForwardRef');
case REACT_MEMO_TYPE:
var outerName = type.displayName || null;
if (outerName !== null) {
return outerName;
}
return getComponentNameFromType(type.type) || 'Memo';
case REACT_LAZY_TYPE:
{
var lazyComponent = type;
var payload = lazyComponent._payload;
var init = lazyComponent._init;
try {
return getComponentNameFromType(init(payload));
} catch (x) {
return null;
}
}
// eslint-disable-next-line no-fallthrough
}
}
return null;
}
function getWrappedName$1(outerType, innerType, wrapperName) {
var functionName = innerType.displayName || innerType.name || '';
return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName);
} // Keep in sync with shared/getComponentNameFromType
function getContextName$1(type) {
return type.displayName || 'Context';
}
function getComponentNameFromFiber(fiber) {
var tag = fiber.tag,
type = fiber.type;
switch (tag) {
case CacheComponent:
return 'Cache';
case ContextConsumer:
var context = type;
return getContextName$1(context) + '.Consumer';
case ContextProvider:
var provider = type;
return getContextName$1(provider._context) + '.Provider';
case DehydratedFragment:
return 'DehydratedFragment';
case ForwardRef:
return getWrappedName$1(type, type.render, 'ForwardRef');
case Fragment:
return 'Fragment';
case HostComponent:
// Host component type is the display name (e.g. "div", "View")
return type;
case HostPortal:
return 'Portal';
case HostRoot:
return 'Root';
case HostText:
return 'Text';
case LazyComponent:
// Name comes from the type in this case; we don't have a tag.
return getComponentNameFromType(type);
case Mode:
if (type === REACT_STRICT_MODE_TYPE) {
// Don't be less specific than shared/getComponentNameFromType
return 'StrictMode';
}
return 'Mode';
case OffscreenComponent:
return 'Offscreen';
case Profiler:
return 'Profiler';
case ScopeComponent:
return 'Scope';
case SuspenseComponent:
return 'Suspense';
case SuspenseListComponent:
return 'SuspenseList';
case TracingMarkerComponent:
return 'TracingMarker';
// The display name for this tags come from the user-provided type:
case ClassComponent:
case FunctionComponent:
case IncompleteClassComponent:
case IndeterminateComponent:
case MemoComponent:
case SimpleMemoComponent:
if (typeof type === 'function') {
return type.displayName || type.name || null;
}
if (typeof type === 'string') {
return type;
}
break;
}
return null;
}
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
var current = null;
var isRendering = false;
function getCurrentFiberOwnerNameInDevOrNull() {
{
if (current === null) {
return null;
}
var owner = current._debugOwner;
if (owner !== null && typeof owner !== 'undefined') {
return getComponentNameFromFiber(owner);
}
}
return null;
}
function getCurrentFiberStackInDev() {
{
if (current === null) {
return '';
} // Safe because if current fiber exists, we are reconciling,
// and it is guaranteed to be the work-in-progress version.
return getStackByFiberInDevAndProd(current);
}
}
function resetCurrentFiber() {
{
ReactDebugCurrentFrame.getCurrentStack = null;
current = null;
isRendering = false;
}
}
function setCurrentFiber(fiber) {
{
ReactDebugCurrentFrame.getCurrentStack = fiber === null ? null : getCurrentFiberStackInDev;
current = fiber;
isRendering = false;
}
}
function getCurrentFiber() {
{
return current;
}
}
function setIsRendering(rendering) {
{
isRendering = rendering;
}
}
// Flow does not allow string concatenation of most non-string types. To work
// around this limitation, we use an opaque type that can only be obtained by
// passing the value through getToStringValue first.
function toString(value) {
// The coercion safety check is performed in getToStringValue().
// eslint-disable-next-line react-internal/safe-string-coercion
return '' + value;
}
function getToStringValue(value) {
switch (typeof value) {
case 'boolean':
case 'number':
case 'string':
case 'undefined':
return value;
case 'object':
{
checkFormFieldValueStringCoercion(value);
}
return value;
default:
// function, symbol are assigned as empty strings
return '';
}
}
var hasReadOnlyValue = {
button: true,
checkbox: true,
image: true,
hidden: true,
radio: true,
reset: true,
submit: true
};
function checkControlledValueProps(tagName, props) {
{
if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) {
error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
}
if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) {
error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
}
}
}
function isCheckable(elem) {
var type = elem.type;
var nodeName = elem.nodeName;
return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio');
}
function getTracker(node) {
return node._valueTracker;
}
function detachTracker(node) {
node._valueTracker = null;
}
function getValueFromNode(node) {
var value = '';
if (!node) {
return value;
}
if (isCheckable(node)) {
value = node.checked ? 'true' : 'false';
} else {
value = node.value;
}
return value;
}
function trackValueOnNode(node) {
var valueField = isCheckable(node) ? 'checked' : 'value';
var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField);
{
checkFormFieldValueStringCoercion(node[valueField]);
}
var currentValue = '' + node[valueField]; // if someone has already defined a value or Safari, then bail
// and don't track value will cause over reporting of changes,
// but it's better then a hard failure
// (needed for certain tests that spyOn input values and Safari)
if (node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') {
return;
}
var get = descriptor.get,
set = descriptor.set;
Object.defineProperty(node, valueField, {
configurable: true,
get: function () {
return get.call(this);
},
set: function (value) {
{
checkFormFieldValueStringCoercion(value);
}
currentValue = '' + value;
set.call(this, value);
}
}); // We could've passed this the first time
// but it triggers a bug in IE11 and Edge 14/15.
// Calling defineProperty() again should be equivalent.
// https://github.com/facebook/react/issues/11768
Object.defineProperty(node, valueField, {
enumerable: descriptor.enumerable
});
var tracker = {
getValue: function () {
return currentValue;
},
setValue: function (value) {
{
checkFormFieldValueStringCoercion(value);
}
currentValue = '' + value;
},
stopTracking: function () {
detachTracker(node);
delete node[valueField];
}
};
return tracker;
}
function track(node) {
if (getTracker(node)) {
return;
} // TODO: Once it's just Fiber we can move this to node._wrapperState
node._valueTracker = trackValueOnNode(node);
}
function updateValueIfChanged(node) {
if (!node) {
return false;
}
var tracker = getTracker(node); // if there is no tracker at this point it's unlikely
// that trying again will succeed
if (!tracker) {
return true;
}
var lastValue = tracker.getValue();
var nextValue = getValueFromNode(node);
if (nextValue !== lastValue) {
tracker.setValue(nextValue);
return true;
}
return false;
}
function getActiveElement(doc) {
doc = doc || (typeof document !== 'undefined' ? document : undefined);
if (typeof doc === 'undefined') {
return null;
}
try {
return doc.activeElement || doc.body;
} catch (e) {
return doc.body;
}
}
var didWarnValueDefaultValue = false;
var didWarnCheckedDefaultChecked = false;
var didWarnControlledToUncontrolled = false;
var didWarnUncontrolledToControlled = false;
function isControlled(props) {
var usesChecked = props.type === 'checkbox' || props.type === 'radio';
return usesChecked ? props.checked != null : props.value != null;
}
/**
* Implements an <input> host component that allows setting these optional
* props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
*
* If `checked` or `value` are not supplied (or null/undefined), user actions
* that affect the checked state or value will trigger updates to the element.
*
* If they are supplied (and not null/undefined), the rendered element will not
* trigger updates to the element. Instead, the props must change in order for
* the rendered element to be updated.
*
* The rendered element will be initialized as unchecked (or `defaultChecked`)
* with an empty value (or `defaultValue`).
*
* See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
*/
function getHostProps(element, props) {
var node = element;
var checked = props.checked;
var hostProps = assign({}, props, {
defaultChecked: undefined,
defaultValue: undefined,
value: undefined,
checked: checked != null ? checked : node._wrapperState.initialChecked
});
return hostProps;
}
function initWrapperState(element, props) {
{
checkControlledValueProps('input', props);
if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) {
error('%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type);
didWarnCheckedDefaultChecked = true;
}
if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {
error('%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type);
didWarnValueDefaultValue = true;
}
}
var node = element;
var defaultValue = props.defaultValue == null ? '' : props.defaultValue;
node._wrapperState = {
initialChecked: props.checked != null ? props.checked : props.defaultChecked,
initialValue: getToStringValue(props.value != null ? props.value : defaultValue),
controlled: isControlled(props)
};
}
function updateChecked(element, props) {
var node = element;
var checked = props.checked;
if (checked != null) {
setValueForProperty(node, 'checked', checked, false);
}
}
function updateWrapper(element, props) {
var node = element;
{
var controlled = isControlled(props);
if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) {
error('A component is changing an uncontrolled input to be controlled. ' + 'This is likely caused by the value changing from undefined to ' + 'a defined value, which should not happen. ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components');
didWarnUncontrolledToControlled = true;
}
if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) {
error('A component is changing a controlled input to be uncontrolled. ' + 'This is likely caused by the value changing from a defined to ' + 'undefined, which should not happen. ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components');
didWarnControlledToUncontrolled = true;
}
}
updateChecked(element, props);
var value = getToStringValue(props.value);
var type = props.type;
if (value != null) {
if (type === 'number') {
if (value === 0 && node.value === '' || // We explicitly want to coerce to number here if possible.
// eslint-disable-next-line
node.value != value) {
node.value = toString(value);
}
} else if (node.value !== toString(value)) {
node.value = toString(value);
}
} else if (type === 'submit' || type === 'reset') {
// Submit/reset inputs need the attribute removed completely to avoid
// blank-text buttons.
node.removeAttribute('value');
return;
}
{
// When syncing the value attribute, the value comes from a cascade of
// properties:
// 1. The value React property
// 2. The defaultValue React property
// 3. Otherwise there should be no change
if (props.hasOwnProperty('value')) {
setDefaultValue(node, props.type, value);
} else if (props.hasOwnProperty('defaultValue')) {
setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
}
}
{
// When syncing the checked attribute, it only changes when it needs
// to be removed, such as transitioning from a checkbox into a text input
if (props.checked == null && props.defaultChecked != null) {
node.defaultChecked = !!props.defaultChecked;
}
}
}
function postMountWrapper(element, props, isHydrating) {
var node = element; // Do not assign value if it is already set. This prevents user text input
// from being lost during SSR hydration.
if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) {
var type = props.type;
var isButton = type === 'submit' || type === 'reset'; // Avoid setting value attribute on submit/reset inputs as it overrides the
// default value provided by the browser. See: #12872
if (isButton && (props.value === undefined || props.value === null)) {
return;
}
var initialValue = toString(node._wrapperState.initialValue); // Do not assign value if it is already set. This prevents user text input
// from being lost during SSR hydration.
if (!isHydrating) {
{
// When syncing the value attribute, the value property should use
// the wrapperState._initialValue property. This uses:
//
// 1. The value React property when present
// 2. The defaultValue React property when present
// 3. An empty string
if (initialValue !== node.value) {
node.value = initialValue;
}
}
}
{
// Otherwise, the value attribute is synchronized to the property,
// so we assign defaultValue to the same thing as the value property
// assignment step above.
node.defaultValue = initialValue;
}
} // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug
// this is needed to work around a chrome bug where setting defaultChecked
// will sometimes influence the value of checked (even after detachment).
// Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416
// We need to temporarily unset name to avoid disrupting radio button groups.
var name = node.name;
if (name !== '') {
node.name = '';
}
{
// When syncing the checked attribute, both the checked property and
// attribute are assigned at the same time using defaultChecked. This uses:
//
// 1. The checked React property when present
// 2. The defaultChecked React property when present
// 3. Otherwise, false
node.defaultChecked = !node.defaultChecked;
node.defaultChecked = !!node._wrapperState.initialChecked;
}
if (name !== '') {
node.name = name;
}
}
function restoreControlledState(element, props) {
var node = element;
updateWrapper(node, props);
updateNamedCousins(node, props);
}
function updateNamedCousins(rootNode, props) {
var name = props.name;
if (props.type === 'radio' && name != null) {
var queryRoot = rootNode;
while (queryRoot.parentNode) {
queryRoot = queryRoot.parentNode;
} // If `rootNode.form` was non-null, then we could try `form.elements`,
// but that sometimes behaves strangely in IE8. We could also try using
// `form.getElementsByName`, but that will only return direct children
// and won't include inputs that use the HTML5 `form=` attribute. Since
// the input might not even be in a form. It might not even be in the
// document. Let's just use the local `querySelectorAll` to ensure we don't
// miss anything.
{
checkAttributeStringCoercion(name, 'name');
}
var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]');
for (var i = 0; i < group.length; i++) {
var otherNode = group[i];
if (otherNode === rootNode || otherNode.form !== rootNode.form) {
continue;
} // This will throw if radio buttons rendered by different copies of React
// and the same name are rendered into the same form (same as #1939).
// That's probably okay; we don't support it just as we don't support
// mixing React radio buttons with non-React ones.
var otherProps = getFiberCurrentPropsFromNode(otherNode);
if (!otherProps) {
throw new Error('ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.');
} // We need update the tracked value on the named cousin since the value
// was changed but the input saw no event or value set
updateValueIfChanged(otherNode); // If this is a controlled radio button group, forcing the input that
// was previously checked to update will cause it to be come re-checked
// as appropriate.
updateWrapper(otherNode, otherProps);
}
}
} // In Chrome, assigning defaultValue to certain input types triggers input validation.
// For number inputs, the display value loses trailing decimal points. For email inputs,
// Chrome raises "The specified value <x> is not a valid email address".
//
// Here we check to see if the defaultValue has actually changed, avoiding these problems
// when the user is inputting text
//
// https://github.com/facebook/react/issues/7253
function setDefaultValue(node, type, value) {
if ( // Focused number inputs synchronize on blur. See ChangeEventPlugin.js
type !== 'number' || getActiveElement(node.ownerDocument) !== node) {
if (value == null) {
node.defaultValue = toString(node._wrapperState.initialValue);
} else if (node.defaultValue !== toString(value)) {
node.defaultValue = toString(value);
}
}
}
var didWarnSelectedSetOnOption = false;
var didWarnInvalidChild = false;
var didWarnInvalidInnerHTML = false;
/**
* Implements an <option> host component that warns when `selected` is set.
*/
function validateProps(element, props) {
{
// If a value is not provided, then the children must be simple.
if (props.value == null) {
if (typeof props.children === 'object' && props.children !== null) {
React.Children.forEach(props.children, function (child) {
if (child == null) {
return;
}
if (typeof child === 'string' || typeof child === 'number') {
return;
}
if (!didWarnInvalidChild) {
didWarnInvalidChild = true;
error('Cannot infer the option value of complex children. ' + 'Pass a `value` prop or use a plain string as children to <option>.');
}
});
} else if (props.dangerouslySetInnerHTML != null) {
if (!didWarnInvalidInnerHTML) {
didWarnInvalidInnerHTML = true;
error('Pass a `value` prop if you set dangerouslyInnerHTML so React knows ' + 'which value should be selected.');
}
}
} // TODO: Remove support for `selected` in <option>.
if (props.selected != null && !didWarnSelectedSetOnOption) {
error('Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');
didWarnSelectedSetOnOption = true;
}
}
}
function postMountWrapper$1(element, props) {
// value="" should make a value attribute (#6219)
if (props.value != null) {
element.setAttribute('value', toString(getToStringValue(props.value)));
}
}
var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
function isArray(a) {
return isArrayImpl(a);
}
var didWarnValueDefaultValue$1;
{
didWarnValueDefaultValue$1 = false;
}
function getDeclarationErrorAddendum() {
var ownerName = getCurrentFiberOwnerNameInDevOrNull();
if (ownerName) {
return '\n\nCheck the render method of `' + ownerName + '`.';
}
return '';
}
var valuePropNames = ['value', 'defaultValue'];
/**
* Validation function for `value` and `defaultValue`.
*/
function checkSelectPropTypes(props) {
{
checkControlledValueProps('select', props);
for (var i = 0; i < valuePropNames.length; i++) {
var propName = valuePropNames[i];
if (props[propName] == null) {
continue;
}
var propNameIsArray = isArray(props[propName]);
if (props.multiple && !propNameIsArray) {
error('The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum());
} else if (!props.multiple && propNameIsArray) {
error('The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum());
}
}
}
}
function updateOptions(node, multiple, propValue, setDefaultSelected) {
var options = node.options;
if (multiple) {
var selectedValues = propValue;
var selectedValue = {};
for (var i = 0; i < selectedValues.length; i++) {
// Prefix to avoid chaos with special keys.
selectedValue['$' + selectedValues[i]] = true;
}
for (var _i = 0; _i < options.length; _i++) {
var selected = selectedValue.hasOwnProperty('$' + options[_i].value);
if (options[_i].selected !== selected) {
options[_i].selected = selected;
}
if (selected && setDefaultSelected) {
options[_i].defaultSelected = true;
}
}
} else {
// Do not set `select.value` as exact behavior isn't consistent across all
// browsers for all cases.
var _selectedValue = toString(getToStringValue(propValue));
var defaultSelected = null;
for (var _i2 = 0; _i2 < options.length; _i2++) {
if (options[_i2].value === _selectedValue) {
options[_i2].selected = true;
if (setDefaultSelected) {
options[_i2].defaultSelected = true;
}
return;
}
if (defaultSelected === null && !options[_i2].disabled) {
defaultSelected = options[_i2];
}
}
if (defaultSelected !== null) {
defaultSelected.selected = true;
}
}
}
/**
* Implements a <select> host component that allows optionally setting the
* props `value` and `defaultValue`. If `multiple` is false, the prop must be a
* stringable. If `multiple` is true, the prop must be an array of stringables.
*
* If `value` is not supplied (or null/undefined), user actions that change the
* selected option will trigger updates to the rendered options.
*
* If it is supplied (and not null/undefined), the rendered options will not
* update in response to user actions. Instead, the `value` prop must change in
* order for the rendered options to update.
*
* If `defaultValue` is provided, any options with the supplied values will be
* selected.
*/
function getHostProps$1(element, props) {
return assign({}, props, {
value: undefined
});
}
function initWrapperState$1(element, props) {
var node = element;
{
checkSelectPropTypes(props);
}
node._wrapperState = {
wasMultiple: !!props.multiple
};
{
if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue$1) {
error('Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components');
didWarnValueDefaultValue$1 = true;
}
}
}
function postMountWrapper$2(element, props) {
var node = element;
node.multiple = !!props.multiple;
var value = props.value;
if (value != null) {
updateOptions(node, !!props.multiple, value, false);
} else if (props.defaultValue != null) {
updateOptions(node, !!props.multiple, props.defaultValue, true);
}
}
function postUpdateWrapper(element, props) {
var node = element;
var wasMultiple = node._wrapperState.wasMultiple;
node._wrapperState.wasMultiple = !!props.multiple;
var value = props.value;
if (value != null) {
updateOptions(node, !!props.multiple, value, false);
} else if (wasMultiple !== !!props.multiple) {
// For simplicity, reapply `defaultValue` if `multiple` is toggled.
if (props.defaultValue != null) {
updateOptions(node, !!props.multiple, props.defaultValue, true);
} else {
// Revert the select back to its default unselected state.
updateOptions(node, !!props.multiple, props.multiple ? [] : '', false);
}
}
}
function restoreControlledState$1(element, props) {
var node = element;
var value = props.value;
if (value != null) {
updateOptions(node, !!props.multiple, value, false);
}
}
var didWarnValDefaultVal = false;
/**
* Implements a <textarea> host component that allows setting `value`, and
* `defaultValue`. This differs from the traditional DOM API because value is
* usually set as PCDATA children.
*
* If `value` is not supplied (or null/undefined), user actions that affect the
* value will trigger updates to the element.
*
* If `value` is supplied (and not null/undefined), the rendered element will
* not trigger updates to the element. Instead, the `value` prop must change in
* order for the rendered element to be updated.
*
* The rendered element will be initialized with an empty value, the prop
* `defaultValue` if specified, or the children content (deprecated).
*/
function getHostProps$2(element, props) {
var node = element;
if (props.dangerouslySetInnerHTML != null) {
throw new Error('`dangerouslySetInnerHTML` does not make sense on <textarea>.');
} // Always set children to the same thing. In IE9, the selection range will
// get reset if `textContent` is mutated. We could add a check in setTextContent
// to only set the value if/when the value differs from the node value (which would
// completely solve this IE9 bug), but Sebastian+Sophie seemed to like this
// solution. The value can be a boolean or object so that's why it's forced
// to be a string.
var hostProps = assign({}, props, {
value: undefined,
defaultValue: undefined,
children: toString(node._wrapperState.initialValue)
});
return hostProps;
}
function initWrapperState$2(element, props) {
var node = element;
{
checkControlledValueProps('textarea', props);
if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) {
error('%s contains a textarea with both value and defaultValue props. ' + 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component');
didWarnValDefaultVal = true;
}
}
var initialValue = props.value; // Only bother fetching default value if we're going to use it
if (initialValue == null) {
var children = props.children,
defaultValue = props.defaultValue;
if (children != null) {
{
error('Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
}
{
if (defaultValue != null) {
throw new Error('If you supply `defaultValue` on a <textarea>, do not pass children.');
}
if (isArray(children)) {
if (children.length > 1) {
throw new Error('<textarea> can only have at most one child.');
}
children = children[0];
}
defaultValue = children;
}
}
if (defaultValue == null) {
defaultValue = '';
}
initialValue = defaultValue;
}
node._wrapperState = {
initialValue: getToStringValue(initialValue)
};
}
function updateWrapper$1(element, props) {
var node = element;
var value = getToStringValue(props.value);
var defaultValue = getToStringValue(props.defaultValue);
if (value != null) {
// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
var newValue = toString(value); // To avoid side effects (such as losing text selection), only set value if changed
if (newValue !== node.value) {
node.value = newValue;
}
if (props.defaultValue == null && node.defaultValue !== newValue) {
node.defaultValue = newValue;
}
}
if (defaultValue != null) {
node.defaultValue = toString(defaultValue);
}
}
function postMountWrapper$3(element, props) {
var node = element; // This is in postMount because we need access to the DOM node, which is not
// available until after the component has mounted.
var textContent = node.textContent; // Only set node.value if textContent is equal to the expected
// initial value. In IE10/IE11 there is a bug where the placeholder attribute
// will populate textContent as well.
// https://developer.microsoft.com/microsoft-edge/platform/issues/101525/
if (textContent === node._wrapperState.initialValue) {
if (textContent !== '' && textContent !== null) {
node.value = textContent;
}
}
}
function restoreControlledState$2(element, props) {
// DOM component is still mounted; update
updateWrapper$1(element, props);
}
var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
var MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
var SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; // Assumes there is no parent namespace.
function getIntrinsicNamespace(type) {
switch (type) {
case 'svg':
return SVG_NAMESPACE;
case 'math':
return MATH_NAMESPACE;
default:
return HTML_NAMESPACE;
}
}
function getChildNamespace(parentNamespace, type) {
if (parentNamespace == null || parentNamespace === HTML_NAMESPACE) {
// No (or default) parent namespace: potential entry point.
return getIntrinsicNamespace(type);
}
if (parentNamespace === SVG_NAMESPACE && type === 'foreignObject') {
// We're leaving SVG.
return HTML_NAMESPACE;
} // By default, pass namespace below.
return parentNamespace;
}
/* globals MSApp */
/**
* Create a function which has 'unsafe' privileges (required by windows8 apps)
*/
var createMicrosoftUnsafeLocalFunction = function (func) {
if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
return function (arg0, arg1, arg2, arg3) {
MSApp.execUnsafeLocalFunction(function () {
return func(arg0, arg1, arg2, arg3);
});
};
} else {
return func;
}
};
var reusableSVGContainer;
/**
* Set the innerHTML property of a node
*
* @param {DOMElement} node
* @param {string} html
* @internal
*/
var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) {
if (node.namespaceURI === SVG_NAMESPACE) {
if (!('innerHTML' in node)) {
// IE does not have innerHTML for SVG nodes, so instead we inject the
// new markup in a temp node and then move the child nodes across into
// the target node
reusableSVGContainer = reusableSVGContainer || document.createElement('div');
reusableSVGContainer.innerHTML = '<svg>' + html.valueOf().toString() + '</svg>';
var svgNode = reusableSVGContainer.firstChild;
while (node.firstChild) {
node.removeChild(node.firstChild);
}
while (svgNode.firstChild) {
node.appendChild(svgNode.firstChild);
}
return;
}
}
node.innerHTML = html;
});
/**
* HTML nodeType values that represent the type of the node
*/
var ELEMENT_NODE = 1;
var TEXT_NODE = 3;
var COMMENT_NODE = 8;
var DOCUMENT_NODE = 9;
var DOCUMENT_FRAGMENT_NODE = 11;
/**
* Set the textContent property of a node. For text updates, it's faster
* to set the `nodeValue` of the Text node directly instead of using
* `.textContent` which will remove the existing node and create a new one.
*
* @param {DOMElement} node
* @param {string} text
* @internal
*/
var setTextContent = function (node, text) {
if (text) {
var firstChild = node.firstChild;
if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {
firstChild.nodeValue = text;
return;
}
}
node.textContent = text;
};
// List derived from Gecko source code:
// https://github.com/mozilla/gecko-dev/blob/4e638efc71/layout/style/test/property_database.js
var shorthandToLonghand = {
animation: ['animationDelay', 'animationDirection', 'animationDuration', 'animationFillMode', 'animationIterationCount', 'animationName', 'animationPlayState', 'animationTimingFunction'],
background: ['backgroundAttachment', 'backgroundClip', 'backgroundColor', 'backgroundImage', 'backgroundOrigin', 'backgroundPositionX', 'backgroundPositionY', 'backgroundRepeat', 'backgroundSize'],
backgroundPosition: ['backgroundPositionX', 'backgroundPositionY'],
border: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth', 'borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderTopColor', 'borderTopStyle', 'borderTopWidth'],
borderBlockEnd: ['borderBlockEndColor', 'borderBlockEndStyle', 'borderBlockEndWidth'],
borderBlockStart: ['borderBlockStartColor', 'borderBlockStartStyle', 'borderBlockStartWidth'],
borderBottom: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth'],
borderColor: ['borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor'],
borderImage: ['borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth'],
borderInlineEnd: ['borderInlineEndColor', 'borderInlineEndStyle', 'borderInlineEndWidth'],
borderInlineStart: ['borderInlineStartColor', 'borderInlineStartStyle', 'borderInlineStartWidth'],
borderLeft: ['borderLeftColor', 'borderLeftStyle', 'borderLeftWidth'],
borderRadius: ['borderBottomLeftRadius', 'borderBottomRightRadius', 'borderTopLeftRadius', 'borderTopRightRadius'],
borderRight: ['borderRightColor', 'borderRightStyle', 'borderRightWidth'],
borderStyle: ['borderBottomStyle', 'borderLeftStyle', 'borderRightStyle', 'borderTopStyle'],
borderTop: ['borderTopColor', 'borderTopStyle', 'borderTopWidth'],
borderWidth: ['borderBottomWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth'],
columnRule: ['columnRuleColor', 'columnRuleStyle', 'columnRuleWidth'],
columns: ['columnCount', 'columnWidth'],
flex: ['flexBasis', 'flexGrow', 'flexShrink'],
flexFlow: ['flexDirection', 'flexWrap'],
font: ['fontFamily', 'fontFeatureSettings', 'fontKerning', 'fontLanguageOverride', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition', 'fontWeight', 'lineHeight'],
fontVariant: ['fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition'],
gap: ['columnGap', 'rowGap'],
grid: ['gridAutoColumns', 'gridAutoFlow', 'gridAutoRows', 'gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
gridArea: ['gridColumnEnd', 'gridColumnStart', 'gridRowEnd', 'gridRowStart'],
gridColumn: ['gridColumnEnd', 'gridColumnStart'],
gridColumnGap: ['columnGap'],
gridGap: ['columnGap', 'rowGap'],
gridRow: ['gridRowEnd', 'gridRowStart'],
gridRowGap: ['rowGap'],
gridTemplate: ['gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
listStyle: ['listStyleImage', 'listStylePosition', 'listStyleType'],
margin: ['marginBottom', 'marginLeft', 'marginRight', 'marginTop'],
marker: ['markerEnd', 'markerMid', 'markerStart'],
mask: ['maskClip', 'maskComposite', 'maskImage', 'maskMode', 'maskOrigin', 'maskPositionX', 'maskPositionY', 'maskRepeat', 'maskSize'],
maskPosition: ['maskPositionX', 'maskPositionY'],
outline: ['outlineColor', 'outlineStyle', 'outlineWidth'],
overflow: ['overflowX', 'overflowY'],
padding: ['paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop'],
placeContent: ['alignContent', 'justifyContent'],
placeItems: ['alignItems', 'justifyItems'],
placeSelf: ['alignSelf', 'justifySelf'],
textDecoration: ['textDecorationColor', 'textDecorationLine', 'textDecorationStyle'],
textEmphasis: ['textEmphasisColor', 'textEmphasisStyle'],
transition: ['transitionDelay', 'transitionDuration', 'transitionProperty', 'transitionTimingFunction'],
wordWrap: ['overflowWrap']
};
/**
* CSS properties which accept numbers but are not in units of "px".
*/
var isUnitlessNumber = {
animationIterationCount: true,
aspectRatio: true,
borderImageOutset: true,
borderImageSlice: true,
borderImageWidth: true,
boxFlex: true,
boxFlexGroup: true,
boxOrdinalGroup: true,
columnCount: true,
columns: true,
flex: true,
flexGrow: true,
flexPositive: true,
flexShrink: true,
flexNegative: true,
flexOrder: true,
gridArea: true,
gridRow: true,
gridRowEnd: true,
gridRowSpan: true,
gridRowStart: true,
gridColumn: true,
gridColumnEnd: true,
gridColumnSpan: true,
gridColumnStart: true,
fontWeight: true,
lineClamp: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
tabSize: true,
widows: true,
zIndex: true,
zoom: true,
// SVG-related properties
fillOpacity: true,
floodOpacity: true,
stopOpacity: true,
strokeDasharray: true,
strokeDashoffset: true,
strokeMiterlimit: true,
strokeOpacity: true,
strokeWidth: true
};
/**
* @param {string} prefix vendor-specific prefix, eg: Webkit
* @param {string} key style name, eg: transitionDuration
* @return {string} style name prefixed with `prefix`, properly camelCased, eg:
* WebkitTransitionDuration
*/
function prefixKey(prefix, key) {
return prefix + key.charAt(0).toUpperCase() + key.substring(1);
}
/**
* Support style names that may come passed in prefixed by adding permutations
* of vendor prefixes.
*/
var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
// infinite loop, because it iterates over the newly added props too.
Object.keys(isUnitlessNumber).forEach(function (prop) {
prefixes.forEach(function (prefix) {
isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
});
});
/**
* Convert a value into the proper css writable value. The style name `name`
* should be logical (no hyphens), as specified
* in `CSSProperty.isUnitlessNumber`.
*
* @param {string} name CSS property name such as `topMargin`.
* @param {*} value CSS property value such as `10px`.
* @return {string} Normalized style value with dimensions applied.
*/
function dangerousStyleValue(name, value, isCustomProperty) {
// Note that we've removed escapeTextForBrowser() calls here since the
// whole string will be escaped when the attribute is injected into
// the markup. If you provide unsafe user data here they can inject
// arbitrary CSS which may be problematic (I couldn't repro this):
// https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
// http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
// This is not an XSS hole but instead a potential CSS injection issue
// which has lead to a greater discussion about how we're going to
// trust URLs moving forward. See #2115901
var isEmpty = value == null || typeof value === 'boolean' || value === '';
if (isEmpty) {
return '';
}
if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) {
return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers
}
{
checkCSSPropertyStringCoercion(value, name);
}
return ('' + value).trim();
}
var uppercasePattern = /([A-Z])/g;
var msPattern = /^ms-/;
/**
* Hyphenates a camelcased CSS property name, for example:
*
* > hyphenateStyleName('backgroundColor')
* < "background-color"
* > hyphenateStyleName('MozTransition')
* < "-moz-transition"
* > hyphenateStyleName('msTransition')
* < "-ms-transition"
*
* As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
* is converted to `-ms-`.
*/
function hyphenateStyleName(name) {
return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-');
}
var warnValidStyle = function () {};
{
// 'msTransform' is correct, but the other prefixes should be capitalized
var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
var msPattern$1 = /^-ms-/;
var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon
var badStyleValueWithSemicolonPattern = /;\s*$/;
var warnedStyleNames = {};
var warnedStyleValues = {};
var warnedForNaNValue = false;
var warnedForInfinityValue = false;
var camelize = function (string) {
return string.replace(hyphenPattern, function (_, character) {
return character.toUpperCase();
});
};
var warnHyphenatedStyleName = function (name) {
if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
return;
}
warnedStyleNames[name] = true;
error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests
// (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
// is converted to lowercase `ms`.
camelize(name.replace(msPattern$1, 'ms-')));
};
var warnBadVendoredStyleName = function (name) {
if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
return;
}
warnedStyleNames[name] = true;
error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));
};
var warnStyleValueWithSemicolon = function (name, value) {
if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
return;
}
warnedStyleValues[value] = true;
error("Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));
};
var warnStyleValueIsNaN = function (name, value) {
if (warnedForNaNValue) {
return;
}
warnedForNaNValue = true;
error('`NaN` is an invalid value for the `%s` css style property.', name);
};
var warnStyleValueIsInfinity = function (name, value) {
if (warnedForInfinityValue) {
return;
}
warnedForInfinityValue = true;
error('`Infinity` is an invalid value for the `%s` css style property.', name);
};
warnValidStyle = function (name, value) {
if (name.indexOf('-') > -1) {
warnHyphenatedStyleName(name);
} else if (badVendoredStyleNamePattern.test(name)) {
warnBadVendoredStyleName(name);
} else if (badStyleValueWithSemicolonPattern.test(value)) {
warnStyleValueWithSemicolon(name, value);
}
if (typeof value === 'number') {
if (isNaN(value)) {
warnStyleValueIsNaN(name, value);
} else if (!isFinite(value)) {
warnStyleValueIsInfinity(name, value);
}
}
};
}
var warnValidStyle$1 = warnValidStyle;
/**
* Operations for dealing with CSS properties.
*/
/**
* This creates a string that is expected to be equivalent to the style
* attribute generated by server-side rendering. It by-passes warnings and
* security checks so it's not safe to use this value for anything other than
* comparison. It is only used in DEV for SSR validation.
*/
function createDangerousStringForStyles(styles) {
{
var serialized = '';
var delimiter = '';
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var styleValue = styles[styleName];
if (styleValue != null) {
var isCustomProperty = styleName.indexOf('--') === 0;
serialized += delimiter + (isCustomProperty ? styleName : hyphenateStyleName(styleName)) + ':';
serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);
delimiter = ';';
}
}
return serialized || null;
}
}
/**
* Sets the value for multiple styles on a node. If a value is specified as
* '' (empty string), the corresponding style property will be unset.
*
* @param {DOMElement} node
* @param {object} styles
*/
function setValueForStyles(node, styles) {
var style = node.style;
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var isCustomProperty = styleName.indexOf('--') === 0;
{
if (!isCustomProperty) {
warnValidStyle$1(styleName, styles[styleName]);
}
}
var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty);
if (styleName === 'float') {
styleName = 'cssFloat';
}
if (isCustomProperty) {
style.setProperty(styleName, styleValue);
} else {
style[styleName] = styleValue;
}
}
}
function isValueEmpty(value) {
return value == null || typeof value === 'boolean' || value === '';
}
/**
* Given {color: 'red', overflow: 'hidden'} returns {
* color: 'color',
* overflowX: 'overflow',
* overflowY: 'overflow',
* }. This can be read as "the overflowY property was set by the overflow
* shorthand". That is, the values are the property that each was derived from.
*/
function expandShorthandMap(styles) {
var expanded = {};
for (var key in styles) {
var longhands = shorthandToLonghand[key] || [key];
for (var i = 0; i < longhands.length; i++) {
expanded[longhands[i]] = key;
}
}
return expanded;
}
/**
* When mixing shorthand and longhand property names, we warn during updates if
* we expect an incorrect result to occur. In particular, we warn for:
*
* Updating a shorthand property (longhand gets overwritten):
* {font: 'foo', fontVariant: 'bar'} -> {font: 'baz', fontVariant: 'bar'}
* becomes .style.font = 'baz'
* Removing a shorthand property (longhand gets lost too):
* {font: 'foo', fontVariant: 'bar'} -> {fontVariant: 'bar'}
* becomes .style.font = ''
* Removing a longhand property (should revert to shorthand; doesn't):
* {font: 'foo', fontVariant: 'bar'} -> {font: 'foo'}
* becomes .style.fontVariant = ''
*/
function validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) {
{
if (!nextStyles) {
return;
}
var expandedUpdates = expandShorthandMap(styleUpdates);
var expandedStyles = expandShorthandMap(nextStyles);
var warnedAbout = {};
for (var key in expandedUpdates) {
var originalKey = expandedUpdates[key];
var correctOriginalKey = expandedStyles[key];
if (correctOriginalKey && originalKey !== correctOriginalKey) {
var warningKey = originalKey + ',' + correctOriginalKey;
if (warnedAbout[warningKey]) {
continue;
}
warnedAbout[warningKey] = true;
error('%s a style property during rerender (%s) when a ' + 'conflicting property is set (%s) can lead to styling bugs. To ' + "avoid this, don't mix shorthand and non-shorthand properties " + 'for the same value; instead, replace the shorthand with ' + 'separate values.', isValueEmpty(styleUpdates[originalKey]) ? 'Removing' : 'Updating', originalKey, correctOriginalKey);
}
}
}
}
// For HTML, certain tags should omit their close tag. We keep a list for
// those special-case tags.
var omittedCloseTags = {
area: true,
base: true,
br: true,
col: true,
embed: true,
hr: true,
img: true,
input: true,
keygen: true,
link: true,
meta: true,
param: true,
source: true,
track: true,
wbr: true // NOTE: menuitem's close tag should be omitted, but that causes problems.
};
// `omittedCloseTags` except that `menuitem` should still have its closing tag.
var voidElementTags = assign({
menuitem: true
}, omittedCloseTags);
var HTML = '__html';
function assertValidProps(tag, props) {
if (!props) {
return;
} // Note the use of `==` which checks for null or undefined.
if (voidElementTags[tag]) {
if (props.children != null || props.dangerouslySetInnerHTML != null) {
throw new Error(tag + " is a void element tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.');
}
}
if (props.dangerouslySetInnerHTML != null) {
if (props.children != null) {
throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.');
}
if (typeof props.dangerouslySetInnerHTML !== 'object' || !(HTML in props.dangerouslySetInnerHTML)) {
throw new Error('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://reactjs.org/link/dangerously-set-inner-html ' + 'for more information.');
}
}
{
if (!props.suppressContentEditableWarning && props.contentEditable && props.children != null) {
error('A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.');
}
}
if (props.style != null && typeof props.style !== 'object') {
throw new Error('The `style` prop expects a mapping from style properties to values, ' + "not a string. For example, style={{marginRight: spacing + 'em'}} when " + 'using JSX.');
}
}
function isCustomComponent(tagName, props) {
if (tagName.indexOf('-') === -1) {
return typeof props.is === 'string';
}
switch (tagName) {
// These are reserved SVG and MathML elements.
// We don't mind this list too much because we expect it to never grow.
// The alternative is to track the namespace in a few places which is convoluted.
// https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
case 'annotation-xml':
case 'color-profile':
case 'font-face':
case 'font-face-src':
case 'font-face-uri':
case 'font-face-format':
case 'font-face-name':
case 'missing-glyph':
return false;
default:
return true;
}
}
// When adding attributes to the HTML or SVG allowed attribute list, be sure to
// also add them to this module to ensure casing and incorrect name
// warnings.
var possibleStandardNames = {
// HTML
accept: 'accept',
acceptcharset: 'acceptCharset',
'accept-charset': 'acceptCharset',
accesskey: 'accessKey',
action: 'action',
allowfullscreen: 'allowFullScreen',
alt: 'alt',
as: 'as',
async: 'async',
autocapitalize: 'autoCapitalize',
autocomplete: 'autoComplete',
autocorrect: 'autoCorrect',
autofocus: 'autoFocus',
autoplay: 'autoPlay',
autosave: 'autoSave',
capture: 'capture',
cellpadding: 'cellPadding',
cellspacing: 'cellSpacing',
challenge: 'challenge',
charset: 'charSet',
checked: 'checked',
children: 'children',
cite: 'cite',
class: 'className',
classid: 'classID',
classname: 'className',
cols: 'cols',
colspan: 'colSpan',
content: 'content',
contenteditable: 'contentEditable',
contextmenu: 'contextMenu',
controls: 'controls',
controlslist: 'controlsList',
coords: 'coords',
crossorigin: 'crossOrigin',
dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
data: 'data',
datetime: 'dateTime',
default: 'default',
defaultchecked: 'defaultChecked',
defaultvalue: 'defaultValue',
defer: 'defer',
dir: 'dir',
disabled: 'disabled',
disablepictureinpicture: 'disablePictureInPicture',
disableremoteplayback: 'disableRemotePlayback',
download: 'download',
draggable: 'draggable',
enctype: 'encType',
enterkeyhint: 'enterKeyHint',
for: 'htmlFor',
form: 'form',
formmethod: 'formMethod',
formaction: 'formAction',
formenctype: 'formEncType',
formnovalidate: 'formNoValidate',
formtarget: 'formTarget',
frameborder: 'frameBorder',
headers: 'headers',
height: 'height',
hidden: 'hidden',
high: 'high',
href: 'href',
hreflang: 'hrefLang',
htmlfor: 'htmlFor',
httpequiv: 'httpEquiv',
'http-equiv': 'httpEquiv',
icon: 'icon',
id: 'id',
imagesizes: 'imageSizes',
imagesrcset: 'imageSrcSet',
innerhtml: 'innerHTML',
inputmode: 'inputMode',
integrity: 'integrity',
is: 'is',
itemid: 'itemID',
itemprop: 'itemProp',
itemref: 'itemRef',
itemscope: 'itemScope',
itemtype: 'itemType',
keyparams: 'keyParams',
keytype: 'keyType',
kind: 'kind',
label: 'label',
lang: 'lang',
list: 'list',
loop: 'loop',
low: 'low',
manifest: 'manifest',
marginwidth: 'marginWidth',
marginheight: 'marginHeight',
max: 'max',
maxlength: 'maxLength',
media: 'media',
mediagroup: 'mediaGroup',
method: 'method',
min: 'min',
minlength: 'minLength',
multiple: 'multiple',
muted: 'muted',
name: 'name',
nomodule: 'noModule',
nonce: 'nonce',
novalidate: 'noValidate',
open: 'open',
optimum: 'optimum',
pattern: 'pattern',
placeholder: 'placeholder',
playsinline: 'playsInline',
poster: 'poster',
preload: 'preload',
profile: 'profile',
radiogroup: 'radioGroup',
readonly: 'readOnly',
referrerpolicy: 'referrerPolicy',
rel: 'rel',
required: 'required',
reversed: 'reversed',
role: 'role',
rows: 'rows',
rowspan: 'rowSpan',
sandbox: 'sandbox',
scope: 'scope',
scoped: 'scoped',
scrolling: 'scrolling',
seamless: 'seamless',
selected: 'selected',
shape: 'shape',
size: 'size',
sizes: 'sizes',
span: 'span',
spellcheck: 'spellCheck',
src: 'src',
srcdoc: 'srcDoc',
srclang: 'srcLang',
srcset: 'srcSet',
start: 'start',
step: 'step',
style: 'style',
summary: 'summary',
tabindex: 'tabIndex',
target: 'target',
title: 'title',
type: 'type',
usemap: 'useMap',
value: 'value',
width: 'width',
wmode: 'wmode',
wrap: 'wrap',
// SVG
about: 'about',
accentheight: 'accentHeight',
'accent-height': 'accentHeight',
accumulate: 'accumulate',
additive: 'additive',
alignmentbaseline: 'alignmentBaseline',
'alignment-baseline': 'alignmentBaseline',
allowreorder: 'allowReorder',
alphabetic: 'alphabetic',
amplitude: 'amplitude',
arabicform: 'arabicForm',
'arabic-form': 'arabicForm',
ascent: 'ascent',
attributename: 'attributeName',
attributetype: 'attributeType',
autoreverse: 'autoReverse',
azimuth: 'azimuth',
basefrequency: 'baseFrequency',
baselineshift: 'baselineShift',
'baseline-shift': 'baselineShift',
baseprofile: 'baseProfile',
bbox: 'bbox',
begin: 'begin',
bias: 'bias',
by: 'by',
calcmode: 'calcMode',
capheight: 'capHeight',
'cap-height': 'capHeight',
clip: 'clip',
clippath: 'clipPath',
'clip-path': 'clipPath',
clippathunits: 'clipPathUnits',
cliprule: 'clipRule',
'clip-rule': 'clipRule',
color: 'color',
colorinterpolation: 'colorInterpolation',
'color-interpolation': 'colorInterpolation',
colorinterpolationfilters: 'colorInterpolationFilters',
'color-interpolation-filters': 'colorInterpolationFilters',
colorprofile: 'colorProfile',
'color-profile': 'colorProfile',
colorrendering: 'colorRendering',
'color-rendering': 'colorRendering',
contentscripttype: 'contentScriptType',
contentstyletype: 'contentStyleType',
cursor: 'cursor',
cx: 'cx',
cy: 'cy',
d: 'd',
datatype: 'datatype',
decelerate: 'decelerate',
descent: 'descent',
diffuseconstant: 'diffuseConstant',
direction: 'direction',
display: 'display',
divisor: 'divisor',
dominantbaseline: 'dominantBaseline',
'dominant-baseline': 'dominantBaseline',
dur: 'dur',
dx: 'dx',
dy: 'dy',
edgemode: 'edgeMode',
elevation: 'elevation',
enablebackground: 'enableBackground',
'enable-background': 'enableBackground',
end: 'end',
exponent: 'exponent',
externalresourcesrequired: 'externalResourcesRequired',
fill: 'fill',
fillopacity: 'fillOpacity',
'fill-opacity': 'fillOpacity',
fillrule: 'fillRule',
'fill-rule': 'fillRule',
filter: 'filter',
filterres: 'filterRes',
filterunits: 'filterUnits',
floodopacity: 'floodOpacity',
'flood-opacity': 'floodOpacity',
floodcolor: 'floodColor',
'flood-color': 'floodColor',
focusable: 'focusable',
fontfamily: 'fontFamily',
'font-family': 'fontFamily',
fontsize: 'fontSize',
'font-size': 'fontSize',
fontsizeadjust: 'fontSizeAdjust',
'font-size-adjust': 'fontSizeAdjust',
fontstretch: 'fontStretch',
'font-stretch': 'fontStretch',
fontstyle: 'fontStyle',
'font-style': 'fontStyle',
fontvariant: 'fontVariant',
'font-variant': 'fontVariant',
fontweight: 'fontWeight',
'font-weight': 'fontWeight',
format: 'format',
from: 'from',
fx: 'fx',
fy: 'fy',
g1: 'g1',
g2: 'g2',
glyphname: 'glyphName',
'glyph-name': 'glyphName',
glyphorientationhorizontal: 'glyphOrientationHorizontal',
'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
glyphorientationvertical: 'glyphOrientationVertical',
'glyph-orientation-vertical': 'glyphOrientationVertical',
glyphref: 'glyphRef',
gradienttransform: 'gradientTransform',
gradientunits: 'gradientUnits',
hanging: 'hanging',
horizadvx: 'horizAdvX',
'horiz-adv-x': 'horizAdvX',
horizoriginx: 'horizOriginX',
'horiz-origin-x': 'horizOriginX',
ideographic: 'ideographic',
imagerendering: 'imageRendering',
'image-rendering': 'imageRendering',
in2: 'in2',
in: 'in',
inlist: 'inlist',
intercept: 'intercept',
k1: 'k1',
k2: 'k2',
k3: 'k3',
k4: 'k4',
k: 'k',
kernelmatrix: 'kernelMatrix',
kernelunitlength: 'kernelUnitLength',
kerning: 'kerning',
keypoints: 'keyPoints',
keysplines: 'keySplines',
keytimes: 'keyTimes',
lengthadjust: 'lengthAdjust',
letterspacing: 'letterSpacing',
'letter-spacing': 'letterSpacing',
lightingcolor: 'lightingColor',
'lighting-color': 'lightingColor',
limitingconeangle: 'limitingConeAngle',
local: 'local',
markerend: 'markerEnd',
'marker-end': 'markerEnd',
markerheight: 'markerHeight',
markermid: 'markerMid',
'marker-mid': 'markerMid',
markerstart: 'markerStart',
'marker-start': 'markerStart',
markerunits: 'markerUnits',
markerwidth: 'markerWidth',
mask: 'mask',
maskcontentunits: 'maskContentUnits',
maskunits: 'maskUnits',
mathematical: 'mathematical',
mode: 'mode',
numoctaves: 'numOctaves',
offset: 'offset',
opacity: 'opacity',
operator: 'operator',
order: 'order',
orient: 'orient',
orientation: 'orientation',
origin: 'origin',
overflow: 'overflow',
overlineposition: 'overlinePosition',
'overline-position': 'overlinePosition',
overlinethickness: 'overlineThickness',
'overline-thickness': 'overlineThickness',
paintorder: 'paintOrder',
'paint-order': 'paintOrder',
panose1: 'panose1',
'panose-1': 'panose1',
pathlength: 'pathLength',
patterncontentunits: 'patternContentUnits',
patterntransform: 'patternTransform',
patternunits: 'patternUnits',
pointerevents: 'pointerEvents',
'pointer-events': 'pointerEvents',
points: 'points',
pointsatx: 'pointsAtX',
pointsaty: 'pointsAtY',
pointsatz: 'pointsAtZ',
prefix: 'prefix',
preservealpha: 'preserveAlpha',
preserveaspectratio: 'preserveAspectRatio',
primitiveunits: 'primitiveUnits',
property: 'property',
r: 'r',
radius: 'radius',
refx: 'refX',
refy: 'refY',
renderingintent: 'renderingIntent',
'rendering-intent': 'renderingIntent',
repeatcount: 'repeatCount',
repeatdur: 'repeatDur',
requiredextensions: 'requiredExtensions',
requiredfeatures: 'requiredFeatures',
resource: 'resource',
restart: 'restart',
result: 'result',
results: 'results',
rotate: 'rotate',
rx: 'rx',
ry: 'ry',
scale: 'scale',
security: 'security',
seed: 'seed',
shaperendering: 'shapeRendering',
'shape-rendering': 'shapeRendering',
slope: 'slope',
spacing: 'spacing',
specularconstant: 'specularConstant',
specularexponent: 'specularExponent',
speed: 'speed',
spreadmethod: 'spreadMethod',
startoffset: 'startOffset',
stddeviation: 'stdDeviation',
stemh: 'stemh',
stemv: 'stemv',
stitchtiles: 'stitchTiles',
stopcolor: 'stopColor',
'stop-color': 'stopColor',
stopopacity: 'stopOpacity',
'stop-opacity': 'stopOpacity',
strikethroughposition: 'strikethroughPosition',
'strikethrough-position': 'strikethroughPosition',
strikethroughthickness: 'strikethroughThickness',
'strikethrough-thickness': 'strikethroughThickness',
string: 'string',
stroke: 'stroke',
strokedasharray: 'strokeDasharray',
'stroke-dasharray': 'strokeDasharray',
strokedashoffset: 'strokeDashoffset',
'stroke-dashoffset': 'strokeDashoffset',
strokelinecap: 'strokeLinecap',
'stroke-linecap': 'strokeLinecap',
strokelinejoin: 'strokeLinejoin',
'stroke-linejoin': 'strokeLinejoin',
strokemiterlimit: 'strokeMiterlimit',
'stroke-miterlimit': 'strokeMiterlimit',
strokewidth: 'strokeWidth',
'stroke-width': 'strokeWidth',
strokeopacity: 'strokeOpacity',
'stroke-opacity': 'strokeOpacity',
suppresscontenteditablewarning: 'suppressContentEditableWarning',
suppresshydrationwarning: 'suppressHydrationWarning',
surfacescale: 'surfaceScale',
systemlanguage: 'systemLanguage',
tablevalues: 'tableValues',
targetx: 'targetX',
targety: 'targetY',
textanchor: 'textAnchor',
'text-anchor': 'textAnchor',
textdecoration: 'textDecoration',
'text-decoration': 'textDecoration',
textlength: 'textLength',
textrendering: 'textRendering',
'text-rendering': 'textRendering',
to: 'to',
transform: 'transform',
typeof: 'typeof',
u1: 'u1',
u2: 'u2',
underlineposition: 'underlinePosition',
'underline-position': 'underlinePosition',
underlinethickness: 'underlineThickness',
'underline-thickness': 'underlineThickness',
unicode: 'unicode',
unicodebidi: 'unicodeBidi',
'unicode-bidi': 'unicodeBidi',
unicoderange: 'unicodeRange',
'unicode-range': 'unicodeRange',
unitsperem: 'unitsPerEm',
'units-per-em': 'unitsPerEm',
unselectable: 'unselectable',
valphabetic: 'vAlphabetic',
'v-alphabetic': 'vAlphabetic',
values: 'values',
vectoreffect: 'vectorEffect',
'vector-effect': 'vectorEffect',
version: 'version',
vertadvy: 'vertAdvY',
'vert-adv-y': 'vertAdvY',
vertoriginx: 'vertOriginX',
'vert-origin-x': 'vertOriginX',
vertoriginy: 'vertOriginY',
'vert-origin-y': 'vertOriginY',
vhanging: 'vHanging',
'v-hanging': 'vHanging',
videographic: 'vIdeographic',
'v-ideographic': 'vIdeographic',
viewbox: 'viewBox',
viewtarget: 'viewTarget',
visibility: 'visibility',
vmathematical: 'vMathematical',
'v-mathematical': 'vMathematical',
vocab: 'vocab',
widths: 'widths',
wordspacing: 'wordSpacing',
'word-spacing': 'wordSpacing',
writingmode: 'writingMode',
'writing-mode': 'writingMode',
x1: 'x1',
x2: 'x2',
x: 'x',
xchannelselector: 'xChannelSelector',
xheight: 'xHeight',
'x-height': 'xHeight',
xlinkactuate: 'xlinkActuate',
'xlink:actuate': 'xlinkActuate',
xlinkarcrole: 'xlinkArcrole',
'xlink:arcrole': 'xlinkArcrole',
xlinkhref: 'xlinkHref',
'xlink:href': 'xlinkHref',
xlinkrole: 'xlinkRole',
'xlink:role': 'xlinkRole',
xlinkshow: 'xlinkShow',
'xlink:show': 'xlinkShow',
xlinktitle: 'xlinkTitle',
'xlink:title': 'xlinkTitle',
xlinktype: 'xlinkType',
'xlink:type': 'xlinkType',
xmlbase: 'xmlBase',
'xml:base': 'xmlBase',
xmllang: 'xmlLang',
'xml:lang': 'xmlLang',
xmlns: 'xmlns',
'xml:space': 'xmlSpace',
xmlnsxlink: 'xmlnsXlink',
'xmlns:xlink': 'xmlnsXlink',
xmlspace: 'xmlSpace',
y1: 'y1',
y2: 'y2',
y: 'y',
ychannelselector: 'yChannelSelector',
z: 'z',
zoomandpan: 'zoomAndPan'
};
var ariaProperties = {
'aria-current': 0,
// state
'aria-description': 0,
'aria-details': 0,
'aria-disabled': 0,
// state
'aria-hidden': 0,
// state
'aria-invalid': 0,
// state
'aria-keyshortcuts': 0,
'aria-label': 0,
'aria-roledescription': 0,
// Widget Attributes
'aria-autocomplete': 0,
'aria-checked': 0,
'aria-expanded': 0,
'aria-haspopup': 0,
'aria-level': 0,
'aria-modal': 0,
'aria-multiline': 0,
'aria-multiselectable': 0,
'aria-orientation': 0,
'aria-placeholder': 0,
'aria-pressed': 0,
'aria-readonly': 0,
'aria-required': 0,
'aria-selected': 0,
'aria-sort': 0,
'aria-valuemax': 0,
'aria-valuemin': 0,
'aria-valuenow': 0,
'aria-valuetext': 0,
// Live Region Attributes
'aria-atomic': 0,
'aria-busy': 0,
'aria-live': 0,
'aria-relevant': 0,
// Drag-and-Drop Attributes
'aria-dropeffect': 0,
'aria-grabbed': 0,
// Relationship Attributes
'aria-activedescendant': 0,
'aria-colcount': 0,
'aria-colindex': 0,
'aria-colspan': 0,
'aria-controls': 0,
'aria-describedby': 0,
'aria-errormessage': 0,
'aria-flowto': 0,
'aria-labelledby': 0,
'aria-owns': 0,
'aria-posinset': 0,
'aria-rowcount': 0,
'aria-rowindex': 0,
'aria-rowspan': 0,
'aria-setsize': 0
};
var warnedProperties = {};
var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
function validateProperty(tagName, name) {
{
if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) {
return true;
}
if (rARIACamel.test(name)) {
var ariaName = 'aria-' + name.slice(4).toLowerCase();
var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM
// DOM properties, then it is an invalid aria-* attribute.
if (correctName == null) {
error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);
warnedProperties[name] = true;
return true;
} // aria-* attributes should be lowercase; suggest the lowercase version.
if (name !== correctName) {
error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);
warnedProperties[name] = true;
return true;
}
}
if (rARIA.test(name)) {
var lowerCasedName = name.toLowerCase();
var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM
// DOM properties, then it is an invalid aria-* attribute.
if (standardName == null) {
warnedProperties[name] = true;
return false;
} // aria-* attributes should be lowercase; suggest the lowercase version.
if (name !== standardName) {
error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);
warnedProperties[name] = true;
return true;
}
}
}
return true;
}
function warnInvalidARIAProps(type, props) {
{
var invalidProps = [];
for (var key in props) {
var isValid = validateProperty(type, key);
if (!isValid) {
invalidProps.push(key);
}
}
var unknownPropString = invalidProps.map(function (prop) {
return '`' + prop + '`';
}).join(', ');
if (invalidProps.length === 1) {
error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);
} else if (invalidProps.length > 1) {
error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);
}
}
}
function validateProperties(type, props) {
if (isCustomComponent(type, props)) {
return;
}
warnInvalidARIAProps(type, props);
}
var didWarnValueNull = false;
function validateProperties$1(type, props) {
{
if (type !== 'input' && type !== 'textarea' && type !== 'select') {
return;
}
if (props != null && props.value === null && !didWarnValueNull) {
didWarnValueNull = true;
if (type === 'select' && props.multiple) {
error('`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type);
} else {
error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type);
}
}
}
}
var validateProperty$1 = function () {};
{
var warnedProperties$1 = {};
var EVENT_NAME_REGEX = /^on./;
var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
validateProperty$1 = function (tagName, name, value, eventRegistry) {
if (hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
return true;
}
var lowerCasedName = name.toLowerCase();
if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.');
warnedProperties$1[name] = true;
return true;
} // We can't rely on the event system being injected on the server.
if (eventRegistry != null) {
var registrationNameDependencies = eventRegistry.registrationNameDependencies,
possibleRegistrationNames = eventRegistry.possibleRegistrationNames;
if (registrationNameDependencies.hasOwnProperty(name)) {
return true;
}
var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;
if (registrationName != null) {
error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);
warnedProperties$1[name] = true;
return true;
}
if (EVENT_NAME_REGEX.test(name)) {
error('Unknown event handler property `%s`. It will be ignored.', name);
warnedProperties$1[name] = true;
return true;
}
} else if (EVENT_NAME_REGEX.test(name)) {
// If no event plugins have been injected, we are in a server environment.
// So we can't tell if the event name is correct for sure, but we can filter
// out known bad ones like `onclick`. We can't suggest a specific replacement though.
if (INVALID_EVENT_NAME_REGEX.test(name)) {
error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);
}
warnedProperties$1[name] = true;
return true;
} // Let the ARIA attribute hook validate ARIA attributes
if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
return true;
}
if (lowerCasedName === 'innerhtml') {
error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');
warnedProperties$1[name] = true;
return true;
}
if (lowerCasedName === 'aria') {
error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');
warnedProperties$1[name] = true;
return true;
}
if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);
warnedProperties$1[name] = true;
return true;
}
if (typeof value === 'number' && isNaN(value)) {
error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);
warnedProperties$1[name] = true;
return true;
}
var propertyInfo = getPropertyInfo(name);
var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config.
if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
var standardName = possibleStandardNames[lowerCasedName];
if (standardName !== name) {
error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);
warnedProperties$1[name] = true;
return true;
}
} else if (!isReserved && name !== lowerCasedName) {
// Unknown attributes should have lowercase casing since that's how they
// will be cased anyway with server rendering.
error('React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName);
warnedProperties$1[name] = true;
return true;
}
if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
if (value) {
error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.', value, name, name, value, name);
} else {
error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name);
}
warnedProperties$1[name] = true;
return true;
} // Now that we've validated casing, do not validate
// data types for reserved props
if (isReserved) {
return true;
} // Warn when a known attribute is a bad type
if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
warnedProperties$1[name] = true;
return false;
} // Warn when passing the strings 'false' or 'true' into a boolean prop
if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
error('Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string "false".', name, value);
warnedProperties$1[name] = true;
return true;
}
return true;
};
}
var warnUnknownProperties = function (type, props, eventRegistry) {
{
var unknownProps = [];
for (var key in props) {
var isValid = validateProperty$1(type, key, props[key], eventRegistry);
if (!isValid) {
unknownProps.push(key);
}
}
var unknownPropString = unknownProps.map(function (prop) {
return '`' + prop + '`';
}).join(', ');
if (unknownProps.length === 1) {
error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type);
} else if (unknownProps.length > 1) {
error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type);
}
}
};
function validateProperties$2(type, props, eventRegistry) {
if (isCustomComponent(type, props)) {
return;
}
warnUnknownProperties(type, props, eventRegistry);
}
var IS_EVENT_HANDLE_NON_MANAGED_NODE = 1;
var IS_NON_DELEGATED = 1 << 1;
var IS_CAPTURE_PHASE = 1 << 2;
// set to LEGACY_FB_SUPPORT. LEGACY_FB_SUPPORT only gets set when
// we call willDeferLaterForLegacyFBSupport, thus not bailing out
// will result in endless cycles like an infinite loop.
// We also don't want to defer during event replaying.
var SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS = IS_EVENT_HANDLE_NON_MANAGED_NODE | IS_NON_DELEGATED | IS_CAPTURE_PHASE;
// This exists to avoid circular dependency between ReactDOMEventReplaying
// and DOMPluginEventSystem.
var currentReplayingEvent = null;
function setReplayingEvent(event) {
{
if (currentReplayingEvent !== null) {
error('Expected currently replaying event to be null. This error ' + 'is likely caused by a bug in React. Please file an issue.');
}
}
currentReplayingEvent = event;
}
function resetReplayingEvent() {
{
if (currentReplayingEvent === null) {
error('Expected currently replaying event to not be null. This error ' + 'is likely caused by a bug in React. Please file an issue.');
}
}
currentReplayingEvent = null;
}
function isReplayingEvent(event) {
return event === currentReplayingEvent;
}
/**
* Gets the target node from a native browser event by accounting for
* inconsistencies in browser DOM APIs.
*
* @param {object} nativeEvent Native browser event.
* @return {DOMEventTarget} Target node.
*/
function getEventTarget(nativeEvent) {
// Fallback to nativeEvent.srcElement for IE9
// https://github.com/facebook/react/issues/12506
var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963
if (target.correspondingUseElement) {
target = target.correspondingUseElement;
} // Safari may fire events on text nodes (Node.TEXT_NODE is 3).
// @see http://www.quirksmode.org/js/events_properties.html
return target.nodeType === TEXT_NODE ? target.parentNode : target;
}
var restoreImpl = null;
var restoreTarget = null;
var restoreQueue = null;
function restoreStateOfTarget(target) {
// We perform this translation at the end of the event loop so that we
// always receive the correct fiber here
var internalInstance = getInstanceFromNode(target);
if (!internalInstance) {
// Unmounted
return;
}
if (typeof restoreImpl !== 'function') {
throw new Error('setRestoreImplementation() needs to be called to handle a target for controlled ' + 'events. This error is likely caused by a bug in React. Please file an issue.');
}
var stateNode = internalInstance.stateNode; // Guard against Fiber being unmounted.
if (stateNode) {
var _props = getFiberCurrentPropsFromNode(stateNode);
restoreImpl(internalInstance.stateNode, internalInstance.type, _props);
}
}
function setRestoreImplementation(impl) {
restoreImpl = impl;
}
function enqueueStateRestore(target) {
if (restoreTarget) {
if (restoreQueue) {
restoreQueue.push(target);
} else {
restoreQueue = [target];
}
} else {
restoreTarget = target;
}
}
function needsStateRestore() {
return restoreTarget !== null || restoreQueue !== null;
}
function restoreStateIfNeeded() {
if (!restoreTarget) {
return;
}
var target = restoreTarget;
var queuedTargets = restoreQueue;
restoreTarget = null;
restoreQueue = null;
restoreStateOfTarget(target);
if (queuedTargets) {
for (var i = 0; i < queuedTargets.length; i++) {
restoreStateOfTarget(queuedTargets[i]);
}
}
}
// the renderer. Such as when we're dispatching events or if third party
// libraries need to call batchedUpdates. Eventually, this API will go away when
// everything is batched by default. We'll then have a similar API to opt-out of
// scheduled work and instead do synchronous work.
// Defaults
var batchedUpdatesImpl = function (fn, bookkeeping) {
return fn(bookkeeping);
};
var flushSyncImpl = function () {};
var isInsideEventHandler = false;
function finishEventHandler() {
// Here we wait until all updates have propagated, which is important
// when using controlled components within layers:
// https://github.com/facebook/react/issues/1698
// Then we restore state of any controlled component.
var controlledComponentsHavePendingUpdates = needsStateRestore();
if (controlledComponentsHavePendingUpdates) {
// If a controlled event was fired, we may need to restore the state of
// the DOM node back to the controlled value. This is necessary when React
// bails out of the update without touching the DOM.
// TODO: Restore state in the microtask, after the discrete updates flush,
// instead of early flushing them here.
flushSyncImpl();
restoreStateIfNeeded();
}
}
function batchedUpdates(fn, a, b) {
if (isInsideEventHandler) {
// If we are currently inside another batch, we need to wait until it
// fully completes before restoring state.
return fn(a, b);
}
isInsideEventHandler = true;
try {
return batchedUpdatesImpl(fn, a, b);
} finally {
isInsideEventHandler = false;
finishEventHandler();
}
} // TODO: Replace with flushSync
function setBatchingImplementation(_batchedUpdatesImpl, _discreteUpdatesImpl, _flushSyncImpl) {
batchedUpdatesImpl = _batchedUpdatesImpl;
flushSyncImpl = _flushSyncImpl;
}
function isInteractive(tag) {
return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
}
function shouldPreventMouseEvent(name, type, props) {
switch (name) {
case 'onClick':
case 'onClickCapture':
case 'onDoubleClick':
case 'onDoubleClickCapture':
case 'onMouseDown':
case 'onMouseDownCapture':
case 'onMouseMove':
case 'onMouseMoveCapture':
case 'onMouseUp':
case 'onMouseUpCapture':
case 'onMouseEnter':
return !!(props.disabled && isInteractive(type));
default:
return false;
}
}
/**
* @param {object} inst The instance, which is the source of events.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @return {?function} The stored callback.
*/
function getListener(inst, registrationName) {
var stateNode = inst.stateNode;
if (stateNode === null) {
// Work in progress (ex: onload events in incremental mode).
return null;
}
var props = getFiberCurrentPropsFromNode(stateNode);
if (props === null) {
// Work in progress.
return null;
}
var listener = props[registrationName];
if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
return null;
}
if (listener && typeof listener !== 'function') {
throw new Error("Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type.");
}
return listener;
}
var passiveBrowserEventsSupported = false; // Check if browser support events with passive listeners
// https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
if (canUseDOM) {
try {
var options = {}; // $FlowFixMe: Ignore Flow complaining about needing a value
Object.defineProperty(options, 'passive', {
get: function () {
passiveBrowserEventsSupported = true;
}
});
window.addEventListener('test', options, options);
window.removeEventListener('test', options, options);
} catch (e) {
passiveBrowserEventsSupported = false;
}
}
function invokeGuardedCallbackProd(name, func, context, a, b, c, d, e, f) {
var funcArgs = Array.prototype.slice.call(arguments, 3);
try {
func.apply(context, funcArgs);
} catch (error) {
this.onError(error);
}
}
var invokeGuardedCallbackImpl = invokeGuardedCallbackProd;
{
// In DEV mode, we swap out invokeGuardedCallback for a special version
// that plays more nicely with the browser's DevTools. The idea is to preserve
// "Pause on exceptions" behavior. Because React wraps all user-provided
// functions in invokeGuardedCallback, and the production version of
// invokeGuardedCallback uses a try-catch, all user exceptions are treated
// like caught exceptions, and the DevTools won't pause unless the developer
// takes the extra step of enabling pause on caught exceptions. This is
// unintuitive, though, because even though React has caught the error, from
// the developer's perspective, the error is uncaught.
//
// To preserve the expected "Pause on exceptions" behavior, we don't use a
// try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
// DOM node, and call the user-provided callback from inside an event handler
// for that fake event. If the callback throws, the error is "captured" using
// a global event handler. But because the error happens in a different
// event loop context, it does not interrupt the normal program flow.
// Effectively, this gives us try-catch behavior without actually using
// try-catch. Neat!
// Check that the browser supports the APIs we need to implement our special
// DEV version of invokeGuardedCallback
if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
var fakeNode = document.createElement('react');
invokeGuardedCallbackImpl = function invokeGuardedCallbackDev(name, func, context, a, b, c, d, e, f) {
// If document doesn't exist we know for sure we will crash in this method
// when we call document.createEvent(). However this can cause confusing
// errors: https://github.com/facebook/create-react-app/issues/3482
// So we preemptively throw with a better message instead.
if (typeof document === 'undefined' || document === null) {
throw new Error('The `document` global was defined when React was initialized, but is not ' + 'defined anymore. This can happen in a test environment if a component ' + 'schedules an update from an asynchronous callback, but the test has already ' + 'finished running. To solve this, you can either unmount the component at ' + 'the end of your test (and ensure that any asynchronous operations get ' + 'canceled in `componentWillUnmount`), or you can change the test itself ' + 'to be asynchronous.');
}
var evt = document.createEvent('Event');
var didCall = false; // Keeps track of whether the user-provided callback threw an error. We
// set this to true at the beginning, then set it to false right after
// calling the function. If the function errors, `didError` will never be
// set to false. This strategy works even if the browser is flaky and
// fails to call our global error handler, because it doesn't rely on
// the error event at all.
var didError = true; // Keeps track of the value of window.event so that we can reset it
// during the callback to let user code access window.event in the
// browsers that support it.
var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event
// dispatching: https://github.com/facebook/react/issues/13688
var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event');
function restoreAfterDispatch() {
// We immediately remove the callback from event listeners so that
// nested `invokeGuardedCallback` calls do not clash. Otherwise, a
// nested call would trigger the fake event handlers of any call higher
// in the stack.
fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the
// window.event assignment in both IE <= 10 as they throw an error
// "Member not found" in strict mode, and in Firefox which does not
// support window.event.
if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
window.event = windowEvent;
}
} // Create an event handler for our fake event. We will synchronously
// dispatch our fake event using `dispatchEvent`. Inside the handler, we
// call the user-provided callback.
var funcArgs = Array.prototype.slice.call(arguments, 3);
function callCallback() {
didCall = true;
restoreAfterDispatch();
func.apply(context, funcArgs);
didError = false;
} // Create a global error event handler. We use this to capture the value
// that was thrown. It's possible that this error handler will fire more
// than once; for example, if non-React code also calls `dispatchEvent`
// and a handler for that event throws. We should be resilient to most of
// those cases. Even if our error event handler fires more than once, the
// last error event is always used. If the callback actually does error,
// we know that the last error event is the correct one, because it's not
// possible for anything else to have happened in between our callback
// erroring and the code that follows the `dispatchEvent` call below. If
// the callback doesn't error, but the error event was fired, we know to
// ignore it because `didError` will be false, as described above.
var error; // Use this to track whether the error event is ever called.
var didSetError = false;
var isCrossOriginError = false;
function handleWindowError(event) {
error = event.error;
didSetError = true;
if (error === null && event.colno === 0 && event.lineno === 0) {
isCrossOriginError = true;
}
if (event.defaultPrevented) {
// Some other error handler has prevented default.
// Browsers silence the error report if this happens.
// We'll remember this to later decide whether to log it or not.
if (error != null && typeof error === 'object') {
try {
error._suppressLogging = true;
} catch (inner) {// Ignore.
}
}
}
} // Create a fake event type.
var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers
window.addEventListener('error', handleWindowError);
fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function
// errors, it will trigger our global error handler.
evt.initEvent(evtType, false, false);
fakeNode.dispatchEvent(evt);
if (windowEventDescriptor) {
Object.defineProperty(window, 'event', windowEventDescriptor);
}
if (didCall && didError) {
if (!didSetError) {
// The callback errored, but the error event never fired.
// eslint-disable-next-line react-internal/prod-error-codes
error = new Error('An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.');
} else if (isCrossOriginError) {
// eslint-disable-next-line react-internal/prod-error-codes
error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://reactjs.org/link/crossorigin-error for more information.');
}
this.onError(error);
} // Remove our event listeners
window.removeEventListener('error', handleWindowError);
if (!didCall) {
// Something went really wrong, and our event was not dispatched.
// https://github.com/facebook/react/issues/16734
// https://github.com/facebook/react/issues/16585
// Fall back to the production implementation.
restoreAfterDispatch();
return invokeGuardedCallbackProd.apply(this, arguments);
}
};
}
}
var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;
var hasError = false;
var caughtError = null; // Used by event system to capture/rethrow the first error.
var hasRethrowError = false;
var rethrowError = null;
var reporter = {
onError: function (error) {
hasError = true;
caughtError = error;
}
};
/**
* Call a function while guarding against errors that happens within it.
* Returns an error if it throws, otherwise null.
*
* In production, this is implemented using a try-catch. The reason we don't
* use a try-catch directly is so that we can swap out a different
* implementation in DEV mode.
*
* @param {String} name of the guard to use for logging or debugging
* @param {Function} func The function to invoke
* @param {*} context The context to use when calling the function
* @param {...*} args Arguments for function
*/
function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
hasError = false;
caughtError = null;
invokeGuardedCallbackImpl$1.apply(reporter, arguments);
}
/**
* Same as invokeGuardedCallback, but instead of returning an error, it stores
* it in a global so it can be rethrown by `rethrowCaughtError` later.
* TODO: See if caughtError and rethrowError can be unified.
*
* @param {String} name of the guard to use for logging or debugging
* @param {Function} func The function to invoke
* @param {*} context The context to use when calling the function
* @param {...*} args Arguments for function
*/
function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) {
invokeGuardedCallback.apply(this, arguments);
if (hasError) {
var error = clearCaughtError();
if (!hasRethrowError) {
hasRethrowError = true;
rethrowError = error;
}
}
}
/**
* During execution of guarded functions we will capture the first error which
* we will rethrow to be handled by the top level error handler.
*/
function rethrowCaughtError() {
if (hasRethrowError) {
var error = rethrowError;
hasRethrowError = false;
rethrowError = null;
throw error;
}
}
function hasCaughtError() {
return hasError;
}
function clearCaughtError() {
if (hasError) {
var error = caughtError;
hasError = false;
caughtError = null;
return error;
} else {
throw new Error('clearCaughtError was called but no error was captured. This error ' + 'is likely caused by a bug in React. Please file an issue.');
}
}
var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
var _ReactInternals$Sched = ReactInternals.Scheduler,
unstable_cancelCallback = _ReactInternals$Sched.unstable_cancelCallback,
unstable_now = _ReactInternals$Sched.unstable_now,
unstable_scheduleCallback = _ReactInternals$Sched.unstable_scheduleCallback,
unstable_shouldYield = _ReactInternals$Sched.unstable_shouldYield,
unstable_requestPaint = _ReactInternals$Sched.unstable_requestPaint,
unstable_getFirstCallbackNode = _ReactInternals$Sched.unstable_getFirstCallbackNode,
unstable_runWithPriority = _ReactInternals$Sched.unstable_runWithPriority,
unstable_next = _ReactInternals$Sched.unstable_next,
unstable_continueExecution = _ReactInternals$Sched.unstable_continueExecution,
unstable_pauseExecution = _ReactInternals$Sched.unstable_pauseExecution,
unstable_getCurrentPriorityLevel = _ReactInternals$Sched.unstable_getCurrentPriorityLevel,
unstable_ImmediatePriority = _ReactInternals$Sched.unstable_ImmediatePriority,
unstable_UserBlockingPriority = _ReactInternals$Sched.unstable_UserBlockingPriority,
unstable_NormalPriority = _ReactInternals$Sched.unstable_NormalPriority,
unstable_LowPriority = _ReactInternals$Sched.unstable_LowPriority,
unstable_IdlePriority = _ReactInternals$Sched.unstable_IdlePriority,
unstable_forceFrameRate = _ReactInternals$Sched.unstable_forceFrameRate,
unstable_flushAllWithoutAsserting = _ReactInternals$Sched.unstable_flushAllWithoutAsserting,
unstable_yieldValue = _ReactInternals$Sched.unstable_yieldValue,
unstable_setDisableYieldValue = _ReactInternals$Sched.unstable_setDisableYieldValue;
/**
* `ReactInstanceMap` maintains a mapping from a public facing stateful
* instance (key) and the internal representation (value). This allows public
* methods to accept the user facing instance as an argument and map them back
* to internal methods.
*
* Note that this module is currently shared and assumed to be stateless.
* If this becomes an actual Map, that will break.
*/
function get(key) {
return key._reactInternals;
}
function has(key) {
return key._reactInternals !== undefined;
}
function set(key, value) {
key._reactInternals = value;
}
// Don't change these two values. They're used by React Dev Tools.
var NoFlags =
/* */
0;
var PerformedWork =
/* */
1; // You can change the rest (and add more).
var Placement =
/* */
2;
var Update =
/* */
4;
var ChildDeletion =
/* */
16;
var ContentReset =
/* */
32;
var Callback =
/* */
64;
var DidCapture =
/* */
128;
var ForceClientRender =
/* */
256;
var Ref =
/* */
512;
var Snapshot =
/* */
1024;
var Passive =
/* */
2048;
var Hydrating =
/* */
4096;
var Visibility =
/* */
8192;
var StoreConsistency =
/* */
16384;
var LifecycleEffectMask = Passive | Update | Callback | Ref | Snapshot | StoreConsistency; // Union of all commit flags (flags with the lifetime of a particular commit)
var HostEffectMask =
/* */
32767; // These are not really side effects, but we still reuse this field.
var Incomplete =
/* */
32768;
var ShouldCapture =
/* */
65536;
var ForceUpdateForLegacySuspense =
/* */
131072;
var Forked =
/* */
1048576; // Static tags describe aspects of a fiber that are not specific to a render,
// e.g. a fiber uses a passive effect (even if there are no updates on this particular render).
// This enables us to defer more work in the unmount case,
// since we can defer traversing the tree during layout to look for Passive effects,
// and instead rely on the static flag as a signal that there may be cleanup work.
var RefStatic =
/* */
2097152;
var LayoutStatic =
/* */
4194304;
var PassiveStatic =
/* */
8388608; // These flags allow us to traverse to fibers that have effects on mount
// without traversing the entire tree after every commit for
// double invoking
var MountLayoutDev =
/* */
16777216;
var MountPassiveDev =
/* */
33554432; // Groups of flags that are used in the commit phase to skip over trees that
// don't contain effects, by checking subtreeFlags.
var BeforeMutationMask = // TODO: Remove Update flag from before mutation phase by re-landing Visibility
// flag logic (see #20043)
Update | Snapshot | ( 0);
var MutationMask = Placement | Update | ChildDeletion | ContentReset | Ref | Hydrating | Visibility;
var LayoutMask = Update | Callback | Ref | Visibility; // TODO: Split into PassiveMountMask and PassiveUnmountMask
var PassiveMask = Passive | ChildDeletion; // Union of tags that don't get reset on clones.
// This allows certain concepts to persist without recalculating them,
// e.g. whether a subtree contains passive effects or portals.
var StaticMask = LayoutStatic | PassiveStatic | RefStatic;
var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
function getNearestMountedFiber(fiber) {
var node = fiber;
var nearestMounted = fiber;
if (!fiber.alternate) {
// If there is no alternate, this might be a new tree that isn't inserted
// yet. If it is, then it will have a pending insertion effect on it.
var nextNode = node;
do {
node = nextNode;
if ((node.flags & (Placement | Hydrating)) !== NoFlags) {
// This is an insertion or in-progress hydration. The nearest possible
// mounted fiber is the parent but we need to continue to figure out
// if that one is still mounted.
nearestMounted = node.return;
}
nextNode = node.return;
} while (nextNode);
} else {
while (node.return) {
node = node.return;
}
}
if (node.tag === HostRoot) {
// TODO: Check if this was a nested HostRoot when used with
// renderContainerIntoSubtree.
return nearestMounted;
} // If we didn't hit the root, that means that we're in an disconnected tree
// that has been unmounted.
return null;
}
function getSuspenseInstanceFromFiber(fiber) {
if (fiber.tag === SuspenseComponent) {
var suspenseState = fiber.memoizedState;
if (suspenseState === null) {
var current = fiber.alternate;
if (current !== null) {
suspenseState = current.memoizedState;
}
}
if (suspenseState !== null) {
return suspenseState.dehydrated;
}
}
return null;
}
function getContainerFromFiber(fiber) {
return fiber.tag === HostRoot ? fiber.stateNode.containerInfo : null;
}
function isFiberMounted(fiber) {
return getNearestMountedFiber(fiber) === fiber;
}
function isMounted(component) {
{
var owner = ReactCurrentOwner.current;
if (owner !== null && owner.tag === ClassComponent) {
var ownerFiber = owner;
var instance = ownerFiber.stateNode;
if (!instance._warnedAboutRefsInRender) {
error('%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentNameFromFiber(ownerFiber) || 'A component');
}
instance._warnedAboutRefsInRender = true;
}
}
var fiber = get(component);
if (!fiber) {
return false;
}
return getNearestMountedFiber(fiber) === fiber;
}
function assertIsMounted(fiber) {
if (getNearestMountedFiber(fiber) !== fiber) {
throw new Error('Unable to find node on an unmounted component.');
}
}
function findCurrentFiberUsingSlowPath(fiber) {
var alternate = fiber.alternate;
if (!alternate) {
// If there is no alternate, then we only need to check if it is mounted.
var nearestMounted = getNearestMountedFiber(fiber);
if (nearestMounted === null) {
throw new Error('Unable to find node on an unmounted component.');
}
if (nearestMounted !== fiber) {
return null;
}
return fiber;
} // If we have two possible branches, we'll walk backwards up to the root
// to see what path the root points to. On the way we may hit one of the
// special cases and we'll deal with them.
var a = fiber;
var b = alternate;
while (true) {
var parentA = a.return;
if (parentA === null) {
// We're at the root.
break;
}
var parentB = parentA.alternate;
if (parentB === null) {
// There is no alternate. This is an unusual case. Currently, it only
// happens when a Suspense component is hidden. An extra fragment fiber
// is inserted in between the Suspense fiber and its children. Skip
// over this extra fragment fiber and proceed to the next parent.
var nextParent = parentA.return;
if (nextParent !== null) {
a = b = nextParent;
continue;
} // If there's no parent, we're at the root.
break;
} // If both copies of the parent fiber point to the same child, we can
// assume that the child is current. This happens when we bailout on low
// priority: the bailed out fiber's child reuses the current child.
if (parentA.child === parentB.child) {
var child = parentA.child;
while (child) {
if (child === a) {
// We've determined that A is the current branch.
assertIsMounted(parentA);
return fiber;
}
if (child === b) {
// We've determined that B is the current branch.
assertIsMounted(parentA);
return alternate;
}
child = child.sibling;
} // We should never have an alternate for any mounting node. So the only
// way this could possibly happen is if this was unmounted, if at all.
throw new Error('Unable to find node on an unmounted component.');
}
if (a.return !== b.return) {
// The return pointer of A and the return pointer of B point to different
// fibers. We assume that return pointers never criss-cross, so A must
// belong to the child set of A.return, and B must belong to the child
// set of B.return.
a = parentA;
b = parentB;
} else {
// The return pointers point to the same fiber. We'll have to use the
// default, slow path: scan the child sets of each parent alternate to see
// which child belongs to which set.
//
// Search parent A's child set
var didFindChild = false;
var _child = parentA.child;
while (_child) {
if (_child === a) {
didFindChild = true;
a = parentA;
b = parentB;
break;
}
if (_child === b) {
didFindChild = true;
b = parentA;
a = parentB;
break;
}
_child = _child.sibling;
}
if (!didFindChild) {
// Search parent B's child set
_child = parentB.child;
while (_child) {
if (_child === a) {
didFindChild = true;
a = parentB;
b = parentA;
break;
}
if (_child === b) {
didFindChild = true;
b = parentB;
a = parentA;
break;
}
_child = _child.sibling;
}
if (!didFindChild) {
throw new Error('Child was not found in either parent set. This indicates a bug ' + 'in React related to the return pointer. Please file an issue.');
}
}
}
if (a.alternate !== b) {
throw new Error("Return fibers should always be each others' alternates. " + 'This error is likely caused by a bug in React. Please file an issue.');
}
} // If the root is not a host container, we're in a disconnected tree. I.e.
// unmounted.
if (a.tag !== HostRoot) {
throw new Error('Unable to find node on an unmounted component.');
}
if (a.stateNode.current === a) {
// We've determined that A is the current branch.
return fiber;
} // Otherwise B has to be current branch.
return alternate;
}
function findCurrentHostFiber(parent) {
var currentParent = findCurrentFiberUsingSlowPath(parent);
return currentParent !== null ? findCurrentHostFiberImpl(currentParent) : null;
}
function findCurrentHostFiberImpl(node) {
// Next we'll drill down this component to find the first HostComponent/Text.
if (node.tag === HostComponent || node.tag === HostText) {
return node;
}
var child = node.child;
while (child !== null) {
var match = findCurrentHostFiberImpl(child);
if (match !== null) {
return match;
}
child = child.sibling;
}
return null;
}
function findCurrentHostFiberWithNoPortals(parent) {
var currentParent = findCurrentFiberUsingSlowPath(parent);
return currentParent !== null ? findCurrentHostFiberWithNoPortalsImpl(currentParent) : null;
}
function findCurrentHostFiberWithNoPortalsImpl(node) {
// Next we'll drill down this component to find the first HostComponent/Text.
if (node.tag === HostComponent || node.tag === HostText) {
return node;
}
var child = node.child;
while (child !== null) {
if (child.tag !== HostPortal) {
var match = findCurrentHostFiberWithNoPortalsImpl(child);
if (match !== null) {
return match;
}
}
child = child.sibling;
}
return null;
}
// This module only exists as an ESM wrapper around the external CommonJS
var scheduleCallback = unstable_scheduleCallback;
var cancelCallback = unstable_cancelCallback;
var shouldYield = unstable_shouldYield;
var requestPaint = unstable_requestPaint;
var now = unstable_now;
var getCurrentPriorityLevel = unstable_getCurrentPriorityLevel;
var ImmediatePriority = unstable_ImmediatePriority;
var UserBlockingPriority = unstable_UserBlockingPriority;
var NormalPriority = unstable_NormalPriority;
var LowPriority = unstable_LowPriority;
var IdlePriority = unstable_IdlePriority;
// this doesn't actually exist on the scheduler, but it *does*
// on scheduler/unstable_mock, which we'll need for internal testing
var unstable_yieldValue$1 = unstable_yieldValue;
var unstable_setDisableYieldValue$1 = unstable_setDisableYieldValue;
var rendererID = null;
var injectedHook = null;
var injectedProfilingHooks = null;
var hasLoggedError = false;
var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';
function injectInternals(internals) {
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
// No DevTools
return false;
}
var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
if (hook.isDisabled) {
// This isn't a real property on the hook, but it can be set to opt out
// of DevTools integration and associated warnings and logs.
// https://github.com/facebook/react/issues/3877
return true;
}
if (!hook.supportsFiber) {
{
error('The installed version of React DevTools is too old and will not work ' + 'with the current version of React. Please update React DevTools. ' + 'https://reactjs.org/link/react-devtools');
} // DevTools exists, even though it doesn't support Fiber.
return true;
}
try {
if (enableSchedulingProfiler) {
// Conditionally inject these hooks only if Timeline profiler is supported by this build.
// This gives DevTools a way to feature detect that isn't tied to version number
// (since profiling and timeline are controlled by different feature flags).
internals = assign({}, internals, {
getLaneLabelMap: getLaneLabelMap,
injectProfilingHooks: injectProfilingHooks
});
}
rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks.
injectedHook = hook;
} catch (err) {
// Catch all errors because it is unsafe to throw during initialization.
{
error('React instrumentation encountered an error: %s.', err);
}
}
if (hook.checkDCE) {
// This is the real DevTools.
return true;
} else {
// This is likely a hook installed by Fast Refresh runtime.
return false;
}
}
function onScheduleRoot(root, children) {
{
if (injectedHook && typeof injectedHook.onScheduleFiberRoot === 'function') {
try {
injectedHook.onScheduleFiberRoot(rendererID, root, children);
} catch (err) {
if ( !hasLoggedError) {
hasLoggedError = true;
error('React instrumentation encountered an error: %s', err);
}
}
}
}
}
function onCommitRoot(root, eventPriority) {
if (injectedHook && typeof injectedHook.onCommitFiberRoot === 'function') {
try {
var didError = (root.current.flags & DidCapture) === DidCapture;
if (enableProfilerTimer) {
var schedulerPriority;
switch (eventPriority) {
case DiscreteEventPriority:
schedulerPriority = ImmediatePriority;
break;
case ContinuousEventPriority:
schedulerPriority = UserBlockingPriority;
break;
case DefaultEventPriority:
schedulerPriority = NormalPriority;
break;
case IdleEventPriority:
schedulerPriority = IdlePriority;
break;
default:
schedulerPriority = NormalPriority;
break;
}
injectedHook.onCommitFiberRoot(rendererID, root, schedulerPriority, didError);
} else {
injectedHook.onCommitFiberRoot(rendererID, root, undefined, didError);
}
} catch (err) {
{
if (!hasLoggedError) {
hasLoggedError = true;
error('React instrumentation encountered an error: %s', err);
}
}
}
}
}
function onPostCommitRoot(root) {
if (injectedHook && typeof injectedHook.onPostCommitFiberRoot === 'function') {
try {
injectedHook.onPostCommitFiberRoot(rendererID, root);
} catch (err) {
{
if (!hasLoggedError) {
hasLoggedError = true;
error('React instrumentation encountered an error: %s', err);
}
}
}
}
}
function onCommitUnmount(fiber) {
if (injectedHook && typeof injectedHook.onCommitFiberUnmount === 'function') {
try {
injectedHook.onCommitFiberUnmount(rendererID, fiber);
} catch (err) {
{
if (!hasLoggedError) {
hasLoggedError = true;
error('React instrumentation encountered an error: %s', err);
}
}
}
}
}
function setIsStrictModeForDevtools(newIsStrictMode) {
{
if (typeof unstable_yieldValue$1 === 'function') {
// We're in a test because Scheduler.unstable_yieldValue only exists
// in SchedulerMock. To reduce the noise in strict mode tests,
// suppress warnings and disable scheduler yielding during the double render
unstable_setDisableYieldValue$1(newIsStrictMode);
setSuppressWarning(newIsStrictMode);
}
if (injectedHook && typeof injectedHook.setStrictMode === 'function') {
try {
injectedHook.setStrictMode(rendererID, newIsStrictMode);
} catch (err) {
{
if (!hasLoggedError) {
hasLoggedError = true;
error('React instrumentation encountered an error: %s', err);
}
}
}
}
}
} // Profiler API hooks
function injectProfilingHooks(profilingHooks) {
injectedProfilingHooks = profilingHooks;
}
function getLaneLabelMap() {
{
var map = new Map();
var lane = 1;
for (var index = 0; index < TotalLanes; index++) {
var label = getLabelForLane(lane);
map.set(lane, label);
lane *= 2;
}
return map;
}
}
function markCommitStarted(lanes) {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStarted === 'function') {
injectedProfilingHooks.markCommitStarted(lanes);
}
}
}
function markCommitStopped() {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStopped === 'function') {
injectedProfilingHooks.markCommitStopped();
}
}
}
function markComponentRenderStarted(fiber) {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStarted === 'function') {
injectedProfilingHooks.markComponentRenderStarted(fiber);
}
}
}
function markComponentRenderStopped() {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStopped === 'function') {
injectedProfilingHooks.markComponentRenderStopped();
}
}
}
function markComponentPassiveEffectMountStarted(fiber) {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStarted === 'function') {
injectedProfilingHooks.markComponentPassiveEffectMountStarted(fiber);
}
}
}
function markComponentPassiveEffectMountStopped() {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStopped === 'function') {
injectedProfilingHooks.markComponentPassiveEffectMountStopped();
}
}
}
function markComponentPassiveEffectUnmountStarted(fiber) {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStarted === 'function') {
injectedProfilingHooks.markComponentPassiveEffectUnmountStarted(fiber);
}
}
}
function markComponentPassiveEffectUnmountStopped() {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStopped === 'function') {
injectedProfilingHooks.markComponentPassiveEffectUnmountStopped();
}
}
}
function markComponentLayoutEffectMountStarted(fiber) {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStarted === 'function') {
injectedProfilingHooks.markComponentLayoutEffectMountStarted(fiber);
}
}
}
function markComponentLayoutEffectMountStopped() {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStopped === 'function') {
injectedProfilingHooks.markComponentLayoutEffectMountStopped();
}
}
}
function markComponentLayoutEffectUnmountStarted(fiber) {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStarted === 'function') {
injectedProfilingHooks.markComponentLayoutEffectUnmountStarted(fiber);
}
}
}
function markComponentLayoutEffectUnmountStopped() {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStopped === 'function') {
injectedProfilingHooks.markComponentLayoutEffectUnmountStopped();
}
}
}
function markComponentErrored(fiber, thrownValue, lanes) {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentErrored === 'function') {
injectedProfilingHooks.markComponentErrored(fiber, thrownValue, lanes);
}
}
}
function markComponentSuspended(fiber, wakeable, lanes) {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentSuspended === 'function') {
injectedProfilingHooks.markComponentSuspended(fiber, wakeable, lanes);
}
}
}
function markLayoutEffectsStarted(lanes) {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStarted === 'function') {
injectedProfilingHooks.markLayoutEffectsStarted(lanes);
}
}
}
function markLayoutEffectsStopped() {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStopped === 'function') {
injectedProfilingHooks.markLayoutEffectsStopped();
}
}
}
function markPassiveEffectsStarted(lanes) {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStarted === 'function') {
injectedProfilingHooks.markPassiveEffectsStarted(lanes);
}
}
}
function markPassiveEffectsStopped() {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStopped === 'function') {
injectedProfilingHooks.markPassiveEffectsStopped();
}
}
}
function markRenderStarted(lanes) {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStarted === 'function') {
injectedProfilingHooks.markRenderStarted(lanes);
}
}
}
function markRenderYielded() {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderYielded === 'function') {
injectedProfilingHooks.markRenderYielded();
}
}
}
function markRenderStopped() {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStopped === 'function') {
injectedProfilingHooks.markRenderStopped();
}
}
}
function markRenderScheduled(lane) {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderScheduled === 'function') {
injectedProfilingHooks.markRenderScheduled(lane);
}
}
}
function markForceUpdateScheduled(fiber, lane) {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markForceUpdateScheduled === 'function') {
injectedProfilingHooks.markForceUpdateScheduled(fiber, lane);
}
}
}
function markStateUpdateScheduled(fiber, lane) {
{
if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markStateUpdateScheduled === 'function') {
injectedProfilingHooks.markStateUpdateScheduled(fiber, lane);
}
}
}
var NoMode =
/* */
0; // TODO: Remove ConcurrentMode by reading from the root tag instead
var ConcurrentMode =
/* */
1;
var ProfileMode =
/* */
2;
var StrictLegacyMode =
/* */
8;
var StrictEffectsMode =
/* */
16;
// TODO: This is pretty well supported by browsers. Maybe we can drop it.
var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros.
// Based on:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32
var log = Math.log;
var LN2 = Math.LN2;
function clz32Fallback(x) {
var asUint = x >>> 0;
if (asUint === 0) {
return 32;
}
return 31 - (log(asUint) / LN2 | 0) | 0;
}
// If those values are changed that package should be rebuilt and redeployed.
var TotalLanes = 31;
var NoLanes =
/* */
0;
var NoLane =
/* */
0;
var SyncLane =
/* */
1;
var InputContinuousHydrationLane =
/* */
2;
var InputContinuousLane =
/* */
4;
var DefaultHydrationLane =
/* */
8;
var DefaultLane =
/* */
16;
var TransitionHydrationLane =
/* */
32;
var TransitionLanes =
/* */
4194240;
var TransitionLane1 =
/* */
64;
var TransitionLane2 =
/* */
128;
var TransitionLane3 =
/* */
256;
var TransitionLane4 =
/* */
512;
var TransitionLane5 =
/* */
1024;
var TransitionLane6 =
/* */
2048;
var TransitionLane7 =
/* */
4096;
var TransitionLane8 =
/* */
8192;
var TransitionLane9 =
/* */
16384;
var TransitionLane10 =
/* */
32768;
var TransitionLane11 =
/* */
65536;
var TransitionLane12 =
/* */
131072;
var TransitionLane13 =
/* */
262144;
var TransitionLane14 =
/* */
524288;
var TransitionLane15 =
/* */
1048576;
var TransitionLane16 =
/* */
2097152;
var RetryLanes =
/* */
130023424;
var RetryLane1 =
/* */
4194304;
var RetryLane2 =
/* */
8388608;
var RetryLane3 =
/* */
16777216;
var RetryLane4 =
/* */
33554432;
var RetryLane5 =
/* */
67108864;
var SomeRetryLane = RetryLane1;
var SelectiveHydrationLane =
/* */
134217728;
var NonIdleLanes =
/* */
268435455;
var IdleHydrationLane =
/* */
268435456;
var IdleLane =
/* */
536870912;
var OffscreenLane =
/* */
1073741824; // This function is used for the experimental timeline (react-devtools-timeline)
// It should be kept in sync with the Lanes values above.
function getLabelForLane(lane) {
{
if (lane & SyncLane) {
return 'Sync';
}
if (lane & InputContinuousHydrationLane) {
return 'InputContinuousHydration';
}
if (lane & InputContinuousLane) {
return 'InputContinuous';
}
if (lane & DefaultHydrationLane) {
return 'DefaultHydration';
}
if (lane & DefaultLane) {
return 'Default';
}
if (lane & TransitionHydrationLane) {
return 'TransitionHydration';
}
if (lane & TransitionLanes) {
return 'Transition';
}
if (lane & RetryLanes) {
return 'Retry';
}
if (lane & SelectiveHydrationLane) {
return 'SelectiveHydration';
}
if (lane & IdleHydrationLane) {
return 'IdleHydration';
}
if (lane & IdleLane) {
return 'Idle';
}
if (lane & OffscreenLane) {
return 'Offscreen';
}
}
}
var NoTimestamp = -1;
var nextTransitionLane = TransitionLane1;
var nextRetryLane = RetryLane1;
function getHighestPriorityLanes(lanes) {
switch (getHighestPriorityLane(lanes)) {
case SyncLane:
return SyncLane;
case InputContinuousHydrationLane:
return InputContinuousHydrationLane;
case InputContinuousLane:
return InputContinuousLane;
case DefaultHydrationLane:
return DefaultHydrationLane;
case DefaultLane:
return DefaultLane;
case TransitionHydrationLane:
return TransitionHydrationLane;
case TransitionLane1:
case TransitionLane2:
case TransitionLane3:
case TransitionLane4:
case TransitionLane5:
case TransitionLane6:
case TransitionLane7:
case TransitionLane8:
case TransitionLane9:
case TransitionLane10:
case TransitionLane11:
case TransitionLane12:
case TransitionLane13:
case TransitionLane14:
case TransitionLane15:
case TransitionLane16:
return lanes & TransitionLanes;
case RetryLane1:
case RetryLane2:
case RetryLane3:
case RetryLane4:
case RetryLane5:
return lanes & RetryLanes;
case SelectiveHydrationLane:
return SelectiveHydrationLane;
case IdleHydrationLane:
return IdleHydrationLane;
case IdleLane:
return IdleLane;
case OffscreenLane:
return OffscreenLane;
default:
{
error('Should have found matching lanes. This is a bug in React.');
} // This shouldn't be reachable, but as a fallback, return the entire bitmask.
return lanes;
}
}
function getNextLanes(root, wipLanes) {
// Early bailout if there's no pending work left.
var pendingLanes = root.pendingLanes;
if (pendingLanes === NoLanes) {
return NoLanes;
}
var nextLanes = NoLanes;
var suspendedLanes = root.suspendedLanes;
var pingedLanes = root.pingedLanes; // Do not work on any idle work until all the non-idle work has finished,
// even if the work is suspended.
var nonIdlePendingLanes = pendingLanes & NonIdleLanes;
if (nonIdlePendingLanes !== NoLanes) {
var nonIdleUnblockedLanes = nonIdlePendingLanes & ~suspendedLanes;
if (nonIdleUnblockedLanes !== NoLanes) {
nextLanes = getHighestPriorityLanes(nonIdleUnblockedLanes);
} else {
var nonIdlePingedLanes = nonIdlePendingLanes & pingedLanes;
if (nonIdlePingedLanes !== NoLanes) {
nextLanes = getHighestPriorityLanes(nonIdlePingedLanes);
}
}
} else {
// The only remaining work is Idle.
var unblockedLanes = pendingLanes & ~suspendedLanes;
if (unblockedLanes !== NoLanes) {
nextLanes = getHighestPriorityLanes(unblockedLanes);
} else {
if (pingedLanes !== NoLanes) {
nextLanes = getHighestPriorityLanes(pingedLanes);
}
}
}
if (nextLanes === NoLanes) {
// This should only be reachable if we're suspended
// TODO: Consider warning in this path if a fallback timer is not scheduled.
return NoLanes;
} // If we're already in the middle of a render, switching lanes will interrupt
// it and we'll lose our progress. We should only do this if the new lanes are
// higher priority.
if (wipLanes !== NoLanes && wipLanes !== nextLanes && // If we already suspended with a delay, then interrupting is fine. Don't
// bother waiting until the root is complete.
(wipLanes & suspendedLanes) === NoLanes) {
var nextLane = getHighestPriorityLane(nextLanes);
var wipLane = getHighestPriorityLane(wipLanes);
if ( // Tests whether the next lane is equal or lower priority than the wip
// one. This works because the bits decrease in priority as you go left.
nextLane >= wipLane || // Default priority updates should not interrupt transition updates. The
// only difference between default updates and transition updates is that
// default updates do not support refresh transitions.
nextLane === DefaultLane && (wipLane & TransitionLanes) !== NoLanes) {
// Keep working on the existing in-progress tree. Do not interrupt.
return wipLanes;
}
}
if ((nextLanes & InputContinuousLane) !== NoLanes) {
// When updates are sync by default, we entangle continuous priority updates
// and default updates, so they render in the same batch. The only reason
// they use separate lanes is because continuous updates should interrupt
// transitions, but default updates should not.
nextLanes |= pendingLanes & DefaultLane;
} // Check for entangled lanes and add them to the batch.
//
// A lane is said to be entangled with another when it's not allowed to render
// in a batch that does not also include the other lane. Typically we do this
// when multiple updates have the same source, and we only want to respond to
// the most recent event from that source.
//
// Note that we apply entanglements *after* checking for partial work above.
// This means that if a lane is entangled during an interleaved event while
// it's already rendering, we won't interrupt it. This is intentional, since
// entanglement is usually "best effort": we'll try our best to render the
// lanes in the same batch, but it's not worth throwing out partially
// completed work in order to do it.
// TODO: Reconsider this. The counter-argument is that the partial work
// represents an intermediate state, which we don't want to show to the user.
// And by spending extra time finishing it, we're increasing the amount of
// time it takes to show the final state, which is what they are actually
// waiting for.
//
// For those exceptions where entanglement is semantically important, like
// useMutableSource, we should ensure that there is no partial work at the
// time we apply the entanglement.
var entangledLanes = root.entangledLanes;
if (entangledLanes !== NoLanes) {
var entanglements = root.entanglements;
var lanes = nextLanes & entangledLanes;
while (lanes > 0) {
var index = pickArbitraryLaneIndex(lanes);
var lane = 1 << index;
nextLanes |= entanglements[index];
lanes &= ~lane;
}
}
return nextLanes;
}
function getMostRecentEventTime(root, lanes) {
var eventTimes = root.eventTimes;
var mostRecentEventTime = NoTimestamp;
while (lanes > 0) {
var index = pickArbitraryLaneIndex(lanes);
var lane = 1 << index;
var eventTime = eventTimes[index];
if (eventTime > mostRecentEventTime) {
mostRecentEventTime = eventTime;
}
lanes &= ~lane;
}
return mostRecentEventTime;
}
function computeExpirationTime(lane, currentTime) {
switch (lane) {
case SyncLane:
case InputContinuousHydrationLane:
case InputContinuousLane:
// User interactions should expire slightly more quickly.
//
// NOTE: This is set to the corresponding constant as in Scheduler.js.
// When we made it larger, a product metric in www regressed, suggesting
// there's a user interaction that's being starved by a series of
// synchronous updates. If that theory is correct, the proper solution is
// to fix the starvation. However, this scenario supports the idea that
// expiration times are an important safeguard when starvation
// does happen.
return currentTime + 250;
case DefaultHydrationLane:
case DefaultLane:
case TransitionHydrationLane:
case TransitionLane1:
case TransitionLane2:
case TransitionLane3:
case TransitionLane4:
case TransitionLane5:
case TransitionLane6:
case TransitionLane7:
case TransitionLane8:
case TransitionLane9:
case TransitionLane10:
case TransitionLane11:
case TransitionLane12:
case TransitionLane13:
case TransitionLane14:
case TransitionLane15:
case TransitionLane16:
return currentTime + 5000;
case RetryLane1:
case RetryLane2:
case RetryLane3:
case RetryLane4:
case RetryLane5:
// TODO: Retries should be allowed to expire if they are CPU bound for
// too long, but when I made this change it caused a spike in browser
// crashes. There must be some other underlying bug; not super urgent but
// ideally should figure out why and fix it. Unfortunately we don't have
// a repro for the crashes, only detected via production metrics.
return NoTimestamp;
case SelectiveHydrationLane:
case IdleHydrationLane:
case IdleLane:
case OffscreenLane:
// Anything idle priority or lower should never expire.
return NoTimestamp;
default:
{
error('Should have found matching lanes. This is a bug in React.');
}
return NoTimestamp;
}
}
function markStarvedLanesAsExpired(root, currentTime) {
// TODO: This gets called every time we yield. We can optimize by storing
// the earliest expiration time on the root. Then use that to quickly bail out
// of this function.
var pendingLanes = root.pendingLanes;
var suspendedLanes = root.suspendedLanes;
var pingedLanes = root.pingedLanes;
var expirationTimes = root.expirationTimes; // Iterate through the pending lanes and check if we've reached their
// expiration time. If so, we'll assume the update is being starved and mark
// it as expired to force it to finish.
var lanes = pendingLanes;
while (lanes > 0) {
var index = pickArbitraryLaneIndex(lanes);
var lane = 1 << index;
var expirationTime = expirationTimes[index];
if (expirationTime === NoTimestamp) {
// Found a pending lane with no expiration time. If it's not suspended, or
// if it's pinged, assume it's CPU-bound. Compute a new expiration time
// using the current time.
if ((lane & suspendedLanes) === NoLanes || (lane & pingedLanes) !== NoLanes) {
// Assumes timestamps are monotonically increasing.
expirationTimes[index] = computeExpirationTime(lane, currentTime);
}
} else if (expirationTime <= currentTime) {
// This lane expired
root.expiredLanes |= lane;
}
lanes &= ~lane;
}
} // This returns the highest priority pending lanes regardless of whether they
// are suspended.
function getHighestPriorityPendingLanes(root) {
return getHighestPriorityLanes(root.pendingLanes);
}
function getLanesToRetrySynchronouslyOnError(root) {
var everythingButOffscreen = root.pendingLanes & ~OffscreenLane;
if (everythingButOffscreen !== NoLanes) {
return everythingButOffscreen;
}
if (everythingButOffscreen & OffscreenLane) {
return OffscreenLane;
}
return NoLanes;
}
function includesSyncLane(lanes) {
return (lanes & SyncLane) !== NoLanes;
}
function includesNonIdleWork(lanes) {
return (lanes & NonIdleLanes) !== NoLanes;
}
function includesOnlyRetries(lanes) {
return (lanes & RetryLanes) === lanes;
}
function includesOnlyNonUrgentLanes(lanes) {
var UrgentLanes = SyncLane | InputContinuousLane | DefaultLane;
return (lanes & UrgentLanes) === NoLanes;
}
function includesOnlyTransitions(lanes) {
return (lanes & TransitionLanes) === lanes;
}
function includesBlockingLane(root, lanes) {
var SyncDefaultLanes = InputContinuousHydrationLane | InputContinuousLane | DefaultHydrationLane | DefaultLane;
return (lanes & SyncDefaultLanes) !== NoLanes;
}
function includesExpiredLane(root, lanes) {
// This is a separate check from includesBlockingLane because a lane can
// expire after a render has already started.
return (lanes & root.expiredLanes) !== NoLanes;
}
function isTransitionLane(lane) {
return (lane & TransitionLanes) !== NoLanes;
}
function claimNextTransitionLane() {
// Cycle through the lanes, assigning each new transition to the next lane.
// In most cases, this means every transition gets its own lane, until we
// run out of lanes and cycle back to the beginning.
var lane = nextTransitionLane;
nextTransitionLane <<= 1;
if ((nextTransitionLane & TransitionLanes) === NoLanes) {
nextTransitionLane = TransitionLane1;
}
return lane;
}
function claimNextRetryLane() {
var lane = nextRetryLane;
nextRetryLane <<= 1;
if ((nextRetryLane & RetryLanes) === NoLanes) {
nextRetryLane = RetryLane1;
}
return lane;
}
function getHighestPriorityLane(lanes) {
return lanes & -lanes;
}
function pickArbitraryLane(lanes) {
// This wrapper function gets inlined. Only exists so to communicate that it
// doesn't matter which bit is selected; you can pick any bit without
// affecting the algorithms where its used. Here I'm using
// getHighestPriorityLane because it requires the fewest operations.
return getHighestPriorityLane(lanes);
}
function pickArbitraryLaneIndex(lanes) {
return 31 - clz32(lanes);
}
function laneToIndex(lane) {
return pickArbitraryLaneIndex(lane);
}
function includesSomeLane(a, b) {
return (a & b) !== NoLanes;
}
function isSubsetOfLanes(set, subset) {
return (set & subset) === subset;
}
function mergeLanes(a, b) {
return a | b;
}
function removeLanes(set, subset) {
return set & ~subset;
}
function intersectLanes(a, b) {
return a & b;
} // Seems redundant, but it changes the type from a single lane (used for
// updates) to a group of lanes (used for flushing work).
function laneToLanes(lane) {
return lane;
}
function higherPriorityLane(a, b) {
// This works because the bit ranges decrease in priority as you go left.
return a !== NoLane && a < b ? a : b;
}
function createLaneMap(initial) {
// Intentionally pushing one by one.
// https://v8.dev/blog/elements-kinds#avoid-creating-holes
var laneMap = [];
for (var i = 0; i < TotalLanes; i++) {
laneMap.push(initial);
}
return laneMap;
}
function markRootUpdated(root, updateLane, eventTime) {
root.pendingLanes |= updateLane; // If there are any suspended transitions, it's possible this new update
// could unblock them. Clear the suspended lanes so that we can try rendering
// them again.
//
// TODO: We really only need to unsuspend only lanes that are in the
// `subtreeLanes` of the updated fiber, or the update lanes of the return
// path. This would exclude suspended updates in an unrelated sibling tree,
// since there's no way for this update to unblock it.
//
// We don't do this if the incoming update is idle, because we never process
// idle updates until after all the regular updates have finished; there's no
// way it could unblock a transition.
if (updateLane !== IdleLane) {
root.suspendedLanes = NoLanes;
root.pingedLanes = NoLanes;
}
var eventTimes = root.eventTimes;
var index = laneToIndex(updateLane); // We can always overwrite an existing timestamp because we prefer the most
// recent event, and we assume time is monotonically increasing.
eventTimes[index] = eventTime;
}
function markRootSuspended(root, suspendedLanes) {
root.suspendedLanes |= suspendedLanes;
root.pingedLanes &= ~suspendedLanes; // The suspended lanes are no longer CPU-bound. Clear their expiration times.
var expirationTimes = root.expirationTimes;
var lanes = suspendedLanes;
while (lanes > 0) {
var index = pickArbitraryLaneIndex(lanes);
var lane = 1 << index;
expirationTimes[index] = NoTimestamp;
lanes &= ~lane;
}
}
function markRootPinged(root, pingedLanes, eventTime) {
root.pingedLanes |= root.suspendedLanes & pingedLanes;
}
function markRootFinished(root, remainingLanes) {
var noLongerPendingLanes = root.pendingLanes & ~remainingLanes;
root.pendingLanes = remainingLanes; // Let's try everything again
root.suspendedLanes = NoLanes;
root.pingedLanes = NoLanes;
root.expiredLanes &= remainingLanes;
root.mutableReadLanes &= remainingLanes;
root.entangledLanes &= remainingLanes;
var entanglements = root.entanglements;
var eventTimes = root.eventTimes;
var expirationTimes = root.expirationTimes; // Clear the lanes that no longer have pending work
var lanes = noLongerPendingLanes;
while (lanes > 0) {
var index = pickArbitraryLaneIndex(lanes);
var lane = 1 << index;
entanglements[index] = NoLanes;
eventTimes[index] = NoTimestamp;
expirationTimes[index] = NoTimestamp;
lanes &= ~lane;
}
}
function markRootEntangled(root, entangledLanes) {
// In addition to entangling each of the given lanes with each other, we also
// have to consider _transitive_ entanglements. For each lane that is already
// entangled with *any* of the given lanes, that lane is now transitively
// entangled with *all* the given lanes.
//
// Translated: If C is entangled with A, then entangling A with B also
// entangles C with B.
//
// If this is hard to grasp, it might help to intentionally break this
// function and look at the tests that fail in ReactTransition-test.js. Try
// commenting out one of the conditions below.
var rootEntangledLanes = root.entangledLanes |= entangledLanes;
var entanglements = root.entanglements;
var lanes = rootEntangledLanes;
while (lanes) {
var index = pickArbitraryLaneIndex(lanes);
var lane = 1 << index;
if ( // Is this one of the newly entangled lanes?
lane & entangledLanes | // Is this lane transitively entangled with the newly entangled lanes?
entanglements[index] & entangledLanes) {
entanglements[index] |= entangledLanes;
}
lanes &= ~lane;
}
}
function getBumpedLaneForHydration(root, renderLanes) {
var renderLane = getHighestPriorityLane(renderLanes);
var lane;
switch (renderLane) {
case InputContinuousLane:
lane = InputContinuousHydrationLane;
break;
case DefaultLane:
lane = DefaultHydrationLane;
break;
case TransitionLane1:
case TransitionLane2:
case TransitionLane3:
case TransitionLane4:
case TransitionLane5:
case TransitionLane6:
case TransitionLane7:
case TransitionLane8:
case TransitionLane9:
case TransitionLane10:
case TransitionLane11:
case TransitionLane12:
case TransitionLane13:
case TransitionLane14:
case TransitionLane15:
case TransitionLane16:
case RetryLane1:
case RetryLane2:
case RetryLane3:
case RetryLane4:
case RetryLane5:
lane = TransitionHydrationLane;
break;
case IdleLane:
lane = IdleHydrationLane;
break;
default:
// Everything else is already either a hydration lane, or shouldn't
// be retried at a hydration lane.
lane = NoLane;
break;
} // Check if the lane we chose is suspended. If so, that indicates that we
// already attempted and failed to hydrate at that level. Also check if we're
// already rendering that lane, which is rare but could happen.
if ((lane & (root.suspendedLanes | renderLanes)) !== NoLane) {
// Give up trying to hydrate and fall back to client render.
return NoLane;
}
return lane;
}
function addFiberToLanesMap(root, fiber, lanes) {
if (!isDevToolsPresent) {
return;
}
var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap;
while (lanes > 0) {
var index = laneToIndex(lanes);
var lane = 1 << index;
var updaters = pendingUpdatersLaneMap[index];
updaters.add(fiber);
lanes &= ~lane;
}
}
function movePendingFibersToMemoized(root, lanes) {
if (!isDevToolsPresent) {
return;
}
var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap;
var memoizedUpdaters = root.memoizedUpdaters;
while (lanes > 0) {
var index = laneToIndex(lanes);
var lane = 1 << index;
var updaters = pendingUpdatersLaneMap[index];
if (updaters.size > 0) {
updaters.forEach(function (fiber) {
var alternate = fiber.alternate;
if (alternate === null || !memoizedUpdaters.has(alternate)) {
memoizedUpdaters.add(fiber);
}
});
updaters.clear();
}
lanes &= ~lane;
}
}
function getTransitionsForLanes(root, lanes) {
{
return null;
}
}
var DiscreteEventPriority = SyncLane;
var ContinuousEventPriority = InputContinuousLane;
var DefaultEventPriority = DefaultLane;
var IdleEventPriority = IdleLane;
var currentUpdatePriority = NoLane;
function getCurrentUpdatePriority() {
return currentUpdatePriority;
}
function setCurrentUpdatePriority(newPriority) {
currentUpdatePriority = newPriority;
}
function runWithPriority(priority, fn) {
var previousPriority = currentUpdatePriority;
try {
currentUpdatePriority = priority;
return fn();
} finally {
currentUpdatePriority = previousPriority;
}
}
function higherEventPriority(a, b) {
return a !== 0 && a < b ? a : b;
}
function lowerEventPriority(a, b) {
return a === 0 || a > b ? a : b;
}
function isHigherEventPriority(a, b) {
return a !== 0 && a < b;
}
function lanesToEventPriority(lanes) {
var lane = getHighestPriorityLane(lanes);
if (!isHigherEventPriority(DiscreteEventPriority, lane)) {
return DiscreteEventPriority;
}
if (!isHigherEventPriority(ContinuousEventPriority, lane)) {
return ContinuousEventPriority;
}
if (includesNonIdleWork(lane)) {
return DefaultEventPriority;
}
return IdleEventPriority;
}
// This is imported by the event replaying implementation in React DOM. It's
// in a separate file to break a circular dependency between the renderer and
// the reconciler.
function isRootDehydrated(root) {
var currentState = root.current.memoizedState;
return currentState.isDehydrated;
}
var _attemptSynchronousHydration;
function setAttemptSynchronousHydration(fn) {
_attemptSynchronousHydration = fn;
}
function attemptSynchronousHydration(fiber) {
_attemptSynchronousHydration(fiber);
}
var attemptContinuousHydration;
function setAttemptContinuousHydration(fn) {
attemptContinuousHydration = fn;
}
var attemptHydrationAtCurrentPriority;
function setAttemptHydrationAtCurrentPriority(fn) {
attemptHydrationAtCurrentPriority = fn;
}
var getCurrentUpdatePriority$1;
function setGetCurrentUpdatePriority(fn) {
getCurrentUpdatePriority$1 = fn;
}
var attemptHydrationAtPriority;
function setAttemptHydrationAtPriority(fn) {
attemptHydrationAtPriority = fn;
} // TODO: Upgrade this definition once we're on a newer version of Flow that
// has this definition built-in.
var hasScheduledReplayAttempt = false; // The queue of discrete events to be replayed.
var queuedDiscreteEvents = []; // Indicates if any continuous event targets are non-null for early bailout.
// if the last target was dehydrated.
var queuedFocus = null;
var queuedDrag = null;
var queuedMouse = null; // For pointer events there can be one latest event per pointerId.
var queuedPointers = new Map();
var queuedPointerCaptures = new Map(); // We could consider replaying selectionchange and touchmoves too.
var queuedExplicitHydrationTargets = [];
var discreteReplayableEvents = ['mousedown', 'mouseup', 'touchcancel', 'touchend', 'touchstart', 'auxclick', 'dblclick', 'pointercancel', 'pointerdown', 'pointerup', 'dragend', 'dragstart', 'drop', 'compositionend', 'compositionstart', 'keydown', 'keypress', 'keyup', 'input', 'textInput', // Intentionally camelCase
'copy', 'cut', 'paste', 'click', 'change', 'contextmenu', 'reset', 'submit'];
function isDiscreteEventThatRequiresHydration(eventType) {
return discreteReplayableEvents.indexOf(eventType) > -1;
}
function createQueuedReplayableEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
return {
blockedOn: blockedOn,
domEventName: domEventName,
eventSystemFlags: eventSystemFlags,
nativeEvent: nativeEvent,
targetContainers: [targetContainer]
};
}
function clearIfContinuousEvent(domEventName, nativeEvent) {
switch (domEventName) {
case 'focusin':
case 'focusout':
queuedFocus = null;
break;
case 'dragenter':
case 'dragleave':
queuedDrag = null;
break;
case 'mouseover':
case 'mouseout':
queuedMouse = null;
break;
case 'pointerover':
case 'pointerout':
{
var pointerId = nativeEvent.pointerId;
queuedPointers.delete(pointerId);
break;
}
case 'gotpointercapture':
case 'lostpointercapture':
{
var _pointerId = nativeEvent.pointerId;
queuedPointerCaptures.delete(_pointerId);
break;
}
}
}
function accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent, blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
if (existingQueuedEvent === null || existingQueuedEvent.nativeEvent !== nativeEvent) {
var queuedEvent = createQueuedReplayableEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent);
if (blockedOn !== null) {
var _fiber2 = getInstanceFromNode(blockedOn);
if (_fiber2 !== null) {
// Attempt to increase the priority of this target.
attemptContinuousHydration(_fiber2);
}
}
return queuedEvent;
} // If we have already queued this exact event, then it's because
// the different event systems have different DOM event listeners.
// We can accumulate the flags, and the targetContainers, and
// store a single event to be replayed.
existingQueuedEvent.eventSystemFlags |= eventSystemFlags;
var targetContainers = existingQueuedEvent.targetContainers;
if (targetContainer !== null && targetContainers.indexOf(targetContainer) === -1) {
targetContainers.push(targetContainer);
}
return existingQueuedEvent;
}
function queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
// These set relatedTarget to null because the replayed event will be treated as if we
// moved from outside the window (no target) onto the target once it hydrates.
// Instead of mutating we could clone the event.
switch (domEventName) {
case 'focusin':
{
var focusEvent = nativeEvent;
queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(queuedFocus, blockedOn, domEventName, eventSystemFlags, targetContainer, focusEvent);
return true;
}
case 'dragenter':
{
var dragEvent = nativeEvent;
queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(queuedDrag, blockedOn, domEventName, eventSystemFlags, targetContainer, dragEvent);
return true;
}
case 'mouseover':
{
var mouseEvent = nativeEvent;
queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(queuedMouse, blockedOn, domEventName, eventSystemFlags, targetContainer, mouseEvent);
return true;
}
case 'pointerover':
{
var pointerEvent = nativeEvent;
var pointerId = pointerEvent.pointerId;
queuedPointers.set(pointerId, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointers.get(pointerId) || null, blockedOn, domEventName, eventSystemFlags, targetContainer, pointerEvent));
return true;
}
case 'gotpointercapture':
{
var _pointerEvent = nativeEvent;
var _pointerId2 = _pointerEvent.pointerId;
queuedPointerCaptures.set(_pointerId2, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointerCaptures.get(_pointerId2) || null, blockedOn, domEventName, eventSystemFlags, targetContainer, _pointerEvent));
return true;
}
}
return false;
} // Check if this target is unblocked. Returns true if it's unblocked.
function attemptExplicitHydrationTarget(queuedTarget) {
// TODO: This function shares a lot of logic with findInstanceBlockingEvent.
// Try to unify them. It's a bit tricky since it would require two return
// values.
var targetInst = getClosestInstanceFromNode(queuedTarget.target);
if (targetInst !== null) {
var nearestMounted = getNearestMountedFiber(targetInst);
if (nearestMounted !== null) {
var tag = nearestMounted.tag;
if (tag === SuspenseComponent) {
var instance = getSuspenseInstanceFromFiber(nearestMounted);
if (instance !== null) {
// We're blocked on hydrating this boundary.
// Increase its priority.
queuedTarget.blockedOn = instance;
attemptHydrationAtPriority(queuedTarget.priority, function () {
attemptHydrationAtCurrentPriority(nearestMounted);
});
return;
}
} else if (tag === HostRoot) {
var root = nearestMounted.stateNode;
if (isRootDehydrated(root)) {
queuedTarget.blockedOn = getContainerFromFiber(nearestMounted); // We don't currently have a way to increase the priority of
// a root other than sync.
return;
}
}
}
}
queuedTarget.blockedOn = null;
}
function queueExplicitHydrationTarget(target) {
// TODO: This will read the priority if it's dispatched by the React
// event system but not native events. Should read window.event.type, like
// we do for updates (getCurrentEventPriority).
var updatePriority = getCurrentUpdatePriority$1();
var queuedTarget = {
blockedOn: null,
target: target,
priority: updatePriority
};
var i = 0;
for (; i < queuedExplicitHydrationTargets.length; i++) {
// Stop once we hit the first target with lower priority than
if (!isHigherEventPriority(updatePriority, queuedExplicitHydrationTargets[i].priority)) {
break;
}
}
queuedExplicitHydrationTargets.splice(i, 0, queuedTarget);
if (i === 0) {
attemptExplicitHydrationTarget(queuedTarget);
}
}
function attemptReplayContinuousQueuedEvent(queuedEvent) {
if (queuedEvent.blockedOn !== null) {
return false;
}
var targetContainers = queuedEvent.targetContainers;
while (targetContainers.length > 0) {
var targetContainer = targetContainers[0];
var nextBlockedOn = findInstanceBlockingEvent(queuedEvent.domEventName, queuedEvent.eventSystemFlags, targetContainer, queuedEvent.nativeEvent);
if (nextBlockedOn === null) {
{
var nativeEvent = queuedEvent.nativeEvent;
var nativeEventClone = new nativeEvent.constructor(nativeEvent.type, nativeEvent);
setReplayingEvent(nativeEventClone);
nativeEvent.target.dispatchEvent(nativeEventClone);
resetReplayingEvent();
}
} else {
// We're still blocked. Try again later.
var _fiber3 = getInstanceFromNode(nextBlockedOn);
if (_fiber3 !== null) {
attemptContinuousHydration(_fiber3);
}
queuedEvent.blockedOn = nextBlockedOn;
return false;
} // This target container was successfully dispatched. Try the next.
targetContainers.shift();
}
return true;
}
function attemptReplayContinuousQueuedEventInMap(queuedEvent, key, map) {
if (attemptReplayContinuousQueuedEvent(queuedEvent)) {
map.delete(key);
}
}
function replayUnblockedEvents() {
hasScheduledReplayAttempt = false;
if (queuedFocus !== null && attemptReplayContinuousQueuedEvent(queuedFocus)) {
queuedFocus = null;
}
if (queuedDrag !== null && attemptReplayContinuousQueuedEvent(queuedDrag)) {
queuedDrag = null;
}
if (queuedMouse !== null && attemptReplayContinuousQueuedEvent(queuedMouse)) {
queuedMouse = null;
}
queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap);
queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap);
}
function scheduleCallbackIfUnblocked(queuedEvent, unblocked) {
if (queuedEvent.blockedOn === unblocked) {
queuedEvent.blockedOn = null;
if (!hasScheduledReplayAttempt) {
hasScheduledReplayAttempt = true; // Schedule a callback to attempt replaying as many events as are
// now unblocked. This first might not actually be unblocked yet.
// We could check it early to avoid scheduling an unnecessary callback.
unstable_scheduleCallback(unstable_NormalPriority, replayUnblockedEvents);
}
}
}
function retryIfBlockedOn(unblocked) {
// Mark anything that was blocked on this as no longer blocked
// and eligible for a replay.
if (queuedDiscreteEvents.length > 0) {
scheduleCallbackIfUnblocked(queuedDiscreteEvents[0], unblocked); // This is a exponential search for each boundary that commits. I think it's
// worth it because we expect very few discrete events to queue up and once
// we are actually fully unblocked it will be fast to replay them.
for (var i = 1; i < queuedDiscreteEvents.length; i++) {
var queuedEvent = queuedDiscreteEvents[i];
if (queuedEvent.blockedOn === unblocked) {
queuedEvent.blockedOn = null;
}
}
}
if (queuedFocus !== null) {
scheduleCallbackIfUnblocked(queuedFocus, unblocked);
}
if (queuedDrag !== null) {
scheduleCallbackIfUnblocked(queuedDrag, unblocked);
}
if (queuedMouse !== null) {
scheduleCallbackIfUnblocked(queuedMouse, unblocked);
}
var unblock = function (queuedEvent) {
return scheduleCallbackIfUnblocked(queuedEvent, unblocked);
};
queuedPointers.forEach(unblock);
queuedPointerCaptures.forEach(unblock);
for (var _i = 0; _i < queuedExplicitHydrationTargets.length; _i++) {
var queuedTarget = queuedExplicitHydrationTargets[_i];
if (queuedTarget.blockedOn === unblocked) {
queuedTarget.blockedOn = null;
}
}
while (queuedExplicitHydrationTargets.length > 0) {
var nextExplicitTarget = queuedExplicitHydrationTargets[0];
if (nextExplicitTarget.blockedOn !== null) {
// We're still blocked.
break;
} else {
attemptExplicitHydrationTarget(nextExplicitTarget);
if (nextExplicitTarget.blockedOn === null) {
// We're unblocked.
queuedExplicitHydrationTargets.shift();
}
}
}
}
var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig; // TODO: can we stop exporting these?
var _enabled = true; // This is exported in FB builds for use by legacy FB layer infra.
// We'd like to remove this but it's not clear if this is safe.
function setEnabled(enabled) {
_enabled = !!enabled;
}
function isEnabled() {
return _enabled;
}
function createEventListenerWrapperWithPriority(targetContainer, domEventName, eventSystemFlags) {
var eventPriority = getEventPriority(domEventName);
var listenerWrapper;
switch (eventPriority) {
case DiscreteEventPriority:
listenerWrapper = dispatchDiscreteEvent;
break;
case ContinuousEventPriority:
listenerWrapper = dispatchContinuousEvent;
break;
case DefaultEventPriority:
default:
listenerWrapper = dispatchEvent;
break;
}
return listenerWrapper.bind(null, domEventName, eventSystemFlags, targetContainer);
}
function dispatchDiscreteEvent(domEventName, eventSystemFlags, container, nativeEvent) {
var previousPriority = getCurrentUpdatePriority();
var prevTransition = ReactCurrentBatchConfig.transition;
ReactCurrentBatchConfig.transition = null;
try {
setCurrentUpdatePriority(DiscreteEventPriority);
dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent);
} finally {
setCurrentUpdatePriority(previousPriority);
ReactCurrentBatchConfig.transition = prevTransition;
}
}
function dispatchContinuousEvent(domEventName, eventSystemFlags, container, nativeEvent) {
var previousPriority = getCurrentUpdatePriority();
var prevTransition = ReactCurrentBatchConfig.transition;
ReactCurrentBatchConfig.transition = null;
try {
setCurrentUpdatePriority(ContinuousEventPriority);
dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent);
} finally {
setCurrentUpdatePriority(previousPriority);
ReactCurrentBatchConfig.transition = prevTransition;
}
}
function dispatchEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
if (!_enabled) {
return;
}
{
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay(domEventName, eventSystemFlags, targetContainer, nativeEvent);
}
}
function dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
var blockedOn = findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent);
if (blockedOn === null) {
dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, return_targetInst, targetContainer);
clearIfContinuousEvent(domEventName, nativeEvent);
return;
}
if (queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent)) {
nativeEvent.stopPropagation();
return;
} // We need to clear only if we didn't queue because
// queueing is accumulative.
clearIfContinuousEvent(domEventName, nativeEvent);
if (eventSystemFlags & IS_CAPTURE_PHASE && isDiscreteEventThatRequiresHydration(domEventName)) {
while (blockedOn !== null) {
var fiber = getInstanceFromNode(blockedOn);
if (fiber !== null) {
attemptSynchronousHydration(fiber);
}
var nextBlockedOn = findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent);
if (nextBlockedOn === null) {
dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, return_targetInst, targetContainer);
}
if (nextBlockedOn === blockedOn) {
break;
}
blockedOn = nextBlockedOn;
}
if (blockedOn !== null) {
nativeEvent.stopPropagation();
}
return;
} // This is not replayable so we'll invoke it but without a target,
// in case the event system needs to trace it.
dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, null, targetContainer);
}
var return_targetInst = null; // Returns a SuspenseInstance or Container if it's blocked.
// The return_targetInst field above is conceptually part of the return value.
function findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
// TODO: Warn if _enabled is false.
return_targetInst = null;
var nativeEventTarget = getEventTarget(nativeEvent);
var targetInst = getClosestInstanceFromNode(nativeEventTarget);
if (targetInst !== null) {
var nearestMounted = getNearestMountedFiber(targetInst);
if (nearestMounted === null) {
// This tree has been unmounted already. Dispatch without a target.
targetInst = null;
} else {
var tag = nearestMounted.tag;
if (tag === SuspenseComponent) {
var instance = getSuspenseInstanceFromFiber(nearestMounted);
if (instance !== null) {
// Queue the event to be replayed later. Abort dispatching since we
// don't want this event dispatched twice through the event system.
// TODO: If this is the first discrete event in the queue. Schedule an increased
// priority for this boundary.
return instance;
} // This shouldn't happen, something went wrong but to avoid blocking
// the whole system, dispatch the event without a target.
// TODO: Warn.
targetInst = null;
} else if (tag === HostRoot) {
var root = nearestMounted.stateNode;
if (isRootDehydrated(root)) {
// If this happens during a replay something went wrong and it might block
// the whole system.
return getContainerFromFiber(nearestMounted);
}
targetInst = null;
} else if (nearestMounted !== targetInst) {
// If we get an event (ex: img onload) before committing that
// component's mount, ignore it for now (that is, treat it as if it was an
// event on a non-React tree). We might also consider queueing events and
// dispatching them after the mount.
targetInst = null;
}
}
}
return_targetInst = targetInst; // We're not blocked on anything.
return null;
}
function getEventPriority(domEventName) {
switch (domEventName) {
// Used by SimpleEventPlugin:
case 'cancel':
case 'click':
case 'close':
case 'contextmenu':
case 'copy':
case 'cut':
case 'auxclick':
case 'dblclick':
case 'dragend':
case 'dragstart':
case 'drop':
case 'focusin':
case 'focusout':
case 'input':
case 'invalid':
case 'keydown':
case 'keypress':
case 'keyup':
case 'mousedown':
case 'mouseup':
case 'paste':
case 'pause':
case 'play':
case 'pointercancel':
case 'pointerdown':
case 'pointerup':
case 'ratechange':
case 'reset':
case 'resize':
case 'seeked':
case 'submit':
case 'touchcancel':
case 'touchend':
case 'touchstart':
case 'volumechange': // Used by polyfills:
// eslint-disable-next-line no-fallthrough
case 'change':
case 'selectionchange':
case 'textInput':
case 'compositionstart':
case 'compositionend':
case 'compositionupdate': // Only enableCreateEventHandleAPI:
// eslint-disable-next-line no-fallthrough
case 'beforeblur':
case 'afterblur': // Not used by React but could be by user code:
// eslint-disable-next-line no-fallthrough
case 'beforeinput':
case 'blur':
case 'fullscreenchange':
case 'focus':
case 'hashchange':
case 'popstate':
case 'select':
case 'selectstart':
return DiscreteEventPriority;
case 'drag':
case 'dragenter':
case 'dragexit':
case 'dragleave':
case 'dragover':
case 'mousemove':
case 'mouseout':
case 'mouseover':
case 'pointermove':
case 'pointerout':
case 'pointerover':
case 'scroll':
case 'toggle':
case 'touchmove':
case 'wheel': // Not used by React but could be by user code:
// eslint-disable-next-line no-fallthrough
case 'mouseenter':
case 'mouseleave':
case 'pointerenter':
case 'pointerleave':
return ContinuousEventPriority;
case 'message':
{
// We might be in the Scheduler callback.
// Eventually this mechanism will be replaced by a check
// of the current priority on the native scheduler.
var schedulerPriority = getCurrentPriorityLevel();
switch (schedulerPriority) {
case ImmediatePriority:
return DiscreteEventPriority;
case UserBlockingPriority:
return ContinuousEventPriority;
case NormalPriority:
case LowPriority:
// TODO: Handle LowSchedulerPriority, somehow. Maybe the same lane as hydration.
return DefaultEventPriority;
case IdlePriority:
return IdleEventPriority;
default:
return DefaultEventPriority;
}
}
default:
return DefaultEventPriority;
}
}
function addEventBubbleListener(target, eventType, listener) {
target.addEventListener(eventType, listener, false);
return listener;
}
function addEventCaptureListener(target, eventType, listener) {
target.addEventListener(eventType, listener, true);
return listener;
}
function addEventCaptureListenerWithPassiveFlag(target, eventType, listener, passive) {
target.addEventListener(eventType, listener, {
capture: true,
passive: passive
});
return listener;
}
function addEventBubbleListenerWithPassiveFlag(target, eventType, listener, passive) {
target.addEventListener(eventType, listener, {
passive: passive
});
return listener;
}
/**
* These variables store information about text content of a target node,
* allowing comparison of content before and after a given event.
*
* Identify the node where selection currently begins, then observe
* both its text content and its current position in the DOM. Since the
* browser may natively replace the target node during composition, we can
* use its position to find its replacement.
*
*
*/
var root = null;
var startText = null;
var fallbackText = null;
function initialize(nativeEventTarget) {
root = nativeEventTarget;
startText = getText();
return true;
}
function reset() {
root = null;
startText = null;
fallbackText = null;
}
function getData() {
if (fallbackText) {
return fallbackText;
}
var start;
var startValue = startText;
var startLength = startValue.length;
var end;
var endValue = getText();
var endLength = endValue.length;
for (start = 0; start < startLength; start++) {
if (startValue[start] !== endValue[start]) {
break;
}
}
var minEnd = startLength - start;
for (end = 1; end <= minEnd; end++) {
if (startValue[startLength - end] !== endValue[endLength - end]) {
break;
}
}
var sliceTail = end > 1 ? 1 - end : undefined;
fallbackText = endValue.slice(start, sliceTail);
return fallbackText;
}
function getText() {
if ('value' in root) {
return root.value;
}
return root.textContent;
}
/**
* `charCode` represents the actual "character code" and is safe to use with
* `String.fromCharCode`. As such, only keys that correspond to printable
* characters produce a valid `charCode`, the only exception to this is Enter.
* The Tab-key is considered non-printable and does not have a `charCode`,
* presumably because it does not produce a tab-character in browsers.
*
* @param {object} nativeEvent Native browser event.
* @return {number} Normalized `charCode` property.
*/
function getEventCharCode(nativeEvent) {
var charCode;
var keyCode = nativeEvent.keyCode;
if ('charCode' in nativeEvent) {
charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`.
if (charCode === 0 && keyCode === 13) {
charCode = 13;
}
} else {
// IE8 does not implement `charCode`, but `keyCode` has the correct value.
charCode = keyCode;
} // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)
// report Enter as charCode 10 when ctrl is pressed.
if (charCode === 10) {
charCode = 13;
} // Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
// Must not discard the (non-)printable Enter-key.
if (charCode >= 32 || charCode === 13) {
return charCode;
}
return 0;
}
function functionThatReturnsTrue() {
return true;
}
function functionThatReturnsFalse() {
return false;
} // This is intentionally a factory so that we have different returned constructors.
// If we had a single constructor, it would be megamorphic and engines would deopt.
function createSyntheticEvent(Interface) {
/**
* Synthetic events are dispatched by event plugins, typically in response to a
* top-level event delegation handler.
*
* These systems should generally use pooling to reduce the frequency of garbage
* collection. The system should check `isPersistent` to determine whether the
* event should be released into the pool after being dispatched. Users that
* need a persisted event should invoke `persist`.
*
* Synthetic events (and subclasses) implement the DOM Level 3 Events API by
* normalizing browser quirks. Subclasses do not necessarily have to implement a
* DOM interface; custom application-specific events can also subclass this.
*/
function SyntheticBaseEvent(reactName, reactEventType, targetInst, nativeEvent, nativeEventTarget) {
this._reactName = reactName;
this._targetInst = targetInst;
this.type = reactEventType;
this.nativeEvent = nativeEvent;
this.target = nativeEventTarget;
this.currentTarget = null;
for (var _propName in Interface) {
if (!Interface.hasOwnProperty(_propName)) {
continue;
}
var normalize = Interface[_propName];
if (normalize) {
this[_propName] = normalize(nativeEvent);
} else {
this[_propName] = nativeEvent[_propName];
}
}
var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
if (defaultPrevented) {
this.isDefaultPrevented = functionThatReturnsTrue;
} else {
this.isDefaultPrevented = functionThatReturnsFalse;
}
this.isPropagationStopped = functionThatReturnsFalse;
return this;
}
assign(SyntheticBaseEvent.prototype, {
preventDefault: function () {
this.defaultPrevented = true;
var event = this.nativeEvent;
if (!event) {
return;
}
if (event.preventDefault) {
event.preventDefault(); // $FlowFixMe - flow is not aware of `unknown` in IE
} else if (typeof event.returnValue !== 'unknown') {
event.returnValue = false;
}
this.isDefaultPrevented = functionThatReturnsTrue;
},
stopPropagation: function () {
var event = this.nativeEvent;
if (!event) {
return;
}
if (event.stopPropagation) {
event.stopPropagation(); // $FlowFixMe - flow is not aware of `unknown` in IE
} else if (typeof event.cancelBubble !== 'unknown') {
// The ChangeEventPlugin registers a "propertychange" event for
// IE. This event does not support bubbling or cancelling, and
// any references to cancelBubble throw "Member not found". A
// typeof check of "unknown" circumvents this issue (and is also
// IE specific).
event.cancelBubble = true;
}
this.isPropagationStopped = functionThatReturnsTrue;
},
/**
* We release all dispatched `SyntheticEvent`s after each event loop, adding
* them back into the pool. This allows a way to hold onto a reference that
* won't be added back into the pool.
*/
persist: function () {// Modern event system doesn't use pooling.
},
/**
* Checks if this event should be released back into the pool.
*
* @return {boolean} True if this should not be released, false otherwise.
*/
isPersistent: functionThatReturnsTrue
});
return SyntheticBaseEvent;
}
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var EventInterface = {
eventPhase: 0,
bubbles: 0,
cancelable: 0,
timeStamp: function (event) {
return event.timeStamp || Date.now();
},
defaultPrevented: 0,
isTrusted: 0
};
var SyntheticEvent = createSyntheticEvent(EventInterface);
var UIEventInterface = assign({}, EventInterface, {
view: 0,
detail: 0
});
var SyntheticUIEvent = createSyntheticEvent(UIEventInterface);
var lastMovementX;
var lastMovementY;
var lastMouseEvent;
function updateMouseMovementPolyfillState(event) {
if (event !== lastMouseEvent) {
if (lastMouseEvent && event.type === 'mousemove') {
lastMovementX = event.screenX - lastMouseEvent.screenX;
lastMovementY = event.screenY - lastMouseEvent.screenY;
} else {
lastMovementX = 0;
lastMovementY = 0;
}
lastMouseEvent = event;
}
}
/**
* @interface MouseEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var MouseEventInterface = assign({}, UIEventInterface, {
screenX: 0,
screenY: 0,
clientX: 0,
clientY: 0,
pageX: 0,
pageY: 0,
ctrlKey: 0,
shiftKey: 0,
altKey: 0,
metaKey: 0,
getModifierState: getEventModifierState,
button: 0,
buttons: 0,
relatedTarget: function (event) {
if (event.relatedTarget === undefined) return event.fromElement === event.srcElement ? event.toElement : event.fromElement;
return event.relatedTarget;
},
movementX: function (event) {
if ('movementX' in event) {
return event.movementX;
}
updateMouseMovementPolyfillState(event);
return lastMovementX;
},
movementY: function (event) {
if ('movementY' in event) {
return event.movementY;
} // Don't need to call updateMouseMovementPolyfillState() here
// because it's guaranteed to have already run when movementX
// was copied.
return lastMovementY;
}
});
var SyntheticMouseEvent = createSyntheticEvent(MouseEventInterface);
/**
* @interface DragEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var DragEventInterface = assign({}, MouseEventInterface, {
dataTransfer: 0
});
var SyntheticDragEvent = createSyntheticEvent(DragEventInterface);
/**
* @interface FocusEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var FocusEventInterface = assign({}, UIEventInterface, {
relatedTarget: 0
});
var SyntheticFocusEvent = createSyntheticEvent(FocusEventInterface);
/**
* @interface Event
* @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
* @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
*/
var AnimationEventInterface = assign({}, EventInterface, {
animationName: 0,
elapsedTime: 0,
pseudoElement: 0
});
var SyntheticAnimationEvent = createSyntheticEvent(AnimationEventInterface);
/**
* @interface Event
* @see http://www.w3.org/TR/clipboard-apis/
*/
var ClipboardEventInterface = assign({}, EventInterface, {
clipboardData: function (event) {
return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
}
});
var SyntheticClipboardEvent = createSyntheticEvent(ClipboardEventInterface);
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
*/
var CompositionEventInterface = assign({}, EventInterface, {
data: 0
});
var SyntheticCompositionEvent = createSyntheticEvent(CompositionEventInterface);
/**
* @interface Event
* @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
* /#events-inputevents
*/
// Happens to share the same list for now.
var SyntheticInputEvent = SyntheticCompositionEvent;
/**
* Normalization of deprecated HTML5 `key` values
* @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
*/
var normalizeKey = {
Esc: 'Escape',
Spacebar: ' ',
Left: 'ArrowLeft',
Up: 'ArrowUp',
Right: 'ArrowRight',
Down: 'ArrowDown',
Del: 'Delete',
Win: 'OS',
Menu: 'ContextMenu',
Apps: 'ContextMenu',
Scroll: 'ScrollLock',
MozPrintableKey: 'Unidentified'
};
/**
* Translation from legacy `keyCode` to HTML5 `key`
* Only special keys supported, all others depend on keyboard layout or browser
* @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
*/
var translateToKey = {
'8': 'Backspace',
'9': 'Tab',
'12': 'Clear',
'13': 'Enter',
'16': 'Shift',
'17': 'Control',
'18': 'Alt',
'19': 'Pause',
'20': 'CapsLock',
'27': 'Escape',
'32': ' ',
'33': 'PageUp',
'34': 'PageDown',
'35': 'End',
'36': 'Home',
'37': 'ArrowLeft',
'38': 'ArrowUp',
'39': 'ArrowRight',
'40': 'ArrowDown',
'45': 'Insert',
'46': 'Delete',
'112': 'F1',
'113': 'F2',
'114': 'F3',
'115': 'F4',
'116': 'F5',
'117': 'F6',
'118': 'F7',
'119': 'F8',
'120': 'F9',
'121': 'F10',
'122': 'F11',
'123': 'F12',
'144': 'NumLock',
'145': 'ScrollLock',
'224': 'Meta'
};
/**
* @param {object} nativeEvent Native browser event.
* @return {string} Normalized `key` property.
*/
function getEventKey(nativeEvent) {
if (nativeEvent.key) {
// Normalize inconsistent values reported by browsers due to
// implementations of a working draft specification.
// FireFox implements `key` but returns `MozPrintableKey` for all
// printable characters (normalized to `Unidentified`), ignore it.
var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
if (key !== 'Unidentified') {
return key;
}
} // Browser does not implement `key`, polyfill as much of it as we can.
if (nativeEvent.type === 'keypress') {
var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can
// thus be captured by `keypress`, no other non-printable key should.
return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
}
if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
// While user keyboard layout determines the actual meaning of each
// `keyCode` value, almost all function keys have a universal value.
return translateToKey[nativeEvent.keyCode] || 'Unidentified';
}
return '';
}
/**
* Translation from modifier key to the associated property in the event.
* @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
*/
var modifierKeyToProp = {
Alt: 'altKey',
Control: 'ctrlKey',
Meta: 'metaKey',
Shift: 'shiftKey'
}; // Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
// getModifierState. If getModifierState is not supported, we map it to a set of
// modifier keys exposed by the event. In this case, Lock-keys are not supported.
function modifierStateGetter(keyArg) {
var syntheticEvent = this;
var nativeEvent = syntheticEvent.nativeEvent;
if (nativeEvent.getModifierState) {
return nativeEvent.getModifierState(keyArg);
}
var keyProp = modifierKeyToProp[keyArg];
return keyProp ? !!nativeEvent[keyProp] : false;
}
function getEventModifierState(nativeEvent) {
return modifierStateGetter;
}
/**
* @interface KeyboardEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var KeyboardEventInterface = assign({}, UIEventInterface, {
key: getEventKey,
code: 0,
location: 0,
ctrlKey: 0,
shiftKey: 0,
altKey: 0,
metaKey: 0,
repeat: 0,
locale: 0,
getModifierState: getEventModifierState,
// Legacy Interface
charCode: function (event) {
// `charCode` is the result of a KeyPress event and represents the value of
// the actual printable character.
// KeyPress is deprecated, but its replacement is not yet final and not
// implemented in any major browser. Only KeyPress has charCode.
if (event.type === 'keypress') {
return getEventCharCode(event);
}
return 0;
},
keyCode: function (event) {
// `keyCode` is the result of a KeyDown/Up event and represents the value of
// physical keyboard key.
// The actual meaning of the value depends on the users' keyboard layout
// which cannot be detected. Assuming that it is a US keyboard layout
// provides a surprisingly accurate mapping for US and European users.
// Due to this, it is left to the user to implement at this time.
if (event.type === 'keydown' || event.type === 'keyup') {
return event.keyCode;
}
return 0;
},
which: function (event) {
// `which` is an alias for either `keyCode` or `charCode` depending on the
// type of the event.
if (event.type === 'keypress') {
return getEventCharCode(event);
}
if (event.type === 'keydown' || event.type === 'keyup') {
return event.keyCode;
}
return 0;
}
});
var SyntheticKeyboardEvent = createSyntheticEvent(KeyboardEventInterface);
/**
* @interface PointerEvent
* @see http://www.w3.org/TR/pointerevents/
*/
var PointerEventInterface = assign({}, MouseEventInterface, {
pointerId: 0,
width: 0,
height: 0,
pressure: 0,
tangentialPressure: 0,
tiltX: 0,
tiltY: 0,
twist: 0,
pointerType: 0,
isPrimary: 0
});
var SyntheticPointerEvent = createSyntheticEvent(PointerEventInterface);
/**
* @interface TouchEvent
* @see http://www.w3.org/TR/touch-events/
*/
var TouchEventInterface = assign({}, UIEventInterface, {
touches: 0,
targetTouches: 0,
changedTouches: 0,
altKey: 0,
metaKey: 0,
ctrlKey: 0,
shiftKey: 0,
getModifierState: getEventModifierState
});
var SyntheticTouchEvent = createSyntheticEvent(TouchEventInterface);
/**
* @interface Event
* @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
* @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
*/
var TransitionEventInterface = assign({}, EventInterface, {
propertyName: 0,
elapsedTime: 0,
pseudoElement: 0
});
var SyntheticTransitionEvent = createSyntheticEvent(TransitionEventInterface);
/**
* @interface WheelEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var WheelEventInterface = assign({}, MouseEventInterface, {
deltaX: function (event) {
return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
},
deltaY: function (event) {
return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
'wheelDelta' in event ? -event.wheelDelta : 0;
},
deltaZ: 0,
// Browsers without "deltaMode" is reporting in raw wheel delta where one
// notch on the scroll is always +/- 120, roughly equivalent to pixels.
// A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
// ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
deltaMode: 0
});
var SyntheticWheelEvent = createSyntheticEvent(WheelEventInterface);
var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
var START_KEYCODE = 229;
var canUseCompositionEvent = canUseDOM && 'CompositionEvent' in window;
var documentMode = null;
if (canUseDOM && 'documentMode' in document) {
documentMode = document.documentMode;
} // Webkit offers a very useful `textInput` event that can be used to
// directly represent `beforeInput`. The IE `textinput` event is not as
// useful, so we don't use it.
var canUseTextInputEvent = canUseDOM && 'TextEvent' in window && !documentMode; // In IE9+, we have access to composition events, but the data supplied
// by the native compositionend event may be incorrect. Japanese ideographic
// spaces, for instance (\u3000) are not recorded correctly.
var useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
var SPACEBAR_CODE = 32;
var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE);
function registerEvents() {
registerTwoPhaseEvent('onBeforeInput', ['compositionend', 'keypress', 'textInput', 'paste']);
registerTwoPhaseEvent('onCompositionEnd', ['compositionend', 'focusout', 'keydown', 'keypress', 'keyup', 'mousedown']);
registerTwoPhaseEvent('onCompositionStart', ['compositionstart', 'focusout', 'keydown', 'keypress', 'keyup', 'mousedown']);
registerTwoPhaseEvent('onCompositionUpdate', ['compositionupdate', 'focusout', 'keydown', 'keypress', 'keyup', 'mousedown']);
} // Track whether we've ever handled a keypress on the space key.
var hasSpaceKeypress = false;
/**
* Return whether a native keypress event is assumed to be a command.
* This is required because Firefox fires `keypress` events for key commands
* (cut, copy, select-all, etc.) even though no character is inserted.
*/
function isKeypressCommand(nativeEvent) {
return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command.
!(nativeEvent.ctrlKey && nativeEvent.altKey);
}
/**
* Translate native top level events into event types.
*/
function getCompositionEventType(domEventName) {
switch (domEventName) {
case 'compositionstart':
return 'onCompositionStart';
case 'compositionend':
return 'onCompositionEnd';
case 'compositionupdate':
return 'onCompositionUpdate';
}
}
/**
* Does our fallback best-guess model think this event signifies that
* composition has begun?
*/
function isFallbackCompositionStart(domEventName, nativeEvent) {
return domEventName === 'keydown' && nativeEvent.keyCode === START_KEYCODE;
}
/**
* Does our fallback mode think that this event is the end of composition?
*/
function isFallbackCompositionEnd(domEventName, nativeEvent) {
switch (domEventName) {
case 'keyup':
// Command keys insert or clear IME input.
return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
case 'keydown':
// Expect IME keyCode on each keydown. If we get any other
// code we must have exited earlier.
return nativeEvent.keyCode !== START_KEYCODE;
case 'keypress':
case 'mousedown':
case 'focusout':
// Events are not possible without cancelling IME.
return true;
default:
return false;
}
}
/**
* Google Input Tools provides composition data via a CustomEvent,
* with the `data` property populated in the `detail` object. If this
* is available on the event object, use it. If not, this is a plain
* composition event and we have nothing special to extract.
*
* @param {object} nativeEvent
* @return {?string}
*/
function getDataFromCustomEvent(nativeEvent) {
var detail = nativeEvent.detail;
if (typeof detail === 'object' && 'data' in detail) {
return detail.data;
}
return null;
}
/**
* Check if a composition event was triggered by Korean IME.
* Our fallback mode does not work well with IE's Korean IME,
* so just use native composition events when Korean IME is used.
* Although CompositionEvent.locale property is deprecated,
* it is available in IE, where our fallback mode is enabled.
*
* @param {object} nativeEvent
* @return {boolean}
*/
function isUsingKoreanIME(nativeEvent) {
return nativeEvent.locale === 'ko';
} // Track the current IME composition status, if any.
var isComposing = false;
/**
* @return {?object} A SyntheticCompositionEvent.
*/
function extractCompositionEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget) {
var eventType;
var fallbackData;
if (canUseCompositionEvent) {
eventType = getCompositionEventType(domEventName);
} else if (!isComposing) {
if (isFallbackCompositionStart(domEventName, nativeEvent)) {
eventType = 'onCompositionStart';
}
} else if (isFallbackCompositionEnd(domEventName, nativeEvent)) {
eventType = 'onCompositionEnd';
}
if (!eventType) {
return null;
}
if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) {
// The current composition is stored statically and must not be
// overwritten while composition continues.
if (!isComposing && eventType === 'onCompositionStart') {
isComposing = initialize(nativeEventTarget);
} else if (eventType === 'onCompositionEnd') {
if (isComposing) {
fallbackData = getData();
}
}
}
var listeners = accumulateTwoPhaseListeners(targetInst, eventType);
if (listeners.length > 0) {
var event = new SyntheticCompositionEvent(eventType, domEventName, null, nativeEvent, nativeEventTarget);
dispatchQueue.push({
event: event,
listeners: listeners
});
if (fallbackData) {
// Inject data generated from fallback path into the synthetic event.
// This matches the property of native CompositionEventInterface.
event.data = fallbackData;
} else {
var customData = getDataFromCustomEvent(nativeEvent);
if (customData !== null) {
event.data = customData;
}
}
}
}
function getNativeBeforeInputChars(domEventName, nativeEvent) {
switch (domEventName) {
case 'compositionend':
return getDataFromCustomEvent(nativeEvent);
case 'keypress':
/**
* If native `textInput` events are available, our goal is to make
* use of them. However, there is a special case: the spacebar key.
* In Webkit, preventing default on a spacebar `textInput` event
* cancels character insertion, but it *also* causes the browser
* to fall back to its default spacebar behavior of scrolling the
* page.
*
* Tracking at:
* https://code.google.com/p/chromium/issues/detail?id=355103
*
* To avoid this issue, use the keypress event as if no `textInput`
* event is available.
*/
var which = nativeEvent.which;
if (which !== SPACEBAR_CODE) {
return null;
}
hasSpaceKeypress = true;
return SPACEBAR_CHAR;
case 'textInput':
// Record the characters to be added to the DOM.
var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled
// it at the keypress level and bail immediately. Android Chrome
// doesn't give us keycodes, so we need to ignore it.
if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
return null;
}
return chars;
default:
// For other native event types, do nothing.
return null;
}
}
/**
* For browsers that do not provide the `textInput` event, extract the
* appropriate string to use for SyntheticInputEvent.
*/
function getFallbackBeforeInputChars(domEventName, nativeEvent) {
// If we are currently composing (IME) and using a fallback to do so,
// try to extract the composed characters from the fallback object.
// If composition event is available, we extract a string only at
// compositionevent, otherwise extract it at fallback events.
if (isComposing) {
if (domEventName === 'compositionend' || !canUseCompositionEvent && isFallbackCompositionEnd(domEventName, nativeEvent)) {
var chars = getData();
reset();
isComposing = false;
return chars;
}
return null;
}
switch (domEventName) {
case 'paste':
// If a paste event occurs after a keypress, throw out the input
// chars. Paste events should not lead to BeforeInput events.
return null;
case 'keypress':
/**
* As of v27, Firefox may fire keypress events even when no character
* will be inserted. A few possibilities:
*
* - `which` is `0`. Arrow keys, Esc key, etc.
*
* - `which` is the pressed key code, but no char is available.
* Ex: 'AltGr + d` in Polish. There is no modified character for
* this key combination and no character is inserted into the
* document, but FF fires the keypress for char code `100` anyway.
* No `input` event will occur.
*
* - `which` is the pressed key code, but a command combination is
* being used. Ex: `Cmd+C`. No character is inserted, and no
* `input` event will occur.
*/
if (!isKeypressCommand(nativeEvent)) {
// IE fires the `keypress` event when a user types an emoji via
// Touch keyboard of Windows. In such a case, the `char` property
// holds an emoji character like `\uD83D\uDE0A`. Because its length
// is 2, the property `which` does not represent an emoji correctly.
// In such a case, we directly return the `char` property instead of
// using `which`.
if (nativeEvent.char && nativeEvent.char.length > 1) {
return nativeEvent.char;
} else if (nativeEvent.which) {
return String.fromCharCode(nativeEvent.which);
}
}
return null;
case 'compositionend':
return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data;
default:
return null;
}
}
/**
* Extract a SyntheticInputEvent for `beforeInput`, based on either native
* `textInput` or fallback behavior.
*
* @return {?object} A SyntheticInputEvent.
*/
function extractBeforeInputEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget) {
var chars;
if (canUseTextInputEvent) {
chars = getNativeBeforeInputChars(domEventName, nativeEvent);
} else {
chars = getFallbackBeforeInputChars(domEventName, nativeEvent);
} // If no characters are being inserted, no BeforeInput event should
// be fired.
if (!chars) {
return null;
}
var listeners = accumulateTwoPhaseListeners(targetInst, 'onBeforeInput');
if (listeners.length > 0) {
var event = new SyntheticInputEvent('onBeforeInput', 'beforeinput', null, nativeEvent, nativeEventTarget);
dispatchQueue.push({
event: event,
listeners: listeners
});
event.data = chars;
}
}
/**
* Create an `onBeforeInput` event to match
* http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
*
* This event plugin is based on the native `textInput` event
* available in Chrome, Safari, Opera, and IE. This event fires after
* `onKeyPress` and `onCompositionEnd`, but before `onInput`.
*
* `beforeInput` is spec'd but not implemented in any browsers, and
* the `input` event does not provide any useful information about what has
* actually been added, contrary to the spec. Thus, `textInput` is the best
* available event to identify the characters that have actually been inserted
* into the target node.
*
* This plugin is also responsible for emitting `composition` events, thus
* allowing us to share composition fallback code for both `beforeInput` and
* `composition` event types.
*/
function extractEvents(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
extractCompositionEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
extractBeforeInputEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
}
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
*/
var supportedInputTypes = {
color: true,
date: true,
datetime: true,
'datetime-local': true,
email: true,
month: true,
number: true,
password: true,
range: true,
search: true,
tel: true,
text: true,
time: true,
url: true,
week: true
};
function isTextInputElement(elem) {
var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
if (nodeName === 'input') {
return !!supportedInputTypes[elem.type];
}
if (nodeName === 'textarea') {
return true;
}
return false;
}
/**
* Checks if an event is supported in the current execution environment.
*
* NOTE: This will not work correctly for non-generic events such as `change`,
* `reset`, `load`, `error`, and `select`.
*
* Borrows from Modernizr.
*
* @param {string} eventNameSuffix Event name, e.g. "click".
* @return {boolean} True if the event is supported.
* @internal
* @license Modernizr 3.0.0pre (Custom Build) | MIT
*/
function isEventSupported(eventNameSuffix) {
if (!canUseDOM) {
return false;
}
var eventName = 'on' + eventNameSuffix;
var isSupported = (eventName in document);
if (!isSupported) {
var element = document.createElement('div');
element.setAttribute(eventName, 'return;');
isSupported = typeof element[eventName] === 'function';
}
return isSupported;
}
function registerEvents$1() {
registerTwoPhaseEvent('onChange', ['change', 'click', 'focusin', 'focusout', 'input', 'keydown', 'keyup', 'selectionchange']);
}
function createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, target) {
// Flag this event loop as needing state restore.
enqueueStateRestore(target);
var listeners = accumulateTwoPhaseListeners(inst, 'onChange');
if (listeners.length > 0) {
var event = new SyntheticEvent('onChange', 'change', null, nativeEvent, target);
dispatchQueue.push({
event: event,
listeners: listeners
});
}
}
/**
* For IE shims
*/
var activeElement = null;
var activeElementInst = null;
/**
* SECTION: handle `change` event
*/
function shouldUseChangeEvent(elem) {
var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';
}
function manualDispatchChangeEvent(nativeEvent) {
var dispatchQueue = [];
createAndAccumulateChangeEvent(dispatchQueue, activeElementInst, nativeEvent, getEventTarget(nativeEvent)); // If change and propertychange bubbled, we'd just bind to it like all the
// other events and have it go through ReactBrowserEventEmitter. Since it
// doesn't, we manually listen for the events and so we have to enqueue and
// process the abstract event manually.
//
// Batching is necessary here in order to ensure that all event handlers run
// before the next rerender (including event handlers attached to ancestor
// elements instead of directly on the input). Without this, controlled
// components don't work properly in conjunction with event bubbling because
// the component is rerendered and the value reverted before all the event
// handlers can run. See https://github.com/facebook/react/issues/708.
batchedUpdates(runEventInBatch, dispatchQueue);
}
function runEventInBatch(dispatchQueue) {
processDispatchQueue(dispatchQueue, 0);
}
function getInstIfValueChanged(targetInst) {
var targetNode = getNodeFromInstance(targetInst);
if (updateValueIfChanged(targetNode)) {
return targetInst;
}
}
function getTargetInstForChangeEvent(domEventName, targetInst) {
if (domEventName === 'change') {
return targetInst;
}
}
/**
* SECTION: handle `input` event
*/
var isInputEventSupported = false;
if (canUseDOM) {
// IE9 claims to support the input event but fails to trigger it when
// deleting text, so we ignore its input events.
isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 9);
}
/**
* (For IE <=9) Starts tracking propertychange events on the passed-in element
* and override the value property so that we can distinguish user events from
* value changes in JS.
*/
function startWatchingForValueChange(target, targetInst) {
activeElement = target;
activeElementInst = targetInst;
activeElement.attachEvent('onpropertychange', handlePropertyChange);
}
/**
* (For IE <=9) Removes the event listeners from the currently-tracked element,
* if any exists.
*/
function stopWatchingForValueChange() {
if (!activeElement) {
return;
}
activeElement.detachEvent('onpropertychange', handlePropertyChange);
activeElement = null;
activeElementInst = null;
}
/**
* (For IE <=9) Handles a propertychange event, sending a `change` event if
* the value of the active element has changed.
*/
function handlePropertyChange(nativeEvent) {
if (nativeEvent.propertyName !== 'value') {
return;
}
if (getInstIfValueChanged(activeElementInst)) {
manualDispatchChangeEvent(nativeEvent);
}
}
function handleEventsForInputEventPolyfill(domEventName, target, targetInst) {
if (domEventName === 'focusin') {
// In IE9, propertychange fires for most input events but is buggy and
// doesn't fire when text is deleted, but conveniently, selectionchange
// appears to fire in all of the remaining cases so we catch those and
// forward the event if the value has changed
// In either case, we don't want to call the event handler if the value
// is changed from JS so we redefine a setter for `.value` that updates
// our activeElementValue variable, allowing us to ignore those changes
//
// stopWatching() should be a noop here but we call it just in case we
// missed a blur event somehow.
stopWatchingForValueChange();
startWatchingForValueChange(target, targetInst);
} else if (domEventName === 'focusout') {
stopWatchingForValueChange();
}
} // For IE8 and IE9.
function getTargetInstForInputEventPolyfill(domEventName, targetInst) {
if (domEventName === 'selectionchange' || domEventName === 'keyup' || domEventName === 'keydown') {
// On the selectionchange event, the target is just document which isn't
// helpful for us so just check activeElement instead.
//
// 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
// propertychange on the first input event after setting `value` from a
// script and fires only keydown, keypress, keyup. Catching keyup usually
// gets it and catching keydown lets us fire an event for the first
// keystroke if user does a key repeat (it'll be a little delayed: right
// before the second keystroke). Other input methods (e.g., paste) seem to
// fire selectionchange normally.
return getInstIfValueChanged(activeElementInst);
}
}
/**
* SECTION: handle `click` event
*/
function shouldUseClickEvent(elem) {
// Use the `click` event to detect changes to checkbox and radio inputs.
// This approach works across all browsers, whereas `change` does not fire
// until `blur` in IE8.
var nodeName = elem.nodeName;
return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
}
function getTargetInstForClickEvent(domEventName, targetInst) {
if (domEventName === 'click') {
return getInstIfValueChanged(targetInst);
}
}
function getTargetInstForInputOrChangeEvent(domEventName, targetInst) {
if (domEventName === 'input' || domEventName === 'change') {
return getInstIfValueChanged(targetInst);
}
}
function handleControlledInputBlur(node) {
var state = node._wrapperState;
if (!state || !state.controlled || node.type !== 'number') {
return;
}
{
// If controlled, assign the value attribute to the current value on blur
setDefaultValue(node, 'number', node.value);
}
}
/**
* This plugin creates an `onChange` event that normalizes change events
* across form elements. This event fires at a time when it's possible to
* change the element's value without seeing a flicker.
*
* Supported elements are:
* - input (see `isTextInputElement`)
* - textarea
* - select
*/
function extractEvents$1(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
var targetNode = targetInst ? getNodeFromInstance(targetInst) : window;
var getTargetInstFunc, handleEventFunc;
if (shouldUseChangeEvent(targetNode)) {
getTargetInstFunc = getTargetInstForChangeEvent;
} else if (isTextInputElement(targetNode)) {
if (isInputEventSupported) {
getTargetInstFunc = getTargetInstForInputOrChangeEvent;
} else {
getTargetInstFunc = getTargetInstForInputEventPolyfill;
handleEventFunc = handleEventsForInputEventPolyfill;
}
} else if (shouldUseClickEvent(targetNode)) {
getTargetInstFunc = getTargetInstForClickEvent;
}
if (getTargetInstFunc) {
var inst = getTargetInstFunc(domEventName, targetInst);
if (inst) {
createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, nativeEventTarget);
return;
}
}
if (handleEventFunc) {
handleEventFunc(domEventName, targetNode, targetInst);
} // When blurring, set the value attribute for number inputs
if (domEventName === 'focusout') {
handleControlledInputBlur(targetNode);
}
}
function registerEvents$2() {
registerDirectEvent('onMouseEnter', ['mouseout', 'mouseover']);
registerDirectEvent('onMouseLeave', ['mouseout', 'mouseover']);
registerDirectEvent('onPointerEnter', ['pointerout', 'pointerover']);
registerDirectEvent('onPointerLeave', ['pointerout', 'pointerover']);
}
/**
* For almost every interaction we care about, there will be both a top-level
* `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
* we do not extract duplicate events. However, moving the mouse into the
* browser from outside will not fire a `mouseout` event. In this case, we use
* the `mouseover` top-level event.
*/
function extractEvents$2(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
var isOverEvent = domEventName === 'mouseover' || domEventName === 'pointerover';
var isOutEvent = domEventName === 'mouseout' || domEventName === 'pointerout';
if (isOverEvent && !isReplayingEvent(nativeEvent)) {
// If this is an over event with a target, we might have already dispatched
// the event in the out event of the other target. If this is replayed,
// then it's because we couldn't dispatch against this target previously
// so we have to do it now instead.
var related = nativeEvent.relatedTarget || nativeEvent.fromElement;
if (related) {
// If the related node is managed by React, we can assume that we have
// already dispatched the corresponding events during its mouseout.
if (getClosestInstanceFromNode(related) || isContainerMarkedAsRoot(related)) {
return;
}
}
}
if (!isOutEvent && !isOverEvent) {
// Must not be a mouse or pointer in or out - ignoring.
return;
}
var win; // TODO: why is this nullable in the types but we read from it?
if (nativeEventTarget.window === nativeEventTarget) {
// `nativeEventTarget` is probably a window object.
win = nativeEventTarget;
} else {
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
var doc = nativeEventTarget.ownerDocument;
if (doc) {
win = doc.defaultView || doc.parentWindow;
} else {
win = window;
}
}
var from;
var to;
if (isOutEvent) {
var _related = nativeEvent.relatedTarget || nativeEvent.toElement;
from = targetInst;
to = _related ? getClosestInstanceFromNode(_related) : null;
if (to !== null) {
var nearestMounted = getNearestMountedFiber(to);
if (to !== nearestMounted || to.tag !== HostComponent && to.tag !== HostText) {
to = null;
}
}
} else {
// Moving to a node from outside the window.
from = null;
to = targetInst;
}
if (from === to) {
// Nothing pertains to our managed components.
return;
}
var SyntheticEventCtor = SyntheticMouseEvent;
var leaveEventType = 'onMouseLeave';
var enterEventType = 'onMouseEnter';
var eventTypePrefix = 'mouse';
if (domEventName === 'pointerout' || domEventName === 'pointerover') {
SyntheticEventCtor = SyntheticPointerEvent;
leaveEventType = 'onPointerLeave';
enterEventType = 'onPointerEnter';
eventTypePrefix = 'pointer';
}
var fromNode = from == null ? win : getNodeFromInstance(from);
var toNode = to == null ? win : getNodeFromInstance(to);
var leave = new SyntheticEventCtor(leaveEventType, eventTypePrefix + 'leave', from, nativeEvent, nativeEventTarget);
leave.target = fromNode;
leave.relatedTarget = toNode;
var enter = null; // We should only process this nativeEvent if we are processing
// the first ancestor. Next time, we will ignore the event.
var nativeTargetInst = getClosestInstanceFromNode(nativeEventTarget);
if (nativeTargetInst === targetInst) {
var enterEvent = new SyntheticEventCtor(enterEventType, eventTypePrefix + 'enter', to, nativeEvent, nativeEventTarget);
enterEvent.target = toNode;
enterEvent.relatedTarget = fromNode;
enter = enterEvent;
}
accumulateEnterLeaveTwoPhaseListeners(dispatchQueue, leave, enter, from, to);
}
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
function is(x, y) {
return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
;
}
var objectIs = typeof Object.is === 'function' ? Object.is : is;
/**
* Performs equality by iterating through keys on an object and returning false
* when any key has values which are not strictly equal between the arguments.
* Returns true when the values of all keys are strictly equal.
*/
function shallowEqual(objA, objB) {
if (objectIs(objA, objB)) {
return true;
}
if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
} // Test for A's keys different from B.
for (var i = 0; i < keysA.length; i++) {
var currentKey = keysA[i];
if (!hasOwnProperty.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey])) {
return false;
}
}
return true;
}
/**
* Given any node return the first leaf node without children.
*
* @param {DOMElement|DOMTextNode} node
* @return {DOMElement|DOMTextNode}
*/
function getLeafNode(node) {
while (node && node.firstChild) {
node = node.firstChild;
}
return node;
}
/**
* Get the next sibling within a container. This will walk up the
* DOM if a node's siblings have been exhausted.
*
* @param {DOMElement|DOMTextNode} node
* @return {?DOMElement|DOMTextNode}
*/
function getSiblingNode(node) {
while (node) {
if (node.nextSibling) {
return node.nextSibling;
}
node = node.parentNode;
}
}
/**
* Get object describing the nodes which contain characters at offset.
*
* @param {DOMElement|DOMTextNode} root
* @param {number} offset
* @return {?object}
*/
function getNodeForCharacterOffset(root, offset) {
var node = getLeafNode(root);
var nodeStart = 0;
var nodeEnd = 0;
while (node) {
if (node.nodeType === TEXT_NODE) {
nodeEnd = nodeStart + node.textContent.length;
if (nodeStart <= offset && nodeEnd >= offset) {
return {
node: node,
offset: offset - nodeStart
};
}
nodeStart = nodeEnd;
}
node = getLeafNode(getSiblingNode(node));
}
}
/**
* @param {DOMElement} outerNode
* @return {?object}
*/
function getOffsets(outerNode) {
var ownerDocument = outerNode.ownerDocument;
var win = ownerDocument && ownerDocument.defaultView || window;
var selection = win.getSelection && win.getSelection();
if (!selection || selection.rangeCount === 0) {
return null;
}
var anchorNode = selection.anchorNode,
anchorOffset = selection.anchorOffset,
focusNode = selection.focusNode,
focusOffset = selection.focusOffset; // In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the
// up/down buttons on an <input type="number">. Anonymous divs do not seem to
// expose properties, triggering a "Permission denied error" if any of its
// properties are accessed. The only seemingly possible way to avoid erroring
// is to access a property that typically works for non-anonymous divs and
// catch any error that may otherwise arise. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=208427
try {
/* eslint-disable no-unused-expressions */
anchorNode.nodeType;
focusNode.nodeType;
/* eslint-enable no-unused-expressions */
} catch (e) {
return null;
}
return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset);
}
/**
* Returns {start, end} where `start` is the character/codepoint index of
* (anchorNode, anchorOffset) within the textContent of `outerNode`, and
* `end` is the index of (focusNode, focusOffset).
*
* Returns null if you pass in garbage input but we should probably just crash.
*
* Exported only for testing.
*/
function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) {
var length = 0;
var start = -1;
var end = -1;
var indexWithinAnchor = 0;
var indexWithinFocus = 0;
var node = outerNode;
var parentNode = null;
outer: while (true) {
var next = null;
while (true) {
if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) {
start = length + anchorOffset;
}
if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) {
end = length + focusOffset;
}
if (node.nodeType === TEXT_NODE) {
length += node.nodeValue.length;
}
if ((next = node.firstChild) === null) {
break;
} // Moving from `node` to its first child `next`.
parentNode = node;
node = next;
}
while (true) {
if (node === outerNode) {
// If `outerNode` has children, this is always the second time visiting
// it. If it has no children, this is still the first loop, and the only
// valid selection is anchorNode and focusNode both equal to this node
// and both offsets 0, in which case we will have handled above.
break outer;
}
if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) {
start = length;
}
if (parentNode === focusNode && ++indexWithinFocus === focusOffset) {
end = length;
}
if ((next = node.nextSibling) !== null) {
break;
}
node = parentNode;
parentNode = node.parentNode;
} // Moving from `node` to its next sibling `next`.
node = next;
}
if (start === -1 || end === -1) {
// This should never happen. (Would happen if the anchor/focus nodes aren't
// actually inside the passed-in node.)
return null;
}
return {
start: start,
end: end
};
}
/**
* In modern non-IE browsers, we can support both forward and backward
* selections.
*
* Note: IE10+ supports the Selection object, but it does not support
* the `extend` method, which means that even in modern IE, it's not possible
* to programmatically create a backward selection. Thus, for all IE
* versions, we use the old IE API to create our selections.
*
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
function setOffsets(node, offsets) {
var doc = node.ownerDocument || document;
var win = doc && doc.defaultView || window; // Edge fails with "Object expected" in some scenarios.
// (For instance: TinyMCE editor used in a list component that supports pasting to add more,
// fails when pasting 100+ items)
if (!win.getSelection) {
return;
}
var selection = win.getSelection();
var length = node.textContent.length;
var start = Math.min(offsets.start, length);
var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method.
// Flip backward selections, so we can set with a single range.
if (!selection.extend && start > end) {
var temp = end;
end = start;
start = temp;
}
var startMarker = getNodeForCharacterOffset(node, start);
var endMarker = getNodeForCharacterOffset(node, end);
if (startMarker && endMarker) {
if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) {
return;
}
var range = doc.createRange();
range.setStart(startMarker.node, startMarker.offset);
selection.removeAllRanges();
if (start > end) {
selection.addRange(range);
selection.extend(endMarker.node, endMarker.offset);
} else {
range.setEnd(endMarker.node, endMarker.offset);
selection.addRange(range);
}
}
}
function isTextNode(node) {
return node && node.nodeType === TEXT_NODE;
}
function containsNode(outerNode, innerNode) {
if (!outerNode || !innerNode) {
return false;
} else if (outerNode === innerNode) {
return true;
} else if (isTextNode(outerNode)) {
return false;
} else if (isTextNode(innerNode)) {
return containsNode(outerNode, innerNode.parentNode);
} else if ('contains' in outerNode) {
return outerNode.contains(innerNode);
} else if (outerNode.compareDocumentPosition) {
return !!(outerNode.compareDocumentPosition(innerNode) & 16);
} else {
return false;
}
}
function isInDocument(node) {
return node && node.ownerDocument && containsNode(node.ownerDocument.documentElement, node);
}
function isSameOriginFrame(iframe) {
try {
// Accessing the contentDocument of a HTMLIframeElement can cause the browser
// to throw, e.g. if it has a cross-origin src attribute.
// Safari will show an error in the console when the access results in "Blocked a frame with origin". e.g:
// iframe.contentDocument.defaultView;
// A safety way is to access one of the cross origin properties: Window or Location
// Which might result in "SecurityError" DOM Exception and it is compatible to Safari.
// https://html.spec.whatwg.org/multipage/browsers.html#integration-with-idl
return typeof iframe.contentWindow.location.href === 'string';
} catch (err) {
return false;
}
}
function getActiveElementDeep() {
var win = window;
var element = getActiveElement();
while (element instanceof win.HTMLIFrameElement) {
if (isSameOriginFrame(element)) {
win = element.contentWindow;
} else {
return element;
}
element = getActiveElement(win.document);
}
return element;
}
/**
* @ReactInputSelection: React input selection module. Based on Selection.js,
* but modified to be suitable for react and has a couple of bug fixes (doesn't
* assume buttons have range selections allowed).
* Input selection module for React.
*/
/**
* @hasSelectionCapabilities: we get the element types that support selection
* from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart`
* and `selectionEnd` rows.
*/
function hasSelectionCapabilities(elem) {
var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
return nodeName && (nodeName === 'input' && (elem.type === 'text' || elem.type === 'search' || elem.type === 'tel' || elem.type === 'url' || elem.type === 'password') || nodeName === 'textarea' || elem.contentEditable === 'true');
}
function getSelectionInformation() {
var focusedElem = getActiveElementDeep();
return {
focusedElem: focusedElem,
selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection(focusedElem) : null
};
}
/**
* @restoreSelection: If any selection information was potentially lost,
* restore it. This is useful when performing operations that could remove dom
* nodes and place them back in, resulting in focus being lost.
*/
function restoreSelection(priorSelectionInformation) {
var curFocusedElem = getActiveElementDeep();
var priorFocusedElem = priorSelectionInformation.focusedElem;
var priorSelectionRange = priorSelectionInformation.selectionRange;
if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) {
setSelection(priorFocusedElem, priorSelectionRange);
} // Focusing a node can change the scroll position, which is undesirable
var ancestors = [];
var ancestor = priorFocusedElem;
while (ancestor = ancestor.parentNode) {
if (ancestor.nodeType === ELEMENT_NODE) {
ancestors.push({
element: ancestor,
left: ancestor.scrollLeft,
top: ancestor.scrollTop
});
}
}
if (typeof priorFocusedElem.focus === 'function') {
priorFocusedElem.focus();
}
for (var i = 0; i < ancestors.length; i++) {
var info = ancestors[i];
info.element.scrollLeft = info.left;
info.element.scrollTop = info.top;
}
}
}
/**
* @getSelection: Gets the selection bounds of a focused textarea, input or
* contentEditable node.
* -@input: Look up selection bounds of this input
* -@return {start: selectionStart, end: selectionEnd}
*/
function getSelection(input) {
var selection;
if ('selectionStart' in input) {
// Modern browser with input or textarea.
selection = {
start: input.selectionStart,
end: input.selectionEnd
};
} else {
// Content editable or old IE textarea.
selection = getOffsets(input);
}
return selection || {
start: 0,
end: 0
};
}
/**
* @setSelection: Sets the selection bounds of a textarea or input and focuses
* the input.
* -@input Set selection bounds of this input or textarea
* -@offsets Object of same form that is returned from get*
*/
function setSelection(input, offsets) {
var start = offsets.start;
var end = offsets.end;
if (end === undefined) {
end = start;
}
if ('selectionStart' in input) {
input.selectionStart = start;
input.selectionEnd = Math.min(end, input.value.length);
} else {
setOffsets(input, offsets);
}
}
var skipSelectionChangeEvent = canUseDOM && 'documentMode' in document && document.documentMode <= 11;
function registerEvents$3() {
registerTwoPhaseEvent('onSelect', ['focusout', 'contextmenu', 'dragend', 'focusin', 'keydown', 'keyup', 'mousedown', 'mouseup', 'selectionchange']);
}
var activeElement$1 = null;
var activeElementInst$1 = null;
var lastSelection = null;
var mouseDown = false;
/**
* Get an object which is a unique representation of the current selection.
*
* The return value will not be consistent across nodes or browsers, but
* two identical selections on the same node will return identical objects.
*/
function getSelection$1(node) {
if ('selectionStart' in node && hasSelectionCapabilities(node)) {
return {
start: node.selectionStart,
end: node.selectionEnd
};
} else {
var win = node.ownerDocument && node.ownerDocument.defaultView || window;
var selection = win.getSelection();
return {
anchorNode: selection.anchorNode,
anchorOffset: selection.anchorOffset,
focusNode: selection.focusNode,
focusOffset: selection.focusOffset
};
}
}
/**
* Get document associated with the event target.
*/
function getEventTargetDocument(eventTarget) {
return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;
}
/**
* Poll selection to see whether it's changed.
*
* @param {object} nativeEvent
* @param {object} nativeEventTarget
* @return {?SyntheticEvent}
*/
function constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget) {
// Ensure we have the right element, and that the user is not dragging a
// selection (this matches native `select` event behavior). In HTML5, select
// fires only on input and textarea thus if there's no focused element we
// won't dispatch.
var doc = getEventTargetDocument(nativeEventTarget);
if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) {
return;
} // Only fire when selection has actually changed.
var currentSelection = getSelection$1(activeElement$1);
if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
lastSelection = currentSelection;
var listeners = accumulateTwoPhaseListeners(activeElementInst$1, 'onSelect');
if (listeners.length > 0) {
var event = new SyntheticEvent('onSelect', 'select', null, nativeEvent, nativeEventTarget);
dispatchQueue.push({
event: event,
listeners: listeners
});
event.target = activeElement$1;
}
}
}
/**
* This plugin creates an `onSelect` event that normalizes select events
* across form elements.
*
* Supported elements are:
* - input (see `isTextInputElement`)
* - textarea
* - contentEditable
*
* This differs from native browser implementations in the following ways:
* - Fires on contentEditable fields as well as inputs.
* - Fires for collapsed selection.
* - Fires after user input.
*/
function extractEvents$3(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
var targetNode = targetInst ? getNodeFromInstance(targetInst) : window;
switch (domEventName) {
// Track the input node that has focus.
case 'focusin':
if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') {
activeElement$1 = targetNode;
activeElementInst$1 = targetInst;
lastSelection = null;
}
break;
case 'focusout':
activeElement$1 = null;
activeElementInst$1 = null;
lastSelection = null;
break;
// Don't fire the event while the user is dragging. This matches the
// semantics of the native select event.
case 'mousedown':
mouseDown = true;
break;
case 'contextmenu':
case 'mouseup':
case 'dragend':
mouseDown = false;
constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget);
break;
// Chrome and IE fire non-standard event when selection is changed (and
// sometimes when it hasn't). IE's event fires out of order with respect
// to key and input events on deletion, so we discard it.
//
// Firefox doesn't support selectionchange, so check selection status
// after each key entry. The selection changes after keydown and before
// keyup, but we check on keydown as well in the case of holding down a
// key, when multiple keydown events are fired but only one keyup is.
// This is also our approach for IE handling, for the reason above.
case 'selectionchange':
if (skipSelectionChangeEvent) {
break;
}
// falls through
case 'keydown':
case 'keyup':
constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget);
}
}
/**
* Generate a mapping of standard vendor prefixes using the defined style property and event name.
*
* @param {string} styleProp
* @param {string} eventName
* @returns {object}
*/
function makePrefixMap(styleProp, eventName) {
var prefixes = {};
prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
prefixes['Webkit' + styleProp] = 'webkit' + eventName;
prefixes['Moz' + styleProp] = 'moz' + eventName;
return prefixes;
}
/**
* A list of event names to a configurable list of vendor prefixes.
*/
var vendorPrefixes = {
animationend: makePrefixMap('Animation', 'AnimationEnd'),
animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
animationstart: makePrefixMap('Animation', 'AnimationStart'),
transitionend: makePrefixMap('Transition', 'TransitionEnd')
};
/**
* Event names that have already been detected and prefixed (if applicable).
*/
var prefixedEventNames = {};
/**
* Element to check for prefixes on.
*/
var style = {};
/**
* Bootstrap if a DOM exists.
*/
if (canUseDOM) {
style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x,
// the un-prefixed "animation" and "transition" properties are defined on the
// style object but the events that fire will still be prefixed, so we need
// to check if the un-prefixed events are usable, and if not remove them from the map.
if (!('AnimationEvent' in window)) {
delete vendorPrefixes.animationend.animation;
delete vendorPrefixes.animationiteration.animation;
delete vendorPrefixes.animationstart.animation;
} // Same as above
if (!('TransitionEvent' in window)) {
delete vendorPrefixes.transitionend.transition;
}
}
/**
* Attempts to determine the correct vendor prefixed event name.
*
* @param {string} eventName
* @returns {string}
*/
function getVendorPrefixedEventName(eventName) {
if (prefixedEventNames[eventName]) {
return prefixedEventNames[eventName];
} else if (!vendorPrefixes[eventName]) {
return eventName;
}
var prefixMap = vendorPrefixes[eventName];
for (var styleProp in prefixMap) {
if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
return prefixedEventNames[eventName] = prefixMap[styleProp];
}
}
return eventName;
}
var ANIMATION_END = getVendorPrefixedEventName('animationend');
var ANIMATION_ITERATION = getVendorPrefixedEventName('animationiteration');
var ANIMATION_START = getVendorPrefixedEventName('animationstart');
var TRANSITION_END = getVendorPrefixedEventName('transitionend');
var topLevelEventsToReactNames = new Map(); // NOTE: Capitalization is important in this list!
//
// E.g. it needs "pointerDown", not "pointerdown".
// This is because we derive both React name ("onPointerDown")
// and DOM name ("pointerdown") from the same list.
//
// Exceptions that don't match this convention are listed separately.
//
// prettier-ignore
var simpleEventPluginEvents = ['abort', 'auxClick', 'cancel', 'canPlay', 'canPlayThrough', 'click', 'close', 'contextMenu', 'copy', 'cut', 'drag', 'dragEnd', 'dragEnter', 'dragExit', 'dragLeave', 'dragOver', 'dragStart', 'drop', 'durationChange', 'emptied', 'encrypted', 'ended', 'error', 'gotPointerCapture', 'input', 'invalid', 'keyDown', 'keyPress', 'keyUp', 'load', 'loadedData', 'loadedMetadata', 'loadStart', 'lostPointerCapture', 'mouseDown', 'mouseMove', 'mouseOut', 'mouseOver', 'mouseUp', 'paste', 'pause', 'play', 'playing', 'pointerCancel', 'pointerDown', 'pointerMove', 'pointerOut', 'pointerOver', 'pointerUp', 'progress', 'rateChange', 'reset', 'resize', 'seeked', 'seeking', 'stalled', 'submit', 'suspend', 'timeUpdate', 'touchCancel', 'touchEnd', 'touchStart', 'volumeChange', 'scroll', 'toggle', 'touchMove', 'waiting', 'wheel'];
function registerSimpleEvent(domEventName, reactName) {
topLevelEventsToReactNames.set(domEventName, reactName);
registerTwoPhaseEvent(reactName, [domEventName]);
}
function registerSimpleEvents() {
for (var i = 0; i < simpleEventPluginEvents.length; i++) {
var eventName = simpleEventPluginEvents[i];
var domEventName = eventName.toLowerCase();
var capitalizedEvent = eventName[0].toUpperCase() + eventName.slice(1);
registerSimpleEvent(domEventName, 'on' + capitalizedEvent);
} // Special cases where event names don't match.
registerSimpleEvent(ANIMATION_END, 'onAnimationEnd');
registerSimpleEvent(ANIMATION_ITERATION, 'onAnimationIteration');
registerSimpleEvent(ANIMATION_START, 'onAnimationStart');
registerSimpleEvent('dblclick', 'onDoubleClick');
registerSimpleEvent('focusin', 'onFocus');
registerSimpleEvent('focusout', 'onBlur');
registerSimpleEvent(TRANSITION_END, 'onTransitionEnd');
}
function extractEvents$4(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
var reactName = topLevelEventsToReactNames.get(domEventName);
if (reactName === undefined) {
return;
}
var SyntheticEventCtor = SyntheticEvent;
var reactEventType = domEventName;
switch (domEventName) {
case 'keypress':
// Firefox creates a keypress event for function keys too. This removes
// the unwanted keypress events. Enter is however both printable and
// non-printable. One would expect Tab to be as well (but it isn't).
if (getEventCharCode(nativeEvent) === 0) {
return;
}
/* falls through */
case 'keydown':
case 'keyup':
SyntheticEventCtor = SyntheticKeyboardEvent;
break;
case 'focusin':
reactEventType = 'focus';
SyntheticEventCtor = SyntheticFocusEvent;
break;
case 'focusout':
reactEventType = 'blur';
SyntheticEventCtor = SyntheticFocusEvent;
break;
case 'beforeblur':
case 'afterblur':
SyntheticEventCtor = SyntheticFocusEvent;
break;
case 'click':
// Firefox creates a click event on right mouse clicks. This removes the
// unwanted click events.
if (nativeEvent.button === 2) {
return;
}
/* falls through */
case 'auxclick':
case 'dblclick':
case 'mousedown':
case 'mousemove':
case 'mouseup': // TODO: Disabled elements should not respond to mouse events
/* falls through */
case 'mouseout':
case 'mouseover':
case 'contextmenu':
SyntheticEventCtor = SyntheticMouseEvent;
break;
case 'drag':
case 'dragend':
case 'dragenter':
case 'dragexit':
case 'dragleave':
case 'dragover':
case 'dragstart':
case 'drop':
SyntheticEventCtor = SyntheticDragEvent;
break;
case 'touchcancel':
case 'touchend':
case 'touchmove':
case 'touchstart':
SyntheticEventCtor = SyntheticTouchEvent;
break;
case ANIMATION_END:
case ANIMATION_ITERATION:
case ANIMATION_START:
SyntheticEventCtor = SyntheticAnimationEvent;
break;
case TRANSITION_END:
SyntheticEventCtor = SyntheticTransitionEvent;
break;
case 'scroll':
SyntheticEventCtor = SyntheticUIEvent;
break;
case 'wheel':
SyntheticEventCtor = SyntheticWheelEvent;
break;
case 'copy':
case 'cut':
case 'paste':
SyntheticEventCtor = SyntheticClipboardEvent;
break;
case 'gotpointercapture':
case 'lostpointercapture':
case 'pointercancel':
case 'pointerdown':
case 'pointermove':
case 'pointerout':
case 'pointerover':
case 'pointerup':
SyntheticEventCtor = SyntheticPointerEvent;
break;
}
var inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0;
{
// Some events don't bubble in the browser.
// In the past, React has always bubbled them, but this can be surprising.
// We're going to try aligning closer to the browser behavior by not bubbling
// them in React either. We'll start by not bubbling onScroll, and then expand.
var accumulateTargetOnly = !inCapturePhase && // TODO: ideally, we'd eventually add all events from
// nonDelegatedEvents list in DOMPluginEventSystem.
// Then we can remove this special list.
// This is a breaking change that can wait until React 18.
domEventName === 'scroll';
var _listeners = accumulateSinglePhaseListeners(targetInst, reactName, nativeEvent.type, inCapturePhase, accumulateTargetOnly);
if (_listeners.length > 0) {
// Intentionally create event lazily.
var _event = new SyntheticEventCtor(reactName, reactEventType, null, nativeEvent, nativeEventTarget);
dispatchQueue.push({
event: _event,
listeners: _listeners
});
}
}
}
// TODO: remove top-level side effect.
registerSimpleEvents();
registerEvents$2();
registerEvents$1();
registerEvents$3();
registerEvents();
function extractEvents$5(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
// TODO: we should remove the concept of a "SimpleEventPlugin".
// This is the basic functionality of the event system. All
// the other plugins are essentially polyfills. So the plugin
// should probably be inlined somewhere and have its logic
// be core the to event system. This would potentially allow
// us to ship builds of React without the polyfilled plugins below.
extractEvents$4(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
var shouldProcessPolyfillPlugins = (eventSystemFlags & SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS) === 0; // We don't process these events unless we are in the
// event's native "bubble" phase, which means that we're
// not in the capture phase. That's because we emulate
// the capture phase here still. This is a trade-off,
// because in an ideal world we would not emulate and use
// the phases properly, like we do with the SimpleEvent
// plugin. However, the plugins below either expect
// emulation (EnterLeave) or use state localized to that
// plugin (BeforeInput, Change, Select). The state in
// these modules complicates things, as you'll essentially
// get the case where the capture phase event might change
// state, only for the following bubble event to come in
// later and not trigger anything as the state now
// invalidates the heuristics of the event plugin. We
// could alter all these plugins to work in such ways, but
// that might cause other unknown side-effects that we
// can't foresee right now.
if (shouldProcessPolyfillPlugins) {
extractEvents$2(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
extractEvents$1(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
extractEvents$3(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
extractEvents(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
}
} // List of events that need to be individually attached to media elements.
var mediaEventTypes = ['abort', 'canplay', 'canplaythrough', 'durationchange', 'emptied', 'encrypted', 'ended', 'error', 'loadeddata', 'loadedmetadata', 'loadstart', 'pause', 'play', 'playing', 'progress', 'ratechange', 'resize', 'seeked', 'seeking', 'stalled', 'suspend', 'timeupdate', 'volumechange', 'waiting']; // We should not delegate these events to the container, but rather
// set them on the actual target element itself. This is primarily
// because these events do not consistently bubble in the DOM.
var nonDelegatedEvents = new Set(['cancel', 'close', 'invalid', 'load', 'scroll', 'toggle'].concat(mediaEventTypes));
function executeDispatch(event, listener, currentTarget) {
var type = event.type || 'unknown-event';
event.currentTarget = currentTarget;
invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
event.currentTarget = null;
}
function processDispatchQueueItemsInOrder(event, dispatchListeners, inCapturePhase) {
var previousInstance;
if (inCapturePhase) {
for (var i = dispatchListeners.length - 1; i >= 0; i--) {
var _dispatchListeners$i = dispatchListeners[i],
instance = _dispatchListeners$i.instance,
currentTarget = _dispatchListeners$i.currentTarget,
listener = _dispatchListeners$i.listener;
if (instance !== previousInstance && event.isPropagationStopped()) {
return;
}
executeDispatch(event, listener, currentTarget);
previousInstance = instance;
}
} else {
for (var _i = 0; _i < dispatchListeners.length; _i++) {
var _dispatchListeners$_i = dispatchListeners[_i],
_instance = _dispatchListeners$_i.instance,
_currentTarget = _dispatchListeners$_i.currentTarget,
_listener = _dispatchListeners$_i.listener;
if (_instance !== previousInstance && event.isPropagationStopped()) {
return;
}
executeDispatch(event, _listener, _currentTarget);
previousInstance = _instance;
}
}
}
function processDispatchQueue(dispatchQueue, eventSystemFlags) {
var inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0;
for (var i = 0; i < dispatchQueue.length; i++) {
var _dispatchQueue$i = dispatchQueue[i],
event = _dispatchQueue$i.event,
listeners = _dispatchQueue$i.listeners;
processDispatchQueueItemsInOrder(event, listeners, inCapturePhase); // event system doesn't use pooling.
} // This would be a good time to rethrow if any of the event handlers threw.
rethrowCaughtError();
}
function dispatchEventsForPlugins(domEventName, eventSystemFlags, nativeEvent, targetInst, targetContainer) {
var nativeEventTarget = getEventTarget(nativeEvent);
var dispatchQueue = [];
extractEvents$5(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
processDispatchQueue(dispatchQueue, eventSystemFlags);
}
function listenToNonDelegatedEvent(domEventName, targetElement) {
{
if (!nonDelegatedEvents.has(domEventName)) {
error('Did not expect a listenToNonDelegatedEvent() call for "%s". ' + 'This is a bug in React. Please file an issue.', domEventName);
}
}
var isCapturePhaseListener = false;
var listenerSet = getEventListenerSet(targetElement);
var listenerSetKey = getListenerSetKey(domEventName, isCapturePhaseListener);
if (!listenerSet.has(listenerSetKey)) {
addTrappedEventListener(targetElement, domEventName, IS_NON_DELEGATED, isCapturePhaseListener);
listenerSet.add(listenerSetKey);
}
}
function listenToNativeEvent(domEventName, isCapturePhaseListener, target) {
{
if (nonDelegatedEvents.has(domEventName) && !isCapturePhaseListener) {
error('Did not expect a listenToNativeEvent() call for "%s" in the bubble phase. ' + 'This is a bug in React. Please file an issue.', domEventName);
}
}
var eventSystemFlags = 0;
if (isCapturePhaseListener) {
eventSystemFlags |= IS_CAPTURE_PHASE;
}
addTrappedEventListener(target, domEventName, eventSystemFlags, isCapturePhaseListener);
} // This is only used by createEventHandle when the
var listeningMarker = '_reactListening' + Math.random().toString(36).slice(2);
function listenToAllSupportedEvents(rootContainerElement) {
if (!rootContainerElement[listeningMarker]) {
rootContainerElement[listeningMarker] = true;
allNativeEvents.forEach(function (domEventName) {
// We handle selectionchange separately because it
// doesn't bubble and needs to be on the document.
if (domEventName !== 'selectionchange') {
if (!nonDelegatedEvents.has(domEventName)) {
listenToNativeEvent(domEventName, false, rootContainerElement);
}
listenToNativeEvent(domEventName, true, rootContainerElement);
}
});
var ownerDocument = rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;
if (ownerDocument !== null) {
// The selectionchange event also needs deduplication
// but it is attached to the document.
if (!ownerDocument[listeningMarker]) {
ownerDocument[listeningMarker] = true;
listenToNativeEvent('selectionchange', false, ownerDocument);
}
}
}
}
function addTrappedEventListener(targetContainer, domEventName, eventSystemFlags, isCapturePhaseListener, isDeferredListenerForLegacyFBSupport) {
var listener = createEventListenerWrapperWithPriority(targetContainer, domEventName, eventSystemFlags); // If passive option is not supported, then the event will be
// active and not passive.
var isPassiveListener = undefined;
if (passiveBrowserEventsSupported) {
// Browsers introduced an intervention, making these events
// passive by default on document. React doesn't bind them
// to document anymore, but changing this now would undo
// the performance wins from the change. So we emulate
// the existing behavior manually on the roots now.
// https://github.com/facebook/react/issues/19651
if (domEventName === 'touchstart' || domEventName === 'touchmove' || domEventName === 'wheel') {
isPassiveListener = true;
}
}
targetContainer = targetContainer;
var unsubscribeListener; // When legacyFBSupport is enabled, it's for when we
if (isCapturePhaseListener) {
if (isPassiveListener !== undefined) {
unsubscribeListener = addEventCaptureListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener);
} else {
unsubscribeListener = addEventCaptureListener(targetContainer, domEventName, listener);
}
} else {
if (isPassiveListener !== undefined) {
unsubscribeListener = addEventBubbleListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener);
} else {
unsubscribeListener = addEventBubbleListener(targetContainer, domEventName, listener);
}
}
}
function isMatchingRootContainer(grandContainer, targetContainer) {
return grandContainer === targetContainer || grandContainer.nodeType === COMMENT_NODE && grandContainer.parentNode === targetContainer;
}
function dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, targetInst, targetContainer) {
var ancestorInst = targetInst;
if ((eventSystemFlags & IS_EVENT_HANDLE_NON_MANAGED_NODE) === 0 && (eventSystemFlags & IS_NON_DELEGATED) === 0) {
var targetContainerNode = targetContainer; // If we are using the legacy FB support flag, we
if (targetInst !== null) {
// The below logic attempts to work out if we need to change
// the target fiber to a different ancestor. We had similar logic
// in the legacy event system, except the big difference between
// systems is that the modern event system now has an event listener
// attached to each React Root and React Portal Root. Together,
// the DOM nodes representing these roots are the "rootContainer".
// To figure out which ancestor instance we should use, we traverse
// up the fiber tree from the target instance and attempt to find
// root boundaries that match that of our current "rootContainer".
// If we find that "rootContainer", we find the parent fiber
// sub-tree for that root and make that our ancestor instance.
var node = targetInst;
mainLoop: while (true) {
if (node === null) {
return;
}
var nodeTag = node.tag;
if (nodeTag === HostRoot || nodeTag === HostPortal) {
var container = node.stateNode.containerInfo;
if (isMatchingRootContainer(container, targetContainerNode)) {
break;
}
if (nodeTag === HostPortal) {
// The target is a portal, but it's not the rootContainer we're looking for.
// Normally portals handle their own events all the way down to the root.
// So we should be able to stop now. However, we don't know if this portal
// was part of *our* root.
var grandNode = node.return;
while (grandNode !== null) {
var grandTag = grandNode.tag;
if (grandTag === HostRoot || grandTag === HostPortal) {
var grandContainer = grandNode.stateNode.containerInfo;
if (isMatchingRootContainer(grandContainer, targetContainerNode)) {
// This is the rootContainer we're looking for and we found it as
// a parent of the Portal. That means we can ignore it because the
// Portal will bubble through to us.
return;
}
}
grandNode = grandNode.return;
}
} // Now we need to find it's corresponding host fiber in the other
// tree. To do this we can use getClosestInstanceFromNode, but we
// need to validate that the fiber is a host instance, otherwise
// we need to traverse up through the DOM till we find the correct
// node that is from the other tree.
while (container !== null) {
var parentNode = getClosestInstanceFromNode(container);
if (parentNode === null) {
return;
}
var parentTag = parentNode.tag;
if (parentTag === HostComponent || parentTag === HostText) {
node = ancestorInst = parentNode;
continue mainLoop;
}
container = container.parentNode;
}
}
node = node.return;
}
}
}
batchedUpdates(function () {
return dispatchEventsForPlugins(domEventName, eventSystemFlags, nativeEvent, ancestorInst);
});
}
function createDispatchListener(instance, listener, currentTarget) {
return {
instance: instance,
listener: listener,
currentTarget: currentTarget
};
}
function accumulateSinglePhaseListeners(targetFiber, reactName, nativeEventType, inCapturePhase, accumulateTargetOnly, nativeEvent) {
var captureName = reactName !== null ? reactName + 'Capture' : null;
var reactEventName = inCapturePhase ? captureName : reactName;
var listeners = [];
var instance = targetFiber;
var lastHostComponent = null; // Accumulate all instances and listeners via the target -> root path.
while (instance !== null) {
var _instance2 = instance,
stateNode = _instance2.stateNode,
tag = _instance2.tag; // Handle listeners that are on HostComponents (i.e. <div>)
if (tag === HostComponent && stateNode !== null) {
lastHostComponent = stateNode; // createEventHandle listeners
if (reactEventName !== null) {
var listener = getListener(instance, reactEventName);
if (listener != null) {
listeners.push(createDispatchListener(instance, listener, lastHostComponent));
}
}
} // If we are only accumulating events for the target, then we don't
// continue to propagate through the React fiber tree to find other
// listeners.
if (accumulateTargetOnly) {
break;
} // If we are processing the onBeforeBlur event, then we need to take
instance = instance.return;
}
return listeners;
} // We should only use this function for:
// - BeforeInputEventPlugin
// - ChangeEventPlugin
// - SelectEventPlugin
// This is because we only process these plugins
// in the bubble phase, so we need to accumulate two
// phase event listeners (via emulation).
function accumulateTwoPhaseListeners(targetFiber, reactName) {
var captureName = reactName + 'Capture';
var listeners = [];
var instance = targetFiber; // Accumulate all instances and listeners via the target -> root path.
while (instance !== null) {
var _instance3 = instance,
stateNode = _instance3.stateNode,
tag = _instance3.tag; // Handle listeners that are on HostComponents (i.e. <div>)
if (tag === HostComponent && stateNode !== null) {
var currentTarget = stateNode;
var captureListener = getListener(instance, captureName);
if (captureListener != null) {
listeners.unshift(createDispatchListener(instance, captureListener, currentTarget));
}
var bubbleListener = getListener(instance, reactName);
if (bubbleListener != null) {
listeners.push(createDispatchListener(instance, bubbleListener, currentTarget));
}
}
instance = instance.return;
}
return listeners;
}
function getParent(inst) {
if (inst === null) {
return null;
}
do {
inst = inst.return; // TODO: If this is a HostRoot we might want to bail out.
// That is depending on if we want nested subtrees (layers) to bubble
// events to their parent. We could also go through parentNode on the
// host node but that wouldn't work for React Native and doesn't let us
// do the portal feature.
} while (inst && inst.tag !== HostComponent);
if (inst) {
return inst;
}
return null;
}
/**
* Return the lowest common ancestor of A and B, or null if they are in
* different trees.
*/
function getLowestCommonAncestor(instA, instB) {
var nodeA = instA;
var nodeB = instB;
var depthA = 0;
for (var tempA = nodeA; tempA; tempA = getParent(tempA)) {
depthA++;
}
var depthB = 0;
for (var tempB = nodeB; tempB; tempB = getParent(tempB)) {
depthB++;
} // If A is deeper, crawl up.
while (depthA - depthB > 0) {
nodeA = getParent(nodeA);
depthA--;
} // If B is deeper, crawl up.
while (depthB - depthA > 0) {
nodeB = getParent(nodeB);
depthB--;
} // Walk in lockstep until we find a match.
var depth = depthA;
while (depth--) {
if (nodeA === nodeB || nodeB !== null && nodeA === nodeB.alternate) {
return nodeA;
}
nodeA = getParent(nodeA);
nodeB = getParent(nodeB);
}
return null;
}
function accumulateEnterLeaveListenersForEvent(dispatchQueue, event, target, common, inCapturePhase) {
var registrationName = event._reactName;
var listeners = [];
var instance = target;
while (instance !== null) {
if (instance === common) {
break;
}
var _instance4 = instance,
alternate = _instance4.alternate,
stateNode = _instance4.stateNode,
tag = _instance4.tag;
if (alternate !== null && alternate === common) {
break;
}
if (tag === HostComponent && stateNode !== null) {
var currentTarget = stateNode;
if (inCapturePhase) {
var captureListener = getListener(instance, registrationName);
if (captureListener != null) {
listeners.unshift(createDispatchListener(instance, captureListener, currentTarget));
}
} else if (!inCapturePhase) {
var bubbleListener = getListener(instance, registrationName);
if (bubbleListener != null) {
listeners.push(createDispatchListener(instance, bubbleListener, currentTarget));
}
}
}
instance = instance.return;
}
if (listeners.length !== 0) {
dispatchQueue.push({
event: event,
listeners: listeners
});
}
} // We should only use this function for:
// - EnterLeaveEventPlugin
// This is because we only process this plugin
// in the bubble phase, so we need to accumulate two
// phase event listeners.
function accumulateEnterLeaveTwoPhaseListeners(dispatchQueue, leaveEvent, enterEvent, from, to) {
var common = from && to ? getLowestCommonAncestor(from, to) : null;
if (from !== null) {
accumulateEnterLeaveListenersForEvent(dispatchQueue, leaveEvent, from, common, false);
}
if (to !== null && enterEvent !== null) {
accumulateEnterLeaveListenersForEvent(dispatchQueue, enterEvent, to, common, true);
}
}
function getListenerSetKey(domEventName, capture) {
return domEventName + "__" + (capture ? 'capture' : 'bubble');
}
var didWarnInvalidHydration = false;
var DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML';
var SUPPRESS_CONTENT_EDITABLE_WARNING = 'suppressContentEditableWarning';
var SUPPRESS_HYDRATION_WARNING = 'suppressHydrationWarning';
var AUTOFOCUS = 'autoFocus';
var CHILDREN = 'children';
var STYLE = 'style';
var HTML$1 = '__html';
var warnedUnknownTags;
var validatePropertiesInDevelopment;
var warnForPropDifference;
var warnForExtraAttributes;
var warnForInvalidEventListener;
var canDiffStyleForHydrationWarning;
var normalizeHTML;
{
warnedUnknownTags = {
// There are working polyfills for <dialog>. Let people use it.
dialog: true,
// Electron ships a custom <webview> tag to display external web content in
// an isolated frame and process.
// This tag is not present in non Electron environments such as JSDom which
// is often used for testing purposes.
// @see https://electronjs.org/docs/api/webview-tag
webview: true
};
validatePropertiesInDevelopment = function (type, props) {
validateProperties(type, props);
validateProperties$1(type, props);
validateProperties$2(type, props, {
registrationNameDependencies: registrationNameDependencies,
possibleRegistrationNames: possibleRegistrationNames
});
}; // IE 11 parses & normalizes the style attribute as opposed to other
// browsers. It adds spaces and sorts the properties in some
// non-alphabetical order. Handling that would require sorting CSS
// properties in the client & server versions or applying
// `expectedStyle` to a temporary DOM node to read its `style` attribute
// normalized. Since it only affects IE, we're skipping style warnings
// in that browser completely in favor of doing all that work.
// See https://github.com/facebook/react/issues/11807
canDiffStyleForHydrationWarning = canUseDOM && !document.documentMode;
warnForPropDifference = function (propName, serverValue, clientValue) {
if (didWarnInvalidHydration) {
return;
}
var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue);
var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue);
if (normalizedServerValue === normalizedClientValue) {
return;
}
didWarnInvalidHydration = true;
error('Prop `%s` did not match. Server: %s Client: %s', propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue));
};
warnForExtraAttributes = function (attributeNames) {
if (didWarnInvalidHydration) {
return;
}
didWarnInvalidHydration = true;
var names = [];
attributeNames.forEach(function (name) {
names.push(name);
});
error('Extra attributes from the server: %s', names);
};
warnForInvalidEventListener = function (registrationName, listener) {
if (listener === false) {
error('Expected `%s` listener to be a function, instead got `false`.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', registrationName, registrationName, registrationName);
} else {
error('Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener);
}
}; // Parse the HTML and read it back to normalize the HTML string so that it
// can be used for comparison.
normalizeHTML = function (parent, html) {
// We could have created a separate document here to avoid
// re-initializing custom elements if they exist. But this breaks
// how <noscript> is being handled. So we use the same document.
// See the discussion in https://github.com/facebook/react/pull/11157.
var testElement = parent.namespaceURI === HTML_NAMESPACE ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName);
testElement.innerHTML = html;
return testElement.innerHTML;
};
} // HTML parsing normalizes CR and CRLF to LF.
// It also can turn \u0000 into \uFFFD inside attributes.
// https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream
// If we have a mismatch, it might be caused by that.
// We will still patch up in this case but not fire the warning.
var NORMALIZE_NEWLINES_REGEX = /\r\n?/g;
var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;
function normalizeMarkupForTextOrAttribute(markup) {
{
checkHtmlStringCoercion(markup);
}
var markupString = typeof markup === 'string' ? markup : '' + markup;
return markupString.replace(NORMALIZE_NEWLINES_REGEX, '\n').replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, '');
}
function checkForUnmatchedText(serverText, clientText, isConcurrentMode, shouldWarnDev) {
var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText);
var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText);
if (normalizedServerText === normalizedClientText) {
return;
}
if (shouldWarnDev) {
{
if (!didWarnInvalidHydration) {
didWarnInvalidHydration = true;
error('Text content did not match. Server: "%s" Client: "%s"', normalizedServerText, normalizedClientText);
}
}
}
if (isConcurrentMode && enableClientRenderFallbackOnTextMismatch) {
// In concurrent roots, we throw when there's a text mismatch and revert to
// client rendering, up to the nearest Suspense boundary.
throw new Error('Text content does not match server-rendered HTML.');
}
}
function getOwnerDocumentFromRootContainer(rootContainerElement) {
return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;
}
function noop() {}
function trapClickOnNonInteractiveElement(node) {
// Mobile Safari does not fire properly bubble click events on
// non-interactive elements, which means delegated click listeners do not
// fire. The workaround for this bug involves attaching an empty click
// listener on the target node.
// https://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
// Just set it using the onclick property so that we don't have to manage any
// bookkeeping for it. Not sure if we need to clear it when the listener is
// removed.
// TODO: Only do this for the relevant Safaris maybe?
node.onclick = noop;
}
function setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) {
for (var propKey in nextProps) {
if (!nextProps.hasOwnProperty(propKey)) {
continue;
}
var nextProp = nextProps[propKey];
if (propKey === STYLE) {
{
if (nextProp) {
// Freeze the next style object so that we can assume it won't be
// mutated. We have already warned for this in the past.
Object.freeze(nextProp);
}
} // Relies on `updateStylesByID` not mutating `styleUpdates`.
setValueForStyles(domElement, nextProp);
} else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
var nextHtml = nextProp ? nextProp[HTML$1] : undefined;
if (nextHtml != null) {
setInnerHTML(domElement, nextHtml);
}
} else if (propKey === CHILDREN) {
if (typeof nextProp === 'string') {
// Avoid setting initial textContent when the text is empty. In IE11 setting
// textContent on a <textarea> will cause the placeholder to not
// show within the <textarea> until it has been focused and blurred again.
// https://github.com/facebook/react/issues/6731#issuecomment-254874553
var canSetTextContent = tag !== 'textarea' || nextProp !== '';
if (canSetTextContent) {
setTextContent(domElement, nextProp);
}
} else if (typeof nextProp === 'number') {
setTextContent(domElement, '' + nextProp);
}
} else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (propKey === AUTOFOCUS) ; else if (registrationNameDependencies.hasOwnProperty(propKey)) {
if (nextProp != null) {
if ( typeof nextProp !== 'function') {
warnForInvalidEventListener(propKey, nextProp);
}
if (propKey === 'onScroll') {
listenToNonDelegatedEvent('scroll', domElement);
}
}
} else if (nextProp != null) {
setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag);
}
}
}
function updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) {
// TODO: Handle wasCustomComponentTag
for (var i = 0; i < updatePayload.length; i += 2) {
var propKey = updatePayload[i];
var propValue = updatePayload[i + 1];
if (propKey === STYLE) {
setValueForStyles(domElement, propValue);
} else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
setInnerHTML(domElement, propValue);
} else if (propKey === CHILDREN) {
setTextContent(domElement, propValue);
} else {
setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);
}
}
}
function createElement(type, props, rootContainerElement, parentNamespace) {
var isCustomComponentTag; // We create tags in the namespace of their parent container, except HTML
// tags get no namespace.
var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement);
var domElement;
var namespaceURI = parentNamespace;
if (namespaceURI === HTML_NAMESPACE) {
namespaceURI = getIntrinsicNamespace(type);
}
if (namespaceURI === HTML_NAMESPACE) {
{
isCustomComponentTag = isCustomComponent(type, props); // Should this check be gated by parent namespace? Not sure we want to
// allow <SVG> or <mATH>.
if (!isCustomComponentTag && type !== type.toLowerCase()) {
error('<%s /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', type);
}
}
if (type === 'script') {
// Create the script via .innerHTML so its "parser-inserted" flag is
// set to true and it does not execute
var div = ownerDocument.createElement('div');
div.innerHTML = '<script><' + '/script>'; // eslint-disable-line
// This is guaranteed to yield a script element.
var firstChild = div.firstChild;
domElement = div.removeChild(firstChild);
} else if (typeof props.is === 'string') {
// $FlowIssue `createElement` should be updated for Web Components
domElement = ownerDocument.createElement(type, {
is: props.is
});
} else {
// Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.
// See discussion in https://github.com/facebook/react/pull/6896
// and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
domElement = ownerDocument.createElement(type); // Normally attributes are assigned in `setInitialDOMProperties`, however the `multiple` and `size`
// attributes on `select`s needs to be added before `option`s are inserted.
// This prevents:
// - a bug where the `select` does not scroll to the correct option because singular
// `select` elements automatically pick the first item #13222
// - a bug where the `select` set the first item as selected despite the `size` attribute #14239
// See https://github.com/facebook/react/issues/13222
// and https://github.com/facebook/react/issues/14239
if (type === 'select') {
var node = domElement;
if (props.multiple) {
node.multiple = true;
} else if (props.size) {
// Setting a size greater than 1 causes a select to behave like `multiple=true`, where
// it is possible that no option is selected.
//
// This is only necessary when a select in "single selection mode".
node.size = props.size;
}
}
}
} else {
domElement = ownerDocument.createElementNS(namespaceURI, type);
}
{
if (namespaceURI === HTML_NAMESPACE) {
if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === '[object HTMLUnknownElement]' && !hasOwnProperty.call(warnedUnknownTags, type)) {
warnedUnknownTags[type] = true;
error('The tag <%s> is unrecognized in this browser. ' + 'If you meant to render a React component, start its name with ' + 'an uppercase letter.', type);
}
}
}
return domElement;
}
function createTextNode(text, rootContainerElement) {
return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text);
}
function setInitialProperties(domElement, tag, rawProps, rootContainerElement) {
var isCustomComponentTag = isCustomComponent(tag, rawProps);
{
validatePropertiesInDevelopment(tag, rawProps);
} // TODO: Make sure that we check isMounted before firing any of these events.
var props;
switch (tag) {
case 'dialog':
listenToNonDelegatedEvent('cancel', domElement);
listenToNonDelegatedEvent('close', domElement);
props = rawProps;
break;
case 'iframe':
case 'object':
case 'embed':
// We listen to this event in case to ensure emulated bubble
// listeners still fire for the load event.
listenToNonDelegatedEvent('load', domElement);
props = rawProps;
break;
case 'video':
case 'audio':
// We listen to these events in case to ensure emulated bubble
// listeners still fire for all the media events.
for (var i = 0; i < mediaEventTypes.length; i++) {
listenToNonDelegatedEvent(mediaEventTypes[i], domElement);
}
props = rawProps;
break;
case 'source':
// We listen to this event in case to ensure emulated bubble
// listeners still fire for the error event.
listenToNonDelegatedEvent('error', domElement);
props = rawProps;
break;
case 'img':
case 'image':
case 'link':
// We listen to these events in case to ensure emulated bubble
// listeners still fire for error and load events.
listenToNonDelegatedEvent('error', domElement);
listenToNonDelegatedEvent('load', domElement);
props = rawProps;
break;
case 'details':
// We listen to this event in case to ensure emulated bubble
// listeners still fire for the toggle event.
listenToNonDelegatedEvent('toggle', domElement);
props = rawProps;
break;
case 'input':
initWrapperState(domElement, rawProps);
props = getHostProps(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid', domElement);
break;
case 'option':
validateProps(domElement, rawProps);
props = rawProps;
break;
case 'select':
initWrapperState$1(domElement, rawProps);
props = getHostProps$1(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid', domElement);
break;
case 'textarea':
initWrapperState$2(domElement, rawProps);
props = getHostProps$2(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid', domElement);
break;
default:
props = rawProps;
}
assertValidProps(tag, props);
setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag);
switch (tag) {
case 'input':
// TODO: Make sure we check if this is still unmounted or do any clean
// up necessary since we never stop tracking anymore.
track(domElement);
postMountWrapper(domElement, rawProps, false);
break;
case 'textarea':
// TODO: Make sure we check if this is still unmounted or do any clean
// up necessary since we never stop tracking anymore.
track(domElement);
postMountWrapper$3(domElement);
break;
case 'option':
postMountWrapper$1(domElement, rawProps);
break;
case 'select':
postMountWrapper$2(domElement, rawProps);
break;
default:
if (typeof props.onClick === 'function') {
// TODO: This cast may not be sound for SVG, MathML or custom elements.
trapClickOnNonInteractiveElement(domElement);
}
break;
}
} // Calculate the diff between the two objects.
function diffProperties(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) {
{
validatePropertiesInDevelopment(tag, nextRawProps);
}
var updatePayload = null;
var lastProps;
var nextProps;
switch (tag) {
case 'input':
lastProps = getHostProps(domElement, lastRawProps);
nextProps = getHostProps(domElement, nextRawProps);
updatePayload = [];
break;
case 'select':
lastProps = getHostProps$1(domElement, lastRawProps);
nextProps = getHostProps$1(domElement, nextRawProps);
updatePayload = [];
break;
case 'textarea':
lastProps = getHostProps$2(domElement, lastRawProps);
nextProps = getHostProps$2(domElement, nextRawProps);
updatePayload = [];
break;
default:
lastProps = lastRawProps;
nextProps = nextRawProps;
if (typeof lastProps.onClick !== 'function' && typeof nextProps.onClick === 'function') {
// TODO: This cast may not be sound for SVG, MathML or custom elements.
trapClickOnNonInteractiveElement(domElement);
}
break;
}
assertValidProps(tag, nextProps);
var propKey;
var styleName;
var styleUpdates = null;
for (propKey in lastProps) {
if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {
continue;
}
if (propKey === STYLE) {
var lastStyle = lastProps[propKey];
for (styleName in lastStyle) {
if (lastStyle.hasOwnProperty(styleName)) {
if (!styleUpdates) {
styleUpdates = {};
}
styleUpdates[styleName] = '';
}
}
} else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) ; else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (propKey === AUTOFOCUS) ; else if (registrationNameDependencies.hasOwnProperty(propKey)) {
// This is a special case. If any listener updates we need to ensure
// that the "current" fiber pointer gets updated so we need a commit
// to update this element.
if (!updatePayload) {
updatePayload = [];
}
} else {
// For all other deleted properties we add it to the queue. We use
// the allowed property list in the commit phase instead.
(updatePayload = updatePayload || []).push(propKey, null);
}
}
for (propKey in nextProps) {
var nextProp = nextProps[propKey];
var lastProp = lastProps != null ? lastProps[propKey] : undefined;
if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {
continue;
}
if (propKey === STYLE) {
{
if (nextProp) {
// Freeze the next style object so that we can assume it won't be
// mutated. We have already warned for this in the past.
Object.freeze(nextProp);
}
}
if (lastProp) {
// Unset styles on `lastProp` but not on `nextProp`.
for (styleName in lastProp) {
if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
if (!styleUpdates) {
styleUpdates = {};
}
styleUpdates[styleName] = '';
}
} // Update styles that changed since `lastProp`.
for (styleName in nextProp) {
if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
if (!styleUpdates) {
styleUpdates = {};
}
styleUpdates[styleName] = nextProp[styleName];
}
}
} else {
// Relies on `updateStylesByID` not mutating `styleUpdates`.
if (!styleUpdates) {
if (!updatePayload) {
updatePayload = [];
}
updatePayload.push(propKey, styleUpdates);
}
styleUpdates = nextProp;
}
} else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
var nextHtml = nextProp ? nextProp[HTML$1] : undefined;
var lastHtml = lastProp ? lastProp[HTML$1] : undefined;
if (nextHtml != null) {
if (lastHtml !== nextHtml) {
(updatePayload = updatePayload || []).push(propKey, nextHtml);
}
}
} else if (propKey === CHILDREN) {
if (typeof nextProp === 'string' || typeof nextProp === 'number') {
(updatePayload = updatePayload || []).push(propKey, '' + nextProp);
}
} else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (registrationNameDependencies.hasOwnProperty(propKey)) {
if (nextProp != null) {
// We eagerly listen to this even though we haven't committed yet.
if ( typeof nextProp !== 'function') {
warnForInvalidEventListener(propKey, nextProp);
}
if (propKey === 'onScroll') {
listenToNonDelegatedEvent('scroll', domElement);
}
}
if (!updatePayload && lastProp !== nextProp) {
// This is a special case. If any listener updates we need to ensure
// that the "current" props pointer gets updated so we need a commit
// to update this element.
updatePayload = [];
}
} else {
// For any other property we always add it to the queue and then we
// filter it out using the allowed property list during the commit.
(updatePayload = updatePayload || []).push(propKey, nextProp);
}
}
if (styleUpdates) {
{
validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE]);
}
(updatePayload = updatePayload || []).push(STYLE, styleUpdates);
}
return updatePayload;
} // Apply the diff.
function updateProperties(domElement, updatePayload, tag, lastRawProps, nextRawProps) {
// Update checked *before* name.
// In the middle of an update, it is possible to have multiple checked.
// When a checked radio tries to change name, browser makes another radio's checked false.
if (tag === 'input' && nextRawProps.type === 'radio' && nextRawProps.name != null) {
updateChecked(domElement, nextRawProps);
}
var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
var isCustomComponentTag = isCustomComponent(tag, nextRawProps); // Apply the diff.
updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag); // TODO: Ensure that an update gets scheduled if any of the special props
// changed.
switch (tag) {
case 'input':
// Update the wrapper around inputs *after* updating props. This has to
// happen after `updateDOMProperties`. Otherwise HTML5 input validations
// raise warnings and prevent the new value from being assigned.
updateWrapper(domElement, nextRawProps);
break;
case 'textarea':
updateWrapper$1(domElement, nextRawProps);
break;
case 'select':
// <select> value update needs to occur after <option> children
// reconciliation
postUpdateWrapper(domElement, nextRawProps);
break;
}
}
function getPossibleStandardName(propName) {
{
var lowerCasedName = propName.toLowerCase();
if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) {
return null;
}
return possibleStandardNames[lowerCasedName] || null;
}
}
function diffHydratedProperties(domElement, tag, rawProps, parentNamespace, rootContainerElement, isConcurrentMode, shouldWarnDev) {
var isCustomComponentTag;
var extraAttributeNames;
{
isCustomComponentTag = isCustomComponent(tag, rawProps);
validatePropertiesInDevelopment(tag, rawProps);
} // TODO: Make sure that we check isMounted before firing any of these events.
switch (tag) {
case 'dialog':
listenToNonDelegatedEvent('cancel', domElement);
listenToNonDelegatedEvent('close', domElement);
break;
case 'iframe':
case 'object':
case 'embed':
// We listen to this event in case to ensure emulated bubble
// listeners still fire for the load event.
listenToNonDelegatedEvent('load', domElement);
break;
case 'video':
case 'audio':
// We listen to these events in case to ensure emulated bubble
// listeners still fire for all the media events.
for (var i = 0; i < mediaEventTypes.length; i++) {
listenToNonDelegatedEvent(mediaEventTypes[i], domElement);
}
break;
case 'source':
// We listen to this event in case to ensure emulated bubble
// listeners still fire for the error event.
listenToNonDelegatedEvent('error', domElement);
break;
case 'img':
case 'image':
case 'link':
// We listen to these events in case to ensure emulated bubble
// listeners still fire for error and load events.
listenToNonDelegatedEvent('error', domElement);
listenToNonDelegatedEvent('load', domElement);
break;
case 'details':
// We listen to this event in case to ensure emulated bubble
// listeners still fire for the toggle event.
listenToNonDelegatedEvent('toggle', domElement);
break;
case 'input':
initWrapperState(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid', domElement);
break;
case 'option':
validateProps(domElement, rawProps);
break;
case 'select':
initWrapperState$1(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid', domElement);
break;
case 'textarea':
initWrapperState$2(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
// listeners still fire for the invalid event.
listenToNonDelegatedEvent('invalid', domElement);
break;
}
assertValidProps(tag, rawProps);
{
extraAttributeNames = new Set();
var attributes = domElement.attributes;
for (var _i = 0; _i < attributes.length; _i++) {
var name = attributes[_i].name.toLowerCase();
switch (name) {
// Controlled attributes are not validated
// TODO: Only ignore them on controlled tags.
case 'value':
break;
case 'checked':
break;
case 'selected':
break;
default:
// Intentionally use the original name.
// See discussion in https://github.com/facebook/react/pull/10676.
extraAttributeNames.add(attributes[_i].name);
}
}
}
var updatePayload = null;
for (var propKey in rawProps) {
if (!rawProps.hasOwnProperty(propKey)) {
continue;
}
var nextProp = rawProps[propKey];
if (propKey === CHILDREN) {
// For text content children we compare against textContent. This
// might match additional HTML that is hidden when we read it using
// textContent. E.g. "foo" will match "f<span>oo</span>" but that still
// satisfies our requirement. Our requirement is not to produce perfect
// HTML and attributes. Ideally we should preserve structure but it's
// ok not to if the visible content is still enough to indicate what
// even listeners these nodes might be wired up to.
// TODO: Warn if there is more than a single textNode as a child.
// TODO: Should we use domElement.firstChild.nodeValue to compare?
if (typeof nextProp === 'string') {
if (domElement.textContent !== nextProp) {
if (rawProps[SUPPRESS_HYDRATION_WARNING] !== true) {
checkForUnmatchedText(domElement.textContent, nextProp, isConcurrentMode, shouldWarnDev);
}
updatePayload = [CHILDREN, nextProp];
}
} else if (typeof nextProp === 'number') {
if (domElement.textContent !== '' + nextProp) {
if (rawProps[SUPPRESS_HYDRATION_WARNING] !== true) {
checkForUnmatchedText(domElement.textContent, nextProp, isConcurrentMode, shouldWarnDev);
}
updatePayload = [CHILDREN, '' + nextProp];
}
}
} else if (registrationNameDependencies.hasOwnProperty(propKey)) {
if (nextProp != null) {
if ( typeof nextProp !== 'function') {
warnForInvalidEventListener(propKey, nextProp);
}
if (propKey === 'onScroll') {
listenToNonDelegatedEvent('scroll', domElement);
}
}
} else if (shouldWarnDev && true && // Convince Flow we've calculated it (it's DEV-only in this method.)
typeof isCustomComponentTag === 'boolean') {
// Validate that the properties correspond to their expected values.
var serverValue = void 0;
var propertyInfo = isCustomComponentTag && enableCustomElementPropertySupport ? null : getPropertyInfo(propKey);
if (rawProps[SUPPRESS_HYDRATION_WARNING] === true) ; else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING || // Controlled attributes are not validated
// TODO: Only ignore them on controlled tags.
propKey === 'value' || propKey === 'checked' || propKey === 'selected') ; else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
var serverHTML = domElement.innerHTML;
var nextHtml = nextProp ? nextProp[HTML$1] : undefined;
if (nextHtml != null) {
var expectedHTML = normalizeHTML(domElement, nextHtml);
if (expectedHTML !== serverHTML) {
warnForPropDifference(propKey, serverHTML, expectedHTML);
}
}
} else if (propKey === STYLE) {
// $FlowFixMe - Should be inferred as not undefined.
extraAttributeNames.delete(propKey);
if (canDiffStyleForHydrationWarning) {
var expectedStyle = createDangerousStringForStyles(nextProp);
serverValue = domElement.getAttribute('style');
if (expectedStyle !== serverValue) {
warnForPropDifference(propKey, serverValue, expectedStyle);
}
}
} else if (isCustomComponentTag && !enableCustomElementPropertySupport) {
// $FlowFixMe - Should be inferred as not undefined.
extraAttributeNames.delete(propKey.toLowerCase());
serverValue = getValueForAttribute(domElement, propKey, nextProp);
if (nextProp !== serverValue) {
warnForPropDifference(propKey, serverValue, nextProp);
}
} else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) {
var isMismatchDueToBadCasing = false;
if (propertyInfo !== null) {
// $FlowFixMe - Should be inferred as not undefined.
extraAttributeNames.delete(propertyInfo.attributeName);
serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo);
} else {
var ownNamespace = parentNamespace;
if (ownNamespace === HTML_NAMESPACE) {
ownNamespace = getIntrinsicNamespace(tag);
}
if (ownNamespace === HTML_NAMESPACE) {
// $FlowFixMe - Should be inferred as not undefined.
extraAttributeNames.delete(propKey.toLowerCase());
} else {
var standardName = getPossibleStandardName(propKey);
if (standardName !== null && standardName !== propKey) {
// If an SVG prop is supplied with bad casing, it will
// be successfully parsed from HTML, but will produce a mismatch
// (and would be incorrectly rendered on the client).
// However, we already warn about bad casing elsewhere.
// So we'll skip the misleading extra mismatch warning in this case.
isMismatchDueToBadCasing = true; // $FlowFixMe - Should be inferred as not undefined.
extraAttributeNames.delete(standardName);
} // $FlowFixMe - Should be inferred as not undefined.
extraAttributeNames.delete(propKey);
}
serverValue = getValueForAttribute(domElement, propKey, nextProp);
}
var dontWarnCustomElement = enableCustomElementPropertySupport ;
if (!dontWarnCustomElement && nextProp !== serverValue && !isMismatchDueToBadCasing) {
warnForPropDifference(propKey, serverValue, nextProp);
}
}
}
}
{
if (shouldWarnDev) {
if ( // $FlowFixMe - Should be inferred as not undefined.
extraAttributeNames.size > 0 && rawProps[SUPPRESS_HYDRATION_WARNING] !== true) {
// $FlowFixMe - Should be inferred as not undefined.
warnForExtraAttributes(extraAttributeNames);
}
}
}
switch (tag) {
case 'input':
// TODO: Make sure we check if this is still unmounted or do any clean
// up necessary since we never stop tracking anymore.
track(domElement);
postMountWrapper(domElement, rawProps, true);
break;
case 'textarea':
// TODO: Make sure we check if this is still unmounted or do any clean
// up necessary since we never stop tracking anymore.
track(domElement);
postMountWrapper$3(domElement);
break;
case 'select':
case 'option':
// For input and textarea we current always set the value property at
// post mount to force it to diverge from attributes. However, for
// option and select we don't quite do the same thing and select
// is not resilient to the DOM state changing so we don't do that here.
// TODO: Consider not doing this for input and textarea.
break;
default:
if (typeof rawProps.onClick === 'function') {
// TODO: This cast may not be sound for SVG, MathML or custom elements.
trapClickOnNonInteractiveElement(domElement);
}
break;
}
return updatePayload;
}
function diffHydratedText(textNode, text, isConcurrentMode) {
var isDifferent = textNode.nodeValue !== text;
return isDifferent;
}
function warnForDeletedHydratableElement(parentNode, child) {
{
if (didWarnInvalidHydration) {
return;
}
didWarnInvalidHydration = true;
error('Did not expect server HTML to contain a <%s> in <%s>.', child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase());
}
}
function warnForDeletedHydratableText(parentNode, child) {
{
if (didWarnInvalidHydration) {
return;
}
didWarnInvalidHydration = true;
error('Did not expect server HTML to contain the text node "%s" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase());
}
}
function warnForInsertedHydratedElement(parentNode, tag, props) {
{
if (didWarnInvalidHydration) {
return;
}
didWarnInvalidHydration = true;
error('Expected server HTML to contain a matching <%s> in <%s>.', tag, parentNode.nodeName.toLowerCase());
}
}
function warnForInsertedHydratedText(parentNode, text) {
{
if (text === '') {
// We expect to insert empty text nodes since they're not represented in
// the HTML.
// TODO: Remove this special case if we can just avoid inserting empty
// text nodes.
return;
}
if (didWarnInvalidHydration) {
return;
}
didWarnInvalidHydration = true;
error('Expected server HTML to contain a matching text node for "%s" in <%s>.', text, parentNode.nodeName.toLowerCase());
}
}
function restoreControlledState$3(domElement, tag, props) {
switch (tag) {
case 'input':
restoreControlledState(domElement, props);
return;
case 'textarea':
restoreControlledState$2(domElement, props);
return;
case 'select':
restoreControlledState$1(domElement, props);
return;
}
}
var validateDOMNesting = function () {};
var updatedAncestorInfo = function () {};
{
// This validation code was written based on the HTML5 parsing spec:
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
//
// Note: this does not catch all invalid nesting, nor does it try to (as it's
// not clear what practical benefit doing so provides); instead, we warn only
// for cases where the parser will give a parse tree differing from what React
// intended. For example, <b><div></div></b> is invalid but we don't warn
// because it still parses correctly; we do warn for other cases like nested
// <p> tags where the beginning of the second element implicitly closes the
// first, causing a confusing mess.
// https://html.spec.whatwg.org/multipage/syntax.html#special
var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
// TODO: Distinguish by namespace here -- for <title>, including it here
// errs on the side of fewer warnings
'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];
var emptyAncestorInfo = {
current: null,
formTag: null,
aTagInScope: null,
buttonTagInScope: null,
nobrTagInScope: null,
pTagInButtonScope: null,
listItemTagAutoclosing: null,
dlItemTagAutoclosing: null
};
updatedAncestorInfo = function (oldInfo, tag) {
var ancestorInfo = assign({}, oldInfo || emptyAncestorInfo);
var info = {
tag: tag
};
if (inScopeTags.indexOf(tag) !== -1) {
ancestorInfo.aTagInScope = null;
ancestorInfo.buttonTagInScope = null;
ancestorInfo.nobrTagInScope = null;
}
if (buttonScopeTags.indexOf(tag) !== -1) {
ancestorInfo.pTagInButtonScope = null;
} // See rules for 'li', 'dd', 'dt' start tags in
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {
ancestorInfo.listItemTagAutoclosing = null;
ancestorInfo.dlItemTagAutoclosing = null;
}
ancestorInfo.current = info;
if (tag === 'form') {
ancestorInfo.formTag = info;
}
if (tag === 'a') {
ancestorInfo.aTagInScope = info;
}
if (tag === 'button') {
ancestorInfo.buttonTagInScope = info;
}
if (tag === 'nobr') {
ancestorInfo.nobrTagInScope = info;
}
if (tag === 'p') {
ancestorInfo.pTagInButtonScope = info;
}
if (tag === 'li') {
ancestorInfo.listItemTagAutoclosing = info;
}
if (tag === 'dd' || tag === 'dt') {
ancestorInfo.dlItemTagAutoclosing = info;
}
return ancestorInfo;
};
/**
* Returns whether
*/
var isTagValidWithParent = function (tag, parentTag) {
// First, let's check if we're in an unusual parsing mode...
switch (parentTag) {
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
case 'select':
return tag === 'option' || tag === 'optgroup' || tag === '#text';
case 'optgroup':
return tag === 'option' || tag === '#text';
// Strictly speaking, seeing an <option> doesn't mean we're in a <select>
// but
case 'option':
return tag === '#text';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
// No special behavior since these rules fall back to "in body" mode for
// all except special table nodes which cause bad parsing behavior anyway.
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
case 'tr':
return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
case 'tbody':
case 'thead':
case 'tfoot':
return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
case 'colgroup':
return tag === 'col' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
case 'table':
return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
case 'head':
return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
case 'html':
return tag === 'head' || tag === 'body' || tag === 'frameset';
case 'frameset':
return tag === 'frame';
case '#document':
return tag === 'html';
} // Probably in the "in body" parsing mode, so we outlaw only tag combos
// where the parsing rules cause implicit opens or closes to be added.
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
switch (tag) {
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6':
return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';
case 'rp':
case 'rt':
return impliedEndTags.indexOf(parentTag) === -1;
case 'body':
case 'caption':
case 'col':
case 'colgroup':
case 'frameset':
case 'frame':
case 'head':
case 'html':
case 'tbody':
case 'td':
case 'tfoot':
case 'th':
case 'thead':
case 'tr':
// These tags are only valid with a few parents that have special child
// parsing rules -- if we're down here, then none of those matched and
// so we allow it only if we don't know what the parent is, as all other
// cases are invalid.
return parentTag == null;
}
return true;
};
/**
* Returns whether
*/
var findInvalidAncestorForTag = function (tag, ancestorInfo) {
switch (tag) {
case 'address':
case 'article':
case 'aside':
case 'blockquote':
case 'center':
case 'details':
case 'dialog':
case 'dir':
case 'div':
case 'dl':
case 'fieldset':
case 'figcaption':
case 'figure':
case 'footer':
case 'header':
case 'hgroup':
case 'main':
case 'menu':
case 'nav':
case 'ol':
case 'p':
case 'section':
case 'summary':
case 'ul':
case 'pre':
case 'listing':
case 'table':
case 'hr':
case 'xmp':
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6':
return ancestorInfo.pTagInButtonScope;
case 'form':
return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
case 'li':
return ancestorInfo.listItemTagAutoclosing;
case 'dd':
case 'dt':
return ancestorInfo.dlItemTagAutoclosing;
case 'button':
return ancestorInfo.buttonTagInScope;
case 'a':
// Spec says something about storing a list of markers, but it sounds
// equivalent to this check.
return ancestorInfo.aTagInScope;
case 'nobr':
return ancestorInfo.nobrTagInScope;
}
return null;
};
var didWarn$1 = {};
validateDOMNesting = function (childTag, childText, ancestorInfo) {
ancestorInfo = ancestorInfo || emptyAncestorInfo;
var parentInfo = ancestorInfo.current;
var parentTag = parentInfo && parentInfo.tag;
if (childText != null) {
if (childTag != null) {
error('validateDOMNesting: when childText is passed, childTag should be null');
}
childTag = '#text';
}
var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
var invalidParentOrAncestor = invalidParent || invalidAncestor;
if (!invalidParentOrAncestor) {
return;
}
var ancestorTag = invalidParentOrAncestor.tag;
var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag;
if (didWarn$1[warnKey]) {
return;
}
didWarn$1[warnKey] = true;
var tagDisplayName = childTag;
var whitespaceInfo = '';
if (childTag === '#text') {
if (/\S/.test(childText)) {
tagDisplayName = 'Text nodes';
} else {
tagDisplayName = 'Whitespace text nodes';
whitespaceInfo = " Make sure you don't have any extra whitespace between tags on " + 'each line of your source code.';
}
} else {
tagDisplayName = '<' + childTag + '>';
}
if (invalidParent) {
var info = '';
if (ancestorTag === 'table' && childTag === 'tr') {
info += ' Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by ' + 'the browser.';
}
error('validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s', tagDisplayName, ancestorTag, whitespaceInfo, info);
} else {
error('validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.', tagDisplayName, ancestorTag);
}
};
}
var SUPPRESS_HYDRATION_WARNING$1 = 'suppressHydrationWarning';
var SUSPENSE_START_DATA = '$';
var SUSPENSE_END_DATA = '/$';
var SUSPENSE_PENDING_START_DATA = '$?';
var SUSPENSE_FALLBACK_START_DATA = '$!';
var STYLE$1 = 'style';
var eventsEnabled = null;
var selectionInformation = null;
function getRootHostContext(rootContainerInstance) {
var type;
var namespace;
var nodeType = rootContainerInstance.nodeType;
switch (nodeType) {
case DOCUMENT_NODE:
case DOCUMENT_FRAGMENT_NODE:
{
type = nodeType === DOCUMENT_NODE ? '#document' : '#fragment';
var root = rootContainerInstance.documentElement;
namespace = root ? root.namespaceURI : getChildNamespace(null, '');
break;
}
default:
{
var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance;
var ownNamespace = container.namespaceURI || null;
type = container.tagName;
namespace = getChildNamespace(ownNamespace, type);
break;
}
}
{
var validatedTag = type.toLowerCase();
var ancestorInfo = updatedAncestorInfo(null, validatedTag);
return {
namespace: namespace,
ancestorInfo: ancestorInfo
};
}
}
function getChildHostContext(parentHostContext, type, rootContainerInstance) {
{
var parentHostContextDev = parentHostContext;
var namespace = getChildNamespace(parentHostContextDev.namespace, type);
var ancestorInfo = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type);
return {
namespace: namespace,
ancestorInfo: ancestorInfo
};
}
}
function getPublicInstance(instance) {
return instance;
}
function prepareForCommit(containerInfo) {
eventsEnabled = isEnabled();
selectionInformation = getSelectionInformation();
var activeInstance = null;
setEnabled(false);
return activeInstance;
}
function resetAfterCommit(containerInfo) {
restoreSelection(selectionInformation);
setEnabled(eventsEnabled);
eventsEnabled = null;
selectionInformation = null;
}
function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
var parentNamespace;
{
// TODO: take namespace into account when validating.
var hostContextDev = hostContext;
validateDOMNesting(type, null, hostContextDev.ancestorInfo);
if (typeof props.children === 'string' || typeof props.children === 'number') {
var string = '' + props.children;
var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
validateDOMNesting(null, string, ownAncestorInfo);
}
parentNamespace = hostContextDev.namespace;
}
var domElement = createElement(type, props, rootContainerInstance, parentNamespace);
precacheFiberNode(internalInstanceHandle, domElement);
updateFiberProps(domElement, props);
return domElement;
}
function appendInitialChild(parentInstance, child) {
parentInstance.appendChild(child);
}
function finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) {
setInitialProperties(domElement, type, props, rootContainerInstance);
switch (type) {
case 'button':
case 'input':
case 'select':
case 'textarea':
return !!props.autoFocus;
case 'img':
return true;
default:
return false;
}
}
function prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) {
{
var hostContextDev = hostContext;
if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === 'string' || typeof newProps.children === 'number')) {
var string = '' + newProps.children;
var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
validateDOMNesting(null, string, ownAncestorInfo);
}
}
return diffProperties(domElement, type, oldProps, newProps);
}
function shouldSetTextContent(type, props) {
return type === 'textarea' || type === 'noscript' || typeof props.children === 'string' || typeof props.children === 'number' || typeof props.dangerouslySetInnerHTML === 'object' && props.dangerouslySetInnerHTML !== null && props.dangerouslySetInnerHTML.__html != null;
}
function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {
{
var hostContextDev = hostContext;
validateDOMNesting(null, text, hostContextDev.ancestorInfo);
}
var textNode = createTextNode(text, rootContainerInstance);
precacheFiberNode(internalInstanceHandle, textNode);
return textNode;
}
function getCurrentEventPriority() {
var currentEvent = window.event;
if (currentEvent === undefined) {
return DefaultEventPriority;
}
return getEventPriority(currentEvent.type);
}
// if a component just imports ReactDOM (e.g. for findDOMNode).
// Some environments might not have setTimeout or clearTimeout.
var scheduleTimeout = typeof setTimeout === 'function' ? setTimeout : undefined;
var cancelTimeout = typeof clearTimeout === 'function' ? clearTimeout : undefined;
var noTimeout = -1;
var localPromise = typeof Promise === 'function' ? Promise : undefined; // -------------------
var scheduleMicrotask = typeof queueMicrotask === 'function' ? queueMicrotask : typeof localPromise !== 'undefined' ? function (callback) {
return localPromise.resolve(null).then(callback).catch(handleErrorInNextTick);
} : scheduleTimeout; // TODO: Determine the best fallback here.
function handleErrorInNextTick(error) {
setTimeout(function () {
throw error;
});
} // -------------------
function commitMount(domElement, type, newProps, internalInstanceHandle) {
// Despite the naming that might imply otherwise, this method only
// fires if there is an `Update` effect scheduled during mounting.
// This happens if `finalizeInitialChildren` returns `true` (which it
// does to implement the `autoFocus` attribute on the client). But
// there are also other cases when this might happen (such as patching
// up text content during hydration mismatch). So we'll check this again.
switch (type) {
case 'button':
case 'input':
case 'select':
case 'textarea':
if (newProps.autoFocus) {
domElement.focus();
}
return;
case 'img':
{
if (newProps.src) {
domElement.src = newProps.src;
}
return;
}
}
}
function commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) {
// Apply the diff to the DOM node.
updateProperties(domElement, updatePayload, type, oldProps, newProps); // Update the props handle so that we know which props are the ones with
// with current event handlers.
updateFiberProps(domElement, newProps);
}
function resetTextContent(domElement) {
setTextContent(domElement, '');
}
function commitTextUpdate(textInstance, oldText, newText) {
textInstance.nodeValue = newText;
}
function appendChild(parentInstance, child) {
parentInstance.appendChild(child);
}
function appendChildToContainer(container, child) {
var parentNode;
if (container.nodeType === COMMENT_NODE) {
parentNode = container.parentNode;
parentNode.insertBefore(child, container);
} else {
parentNode = container;
parentNode.appendChild(child);
} // This container might be used for a portal.
// If something inside a portal is clicked, that click should bubble
// through the React tree. However, on Mobile Safari the click would
// never bubble through the *DOM* tree unless an ancestor with onclick
// event exists. So we wouldn't see it and dispatch it.
// This is why we ensure that non React root containers have inline onclick
// defined.
// https://github.com/facebook/react/issues/11918
var reactRootContainer = container._reactRootContainer;
if ((reactRootContainer === null || reactRootContainer === undefined) && parentNode.onclick === null) {
// TODO: This cast may not be sound for SVG, MathML or custom elements.
trapClickOnNonInteractiveElement(parentNode);
}
}
function insertBefore(parentInstance, child, beforeChild) {
parentInstance.insertBefore(child, beforeChild);
}
function insertInContainerBefore(container, child, beforeChild) {
if (container.nodeType === COMMENT_NODE) {
container.parentNode.insertBefore(child, beforeChild);
} else {
container.insertBefore(child, beforeChild);
}
}
function removeChild(parentInstance, child) {
parentInstance.removeChild(child);
}
function removeChildFromContainer(container, child) {
if (container.nodeType === COMMENT_NODE) {
container.parentNode.removeChild(child);
} else {
container.removeChild(child);
}
}
function clearSuspenseBoundary(parentInstance, suspenseInstance) {
var node = suspenseInstance; // Delete all nodes within this suspense boundary.
// There might be nested nodes so we need to keep track of how
// deep we are and only break out when we're back on top.
var depth = 0;
do {
var nextNode = node.nextSibling;
parentInstance.removeChild(node);
if (nextNode && nextNode.nodeType === COMMENT_NODE) {
var data = nextNode.data;
if (data === SUSPENSE_END_DATA) {
if (depth === 0) {
parentInstance.removeChild(nextNode); // Retry if any event replaying was blocked on this.
retryIfBlockedOn(suspenseInstance);
return;
} else {
depth--;
}
} else if (data === SUSPENSE_START_DATA || data === SUSPENSE_PENDING_START_DATA || data === SUSPENSE_FALLBACK_START_DATA) {
depth++;
}
}
node = nextNode;
} while (node); // TODO: Warn, we didn't find the end comment boundary.
// Retry if any event replaying was blocked on this.
retryIfBlockedOn(suspenseInstance);
}
function clearSuspenseBoundaryFromContainer(container, suspenseInstance) {
if (container.nodeType === COMMENT_NODE) {
clearSuspenseBoundary(container.parentNode, suspenseInstance);
} else if (container.nodeType === ELEMENT_NODE) {
clearSuspenseBoundary(container, suspenseInstance);
} // Retry if any event replaying was blocked on this.
retryIfBlockedOn(container);
}
function hideInstance(instance) {
// TODO: Does this work for all element types? What about MathML? Should we
// pass host context to this method?
instance = instance;
var style = instance.style;
if (typeof style.setProperty === 'function') {
style.setProperty('display', 'none', 'important');
} else {
style.display = 'none';
}
}
function hideTextInstance(textInstance) {
textInstance.nodeValue = '';
}
function unhideInstance(instance, props) {
instance = instance;
var styleProp = props[STYLE$1];
var display = styleProp !== undefined && styleProp !== null && styleProp.hasOwnProperty('display') ? styleProp.display : null;
instance.style.display = dangerousStyleValue('display', display);
}
function unhideTextInstance(textInstance, text) {
textInstance.nodeValue = text;
}
function clearContainer(container) {
if (container.nodeType === ELEMENT_NODE) {
container.textContent = '';
} else if (container.nodeType === DOCUMENT_NODE) {
if (container.documentElement) {
container.removeChild(container.documentElement);
}
}
} // -------------------
function canHydrateInstance(instance, type, props) {
if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) {
return null;
} // This has now been refined to an element node.
return instance;
}
function canHydrateTextInstance(instance, text) {
if (text === '' || instance.nodeType !== TEXT_NODE) {
// Empty strings are not parsed by HTML so there won't be a correct match here.
return null;
} // This has now been refined to a text node.
return instance;
}
function canHydrateSuspenseInstance(instance) {
if (instance.nodeType !== COMMENT_NODE) {
// Empty strings are not parsed by HTML so there won't be a correct match here.
return null;
} // This has now been refined to a suspense node.
return instance;
}
function isSuspenseInstancePending(instance) {
return instance.data === SUSPENSE_PENDING_START_DATA;
}
function isSuspenseInstanceFallback(instance) {
return instance.data === SUSPENSE_FALLBACK_START_DATA;
}
function getSuspenseInstanceFallbackErrorDetails(instance) {
var dataset = instance.nextSibling && instance.nextSibling.dataset;
var digest, message, stack;
if (dataset) {
digest = dataset.dgst;
{
message = dataset.msg;
stack = dataset.stck;
}
}
{
return {
message: message,
digest: digest,
stack: stack
};
} // let value = {message: undefined, hash: undefined};
// const nextSibling = instance.nextSibling;
// if (nextSibling) {
// const dataset = ((nextSibling: any): HTMLTemplateElement).dataset;
// value.message = dataset.msg;
// value.hash = dataset.hash;
// if (true) {
// value.stack = dataset.stack;
// }
// }
// return value;
}
function registerSuspenseInstanceRetry(instance, callback) {
instance._reactRetry = callback;
}
function getNextHydratable(node) {
// Skip non-hydratable nodes.
for (; node != null; node = node.nextSibling) {
var nodeType = node.nodeType;
if (nodeType === ELEMENT_NODE || nodeType === TEXT_NODE) {
break;
}
if (nodeType === COMMENT_NODE) {
var nodeData = node.data;
if (nodeData === SUSPENSE_START_DATA || nodeData === SUSPENSE_FALLBACK_START_DATA || nodeData === SUSPENSE_PENDING_START_DATA) {
break;
}
if (nodeData === SUSPENSE_END_DATA) {
return null;
}
}
}
return node;
}
function getNextHydratableSibling(instance) {
return getNextHydratable(instance.nextSibling);
}
function getFirstHydratableChild(parentInstance) {
return getNextHydratable(parentInstance.firstChild);
}
function getFirstHydratableChildWithinContainer(parentContainer) {
return getNextHydratable(parentContainer.firstChild);
}
function getFirstHydratableChildWithinSuspenseInstance(parentInstance) {
return getNextHydratable(parentInstance.nextSibling);
}
function hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle, shouldWarnDev) {
precacheFiberNode(internalInstanceHandle, instance); // TODO: Possibly defer this until the commit phase where all the events
// get attached.
updateFiberProps(instance, props);
var parentNamespace;
{
var hostContextDev = hostContext;
parentNamespace = hostContextDev.namespace;
} // TODO: Temporary hack to check if we're in a concurrent root. We can delete
// when the legacy root API is removed.
var isConcurrentMode = (internalInstanceHandle.mode & ConcurrentMode) !== NoMode;
return diffHydratedProperties(instance, type, props, parentNamespace, rootContainerInstance, isConcurrentMode, shouldWarnDev);
}
function hydrateTextInstance(textInstance, text, internalInstanceHandle, shouldWarnDev) {
precacheFiberNode(internalInstanceHandle, textInstance); // TODO: Temporary hack to check if we're in a concurrent root. We can delete
// when the legacy root API is removed.
var isConcurrentMode = (internalInstanceHandle.mode & ConcurrentMode) !== NoMode;
return diffHydratedText(textInstance, text);
}
function hydrateSuspenseInstance(suspenseInstance, internalInstanceHandle) {
precacheFiberNode(internalInstanceHandle, suspenseInstance);
}
function getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance) {
var node = suspenseInstance.nextSibling; // Skip past all nodes within this suspense boundary.
// There might be nested nodes so we need to keep track of how
// deep we are and only break out when we're back on top.
var depth = 0;
while (node) {
if (node.nodeType === COMMENT_NODE) {
var data = node.data;
if (data === SUSPENSE_END_DATA) {
if (depth === 0) {
return getNextHydratableSibling(node);
} else {
depth--;
}
} else if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
depth++;
}
}
node = node.nextSibling;
} // TODO: Warn, we didn't find the end comment boundary.
return null;
} // Returns the SuspenseInstance if this node is a direct child of a
// SuspenseInstance. I.e. if its previous sibling is a Comment with
// SUSPENSE_x_START_DATA. Otherwise, null.
function getParentSuspenseInstance(targetInstance) {
var node = targetInstance.previousSibling; // Skip past all nodes within this suspense boundary.
// There might be nested nodes so we need to keep track of how
// deep we are and only break out when we're back on top.
var depth = 0;
while (node) {
if (node.nodeType === COMMENT_NODE) {
var data = node.data;
if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
if (depth === 0) {
return node;
} else {
depth--;
}
} else if (data === SUSPENSE_END_DATA) {
depth++;
}
}
node = node.previousSibling;
}
return null;
}
function commitHydratedContainer(container) {
// Retry if any event replaying was blocked on this.
retryIfBlockedOn(container);
}
function commitHydratedSuspenseInstance(suspenseInstance) {
// Retry if any event replaying was blocked on this.
retryIfBlockedOn(suspenseInstance);
}
function shouldDeleteUnhydratedTailInstances(parentType) {
return parentType !== 'head' && parentType !== 'body';
}
function didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text, isConcurrentMode) {
var shouldWarnDev = true;
checkForUnmatchedText(textInstance.nodeValue, text, isConcurrentMode, shouldWarnDev);
}
function didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text, isConcurrentMode) {
if (parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
var shouldWarnDev = true;
checkForUnmatchedText(textInstance.nodeValue, text, isConcurrentMode, shouldWarnDev);
}
}
function didNotHydrateInstanceWithinContainer(parentContainer, instance) {
{
if (instance.nodeType === ELEMENT_NODE) {
warnForDeletedHydratableElement(parentContainer, instance);
} else if (instance.nodeType === COMMENT_NODE) ; else {
warnForDeletedHydratableText(parentContainer, instance);
}
}
}
function didNotHydrateInstanceWithinSuspenseInstance(parentInstance, instance) {
{
// $FlowFixMe: Only Element or Document can be parent nodes.
var parentNode = parentInstance.parentNode;
if (parentNode !== null) {
if (instance.nodeType === ELEMENT_NODE) {
warnForDeletedHydratableElement(parentNode, instance);
} else if (instance.nodeType === COMMENT_NODE) ; else {
warnForDeletedHydratableText(parentNode, instance);
}
}
}
}
function didNotHydrateInstance(parentType, parentProps, parentInstance, instance, isConcurrentMode) {
{
if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
if (instance.nodeType === ELEMENT_NODE) {
warnForDeletedHydratableElement(parentInstance, instance);
} else if (instance.nodeType === COMMENT_NODE) ; else {
warnForDeletedHydratableText(parentInstance, instance);
}
}
}
}
function didNotFindHydratableInstanceWithinContainer(parentContainer, type, props) {
{
warnForInsertedHydratedElement(parentContainer, type);
}
}
function didNotFindHydratableTextInstanceWithinContainer(parentContainer, text) {
{
warnForInsertedHydratedText(parentContainer, text);
}
}
function didNotFindHydratableInstanceWithinSuspenseInstance(parentInstance, type, props) {
{
// $FlowFixMe: Only Element or Document can be parent nodes.
var parentNode = parentInstance.parentNode;
if (parentNode !== null) warnForInsertedHydratedElement(parentNode, type);
}
}
function didNotFindHydratableTextInstanceWithinSuspenseInstance(parentInstance, text) {
{
// $FlowFixMe: Only Element or Document can be parent nodes.
var parentNode = parentInstance.parentNode;
if (parentNode !== null) warnForInsertedHydratedText(parentNode, text);
}
}
function didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props, isConcurrentMode) {
{
if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
warnForInsertedHydratedElement(parentInstance, type);
}
}
}
function didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text, isConcurrentMode) {
{
if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
warnForInsertedHydratedText(parentInstance, text);
}
}
}
function errorHydratingContainer(parentContainer) {
{
// TODO: This gets logged by onRecoverableError, too, so we should be
// able to remove it.
error('An error occurred during hydration. The server HTML was replaced with client content in <%s>.', parentContainer.nodeName.toLowerCase());
}
}
function preparePortalMount(portalInstance) {
listenToAllSupportedEvents(portalInstance);
}
var randomKey = Math.random().toString(36).slice(2);
var internalInstanceKey = '__reactFiber$' + randomKey;
var internalPropsKey = '__reactProps$' + randomKey;
var internalContainerInstanceKey = '__reactContainer$' + randomKey;
var internalEventHandlersKey = '__reactEvents$' + randomKey;
var internalEventHandlerListenersKey = '__reactListeners$' + randomKey;
var internalEventHandlesSetKey = '__reactHandles$' + randomKey;
function detachDeletedInstance(node) {
// TODO: This function is only called on host components. I don't think all of
// these fields are relevant.
delete node[internalInstanceKey];
delete node[internalPropsKey];
delete node[internalEventHandlersKey];
delete node[internalEventHandlerListenersKey];
delete node[internalEventHandlesSetKey];
}
function precacheFiberNode(hostInst, node) {
node[internalInstanceKey] = hostInst;
}
function markContainerAsRoot(hostRoot, node) {
node[internalContainerInstanceKey] = hostRoot;
}
function unmarkContainerAsRoot(node) {
node[internalContainerInstanceKey] = null;
}
function isContainerMarkedAsRoot(node) {
return !!node[internalContainerInstanceKey];
} // Given a DOM node, return the closest HostComponent or HostText fiber ancestor.
// If the target node is part of a hydrated or not yet rendered subtree, then
// this may also return a SuspenseComponent or HostRoot to indicate that.
// Conceptually the HostRoot fiber is a child of the Container node. So if you
// pass the Container node as the targetNode, you will not actually get the
// HostRoot back. To get to the HostRoot, you need to pass a child of it.
// The same thing applies to Suspense boundaries.
function getClosestInstanceFromNode(targetNode) {
var targetInst = targetNode[internalInstanceKey];
if (targetInst) {
// Don't return HostRoot or SuspenseComponent here.
return targetInst;
} // If the direct event target isn't a React owned DOM node, we need to look
// to see if one of its parents is a React owned DOM node.
var parentNode = targetNode.parentNode;
while (parentNode) {
// We'll check if this is a container root that could include
// React nodes in the future. We need to check this first because
// if we're a child of a dehydrated container, we need to first
// find that inner container before moving on to finding the parent
// instance. Note that we don't check this field on the targetNode
// itself because the fibers are conceptually between the container
// node and the first child. It isn't surrounding the container node.
// If it's not a container, we check if it's an instance.
targetInst = parentNode[internalContainerInstanceKey] || parentNode[internalInstanceKey];
if (targetInst) {
// Since this wasn't the direct target of the event, we might have
// stepped past dehydrated DOM nodes to get here. However they could
// also have been non-React nodes. We need to answer which one.
// If we the instance doesn't have any children, then there can't be
// a nested suspense boundary within it. So we can use this as a fast
// bailout. Most of the time, when people add non-React children to
// the tree, it is using a ref to a child-less DOM node.
// Normally we'd only need to check one of the fibers because if it
// has ever gone from having children to deleting them or vice versa
// it would have deleted the dehydrated boundary nested inside already.
// However, since the HostRoot starts out with an alternate it might
// have one on the alternate so we need to check in case this was a
// root.
var alternate = targetInst.alternate;
if (targetInst.child !== null || alternate !== null && alternate.child !== null) {
// Next we need to figure out if the node that skipped past is
// nested within a dehydrated boundary and if so, which one.
var suspenseInstance = getParentSuspenseInstance(targetNode);
while (suspenseInstance !== null) {
// We found a suspense instance. That means that we haven't
// hydrated it yet. Even though we leave the comments in the
// DOM after hydrating, and there are boundaries in the DOM
// that could already be hydrated, we wouldn't have found them
// through this pass since if the target is hydrated it would
// have had an internalInstanceKey on it.
// Let's get the fiber associated with the SuspenseComponent
// as the deepest instance.
var targetSuspenseInst = suspenseInstance[internalInstanceKey];
if (targetSuspenseInst) {
return targetSuspenseInst;
} // If we don't find a Fiber on the comment, it might be because
// we haven't gotten to hydrate it yet. There might still be a
// parent boundary that hasn't above this one so we need to find
// the outer most that is known.
suspenseInstance = getParentSuspenseInstance(suspenseInstance); // If we don't find one, then that should mean that the parent
// host component also hasn't hydrated yet. We can return it
// below since it will bail out on the isMounted check later.
}
}
return targetInst;
}
targetNode = parentNode;
parentNode = targetNode.parentNode;
}
return null;
}
/**
* Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
* instance, or null if the node was not rendered by this React.
*/
function getInstanceFromNode(node) {
var inst = node[internalInstanceKey] || node[internalContainerInstanceKey];
if (inst) {
if (inst.tag === HostComponent || inst.tag === HostText || inst.tag === SuspenseComponent || inst.tag === HostRoot) {
return inst;
} else {
return null;
}
}
return null;
}
/**
* Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
* DOM node.
*/
function getNodeFromInstance(inst) {
if (inst.tag === HostComponent || inst.tag === HostText) {
// In Fiber this, is just the state node right now. We assume it will be
// a host component or host text.
return inst.stateNode;
} // Without this first invariant, passing a non-DOM-component triggers the next
// invariant for a missing parent, which is super confusing.
throw new Error('getNodeFromInstance: Invalid argument.');
}
function getFiberCurrentPropsFromNode(node) {
return node[internalPropsKey] || null;
}
function updateFiberProps(node, props) {
node[internalPropsKey] = props;
}
function getEventListenerSet(node) {
var elementListenerSet = node[internalEventHandlersKey];
if (elementListenerSet === undefined) {
elementListenerSet = node[internalEventHandlersKey] = new Set();
}
return elementListenerSet;
}
var loggedTypeFailures = {};
var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
function setCurrentlyValidatingElement(element) {
{
if (element) {
var owner = element._owner;
var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
} else {
ReactDebugCurrentFrame$1.setExtraStackFrame(null);
}
}
}
function checkPropTypes(typeSpecs, values, location, componentName, element) {
{
// $FlowFixMe This is okay but Flow doesn't know it.
var has = Function.call.bind(hasOwnProperty);
for (var typeSpecName in typeSpecs) {
if (has(typeSpecs, typeSpecName)) {
var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
if (typeof typeSpecs[typeSpecName] !== 'function') {
// eslint-disable-next-line react-internal/prod-error-codes
var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
err.name = 'Invariant Violation';
throw err;
}
error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
} catch (ex) {
error$1 = ex;
}
if (error$1 && !(error$1 instanceof Error)) {
setCurrentlyValidatingElement(element);
error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);
setCurrentlyValidatingElement(null);
}
if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error$1.message] = true;
setCurrentlyValidatingElement(element);
error('Failed %s type: %s', location, error$1.message);
setCurrentlyValidatingElement(null);
}
}
}
}
}
var valueStack = [];
var fiberStack;
{
fiberStack = [];
}
var index = -1;
function createCursor(defaultValue) {
return {
current: defaultValue
};
}
function pop(cursor, fiber) {
if (index < 0) {
{
error('Unexpected pop.');
}
return;
}
{
if (fiber !== fiberStack[index]) {
error('Unexpected Fiber popped.');
}
}
cursor.current = valueStack[index];
valueStack[index] = null;
{
fiberStack[index] = null;
}
index--;
}
function push(cursor, value, fiber) {
index++;
valueStack[index] = cursor.current;
{
fiberStack[index] = fiber;
}
cursor.current = value;
}
var warnedAboutMissingGetChildContext;
{
warnedAboutMissingGetChildContext = {};
}
var emptyContextObject = {};
{
Object.freeze(emptyContextObject);
} // A cursor to the current merged context object on the stack.
var contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed.
var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack.
// We use this to get access to the parent context after we have already
// pushed the next context provider, and now need to merge their contexts.
var previousContext = emptyContextObject;
function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) {
{
if (didPushOwnContextIfProvider && isContextProvider(Component)) {
// If the fiber is a context provider itself, when we read its context
// we may have already pushed its own child context on the stack. A context
// provider should not "see" its own child context. Therefore we read the
// previous (parent) context instead for a context provider.
return previousContext;
}
return contextStackCursor.current;
}
}
function cacheContext(workInProgress, unmaskedContext, maskedContext) {
{
var instance = workInProgress.stateNode;
instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
}
}
function getMaskedContext(workInProgress, unmaskedContext) {
{
var type = workInProgress.type;
var contextTypes = type.contextTypes;
if (!contextTypes) {
return emptyContextObject;
} // Avoid recreating masked context unless unmasked context has changed.
// Failing to do this will result in unnecessary calls to componentWillReceiveProps.
// This may trigger infinite loops if componentWillReceiveProps calls setState.
var instance = workInProgress.stateNode;
if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
return instance.__reactInternalMemoizedMaskedChildContext;
}
var context = {};
for (var key in contextTypes) {
context[key] = unmaskedContext[key];
}
{
var name = getComponentNameFromFiber(workInProgress) || 'Unknown';
checkPropTypes(contextTypes, context, 'context', name);
} // Cache unmasked context so we can avoid recreating masked context unless necessary.
// Context is created before the class component is instantiated so check for instance.
if (instance) {
cacheContext(workInProgress, unmaskedContext, context);
}
return context;
}
}
function hasContextChanged() {
{
return didPerformWorkStackCursor.current;
}
}
function isContextProvider(type) {
{
var childContextTypes = type.childContextTypes;
return childContextTypes !== null && childContextTypes !== undefined;
}
}
function popContext(fiber) {
{
pop(didPerformWorkStackCursor, fiber);
pop(contextStackCursor, fiber);
}
}
function popTopLevelContextObject(fiber) {
{
pop(didPerformWorkStackCursor, fiber);
pop(contextStackCursor, fiber);
}
}
function pushTopLevelContextObject(fiber, context, didChange) {
{
if (contextStackCursor.current !== emptyContextObject) {
throw new Error('Unexpected context found on stack. ' + 'This error is likely caused by a bug in React. Please file an issue.');
}
push(contextStackCursor, context, fiber);
push(didPerformWorkStackCursor, didChange, fiber);
}
}
function processChildContext(fiber, type, parentContext) {
{
var instance = fiber.stateNode;
var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future.
// It has only been added in Fiber to match the (unintentional) behavior in Stack.
if (typeof instance.getChildContext !== 'function') {
{
var componentName = getComponentNameFromFiber(fiber) || 'Unknown';
if (!warnedAboutMissingGetChildContext[componentName]) {
warnedAboutMissingGetChildContext[componentName] = true;
error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName);
}
}
return parentContext;
}
var childContext = instance.getChildContext();
for (var contextKey in childContext) {
if (!(contextKey in childContextTypes)) {
throw new Error((getComponentNameFromFiber(fiber) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes.");
}
}
{
var name = getComponentNameFromFiber(fiber) || 'Unknown';
checkPropTypes(childContextTypes, childContext, 'child context', name);
}
return assign({}, parentContext, childContext);
}
}
function pushContextProvider(workInProgress) {
{
var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity.
// If the instance does not exist yet, we will push null at first,
// and replace it on the stack later when invalidating the context.
var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; // Remember the parent context so we can merge with it later.
// Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.
previousContext = contextStackCursor.current;
push(contextStackCursor, memoizedMergedChildContext, workInProgress);
push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);
return true;
}
}
function invalidateContextProvider(workInProgress, type, didChange) {
{
var instance = workInProgress.stateNode;
if (!instance) {
throw new Error('Expected to have an instance by this point. ' + 'This error is likely caused by a bug in React. Please file an issue.');
}
if (didChange) {
// Merge parent and own context.
// Skip this if we're not updating due to sCU.
// This avoids unnecessarily recomputing memoized values.
var mergedContext = processChildContext(workInProgress, type, previousContext);
instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one.
// It is important to unwind the context in the reverse order.
pop(didPerformWorkStackCursor, workInProgress);
pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed.
push(contextStackCursor, mergedContext, workInProgress);
push(didPerformWorkStackCursor, didChange, workInProgress);
} else {
pop(didPerformWorkStackCursor, workInProgress);
push(didPerformWorkStackCursor, didChange, workInProgress);
}
}
}
function findCurrentUnmaskedContext(fiber) {
{
// Currently this is only used with renderSubtreeIntoContainer; not sure if it
// makes sense elsewhere
if (!isFiberMounted(fiber) || fiber.tag !== ClassComponent) {
throw new Error('Expected subtree parent to be a mounted class component. ' + 'This error is likely caused by a bug in React. Please file an issue.');
}
var node = fiber;
do {
switch (node.tag) {
case HostRoot:
return node.stateNode.context;
case ClassComponent:
{
var Component = node.type;
if (isContextProvider(Component)) {
return node.stateNode.__reactInternalMemoizedMergedChildContext;
}
break;
}
}
node = node.return;
} while (node !== null);
throw new Error('Found unexpected detached subtree parent. ' + 'This error is likely caused by a bug in React. Please file an issue.');
}
}
var LegacyRoot = 0;
var ConcurrentRoot = 1;
var syncQueue = null;
var includesLegacySyncCallbacks = false;
var isFlushingSyncQueue = false;
function scheduleSyncCallback(callback) {
// Push this callback into an internal queue. We'll flush these either in
// the next tick, or earlier if something calls `flushSyncCallbackQueue`.
if (syncQueue === null) {
syncQueue = [callback];
} else {
// Push onto existing queue. Don't need to schedule a callback because
// we already scheduled one when we created the queue.
syncQueue.push(callback);
}
}
function scheduleLegacySyncCallback(callback) {
includesLegacySyncCallbacks = true;
scheduleSyncCallback(callback);
}
function flushSyncCallbacksOnlyInLegacyMode() {
// Only flushes the queue if there's a legacy sync callback scheduled.
// TODO: There's only a single type of callback: performSyncOnWorkOnRoot. So
// it might make more sense for the queue to be a list of roots instead of a
// list of generic callbacks. Then we can have two: one for legacy roots, one
// for concurrent roots. And this method would only flush the legacy ones.
if (includesLegacySyncCallbacks) {
flushSyncCallbacks();
}
}
function flushSyncCallbacks() {
if (!isFlushingSyncQueue && syncQueue !== null) {
// Prevent re-entrance.
isFlushingSyncQueue = true;
var i = 0;
var previousUpdatePriority = getCurrentUpdatePriority();
try {
var isSync = true;
var queue = syncQueue; // TODO: Is this necessary anymore? The only user code that runs in this
// queue is in the render or commit phases.
setCurrentUpdatePriority(DiscreteEventPriority);
for (; i < queue.length; i++) {
var callback = queue[i];
do {
callback = callback(isSync);
} while (callback !== null);
}
syncQueue = null;
includesLegacySyncCallbacks = false;
} catch (error) {
// If something throws, leave the remaining callbacks on the queue.
if (syncQueue !== null) {
syncQueue = syncQueue.slice(i + 1);
} // Resume flushing in the next tick
scheduleCallback(ImmediatePriority, flushSyncCallbacks);
throw error;
} finally {
setCurrentUpdatePriority(previousUpdatePriority);
isFlushingSyncQueue = false;
}
}
return null;
}
// TODO: Use the unified fiber stack module instead of this local one?
// Intentionally not using it yet to derisk the initial implementation, because
// the way we push/pop these values is a bit unusual. If there's a mistake, I'd
// rather the ids be wrong than crash the whole reconciler.
var forkStack = [];
var forkStackIndex = 0;
var treeForkProvider = null;
var treeForkCount = 0;
var idStack = [];
var idStackIndex = 0;
var treeContextProvider = null;
var treeContextId = 1;
var treeContextOverflow = '';
function isForkedChild(workInProgress) {
warnIfNotHydrating();
return (workInProgress.flags & Forked) !== NoFlags;
}
function getForksAtLevel(workInProgress) {
warnIfNotHydrating();
return treeForkCount;
}
function getTreeId() {
var overflow = treeContextOverflow;
var idWithLeadingBit = treeContextId;
var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit);
return id.toString(32) + overflow;
}
function pushTreeFork(workInProgress, totalChildren) {
// This is called right after we reconcile an array (or iterator) of child
// fibers, because that's the only place where we know how many children in
// the whole set without doing extra work later, or storing addtional
// information on the fiber.
//
// That's why this function is separate from pushTreeId — it's called during
// the render phase of the fork parent, not the child, which is where we push
// the other context values.
//
// In the Fizz implementation this is much simpler because the child is
// rendered in the same callstack as the parent.
//
// It might be better to just add a `forks` field to the Fiber type. It would
// make this module simpler.
warnIfNotHydrating();
forkStack[forkStackIndex++] = treeForkCount;
forkStack[forkStackIndex++] = treeForkProvider;
treeForkProvider = workInProgress;
treeForkCount = totalChildren;
}
function pushTreeId(workInProgress, totalChildren, index) {
warnIfNotHydrating();
idStack[idStackIndex++] = treeContextId;
idStack[idStackIndex++] = treeContextOverflow;
idStack[idStackIndex++] = treeContextProvider;
treeContextProvider = workInProgress;
var baseIdWithLeadingBit = treeContextId;
var baseOverflow = treeContextOverflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part
// of the id; we use it to account for leading 0s.
var baseLength = getBitLength(baseIdWithLeadingBit) - 1;
var baseId = baseIdWithLeadingBit & ~(1 << baseLength);
var slot = index + 1;
var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into
// consideration the leading 1 we use to mark the end of the sequence.
if (length > 30) {
// We overflowed the bitwise-safe range. Fall back to slower algorithm.
// This branch assumes the length of the base id is greater than 5; it won't
// work for smaller ids, because you need 5 bits per character.
//
// We encode the id in multiple steps: first the base id, then the
// remaining digits.
//
// Each 5 bit sequence corresponds to a single base 32 character. So for
// example, if the current id is 23 bits long, we can convert 20 of those
// bits into a string of 4 characters, with 3 bits left over.
//
// First calculate how many bits in the base id represent a complete
// sequence of characters.
var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits.
var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string.
var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id.
var restOfBaseId = baseId >> numberOfOverflowBits;
var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because
// we made more room, this time it won't overflow.
var restOfLength = getBitLength(totalChildren) + restOfBaseLength;
var restOfNewBits = slot << restOfBaseLength;
var id = restOfNewBits | restOfBaseId;
var overflow = newOverflow + baseOverflow;
treeContextId = 1 << restOfLength | id;
treeContextOverflow = overflow;
} else {
// Normal path
var newBits = slot << baseLength;
var _id = newBits | baseId;
var _overflow = baseOverflow;
treeContextId = 1 << length | _id;
treeContextOverflow = _overflow;
}
}
function pushMaterializedTreeId(workInProgress) {
warnIfNotHydrating(); // This component materialized an id. This will affect any ids that appear
// in its children.
var returnFiber = workInProgress.return;
if (returnFiber !== null) {
var numberOfForks = 1;
var slotIndex = 0;
pushTreeFork(workInProgress, numberOfForks);
pushTreeId(workInProgress, numberOfForks, slotIndex);
}
}
function getBitLength(number) {
return 32 - clz32(number);
}
function getLeadingBit(id) {
return 1 << getBitLength(id) - 1;
}
function popTreeContext(workInProgress) {
// Restore the previous values.
// This is a bit more complicated than other context-like modules in Fiber
// because the same Fiber may appear on the stack multiple times and for
// different reasons. We have to keep popping until the work-in-progress is
// no longer at the top of the stack.
while (workInProgress === treeForkProvider) {
treeForkProvider = forkStack[--forkStackIndex];
forkStack[forkStackIndex] = null;
treeForkCount = forkStack[--forkStackIndex];
forkStack[forkStackIndex] = null;
}
while (workInProgress === treeContextProvider) {
treeContextProvider = idStack[--idStackIndex];
idStack[idStackIndex] = null;
treeContextOverflow = idStack[--idStackIndex];
idStack[idStackIndex] = null;
treeContextId = idStack[--idStackIndex];
idStack[idStackIndex] = null;
}
}
function getSuspendedTreeContext() {
warnIfNotHydrating();
if (treeContextProvider !== null) {
return {
id: treeContextId,
overflow: treeContextOverflow
};
} else {
return null;
}
}
function restoreSuspendedTreeContext(workInProgress, suspendedContext) {
warnIfNotHydrating();
idStack[idStackIndex++] = treeContextId;
idStack[idStackIndex++] = treeContextOverflow;
idStack[idStackIndex++] = treeContextProvider;
treeContextId = suspendedContext.id;
treeContextOverflow = suspendedContext.overflow;
treeContextProvider = workInProgress;
}
function warnIfNotHydrating() {
{
if (!getIsHydrating()) {
error('Expected to be hydrating. This is a bug in React. Please file ' + 'an issue.');
}
}
}
// This may have been an insertion or a hydration.
var hydrationParentFiber = null;
var nextHydratableInstance = null;
var isHydrating = false; // This flag allows for warning supression when we expect there to be mismatches
// due to earlier mismatches or a suspended fiber.
var didSuspendOrErrorDEV = false; // Hydration errors that were thrown inside this boundary
var hydrationErrors = null;
function warnIfHydrating() {
{
if (isHydrating) {
error('We should not be hydrating here. This is a bug in React. Please file a bug.');
}
}
}
function markDidThrowWhileHydratingDEV() {
{
didSuspendOrErrorDEV = true;
}
}
function didSuspendOrErrorWhileHydratingDEV() {
{
return didSuspendOrErrorDEV;
}
}
function enterHydrationState(fiber) {
var parentInstance = fiber.stateNode.containerInfo;
nextHydratableInstance = getFirstHydratableChildWithinContainer(parentInstance);
hydrationParentFiber = fiber;
isHydrating = true;
hydrationErrors = null;
didSuspendOrErrorDEV = false;
return true;
}
function reenterHydrationStateFromDehydratedSuspenseInstance(fiber, suspenseInstance, treeContext) {
nextHydratableInstance = getFirstHydratableChildWithinSuspenseInstance(suspenseInstance);
hydrationParentFiber = fiber;
isHydrating = true;
hydrationErrors = null;
didSuspendOrErrorDEV = false;
if (treeContext !== null) {
restoreSuspendedTreeContext(fiber, treeContext);
}
return true;
}
function warnUnhydratedInstance(returnFiber, instance) {
{
switch (returnFiber.tag) {
case HostRoot:
{
didNotHydrateInstanceWithinContainer(returnFiber.stateNode.containerInfo, instance);
break;
}
case HostComponent:
{
var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;
didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance, // TODO: Delete this argument when we remove the legacy root API.
isConcurrentMode);
break;
}
case SuspenseComponent:
{
var suspenseState = returnFiber.memoizedState;
if (suspenseState.dehydrated !== null) didNotHydrateInstanceWithinSuspenseInstance(suspenseState.dehydrated, instance);
break;
}
}
}
}
function deleteHydratableInstance(returnFiber, instance) {
warnUnhydratedInstance(returnFiber, instance);
var childToDelete = createFiberFromHostInstanceForDeletion();
childToDelete.stateNode = instance;
childToDelete.return = returnFiber;
var deletions = returnFiber.deletions;
if (deletions === null) {
returnFiber.deletions = [childToDelete];
returnFiber.flags |= ChildDeletion;
} else {
deletions.push(childToDelete);
}
}
function warnNonhydratedInstance(returnFiber, fiber) {
{
if (didSuspendOrErrorDEV) {
// Inside a boundary that already suspended. We're currently rendering the
// siblings of a suspended node. The mismatch may be due to the missing
// data, so it's probably a false positive.
return;
}
switch (returnFiber.tag) {
case HostRoot:
{
var parentContainer = returnFiber.stateNode.containerInfo;
switch (fiber.tag) {
case HostComponent:
var type = fiber.type;
var props = fiber.pendingProps;
didNotFindHydratableInstanceWithinContainer(parentContainer, type);
break;
case HostText:
var text = fiber.pendingProps;
didNotFindHydratableTextInstanceWithinContainer(parentContainer, text);
break;
}
break;
}
case HostComponent:
{
var parentType = returnFiber.type;
var parentProps = returnFiber.memoizedProps;
var parentInstance = returnFiber.stateNode;
switch (fiber.tag) {
case HostComponent:
{
var _type = fiber.type;
var _props = fiber.pendingProps;
var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;
didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props, // TODO: Delete this argument when we remove the legacy root API.
isConcurrentMode);
break;
}
case HostText:
{
var _text = fiber.pendingProps;
var _isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;
didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text, // TODO: Delete this argument when we remove the legacy root API.
_isConcurrentMode);
break;
}
}
break;
}
case SuspenseComponent:
{
var suspenseState = returnFiber.memoizedState;
var _parentInstance = suspenseState.dehydrated;
if (_parentInstance !== null) switch (fiber.tag) {
case HostComponent:
var _type2 = fiber.type;
var _props2 = fiber.pendingProps;
didNotFindHydratableInstanceWithinSuspenseInstance(_parentInstance, _type2);
break;
case HostText:
var _text2 = fiber.pendingProps;
didNotFindHydratableTextInstanceWithinSuspenseInstance(_parentInstance, _text2);
break;
}
break;
}
default:
return;
}
}
}
function insertNonHydratedInstance(returnFiber, fiber) {
fiber.flags = fiber.flags & ~Hydrating | Placement;
warnNonhydratedInstance(returnFiber, fiber);
}
function tryHydrate(fiber, nextInstance) {
switch (fiber.tag) {
case HostComponent:
{
var type = fiber.type;
var props = fiber.pendingProps;
var instance = canHydrateInstance(nextInstance, type);
if (instance !== null) {
fiber.stateNode = instance;
hydrationParentFiber = fiber;
nextHydratableInstance = getFirstHydratableChild(instance);
return true;
}
return false;
}
case HostText:
{
var text = fiber.pendingProps;
var textInstance = canHydrateTextInstance(nextInstance, text);
if (textInstance !== null) {
fiber.stateNode = textInstance;
hydrationParentFiber = fiber; // Text Instances don't have children so there's nothing to hydrate.
nextHydratableInstance = null;
return true;
}
return false;
}
case SuspenseComponent:
{
var suspenseInstance = canHydrateSuspenseInstance(nextInstance);
if (suspenseInstance !== null) {
var suspenseState = {
dehydrated: suspenseInstance,
treeContext: getSuspendedTreeContext(),
retryLane: OffscreenLane
};
fiber.memoizedState = suspenseState; // Store the dehydrated fragment as a child fiber.
// This simplifies the code for getHostSibling and deleting nodes,
// since it doesn't have to consider all Suspense boundaries and
// check if they're dehydrated ones or not.
var dehydratedFragment = createFiberFromDehydratedFragment(suspenseInstance);
dehydratedFragment.return = fiber;
fiber.child = dehydratedFragment;
hydrationParentFiber = fiber; // While a Suspense Instance does have children, we won't step into
// it during the first pass. Instead, we'll reenter it later.
nextHydratableInstance = null;
return true;
}
return false;
}
default:
return false;
}
}
function shouldClientRenderOnMismatch(fiber) {
return (fiber.mode & ConcurrentMode) !== NoMode && (fiber.flags & DidCapture) === NoFlags;
}
function throwOnHydrationMismatch(fiber) {
throw new Error('Hydration failed because the initial UI does not match what was ' + 'rendered on the server.');
}
function tryToClaimNextHydratableInstance(fiber) {
if (!isHydrating) {
return;
}
var nextInstance = nextHydratableInstance;
if (!nextInstance) {
if (shouldClientRenderOnMismatch(fiber)) {
warnNonhydratedInstance(hydrationParentFiber, fiber);
throwOnHydrationMismatch();
} // Nothing to hydrate. Make it an insertion.
insertNonHydratedInstance(hydrationParentFiber, fiber);
isHydrating = false;
hydrationParentFiber = fiber;
return;
}
var firstAttemptedInstance = nextInstance;
if (!tryHydrate(fiber, nextInstance)) {
if (shouldClientRenderOnMismatch(fiber)) {
warnNonhydratedInstance(hydrationParentFiber, fiber);
throwOnHydrationMismatch();
} // If we can't hydrate this instance let's try the next one.
// We use this as a heuristic. It's based on intuition and not data so it
// might be flawed or unnecessary.
nextInstance = getNextHydratableSibling(firstAttemptedInstance);
var prevHydrationParentFiber = hydrationParentFiber;
if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
// Nothing to hydrate. Make it an insertion.
insertNonHydratedInstance(hydrationParentFiber, fiber);
isHydrating = false;
hydrationParentFiber = fiber;
return;
} // We matched the next one, we'll now assume that the first one was
// superfluous and we'll delete it. Since we can't eagerly delete it
// we'll have to schedule a deletion. To do that, this node needs a dummy
// fiber associated with it.
deleteHydratableInstance(prevHydrationParentFiber, firstAttemptedInstance);
}
}
function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {
var instance = fiber.stateNode;
var shouldWarnIfMismatchDev = !didSuspendOrErrorDEV;
var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber, shouldWarnIfMismatchDev); // TODO: Type this specific to this type of component.
fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there
// is a new ref we mark this as an update.
if (updatePayload !== null) {
return true;
}
return false;
}
function prepareToHydrateHostTextInstance(fiber) {
var textInstance = fiber.stateNode;
var textContent = fiber.memoizedProps;
var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);
if (shouldUpdate) {
// We assume that prepareToHydrateHostTextInstance is called in a context where the
// hydration parent is the parent host component of this host text.
var returnFiber = hydrationParentFiber;
if (returnFiber !== null) {
switch (returnFiber.tag) {
case HostRoot:
{
var parentContainer = returnFiber.stateNode.containerInfo;
var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;
didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API.
isConcurrentMode);
break;
}
case HostComponent:
{
var parentType = returnFiber.type;
var parentProps = returnFiber.memoizedProps;
var parentInstance = returnFiber.stateNode;
var _isConcurrentMode2 = (returnFiber.mode & ConcurrentMode) !== NoMode;
didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API.
_isConcurrentMode2);
break;
}
}
}
}
return shouldUpdate;
}
function prepareToHydrateHostSuspenseInstance(fiber) {
var suspenseState = fiber.memoizedState;
var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;
if (!suspenseInstance) {
throw new Error('Expected to have a hydrated suspense instance. ' + 'This error is likely caused by a bug in React. Please file an issue.');
}
hydrateSuspenseInstance(suspenseInstance, fiber);
}
function skipPastDehydratedSuspenseInstance(fiber) {
var suspenseState = fiber.memoizedState;
var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;
if (!suspenseInstance) {
throw new Error('Expected to have a hydrated suspense instance. ' + 'This error is likely caused by a bug in React. Please file an issue.');
}
return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);
}
function popToNextHostParent(fiber) {
var parent = fiber.return;
while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) {
parent = parent.return;
}
hydrationParentFiber = parent;
}
function popHydrationState(fiber) {
if (fiber !== hydrationParentFiber) {
// We're deeper than the current hydration context, inside an inserted
// tree.
return false;
}
if (!isHydrating) {
// If we're not currently hydrating but we're in a hydration context, then
// we were an insertion and now need to pop up reenter hydration of our
// siblings.
popToNextHostParent(fiber);
isHydrating = true;
return false;
} // If we have any remaining hydratable nodes, we need to delete them now.
// We only do this deeper than head and body since they tend to have random
// other nodes in them. We also ignore components with pure text content in
// side of them. We also don't delete anything inside the root container.
if (fiber.tag !== HostRoot && (fiber.tag !== HostComponent || shouldDeleteUnhydratedTailInstances(fiber.type) && !shouldSetTextContent(fiber.type, fiber.memoizedProps))) {
var nextInstance = nextHydratableInstance;
if (nextInstance) {
if (shouldClientRenderOnMismatch(fiber)) {
warnIfUnhydratedTailNodes(fiber);
throwOnHydrationMismatch();
} else {
while (nextInstance) {
deleteHydratableInstance(fiber, nextInstance);
nextInstance = getNextHydratableSibling(nextInstance);
}
}
}
}
popToNextHostParent(fiber);
if (fiber.tag === SuspenseComponent) {
nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber);
} else {
nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
}
return true;
}
function hasUnhydratedTailNodes() {
return isHydrating && nextHydratableInstance !== null;
}
function warnIfUnhydratedTailNodes(fiber) {
var nextInstance = nextHydratableInstance;
while (nextInstance) {
warnUnhydratedInstance(fiber, nextInstance);
nextInstance = getNextHydratableSibling(nextInstance);
}
}
function resetHydrationState() {
hydrationParentFiber = null;
nextHydratableInstance = null;
isHydrating = false;
didSuspendOrErrorDEV = false;
}
function upgradeHydrationErrorsToRecoverable() {
if (hydrationErrors !== null) {
// Successfully completed a forced client render. The errors that occurred
// during the hydration attempt are now recovered. We will log them in
// commit phase, once the entire tree has finished.
queueRecoverableErrors(hydrationErrors);
hydrationErrors = null;
}
}
function getIsHydrating() {
return isHydrating;
}
function queueHydrationError(error) {
if (hydrationErrors === null) {
hydrationErrors = [error];
} else {
hydrationErrors.push(error);
}
}
var ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig;
var NoTransition = null;
function requestCurrentTransition() {
return ReactCurrentBatchConfig$1.transition;
}
var ReactStrictModeWarnings = {
recordUnsafeLifecycleWarnings: function (fiber, instance) {},
flushPendingUnsafeLifecycleWarnings: function () {},
recordLegacyContextWarning: function (fiber, instance) {},
flushLegacyContextWarning: function () {},
discardPendingWarnings: function () {}
};
{
var findStrictRoot = function (fiber) {
var maybeStrictRoot = null;
var node = fiber;
while (node !== null) {
if (node.mode & StrictLegacyMode) {
maybeStrictRoot = node;
}
node = node.return;
}
return maybeStrictRoot;
};
var setToSortedString = function (set) {
var array = [];
set.forEach(function (value) {
array.push(value);
});
return array.sort().join(', ');
};
var pendingComponentWillMountWarnings = [];
var pendingUNSAFE_ComponentWillMountWarnings = [];
var pendingComponentWillReceivePropsWarnings = [];
var pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
var pendingComponentWillUpdateWarnings = [];
var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about.
var didWarnAboutUnsafeLifecycles = new Set();
ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {
// Dedupe strategy: Warn once per component.
if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
return;
}
if (typeof instance.componentWillMount === 'function' && // Don't warn about react-lifecycles-compat polyfilled components.
instance.componentWillMount.__suppressDeprecationWarning !== true) {
pendingComponentWillMountWarnings.push(fiber);
}
if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillMount === 'function') {
pendingUNSAFE_ComponentWillMountWarnings.push(fiber);
}
if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
pendingComponentWillReceivePropsWarnings.push(fiber);
}
if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber);
}
if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
pendingComponentWillUpdateWarnings.push(fiber);
}
if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillUpdate === 'function') {
pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber);
}
};
ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {
// We do an initial pass to gather component names
var componentWillMountUniqueNames = new Set();
if (pendingComponentWillMountWarnings.length > 0) {
pendingComponentWillMountWarnings.forEach(function (fiber) {
componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
didWarnAboutUnsafeLifecycles.add(fiber.type);
});
pendingComponentWillMountWarnings = [];
}
var UNSAFE_componentWillMountUniqueNames = new Set();
if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) {
pendingUNSAFE_ComponentWillMountWarnings.forEach(function (fiber) {
UNSAFE_componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
didWarnAboutUnsafeLifecycles.add(fiber.type);
});
pendingUNSAFE_ComponentWillMountWarnings = [];
}
var componentWillReceivePropsUniqueNames = new Set();
if (pendingComponentWillReceivePropsWarnings.length > 0) {
pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {
componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
didWarnAboutUnsafeLifecycles.add(fiber.type);
});
pendingComponentWillReceivePropsWarnings = [];
}
var UNSAFE_componentWillReceivePropsUniqueNames = new Set();
if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) {
pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function (fiber) {
UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
didWarnAboutUnsafeLifecycles.add(fiber.type);
});
pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
}
var componentWillUpdateUniqueNames = new Set();
if (pendingComponentWillUpdateWarnings.length > 0) {
pendingComponentWillUpdateWarnings.forEach(function (fiber) {
componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
didWarnAboutUnsafeLifecycles.add(fiber.type);
});
pendingComponentWillUpdateWarnings = [];
}
var UNSAFE_componentWillUpdateUniqueNames = new Set();
if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) {
pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function (fiber) {
UNSAFE_componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
didWarnAboutUnsafeLifecycles.add(fiber.type);
});
pendingUNSAFE_ComponentWillUpdateWarnings = [];
} // Finally, we flush all the warnings
// UNSAFE_ ones before the deprecated ones, since they'll be 'louder'
if (UNSAFE_componentWillMountUniqueNames.size > 0) {
var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames);
error('Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '\nPlease update the following components: %s', sortedNames);
}
if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) {
var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames);
error('Using UNSAFE_componentWillReceiveProps in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, " + 'refactor your code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '\nPlease update the following components: %s', _sortedNames);
}
if (UNSAFE_componentWillUpdateUniqueNames.size > 0) {
var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames);
error('Using UNSAFE_componentWillUpdate in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '\nPlease update the following components: %s', _sortedNames2);
}
if (componentWillMountUniqueNames.size > 0) {
var _sortedNames3 = setToSortedString(componentWillMountUniqueNames);
warn('componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '* Rename componentWillMount to UNSAFE_componentWillMount to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames3);
}
if (componentWillReceivePropsUniqueNames.size > 0) {
var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames);
warn('componentWillReceiveProps has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, refactor your " + 'code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames4);
}
if (componentWillUpdateUniqueNames.size > 0) {
var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames);
warn('componentWillUpdate has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames5);
}
};
var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about.
var didWarnAboutLegacyContext = new Set();
ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {
var strictRoot = findStrictRoot(fiber);
if (strictRoot === null) {
error('Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.');
return;
} // Dedup strategy: Warn once per component.
if (didWarnAboutLegacyContext.has(fiber.type)) {
return;
}
var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);
if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {
if (warningsForRoot === undefined) {
warningsForRoot = [];
pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
}
warningsForRoot.push(fiber);
}
};
ReactStrictModeWarnings.flushLegacyContextWarning = function () {
pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {
if (fiberArray.length === 0) {
return;
}
var firstFiber = fiberArray[0];
var uniqueNames = new Set();
fiberArray.forEach(function (fiber) {
uniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
didWarnAboutLegacyContext.add(fiber.type);
});
var sortedNames = setToSortedString(uniqueNames);
try {
setCurrentFiber(firstFiber);
error('Legacy context API has been detected within a strict-mode tree.' + '\n\nThe old API will be supported in all 16.x releases, but applications ' + 'using it should migrate to the new version.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context', sortedNames);
} finally {
resetCurrentFiber();
}
});
};
ReactStrictModeWarnings.discardPendingWarnings = function () {
pendingComponentWillMountWarnings = [];
pendingUNSAFE_ComponentWillMountWarnings = [];
pendingComponentWillReceivePropsWarnings = [];
pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
pendingComponentWillUpdateWarnings = [];
pendingUNSAFE_ComponentWillUpdateWarnings = [];
pendingLegacyContextWarning = new Map();
};
}
function resolveDefaultProps(Component, baseProps) {
if (Component && Component.defaultProps) {
// Resolve default props. Taken from ReactElement
var props = assign({}, baseProps);
var defaultProps = Component.defaultProps;
for (var propName in defaultProps) {
if (props[propName] === undefined) {
props[propName] = defaultProps[propName];
}
}
return props;
}
return baseProps;
}
var valueCursor = createCursor(null);
var rendererSigil;
{
// Use this to detect multiple renderers using the same context
rendererSigil = {};
}
var currentlyRenderingFiber = null;
var lastContextDependency = null;
var lastFullyObservedContext = null;
var isDisallowedContextReadInDEV = false;
function resetContextDependencies() {
// This is called right before React yields execution, to ensure `readContext`
// cannot be called outside the render phase.
currentlyRenderingFiber = null;
lastContextDependency = null;
lastFullyObservedContext = null;
{
isDisallowedContextReadInDEV = false;
}
}
function enterDisallowedContextReadInDEV() {
{
isDisallowedContextReadInDEV = true;
}
}
function exitDisallowedContextReadInDEV() {
{
isDisallowedContextReadInDEV = false;
}
}
function pushProvider(providerFiber, context, nextValue) {
{
push(valueCursor, context._currentValue, providerFiber);
context._currentValue = nextValue;
{
if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {
error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
}
context._currentRenderer = rendererSigil;
}
}
}
function popProvider(context, providerFiber) {
var currentValue = valueCursor.current;
pop(valueCursor, providerFiber);
{
{
context._currentValue = currentValue;
}
}
}
function scheduleContextWorkOnParentPath(parent, renderLanes, propagationRoot) {
// Update the child lanes of all the ancestors, including the alternates.
var node = parent;
while (node !== null) {
var alternate = node.alternate;
if (!isSubsetOfLanes(node.childLanes, renderLanes)) {
node.childLanes = mergeLanes(node.childLanes, renderLanes);
if (alternate !== null) {
alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes);
}
} else if (alternate !== null && !isSubsetOfLanes(alternate.childLanes, renderLanes)) {
alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes);
}
if (node === propagationRoot) {
break;
}
node = node.return;
}
{
if (node !== propagationRoot) {
error('Expected to find the propagation root when scheduling context work. ' + 'This error is likely caused by a bug in React. Please file an issue.');
}
}
}
function propagateContextChange(workInProgress, context, renderLanes) {
{
propagateContextChange_eager(workInProgress, context, renderLanes);
}
}
function propagateContextChange_eager(workInProgress, context, renderLanes) {
var fiber = workInProgress.child;
if (fiber !== null) {
// Set the return pointer of the child to the work-in-progress fiber.
fiber.return = workInProgress;
}
while (fiber !== null) {
var nextFiber = void 0; // Visit this fiber.
var list = fiber.dependencies;
if (list !== null) {
nextFiber = fiber.child;
var dependency = list.firstContext;
while (dependency !== null) {
// Check if the context matches.
if (dependency.context === context) {
// Match! Schedule an update on this fiber.
if (fiber.tag === ClassComponent) {
// Schedule a force update on the work-in-progress.
var lane = pickArbitraryLane(renderLanes);
var update = createUpdate(NoTimestamp, lane);
update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the
// update to the current fiber, too, which means it will persist even if
// this render is thrown away. Since it's a race condition, not sure it's
// worth fixing.
// Inlined `enqueueUpdate` to remove interleaved update check
var updateQueue = fiber.updateQueue;
if (updateQueue === null) ; else {
var sharedQueue = updateQueue.shared;
var pending = sharedQueue.pending;
if (pending === null) {
// This is the first update. Create a circular list.
update.next = update;
} else {
update.next = pending.next;
pending.next = update;
}
sharedQueue.pending = update;
}
}
fiber.lanes = mergeLanes(fiber.lanes, renderLanes);
var alternate = fiber.alternate;
if (alternate !== null) {
alternate.lanes = mergeLanes(alternate.lanes, renderLanes);
}
scheduleContextWorkOnParentPath(fiber.return, renderLanes, workInProgress); // Mark the updated lanes on the list, too.
list.lanes = mergeLanes(list.lanes, renderLanes); // Since we already found a match, we can stop traversing the
// dependency list.
break;
}
dependency = dependency.next;
}
} else if (fiber.tag === ContextProvider) {
// Don't scan deeper if this is a matching provider
nextFiber = fiber.type === workInProgress.type ? null : fiber.child;
} else if (fiber.tag === DehydratedFragment) {
// If a dehydrated suspense boundary is in this subtree, we don't know
// if it will have any context consumers in it. The best we can do is
// mark it as having updates.
var parentSuspense = fiber.return;
if (parentSuspense === null) {
throw new Error('We just came from a parent so we must have had a parent. This is a bug in React.');
}
parentSuspense.lanes = mergeLanes(parentSuspense.lanes, renderLanes);
var _alternate = parentSuspense.alternate;
if (_alternate !== null) {
_alternate.lanes = mergeLanes(_alternate.lanes, renderLanes);
} // This is intentionally passing this fiber as the parent
// because we want to schedule this fiber as having work
// on its children. We'll use the childLanes on
// this fiber to indicate that a context has changed.
scheduleContextWorkOnParentPath(parentSuspense, renderLanes, workInProgress);
nextFiber = fiber.sibling;
} else {
// Traverse down.
nextFiber = fiber.child;
}
if (nextFiber !== null) {
// Set the return pointer of the child to the work-in-progress fiber.
nextFiber.return = fiber;
} else {
// No child. Traverse to next sibling.
nextFiber = fiber;
while (nextFiber !== null) {
if (nextFiber === workInProgress) {
// We're back to the root of this subtree. Exit.
nextFiber = null;
break;
}
var sibling = nextFiber.sibling;
if (sibling !== null) {
// Set the return pointer of the sibling to the work-in-progress fiber.
sibling.return = nextFiber.return;
nextFiber = sibling;
break;
} // No more siblings. Traverse up.
nextFiber = nextFiber.return;
}
}
fiber = nextFiber;
}
}
function prepareToReadContext(workInProgress, renderLanes) {
currentlyRenderingFiber = workInProgress;
lastContextDependency = null;
lastFullyObservedContext = null;
var dependencies = workInProgress.dependencies;
if (dependencies !== null) {
{
var firstContext = dependencies.firstContext;
if (firstContext !== null) {
if (includesSomeLane(dependencies.lanes, renderLanes)) {
// Context list has a pending update. Mark that this fiber performed work.
markWorkInProgressReceivedUpdate();
} // Reset the work-in-progress list
dependencies.firstContext = null;
}
}
}
}
function readContext(context) {
{
// This warning would fire if you read context inside a Hook like useMemo.
// Unlike the class check below, it's not enforced in production for perf.
if (isDisallowedContextReadInDEV) {
error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
}
}
var value = context._currentValue ;
if (lastFullyObservedContext === context) ; else {
var contextItem = {
context: context,
memoizedValue: value,
next: null
};
if (lastContextDependency === null) {
if (currentlyRenderingFiber === null) {
throw new Error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
} // This is the first dependency for this component. Create a new list.
lastContextDependency = contextItem;
currentlyRenderingFiber.dependencies = {
lanes: NoLanes,
firstContext: contextItem
};
} else {
// Append a new context item.
lastContextDependency = lastContextDependency.next = contextItem;
}
}
return value;
}
// render. When this render exits, either because it finishes or because it is
// interrupted, the interleaved updates will be transferred onto the main part
// of the queue.
var concurrentQueues = null;
function pushConcurrentUpdateQueue(queue) {
if (concurrentQueues === null) {
concurrentQueues = [queue];
} else {
concurrentQueues.push(queue);
}
}
function finishQueueingConcurrentUpdates() {
// Transfer the interleaved updates onto the main queue. Each queue has a
// `pending` field and an `interleaved` field. When they are not null, they
// point to the last node in a circular linked list. We need to append the
// interleaved list to the end of the pending list by joining them into a
// single, circular list.
if (concurrentQueues !== null) {
for (var i = 0; i < concurrentQueues.length; i++) {
var queue = concurrentQueues[i];
var lastInterleavedUpdate = queue.interleaved;
if (lastInterleavedUpdate !== null) {
queue.interleaved = null;
var firstInterleavedUpdate = lastInterleavedUpdate.next;
var lastPendingUpdate = queue.pending;
if (lastPendingUpdate !== null) {
var firstPendingUpdate = lastPendingUpdate.next;
lastPendingUpdate.next = firstInterleavedUpdate;
lastInterleavedUpdate.next = firstPendingUpdate;
}
queue.pending = lastInterleavedUpdate;
}
}
concurrentQueues = null;
}
}
function enqueueConcurrentHookUpdate(fiber, queue, update, lane) {
var interleaved = queue.interleaved;
if (interleaved === null) {
// This is the first update. Create a circular list.
update.next = update; // At the end of the current render, this queue's interleaved updates will
// be transferred to the pending queue.
pushConcurrentUpdateQueue(queue);
} else {
update.next = interleaved.next;
interleaved.next = update;
}
queue.interleaved = update;
return markUpdateLaneFromFiberToRoot(fiber, lane);
}
function enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue, update, lane) {
var interleaved = queue.interleaved;
if (interleaved === null) {
// This is the first update. Create a circular list.
update.next = update; // At the end of the current render, this queue's interleaved updates will
// be transferred to the pending queue.
pushConcurrentUpdateQueue(queue);
} else {
update.next = interleaved.next;
interleaved.next = update;
}
queue.interleaved = update;
}
function enqueueConcurrentClassUpdate(fiber, queue, update, lane) {
var interleaved = queue.interleaved;
if (interleaved === null) {
// This is the first update. Create a circular list.
update.next = update; // At the end of the current render, this queue's interleaved updates will
// be transferred to the pending queue.
pushConcurrentUpdateQueue(queue);
} else {
update.next = interleaved.next;
interleaved.next = update;
}
queue.interleaved = update;
return markUpdateLaneFromFiberToRoot(fiber, lane);
}
function enqueueConcurrentRenderForLane(fiber, lane) {
return markUpdateLaneFromFiberToRoot(fiber, lane);
} // Calling this function outside this module should only be done for backwards
// compatibility and should always be accompanied by a warning.
var unsafe_markUpdateLaneFromFiberToRoot = markUpdateLaneFromFiberToRoot;
function markUpdateLaneFromFiberToRoot(sourceFiber, lane) {
// Update the source fiber's lanes
sourceFiber.lanes = mergeLanes(sourceFiber.lanes, lane);
var alternate = sourceFiber.alternate;
if (alternate !== null) {
alternate.lanes = mergeLanes(alternate.lanes, lane);
}
{
if (alternate === null && (sourceFiber.flags & (Placement | Hydrating)) !== NoFlags) {
warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
}
} // Walk the parent path to the root and update the child lanes.
var node = sourceFiber;
var parent = sourceFiber.return;
while (parent !== null) {
parent.childLanes = mergeLanes(parent.childLanes, lane);
alternate = parent.alternate;
if (alternate !== null) {
alternate.childLanes = mergeLanes(alternate.childLanes, lane);
} else {
{
if ((parent.flags & (Placement | Hydrating)) !== NoFlags) {
warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
}
}
}
node = parent;
parent = parent.return;
}
if (node.tag === HostRoot) {
var root = node.stateNode;
return root;
} else {
return null;
}
}
var UpdateState = 0;
var ReplaceState = 1;
var ForceUpdate = 2;
var CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`.
// It should only be read right after calling `processUpdateQueue`, via
// `checkHasForceUpdateAfterProcessing`.
var hasForceUpdate = false;
var didWarnUpdateInsideUpdate;
var currentlyProcessingQueue;
{
didWarnUpdateInsideUpdate = false;
currentlyProcessingQueue = null;
}
function initializeUpdateQueue(fiber) {
var queue = {
baseState: fiber.memoizedState,
firstBaseUpdate: null,
lastBaseUpdate: null,
shared: {
pending: null,
interleaved: null,
lanes: NoLanes
},
effects: null
};
fiber.updateQueue = queue;
}
function cloneUpdateQueue(current, workInProgress) {
// Clone the update queue from current. Unless it's already a clone.
var queue = workInProgress.updateQueue;
var currentQueue = current.updateQueue;
if (queue === currentQueue) {
var clone = {
baseState: currentQueue.baseState,
firstBaseUpdate: currentQueue.firstBaseUpdate,
lastBaseUpdate: currentQueue.lastBaseUpdate,
shared: currentQueue.shared,
effects: currentQueue.effects
};
workInProgress.updateQueue = clone;
}
}
function createUpdate(eventTime, lane) {
var update = {
eventTime: eventTime,
lane: lane,
tag: UpdateState,
payload: null,
callback: null,
next: null
};
return update;
}
function enqueueUpdate(fiber, update, lane) {
var updateQueue = fiber.updateQueue;
if (updateQueue === null) {
// Only occurs if the fiber has been unmounted.
return null;
}
var sharedQueue = updateQueue.shared;
{
if (currentlyProcessingQueue === sharedQueue && !didWarnUpdateInsideUpdate) {
error('An update (setState, replaceState, or forceUpdate) was scheduled ' + 'from inside an update function. Update functions should be pure, ' + 'with zero side-effects. Consider using componentDidUpdate or a ' + 'callback.');
didWarnUpdateInsideUpdate = true;
}
}
if (isUnsafeClassRenderPhaseUpdate()) {
// This is an unsafe render phase update. Add directly to the update
// queue so we can process it immediately during the current render.
var pending = sharedQueue.pending;
if (pending === null) {
// This is the first update. Create a circular list.
update.next = update;
} else {
update.next = pending.next;
pending.next = update;
}
sharedQueue.pending = update; // Update the childLanes even though we're most likely already rendering
// this fiber. This is for backwards compatibility in the case where you
// update a different component during render phase than the one that is
// currently renderings (a pattern that is accompanied by a warning).
return unsafe_markUpdateLaneFromFiberToRoot(fiber, lane);
} else {
return enqueueConcurrentClassUpdate(fiber, sharedQueue, update, lane);
}
}
function entangleTransitions(root, fiber, lane) {
var updateQueue = fiber.updateQueue;
if (updateQueue === null) {
// Only occurs if the fiber has been unmounted.
return;
}
var sharedQueue = updateQueue.shared;
if (isTransitionLane(lane)) {
var queueLanes = sharedQueue.lanes; // If any entangled lanes are no longer pending on the root, then they must
// have finished. We can remove them from the shared queue, which represents
// a superset of the actually pending lanes. In some cases we may entangle
// more than we need to, but that's OK. In fact it's worse if we *don't*
// entangle when we should.
queueLanes = intersectLanes(queueLanes, root.pendingLanes); // Entangle the new transition lane with the other transition lanes.
var newQueueLanes = mergeLanes(queueLanes, lane);
sharedQueue.lanes = newQueueLanes; // Even if queue.lanes already include lane, we don't know for certain if
// the lane finished since the last time we entangled it. So we need to
// entangle it again, just to be sure.
markRootEntangled(root, newQueueLanes);
}
}
function enqueueCapturedUpdate(workInProgress, capturedUpdate) {
// Captured updates are updates that are thrown by a child during the render
// phase. They should be discarded if the render is aborted. Therefore,
// we should only put them on the work-in-progress queue, not the current one.
var queue = workInProgress.updateQueue; // Check if the work-in-progress queue is a clone.
var current = workInProgress.alternate;
if (current !== null) {
var currentQueue = current.updateQueue;
if (queue === currentQueue) {
// The work-in-progress queue is the same as current. This happens when
// we bail out on a parent fiber that then captures an error thrown by
// a child. Since we want to append the update only to the work-in
// -progress queue, we need to clone the updates. We usually clone during
// processUpdateQueue, but that didn't happen in this case because we
// skipped over the parent when we bailed out.
var newFirst = null;
var newLast = null;
var firstBaseUpdate = queue.firstBaseUpdate;
if (firstBaseUpdate !== null) {
// Loop through the updates and clone them.
var update = firstBaseUpdate;
do {
var clone = {
eventTime: update.eventTime,
lane: update.lane,
tag: update.tag,
payload: update.payload,
callback: update.callback,
next: null
};
if (newLast === null) {
newFirst = newLast = clone;
} else {
newLast.next = clone;
newLast = clone;
}
update = update.next;
} while (update !== null); // Append the captured update the end of the cloned list.
if (newLast === null) {
newFirst = newLast = capturedUpdate;
} else {
newLast.next = capturedUpdate;
newLast = capturedUpdate;
}
} else {
// There are no base updates.
newFirst = newLast = capturedUpdate;
}
queue = {
baseState: currentQueue.baseState,
firstBaseUpdate: newFirst,
lastBaseUpdate: newLast,
shared: currentQueue.shared,
effects: currentQueue.effects
};
workInProgress.updateQueue = queue;
return;
}
} // Append the update to the end of the list.
var lastBaseUpdate = queue.lastBaseUpdate;
if (lastBaseUpdate === null) {
queue.firstBaseUpdate = capturedUpdate;
} else {
lastBaseUpdate.next = capturedUpdate;
}
queue.lastBaseUpdate = capturedUpdate;
}
function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {
switch (update.tag) {
case ReplaceState:
{
var payload = update.payload;
if (typeof payload === 'function') {
// Updater function
{
enterDisallowedContextReadInDEV();
}
var nextState = payload.call(instance, prevState, nextProps);
{
if ( workInProgress.mode & StrictLegacyMode) {
setIsStrictModeForDevtools(true);
try {
payload.call(instance, prevState, nextProps);
} finally {
setIsStrictModeForDevtools(false);
}
}
exitDisallowedContextReadInDEV();
}
return nextState;
} // State object
return payload;
}
case CaptureUpdate:
{
workInProgress.flags = workInProgress.flags & ~ShouldCapture | DidCapture;
}
// Intentional fallthrough
case UpdateState:
{
var _payload = update.payload;
var partialState;
if (typeof _payload === 'function') {
// Updater function
{
enterDisallowedContextReadInDEV();
}
partialState = _payload.call(instance, prevState, nextProps);
{
if ( workInProgress.mode & StrictLegacyMode) {
setIsStrictModeForDevtools(true);
try {
_payload.call(instance, prevState, nextProps);
} finally {
setIsStrictModeForDevtools(false);
}
}
exitDisallowedContextReadInDEV();
}
} else {
// Partial state object
partialState = _payload;
}
if (partialState === null || partialState === undefined) {
// Null and undefined are treated as no-ops.
return prevState;
} // Merge the partial state and the previous state.
return assign({}, prevState, partialState);
}
case ForceUpdate:
{
hasForceUpdate = true;
return prevState;
}
}
return prevState;
}
function processUpdateQueue(workInProgress, props, instance, renderLanes) {
// This is always non-null on a ClassComponent or HostRoot
var queue = workInProgress.updateQueue;
hasForceUpdate = false;
{
currentlyProcessingQueue = queue.shared;
}
var firstBaseUpdate = queue.firstBaseUpdate;
var lastBaseUpdate = queue.lastBaseUpdate; // Check if there are pending updates. If so, transfer them to the base queue.
var pendingQueue = queue.shared.pending;
if (pendingQueue !== null) {
queue.shared.pending = null; // The pending queue is circular. Disconnect the pointer between first
// and last so that it's non-circular.
var lastPendingUpdate = pendingQueue;
var firstPendingUpdate = lastPendingUpdate.next;
lastPendingUpdate.next = null; // Append pending updates to base queue
if (lastBaseUpdate === null) {
firstBaseUpdate = firstPendingUpdate;
} else {
lastBaseUpdate.next = firstPendingUpdate;
}
lastBaseUpdate = lastPendingUpdate; // If there's a current queue, and it's different from the base queue, then
// we need to transfer the updates to that queue, too. Because the base
// queue is a singly-linked list with no cycles, we can append to both
// lists and take advantage of structural sharing.
// TODO: Pass `current` as argument
var current = workInProgress.alternate;
if (current !== null) {
// This is always non-null on a ClassComponent or HostRoot
var currentQueue = current.updateQueue;
var currentLastBaseUpdate = currentQueue.lastBaseUpdate;
if (currentLastBaseUpdate !== lastBaseUpdate) {
if (currentLastBaseUpdate === null) {
currentQueue.firstBaseUpdate = firstPendingUpdate;
} else {
currentLastBaseUpdate.next = firstPendingUpdate;
}
currentQueue.lastBaseUpdate = lastPendingUpdate;
}
}
} // These values may change as we process the queue.
if (firstBaseUpdate !== null) {
// Iterate through the list of updates to compute the result.
var newState = queue.baseState; // TODO: Don't need to accumulate this. Instead, we can remove renderLanes
// from the original lanes.
var newLanes = NoLanes;
var newBaseState = null;
var newFirstBaseUpdate = null;
var newLastBaseUpdate = null;
var update = firstBaseUpdate;
do {
var updateLane = update.lane;
var updateEventTime = update.eventTime;
if (!isSubsetOfLanes(renderLanes, updateLane)) {
// Priority is insufficient. Skip this update. If this is the first
// skipped update, the previous update/state is the new base
// update/state.
var clone = {
eventTime: updateEventTime,
lane: updateLane,
tag: update.tag,
payload: update.payload,
callback: update.callback,
next: null
};
if (newLastBaseUpdate === null) {
newFirstBaseUpdate = newLastBaseUpdate = clone;
newBaseState = newState;
} else {
newLastBaseUpdate = newLastBaseUpdate.next = clone;
} // Update the remaining priority in the queue.
newLanes = mergeLanes(newLanes, updateLane);
} else {
// This update does have sufficient priority.
if (newLastBaseUpdate !== null) {
var _clone = {
eventTime: updateEventTime,
// This update is going to be committed so we never want uncommit
// it. Using NoLane works because 0 is a subset of all bitmasks, so
// this will never be skipped by the check above.
lane: NoLane,
tag: update.tag,
payload: update.payload,
callback: update.callback,
next: null
};
newLastBaseUpdate = newLastBaseUpdate.next = _clone;
} // Process this update.
newState = getStateFromUpdate(workInProgress, queue, update, newState, props, instance);
var callback = update.callback;
if (callback !== null && // If the update was already committed, we should not queue its
// callback again.
update.lane !== NoLane) {
workInProgress.flags |= Callback;
var effects = queue.effects;
if (effects === null) {
queue.effects = [update];
} else {
effects.push(update);
}
}
}
update = update.next;
if (update === null) {
pendingQueue = queue.shared.pending;
if (pendingQueue === null) {
break;
} else {
// An update was scheduled from inside a reducer. Add the new
// pending updates to the end of the list and keep processing.
var _lastPendingUpdate = pendingQueue; // Intentionally unsound. Pending updates form a circular list, but we
// unravel them when transferring them to the base queue.
var _firstPendingUpdate = _lastPendingUpdate.next;
_lastPendingUpdate.next = null;
update = _firstPendingUpdate;
queue.lastBaseUpdate = _lastPendingUpdate;
queue.shared.pending = null;
}
}
} while (true);
if (newLastBaseUpdate === null) {
newBaseState = newState;
}
queue.baseState = newBaseState;
queue.firstBaseUpdate = newFirstBaseUpdate;
queue.lastBaseUpdate = newLastBaseUpdate; // Interleaved updates are stored on a separate queue. We aren't going to
// process them during this render, but we do need to track which lanes
// are remaining.
var lastInterleaved = queue.shared.interleaved;
if (lastInterleaved !== null) {
var interleaved = lastInterleaved;
do {
newLanes = mergeLanes(newLanes, interleaved.lane);
interleaved = interleaved.next;
} while (interleaved !== lastInterleaved);
} else if (firstBaseUpdate === null) {
// `queue.lanes` is used for entangling transitions. We can set it back to
// zero once the queue is empty.
queue.shared.lanes = NoLanes;
} // Set the remaining expiration time to be whatever is remaining in the queue.
// This should be fine because the only two other things that contribute to
// expiration time are props and context. We're already in the middle of the
// begin phase by the time we start processing the queue, so we've already
// dealt with the props. Context in components that specify
// shouldComponentUpdate is tricky; but we'll have to account for
// that regardless.
markSkippedUpdateLanes(newLanes);
workInProgress.lanes = newLanes;
workInProgress.memoizedState = newState;
}
{
currentlyProcessingQueue = null;
}
}
function callCallback(callback, context) {
if (typeof callback !== 'function') {
throw new Error('Invalid argument passed as callback. Expected a function. Instead ' + ("received: " + callback));
}
callback.call(context);
}
function resetHasForceUpdateBeforeProcessing() {
hasForceUpdate = false;
}
function checkHasForceUpdateAfterProcessing() {
return hasForceUpdate;
}
function commitUpdateQueue(finishedWork, finishedQueue, instance) {
// Commit the effects
var effects = finishedQueue.effects;
finishedQueue.effects = null;
if (effects !== null) {
for (var i = 0; i < effects.length; i++) {
var effect = effects[i];
var callback = effect.callback;
if (callback !== null) {
effect.callback = null;
callCallback(callback, instance);
}
}
}
}
var fakeInternalInstance = {}; // React.Component uses a shared frozen object by default.
// We'll use it to determine whether we need to initialize legacy refs.
var emptyRefsObject = new React.Component().refs;
var didWarnAboutStateAssignmentForComponent;
var didWarnAboutUninitializedState;
var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
var didWarnAboutLegacyLifecyclesAndDerivedState;
var didWarnAboutUndefinedDerivedState;
var warnOnUndefinedDerivedState;
var warnOnInvalidCallback;
var didWarnAboutDirectlyAssigningPropsToState;
var didWarnAboutContextTypeAndContextTypes;
var didWarnAboutInvalidateContextType;
{
didWarnAboutStateAssignmentForComponent = new Set();
didWarnAboutUninitializedState = new Set();
didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
didWarnAboutDirectlyAssigningPropsToState = new Set();
didWarnAboutUndefinedDerivedState = new Set();
didWarnAboutContextTypeAndContextTypes = new Set();
didWarnAboutInvalidateContextType = new Set();
var didWarnOnInvalidCallback = new Set();
warnOnInvalidCallback = function (callback, callerName) {
if (callback === null || typeof callback === 'function') {
return;
}
var key = callerName + '_' + callback;
if (!didWarnOnInvalidCallback.has(key)) {
didWarnOnInvalidCallback.add(key);
error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
}
};
warnOnUndefinedDerivedState = function (type, partialState) {
if (partialState === undefined) {
var componentName = getComponentNameFromType(type) || 'Component';
if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
didWarnAboutUndefinedDerivedState.add(componentName);
error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
}
}
}; // This is so gross but it's at least non-critical and can be removed if
// it causes problems. This is meant to give a nicer error message for
// ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
// ...)) which otherwise throws a "_processChildContext is not a function"
// exception.
Object.defineProperty(fakeInternalInstance, '_processChildContext', {
enumerable: false,
value: function () {
throw new Error('_processChildContext is not available in React 16+. This likely ' + 'means you have multiple copies of React and are attempting to nest ' + 'a React 15 tree inside a React 16 tree using ' + "unstable_renderSubtreeIntoContainer, which isn't supported. Try " + 'to make sure you have only one copy of React (and ideally, switch ' + 'to ReactDOM.createPortal).');
}
});
Object.freeze(fakeInternalInstance);
}
function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) {
var prevState = workInProgress.memoizedState;
var partialState = getDerivedStateFromProps(nextProps, prevState);
{
if ( workInProgress.mode & StrictLegacyMode) {
setIsStrictModeForDevtools(true);
try {
// Invoke the function an extra time to help detect side-effects.
partialState = getDerivedStateFromProps(nextProps, prevState);
} finally {
setIsStrictModeForDevtools(false);
}
}
warnOnUndefinedDerivedState(ctor, partialState);
} // Merge the partial state and the previous state.
var memoizedState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState);
workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the
// base state.
if (workInProgress.lanes === NoLanes) {
// Queue is always non-null for classes
var updateQueue = workInProgress.updateQueue;
updateQueue.baseState = memoizedState;
}
}
var classComponentUpdater = {
isMounted: isMounted,
enqueueSetState: function (inst, payload, callback) {
var fiber = get(inst);
var eventTime = requestEventTime();
var lane = requestUpdateLane(fiber);
var update = createUpdate(eventTime, lane);
update.payload = payload;
if (callback !== undefined && callback !== null) {
{
warnOnInvalidCallback(callback, 'setState');
}
update.callback = callback;
}
var root = enqueueUpdate(fiber, update, lane);
if (root !== null) {
scheduleUpdateOnFiber(root, fiber, lane, eventTime);
entangleTransitions(root, fiber, lane);
}
{
markStateUpdateScheduled(fiber, lane);
}
},
enqueueReplaceState: function (inst, payload, callback) {
var fiber = get(inst);
var eventTime = requestEventTime();
var lane = requestUpdateLane(fiber);
var update = createUpdate(eventTime, lane);
update.tag = ReplaceState;
update.payload = payload;
if (callback !== undefined && callback !== null) {
{
warnOnInvalidCallback(callback, 'replaceState');
}
update.callback = callback;
}
var root = enqueueUpdate(fiber, update, lane);
if (root !== null) {
scheduleUpdateOnFiber(root, fiber, lane, eventTime);
entangleTransitions(root, fiber, lane);
}
{
markStateUpdateScheduled(fiber, lane);
}
},
enqueueForceUpdate: function (inst, callback) {
var fiber = get(inst);
var eventTime = requestEventTime();
var lane = requestUpdateLane(fiber);
var update = createUpdate(eventTime, lane);
update.tag = ForceUpdate;
if (callback !== undefined && callback !== null) {
{
warnOnInvalidCallback(callback, 'forceUpdate');
}
update.callback = callback;
}
var root = enqueueUpdate(fiber, update, lane);
if (root !== null) {
scheduleUpdateOnFiber(root, fiber, lane, eventTime);
entangleTransitions(root, fiber, lane);
}
{
markForceUpdateScheduled(fiber, lane);
}
}
};
function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) {
var instance = workInProgress.stateNode;
if (typeof instance.shouldComponentUpdate === 'function') {
var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
{
if ( workInProgress.mode & StrictLegacyMode) {
setIsStrictModeForDevtools(true);
try {
// Invoke the function an extra time to help detect side-effects.
shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
} finally {
setIsStrictModeForDevtools(false);
}
}
if (shouldUpdate === undefined) {
error('%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', getComponentNameFromType(ctor) || 'Component');
}
}
return shouldUpdate;
}
if (ctor.prototype && ctor.prototype.isPureReactComponent) {
return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
}
return true;
}
function checkClassInstance(workInProgress, ctor, newProps) {
var instance = workInProgress.stateNode;
{
var name = getComponentNameFromType(ctor) || 'Component';
var renderPresent = instance.render;
if (!renderPresent) {
if (ctor.prototype && typeof ctor.prototype.render === 'function') {
error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
} else {
error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
}
}
if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) {
error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name);
}
if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) {
error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name);
}
if (instance.propTypes) {
error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name);
}
if (instance.contextType) {
error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name);
}
{
if (instance.contextTypes) {
error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name);
}
if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
didWarnAboutContextTypeAndContextTypes.add(ctor);
error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
}
}
if (typeof instance.componentShouldUpdate === 'function') {
error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name);
}
if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component');
}
if (typeof instance.componentDidUnmount === 'function') {
error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name);
}
if (typeof instance.componentDidReceiveProps === 'function') {
error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name);
}
if (typeof instance.componentWillRecieveProps === 'function') {
error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name);
}
if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') {
error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name);
}
var hasMutatedProps = instance.props !== newProps;
if (instance.props !== undefined && hasMutatedProps) {
error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name);
}
if (instance.defaultProps) {
error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name);
}
if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor));
}
if (typeof instance.getDerivedStateFromProps === 'function') {
error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
}
if (typeof instance.getDerivedStateFromError === 'function') {
error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
}
if (typeof ctor.getSnapshotBeforeUpdate === 'function') {
error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name);
}
var _state = instance.state;
if (_state && (typeof _state !== 'object' || isArray(_state))) {
error('%s.state: must be set to an object or null', name);
}
if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') {
error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name);
}
}
}
function adoptClassInstance(workInProgress, instance) {
instance.updater = classComponentUpdater;
workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates
set(instance, workInProgress);
{
instance._reactInternalInstance = fakeInternalInstance;
}
}
function constructClassInstance(workInProgress, ctor, props) {
var isLegacyContextConsumer = false;
var unmaskedContext = emptyContextObject;
var context = emptyContextObject;
var contextType = ctor.contextType;
{
if ('contextType' in ctor) {
var isValid = // Allow null for conditional declaration
contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>
if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
didWarnAboutInvalidateContextType.add(ctor);
var addendum = '';
if (contextType === undefined) {
addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.';
} else if (typeof contextType !== 'object') {
addendum = ' However, it is set to a ' + typeof contextType + '.';
} else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
addendum = ' Did you accidentally pass the Context.Provider instead?';
} else if (contextType._context !== undefined) {
// <Context.Consumer>
addendum = ' Did you accidentally pass the Context.Consumer instead?';
} else {
addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
}
error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum);
}
}
}
if (typeof contextType === 'object' && contextType !== null) {
context = readContext(contextType);
} else {
unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
var contextTypes = ctor.contextTypes;
isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined;
context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject;
}
var instance = new ctor(props, context); // Instantiate twice to help detect side-effects.
{
if ( workInProgress.mode & StrictLegacyMode) {
setIsStrictModeForDevtools(true);
try {
instance = new ctor(props, context); // eslint-disable-line no-new
} finally {
setIsStrictModeForDevtools(false);
}
}
}
var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;
adoptClassInstance(workInProgress, instance);
{
if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
var componentName = getComponentNameFromType(ctor) || 'Component';
if (!didWarnAboutUninitializedState.has(componentName)) {
didWarnAboutUninitializedState.add(componentName);
error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName);
}
} // If new component APIs are defined, "unsafe" lifecycles won't be called.
// Warn about these lifecycles if they are present.
// Don't warn about react-lifecycles-compat polyfilled methods though.
if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
var foundWillMountName = null;
var foundWillReceivePropsName = null;
var foundWillUpdateName = null;
if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
foundWillMountName = 'componentWillMount';
} else if (typeof instance.UNSAFE_componentWillMount === 'function') {
foundWillMountName = 'UNSAFE_componentWillMount';
}
if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
foundWillReceivePropsName = 'componentWillReceiveProps';
} else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
}
if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
foundWillUpdateName = 'componentWillUpdate';
} else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
foundWillUpdateName = 'UNSAFE_componentWillUpdate';
}
if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
var _componentName = getComponentNameFromType(ctor) || 'Component';
var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';
if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n " + foundWillUpdateName : '');
}
}
}
} // Cache unmasked context so we can avoid recreating masked context unless necessary.
// ReactFiberContext usually updates this cache but can't for newly-created instances.
if (isLegacyContextConsumer) {
cacheContext(workInProgress, unmaskedContext, context);
}
return instance;
}
function callComponentWillMount(workInProgress, instance) {
var oldState = instance.state;
if (typeof instance.componentWillMount === 'function') {
instance.componentWillMount();
}
if (typeof instance.UNSAFE_componentWillMount === 'function') {
instance.UNSAFE_componentWillMount();
}
if (oldState !== instance.state) {
{
error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentNameFromFiber(workInProgress) || 'Component');
}
classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
}
}
function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) {
var oldState = instance.state;
if (typeof instance.componentWillReceiveProps === 'function') {
instance.componentWillReceiveProps(newProps, nextContext);
}
if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
}
if (instance.state !== oldState) {
{
var componentName = getComponentNameFromFiber(workInProgress) || 'Component';
if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
didWarnAboutStateAssignmentForComponent.add(componentName);
error('%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName);
}
}
classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
}
} // Invokes the mount life-cycles on a previously never rendered instance.
function mountClassInstance(workInProgress, ctor, newProps, renderLanes) {
{
checkClassInstance(workInProgress, ctor, newProps);
}
var instance = workInProgress.stateNode;
instance.props = newProps;
instance.state = workInProgress.memoizedState;
instance.refs = emptyRefsObject;
initializeUpdateQueue(workInProgress);
var contextType = ctor.contextType;
if (typeof contextType === 'object' && contextType !== null) {
instance.context = readContext(contextType);
} else {
var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
instance.context = getMaskedContext(workInProgress, unmaskedContext);
}
{
if (instance.state === newProps) {
var componentName = getComponentNameFromType(ctor) || 'Component';
if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
didWarnAboutDirectlyAssigningPropsToState.add(componentName);
error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName);
}
}
if (workInProgress.mode & StrictLegacyMode) {
ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);
}
{
ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);
}
}
instance.state = workInProgress.memoizedState;
var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
if (typeof getDerivedStateFromProps === 'function') {
applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
instance.state = workInProgress.memoizedState;
} // In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for components using the new APIs.
if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's
// process them now.
processUpdateQueue(workInProgress, newProps, instance, renderLanes);
instance.state = workInProgress.memoizedState;
}
if (typeof instance.componentDidMount === 'function') {
var fiberFlags = Update;
{
fiberFlags |= LayoutStatic;
}
if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) {
fiberFlags |= MountLayoutDev;
}
workInProgress.flags |= fiberFlags;
}
}
function resumeMountClassInstance(workInProgress, ctor, newProps, renderLanes) {
var instance = workInProgress.stateNode;
var oldProps = workInProgress.memoizedProps;
instance.props = oldProps;
var oldContext = instance.context;
var contextType = ctor.contextType;
var nextContext = emptyContextObject;
if (typeof contextType === 'object' && contextType !== null) {
nextContext = readContext(contextType);
} else {
var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);
}
var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
// ever the previously attempted to render - not the "current". However,
// during componentDidUpdate we pass the "current" props.
// In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for components using the new APIs.
if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
if (oldProps !== newProps || oldContext !== nextContext) {
callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
}
}
resetHasForceUpdateBeforeProcessing();
var oldState = workInProgress.memoizedState;
var newState = instance.state = oldState;
processUpdateQueue(workInProgress, newProps, instance, renderLanes);
newState = workInProgress.memoizedState;
if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
// If an update was already in progress, we should schedule an Update
// effect even though we're bailing out, so that cWU/cDU are called.
if (typeof instance.componentDidMount === 'function') {
var fiberFlags = Update;
{
fiberFlags |= LayoutStatic;
}
if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) {
fiberFlags |= MountLayoutDev;
}
workInProgress.flags |= fiberFlags;
}
return false;
}
if (typeof getDerivedStateFromProps === 'function') {
applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
newState = workInProgress.memoizedState;
}
var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
if (shouldUpdate) {
// In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for components using the new APIs.
if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
if (typeof instance.componentWillMount === 'function') {
instance.componentWillMount();
}
if (typeof instance.UNSAFE_componentWillMount === 'function') {
instance.UNSAFE_componentWillMount();
}
}
if (typeof instance.componentDidMount === 'function') {
var _fiberFlags = Update;
{
_fiberFlags |= LayoutStatic;
}
if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) {
_fiberFlags |= MountLayoutDev;
}
workInProgress.flags |= _fiberFlags;
}
} else {
// If an update was already in progress, we should schedule an Update
// effect even though we're bailing out, so that cWU/cDU are called.
if (typeof instance.componentDidMount === 'function') {
var _fiberFlags2 = Update;
{
_fiberFlags2 |= LayoutStatic;
}
if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) {
_fiberFlags2 |= MountLayoutDev;
}
workInProgress.flags |= _fiberFlags2;
} // If shouldComponentUpdate returned false, we should still update the
// memoized state to indicate that this work can be reused.
workInProgress.memoizedProps = newProps;
workInProgress.memoizedState = newState;
} // Update the existing instance's state, props, and context pointers even
// if shouldComponentUpdate returns false.
instance.props = newProps;
instance.state = newState;
instance.context = nextContext;
return shouldUpdate;
} // Invokes the update life-cycles and returns false if it shouldn't rerender.
function updateClassInstance(current, workInProgress, ctor, newProps, renderLanes) {
var instance = workInProgress.stateNode;
cloneUpdateQueue(current, workInProgress);
var unresolvedOldProps = workInProgress.memoizedProps;
var oldProps = workInProgress.type === workInProgress.elementType ? unresolvedOldProps : resolveDefaultProps(workInProgress.type, unresolvedOldProps);
instance.props = oldProps;
var unresolvedNewProps = workInProgress.pendingProps;
var oldContext = instance.context;
var contextType = ctor.contextType;
var nextContext = emptyContextObject;
if (typeof contextType === 'object' && contextType !== null) {
nextContext = readContext(contextType);
} else {
var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);
}
var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
// ever the previously attempted to render - not the "current". However,
// during componentDidUpdate we pass the "current" props.
// In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for components using the new APIs.
if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
if (unresolvedOldProps !== unresolvedNewProps || oldContext !== nextContext) {
callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
}
}
resetHasForceUpdateBeforeProcessing();
var oldState = workInProgress.memoizedState;
var newState = instance.state = oldState;
processUpdateQueue(workInProgress, newProps, instance, renderLanes);
newState = workInProgress.memoizedState;
if (unresolvedOldProps === unresolvedNewProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing() && !(enableLazyContextPropagation )) {
// If an update was already in progress, we should schedule an Update
// effect even though we're bailing out, so that cWU/cDU are called.
if (typeof instance.componentDidUpdate === 'function') {
if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
workInProgress.flags |= Update;
}
}
if (typeof instance.getSnapshotBeforeUpdate === 'function') {
if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
workInProgress.flags |= Snapshot;
}
}
return false;
}
if (typeof getDerivedStateFromProps === 'function') {
applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
newState = workInProgress.memoizedState;
}
var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) || // TODO: In some cases, we'll end up checking if context has changed twice,
// both before and after `shouldComponentUpdate` has been called. Not ideal,
// but I'm loath to refactor this function. This only happens for memoized
// components so it's not that common.
enableLazyContextPropagation ;
if (shouldUpdate) {
// In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for components using the new APIs.
if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {
if (typeof instance.componentWillUpdate === 'function') {
instance.componentWillUpdate(newProps, newState, nextContext);
}
if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
}
}
if (typeof instance.componentDidUpdate === 'function') {
workInProgress.flags |= Update;
}
if (typeof instance.getSnapshotBeforeUpdate === 'function') {
workInProgress.flags |= Snapshot;
}
} else {
// If an update was already in progress, we should schedule an Update
// effect even though we're bailing out, so that cWU/cDU are called.
if (typeof instance.componentDidUpdate === 'function') {
if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
workInProgress.flags |= Update;
}
}
if (typeof instance.getSnapshotBeforeUpdate === 'function') {
if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
workInProgress.flags |= Snapshot;
}
} // If shouldComponentUpdate returned false, we should still update the
// memoized props/state to indicate that this work can be reused.
workInProgress.memoizedProps = newProps;
workInProgress.memoizedState = newState;
} // Update the existing instance's state, props, and context pointers even
// if shouldComponentUpdate returns false.
instance.props = newProps;
instance.state = newState;
instance.context = nextContext;
return shouldUpdate;
}
var didWarnAboutMaps;
var didWarnAboutGenerators;
var didWarnAboutStringRefs;
var ownerHasKeyUseWarning;
var ownerHasFunctionTypeWarning;
var warnForMissingKey = function (child, returnFiber) {};
{
didWarnAboutMaps = false;
didWarnAboutGenerators = false;
didWarnAboutStringRefs = {};
/**
* Warn if there's no key explicitly set on dynamic arrays of children or
* object keys are not valid. This allows us to keep track of children between
* updates.
*/
ownerHasKeyUseWarning = {};
ownerHasFunctionTypeWarning = {};
warnForMissingKey = function (child, returnFiber) {
if (child === null || typeof child !== 'object') {
return;
}
if (!child._store || child._store.validated || child.key != null) {
return;
}
if (typeof child._store !== 'object') {
throw new Error('React Component in warnForMissingKey should have a _store. ' + 'This error is likely caused by a bug in React. Please file an issue.');
}
child._store.validated = true;
var componentName = getComponentNameFromFiber(returnFiber) || 'Component';
if (ownerHasKeyUseWarning[componentName]) {
return;
}
ownerHasKeyUseWarning[componentName] = true;
error('Each child in a list should have a unique ' + '"key" prop. See https://reactjs.org/link/warning-keys for ' + 'more information.');
};
}
function coerceRef(returnFiber, current, element) {
var mixedRef = element.ref;
if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {
{
// TODO: Clean this up once we turn on the string ref warning for
// everyone, because the strict mode case will no longer be relevant
if ((returnFiber.mode & StrictLegacyMode || warnAboutStringRefs) && // We warn in ReactElement.js if owner and self are equal for string refs
// because these cannot be automatically converted to an arrow function
// using a codemod. Therefore, we don't have to warn about string refs again.
!(element._owner && element._self && element._owner.stateNode !== element._self)) {
var componentName = getComponentNameFromFiber(returnFiber) || 'Component';
if (!didWarnAboutStringRefs[componentName]) {
{
error('A string ref, "%s", has been found within a strict mode tree. ' + 'String refs are a source of potential bugs and should be avoided. ' + 'We recommend using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', mixedRef);
}
didWarnAboutStringRefs[componentName] = true;
}
}
}
if (element._owner) {
var owner = element._owner;
var inst;
if (owner) {
var ownerFiber = owner;
if (ownerFiber.tag !== ClassComponent) {
throw new Error('Function components cannot have string refs. ' + 'We recommend using useRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref');
}
inst = ownerFiber.stateNode;
}
if (!inst) {
throw new Error("Missing owner for string ref " + mixedRef + ". This error is likely caused by a " + 'bug in React. Please file an issue.');
} // Assigning this to a const so Flow knows it won't change in the closure
var resolvedInst = inst;
{
checkPropStringCoercion(mixedRef, 'ref');
}
var stringRef = '' + mixedRef; // Check if previous string ref matches new string ref
if (current !== null && current.ref !== null && typeof current.ref === 'function' && current.ref._stringRef === stringRef) {
return current.ref;
}
var ref = function (value) {
var refs = resolvedInst.refs;
if (refs === emptyRefsObject) {
// This is a lazy pooled frozen object, so we need to initialize.
refs = resolvedInst.refs = {};
}
if (value === null) {
delete refs[stringRef];
} else {
refs[stringRef] = value;
}
};
ref._stringRef = stringRef;
return ref;
} else {
if (typeof mixedRef !== 'string') {
throw new Error('Expected ref to be a function, a string, an object returned by React.createRef(), or null.');
}
if (!element._owner) {
throw new Error("Element ref was specified as a string (" + mixedRef + ") but no owner was set. This could happen for one of" + ' the following reasons:\n' + '1. You may be adding a ref to a function component\n' + "2. You may be adding a ref to a component that was not created inside a component's render method\n" + '3. You have multiple copies of React loaded\n' + 'See https://reactjs.org/link/refs-must-have-owner for more information.');
}
}
}
return mixedRef;
}
function throwOnInvalidObjectType(returnFiber, newChild) {
var childString = Object.prototype.toString.call(newChild);
throw new Error("Objects are not valid as a React child (found: " + (childString === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : childString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.');
}
function warnOnFunctionType(returnFiber) {
{
var componentName = getComponentNameFromFiber(returnFiber) || 'Component';
if (ownerHasFunctionTypeWarning[componentName]) {
return;
}
ownerHasFunctionTypeWarning[componentName] = true;
error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.');
}
}
function resolveLazy(lazyType) {
var payload = lazyType._payload;
var init = lazyType._init;
return init(payload);
} // This wrapper function exists because I expect to clone the code in each path
// to be able to optimize each path individually by branching early. This needs
// a compiler or we can do it manually. Helpers that don't need this branching
// live outside of this function.
function ChildReconciler(shouldTrackSideEffects) {
function deleteChild(returnFiber, childToDelete) {
if (!shouldTrackSideEffects) {
// Noop.
return;
}
var deletions = returnFiber.deletions;
if (deletions === null) {
returnFiber.deletions = [childToDelete];
returnFiber.flags |= ChildDeletion;
} else {
deletions.push(childToDelete);
}
}
function deleteRemainingChildren(returnFiber, currentFirstChild) {
if (!shouldTrackSideEffects) {
// Noop.
return null;
} // TODO: For the shouldClone case, this could be micro-optimized a bit by
// assuming that after the first child we've already added everything.
var childToDelete = currentFirstChild;
while (childToDelete !== null) {
deleteChild(returnFiber, childToDelete);
childToDelete = childToDelete.sibling;
}
return null;
}
function mapRemainingChildren(returnFiber, currentFirstChild) {
// Add the remaining children to a temporary map so that we can find them by
// keys quickly. Implicit (null) keys get added to this set with their index
// instead.
var existingChildren = new Map();
var existingChild = currentFirstChild;
while (existingChild !== null) {
if (existingChild.key !== null) {
existingChildren.set(existingChild.key, existingChild);
} else {
existingChildren.set(existingChild.index, existingChild);
}
existingChild = existingChild.sibling;
}
return existingChildren;
}
function useFiber(fiber, pendingProps) {
// We currently set sibling to null and index to 0 here because it is easy
// to forget to do before returning it. E.g. for the single child case.
var clone = createWorkInProgress(fiber, pendingProps);
clone.index = 0;
clone.sibling = null;
return clone;
}
function placeChild(newFiber, lastPlacedIndex, newIndex) {
newFiber.index = newIndex;
if (!shouldTrackSideEffects) {
// During hydration, the useId algorithm needs to know which fibers are
// part of a list of children (arrays, iterators).
newFiber.flags |= Forked;
return lastPlacedIndex;
}
var current = newFiber.alternate;
if (current !== null) {
var oldIndex = current.index;
if (oldIndex < lastPlacedIndex) {
// This is a move.
newFiber.flags |= Placement;
return lastPlacedIndex;
} else {
// This item can stay in place.
return oldIndex;
}
} else {
// This is an insertion.
newFiber.flags |= Placement;
return lastPlacedIndex;
}
}
function placeSingleChild(newFiber) {
// This is simpler for the single child case. We only need to do a
// placement for inserting new children.
if (shouldTrackSideEffects && newFiber.alternate === null) {
newFiber.flags |= Placement;
}
return newFiber;
}
function updateTextNode(returnFiber, current, textContent, lanes) {
if (current === null || current.tag !== HostText) {
// Insert
var created = createFiberFromText(textContent, returnFiber.mode, lanes);
created.return = returnFiber;
return created;
} else {
// Update
var existing = useFiber(current, textContent);
existing.return = returnFiber;
return existing;
}
}
function updateElement(returnFiber, current, element, lanes) {
var elementType = element.type;
if (elementType === REACT_FRAGMENT_TYPE) {
return updateFragment(returnFiber, current, element.props.children, lanes, element.key);
}
if (current !== null) {
if (current.elementType === elementType || ( // Keep this check inline so it only runs on the false path:
isCompatibleFamilyForHotReloading(current, element) ) || // Lazy types should reconcile their resolved type.
// We need to do this after the Hot Reloading check above,
// because hot reloading has different semantics than prod because
// it doesn't resuspend. So we can't let the call below suspend.
typeof elementType === 'object' && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === current.type) {
// Move based on index
var existing = useFiber(current, element.props);
existing.ref = coerceRef(returnFiber, current, element);
existing.return = returnFiber;
{
existing._debugSource = element._source;
existing._debugOwner = element._owner;
}
return existing;
}
} // Insert
var created = createFiberFromElement(element, returnFiber.mode, lanes);
created.ref = coerceRef(returnFiber, current, element);
created.return = returnFiber;
return created;
}
function updatePortal(returnFiber, current, portal, lanes) {
if (current === null || current.tag !== HostPortal || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation) {
// Insert
var created = createFiberFromPortal(portal, returnFiber.mode, lanes);
created.return = returnFiber;
return created;
} else {
// Update
var existing = useFiber(current, portal.children || []);
existing.return = returnFiber;
return existing;
}
}
function updateFragment(returnFiber, current, fragment, lanes, key) {
if (current === null || current.tag !== Fragment) {
// Insert
var created = createFiberFromFragment(fragment, returnFiber.mode, lanes, key);
created.return = returnFiber;
return created;
} else {
// Update
var existing = useFiber(current, fragment);
existing.return = returnFiber;
return existing;
}
}
function createChild(returnFiber, newChild, lanes) {
if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') {
// Text nodes don't have keys. If the previous node is implicitly keyed
// we can continue to replace it without aborting even if it is not a text
// node.
var created = createFiberFromText('' + newChild, returnFiber.mode, lanes);
created.return = returnFiber;
return created;
}
if (typeof newChild === 'object' && newChild !== null) {
switch (newChild.$$typeof) {
case REACT_ELEMENT_TYPE:
{
var _created = createFiberFromElement(newChild, returnFiber.mode, lanes);
_created.ref = coerceRef(returnFiber, null, newChild);
_created.return = returnFiber;
return _created;
}
case REACT_PORTAL_TYPE:
{
var _created2 = createFiberFromPortal(newChild, returnFiber.mode, lanes);
_created2.return = returnFiber;
return _created2;
}
case REACT_LAZY_TYPE:
{
var payload = newChild._payload;
var init = newChild._init;
return createChild(returnFiber, init(payload), lanes);
}
}
if (isArray(newChild) || getIteratorFn(newChild)) {
var _created3 = createFiberFromFragment(newChild, returnFiber.mode, lanes, null);
_created3.return = returnFiber;
return _created3;
}
throwOnInvalidObjectType(returnFiber, newChild);
}
{
if (typeof newChild === 'function') {
warnOnFunctionType(returnFiber);
}
}
return null;
}
function updateSlot(returnFiber, oldFiber, newChild, lanes) {
// Update the fiber if the keys match, otherwise return null.
var key = oldFiber !== null ? oldFiber.key : null;
if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') {
// Text nodes don't have keys. If the previous node is implicitly keyed
// we can continue to replace it without aborting even if it is not a text
// node.
if (key !== null) {
return null;
}
return updateTextNode(returnFiber, oldFiber, '' + newChild, lanes);
}
if (typeof newChild === 'object' && newChild !== null) {
switch (newChild.$$typeof) {
case REACT_ELEMENT_TYPE:
{
if (newChild.key === key) {
return updateElement(returnFiber, oldFiber, newChild, lanes);
} else {
return null;
}
}
case REACT_PORTAL_TYPE:
{
if (newChild.key === key) {
return updatePortal(returnFiber, oldFiber, newChild, lanes);
} else {
return null;
}
}
case REACT_LAZY_TYPE:
{
var payload = newChild._payload;
var init = newChild._init;
return updateSlot(returnFiber, oldFiber, init(payload), lanes);
}
}
if (isArray(newChild) || getIteratorFn(newChild)) {
if (key !== null) {
return null;
}
return updateFragment(returnFiber, oldFiber, newChild, lanes, null);
}
throwOnInvalidObjectType(returnFiber, newChild);
}
{
if (typeof newChild === 'function') {
warnOnFunctionType(returnFiber);
}
}
return null;
}
function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) {
if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') {
// Text nodes don't have keys, so we neither have to check the old nor
// new node for the key. If both are text nodes, they match.
var matchedFiber = existingChildren.get(newIdx) || null;
return updateTextNode(returnFiber, matchedFiber, '' + newChild, lanes);
}
if (typeof newChild === 'object' && newChild !== null) {
switch (newChild.$$typeof) {
case REACT_ELEMENT_TYPE:
{
var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
return updateElement(returnFiber, _matchedFiber, newChild, lanes);
}
case REACT_PORTAL_TYPE:
{
var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
return updatePortal(returnFiber, _matchedFiber2, newChild, lanes);
}
case REACT_LAZY_TYPE:
var payload = newChild._payload;
var init = newChild._init;
return updateFromMap(existingChildren, returnFiber, newIdx, init(payload), lanes);
}
if (isArray(newChild) || getIteratorFn(newChild)) {
var _matchedFiber3 = existingChildren.get(newIdx) || null;
return updateFragment(returnFiber, _matchedFiber3, newChild, lanes, null);
}
throwOnInvalidObjectType(returnFiber, newChild);
}
{
if (typeof newChild === 'function') {
warnOnFunctionType(returnFiber);
}
}
return null;
}
/**
* Warns if there is a duplicate or missing key
*/
function warnOnInvalidKey(child, knownKeys, returnFiber) {
{
if (typeof child !== 'object' || child === null) {
return knownKeys;
}
switch (child.$$typeof) {
case REACT_ELEMENT_TYPE:
case REACT_PORTAL_TYPE:
warnForMissingKey(child, returnFiber);
var key = child.key;
if (typeof key !== 'string') {
break;
}
if (knownKeys === null) {
knownKeys = new Set();
knownKeys.add(key);
break;
}
if (!knownKeys.has(key)) {
knownKeys.add(key);
break;
}
error('Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.', key);
break;
case REACT_LAZY_TYPE:
var payload = child._payload;
var init = child._init;
warnOnInvalidKey(init(payload), knownKeys, returnFiber);
break;
}
}
return knownKeys;
}
function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) {
// This algorithm can't optimize by searching from both ends since we
// don't have backpointers on fibers. I'm trying to see how far we can get
// with that model. If it ends up not being worth the tradeoffs, we can
// add it later.
// Even with a two ended optimization, we'd want to optimize for the case
// where there are few changes and brute force the comparison instead of
// going for the Map. It'd like to explore hitting that path first in
// forward-only mode and only go for the Map once we notice that we need
// lots of look ahead. This doesn't handle reversal as well as two ended
// search but that's unusual. Besides, for the two ended optimization to
// work on Iterables, we'd need to copy the whole set.
// In this first iteration, we'll just live with hitting the bad case
// (adding everything to a Map) in for every insert/move.
// If you change this code, also update reconcileChildrenIterator() which
// uses the same algorithm.
{
// First, validate keys.
var knownKeys = null;
for (var i = 0; i < newChildren.length; i++) {
var child = newChildren[i];
knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber);
}
}
var resultingFirstChild = null;
var previousNewFiber = null;
var oldFiber = currentFirstChild;
var lastPlacedIndex = 0;
var newIdx = 0;
var nextOldFiber = null;
for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
if (oldFiber.index > newIdx) {
nextOldFiber = oldFiber;
oldFiber = null;
} else {
nextOldFiber = oldFiber.sibling;
}
var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], lanes);
if (newFiber === null) {
// TODO: This breaks on empty slots like null children. That's
// unfortunate because it triggers the slow path all the time. We need
// a better way to communicate whether this was a miss or null,
// boolean, undefined, etc.
if (oldFiber === null) {
oldFiber = nextOldFiber;
}
break;
}
if (shouldTrackSideEffects) {
if (oldFiber && newFiber.alternate === null) {
// We matched the slot, but we didn't reuse the existing fiber, so we
// need to delete the existing child.
deleteChild(returnFiber, oldFiber);
}
}
lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
if (previousNewFiber === null) {
// TODO: Move out of the loop. This only happens for the first run.
resultingFirstChild = newFiber;
} else {
// TODO: Defer siblings if we're not at the right index for this slot.
// I.e. if we had null values before, then we want to defer this
// for each null value. However, we also don't want to call updateSlot
// with the previous one.
previousNewFiber.sibling = newFiber;
}
previousNewFiber = newFiber;
oldFiber = nextOldFiber;
}
if (newIdx === newChildren.length) {
// We've reached the end of the new children. We can delete the rest.
deleteRemainingChildren(returnFiber, oldFiber);
if (getIsHydrating()) {
var numberOfForks = newIdx;
pushTreeFork(returnFiber, numberOfForks);
}
return resultingFirstChild;
}
if (oldFiber === null) {
// If we don't have any more existing children we can choose a fast path
// since the rest will all be insertions.
for (; newIdx < newChildren.length; newIdx++) {
var _newFiber = createChild(returnFiber, newChildren[newIdx], lanes);
if (_newFiber === null) {
continue;
}
lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);
if (previousNewFiber === null) {
// TODO: Move out of the loop. This only happens for the first run.
resultingFirstChild = _newFiber;
} else {
previousNewFiber.sibling = _newFiber;
}
previousNewFiber = _newFiber;
}
if (getIsHydrating()) {
var _numberOfForks = newIdx;
pushTreeFork(returnFiber, _numberOfForks);
}
return resultingFirstChild;
} // Add all children to a key map for quick lookups.
var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.
for (; newIdx < newChildren.length; newIdx++) {
var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], lanes);
if (_newFiber2 !== null) {
if (shouldTrackSideEffects) {
if (_newFiber2.alternate !== null) {
// The new fiber is a work in progress, but if there exists a
// current, that means that we reused the fiber. We need to delete
// it from the child list so that we don't add it to the deletion
// list.
existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
}
}
lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);
if (previousNewFiber === null) {
resultingFirstChild = _newFiber2;
} else {
previousNewFiber.sibling = _newFiber2;
}
previousNewFiber = _newFiber2;
}
}
if (shouldTrackSideEffects) {
// Any existing children that weren't consumed above were deleted. We need
// to add them to the deletion list.
existingChildren.forEach(function (child) {
return deleteChild(returnFiber, child);
});
}
if (getIsHydrating()) {
var _numberOfForks2 = newIdx;
pushTreeFork(returnFiber, _numberOfForks2);
}
return resultingFirstChild;
}
function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, lanes) {
// This is the same implementation as reconcileChildrenArray(),
// but using the iterator instead.
var iteratorFn = getIteratorFn(newChildrenIterable);
if (typeof iteratorFn !== 'function') {
throw new Error('An object is not an iterable. This error is likely caused by a bug in ' + 'React. Please file an issue.');
}
{
// We don't support rendering Generators because it's a mutation.
// See https://github.com/facebook/react/issues/12995
if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag
newChildrenIterable[Symbol.toStringTag] === 'Generator') {
if (!didWarnAboutGenerators) {
error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.');
}
didWarnAboutGenerators = true;
} // Warn about using Maps as children
if (newChildrenIterable.entries === iteratorFn) {
if (!didWarnAboutMaps) {
error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
}
didWarnAboutMaps = true;
} // First, validate keys.
// We'll get a different iterator later for the main pass.
var _newChildren = iteratorFn.call(newChildrenIterable);
if (_newChildren) {
var knownKeys = null;
var _step = _newChildren.next();
for (; !_step.done; _step = _newChildren.next()) {
var child = _step.value;
knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber);
}
}
}
var newChildren = iteratorFn.call(newChildrenIterable);
if (newChildren == null) {
throw new Error('An iterable object provided no iterator.');
}
var resultingFirstChild = null;
var previousNewFiber = null;
var oldFiber = currentFirstChild;
var lastPlacedIndex = 0;
var newIdx = 0;
var nextOldFiber = null;
var step = newChildren.next();
for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
if (oldFiber.index > newIdx) {
nextOldFiber = oldFiber;
oldFiber = null;
} else {
nextOldFiber = oldFiber.sibling;
}
var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes);
if (newFiber === null) {
// TODO: This breaks on empty slots like null children. That's
// unfortunate because it triggers the slow path all the time. We need
// a better way to communicate whether this was a miss or null,
// boolean, undefined, etc.
if (oldFiber === null) {
oldFiber = nextOldFiber;
}
break;
}
if (shouldTrackSideEffects) {
if (oldFiber && newFiber.alternate === null) {
// We matched the slot, but we didn't reuse the existing fiber, so we
// need to delete the existing child.
deleteChild(returnFiber, oldFiber);
}
}
lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
if (previousNewFiber === null) {
// TODO: Move out of the loop. This only happens for the first run.
resultingFirstChild = newFiber;
} else {
// TODO: Defer siblings if we're not at the right index for this slot.
// I.e. if we had null values before, then we want to defer this
// for each null value. However, we also don't want to call updateSlot
// with the previous one.
previousNewFiber.sibling = newFiber;
}
previousNewFiber = newFiber;
oldFiber = nextOldFiber;
}
if (step.done) {
// We've reached the end of the new children. We can delete the rest.
deleteRemainingChildren(returnFiber, oldFiber);
if (getIsHydrating()) {
var numberOfForks = newIdx;
pushTreeFork(returnFiber, numberOfForks);
}
return resultingFirstChild;
}
if (oldFiber === null) {
// If we don't have any more existing children we can choose a fast path
// since the rest will all be insertions.
for (; !step.done; newIdx++, step = newChildren.next()) {
var _newFiber3 = createChild(returnFiber, step.value, lanes);
if (_newFiber3 === null) {
continue;
}
lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);
if (previousNewFiber === null) {
// TODO: Move out of the loop. This only happens for the first run.
resultingFirstChild = _newFiber3;
} else {
previousNewFiber.sibling = _newFiber3;
}
previousNewFiber = _newFiber3;
}
if (getIsHydrating()) {
var _numberOfForks3 = newIdx;
pushTreeFork(returnFiber, _numberOfForks3);
}
return resultingFirstChild;
} // Add all children to a key map for quick lookups.
var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.
for (; !step.done; newIdx++, step = newChildren.next()) {
var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, lanes);
if (_newFiber4 !== null) {
if (shouldTrackSideEffects) {
if (_newFiber4.alternate !== null) {
// The new fiber is a work in progress, but if there exists a
// current, that means that we reused the fiber. We need to delete
// it from the child list so that we don't add it to the deletion
// list.
existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
}
}
lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);
if (previousNewFiber === null) {
resultingFirstChild = _newFiber4;
} else {
previousNewFiber.sibling = _newFiber4;
}
previousNewFiber = _newFiber4;
}
}
if (shouldTrackSideEffects) {
// Any existing children that weren't consumed above were deleted. We need
// to add them to the deletion list.
existingChildren.forEach(function (child) {
return deleteChild(returnFiber, child);
});
}
if (getIsHydrating()) {
var _numberOfForks4 = newIdx;
pushTreeFork(returnFiber, _numberOfForks4);
}
return resultingFirstChild;
}
function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, lanes) {
// There's no need to check for keys on text nodes since we don't have a
// way to define them.
if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
// We already have an existing node so let's just update it and delete
// the rest.
deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
var existing = useFiber(currentFirstChild, textContent);
existing.return = returnFiber;
return existing;
} // The existing first child is not a text node so we need to create one
// and delete the existing ones.
deleteRemainingChildren(returnFiber, currentFirstChild);
var created = createFiberFromText(textContent, returnFiber.mode, lanes);
created.return = returnFiber;
return created;
}
function reconcileSingleElement(returnFiber, currentFirstChild, element, lanes) {
var key = element.key;
var child = currentFirstChild;
while (child !== null) {
// TODO: If key === null and child.key === null, then this only applies to
// the first item in the list.
if (child.key === key) {
var elementType = element.type;
if (elementType === REACT_FRAGMENT_TYPE) {
if (child.tag === Fragment) {
deleteRemainingChildren(returnFiber, child.sibling);
var existing = useFiber(child, element.props.children);
existing.return = returnFiber;
{
existing._debugSource = element._source;
existing._debugOwner = element._owner;
}
return existing;
}
} else {
if (child.elementType === elementType || ( // Keep this check inline so it only runs on the false path:
isCompatibleFamilyForHotReloading(child, element) ) || // Lazy types should reconcile their resolved type.
// We need to do this after the Hot Reloading check above,
// because hot reloading has different semantics than prod because
// it doesn't resuspend. So we can't let the call below suspend.
typeof elementType === 'object' && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === child.type) {
deleteRemainingChildren(returnFiber, child.sibling);
var _existing = useFiber(child, element.props);
_existing.ref = coerceRef(returnFiber, child, element);
_existing.return = returnFiber;
{
_existing._debugSource = element._source;
_existing._debugOwner = element._owner;
}
return _existing;
}
} // Didn't match.
deleteRemainingChildren(returnFiber, child);
break;
} else {
deleteChild(returnFiber, child);
}
child = child.sibling;
}
if (element.type === REACT_FRAGMENT_TYPE) {
var created = createFiberFromFragment(element.props.children, returnFiber.mode, lanes, element.key);
created.return = returnFiber;
return created;
} else {
var _created4 = createFiberFromElement(element, returnFiber.mode, lanes);
_created4.ref = coerceRef(returnFiber, currentFirstChild, element);
_created4.return = returnFiber;
return _created4;
}
}
function reconcileSinglePortal(returnFiber, currentFirstChild, portal, lanes) {
var key = portal.key;
var child = currentFirstChild;
while (child !== null) {
// TODO: If key === null and child.key === null, then this only applies to
// the first item in the list.
if (child.key === key) {
if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
deleteRemainingChildren(returnFiber, child.sibling);
var existing = useFiber(child, portal.children || []);
existing.return = returnFiber;
return existing;
} else {
deleteRemainingChildren(returnFiber, child);
break;
}
} else {
deleteChild(returnFiber, child);
}
child = child.sibling;
}
var created = createFiberFromPortal(portal, returnFiber.mode, lanes);
created.return = returnFiber;
return created;
} // This API will tag the children with the side-effect of the reconciliation
// itself. They will be added to the side-effect list as we pass through the
// children and the parent.
function reconcileChildFibers(returnFiber, currentFirstChild, newChild, lanes) {
// This function is not recursive.
// If the top level item is an array, we treat it as a set of children,
// not as a fragment. Nested arrays on the other hand will be treated as
// fragment nodes. Recursion happens at the normal flow.
// Handle top level unkeyed fragments as if they were arrays.
// This leads to an ambiguity between <>{[...]}</> and <>...</>.
// We treat the ambiguous cases above the same.
var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;
if (isUnkeyedTopLevelFragment) {
newChild = newChild.props.children;
} // Handle object types
if (typeof newChild === 'object' && newChild !== null) {
switch (newChild.$$typeof) {
case REACT_ELEMENT_TYPE:
return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, lanes));
case REACT_PORTAL_TYPE:
return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, lanes));
case REACT_LAZY_TYPE:
var payload = newChild._payload;
var init = newChild._init; // TODO: This function is supposed to be non-recursive.
return reconcileChildFibers(returnFiber, currentFirstChild, init(payload), lanes);
}
if (isArray(newChild)) {
return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, lanes);
}
if (getIteratorFn(newChild)) {
return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, lanes);
}
throwOnInvalidObjectType(returnFiber, newChild);
}
if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') {
return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, lanes));
}
{
if (typeof newChild === 'function') {
warnOnFunctionType(returnFiber);
}
} // Remaining cases are all treated as empty.
return deleteRemainingChildren(returnFiber, currentFirstChild);
}
return reconcileChildFibers;
}
var reconcileChildFibers = ChildReconciler(true);
var mountChildFibers = ChildReconciler(false);
function cloneChildFibers(current, workInProgress) {
if (current !== null && workInProgress.child !== current.child) {
throw new Error('Resuming work not yet implemented.');
}
if (workInProgress.child === null) {
return;
}
var currentChild = workInProgress.child;
var newChild = createWorkInProgress(currentChild, currentChild.pendingProps);
workInProgress.child = newChild;
newChild.return = workInProgress;
while (currentChild.sibling !== null) {
currentChild = currentChild.sibling;
newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps);
newChild.return = workInProgress;
}
newChild.sibling = null;
} // Reset a workInProgress child set to prepare it for a second pass.
function resetChildFibers(workInProgress, lanes) {
var child = workInProgress.child;
while (child !== null) {
resetWorkInProgress(child, lanes);
child = child.sibling;
}
}
var NO_CONTEXT = {};
var contextStackCursor$1 = createCursor(NO_CONTEXT);
var contextFiberStackCursor = createCursor(NO_CONTEXT);
var rootInstanceStackCursor = createCursor(NO_CONTEXT);
function requiredContext(c) {
if (c === NO_CONTEXT) {
throw new Error('Expected host context to exist. This error is likely caused by a bug ' + 'in React. Please file an issue.');
}
return c;
}
function getRootHostContainer() {
var rootInstance = requiredContext(rootInstanceStackCursor.current);
return rootInstance;
}
function pushHostContainer(fiber, nextRootInstance) {
// Push current root instance onto the stack;
// This allows us to reset root when portals are popped.
push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it.
// This enables us to pop only Fibers that provide unique contexts.
push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack.
// However, we can't just call getRootHostContext() and push it because
// we'd have a different number of entries on the stack depending on
// whether getRootHostContext() throws somewhere in renderer code or not.
// So we push an empty value first. This lets us safely unwind on errors.
push(contextStackCursor$1, NO_CONTEXT, fiber);
var nextRootContext = getRootHostContext(nextRootInstance); // Now that we know this function doesn't throw, replace it.
pop(contextStackCursor$1, fiber);
push(contextStackCursor$1, nextRootContext, fiber);
}
function popHostContainer(fiber) {
pop(contextStackCursor$1, fiber);
pop(contextFiberStackCursor, fiber);
pop(rootInstanceStackCursor, fiber);
}
function getHostContext() {
var context = requiredContext(contextStackCursor$1.current);
return context;
}
function pushHostContext(fiber) {
var rootInstance = requiredContext(rootInstanceStackCursor.current);
var context = requiredContext(contextStackCursor$1.current);
var nextContext = getChildHostContext(context, fiber.type); // Don't push this Fiber's context unless it's unique.
if (context === nextContext) {
return;
} // Track the context and the Fiber that provided it.
// This enables us to pop only Fibers that provide unique contexts.
push(contextFiberStackCursor, fiber, fiber);
push(contextStackCursor$1, nextContext, fiber);
}
function popHostContext(fiber) {
// Do not pop unless this Fiber provided the current context.
// pushHostContext() only pushes Fibers that provide unique contexts.
if (contextFiberStackCursor.current !== fiber) {
return;
}
pop(contextStackCursor$1, fiber);
pop(contextFiberStackCursor, fiber);
}
var DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is
// inherited deeply down the subtree. The upper bits only affect
// this immediate suspense boundary and gets reset each new
// boundary or suspense list.
var SubtreeSuspenseContextMask = 1; // Subtree Flags:
// InvisibleParentSuspenseContext indicates that one of our parent Suspense
// boundaries is not currently showing visible main content.
// Either because it is already showing a fallback or is not mounted at all.
// We can use this to determine if it is desirable to trigger a fallback at
// the parent. If not, then we might need to trigger undesirable boundaries
// and/or suspend the commit to avoid hiding the parent content.
var InvisibleParentSuspenseContext = 1; // Shallow Flags:
// ForceSuspenseFallback can be used by SuspenseList to force newly added
// items into their fallback state during one of the render passes.
var ForceSuspenseFallback = 2;
var suspenseStackCursor = createCursor(DefaultSuspenseContext);
function hasSuspenseContext(parentContext, flag) {
return (parentContext & flag) !== 0;
}
function setDefaultShallowSuspenseContext(parentContext) {
return parentContext & SubtreeSuspenseContextMask;
}
function setShallowSuspenseContext(parentContext, shallowContext) {
return parentContext & SubtreeSuspenseContextMask | shallowContext;
}
function addSubtreeSuspenseContext(parentContext, subtreeContext) {
return parentContext | subtreeContext;
}
function pushSuspenseContext(fiber, newContext) {
push(suspenseStackCursor, newContext, fiber);
}
function popSuspenseContext(fiber) {
pop(suspenseStackCursor, fiber);
}
function shouldCaptureSuspense(workInProgress, hasInvisibleParent) {
// If it was the primary children that just suspended, capture and render the
// fallback. Otherwise, don't capture and bubble to the next boundary.
var nextState = workInProgress.memoizedState;
if (nextState !== null) {
if (nextState.dehydrated !== null) {
// A dehydrated boundary always captures.
return true;
}
return false;
}
var props = workInProgress.memoizedProps; // Regular boundaries always capture.
{
return true;
} // If it's a boundary we should avoid, then we prefer to bubble up to the
}
function findFirstSuspended(row) {
var node = row;
while (node !== null) {
if (node.tag === SuspenseComponent) {
var state = node.memoizedState;
if (state !== null) {
var dehydrated = state.dehydrated;
if (dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated)) {
return node;
}
}
} else if (node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't
// keep track of whether it suspended or not.
node.memoizedProps.revealOrder !== undefined) {
var didSuspend = (node.flags & DidCapture) !== NoFlags;
if (didSuspend) {
return node;
}
} else if (node.child !== null) {
node.child.return = node;
node = node.child;
continue;
}
if (node === row) {
return null;
}
while (node.sibling === null) {
if (node.return === null || node.return === row) {
return null;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
}
return null;
}
var NoFlags$1 =
/* */
0; // Represents whether effect should fire.
var HasEffect =
/* */
1; // Represents the phase in which the effect (not the clean-up) fires.
var Insertion =
/* */
2;
var Layout =
/* */
4;
var Passive$1 =
/* */
8;
// and should be reset before starting a new render.
// This tracks which mutable sources need to be reset after a render.
var workInProgressSources = [];
function resetWorkInProgressVersions() {
for (var i = 0; i < workInProgressSources.length; i++) {
var mutableSource = workInProgressSources[i];
{
mutableSource._workInProgressVersionPrimary = null;
}
}
workInProgressSources.length = 0;
}
// This ensures that the version used for server rendering matches the one
// that is eventually read during hydration.
// If they don't match there's a potential tear and a full deopt render is required.
function registerMutableSourceForHydration(root, mutableSource) {
var getVersion = mutableSource._getVersion;
var version = getVersion(mutableSource._source); // TODO Clear this data once all pending hydration work is finished.
// Retaining it forever may interfere with GC.
if (root.mutableSourceEagerHydrationData == null) {
root.mutableSourceEagerHydrationData = [mutableSource, version];
} else {
root.mutableSourceEagerHydrationData.push(mutableSource, version);
}
}
var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher,
ReactCurrentBatchConfig$2 = ReactSharedInternals.ReactCurrentBatchConfig;
var didWarnAboutMismatchedHooksForComponent;
var didWarnUncachedGetSnapshot;
{
didWarnAboutMismatchedHooksForComponent = new Set();
}
// These are set right before calling the component.
var renderLanes = NoLanes; // The work-in-progress fiber. I've named it differently to distinguish it from
// the work-in-progress hook.
var currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The
// current hook list is the list that belongs to the current fiber. The
// work-in-progress hook list is a new list that will be added to the
// work-in-progress fiber.
var currentHook = null;
var workInProgressHook = null; // Whether an update was scheduled at any point during the render phase. This
// does not get reset if we do another render pass; only when we're completely
// finished evaluating this component. This is an optimization so we know
// whether we need to clear render phase updates after a throw.
var didScheduleRenderPhaseUpdate = false; // Where an update was scheduled only during the current render pass. This
// gets reset after each attempt.
// TODO: Maybe there's some way to consolidate this with
// `didScheduleRenderPhaseUpdate`. Or with `numberOfReRenders`.
var didScheduleRenderPhaseUpdateDuringThisPass = false; // Counts the number of useId hooks in this component.
var localIdCounter = 0; // Used for ids that are generated completely client-side (i.e. not during
// hydration). This counter is global, so client ids are not stable across
// render attempts.
var globalClientIdCounter = 0;
var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook
var currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders.
// The list stores the order of hooks used during the initial render (mount).
// Subsequent renders (updates) reference this list.
var hookTypesDev = null;
var hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore
// the dependencies for Hooks that need them (e.g. useEffect or useMemo).
// When true, such Hooks will always be "remounted". Only used during hot reload.
var ignorePreviousDependencies = false;
function mountHookTypesDev() {
{
var hookName = currentHookNameInDev;
if (hookTypesDev === null) {
hookTypesDev = [hookName];
} else {
hookTypesDev.push(hookName);
}
}
}
function updateHookTypesDev() {
{
var hookName = currentHookNameInDev;
if (hookTypesDev !== null) {
hookTypesUpdateIndexDev++;
if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {
warnOnHookMismatchInDev(hookName);
}
}
}
}
function checkDepsAreArrayDev(deps) {
{
if (deps !== undefined && deps !== null && !isArray(deps)) {
// Verify deps, but only on mount to avoid extra checks.
// It's unlikely their type would change as usually you define them inline.
error('%s received a final argument that is not an array (instead, received `%s`). When ' + 'specified, the final argument must be an array.', currentHookNameInDev, typeof deps);
}
}
}
function warnOnHookMismatchInDev(currentHookName) {
{
var componentName = getComponentNameFromFiber(currentlyRenderingFiber$1);
if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
didWarnAboutMismatchedHooksForComponent.add(componentName);
if (hookTypesDev !== null) {
var table = '';
var secondColumnStart = 30;
for (var i = 0; i <= hookTypesUpdateIndexDev; i++) {
var oldHookName = hookTypesDev[i];
var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName;
var row = i + 1 + ". " + oldHookName; // Extra space so second column lines up
// lol @ IE not supporting String#repeat
while (row.length < secondColumnStart) {
row += ' ';
}
row += newHookName + '\n';
table += row;
}
error('React has detected a change in the order of Hooks called by %s. ' + 'This will lead to bugs and errors if not fixed. ' + 'For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n' + ' Previous render Next render\n' + ' ------------------------------------------------------\n' + '%s' + ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n', componentName, table);
}
}
}
}
function throwInvalidHookError() {
throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');
}
function areHookInputsEqual(nextDeps, prevDeps) {
{
if (ignorePreviousDependencies) {
// Only true when this component is being hot reloaded.
return false;
}
}
if (prevDeps === null) {
{
error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev);
}
return false;
}
{
// Don't bother comparing lengths in prod because these arrays should be
// passed inline.
if (nextDeps.length !== prevDeps.length) {
error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + prevDeps.join(', ') + "]", "[" + nextDeps.join(', ') + "]");
}
}
for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
if (objectIs(nextDeps[i], prevDeps[i])) {
continue;
}
return false;
}
return true;
}
function renderWithHooks(current, workInProgress, Component, props, secondArg, nextRenderLanes) {
renderLanes = nextRenderLanes;
currentlyRenderingFiber$1 = workInProgress;
{
hookTypesDev = current !== null ? current._debugHookTypes : null;
hookTypesUpdateIndexDev = -1; // Used for hot reloading:
ignorePreviousDependencies = current !== null && current.type !== workInProgress.type;
}
workInProgress.memoizedState = null;
workInProgress.updateQueue = null;
workInProgress.lanes = NoLanes; // The following should have already been reset
// currentHook = null;
// workInProgressHook = null;
// didScheduleRenderPhaseUpdate = false;
// localIdCounter = 0;
// TODO Warn if no hooks are used at all during mount, then some are used during update.
// Currently we will identify the update render as a mount because memoizedState === null.
// This is tricky because it's valid for certain types of components (e.g. React.lazy)
// Using memoizedState to differentiate between mount/update only works if at least one stateful hook is used.
// Non-stateful hooks (e.g. context) don't get added to memoizedState,
// so memoizedState would be null during updates and mounts.
{
if (current !== null && current.memoizedState !== null) {
ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
} else if (hookTypesDev !== null) {
// This dispatcher handles an edge case where a component is updating,
// but no stateful hooks have been used.
// We want to match the production code behavior (which will use HooksDispatcherOnMount),
// but with the extra DEV validation to ensure hooks ordering hasn't changed.
// This dispatcher does that.
ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV;
} else {
ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV;
}
}
var children = Component(props, secondArg); // Check if there was a render phase update
if (didScheduleRenderPhaseUpdateDuringThisPass) {
// Keep rendering in a loop for as long as render phase updates continue to
// be scheduled. Use a counter to prevent infinite loops.
var numberOfReRenders = 0;
do {
didScheduleRenderPhaseUpdateDuringThisPass = false;
localIdCounter = 0;
if (numberOfReRenders >= RE_RENDER_LIMIT) {
throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.');
}
numberOfReRenders += 1;
{
// Even when hot reloading, allow dependencies to stabilize
// after first render to prevent infinite render phase updates.
ignorePreviousDependencies = false;
} // Start over from the beginning of the list
currentHook = null;
workInProgressHook = null;
workInProgress.updateQueue = null;
{
// Also validate hook order for cascading updates.
hookTypesUpdateIndexDev = -1;
}
ReactCurrentDispatcher$1.current = HooksDispatcherOnRerenderInDEV ;
children = Component(props, secondArg);
} while (didScheduleRenderPhaseUpdateDuringThisPass);
} // We can assume the previous dispatcher is always this one, since we set it
// at the beginning of the render phase and there's no re-entrance.
ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
{
workInProgress._debugHookTypes = hookTypesDev;
} // This check uses currentHook so that it works the same in DEV and prod bundles.
// hookTypesDev could catch more cases (e.g. context) but only in DEV bundles.
var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
renderLanes = NoLanes;
currentlyRenderingFiber$1 = null;
currentHook = null;
workInProgressHook = null;
{
currentHookNameInDev = null;
hookTypesDev = null;
hookTypesUpdateIndexDev = -1; // Confirm that a static flag was not added or removed since the last
// render. If this fires, it suggests that we incorrectly reset the static
// flags in some other part of the codebase. This has happened before, for
// example, in the SuspenseList implementation.
if (current !== null && (current.flags & StaticMask) !== (workInProgress.flags & StaticMask) && // Disable this warning in legacy mode, because legacy Suspense is weird
// and creates false positives. To make this work in legacy mode, we'd
// need to mark fibers that commit in an incomplete state, somehow. For
// now I'll disable the warning that most of the bugs that would trigger
// it are either exclusive to concurrent mode or exist in both.
(current.mode & ConcurrentMode) !== NoMode) {
error('Internal React error: Expected static flag was missing. Please ' + 'notify the React team.');
}
}
didScheduleRenderPhaseUpdate = false; // This is reset by checkDidRenderIdHook
// localIdCounter = 0;
if (didRenderTooFewHooks) {
throw new Error('Rendered fewer hooks than expected. This may be caused by an accidental ' + 'early return statement.');
}
return children;
}
function checkDidRenderIdHook() {
// This should be called immediately after every renderWithHooks call.
// Conceptually, it's part of the return value of renderWithHooks; it's only a
// separate function to avoid using an array tuple.
var didRenderIdHook = localIdCounter !== 0;
localIdCounter = 0;
return didRenderIdHook;
}
function bailoutHooks(current, workInProgress, lanes) {
workInProgress.updateQueue = current.updateQueue; // TODO: Don't need to reset the flags here, because they're reset in the
// complete phase (bubbleProperties).
if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) {
workInProgress.flags &= ~(MountPassiveDev | MountLayoutDev | Passive | Update);
} else {
workInProgress.flags &= ~(Passive | Update);
}
current.lanes = removeLanes(current.lanes, lanes);
}
function resetHooksAfterThrow() {
// We can assume the previous dispatcher is always this one, since we set it
// at the beginning of the render phase and there's no re-entrance.
ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
if (didScheduleRenderPhaseUpdate) {
// There were render phase updates. These are only valid for this render
// phase, which we are now aborting. Remove the updates from the queues so
// they do not persist to the next render. Do not remove updates from hooks
// that weren't processed.
//
// Only reset the updates from the queue if it has a clone. If it does
// not have a clone, that means it wasn't processed, and the updates were
// scheduled before we entered the render phase.
var hook = currentlyRenderingFiber$1.memoizedState;
while (hook !== null) {
var queue = hook.queue;
if (queue !== null) {
queue.pending = null;
}
hook = hook.next;
}
didScheduleRenderPhaseUpdate = false;
}
renderLanes = NoLanes;
currentlyRenderingFiber$1 = null;
currentHook = null;
workInProgressHook = null;
{
hookTypesDev = null;
hookTypesUpdateIndexDev = -1;
currentHookNameInDev = null;
isUpdatingOpaqueValueInRenderPhase = false;
}
didScheduleRenderPhaseUpdateDuringThisPass = false;
localIdCounter = 0;
}
function mountWorkInProgressHook() {
var hook = {
memoizedState: null,
baseState: null,
baseQueue: null,
queue: null,
next: null
};
if (workInProgressHook === null) {
// This is the first hook in the list
currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook;
} else {
// Append to the end of the list
workInProgressHook = workInProgressHook.next = hook;
}
return workInProgressHook;
}
function updateWorkInProgressHook() {
// This function is used both for updates and for re-renders triggered by a
// render phase update. It assumes there is either a current hook we can
// clone, or a work-in-progress hook from a previous render pass that we can
// use as a base. When we reach the end of the base list, we must switch to
// the dispatcher used for mounts.
var nextCurrentHook;
if (currentHook === null) {
var current = currentlyRenderingFiber$1.alternate;
if (current !== null) {
nextCurrentHook = current.memoizedState;
} else {
nextCurrentHook = null;
}
} else {
nextCurrentHook = currentHook.next;
}
var nextWorkInProgressHook;
if (workInProgressHook === null) {
nextWorkInProgressHook = currentlyRenderingFiber$1.memoizedState;
} else {
nextWorkInProgressHook = workInProgressHook.next;
}
if (nextWorkInProgressHook !== null) {
// There's already a work-in-progress. Reuse it.
workInProgressHook = nextWorkInProgressHook;
nextWorkInProgressHook = workInProgressHook.next;
currentHook = nextCurrentHook;
} else {
// Clone from the current hook.
if (nextCurrentHook === null) {
throw new Error('Rendered more hooks than during the previous render.');
}
currentHook = nextCurrentHook;
var newHook = {
memoizedState: currentHook.memoizedState,
baseState: currentHook.baseState,
baseQueue: currentHook.baseQueue,
queue: currentHook.queue,
next: null
};
if (workInProgressHook === null) {
// This is the first hook in the list.
currentlyRenderingFiber$1.memoizedState = workInProgressHook = newHook;
} else {
// Append to the end of the list.
workInProgressHook = workInProgressHook.next = newHook;
}
}
return workInProgressHook;
}
function createFunctionComponentUpdateQueue() {
return {
lastEffect: null,
stores: null
};
}
function basicStateReducer(state, action) {
// $FlowFixMe: Flow doesn't like mixed types
return typeof action === 'function' ? action(state) : action;
}
function mountReducer(reducer, initialArg, init) {
var hook = mountWorkInProgressHook();
var initialState;
if (init !== undefined) {
initialState = init(initialArg);
} else {
initialState = initialArg;
}
hook.memoizedState = hook.baseState = initialState;
var queue = {
pending: null,
interleaved: null,
lanes: NoLanes,
dispatch: null,
lastRenderedReducer: reducer,
lastRenderedState: initialState
};
hook.queue = queue;
var dispatch = queue.dispatch = dispatchReducerAction.bind(null, currentlyRenderingFiber$1, queue);
return [hook.memoizedState, dispatch];
}
function updateReducer(reducer, initialArg, init) {
var hook = updateWorkInProgressHook();
var queue = hook.queue;
if (queue === null) {
throw new Error('Should have a queue. This is likely a bug in React. Please file an issue.');
}
queue.lastRenderedReducer = reducer;
var current = currentHook; // The last rebase update that is NOT part of the base state.
var baseQueue = current.baseQueue; // The last pending update that hasn't been processed yet.
var pendingQueue = queue.pending;
if (pendingQueue !== null) {
// We have new updates that haven't been processed yet.
// We'll add them to the base queue.
if (baseQueue !== null) {
// Merge the pending queue and the base queue.
var baseFirst = baseQueue.next;
var pendingFirst = pendingQueue.next;
baseQueue.next = pendingFirst;
pendingQueue.next = baseFirst;
}
{
if (current.baseQueue !== baseQueue) {
// Internal invariant that should never happen, but feasibly could in
// the future if we implement resuming, or some form of that.
error('Internal error: Expected work-in-progress queue to be a clone. ' + 'This is a bug in React.');
}
}
current.baseQueue = baseQueue = pendingQueue;
queue.pending = null;
}
if (baseQueue !== null) {
// We have a queue to process.
var first = baseQueue.next;
var newState = current.baseState;
var newBaseState = null;
var newBaseQueueFirst = null;
var newBaseQueueLast = null;
var update = first;
do {
var updateLane = update.lane;
if (!isSubsetOfLanes(renderLanes, updateLane)) {
// Priority is insufficient. Skip this update. If this is the first
// skipped update, the previous update/state is the new base
// update/state.
var clone = {
lane: updateLane,
action: update.action,
hasEagerState: update.hasEagerState,
eagerState: update.eagerState,
next: null
};
if (newBaseQueueLast === null) {
newBaseQueueFirst = newBaseQueueLast = clone;
newBaseState = newState;
} else {
newBaseQueueLast = newBaseQueueLast.next = clone;
} // Update the remaining priority in the queue.
// TODO: Don't need to accumulate this. Instead, we can remove
// renderLanes from the original lanes.
currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, updateLane);
markSkippedUpdateLanes(updateLane);
} else {
// This update does have sufficient priority.
if (newBaseQueueLast !== null) {
var _clone = {
// This update is going to be committed so we never want uncommit
// it. Using NoLane works because 0 is a subset of all bitmasks, so
// this will never be skipped by the check above.
lane: NoLane,
action: update.action,
hasEagerState: update.hasEagerState,
eagerState: update.eagerState,
next: null
};
newBaseQueueLast = newBaseQueueLast.next = _clone;
} // Process this update.
if (update.hasEagerState) {
// If this update is a state update (not a reducer) and was processed eagerly,
// we can use the eagerly computed state
newState = update.eagerState;
} else {
var action = update.action;
newState = reducer(newState, action);
}
}
update = update.next;
} while (update !== null && update !== first);
if (newBaseQueueLast === null) {
newBaseState = newState;
} else {
newBaseQueueLast.next = newBaseQueueFirst;
} // Mark that the fiber performed work, but only if the new state is
// different from the current state.
if (!objectIs(newState, hook.memoizedState)) {
markWorkInProgressReceivedUpdate();
}
hook.memoizedState = newState;
hook.baseState = newBaseState;
hook.baseQueue = newBaseQueueLast;
queue.lastRenderedState = newState;
} // Interleaved updates are stored on a separate queue. We aren't going to
// process them during this render, but we do need to track which lanes
// are remaining.
var lastInterleaved = queue.interleaved;
if (lastInterleaved !== null) {
var interleaved = lastInterleaved;
do {
var interleavedLane = interleaved.lane;
currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, interleavedLane);
markSkippedUpdateLanes(interleavedLane);
interleaved = interleaved.next;
} while (interleaved !== lastInterleaved);
} else if (baseQueue === null) {
// `queue.lanes` is used for entangling transitions. We can set it back to
// zero once the queue is empty.
queue.lanes = NoLanes;
}
var dispatch = queue.dispatch;
return [hook.memoizedState, dispatch];
}
function rerenderReducer(reducer, initialArg, init) {
var hook = updateWorkInProgressHook();
var queue = hook.queue;
if (queue === null) {
throw new Error('Should have a queue. This is likely a bug in React. Please file an issue.');
}
queue.lastRenderedReducer = reducer; // This is a re-render. Apply the new render phase updates to the previous
// work-in-progress hook.
var dispatch = queue.dispatch;
var lastRenderPhaseUpdate = queue.pending;
var newState = hook.memoizedState;
if (lastRenderPhaseUpdate !== null) {
// The queue doesn't persist past this render pass.
queue.pending = null;
var firstRenderPhaseUpdate = lastRenderPhaseUpdate.next;
var update = firstRenderPhaseUpdate;
do {
// Process this render phase update. We don't have to check the
// priority because it will always be the same as the current
// render's.
var action = update.action;
newState = reducer(newState, action);
update = update.next;
} while (update !== firstRenderPhaseUpdate); // Mark that the fiber performed work, but only if the new state is
// different from the current state.
if (!objectIs(newState, hook.memoizedState)) {
markWorkInProgressReceivedUpdate();
}
hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to
// the base state unless the queue is empty.
// TODO: Not sure if this is the desired semantics, but it's what we
// do for gDSFP. I can't remember why.
if (hook.baseQueue === null) {
hook.baseState = newState;
}
queue.lastRenderedState = newState;
}
return [newState, dispatch];
}
function mountMutableSource(source, getSnapshot, subscribe) {
{
return undefined;
}
}
function updateMutableSource(source, getSnapshot, subscribe) {
{
return undefined;
}
}
function mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
var fiber = currentlyRenderingFiber$1;
var hook = mountWorkInProgressHook();
var nextSnapshot;
var isHydrating = getIsHydrating();
if (isHydrating) {
if (getServerSnapshot === undefined) {
throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.');
}
nextSnapshot = getServerSnapshot();
{
if (!didWarnUncachedGetSnapshot) {
if (nextSnapshot !== getServerSnapshot()) {
error('The result of getServerSnapshot should be cached to avoid an infinite loop');
didWarnUncachedGetSnapshot = true;
}
}
}
} else {
nextSnapshot = getSnapshot();
{
if (!didWarnUncachedGetSnapshot) {
var cachedSnapshot = getSnapshot();
if (!objectIs(nextSnapshot, cachedSnapshot)) {
error('The result of getSnapshot should be cached to avoid an infinite loop');
didWarnUncachedGetSnapshot = true;
}
}
} // Unless we're rendering a blocking lane, schedule a consistency check.
// Right before committing, we will walk the tree and check if any of the
// stores were mutated.
//
// We won't do this if we're hydrating server-rendered content, because if
// the content is stale, it's already visible anyway. Instead we'll patch
// it up in a passive effect.
var root = getWorkInProgressRoot();
if (root === null) {
throw new Error('Expected a work-in-progress root. This is a bug in React. Please file an issue.');
}
if (!includesBlockingLane(root, renderLanes)) {
pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot);
}
} // Read the current snapshot from the store on every render. This breaks the
// normal rules of React, and only works because store updates are
// always synchronous.
hook.memoizedState = nextSnapshot;
var inst = {
value: nextSnapshot,
getSnapshot: getSnapshot
};
hook.queue = inst; // Schedule an effect to subscribe to the store.
mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Schedule an effect to update the mutable instance fields. We will update
// this whenever subscribe, getSnapshot, or value changes. Because there's no
// clean-up function, and we track the deps correctly, we can call pushEffect
// directly, without storing any additional state. For the same reason, we
// don't need to set a static flag, either.
// TODO: We can move this to the passive phase once we add a pre-commit
// consistency check. See the next comment.
fiber.flags |= Passive;
pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), undefined, null);
return nextSnapshot;
}
function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
var fiber = currentlyRenderingFiber$1;
var hook = updateWorkInProgressHook(); // Read the current snapshot from the store on every render. This breaks the
// normal rules of React, and only works because store updates are
// always synchronous.
var nextSnapshot = getSnapshot();
{
if (!didWarnUncachedGetSnapshot) {
var cachedSnapshot = getSnapshot();
if (!objectIs(nextSnapshot, cachedSnapshot)) {
error('The result of getSnapshot should be cached to avoid an infinite loop');
didWarnUncachedGetSnapshot = true;
}
}
}
var prevSnapshot = hook.memoizedState;
var snapshotChanged = !objectIs(prevSnapshot, nextSnapshot);
if (snapshotChanged) {
hook.memoizedState = nextSnapshot;
markWorkInProgressReceivedUpdate();
}
var inst = hook.queue;
updateEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Whenever getSnapshot or subscribe changes, we need to check in the
// commit phase if there was an interleaved mutation. In concurrent mode
// this can happen all the time, but even in synchronous mode, an earlier
// effect may have mutated the store.
if (inst.getSnapshot !== getSnapshot || snapshotChanged || // Check if the susbcribe function changed. We can save some memory by
// checking whether we scheduled a subscription effect above.
workInProgressHook !== null && workInProgressHook.memoizedState.tag & HasEffect) {
fiber.flags |= Passive;
pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), undefined, null); // Unless we're rendering a blocking lane, schedule a consistency check.
// Right before committing, we will walk the tree and check if any of the
// stores were mutated.
var root = getWorkInProgressRoot();
if (root === null) {
throw new Error('Expected a work-in-progress root. This is a bug in React. Please file an issue.');
}
if (!includesBlockingLane(root, renderLanes)) {
pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot);
}
}
return nextSnapshot;
}
function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) {
fiber.flags |= StoreConsistency;
var check = {
getSnapshot: getSnapshot,
value: renderedSnapshot
};
var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue;
if (componentUpdateQueue === null) {
componentUpdateQueue = createFunctionComponentUpdateQueue();
currentlyRenderingFiber$1.updateQueue = componentUpdateQueue;
componentUpdateQueue.stores = [check];
} else {
var stores = componentUpdateQueue.stores;
if (stores === null) {
componentUpdateQueue.stores = [check];
} else {
stores.push(check);
}
}
}
function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) {
// These are updated in the passive phase
inst.value = nextSnapshot;
inst.getSnapshot = getSnapshot; // Something may have been mutated in between render and commit. This could
// have been in an event that fired before the passive effects, or it could
// have been in a layout effect. In that case, we would have used the old
// snapsho and getSnapshot values to bail out. We need to check one more time.
if (checkIfSnapshotChanged(inst)) {
// Force a re-render.
forceStoreRerender(fiber);
}
}
function subscribeToStore(fiber, inst, subscribe) {
var handleStoreChange = function () {
// The store changed. Check if the snapshot changed since the last time we
// read from the store.
if (checkIfSnapshotChanged(inst)) {
// Force a re-render.
forceStoreRerender(fiber);
}
}; // Subscribe to the store and return a clean-up function.
return subscribe(handleStoreChange);
}
function checkIfSnapshotChanged(inst) {
var latestGetSnapshot = inst.getSnapshot;
var prevValue = inst.value;
try {
var nextValue = latestGetSnapshot();
return !objectIs(prevValue, nextValue);
} catch (error) {
return true;
}
}
function forceStoreRerender(fiber) {
var root = enqueueConcurrentRenderForLane(fiber, SyncLane);
if (root !== null) {
scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
}
}
function mountState(initialState) {
var hook = mountWorkInProgressHook();
if (typeof initialState === 'function') {
// $FlowFixMe: Flow doesn't like mixed types
initialState = initialState();
}
hook.memoizedState = hook.baseState = initialState;
var queue = {
pending: null,
interleaved: null,
lanes: NoLanes,
dispatch: null,
lastRenderedReducer: basicStateReducer,
lastRenderedState: initialState
};
hook.queue = queue;
var dispatch = queue.dispatch = dispatchSetState.bind(null, currentlyRenderingFiber$1, queue);
return [hook.memoizedState, dispatch];
}
function updateState(initialState) {
return updateReducer(basicStateReducer);
}
function rerenderState(initialState) {
return rerenderReducer(basicStateReducer);
}
function pushEffect(tag, create, destroy, deps) {
var effect = {
tag: tag,
create: create,
destroy: destroy,
deps: deps,
// Circular
next: null
};
var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue;
if (componentUpdateQueue === null) {
componentUpdateQueue = createFunctionComponentUpdateQueue();
currentlyRenderingFiber$1.updateQueue = componentUpdateQueue;
componentUpdateQueue.lastEffect = effect.next = effect;
} else {
var lastEffect = componentUpdateQueue.lastEffect;
if (lastEffect === null) {
componentUpdateQueue.lastEffect = effect.next = effect;
} else {
var firstEffect = lastEffect.next;
lastEffect.next = effect;
effect.next = firstEffect;
componentUpdateQueue.lastEffect = effect;
}
}
return effect;
}
function mountRef(initialValue) {
var hook = mountWorkInProgressHook();
{
var _ref2 = {
current: initialValue
};
hook.memoizedState = _ref2;
return _ref2;
}
}
function updateRef(initialValue) {
var hook = updateWorkInProgressHook();
return hook.memoizedState;
}
function mountEffectImpl(fiberFlags, hookFlags, create, deps) {
var hook = mountWorkInProgressHook();
var nextDeps = deps === undefined ? null : deps;
currentlyRenderingFiber$1.flags |= fiberFlags;
hook.memoizedState = pushEffect(HasEffect | hookFlags, create, undefined, nextDeps);
}
function updateEffectImpl(fiberFlags, hookFlags, create, deps) {
var hook = updateWorkInProgressHook();
var nextDeps = deps === undefined ? null : deps;
var destroy = undefined;
if (currentHook !== null) {
var prevEffect = currentHook.memoizedState;
destroy = prevEffect.destroy;
if (nextDeps !== null) {
var prevDeps = prevEffect.deps;
if (areHookInputsEqual(nextDeps, prevDeps)) {
hook.memoizedState = pushEffect(hookFlags, create, destroy, nextDeps);
return;
}
}
}
currentlyRenderingFiber$1.flags |= fiberFlags;
hook.memoizedState = pushEffect(HasEffect | hookFlags, create, destroy, nextDeps);
}
function mountEffect(create, deps) {
if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) {
return mountEffectImpl(MountPassiveDev | Passive | PassiveStatic, Passive$1, create, deps);
} else {
return mountEffectImpl(Passive | PassiveStatic, Passive$1, create, deps);
}
}
function updateEffect(create, deps) {
return updateEffectImpl(Passive, Passive$1, create, deps);
}
function mountInsertionEffect(create, deps) {
return mountEffectImpl(Update, Insertion, create, deps);
}
function updateInsertionEffect(create, deps) {
return updateEffectImpl(Update, Insertion, create, deps);
}
function mountLayoutEffect(create, deps) {
var fiberFlags = Update;
{
fiberFlags |= LayoutStatic;
}
if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) {
fiberFlags |= MountLayoutDev;
}
return mountEffectImpl(fiberFlags, Layout, create, deps);
}
function updateLayoutEffect(create, deps) {
return updateEffectImpl(Update, Layout, create, deps);
}
function imperativeHandleEffect(create, ref) {
if (typeof ref === 'function') {
var refCallback = ref;
var _inst = create();
refCallback(_inst);
return function () {
refCallback(null);
};
} else if (ref !== null && ref !== undefined) {
var refObject = ref;
{
if (!refObject.hasOwnProperty('current')) {
error('Expected useImperativeHandle() first argument to either be a ' + 'ref callback or React.createRef() object. Instead received: %s.', 'an object with keys {' + Object.keys(refObject).join(', ') + '}');
}
}
var _inst2 = create();
refObject.current = _inst2;
return function () {
refObject.current = null;
};
}
}
function mountImperativeHandle(ref, create, deps) {
{
if (typeof create !== 'function') {
error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null');
}
} // TODO: If deps are provided, should we skip comparing the ref itself?
var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
var fiberFlags = Update;
{
fiberFlags |= LayoutStatic;
}
if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) {
fiberFlags |= MountLayoutDev;
}
return mountEffectImpl(fiberFlags, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
}
function updateImperativeHandle(ref, create, deps) {
{
if (typeof create !== 'function') {
error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null');
}
} // TODO: If deps are provided, should we skip comparing the ref itself?
var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
return updateEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
}
function mountDebugValue(value, formatterFn) {// This hook is normally a no-op.
// The react-debug-hooks package injects its own implementation
// so that e.g. DevTools can display custom hook values.
}
var updateDebugValue = mountDebugValue;
function mountCallback(callback, deps) {
var hook = mountWorkInProgressHook();
var nextDeps = deps === undefined ? null : deps;
hook.memoizedState = [callback, nextDeps];
return callback;
}
function updateCallback(callback, deps) {
var hook = updateWorkInProgressHook();
var nextDeps = deps === undefined ? null : deps;
var prevState = hook.memoizedState;
if (prevState !== null) {
if (nextDeps !== null) {
var prevDeps = prevState[1];
if (areHookInputsEqual(nextDeps, prevDeps)) {
return prevState[0];
}
}
}
hook.memoizedState = [callback, nextDeps];
return callback;
}
function mountMemo(nextCreate, deps) {
var hook = mountWorkInProgressHook();
var nextDeps = deps === undefined ? null : deps;
var nextValue = nextCreate();
hook.memoizedState = [nextValue, nextDeps];
return nextValue;
}
function updateMemo(nextCreate, deps) {
var hook = updateWorkInProgressHook();
var nextDeps = deps === undefined ? null : deps;
var prevState = hook.memoizedState;
if (prevState !== null) {
// Assume these are defined. If they're not, areHookInputsEqual will warn.
if (nextDeps !== null) {
var prevDeps = prevState[1];
if (areHookInputsEqual(nextDeps, prevDeps)) {
return prevState[0];
}
}
}
var nextValue = nextCreate();
hook.memoizedState = [nextValue, nextDeps];
return nextValue;
}
function mountDeferredValue(value) {
var hook = mountWorkInProgressHook();
hook.memoizedState = value;
return value;
}
function updateDeferredValue(value) {
var hook = updateWorkInProgressHook();
var resolvedCurrentHook = currentHook;
var prevValue = resolvedCurrentHook.memoizedState;
return updateDeferredValueImpl(hook, prevValue, value);
}
function rerenderDeferredValue(value) {
var hook = updateWorkInProgressHook();
if (currentHook === null) {
// This is a rerender during a mount.
hook.memoizedState = value;
return value;
} else {
// This is a rerender during an update.
var prevValue = currentHook.memoizedState;
return updateDeferredValueImpl(hook, prevValue, value);
}
}
function updateDeferredValueImpl(hook, prevValue, value) {
var shouldDeferValue = !includesOnlyNonUrgentLanes(renderLanes);
if (shouldDeferValue) {
// This is an urgent update. If the value has changed, keep using the
// previous value and spawn a deferred render to update it later.
if (!objectIs(value, prevValue)) {
// Schedule a deferred render
var deferredLane = claimNextTransitionLane();
currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, deferredLane);
markSkippedUpdateLanes(deferredLane); // Set this to true to indicate that the rendered value is inconsistent
// from the latest value. The name "baseState" doesn't really match how we
// use it because we're reusing a state hook field instead of creating a
// new one.
hook.baseState = true;
} // Reuse the previous value
return prevValue;
} else {
// This is not an urgent update, so we can use the latest value regardless
// of what it is. No need to defer it.
// However, if we're currently inside a spawned render, then we need to mark
// this as an update to prevent the fiber from bailing out.
//
// `baseState` is true when the current value is different from the rendered
// value. The name doesn't really match how we use it because we're reusing
// a state hook field instead of creating a new one.
if (hook.baseState) {
// Flip this back to false.
hook.baseState = false;
markWorkInProgressReceivedUpdate();
}
hook.memoizedState = value;
return value;
}
}
function startTransition(setPending, callback, options) {
var previousPriority = getCurrentUpdatePriority();
setCurrentUpdatePriority(higherEventPriority(previousPriority, ContinuousEventPriority));
setPending(true);
var prevTransition = ReactCurrentBatchConfig$2.transition;
ReactCurrentBatchConfig$2.transition = {};
var currentTransition = ReactCurrentBatchConfig$2.transition;
{
ReactCurrentBatchConfig$2.transition._updatedFibers = new Set();
}
try {
setPending(false);
callback();
} finally {
setCurrentUpdatePriority(previousPriority);
ReactCurrentBatchConfig$2.transition = prevTransition;
{
if (prevTransition === null && currentTransition._updatedFibers) {
var updatedFibersCount = currentTransition._updatedFibers.size;
if (updatedFibersCount > 10) {
warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.');
}
currentTransition._updatedFibers.clear();
}
}
}
}
function mountTransition() {
var _mountState = mountState(false),
isPending = _mountState[0],
setPending = _mountState[1]; // The `start` method never changes.
var start = startTransition.bind(null, setPending);
var hook = mountWorkInProgressHook();
hook.memoizedState = start;
return [isPending, start];
}
function updateTransition() {
var _updateState = updateState(),
isPending = _updateState[0];
var hook = updateWorkInProgressHook();
var start = hook.memoizedState;
return [isPending, start];
}
function rerenderTransition() {
var _rerenderState = rerenderState(),
isPending = _rerenderState[0];
var hook = updateWorkInProgressHook();
var start = hook.memoizedState;
return [isPending, start];
}
var isUpdatingOpaqueValueInRenderPhase = false;
function getIsUpdatingOpaqueValueInRenderPhaseInDEV() {
{
return isUpdatingOpaqueValueInRenderPhase;
}
}
function mountId() {
var hook = mountWorkInProgressHook();
var root = getWorkInProgressRoot(); // TODO: In Fizz, id generation is specific to each server config. Maybe we
// should do this in Fiber, too? Deferring this decision for now because
// there's no other place to store the prefix except for an internal field on
// the public createRoot object, which the fiber tree does not currently have
// a reference to.
var identifierPrefix = root.identifierPrefix;
var id;
if (getIsHydrating()) {
var treeId = getTreeId(); // Use a captial R prefix for server-generated ids.
id = ':' + identifierPrefix + 'R' + treeId; // Unless this is the first id at this level, append a number at the end
// that represents the position of this useId hook among all the useId
// hooks for this fiber.
var localId = localIdCounter++;
if (localId > 0) {
id += 'H' + localId.toString(32);
}
id += ':';
} else {
// Use a lowercase r prefix for client-generated ids.
var globalClientId = globalClientIdCounter++;
id = ':' + identifierPrefix + 'r' + globalClientId.toString(32) + ':';
}
hook.memoizedState = id;
return id;
}
function updateId() {
var hook = updateWorkInProgressHook();
var id = hook.memoizedState;
return id;
}
function dispatchReducerAction(fiber, queue, action) {
{
if (typeof arguments[3] === 'function') {
error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().');
}
}
var lane = requestUpdateLane(fiber);
var update = {
lane: lane,
action: action,
hasEagerState: false,
eagerState: null,
next: null
};
if (isRenderPhaseUpdate(fiber)) {
enqueueRenderPhaseUpdate(queue, update);
} else {
var root = enqueueConcurrentHookUpdate(fiber, queue, update, lane);
if (root !== null) {
var eventTime = requestEventTime();
scheduleUpdateOnFiber(root, fiber, lane, eventTime);
entangleTransitionUpdate(root, queue, lane);
}
}
markUpdateInDevTools(fiber, lane);
}
function dispatchSetState(fiber, queue, action) {
{
if (typeof arguments[3] === 'function') {
error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().');
}
}
var lane = requestUpdateLane(fiber);
var update = {
lane: lane,
action: action,
hasEagerState: false,
eagerState: null,
next: null
};
if (isRenderPhaseUpdate(fiber)) {
enqueueRenderPhaseUpdate(queue, update);
} else {
var alternate = fiber.alternate;
if (fiber.lanes === NoLanes && (alternate === null || alternate.lanes === NoLanes)) {
// The queue is currently empty, which means we can eagerly compute the
// next state before entering the render phase. If the new state is the
// same as the current state, we may be able to bail out entirely.
var lastRenderedReducer = queue.lastRenderedReducer;
if (lastRenderedReducer !== null) {
var prevDispatcher;
{
prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
}
try {
var currentState = queue.lastRenderedState;
var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute
// it, on the update object. If the reducer hasn't changed by the
// time we enter the render phase, then the eager state can be used
// without calling the reducer again.
update.hasEagerState = true;
update.eagerState = eagerState;
if (objectIs(eagerState, currentState)) {
// Fast path. We can bail out without scheduling React to re-render.
// It's still possible that we'll need to rebase this update later,
// if the component re-renders for a different reason and by that
// time the reducer has changed.
// TODO: Do we still need to entangle transitions in this case?
enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue, update, lane);
return;
}
} catch (error) {// Suppress the error. It will throw again in the render phase.
} finally {
{
ReactCurrentDispatcher$1.current = prevDispatcher;
}
}
}
}
var root = enqueueConcurrentHookUpdate(fiber, queue, update, lane);
if (root !== null) {
var eventTime = requestEventTime();
scheduleUpdateOnFiber(root, fiber, lane, eventTime);
entangleTransitionUpdate(root, queue, lane);
}
}
markUpdateInDevTools(fiber, lane);
}
function isRenderPhaseUpdate(fiber) {
var alternate = fiber.alternate;
return fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1;
}
function enqueueRenderPhaseUpdate(queue, update) {
// This is a render phase update. Stash it in a lazily-created map of
// queue -> linked list of updates. After this render pass, we'll restart
// and apply the stashed updates on top of the work-in-progress hook.
didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true;
var pending = queue.pending;
if (pending === null) {
// This is the first update. Create a circular list.
update.next = update;
} else {
update.next = pending.next;
pending.next = update;
}
queue.pending = update;
} // TODO: Move to ReactFiberConcurrentUpdates?
function entangleTransitionUpdate(root, queue, lane) {
if (isTransitionLane(lane)) {
var queueLanes = queue.lanes; // If any entangled lanes are no longer pending on the root, then they
// must have finished. We can remove them from the shared queue, which
// represents a superset of the actually pending lanes. In some cases we
// may entangle more than we need to, but that's OK. In fact it's worse if
// we *don't* entangle when we should.
queueLanes = intersectLanes(queueLanes, root.pendingLanes); // Entangle the new transition lane with the other transition lanes.
var newQueueLanes = mergeLanes(queueLanes, lane);
queue.lanes = newQueueLanes; // Even if queue.lanes already include lane, we don't know for certain if
// the lane finished since the last time we entangled it. So we need to
// entangle it again, just to be sure.
markRootEntangled(root, newQueueLanes);
}
}
function markUpdateInDevTools(fiber, lane, action) {
{
markStateUpdateScheduled(fiber, lane);
}
}
var ContextOnlyDispatcher = {
readContext: readContext,
useCallback: throwInvalidHookError,
useContext: throwInvalidHookError,
useEffect: throwInvalidHookError,
useImperativeHandle: throwInvalidHookError,
useInsertionEffect: throwInvalidHookError,
useLayoutEffect: throwInvalidHookError,
useMemo: throwInvalidHookError,
useReducer: throwInvalidHookError,
useRef: throwInvalidHookError,
useState: throwInvalidHookError,
useDebugValue: throwInvalidHookError,
useDeferredValue: throwInvalidHookError,
useTransition: throwInvalidHookError,
useMutableSource: throwInvalidHookError,
useSyncExternalStore: throwInvalidHookError,
useId: throwInvalidHookError,
unstable_isNewReconciler: enableNewReconciler
};
var HooksDispatcherOnMountInDEV = null;
var HooksDispatcherOnMountWithHookTypesInDEV = null;
var HooksDispatcherOnUpdateInDEV = null;
var HooksDispatcherOnRerenderInDEV = null;
var InvalidNestedHooksDispatcherOnMountInDEV = null;
var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
var InvalidNestedHooksDispatcherOnRerenderInDEV = null;
{
var warnInvalidContextAccess = function () {
error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
};
var warnInvalidHookAccess = function () {
error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://reactjs.org/link/rules-of-hooks');
};
HooksDispatcherOnMountInDEV = {
readContext: function (context) {
return readContext(context);
},
useCallback: function (callback, deps) {
currentHookNameInDev = 'useCallback';
mountHookTypesDev();
checkDepsAreArrayDev(deps);
return mountCallback(callback, deps);
},
useContext: function (context) {
currentHookNameInDev = 'useContext';
mountHookTypesDev();
return readContext(context);
},
useEffect: function (create, deps) {
currentHookNameInDev = 'useEffect';
mountHookTypesDev();
checkDepsAreArrayDev(deps);
return mountEffect(create, deps);
},
useImperativeHandle: function (ref, create, deps) {
currentHookNameInDev = 'useImperativeHandle';
mountHookTypesDev();
checkDepsAreArrayDev(deps);
return mountImperativeHandle(ref, create, deps);
},
useInsertionEffect: function (create, deps) {
currentHookNameInDev = 'useInsertionEffect';
mountHookTypesDev();
checkDepsAreArrayDev(deps);
return mountInsertionEffect(create, deps);
},
useLayoutEffect: function (create, deps) {
currentHookNameInDev = 'useLayoutEffect';
mountHookTypesDev();
checkDepsAreArrayDev(deps);
return mountLayoutEffect(create, deps);
},
useMemo: function (create, deps) {
currentHookNameInDev = 'useMemo';
mountHookTypesDev();
checkDepsAreArrayDev(deps);
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountMemo(create, deps);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useReducer: function (reducer, initialArg, init) {
currentHookNameInDev = 'useReducer';
mountHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountReducer(reducer, initialArg, init);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useRef: function (initialValue) {
currentHookNameInDev = 'useRef';
mountHookTypesDev();
return mountRef(initialValue);
},
useState: function (initialState) {
currentHookNameInDev = 'useState';
mountHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountState(initialState);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useDebugValue: function (value, formatterFn) {
currentHookNameInDev = 'useDebugValue';
mountHookTypesDev();
return mountDebugValue();
},
useDeferredValue: function (value) {
currentHookNameInDev = 'useDeferredValue';
mountHookTypesDev();
return mountDeferredValue(value);
},
useTransition: function () {
currentHookNameInDev = 'useTransition';
mountHookTypesDev();
return mountTransition();
},
useMutableSource: function (source, getSnapshot, subscribe) {
currentHookNameInDev = 'useMutableSource';
mountHookTypesDev();
return mountMutableSource();
},
useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
currentHookNameInDev = 'useSyncExternalStore';
mountHookTypesDev();
return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
},
useId: function () {
currentHookNameInDev = 'useId';
mountHookTypesDev();
return mountId();
},
unstable_isNewReconciler: enableNewReconciler
};
HooksDispatcherOnMountWithHookTypesInDEV = {
readContext: function (context) {
return readContext(context);
},
useCallback: function (callback, deps) {
currentHookNameInDev = 'useCallback';
updateHookTypesDev();
return mountCallback(callback, deps);
},
useContext: function (context) {
currentHookNameInDev = 'useContext';
updateHookTypesDev();
return readContext(context);
},
useEffect: function (create, deps) {
currentHookNameInDev = 'useEffect';
updateHookTypesDev();
return mountEffect(create, deps);
},
useImperativeHandle: function (ref, create, deps) {
currentHookNameInDev = 'useImperativeHandle';
updateHookTypesDev();
return mountImperativeHandle(ref, create, deps);
},
useInsertionEffect: function (create, deps) {
currentHookNameInDev = 'useInsertionEffect';
updateHookTypesDev();
return mountInsertionEffect(create, deps);
},
useLayoutEffect: function (create, deps) {
currentHookNameInDev = 'useLayoutEffect';
updateHookTypesDev();
return mountLayoutEffect(create, deps);
},
useMemo: function (create, deps) {
currentHookNameInDev = 'useMemo';
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountMemo(create, deps);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useReducer: function (reducer, initialArg, init) {
currentHookNameInDev = 'useReducer';
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountReducer(reducer, initialArg, init);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useRef: function (initialValue) {
currentHookNameInDev = 'useRef';
updateHookTypesDev();
return mountRef(initialValue);
},
useState: function (initialState) {
currentHookNameInDev = 'useState';
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountState(initialState);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useDebugValue: function (value, formatterFn) {
currentHookNameInDev = 'useDebugValue';
updateHookTypesDev();
return mountDebugValue();
},
useDeferredValue: function (value) {
currentHookNameInDev = 'useDeferredValue';
updateHookTypesDev();
return mountDeferredValue(value);
},
useTransition: function () {
currentHookNameInDev = 'useTransition';
updateHookTypesDev();
return mountTransition();
},
useMutableSource: function (source, getSnapshot, subscribe) {
currentHookNameInDev = 'useMutableSource';
updateHookTypesDev();
return mountMutableSource();
},
useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
currentHookNameInDev = 'useSyncExternalStore';
updateHookTypesDev();
return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
},
useId: function () {
currentHookNameInDev = 'useId';
updateHookTypesDev();
return mountId();
},
unstable_isNewReconciler: enableNewReconciler
};
HooksDispatcherOnUpdateInDEV = {
readContext: function (context) {
return readContext(context);
},
useCallback: function (callback, deps) {
currentHookNameInDev = 'useCallback';
updateHookTypesDev();
return updateCallback(callback, deps);
},
useContext: function (context) {
currentHookNameInDev = 'useContext';
updateHookTypesDev();
return readContext(context);
},
useEffect: function (create, deps) {
currentHookNameInDev = 'useEffect';
updateHookTypesDev();
return updateEffect(create, deps);
},
useImperativeHandle: function (ref, create, deps) {
currentHookNameInDev = 'useImperativeHandle';
updateHookTypesDev();
return updateImperativeHandle(ref, create, deps);
},
useInsertionEffect: function (create, deps) {
currentHookNameInDev = 'useInsertionEffect';
updateHookTypesDev();
return updateInsertionEffect(create, deps);
},
useLayoutEffect: function (create, deps) {
currentHookNameInDev = 'useLayoutEffect';
updateHookTypesDev();
return updateLayoutEffect(create, deps);
},
useMemo: function (create, deps) {
currentHookNameInDev = 'useMemo';
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return updateMemo(create, deps);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useReducer: function (reducer, initialArg, init) {
currentHookNameInDev = 'useReducer';
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return updateReducer(reducer, initialArg, init);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useRef: function (initialValue) {
currentHookNameInDev = 'useRef';
updateHookTypesDev();
return updateRef();
},
useState: function (initialState) {
currentHookNameInDev = 'useState';
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return updateState(initialState);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useDebugValue: function (value, formatterFn) {
currentHookNameInDev = 'useDebugValue';
updateHookTypesDev();
return updateDebugValue();
},
useDeferredValue: function (value) {
currentHookNameInDev = 'useDeferredValue';
updateHookTypesDev();
return updateDeferredValue(value);
},
useTransition: function () {
currentHookNameInDev = 'useTransition';
updateHookTypesDev();
return updateTransition();
},
useMutableSource: function (source, getSnapshot, subscribe) {
currentHookNameInDev = 'useMutableSource';
updateHookTypesDev();
return updateMutableSource();
},
useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
currentHookNameInDev = 'useSyncExternalStore';
updateHookTypesDev();
return updateSyncExternalStore(subscribe, getSnapshot);
},
useId: function () {
currentHookNameInDev = 'useId';
updateHookTypesDev();
return updateId();
},
unstable_isNewReconciler: enableNewReconciler
};
HooksDispatcherOnRerenderInDEV = {
readContext: function (context) {
return readContext(context);
},
useCallback: function (callback, deps) {
currentHookNameInDev = 'useCallback';
updateHookTypesDev();
return updateCallback(callback, deps);
},
useContext: function (context) {
currentHookNameInDev = 'useContext';
updateHookTypesDev();
return readContext(context);
},
useEffect: function (create, deps) {
currentHookNameInDev = 'useEffect';
updateHookTypesDev();
return updateEffect(create, deps);
},
useImperativeHandle: function (ref, create, deps) {
currentHookNameInDev = 'useImperativeHandle';
updateHookTypesDev();
return updateImperativeHandle(ref, create, deps);
},
useInsertionEffect: function (create, deps) {
currentHookNameInDev = 'useInsertionEffect';
updateHookTypesDev();
return updateInsertionEffect(create, deps);
},
useLayoutEffect: function (create, deps) {
currentHookNameInDev = 'useLayoutEffect';
updateHookTypesDev();
return updateLayoutEffect(create, deps);
},
useMemo: function (create, deps) {
currentHookNameInDev = 'useMemo';
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
try {
return updateMemo(create, deps);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useReducer: function (reducer, initialArg, init) {
currentHookNameInDev = 'useReducer';
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
try {
return rerenderReducer(reducer, initialArg, init);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useRef: function (initialValue) {
currentHookNameInDev = 'useRef';
updateHookTypesDev();
return updateRef();
},
useState: function (initialState) {
currentHookNameInDev = 'useState';
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
try {
return rerenderState(initialState);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useDebugValue: function (value, formatterFn) {
currentHookNameInDev = 'useDebugValue';
updateHookTypesDev();
return updateDebugValue();
},
useDeferredValue: function (value) {
currentHookNameInDev = 'useDeferredValue';
updateHookTypesDev();
return rerenderDeferredValue(value);
},
useTransition: function () {
currentHookNameInDev = 'useTransition';
updateHookTypesDev();
return rerenderTransition();
},
useMutableSource: function (source, getSnapshot, subscribe) {
currentHookNameInDev = 'useMutableSource';
updateHookTypesDev();
return updateMutableSource();
},
useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
currentHookNameInDev = 'useSyncExternalStore';
updateHookTypesDev();
return updateSyncExternalStore(subscribe, getSnapshot);
},
useId: function () {
currentHookNameInDev = 'useId';
updateHookTypesDev();
return updateId();
},
unstable_isNewReconciler: enableNewReconciler
};
InvalidNestedHooksDispatcherOnMountInDEV = {
readContext: function (context) {
warnInvalidContextAccess();
return readContext(context);
},
useCallback: function (callback, deps) {
currentHookNameInDev = 'useCallback';
warnInvalidHookAccess();
mountHookTypesDev();
return mountCallback(callback, deps);
},
useContext: function (context) {
currentHookNameInDev = 'useContext';
warnInvalidHookAccess();
mountHookTypesDev();
return readContext(context);
},
useEffect: function (create, deps) {
currentHookNameInDev = 'useEffect';
warnInvalidHookAccess();
mountHookTypesDev();
return mountEffect(create, deps);
},
useImperativeHandle: function (ref, create, deps) {
currentHookNameInDev = 'useImperativeHandle';
warnInvalidHookAccess();
mountHookTypesDev();
return mountImperativeHandle(ref, create, deps);
},
useInsertionEffect: function (create, deps) {
currentHookNameInDev = 'useInsertionEffect';
warnInvalidHookAccess();
mountHookTypesDev();
return mountInsertionEffect(create, deps);
},
useLayoutEffect: function (create, deps) {
currentHookNameInDev = 'useLayoutEffect';
warnInvalidHookAccess();
mountHookTypesDev();
return mountLayoutEffect(create, deps);
},
useMemo: function (create, deps) {
currentHookNameInDev = 'useMemo';
warnInvalidHookAccess();
mountHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountMemo(create, deps);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useReducer: function (reducer, initialArg, init) {
currentHookNameInDev = 'useReducer';
warnInvalidHookAccess();
mountHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountReducer(reducer, initialArg, init);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useRef: function (initialValue) {
currentHookNameInDev = 'useRef';
warnInvalidHookAccess();
mountHookTypesDev();
return mountRef(initialValue);
},
useState: function (initialState) {
currentHookNameInDev = 'useState';
warnInvalidHookAccess();
mountHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountState(initialState);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useDebugValue: function (value, formatterFn) {
currentHookNameInDev = 'useDebugValue';
warnInvalidHookAccess();
mountHookTypesDev();
return mountDebugValue();
},
useDeferredValue: function (value) {
currentHookNameInDev = 'useDeferredValue';
warnInvalidHookAccess();
mountHookTypesDev();
return mountDeferredValue(value);
},
useTransition: function () {
currentHookNameInDev = 'useTransition';
warnInvalidHookAccess();
mountHookTypesDev();
return mountTransition();
},
useMutableSource: function (source, getSnapshot, subscribe) {
currentHookNameInDev = 'useMutableSource';
warnInvalidHookAccess();
mountHookTypesDev();
return mountMutableSource();
},
useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
currentHookNameInDev = 'useSyncExternalStore';
warnInvalidHookAccess();
mountHookTypesDev();
return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
},
useId: function () {
currentHookNameInDev = 'useId';
warnInvalidHookAccess();
mountHookTypesDev();
return mountId();
},
unstable_isNewReconciler: enableNewReconciler
};
InvalidNestedHooksDispatcherOnUpdateInDEV = {
readContext: function (context) {
warnInvalidContextAccess();
return readContext(context);
},
useCallback: function (callback, deps) {
currentHookNameInDev = 'useCallback';
warnInvalidHookAccess();
updateHookTypesDev();
return updateCallback(callback, deps);
},
useContext: function (context) {
currentHookNameInDev = 'useContext';
warnInvalidHookAccess();
updateHookTypesDev();
return readContext(context);
},
useEffect: function (create, deps) {
currentHookNameInDev = 'useEffect';
warnInvalidHookAccess();
updateHookTypesDev();
return updateEffect(create, deps);
},
useImperativeHandle: function (ref, create, deps) {
currentHookNameInDev = 'useImperativeHandle';
warnInvalidHookAccess();
updateHookTypesDev();
return updateImperativeHandle(ref, create, deps);
},
useInsertionEffect: function (create, deps) {
currentHookNameInDev = 'useInsertionEffect';
warnInvalidHookAccess();
updateHookTypesDev();
return updateInsertionEffect(create, deps);
},
useLayoutEffect: function (create, deps) {
currentHookNameInDev = 'useLayoutEffect';
warnInvalidHookAccess();
updateHookTypesDev();
return updateLayoutEffect(create, deps);
},
useMemo: function (create, deps) {
currentHookNameInDev = 'useMemo';
warnInvalidHookAccess();
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return updateMemo(create, deps);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useReducer: function (reducer, initialArg, init) {
currentHookNameInDev = 'useReducer';
warnInvalidHookAccess();
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return updateReducer(reducer, initialArg, init);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useRef: function (initialValue) {
currentHookNameInDev = 'useRef';
warnInvalidHookAccess();
updateHookTypesDev();
return updateRef();
},
useState: function (initialState) {
currentHookNameInDev = 'useState';
warnInvalidHookAccess();
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return updateState(initialState);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useDebugValue: function (value, formatterFn) {
currentHookNameInDev = 'useDebugValue';
warnInvalidHookAccess();
updateHookTypesDev();
return updateDebugValue();
},
useDeferredValue: function (value) {
currentHookNameInDev = 'useDeferredValue';
warnInvalidHookAccess();
updateHookTypesDev();
return updateDeferredValue(value);
},
useTransition: function () {
currentHookNameInDev = 'useTransition';
warnInvalidHookAccess();
updateHookTypesDev();
return updateTransition();
},
useMutableSource: function (source, getSnapshot, subscribe) {
currentHookNameInDev = 'useMutableSource';
warnInvalidHookAccess();
updateHookTypesDev();
return updateMutableSource();
},
useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
currentHookNameInDev = 'useSyncExternalStore';
warnInvalidHookAccess();
updateHookTypesDev();
return updateSyncExternalStore(subscribe, getSnapshot);
},
useId: function () {
currentHookNameInDev = 'useId';
warnInvalidHookAccess();
updateHookTypesDev();
return updateId();
},
unstable_isNewReconciler: enableNewReconciler
};
InvalidNestedHooksDispatcherOnRerenderInDEV = {
readContext: function (context) {
warnInvalidContextAccess();
return readContext(context);
},
useCallback: function (callback, deps) {
currentHookNameInDev = 'useCallback';
warnInvalidHookAccess();
updateHookTypesDev();
return updateCallback(callback, deps);
},
useContext: function (context) {
currentHookNameInDev = 'useContext';
warnInvalidHookAccess();
updateHookTypesDev();
return readContext(context);
},
useEffect: function (create, deps) {
currentHookNameInDev = 'useEffect';
warnInvalidHookAccess();
updateHookTypesDev();
return updateEffect(create, deps);
},
useImperativeHandle: function (ref, create, deps) {
currentHookNameInDev = 'useImperativeHandle';
warnInvalidHookAccess();
updateHookTypesDev();
return updateImperativeHandle(ref, create, deps);
},
useInsertionEffect: function (create, deps) {
currentHookNameInDev = 'useInsertionEffect';
warnInvalidHookAccess();
updateHookTypesDev();
return updateInsertionEffect(create, deps);
},
useLayoutEffect: function (create, deps) {
currentHookNameInDev = 'useLayoutEffect';
warnInvalidHookAccess();
updateHookTypesDev();
return updateLayoutEffect(create, deps);
},
useMemo: function (create, deps) {
currentHookNameInDev = 'useMemo';
warnInvalidHookAccess();
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return updateMemo(create, deps);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useReducer: function (reducer, initialArg, init) {
currentHookNameInDev = 'useReducer';
warnInvalidHookAccess();
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return rerenderReducer(reducer, initialArg, init);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useRef: function (initialValue) {
currentHookNameInDev = 'useRef';
warnInvalidHookAccess();
updateHookTypesDev();
return updateRef();
},
useState: function (initialState) {
currentHookNameInDev = 'useState';
warnInvalidHookAccess();
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return rerenderState(initialState);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useDebugValue: function (value, formatterFn) {
currentHookNameInDev = 'useDebugValue';
warnInvalidHookAccess();
updateHookTypesDev();
return updateDebugValue();
},
useDeferredValue: function (value) {
currentHookNameInDev = 'useDeferredValue';
warnInvalidHookAccess();
updateHookTypesDev();
return rerenderDeferredValue(value);
},
useTransition: function () {
currentHookNameInDev = 'useTransition';
warnInvalidHookAccess();
updateHookTypesDev();
return rerenderTransition();
},
useMutableSource: function (source, getSnapshot, subscribe) {
currentHookNameInDev = 'useMutableSource';
warnInvalidHookAccess();
updateHookTypesDev();
return updateMutableSource();
},
useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
currentHookNameInDev = 'useSyncExternalStore';
warnInvalidHookAccess();
updateHookTypesDev();
return updateSyncExternalStore(subscribe, getSnapshot);
},
useId: function () {
currentHookNameInDev = 'useId';
warnInvalidHookAccess();
updateHookTypesDev();
return updateId();
},
unstable_isNewReconciler: enableNewReconciler
};
}
var now$1 = unstable_now;
var commitTime = 0;
var layoutEffectStartTime = -1;
var profilerStartTime = -1;
var passiveEffectStartTime = -1;
/**
* Tracks whether the current update was a nested/cascading update (scheduled from a layout effect).
*
* The overall sequence is:
* 1. render
* 2. commit (and call `onRender`, `onCommit`)
* 3. check for nested updates
* 4. flush passive effects (and call `onPostCommit`)
*
* Nested updates are identified in step 3 above,
* but step 4 still applies to the work that was just committed.
* We use two flags to track nested updates then:
* one tracks whether the upcoming update is a nested update,
* and the other tracks whether the current update was a nested update.
* The first value gets synced to the second at the start of the render phase.
*/
var currentUpdateIsNested = false;
var nestedUpdateScheduled = false;
function isCurrentUpdateNested() {
return currentUpdateIsNested;
}
function markNestedUpdateScheduled() {
{
nestedUpdateScheduled = true;
}
}
function resetNestedUpdateFlag() {
{
currentUpdateIsNested = false;
nestedUpdateScheduled = false;
}
}
function syncNestedUpdateFlag() {
{
currentUpdateIsNested = nestedUpdateScheduled;
nestedUpdateScheduled = false;
}
}
function getCommitTime() {
return commitTime;
}
function recordCommitTime() {
commitTime = now$1();
}
function startProfilerTimer(fiber) {
profilerStartTime = now$1();
if (fiber.actualStartTime < 0) {
fiber.actualStartTime = now$1();
}
}
function stopProfilerTimerIfRunning(fiber) {
profilerStartTime = -1;
}
function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {
if (profilerStartTime >= 0) {
var elapsedTime = now$1() - profilerStartTime;
fiber.actualDuration += elapsedTime;
if (overrideBaseTime) {
fiber.selfBaseDuration = elapsedTime;
}
profilerStartTime = -1;
}
}
function recordLayoutEffectDuration(fiber) {
if (layoutEffectStartTime >= 0) {
var elapsedTime = now$1() - layoutEffectStartTime;
layoutEffectStartTime = -1; // Store duration on the next nearest Profiler ancestor
// Or the root (for the DevTools Profiler to read)
var parentFiber = fiber.return;
while (parentFiber !== null) {
switch (parentFiber.tag) {
case HostRoot:
var root = parentFiber.stateNode;
root.effectDuration += elapsedTime;
return;
case Profiler:
var parentStateNode = parentFiber.stateNode;
parentStateNode.effectDuration += elapsedTime;
return;
}
parentFiber = parentFiber.return;
}
}
}
function recordPassiveEffectDuration(fiber) {
if (passiveEffectStartTime >= 0) {
var elapsedTime = now$1() - passiveEffectStartTime;
passiveEffectStartTime = -1; // Store duration on the next nearest Profiler ancestor
// Or the root (for the DevTools Profiler to read)
var parentFiber = fiber.return;
while (parentFiber !== null) {
switch (parentFiber.tag) {
case HostRoot:
var root = parentFiber.stateNode;
if (root !== null) {
root.passiveEffectDuration += elapsedTime;
}
return;
case Profiler:
var parentStateNode = parentFiber.stateNode;
if (parentStateNode !== null) {
// Detached fibers have their state node cleared out.
// In this case, the return pointer is also cleared out,
// so we won't be able to report the time spent in this Profiler's subtree.
parentStateNode.passiveEffectDuration += elapsedTime;
}
return;
}
parentFiber = parentFiber.return;
}
}
}
function startLayoutEffectTimer() {
layoutEffectStartTime = now$1();
}
function startPassiveEffectTimer() {
passiveEffectStartTime = now$1();
}
function transferActualDuration(fiber) {
// Transfer time spent rendering these children so we don't lose it
// after we rerender. This is used as a helper in special cases
// where we should count the work of multiple passes.
var child = fiber.child;
while (child) {
fiber.actualDuration += child.actualDuration;
child = child.sibling;
}
}
function createCapturedValueAtFiber(value, source) {
// If the value is an error, call this function immediately after it is thrown
// so the stack is accurate.
return {
value: value,
source: source,
stack: getStackByFiberInDevAndProd(source),
digest: null
};
}
function createCapturedValue(value, digest, stack) {
return {
value: value,
source: null,
stack: stack != null ? stack : null,
digest: digest != null ? digest : null
};
}
// This module is forked in different environments.
// By default, return `true` to log errors to the console.
// Forks can return `false` if this isn't desirable.
function showErrorDialog(boundary, errorInfo) {
return true;
}
function logCapturedError(boundary, errorInfo) {
try {
var logError = showErrorDialog(boundary, errorInfo); // Allow injected showErrorDialog() to prevent default console.error logging.
// This enables renderers like ReactNative to better manage redbox behavior.
if (logError === false) {
return;
}
var error = errorInfo.value;
if (true) {
var source = errorInfo.source;
var stack = errorInfo.stack;
var componentStack = stack !== null ? stack : ''; // Browsers support silencing uncaught errors by calling
// `preventDefault()` in window `error` handler.
// We record this information as an expando on the error.
if (error != null && error._suppressLogging) {
if (boundary.tag === ClassComponent) {
// The error is recoverable and was silenced.
// Ignore it and don't print the stack addendum.
// This is handy for testing error boundaries without noise.
return;
} // The error is fatal. Since the silencing might have
// been accidental, we'll surface it anyway.
// However, the browser would have silenced the original error
// so we'll print it first, and then print the stack addendum.
console['error'](error); // Don't transform to our wrapper
// For a more detailed description of this block, see:
// https://github.com/facebook/react/pull/13384
}
var componentName = source ? getComponentNameFromFiber(source) : null;
var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : 'The above error occurred in one of your React components:';
var errorBoundaryMessage;
if (boundary.tag === HostRoot) {
errorBoundaryMessage = 'Consider adding an error boundary to your tree to customize error handling behavior.\n' + 'Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.';
} else {
var errorBoundaryName = getComponentNameFromFiber(boundary) || 'Anonymous';
errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + ".");
}
var combinedMessage = componentNameMessage + "\n" + componentStack + "\n\n" + ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack.
// We don't include the original error message and JS stack because the browser
// has already printed it. Even if the application swallows the error, it is still
// displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
console['error'](combinedMessage); // Don't transform to our wrapper
} else {
// In production, we print the error directly.
// This will include the message, the JS stack, and anything the browser wants to show.
// We pass the error object instead of custom message so that the browser displays the error natively.
console['error'](error); // Don't transform to our wrapper
}
} catch (e) {
// This method must not throw, or React internal state will get messed up.
// If console.error is overridden, or logCapturedError() shows a dialog that throws,
// we want to report this error outside of the normal stack as a last resort.
// https://github.com/facebook/react/issues/13188
setTimeout(function () {
throw e;
});
}
}
var PossiblyWeakMap$1 = typeof WeakMap === 'function' ? WeakMap : Map;
function createRootErrorUpdate(fiber, errorInfo, lane) {
var update = createUpdate(NoTimestamp, lane); // Unmount the root by rendering null.
update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property
// being called "element".
update.payload = {
element: null
};
var error = errorInfo.value;
update.callback = function () {
onUncaughtError(error);
logCapturedError(fiber, errorInfo);
};
return update;
}
function createClassErrorUpdate(fiber, errorInfo, lane) {
var update = createUpdate(NoTimestamp, lane);
update.tag = CaptureUpdate;
var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
if (typeof getDerivedStateFromError === 'function') {
var error$1 = errorInfo.value;
update.payload = function () {
return getDerivedStateFromError(error$1);
};
update.callback = function () {
{
markFailedErrorBoundaryForHotReloading(fiber);
}
logCapturedError(fiber, errorInfo);
};
}
var inst = fiber.stateNode;
if (inst !== null && typeof inst.componentDidCatch === 'function') {
update.callback = function callback() {
{
markFailedErrorBoundaryForHotReloading(fiber);
}
logCapturedError(fiber, errorInfo);
if (typeof getDerivedStateFromError !== 'function') {
// To preserve the preexisting retry behavior of error boundaries,
// we keep track of which ones already failed during this batch.
// This gets reset before we yield back to the browser.
// TODO: Warn in strict mode if getDerivedStateFromError is
// not defined.
markLegacyErrorBoundaryAsFailed(this);
}
var error$1 = errorInfo.value;
var stack = errorInfo.stack;
this.componentDidCatch(error$1, {
componentStack: stack !== null ? stack : ''
});
{
if (typeof getDerivedStateFromError !== 'function') {
// If componentDidCatch is the only error boundary method defined,
// then it needs to call setState to recover from errors.
// If no state update is scheduled then the boundary will swallow the error.
if (!includesSomeLane(fiber.lanes, SyncLane)) {
error('%s: Error boundaries should implement getDerivedStateFromError(). ' + 'In that method, return a state update to display an error message or fallback UI.', getComponentNameFromFiber(fiber) || 'Unknown');
}
}
}
};
}
return update;
}
function attachPingListener(root, wakeable, lanes) {
// Attach a ping listener
//
// The data might resolve before we have a chance to commit the fallback. Or,
// in the case of a refresh, we'll never commit a fallback. So we need to
// attach a listener now. When it resolves ("pings"), we can decide whether to
// try rendering the tree again.
//
// Only attach a listener if one does not already exist for the lanes
// we're currently rendering (which acts like a "thread ID" here).
//
// We only need to do this in concurrent mode. Legacy Suspense always
// commits fallbacks synchronously, so there are no pings.
var pingCache = root.pingCache;
var threadIDs;
if (pingCache === null) {
pingCache = root.pingCache = new PossiblyWeakMap$1();
threadIDs = new Set();
pingCache.set(wakeable, threadIDs);
} else {
threadIDs = pingCache.get(wakeable);
if (threadIDs === undefined) {
threadIDs = new Set();
pingCache.set(wakeable, threadIDs);
}
}
if (!threadIDs.has(lanes)) {
// Memoize using the thread ID to prevent redundant listeners.
threadIDs.add(lanes);
var ping = pingSuspendedRoot.bind(null, root, wakeable, lanes);
{
if (isDevToolsPresent) {
// If we have pending work still, restore the original updaters
restorePendingUpdaters(root, lanes);
}
}
wakeable.then(ping, ping);
}
}
function attachRetryListener(suspenseBoundary, root, wakeable, lanes) {
// Retry listener
//
// If the fallback does commit, we need to attach a different type of
// listener. This one schedules an update on the Suspense boundary to turn
// the fallback state off.
//
// Stash the wakeable on the boundary fiber so we can access it in the
// commit phase.
//
// When the wakeable resolves, we'll attempt to render the boundary
// again ("retry").
var wakeables = suspenseBoundary.updateQueue;
if (wakeables === null) {
var updateQueue = new Set();
updateQueue.add(wakeable);
suspenseBoundary.updateQueue = updateQueue;
} else {
wakeables.add(wakeable);
}
}
function resetSuspendedComponent(sourceFiber, rootRenderLanes) {
// A legacy mode Suspense quirk, only relevant to hook components.
var tag = sourceFiber.tag;
if ((sourceFiber.mode & ConcurrentMode) === NoMode && (tag === FunctionComponent || tag === ForwardRef || tag === SimpleMemoComponent)) {
var currentSource = sourceFiber.alternate;
if (currentSource) {
sourceFiber.updateQueue = currentSource.updateQueue;
sourceFiber.memoizedState = currentSource.memoizedState;
sourceFiber.lanes = currentSource.lanes;
} else {
sourceFiber.updateQueue = null;
sourceFiber.memoizedState = null;
}
}
}
function getNearestSuspenseBoundaryToCapture(returnFiber) {
var node = returnFiber;
do {
if (node.tag === SuspenseComponent && shouldCaptureSuspense(node)) {
return node;
} // This boundary already captured during this render. Continue to the next
// boundary.
node = node.return;
} while (node !== null);
return null;
}
function markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes) {
// This marks a Suspense boundary so that when we're unwinding the stack,
// it captures the suspended "exception" and does a second (fallback) pass.
if ((suspenseBoundary.mode & ConcurrentMode) === NoMode) {
// Legacy Mode Suspense
//
// If the boundary is in legacy mode, we should *not*
// suspend the commit. Pretend as if the suspended component rendered
// null and keep rendering. When the Suspense boundary completes,
// we'll do a second pass to render the fallback.
if (suspenseBoundary === returnFiber) {
// Special case where we suspended while reconciling the children of
// a Suspense boundary's inner Offscreen wrapper fiber. This happens
// when a React.lazy component is a direct child of a
// Suspense boundary.
//
// Suspense boundaries are implemented as multiple fibers, but they
// are a single conceptual unit. The legacy mode behavior where we
// pretend the suspended fiber committed as `null` won't work,
// because in this case the "suspended" fiber is the inner
// Offscreen wrapper.
//
// Because the contents of the boundary haven't started rendering
// yet (i.e. nothing in the tree has partially rendered) we can
// switch to the regular, concurrent mode behavior: mark the
// boundary with ShouldCapture and enter the unwind phase.
suspenseBoundary.flags |= ShouldCapture;
} else {
suspenseBoundary.flags |= DidCapture;
sourceFiber.flags |= ForceUpdateForLegacySuspense; // We're going to commit this fiber even though it didn't complete.
// But we shouldn't call any lifecycle methods or callbacks. Remove
// all lifecycle effect tags.
sourceFiber.flags &= ~(LifecycleEffectMask | Incomplete);
if (sourceFiber.tag === ClassComponent) {
var currentSourceFiber = sourceFiber.alternate;
if (currentSourceFiber === null) {
// This is a new mount. Change the tag so it's not mistaken for a
// completed class component. For example, we should not call
// componentWillUnmount if it is deleted.
sourceFiber.tag = IncompleteClassComponent;
} else {
// When we try rendering again, we should not reuse the current fiber,
// since it's known to be in an inconsistent state. Use a force update to
// prevent a bail out.
var update = createUpdate(NoTimestamp, SyncLane);
update.tag = ForceUpdate;
enqueueUpdate(sourceFiber, update, SyncLane);
}
} // The source fiber did not complete. Mark it with Sync priority to
// indicate that it still has pending work.
sourceFiber.lanes = mergeLanes(sourceFiber.lanes, SyncLane);
}
return suspenseBoundary;
} // Confirmed that the boundary is in a concurrent mode tree. Continue
// with the normal suspend path.
//
// After this we'll use a set of heuristics to determine whether this
// render pass will run to completion or restart or "suspend" the commit.
// The actual logic for this is spread out in different places.
//
// This first principle is that if we're going to suspend when we complete
// a root, then we should also restart if we get an update or ping that
// might unsuspend it, and vice versa. The only reason to suspend is
// because you think you might want to restart before committing. However,
// it doesn't make sense to restart only while in the period we're suspended.
//
// Restarting too aggressively is also not good because it starves out any
// intermediate loading state. So we use heuristics to determine when.
// Suspense Heuristics
//
// If nothing threw a Promise or all the same fallbacks are already showing,
// then don't suspend/restart.
//
// If this is an initial render of a new tree of Suspense boundaries and
// those trigger a fallback, then don't suspend/restart. We want to ensure
// that we can show the initial loading state as quickly as possible.
//
// If we hit a "Delayed" case, such as when we'd switch from content back into
// a fallback, then we should always suspend/restart. Transitions apply
// to this case. If none is defined, JND is used instead.
//
// If we're already showing a fallback and it gets "retried", allowing us to show
// another level, but there's still an inner boundary that would show a fallback,
// then we suspend/restart for 500ms since the last time we showed a fallback
// anywhere in the tree. This effectively throttles progressive loading into a
// consistent train of commits. This also gives us an opportunity to restart to
// get to the completed state slightly earlier.
//
// If there's ambiguity due to batching it's resolved in preference of:
// 1) "delayed", 2) "initial render", 3) "retry".
//
// We want to ensure that a "busy" state doesn't get force committed. We want to
// ensure that new initial loading states can commit as soon as possible.
suspenseBoundary.flags |= ShouldCapture; // TODO: I think we can remove this, since we now use `DidCapture` in
// the begin phase to prevent an early bailout.
suspenseBoundary.lanes = rootRenderLanes;
return suspenseBoundary;
}
function throwException(root, returnFiber, sourceFiber, value, rootRenderLanes) {
// The source fiber did not complete.
sourceFiber.flags |= Incomplete;
{
if (isDevToolsPresent) {
// If we have pending work still, restore the original updaters
restorePendingUpdaters(root, rootRenderLanes);
}
}
if (value !== null && typeof value === 'object' && typeof value.then === 'function') {
// This is a wakeable. The component suspended.
var wakeable = value;
resetSuspendedComponent(sourceFiber);
{
if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) {
markDidThrowWhileHydratingDEV();
}
}
var suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber);
if (suspenseBoundary !== null) {
suspenseBoundary.flags &= ~ForceClientRender;
markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); // We only attach ping listeners in concurrent mode. Legacy Suspense always
// commits fallbacks synchronously, so there are no pings.
if (suspenseBoundary.mode & ConcurrentMode) {
attachPingListener(root, wakeable, rootRenderLanes);
}
attachRetryListener(suspenseBoundary, root, wakeable);
return;
} else {
// No boundary was found. Unless this is a sync update, this is OK.
// We can suspend and wait for more data to arrive.
if (!includesSyncLane(rootRenderLanes)) {
// This is not a sync update. Suspend. Since we're not activating a
// Suspense boundary, this will unwind all the way to the root without
// performing a second pass to render a fallback. (This is arguably how
// refresh transitions should work, too, since we're not going to commit
// the fallbacks anyway.)
//
// This case also applies to initial hydration.
attachPingListener(root, wakeable, rootRenderLanes);
renderDidSuspendDelayIfPossible();
return;
} // This is a sync/discrete update. We treat this case like an error
// because discrete renders are expected to produce a complete tree
// synchronously to maintain consistency with external state.
var uncaughtSuspenseError = new Error('A component suspended while responding to synchronous input. This ' + 'will cause the UI to be replaced with a loading indicator. To ' + 'fix, updates that suspend should be wrapped ' + 'with startTransition.'); // If we're outside a transition, fall through to the regular error path.
// The error will be caught by the nearest suspense boundary.
value = uncaughtSuspenseError;
}
} else {
// This is a regular error, not a Suspense wakeable.
if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) {
markDidThrowWhileHydratingDEV();
var _suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber); // If the error was thrown during hydration, we may be able to recover by
// discarding the dehydrated content and switching to a client render.
// Instead of surfacing the error, find the nearest Suspense boundary
// and render it again without hydration.
if (_suspenseBoundary !== null) {
if ((_suspenseBoundary.flags & ShouldCapture) === NoFlags) {
// Set a flag to indicate that we should try rendering the normal
// children again, not the fallback.
_suspenseBoundary.flags |= ForceClientRender;
}
markSuspenseBoundaryShouldCapture(_suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); // Even though the user may not be affected by this error, we should
// still log it so it can be fixed.
queueHydrationError(createCapturedValueAtFiber(value, sourceFiber));
return;
}
}
}
value = createCapturedValueAtFiber(value, sourceFiber);
renderDidError(value); // We didn't find a boundary that could handle this type of exception. Start
// over and traverse parent path again, this time treating the exception
// as an error.
var workInProgress = returnFiber;
do {
switch (workInProgress.tag) {
case HostRoot:
{
var _errorInfo = value;
workInProgress.flags |= ShouldCapture;
var lane = pickArbitraryLane(rootRenderLanes);
workInProgress.lanes = mergeLanes(workInProgress.lanes, lane);
var update = createRootErrorUpdate(workInProgress, _errorInfo, lane);
enqueueCapturedUpdate(workInProgress, update);
return;
}
case ClassComponent:
// Capture and retry
var errorInfo = value;
var ctor = workInProgress.type;
var instance = workInProgress.stateNode;
if ((workInProgress.flags & DidCapture) === NoFlags && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) {
workInProgress.flags |= ShouldCapture;
var _lane = pickArbitraryLane(rootRenderLanes);
workInProgress.lanes = mergeLanes(workInProgress.lanes, _lane); // Schedule the error boundary to re-render using updated state
var _update = createClassErrorUpdate(workInProgress, errorInfo, _lane);
enqueueCapturedUpdate(workInProgress, _update);
return;
}
break;
}
workInProgress = workInProgress.return;
} while (workInProgress !== null);
}
function getSuspendedCache() {
{
return null;
} // This function is called when a Suspense boundary suspends. It returns the
}
var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
var didReceiveUpdate = false;
var didWarnAboutBadClass;
var didWarnAboutModulePatternComponent;
var didWarnAboutContextTypeOnFunctionComponent;
var didWarnAboutGetDerivedStateOnFunctionComponent;
var didWarnAboutFunctionRefs;
var didWarnAboutReassigningProps;
var didWarnAboutRevealOrder;
var didWarnAboutTailOptions;
{
didWarnAboutBadClass = {};
didWarnAboutModulePatternComponent = {};
didWarnAboutContextTypeOnFunctionComponent = {};
didWarnAboutGetDerivedStateOnFunctionComponent = {};
didWarnAboutFunctionRefs = {};
didWarnAboutReassigningProps = false;
didWarnAboutRevealOrder = {};
didWarnAboutTailOptions = {};
}
function reconcileChildren(current, workInProgress, nextChildren, renderLanes) {
if (current === null) {
// If this is a fresh new component that hasn't been rendered yet, we
// won't update its child set by applying minimal side-effects. Instead,
// we will add them all to the child before it gets rendered. That means
// we can optimize this reconciliation pass by not tracking side-effects.
workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderLanes);
} else {
// If the current child is the same as the work in progress, it means that
// we haven't yet started any work on these children. Therefore, we use
// the clone algorithm to create a copy of all the current children.
// If we had any progressed work already, that is invalid at this point so
// let's throw it out.
workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren, renderLanes);
}
}
function forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes) {
// This function is fork of reconcileChildren. It's used in cases where we
// want to reconcile without matching against the existing set. This has the
// effect of all current children being unmounted; even if the type and key
// are the same, the old child is unmounted and a new child is created.
//
// To do this, we're going to go through the reconcile algorithm twice. In
// the first pass, we schedule a deletion for all the current children by
// passing null.
workInProgress.child = reconcileChildFibers(workInProgress, current.child, null, renderLanes); // In the second pass, we mount the new children. The trick here is that we
// pass null in place of where we usually pass the current child set. This has
// the effect of remounting all children regardless of whether their
// identities match.
workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes);
}
function updateForwardRef(current, workInProgress, Component, nextProps, renderLanes) {
// TODO: current can be non-null here even if the component
// hasn't yet mounted. This happens after the first render suspends.
// We'll need to figure out if this is fine or can cause issues.
{
if (workInProgress.type !== workInProgress.elementType) {
// Lazy component props can't be validated in createElement
// because they're only guaranteed to be resolved here.
var innerPropTypes = Component.propTypes;
if (innerPropTypes) {
checkPropTypes(innerPropTypes, nextProps, // Resolved props
'prop', getComponentNameFromType(Component));
}
}
}
var render = Component.render;
var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent
var nextChildren;
var hasId;
prepareToReadContext(workInProgress, renderLanes);
{
markComponentRenderStarted(workInProgress);
}
{
ReactCurrentOwner$1.current = workInProgress;
setIsRendering(true);
nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes);
hasId = checkDidRenderIdHook();
if ( workInProgress.mode & StrictLegacyMode) {
setIsStrictModeForDevtools(true);
try {
nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes);
hasId = checkDidRenderIdHook();
} finally {
setIsStrictModeForDevtools(false);
}
}
setIsRendering(false);
}
{
markComponentRenderStopped();
}
if (current !== null && !didReceiveUpdate) {
bailoutHooks(current, workInProgress, renderLanes);
return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
}
if (getIsHydrating() && hasId) {
pushMaterializedTreeId(workInProgress);
} // React DevTools reads this flag.
workInProgress.flags |= PerformedWork;
reconcileChildren(current, workInProgress, nextChildren, renderLanes);
return workInProgress.child;
}
function updateMemoComponent(current, workInProgress, Component, nextProps, renderLanes) {
if (current === null) {
var type = Component.type;
if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either.
Component.defaultProps === undefined) {
var resolvedType = type;
{
resolvedType = resolveFunctionForHotReloading(type);
} // If this is a plain function component without default props,
// and with only the default shallow comparison, we upgrade it
// to a SimpleMemoComponent to allow fast path updates.
workInProgress.tag = SimpleMemoComponent;
workInProgress.type = resolvedType;
{
validateFunctionComponentInDev(workInProgress, type);
}
return updateSimpleMemoComponent(current, workInProgress, resolvedType, nextProps, renderLanes);
}
{
var innerPropTypes = type.propTypes;
if (innerPropTypes) {
// Inner memo component props aren't currently validated in createElement.
// We could move it there, but we'd still need this for lazy code path.
checkPropTypes(innerPropTypes, nextProps, // Resolved props
'prop', getComponentNameFromType(type));
}
}
var child = createFiberFromTypeAndProps(Component.type, null, nextProps, workInProgress, workInProgress.mode, renderLanes);
child.ref = workInProgress.ref;
child.return = workInProgress;
workInProgress.child = child;
return child;
}
{
var _type = Component.type;
var _innerPropTypes = _type.propTypes;
if (_innerPropTypes) {
// Inner memo component props aren't currently validated in createElement.
// We could move it there, but we'd still need this for lazy code path.
checkPropTypes(_innerPropTypes, nextProps, // Resolved props
'prop', getComponentNameFromType(_type));
}
}
var currentChild = current.child; // This is always exactly one child
var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current, renderLanes);
if (!hasScheduledUpdateOrContext) {
// This will be the props with resolved defaultProps,
// unlike current.memoizedProps which will be the unresolved ones.
var prevProps = currentChild.memoizedProps; // Default to shallow comparison
var compare = Component.compare;
compare = compare !== null ? compare : shallowEqual;
if (compare(prevProps, nextProps) && current.ref === workInProgress.ref) {
return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
}
} // React DevTools reads this flag.
workInProgress.flags |= PerformedWork;
var newChild = createWorkInProgress(currentChild, nextProps);
newChild.ref = workInProgress.ref;
newChild.return = workInProgress;
workInProgress.child = newChild;
return newChild;
}
function updateSimpleMemoComponent(current, workInProgress, Component, nextProps, renderLanes) {
// TODO: current can be non-null here even if the component
// hasn't yet mounted. This happens when the inner render suspends.
// We'll need to figure out if this is fine or can cause issues.
{
if (workInProgress.type !== workInProgress.elementType) {
// Lazy component props can't be validated in createElement
// because they're only guaranteed to be resolved here.
var outerMemoType = workInProgress.elementType;
if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
// We warn when you define propTypes on lazy()
// so let's just skip over it to find memo() outer wrapper.
// Inner props for memo are validated later.
var lazyComponent = outerMemoType;
var payload = lazyComponent._payload;
var init = lazyComponent._init;
try {
outerMemoType = init(payload);
} catch (x) {
outerMemoType = null;
} // Inner propTypes will be validated in the function component path.
var outerPropTypes = outerMemoType && outerMemoType.propTypes;
if (outerPropTypes) {
checkPropTypes(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)
'prop', getComponentNameFromType(outerMemoType));
}
}
}
}
if (current !== null) {
var prevProps = current.memoizedProps;
if (shallowEqual(prevProps, nextProps) && current.ref === workInProgress.ref && ( // Prevent bailout if the implementation changed due to hot reload.
workInProgress.type === current.type )) {
didReceiveUpdate = false; // The props are shallowly equal. Reuse the previous props object, like we
// would during a normal fiber bailout.
//
// We don't have strong guarantees that the props object is referentially
// equal during updates where we can't bail out anyway — like if the props
// are shallowly equal, but there's a local state or context update in the
// same batch.
//
// However, as a principle, we should aim to make the behavior consistent
// across different ways of memoizing a component. For example, React.memo
// has a different internal Fiber layout if you pass a normal function
// component (SimpleMemoComponent) versus if you pass a different type
// like forwardRef (MemoComponent). But this is an implementation detail.
// Wrapping a component in forwardRef (or React.lazy, etc) shouldn't
// affect whether the props object is reused during a bailout.
workInProgress.pendingProps = nextProps = prevProps;
if (!checkScheduledUpdateOrContext(current, renderLanes)) {
// The pending lanes were cleared at the beginning of beginWork. We're
// about to bail out, but there might be other lanes that weren't
// included in the current render. Usually, the priority level of the
// remaining updates is accumulated during the evaluation of the
// component (i.e. when processing the update queue). But since since
// we're bailing out early *without* evaluating the component, we need
// to account for it here, too. Reset to the value of the current fiber.
// NOTE: This only applies to SimpleMemoComponent, not MemoComponent,
// because a MemoComponent fiber does not have hooks or an update queue;
// rather, it wraps around an inner component, which may or may not
// contains hooks.
// TODO: Move the reset at in beginWork out of the common path so that
// this is no longer necessary.
workInProgress.lanes = current.lanes;
return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
} else if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) {
// This is a special case that only exists for legacy mode.
// See https://github.com/facebook/react/pull/19216.
didReceiveUpdate = true;
}
}
}
return updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes);
}
function updateOffscreenComponent(current, workInProgress, renderLanes) {
var nextProps = workInProgress.pendingProps;
var nextChildren = nextProps.children;
var prevState = current !== null ? current.memoizedState : null;
if (nextProps.mode === 'hidden' || enableLegacyHidden ) {
// Rendering a hidden tree.
if ((workInProgress.mode & ConcurrentMode) === NoMode) {
// In legacy sync mode, don't defer the subtree. Render it now.
// TODO: Consider how Offscreen should work with transitions in the future
var nextState = {
baseLanes: NoLanes,
cachePool: null,
transitions: null
};
workInProgress.memoizedState = nextState;
pushRenderLanes(workInProgress, renderLanes);
} else if (!includesSomeLane(renderLanes, OffscreenLane)) {
var spawnedCachePool = null; // We're hidden, and we're not rendering at Offscreen. We will bail out
// and resume this tree later.
var nextBaseLanes;
if (prevState !== null) {
var prevBaseLanes = prevState.baseLanes;
nextBaseLanes = mergeLanes(prevBaseLanes, renderLanes);
} else {
nextBaseLanes = renderLanes;
} // Schedule this fiber to re-render at offscreen priority. Then bailout.
workInProgress.lanes = workInProgress.childLanes = laneToLanes(OffscreenLane);
var _nextState = {
baseLanes: nextBaseLanes,
cachePool: spawnedCachePool,
transitions: null
};
workInProgress.memoizedState = _nextState;
workInProgress.updateQueue = null;
// to avoid a push/pop misalignment.
pushRenderLanes(workInProgress, nextBaseLanes);
return null;
} else {
// This is the second render. The surrounding visible content has already
// committed. Now we resume rendering the hidden tree.
// Rendering at offscreen, so we can clear the base lanes.
var _nextState2 = {
baseLanes: NoLanes,
cachePool: null,
transitions: null
};
workInProgress.memoizedState = _nextState2; // Push the lanes that were skipped when we bailed out.
var subtreeRenderLanes = prevState !== null ? prevState.baseLanes : renderLanes;
pushRenderLanes(workInProgress, subtreeRenderLanes);
}
} else {
// Rendering a visible tree.
var _subtreeRenderLanes;
if (prevState !== null) {
// We're going from hidden -> visible.
_subtreeRenderLanes = mergeLanes(prevState.baseLanes, renderLanes);
workInProgress.memoizedState = null;
} else {
// We weren't previously hidden, and we still aren't, so there's nothing
// special to do. Need to push to the stack regardless, though, to avoid
// a push/pop misalignment.
_subtreeRenderLanes = renderLanes;
}
pushRenderLanes(workInProgress, _subtreeRenderLanes);
}
reconcileChildren(current, workInProgress, nextChildren, renderLanes);
return workInProgress.child;
} // Note: These happen to have identical begin phases, for now. We shouldn't hold
function updateFragment(current, workInProgress, renderLanes) {
var nextChildren = workInProgress.pendingProps;
reconcileChildren(current, workInProgress, nextChildren, renderLanes);
return workInProgress.child;
}
function updateMode(current, workInProgress, renderLanes) {
var nextChildren = workInProgress.pendingProps.children;
reconcileChildren(current, workInProgress, nextChildren, renderLanes);
return workInProgress.child;
}
function updateProfiler(current, workInProgress, renderLanes) {
{
workInProgress.flags |= Update;
{
// Reset effect durations for the next eventual effect phase.
// These are reset during render to allow the DevTools commit hook a chance to read them,
var stateNode = workInProgress.stateNode;
stateNode.effectDuration = 0;
stateNode.passiveEffectDuration = 0;
}
}
var nextProps = workInProgress.pendingProps;
var nextChildren = nextProps.children;
reconcileChildren(current, workInProgress, nextChildren, renderLanes);
return workInProgress.child;
}
function markRef(current, workInProgress) {
var ref = workInProgress.ref;
if (current === null && ref !== null || current !== null && current.ref !== ref) {
// Schedule a Ref effect
workInProgress.flags |= Ref;
{
workInProgress.flags |= RefStatic;
}
}
}
function updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes) {
{
if (workInProgress.type !== workInProgress.elementType) {
// Lazy component props can't be validated in createElement
// because they're only guaranteed to be resolved here.
var innerPropTypes = Component.propTypes;
if (innerPropTypes) {
checkPropTypes(innerPropTypes, nextProps, // Resolved props
'prop', getComponentNameFromType(Component));
}
}
}
var context;
{
var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
context = getMaskedContext(workInProgress, unmaskedContext);
}
var nextChildren;
var hasId;
prepareToReadContext(workInProgress, renderLanes);
{
markComponentRenderStarted(workInProgress);
}
{
ReactCurrentOwner$1.current = workInProgress;
setIsRendering(true);
nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes);
hasId = checkDidRenderIdHook();
if ( workInProgress.mode & StrictLegacyMode) {
setIsStrictModeForDevtools(true);
try {
nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes);
hasId = checkDidRenderIdHook();
} finally {
setIsStrictModeForDevtools(false);
}
}
setIsRendering(false);
}
{
markComponentRenderStopped();
}
if (current !== null && !didReceiveUpdate) {
bailoutHooks(current, workInProgress, renderLanes);
return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
}
if (getIsHydrating() && hasId) {
pushMaterializedTreeId(workInProgress);
} // React DevTools reads this flag.
workInProgress.flags |= PerformedWork;
reconcileChildren(current, workInProgress, nextChildren, renderLanes);
return workInProgress.child;
}
function updateClassComponent(current, workInProgress, Component, nextProps, renderLanes) {
{
// This is used by DevTools to force a boundary to error.
switch (shouldError(workInProgress)) {
case false:
{
var _instance = workInProgress.stateNode;
var ctor = workInProgress.type; // TODO This way of resetting the error boundary state is a hack.
// Is there a better way to do this?
var tempInstance = new ctor(workInProgress.memoizedProps, _instance.context);
var state = tempInstance.state;
_instance.updater.enqueueSetState(_instance, state, null);
break;
}
case true:
{
workInProgress.flags |= DidCapture;
workInProgress.flags |= ShouldCapture; // eslint-disable-next-line react-internal/prod-error-codes
var error$1 = new Error('Simulated error coming from DevTools');
var lane = pickArbitraryLane(renderLanes);
workInProgress.lanes = mergeLanes(workInProgress.lanes, lane); // Schedule the error boundary to re-render using updated state
var update = createClassErrorUpdate(workInProgress, createCapturedValueAtFiber(error$1, workInProgress), lane);
enqueueCapturedUpdate(workInProgress, update);
break;
}
}
if (workInProgress.type !== workInProgress.elementType) {
// Lazy component props can't be validated in createElement
// because they're only guaranteed to be resolved here.
var innerPropTypes = Component.propTypes;
if (innerPropTypes) {
checkPropTypes(innerPropTypes, nextProps, // Resolved props
'prop', getComponentNameFromType(Component));
}
}
} // Push context providers early to prevent context stack mismatches.
// During mounting we don't know the child context yet as the instance doesn't exist.
// We will invalidate the child context in finishClassComponent() right after rendering.
var hasContext;
if (isContextProvider(Component)) {
hasContext = true;
pushContextProvider(workInProgress);
} else {
hasContext = false;
}
prepareToReadContext(workInProgress, renderLanes);
var instance = workInProgress.stateNode;
var shouldUpdate;
if (instance === null) {
resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress); // In the initial pass we might need to construct the instance.
constructClassInstance(workInProgress, Component, nextProps);
mountClassInstance(workInProgress, Component, nextProps, renderLanes);
shouldUpdate = true;
} else if (current === null) {
// In a resume, we'll already have an instance we can reuse.
shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderLanes);
} else {
shouldUpdate = updateClassInstance(current, workInProgress, Component, nextProps, renderLanes);
}
var nextUnitOfWork = finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes);
{
var inst = workInProgress.stateNode;
if (shouldUpdate && inst.props !== nextProps) {
if (!didWarnAboutReassigningProps) {
error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromFiber(workInProgress) || 'a component');
}
didWarnAboutReassigningProps = true;
}
}
return nextUnitOfWork;
}
function finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes) {
// Refs should update even if shouldComponentUpdate returns false
markRef(current, workInProgress);
var didCaptureError = (workInProgress.flags & DidCapture) !== NoFlags;
if (!shouldUpdate && !didCaptureError) {
// Context providers should defer to sCU for rendering
if (hasContext) {
invalidateContextProvider(workInProgress, Component, false);
}
return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
}
var instance = workInProgress.stateNode; // Rerender
ReactCurrentOwner$1.current = workInProgress;
var nextChildren;
if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {
// If we captured an error, but getDerivedStateFromError is not defined,
// unmount all the children. componentDidCatch will schedule an update to
// re-render a fallback. This is temporary until we migrate everyone to
// the new API.
// TODO: Warn in a future release.
nextChildren = null;
{
stopProfilerTimerIfRunning();
}
} else {
{
markComponentRenderStarted(workInProgress);
}
{
setIsRendering(true);
nextChildren = instance.render();
if ( workInProgress.mode & StrictLegacyMode) {
setIsStrictModeForDevtools(true);
try {
instance.render();
} finally {
setIsStrictModeForDevtools(false);
}
}
setIsRendering(false);
}
{
markComponentRenderStopped();
}
} // React DevTools reads this flag.
workInProgress.flags |= PerformedWork;
if (current !== null && didCaptureError) {
// If we're recovering from an error, reconcile without reusing any of
// the existing children. Conceptually, the normal children and the children
// that are shown on error are two different sets, so we shouldn't reuse
// normal children even if their identities match.
forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes);
} else {
reconcileChildren(current, workInProgress, nextChildren, renderLanes);
} // Memoize state using the values we just used to render.
// TODO: Restructure so we never read values from the instance.
workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it.
if (hasContext) {
invalidateContextProvider(workInProgress, Component, true);
}
return workInProgress.child;
}
function pushHostRootContext(workInProgress) {
var root = workInProgress.stateNode;
if (root.pendingContext) {
pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);
} else if (root.context) {
// Should always be set
pushTopLevelContextObject(workInProgress, root.context, false);
}
pushHostContainer(workInProgress, root.containerInfo);
}
function updateHostRoot(current, workInProgress, renderLanes) {
pushHostRootContext(workInProgress);
if (current === null) {
throw new Error('Should have a current fiber. This is a bug in React.');
}
var nextProps = workInProgress.pendingProps;
var prevState = workInProgress.memoizedState;
var prevChildren = prevState.element;
cloneUpdateQueue(current, workInProgress);
processUpdateQueue(workInProgress, nextProps, null, renderLanes);
var nextState = workInProgress.memoizedState;
var root = workInProgress.stateNode;
// being called "element".
var nextChildren = nextState.element;
if ( prevState.isDehydrated) {
// This is a hydration root whose shell has not yet hydrated. We should
// attempt to hydrate.
// Flip isDehydrated to false to indicate that when this render
// finishes, the root will no longer be dehydrated.
var overrideState = {
element: nextChildren,
isDehydrated: false,
cache: nextState.cache,
pendingSuspenseBoundaries: nextState.pendingSuspenseBoundaries,
transitions: nextState.transitions
};
var updateQueue = workInProgress.updateQueue; // `baseState` can always be the last state because the root doesn't
// have reducer functions so it doesn't need rebasing.
updateQueue.baseState = overrideState;
workInProgress.memoizedState = overrideState;
if (workInProgress.flags & ForceClientRender) {
// Something errored during a previous attempt to hydrate the shell, so we
// forced a client render.
var recoverableError = createCapturedValueAtFiber(new Error('There was an error while hydrating. Because the error happened outside ' + 'of a Suspense boundary, the entire root will switch to ' + 'client rendering.'), workInProgress);
return mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, recoverableError);
} else if (nextChildren !== prevChildren) {
var _recoverableError = createCapturedValueAtFiber(new Error('This root received an early update, before anything was able ' + 'hydrate. Switched the entire root to client rendering.'), workInProgress);
return mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, _recoverableError);
} else {
// The outermost shell has not hydrated yet. Start hydrating.
enterHydrationState(workInProgress);
var child = mountChildFibers(workInProgress, null, nextChildren, renderLanes);
workInProgress.child = child;
var node = child;
while (node) {
// Mark each child as hydrating. This is a fast path to know whether this
// tree is part of a hydrating tree. This is used to determine if a child
// node has fully mounted yet, and for scheduling event replaying.
// Conceptually this is similar to Placement in that a new subtree is
// inserted into the React tree here. It just happens to not need DOM
// mutations because it already exists.
node.flags = node.flags & ~Placement | Hydrating;
node = node.sibling;
}
}
} else {
// Root is not dehydrated. Either this is a client-only root, or it
// already hydrated.
resetHydrationState();
if (nextChildren === prevChildren) {
return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
}
reconcileChildren(current, workInProgress, nextChildren, renderLanes);
}
return workInProgress.child;
}
function mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, recoverableError) {
// Revert to client rendering.
resetHydrationState();
queueHydrationError(recoverableError);
workInProgress.flags |= ForceClientRender;
reconcileChildren(current, workInProgress, nextChildren, renderLanes);
return workInProgress.child;
}
function updateHostComponent(current, workInProgress, renderLanes) {
pushHostContext(workInProgress);
if (current === null) {
tryToClaimNextHydratableInstance(workInProgress);
}
var type = workInProgress.type;
var nextProps = workInProgress.pendingProps;
var prevProps = current !== null ? current.memoizedProps : null;
var nextChildren = nextProps.children;
var isDirectTextChild = shouldSetTextContent(type, nextProps);
if (isDirectTextChild) {
// We special case a direct text child of a host node. This is a common
// case. We won't handle it as a reified child. We will instead handle
// this in the host environment that also has access to this prop. That
// avoids allocating another HostText fiber and traversing it.
nextChildren = null;
} else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
// If we're switching from a direct text child to a normal child, or to
// empty, we need to schedule the text content to be reset.
workInProgress.flags |= ContentReset;
}
markRef(current, workInProgress);
reconcileChildren(current, workInProgress, nextChildren, renderLanes);
return workInProgress.child;
}
function updateHostText(current, workInProgress) {
if (current === null) {
tryToClaimNextHydratableInstance(workInProgress);
} // Nothing to do here. This is terminal. We'll do the completion step
// immediately after.
return null;
}
function mountLazyComponent(_current, workInProgress, elementType, renderLanes) {
resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress);
var props = workInProgress.pendingProps;
var lazyComponent = elementType;
var payload = lazyComponent._payload;
var init = lazyComponent._init;
var Component = init(payload); // Store the unwrapped component in the type.
workInProgress.type = Component;
var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);
var resolvedProps = resolveDefaultProps(Component, props);
var child;
switch (resolvedTag) {
case FunctionComponent:
{
{
validateFunctionComponentInDev(workInProgress, Component);
workInProgress.type = Component = resolveFunctionForHotReloading(Component);
}
child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderLanes);
return child;
}
case ClassComponent:
{
{
workInProgress.type = Component = resolveClassForHotReloading(Component);
}
child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderLanes);
return child;
}
case ForwardRef:
{
{
workInProgress.type = Component = resolveForwardRefForHotReloading(Component);
}
child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderLanes);
return child;
}
case MemoComponent:
{
{
if (workInProgress.type !== workInProgress.elementType) {
var outerPropTypes = Component.propTypes;
if (outerPropTypes) {
checkPropTypes(outerPropTypes, resolvedProps, // Resolved for outer only
'prop', getComponentNameFromType(Component));
}
}
}
child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too
renderLanes);
return child;
}
}
var hint = '';
{
if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {
hint = ' Did you wrap a component in React.lazy() more than once?';
}
} // This message intentionally doesn't mention ForwardRef or MemoComponent
// because the fact that it's a separate type of work is an
// implementation detail.
throw new Error("Element type is invalid. Received a promise that resolves to: " + Component + ". " + ("Lazy element type must resolve to a class or function." + hint));
}
function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderLanes) {
resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress); // Promote the fiber to a class and try rendering again.
workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent`
// Push context providers early to prevent context stack mismatches.
// During mounting we don't know the child context yet as the instance doesn't exist.
// We will invalidate the child context in finishClassComponent() right after rendering.
var hasContext;
if (isContextProvider(Component)) {
hasContext = true;
pushContextProvider(workInProgress);
} else {
hasContext = false;
}
prepareToReadContext(workInProgress, renderLanes);
constructClassInstance(workInProgress, Component, nextProps);
mountClassInstance(workInProgress, Component, nextProps, renderLanes);
return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes);
}
function mountIndeterminateComponent(_current, workInProgress, Component, renderLanes) {
resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress);
var props = workInProgress.pendingProps;
var context;
{
var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);
context = getMaskedContext(workInProgress, unmaskedContext);
}
prepareToReadContext(workInProgress, renderLanes);
var value;
var hasId;
{
markComponentRenderStarted(workInProgress);
}
{
if (Component.prototype && typeof Component.prototype.render === 'function') {
var componentName = getComponentNameFromType(Component) || 'Unknown';
if (!didWarnAboutBadClass[componentName]) {
error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName);
didWarnAboutBadClass[componentName] = true;
}
}
if (workInProgress.mode & StrictLegacyMode) {
ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
}
setIsRendering(true);
ReactCurrentOwner$1.current = workInProgress;
value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes);
hasId = checkDidRenderIdHook();
setIsRendering(false);
}
{
markComponentRenderStopped();
} // React DevTools reads this flag.
workInProgress.flags |= PerformedWork;
{
// Support for module components is deprecated and is removed behind a flag.
// Whether or not it would crash later, we want to show a good message in DEV first.
if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
var _componentName = getComponentNameFromType(Component) || 'Unknown';
if (!didWarnAboutModulePatternComponent[_componentName]) {
error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName);
didWarnAboutModulePatternComponent[_componentName] = true;
}
}
}
if ( // Run these checks in production only if the flag is off.
// Eventually we'll delete this branch altogether.
typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
{
var _componentName2 = getComponentNameFromType(Component) || 'Unknown';
if (!didWarnAboutModulePatternComponent[_componentName2]) {
error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName2, _componentName2, _componentName2);
didWarnAboutModulePatternComponent[_componentName2] = true;
}
} // Proceed under the assumption that this is a class instance
workInProgress.tag = ClassComponent; // Throw out any hooks that were used.
workInProgress.memoizedState = null;
workInProgress.updateQueue = null; // Push context providers early to prevent context stack mismatches.
// During mounting we don't know the child context yet as the instance doesn't exist.
// We will invalidate the child context in finishClassComponent() right after rendering.
var hasContext = false;
if (isContextProvider(Component)) {
hasContext = true;
pushContextProvider(workInProgress);
} else {
hasContext = false;
}
workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;
initializeUpdateQueue(workInProgress);
adoptClassInstance(workInProgress, value);
mountClassInstance(workInProgress, Component, props, renderLanes);
return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes);
} else {
// Proceed under the assumption that this is a function component
workInProgress.tag = FunctionComponent;
{
if ( workInProgress.mode & StrictLegacyMode) {
setIsStrictModeForDevtools(true);
try {
value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes);
hasId = checkDidRenderIdHook();
} finally {
setIsStrictModeForDevtools(false);
}
}
}
if (getIsHydrating() && hasId) {
pushMaterializedTreeId(workInProgress);
}
reconcileChildren(null, workInProgress, value, renderLanes);
{
validateFunctionComponentInDev(workInProgress, Component);
}
return workInProgress.child;
}
}
function validateFunctionComponentInDev(workInProgress, Component) {
{
if (Component) {
if (Component.childContextTypes) {
error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component');
}
}
if (workInProgress.ref !== null) {
var info = '';
var ownerName = getCurrentFiberOwnerNameInDevOrNull();
if (ownerName) {
info += '\n\nCheck the render method of `' + ownerName + '`.';
}
var warningKey = ownerName || '';
var debugSource = workInProgress._debugSource;
if (debugSource) {
warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
}
if (!didWarnAboutFunctionRefs[warningKey]) {
didWarnAboutFunctionRefs[warningKey] = true;
error('Function components cannot be given refs. ' + 'Attempts to access this ref will fail. ' + 'Did you mean to use React.forwardRef()?%s', info);
}
}
if (typeof Component.getDerivedStateFromProps === 'function') {
var _componentName3 = getComponentNameFromType(Component) || 'Unknown';
if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) {
error('%s: Function components do not support getDerivedStateFromProps.', _componentName3);
didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true;
}
}
if (typeof Component.contextType === 'object' && Component.contextType !== null) {
var _componentName4 = getComponentNameFromType(Component) || 'Unknown';
if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) {
error('%s: Function components do not support contextType.', _componentName4);
didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true;
}
}
}
}
var SUSPENDED_MARKER = {
dehydrated: null,
treeContext: null,
retryLane: NoLane
};
function mountSuspenseOffscreenState(renderLanes) {
return {
baseLanes: renderLanes,
cachePool: getSuspendedCache(),
transitions: null
};
}
function updateSuspenseOffscreenState(prevOffscreenState, renderLanes) {
var cachePool = null;
return {
baseLanes: mergeLanes(prevOffscreenState.baseLanes, renderLanes),
cachePool: cachePool,
transitions: prevOffscreenState.transitions
};
} // TODO: Probably should inline this back
function shouldRemainOnFallback(suspenseContext, current, workInProgress, renderLanes) {
// If we're already showing a fallback, there are cases where we need to
// remain on that fallback regardless of whether the content has resolved.
// For example, SuspenseList coordinates when nested content appears.
if (current !== null) {
var suspenseState = current.memoizedState;
if (suspenseState === null) {
// Currently showing content. Don't hide it, even if ForceSuspenseFallback
// is true. More precise name might be "ForceRemainSuspenseFallback".
// Note: This is a factoring smell. Can't remain on a fallback if there's
// no fallback to remain on.
return false;
}
} // Not currently showing content. Consult the Suspense context.
return hasSuspenseContext(suspenseContext, ForceSuspenseFallback);
}
function getRemainingWorkInPrimaryTree(current, renderLanes) {
// TODO: Should not remove render lanes that were pinged during this render
return removeLanes(current.childLanes, renderLanes);
}
function updateSuspenseComponent(current, workInProgress, renderLanes) {
var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend.
{
if (shouldSuspend(workInProgress)) {
workInProgress.flags |= DidCapture;
}
}
var suspenseContext = suspenseStackCursor.current;
var showFallback = false;
var didSuspend = (workInProgress.flags & DidCapture) !== NoFlags;
if (didSuspend || shouldRemainOnFallback(suspenseContext, current)) {
// Something in this boundary's subtree already suspended. Switch to
// rendering the fallback children.
showFallback = true;
workInProgress.flags &= ~DidCapture;
} else {
// Attempting the main content
if (current === null || current.memoizedState !== null) {
// This is a new mount or this boundary is already showing a fallback state.
// Mark this subtree context as having at least one invisible parent that could
// handle the fallback state.
// Avoided boundaries are not considered since they cannot handle preferred fallback states.
{
suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext);
}
}
}
suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
pushSuspenseContext(workInProgress, suspenseContext); // OK, the next part is confusing. We're about to reconcile the Suspense
// boundary's children. This involves some custom reconciliation logic. Two
// main reasons this is so complicated.
//
// First, Legacy Mode has different semantics for backwards compatibility. The
// primary tree will commit in an inconsistent state, so when we do the
// second pass to render the fallback, we do some exceedingly, uh, clever
// hacks to make that not totally break. Like transferring effects and
// deletions from hidden tree. In Concurrent Mode, it's much simpler,
// because we bailout on the primary tree completely and leave it in its old
// state, no effects. Same as what we do for Offscreen (except that
// Offscreen doesn't have the first render pass).
//
// Second is hydration. During hydration, the Suspense fiber has a slightly
// different layout, where the child points to a dehydrated fragment, which
// contains the DOM rendered by the server.
//
// Third, even if you set all that aside, Suspense is like error boundaries in
// that we first we try to render one tree, and if that fails, we render again
// and switch to a different tree. Like a try/catch block. So we have to track
// which branch we're currently rendering. Ideally we would model this using
// a stack.
if (current === null) {
// Initial mount
// Special path for hydration
// If we're currently hydrating, try to hydrate this boundary.
tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component.
var suspenseState = workInProgress.memoizedState;
if (suspenseState !== null) {
var dehydrated = suspenseState.dehydrated;
if (dehydrated !== null) {
return mountDehydratedSuspenseComponent(workInProgress, dehydrated);
}
}
var nextPrimaryChildren = nextProps.children;
var nextFallbackChildren = nextProps.fallback;
if (showFallback) {
var fallbackFragment = mountSuspenseFallbackChildren(workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes);
var primaryChildFragment = workInProgress.child;
primaryChildFragment.memoizedState = mountSuspenseOffscreenState(renderLanes);
workInProgress.memoizedState = SUSPENDED_MARKER;
return fallbackFragment;
} else {
return mountSuspensePrimaryChildren(workInProgress, nextPrimaryChildren);
}
} else {
// This is an update.
// Special path for hydration
var prevState = current.memoizedState;
if (prevState !== null) {
var _dehydrated = prevState.dehydrated;
if (_dehydrated !== null) {
return updateDehydratedSuspenseComponent(current, workInProgress, didSuspend, nextProps, _dehydrated, prevState, renderLanes);
}
}
if (showFallback) {
var _nextFallbackChildren = nextProps.fallback;
var _nextPrimaryChildren = nextProps.children;
var fallbackChildFragment = updateSuspenseFallbackChildren(current, workInProgress, _nextPrimaryChildren, _nextFallbackChildren, renderLanes);
var _primaryChildFragment2 = workInProgress.child;
var prevOffscreenState = current.child.memoizedState;
_primaryChildFragment2.memoizedState = prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes) : updateSuspenseOffscreenState(prevOffscreenState, renderLanes);
_primaryChildFragment2.childLanes = getRemainingWorkInPrimaryTree(current, renderLanes);
workInProgress.memoizedState = SUSPENDED_MARKER;
return fallbackChildFragment;
} else {
var _nextPrimaryChildren2 = nextProps.children;
var _primaryChildFragment3 = updateSuspensePrimaryChildren(current, workInProgress, _nextPrimaryChildren2, renderLanes);
workInProgress.memoizedState = null;
return _primaryChildFragment3;
}
}
}
function mountSuspensePrimaryChildren(workInProgress, primaryChildren, renderLanes) {
var mode = workInProgress.mode;
var primaryChildProps = {
mode: 'visible',
children: primaryChildren
};
var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode);
primaryChildFragment.return = workInProgress;
workInProgress.child = primaryChildFragment;
return primaryChildFragment;
}
function mountSuspenseFallbackChildren(workInProgress, primaryChildren, fallbackChildren, renderLanes) {
var mode = workInProgress.mode;
var progressedPrimaryFragment = workInProgress.child;
var primaryChildProps = {
mode: 'hidden',
children: primaryChildren
};
var primaryChildFragment;
var fallbackChildFragment;
if ((mode & ConcurrentMode) === NoMode && progressedPrimaryFragment !== null) {
// In legacy mode, we commit the primary tree as if it successfully
// completed, even though it's in an inconsistent state.
primaryChildFragment = progressedPrimaryFragment;
primaryChildFragment.childLanes = NoLanes;
primaryChildFragment.pendingProps = primaryChildProps;
if ( workInProgress.mode & ProfileMode) {
// Reset the durations from the first pass so they aren't included in the
// final amounts. This seems counterintuitive, since we're intentionally
// not measuring part of the render phase, but this makes it match what we
// do in Concurrent Mode.
primaryChildFragment.actualDuration = 0;
primaryChildFragment.actualStartTime = -1;
primaryChildFragment.selfBaseDuration = 0;
primaryChildFragment.treeBaseDuration = 0;
}
fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null);
} else {
primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode);
fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null);
}
primaryChildFragment.return = workInProgress;
fallbackChildFragment.return = workInProgress;
primaryChildFragment.sibling = fallbackChildFragment;
workInProgress.child = primaryChildFragment;
return fallbackChildFragment;
}
function mountWorkInProgressOffscreenFiber(offscreenProps, mode, renderLanes) {
// The props argument to `createFiberFromOffscreen` is `any` typed, so we use
// this wrapper function to constrain it.
return createFiberFromOffscreen(offscreenProps, mode, NoLanes, null);
}
function updateWorkInProgressOffscreenFiber(current, offscreenProps) {
// The props argument to `createWorkInProgress` is `any` typed, so we use this
// wrapper function to constrain it.
return createWorkInProgress(current, offscreenProps);
}
function updateSuspensePrimaryChildren(current, workInProgress, primaryChildren, renderLanes) {
var currentPrimaryChildFragment = current.child;
var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
var primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, {
mode: 'visible',
children: primaryChildren
});
if ((workInProgress.mode & ConcurrentMode) === NoMode) {
primaryChildFragment.lanes = renderLanes;
}
primaryChildFragment.return = workInProgress;
primaryChildFragment.sibling = null;
if (currentFallbackChildFragment !== null) {
// Delete the fallback child fragment
var deletions = workInProgress.deletions;
if (deletions === null) {
workInProgress.deletions = [currentFallbackChildFragment];
workInProgress.flags |= ChildDeletion;
} else {
deletions.push(currentFallbackChildFragment);
}
}
workInProgress.child = primaryChildFragment;
return primaryChildFragment;
}
function updateSuspenseFallbackChildren(current, workInProgress, primaryChildren, fallbackChildren, renderLanes) {
var mode = workInProgress.mode;
var currentPrimaryChildFragment = current.child;
var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
var primaryChildProps = {
mode: 'hidden',
children: primaryChildren
};
var primaryChildFragment;
if ( // In legacy mode, we commit the primary tree as if it successfully
// completed, even though it's in an inconsistent state.
(mode & ConcurrentMode) === NoMode && // Make sure we're on the second pass, i.e. the primary child fragment was
// already cloned. In legacy mode, the only case where this isn't true is
// when DevTools forces us to display a fallback; we skip the first render
// pass entirely and go straight to rendering the fallback. (In Concurrent
// Mode, SuspenseList can also trigger this scenario, but this is a legacy-
// only codepath.)
workInProgress.child !== currentPrimaryChildFragment) {
var progressedPrimaryFragment = workInProgress.child;
primaryChildFragment = progressedPrimaryFragment;
primaryChildFragment.childLanes = NoLanes;
primaryChildFragment.pendingProps = primaryChildProps;
if ( workInProgress.mode & ProfileMode) {
// Reset the durations from the first pass so they aren't included in the
// final amounts. This seems counterintuitive, since we're intentionally
// not measuring part of the render phase, but this makes it match what we
// do in Concurrent Mode.
primaryChildFragment.actualDuration = 0;
primaryChildFragment.actualStartTime = -1;
primaryChildFragment.selfBaseDuration = currentPrimaryChildFragment.selfBaseDuration;
primaryChildFragment.treeBaseDuration = currentPrimaryChildFragment.treeBaseDuration;
} // The fallback fiber was added as a deletion during the first pass.
// However, since we're going to remain on the fallback, we no longer want
// to delete it.
workInProgress.deletions = null;
} else {
primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, primaryChildProps); // Since we're reusing a current tree, we need to reuse the flags, too.
// (We don't do this in legacy mode, because in legacy mode we don't re-use
// the current tree; see previous branch.)
primaryChildFragment.subtreeFlags = currentPrimaryChildFragment.subtreeFlags & StaticMask;
}
var fallbackChildFragment;
if (currentFallbackChildFragment !== null) {
fallbackChildFragment = createWorkInProgress(currentFallbackChildFragment, fallbackChildren);
} else {
fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); // Needs a placement effect because the parent (the Suspense boundary) already
// mounted but this is a new fiber.
fallbackChildFragment.flags |= Placement;
}
fallbackChildFragment.return = workInProgress;
primaryChildFragment.return = workInProgress;
primaryChildFragment.sibling = fallbackChildFragment;
workInProgress.child = primaryChildFragment;
return fallbackChildFragment;
}
function retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, recoverableError) {
// Falling back to client rendering. Because this has performance
// implications, it's considered a recoverable error, even though the user
// likely won't observe anything wrong with the UI.
//
// The error is passed in as an argument to enforce that every caller provide
// a custom message, or explicitly opt out (currently the only path that opts
// out is legacy mode; every concurrent path provides an error).
if (recoverableError !== null) {
queueHydrationError(recoverableError);
} // This will add the old fiber to the deletion list
reconcileChildFibers(workInProgress, current.child, null, renderLanes); // We're now not suspended nor dehydrated.
var nextProps = workInProgress.pendingProps;
var primaryChildren = nextProps.children;
var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress, primaryChildren); // Needs a placement effect because the parent (the Suspense boundary) already
// mounted but this is a new fiber.
primaryChildFragment.flags |= Placement;
workInProgress.memoizedState = null;
return primaryChildFragment;
}
function mountSuspenseFallbackAfterRetryWithoutHydrating(current, workInProgress, primaryChildren, fallbackChildren, renderLanes) {
var fiberMode = workInProgress.mode;
var primaryChildProps = {
mode: 'visible',
children: primaryChildren
};
var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, fiberMode);
var fallbackChildFragment = createFiberFromFragment(fallbackChildren, fiberMode, renderLanes, null); // Needs a placement effect because the parent (the Suspense
// boundary) already mounted but this is a new fiber.
fallbackChildFragment.flags |= Placement;
primaryChildFragment.return = workInProgress;
fallbackChildFragment.return = workInProgress;
primaryChildFragment.sibling = fallbackChildFragment;
workInProgress.child = primaryChildFragment;
if ((workInProgress.mode & ConcurrentMode) !== NoMode) {
// We will have dropped the effect list which contains the
// deletion. We need to reconcile to delete the current child.
reconcileChildFibers(workInProgress, current.child, null, renderLanes);
}
return fallbackChildFragment;
}
function mountDehydratedSuspenseComponent(workInProgress, suspenseInstance, renderLanes) {
// During the first pass, we'll bail out and not drill into the children.
// Instead, we'll leave the content in place and try to hydrate it later.
if ((workInProgress.mode & ConcurrentMode) === NoMode) {
{
error('Cannot hydrate Suspense in legacy mode. Switch from ' + 'ReactDOM.hydrate(element, container) to ' + 'ReactDOMClient.hydrateRoot(container, <App />)' + '.render(element) or remove the Suspense components from ' + 'the server rendered components.');
}
workInProgress.lanes = laneToLanes(SyncLane);
} else if (isSuspenseInstanceFallback(suspenseInstance)) {
// This is a client-only boundary. Since we won't get any content from the server
// for this, we need to schedule that at a higher priority based on when it would
// have timed out. In theory we could render it in this pass but it would have the
// wrong priority associated with it and will prevent hydration of parent path.
// Instead, we'll leave work left on it to render it in a separate commit.
// TODO This time should be the time at which the server rendered response that is
// a parent to this boundary was displayed. However, since we currently don't have
// a protocol to transfer that time, we'll just estimate it by using the current
// time. This will mean that Suspense timeouts are slightly shifted to later than
// they should be.
// Schedule a normal pri update to render this content.
workInProgress.lanes = laneToLanes(DefaultHydrationLane);
} else {
// We'll continue hydrating the rest at offscreen priority since we'll already
// be showing the right content coming from the server, it is no rush.
workInProgress.lanes = laneToLanes(OffscreenLane);
}
return null;
}
function updateDehydratedSuspenseComponent(current, workInProgress, didSuspend, nextProps, suspenseInstance, suspenseState, renderLanes) {
if (!didSuspend) {
// This is the first render pass. Attempt to hydrate.
// We should never be hydrating at this point because it is the first pass,
// but after we've already committed once.
warnIfHydrating();
if ((workInProgress.mode & ConcurrentMode) === NoMode) {
return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, // TODO: When we delete legacy mode, we should make this error argument
// required — every concurrent mode path that causes hydration to
// de-opt to client rendering should have an error message.
null);
}
if (isSuspenseInstanceFallback(suspenseInstance)) {
// This boundary is in a permanent fallback state. In this case, we'll never
// get an update and we'll never be able to hydrate the final content. Let's just try the
// client side render instead.
var digest, message, stack;
{
var _getSuspenseInstanceF = getSuspenseInstanceFallbackErrorDetails(suspenseInstance);
digest = _getSuspenseInstanceF.digest;
message = _getSuspenseInstanceF.message;
stack = _getSuspenseInstanceF.stack;
}
var error;
if (message) {
// eslint-disable-next-line react-internal/prod-error-codes
error = new Error(message);
} else {
error = new Error('The server could not finish this Suspense boundary, likely ' + 'due to an error during server rendering. Switched to ' + 'client rendering.');
}
var capturedValue = createCapturedValue(error, digest, stack);
return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, capturedValue);
}
// any context has changed, we need to treat is as if the input might have changed.
var hasContextChanged = includesSomeLane(renderLanes, current.childLanes);
if (didReceiveUpdate || hasContextChanged) {
// This boundary has changed since the first render. This means that we are now unable to
// hydrate it. We might still be able to hydrate it using a higher priority lane.
var root = getWorkInProgressRoot();
if (root !== null) {
var attemptHydrationAtLane = getBumpedLaneForHydration(root, renderLanes);
if (attemptHydrationAtLane !== NoLane && attemptHydrationAtLane !== suspenseState.retryLane) {
// Intentionally mutating since this render will get interrupted. This
// is one of the very rare times where we mutate the current tree
// during the render phase.
suspenseState.retryLane = attemptHydrationAtLane; // TODO: Ideally this would inherit the event time of the current render
var eventTime = NoTimestamp;
enqueueConcurrentRenderForLane(current, attemptHydrationAtLane);
scheduleUpdateOnFiber(root, current, attemptHydrationAtLane, eventTime);
}
} // If we have scheduled higher pri work above, this will probably just abort the render
// since we now have higher priority work, but in case it doesn't, we need to prepare to
// render something, if we time out. Even if that requires us to delete everything and
// skip hydration.
// Delay having to do this as long as the suspense timeout allows us.
renderDidSuspendDelayIfPossible();
var _capturedValue = createCapturedValue(new Error('This Suspense boundary received an update before it finished ' + 'hydrating. This caused the boundary to switch to client rendering. ' + 'The usual way to fix this is to wrap the original update ' + 'in startTransition.'));
return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, _capturedValue);
} else if (isSuspenseInstancePending(suspenseInstance)) {
// This component is still pending more data from the server, so we can't hydrate its
// content. We treat it as if this component suspended itself. It might seem as if
// we could just try to render it client-side instead. However, this will perform a
// lot of unnecessary work and is unlikely to complete since it often will suspend
// on missing data anyway. Additionally, the server might be able to render more
// than we can on the client yet. In that case we'd end up with more fallback states
// on the client than if we just leave it alone. If the server times out or errors
// these should update this boundary to the permanent Fallback state instead.
// Mark it as having captured (i.e. suspended).
workInProgress.flags |= DidCapture; // Leave the child in place. I.e. the dehydrated fragment.
workInProgress.child = current.child; // Register a callback to retry this boundary once the server has sent the result.
var retry = retryDehydratedSuspenseBoundary.bind(null, current);
registerSuspenseInstanceRetry(suspenseInstance, retry);
return null;
} else {
// This is the first attempt.
reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress, suspenseInstance, suspenseState.treeContext);
var primaryChildren = nextProps.children;
var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress, primaryChildren); // Mark the children as hydrating. This is a fast path to know whether this
// tree is part of a hydrating tree. This is used to determine if a child
// node has fully mounted yet, and for scheduling event replaying.
// Conceptually this is similar to Placement in that a new subtree is
// inserted into the React tree here. It just happens to not need DOM
// mutations because it already exists.
primaryChildFragment.flags |= Hydrating;
return primaryChildFragment;
}
} else {
// This is the second render pass. We already attempted to hydrated, but
// something either suspended or errored.
if (workInProgress.flags & ForceClientRender) {
// Something errored during hydration. Try again without hydrating.
workInProgress.flags &= ~ForceClientRender;
var _capturedValue2 = createCapturedValue(new Error('There was an error while hydrating this Suspense boundary. ' + 'Switched to client rendering.'));
return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, _capturedValue2);
} else if (workInProgress.memoizedState !== null) {
// Something suspended and we should still be in dehydrated mode.
// Leave the existing child in place.
workInProgress.child = current.child; // The dehydrated completion pass expects this flag to be there
// but the normal suspense pass doesn't.
workInProgress.flags |= DidCapture;
return null;
} else {
// Suspended but we should no longer be in dehydrated mode.
// Therefore we now have to render the fallback.
var nextPrimaryChildren = nextProps.children;
var nextFallbackChildren = nextProps.fallback;
var fallbackChildFragment = mountSuspenseFallbackAfterRetryWithoutHydrating(current, workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes);
var _primaryChildFragment4 = workInProgress.child;
_primaryChildFragment4.memoizedState = mountSuspenseOffscreenState(renderLanes);
workInProgress.memoizedState = SUSPENDED_MARKER;
return fallbackChildFragment;
}
}
}
function scheduleSuspenseWorkOnFiber(fiber, renderLanes, propagationRoot) {
fiber.lanes = mergeLanes(fiber.lanes, renderLanes);
var alternate = fiber.alternate;
if (alternate !== null) {
alternate.lanes = mergeLanes(alternate.lanes, renderLanes);
}
scheduleContextWorkOnParentPath(fiber.return, renderLanes, propagationRoot);
}
function propagateSuspenseContextChange(workInProgress, firstChild, renderLanes) {
// Mark any Suspense boundaries with fallbacks as having work to do.
// If they were previously forced into fallbacks, they may now be able
// to unblock.
var node = firstChild;
while (node !== null) {
if (node.tag === SuspenseComponent) {
var state = node.memoizedState;
if (state !== null) {
scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress);
}
} else if (node.tag === SuspenseListComponent) {
// If the tail is hidden there might not be an Suspense boundaries
// to schedule work on. In this case we have to schedule it on the
// list itself.
// We don't have to traverse to the children of the list since
// the list will propagate the change when it rerenders.
scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress);
} else if (node.child !== null) {
node.child.return = node;
node = node.child;
continue;
}
if (node === workInProgress) {
return;
}
while (node.sibling === null) {
if (node.return === null || node.return === workInProgress) {
return;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
}
}
function findLastContentRow(firstChild) {
// This is going to find the last row among these children that is already
// showing content on the screen, as opposed to being in fallback state or
// new. If a row has multiple Suspense boundaries, any of them being in the
// fallback state, counts as the whole row being in a fallback state.
// Note that the "rows" will be workInProgress, but any nested children
// will still be current since we haven't rendered them yet. The mounted
// order may not be the same as the new order. We use the new order.
var row = firstChild;
var lastContentRow = null;
while (row !== null) {
var currentRow = row.alternate; // New rows can't be content rows.
if (currentRow !== null && findFirstSuspended(currentRow) === null) {
lastContentRow = row;
}
row = row.sibling;
}
return lastContentRow;
}
function validateRevealOrder(revealOrder) {
{
if (revealOrder !== undefined && revealOrder !== 'forwards' && revealOrder !== 'backwards' && revealOrder !== 'together' && !didWarnAboutRevealOrder[revealOrder]) {
didWarnAboutRevealOrder[revealOrder] = true;
if (typeof revealOrder === 'string') {
switch (revealOrder.toLowerCase()) {
case 'together':
case 'forwards':
case 'backwards':
{
error('"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase());
break;
}
case 'forward':
case 'backward':
{
error('"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'React uses the -s suffix in the spelling. Use "%ss" instead.', revealOrder, revealOrder.toLowerCase());
break;
}
default:
error('"%s" is not a supported revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
break;
}
} else {
error('%s is not a supported value for revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
}
}
}
}
function validateTailOptions(tailMode, revealOrder) {
{
if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) {
if (tailMode !== 'collapsed' && tailMode !== 'hidden') {
didWarnAboutTailOptions[tailMode] = true;
error('"%s" is not a supported value for tail on <SuspenseList />. ' + 'Did you mean "collapsed" or "hidden"?', tailMode);
} else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') {
didWarnAboutTailOptions[tailMode] = true;
error('<SuspenseList tail="%s" /> is only valid if revealOrder is ' + '"forwards" or "backwards". ' + 'Did you mean to specify revealOrder="forwards"?', tailMode);
}
}
}
}
function validateSuspenseListNestedChild(childSlot, index) {
{
var isAnArray = isArray(childSlot);
var isIterable = !isAnArray && typeof getIteratorFn(childSlot) === 'function';
if (isAnArray || isIterable) {
var type = isAnArray ? 'array' : 'iterable';
error('A nested %s was passed to row #%s in <SuspenseList />. Wrap it in ' + 'an additional SuspenseList to configure its revealOrder: ' + '<SuspenseList revealOrder=...> ... ' + '<SuspenseList revealOrder=...>{%s}</SuspenseList> ... ' + '</SuspenseList>', type, index, type);
return false;
}
}
return true;
}
function validateSuspenseListChildren(children, revealOrder) {
{
if ((revealOrder === 'forwards' || revealOrder === 'backwards') && children !== undefined && children !== null && children !== false) {
if (isArray(children)) {
for (var i = 0; i < children.length; i++) {
if (!validateSuspenseListNestedChild(children[i], i)) {
return;
}
}
} else {
var iteratorFn = getIteratorFn(children);
if (typeof iteratorFn === 'function') {
var childrenIterator = iteratorFn.call(children);
if (childrenIterator) {
var step = childrenIterator.next();
var _i = 0;
for (; !step.done; step = childrenIterator.next()) {
if (!validateSuspenseListNestedChild(step.value, _i)) {
return;
}
_i++;
}
}
} else {
error('A single row was passed to a <SuspenseList revealOrder="%s" />. ' + 'This is not useful since it needs multiple rows. ' + 'Did you mean to pass multiple children or an array?', revealOrder);
}
}
}
}
}
function initSuspenseListRenderState(workInProgress, isBackwards, tail, lastContentRow, tailMode) {
var renderState = workInProgress.memoizedState;
if (renderState === null) {
workInProgress.memoizedState = {
isBackwards: isBackwards,
rendering: null,
renderingStartTime: 0,
last: lastContentRow,
tail: tail,
tailMode: tailMode
};
} else {
// We can reuse the existing object from previous renders.
renderState.isBackwards = isBackwards;
renderState.rendering = null;
renderState.renderingStartTime = 0;
renderState.last = lastContentRow;
renderState.tail = tail;
renderState.tailMode = tailMode;
}
} // This can end up rendering this component multiple passes.
// The first pass splits the children fibers into two sets. A head and tail.
// We first render the head. If anything is in fallback state, we do another
// pass through beginWork to rerender all children (including the tail) with
// the force suspend context. If the first render didn't have anything in
// in fallback state. Then we render each row in the tail one-by-one.
// That happens in the completeWork phase without going back to beginWork.
function updateSuspenseListComponent(current, workInProgress, renderLanes) {
var nextProps = workInProgress.pendingProps;
var revealOrder = nextProps.revealOrder;
var tailMode = nextProps.tail;
var newChildren = nextProps.children;
validateRevealOrder(revealOrder);
validateTailOptions(tailMode, revealOrder);
validateSuspenseListChildren(newChildren, revealOrder);
reconcileChildren(current, workInProgress, newChildren, renderLanes);
var suspenseContext = suspenseStackCursor.current;
var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback);
if (shouldForceFallback) {
suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
workInProgress.flags |= DidCapture;
} else {
var didSuspendBefore = current !== null && (current.flags & DidCapture) !== NoFlags;
if (didSuspendBefore) {
// If we previously forced a fallback, we need to schedule work
// on any nested boundaries to let them know to try to render
// again. This is the same as context updating.
propagateSuspenseContextChange(workInProgress, workInProgress.child, renderLanes);
}
suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
}
pushSuspenseContext(workInProgress, suspenseContext);
if ((workInProgress.mode & ConcurrentMode) === NoMode) {
// In legacy mode, SuspenseList doesn't work so we just
// use make it a noop by treating it as the default revealOrder.
workInProgress.memoizedState = null;
} else {
switch (revealOrder) {
case 'forwards':
{
var lastContentRow = findLastContentRow(workInProgress.child);
var tail;
if (lastContentRow === null) {
// The whole list is part of the tail.
// TODO: We could fast path by just rendering the tail now.
tail = workInProgress.child;
workInProgress.child = null;
} else {
// Disconnect the tail rows after the content row.
// We're going to render them separately later.
tail = lastContentRow.sibling;
lastContentRow.sibling = null;
}
initSuspenseListRenderState(workInProgress, false, // isBackwards
tail, lastContentRow, tailMode);
break;
}
case 'backwards':
{
// We're going to find the first row that has existing content.
// At the same time we're going to reverse the list of everything
// we pass in the meantime. That's going to be our tail in reverse
// order.
var _tail = null;
var row = workInProgress.child;
workInProgress.child = null;
while (row !== null) {
var currentRow = row.alternate; // New rows can't be content rows.
if (currentRow !== null && findFirstSuspended(currentRow) === null) {
// This is the beginning of the main content.
workInProgress.child = row;
break;
}
var nextRow = row.sibling;
row.sibling = _tail;
_tail = row;
row = nextRow;
} // TODO: If workInProgress.child is null, we can continue on the tail immediately.
initSuspenseListRenderState(workInProgress, true, // isBackwards
_tail, null, // last
tailMode);
break;
}
case 'together':
{
initSuspenseListRenderState(workInProgress, false, // isBackwards
null, // tail
null, // last
undefined);
break;
}
default:
{
// The default reveal order is the same as not having
// a boundary.
workInProgress.memoizedState = null;
}
}
}
return workInProgress.child;
}
function updatePortalComponent(current, workInProgress, renderLanes) {
pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
var nextChildren = workInProgress.pendingProps;
if (current === null) {
// Portals are special because we don't append the children during mount
// but at commit. Therefore we need to track insertions which the normal
// flow doesn't do during mount. This doesn't happen at the root because
// the root always starts with a "current" with a null child.
// TODO: Consider unifying this with how the root works.
workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes);
} else {
reconcileChildren(current, workInProgress, nextChildren, renderLanes);
}
return workInProgress.child;
}
var hasWarnedAboutUsingNoValuePropOnContextProvider = false;
function updateContextProvider(current, workInProgress, renderLanes) {
var providerType = workInProgress.type;
var context = providerType._context;
var newProps = workInProgress.pendingProps;
var oldProps = workInProgress.memoizedProps;
var newValue = newProps.value;
{
if (!('value' in newProps)) {
if (!hasWarnedAboutUsingNoValuePropOnContextProvider) {
hasWarnedAboutUsingNoValuePropOnContextProvider = true;
error('The `value` prop is required for the `<Context.Provider>`. Did you misspell it or forget to pass it?');
}
}
var providerPropTypes = workInProgress.type.propTypes;
if (providerPropTypes) {
checkPropTypes(providerPropTypes, newProps, 'prop', 'Context.Provider');
}
}
pushProvider(workInProgress, context, newValue);
{
if (oldProps !== null) {
var oldValue = oldProps.value;
if (objectIs(oldValue, newValue)) {
// No change. Bailout early if children are the same.
if (oldProps.children === newProps.children && !hasContextChanged()) {
return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
}
} else {
// The context value changed. Search for matching consumers and schedule
// them to update.
propagateContextChange(workInProgress, context, renderLanes);
}
}
}
var newChildren = newProps.children;
reconcileChildren(current, workInProgress, newChildren, renderLanes);
return workInProgress.child;
}
var hasWarnedAboutUsingContextAsConsumer = false;
function updateContextConsumer(current, workInProgress, renderLanes) {
var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In
// DEV mode, we create a separate object for Context.Consumer that acts
// like a proxy to Context. This proxy object adds unnecessary code in PROD
// so we use the old behaviour (Context.Consumer references Context) to
// reduce size and overhead. The separate object references context via
// a property called "_context", which also gives us the ability to check
// in DEV mode if this property exists or not and warn if it does not.
{
if (context._context === undefined) {
// This may be because it's a Context (rather than a Consumer).
// Or it may be because it's older React where they're the same thing.
// We only want to warn if we're sure it's a new React.
if (context !== context.Consumer) {
if (!hasWarnedAboutUsingContextAsConsumer) {
hasWarnedAboutUsingContextAsConsumer = true;
error('Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
}
}
} else {
context = context._context;
}
}
var newProps = workInProgress.pendingProps;
var render = newProps.children;
{
if (typeof render !== 'function') {
error('A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.');
}
}
prepareToReadContext(workInProgress, renderLanes);
var newValue = readContext(context);
{
markComponentRenderStarted(workInProgress);
}
var newChildren;
{
ReactCurrentOwner$1.current = workInProgress;
setIsRendering(true);
newChildren = render(newValue);
setIsRendering(false);
}
{
markComponentRenderStopped();
} // React DevTools reads this flag.
workInProgress.flags |= PerformedWork;
reconcileChildren(current, workInProgress, newChildren, renderLanes);
return workInProgress.child;
}
function markWorkInProgressReceivedUpdate() {
didReceiveUpdate = true;
}
function resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress) {
if ((workInProgress.mode & ConcurrentMode) === NoMode) {
if (current !== null) {
// A lazy component only mounts if it suspended inside a non-
// concurrent tree, in an inconsistent state. We want to treat it like
// a new mount, even though an empty version of it already committed.
// Disconnect the alternate pointers.
current.alternate = null;
workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
workInProgress.flags |= Placement;
}
}
}
function bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes) {
if (current !== null) {
// Reuse previous dependencies
workInProgress.dependencies = current.dependencies;
}
{
// Don't update "base" render times for bailouts.
stopProfilerTimerIfRunning();
}
markSkippedUpdateLanes(workInProgress.lanes); // Check if the children have any pending work.
if (!includesSomeLane(renderLanes, workInProgress.childLanes)) {
// The children don't have any work either. We can skip them.
// TODO: Once we add back resuming, we should check if the children are
// a work-in-progress set. If so, we need to transfer their effects.
{
return null;
}
} // This fiber doesn't have work, but its subtree does. Clone the child
// fibers and continue.
cloneChildFibers(current, workInProgress);
return workInProgress.child;
}
function remountFiber(current, oldWorkInProgress, newWorkInProgress) {
{
var returnFiber = oldWorkInProgress.return;
if (returnFiber === null) {
// eslint-disable-next-line react-internal/prod-error-codes
throw new Error('Cannot swap the root fiber.');
} // Disconnect from the old current.
// It will get deleted.
current.alternate = null;
oldWorkInProgress.alternate = null; // Connect to the new tree.
newWorkInProgress.index = oldWorkInProgress.index;
newWorkInProgress.sibling = oldWorkInProgress.sibling;
newWorkInProgress.return = oldWorkInProgress.return;
newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it.
if (oldWorkInProgress === returnFiber.child) {
returnFiber.child = newWorkInProgress;
} else {
var prevSibling = returnFiber.child;
if (prevSibling === null) {
// eslint-disable-next-line react-internal/prod-error-codes
throw new Error('Expected parent to have a child.');
}
while (prevSibling.sibling !== oldWorkInProgress) {
prevSibling = prevSibling.sibling;
if (prevSibling === null) {
// eslint-disable-next-line react-internal/prod-error-codes
throw new Error('Expected to find the previous sibling.');
}
}
prevSibling.sibling = newWorkInProgress;
} // Delete the old fiber and place the new one.
// Since the old fiber is disconnected, we have to schedule it manually.
var deletions = returnFiber.deletions;
if (deletions === null) {
returnFiber.deletions = [current];
returnFiber.flags |= ChildDeletion;
} else {
deletions.push(current);
}
newWorkInProgress.flags |= Placement; // Restart work from the new fiber.
return newWorkInProgress;
}
}
function checkScheduledUpdateOrContext(current, renderLanes) {
// Before performing an early bailout, we must check if there are pending
// updates or context.
var updateLanes = current.lanes;
if (includesSomeLane(updateLanes, renderLanes)) {
return true;
} // No pending update, but because context is propagated lazily, we need
return false;
}
function attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress, renderLanes) {
// This fiber does not have any pending work. Bailout without entering
// the begin phase. There's still some bookkeeping we that needs to be done
// in this optimized path, mostly pushing stuff onto the stack.
switch (workInProgress.tag) {
case HostRoot:
pushHostRootContext(workInProgress);
var root = workInProgress.stateNode;
resetHydrationState();
break;
case HostComponent:
pushHostContext(workInProgress);
break;
case ClassComponent:
{
var Component = workInProgress.type;
if (isContextProvider(Component)) {
pushContextProvider(workInProgress);
}
break;
}
case HostPortal:
pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
break;
case ContextProvider:
{
var newValue = workInProgress.memoizedProps.value;
var context = workInProgress.type._context;
pushProvider(workInProgress, context, newValue);
break;
}
case Profiler:
{
// Profiler should only call onRender when one of its descendants actually rendered.
var hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes);
if (hasChildWork) {
workInProgress.flags |= Update;
}
{
// Reset effect durations for the next eventual effect phase.
// These are reset during render to allow the DevTools commit hook a chance to read them,
var stateNode = workInProgress.stateNode;
stateNode.effectDuration = 0;
stateNode.passiveEffectDuration = 0;
}
}
break;
case SuspenseComponent:
{
var state = workInProgress.memoizedState;
if (state !== null) {
if (state.dehydrated !== null) {
pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // We know that this component will suspend again because if it has
// been unsuspended it has committed as a resolved Suspense component.
// If it needs to be retried, it should have work scheduled on it.
workInProgress.flags |= DidCapture; // We should never render the children of a dehydrated boundary until we
// upgrade it. We return null instead of bailoutOnAlreadyFinishedWork.
return null;
} // If this boundary is currently timed out, we need to decide
// whether to retry the primary children, or to skip over it and
// go straight to the fallback. Check the priority of the primary
// child fragment.
var primaryChildFragment = workInProgress.child;
var primaryChildLanes = primaryChildFragment.childLanes;
if (includesSomeLane(renderLanes, primaryChildLanes)) {
// The primary children have pending work. Use the normal path
// to attempt to render the primary children again.
return updateSuspenseComponent(current, workInProgress, renderLanes);
} else {
// The primary child fragment does not have pending work marked
// on it
pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // The primary children do not have pending work with sufficient
// priority. Bailout.
var child = bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
if (child !== null) {
// The fallback children have pending work. Skip over the
// primary children and work on the fallback.
return child.sibling;
} else {
// Note: We can return `null` here because we already checked
// whether there were nested context consumers, via the call to
// `bailoutOnAlreadyFinishedWork` above.
return null;
}
}
} else {
pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current));
}
break;
}
case SuspenseListComponent:
{
var didSuspendBefore = (current.flags & DidCapture) !== NoFlags;
var _hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes);
if (didSuspendBefore) {
if (_hasChildWork) {
// If something was in fallback state last time, and we have all the
// same children then we're still in progressive loading state.
// Something might get unblocked by state updates or retries in the
// tree which will affect the tail. So we need to use the normal
// path to compute the correct tail.
return updateSuspenseListComponent(current, workInProgress, renderLanes);
} // If none of the children had any work, that means that none of
// them got retried so they'll still be blocked in the same way
// as before. We can fast bail out.
workInProgress.flags |= DidCapture;
} // If nothing suspended before and we're rendering the same children,
// then the tail doesn't matter. Anything new that suspends will work
// in the "together" mode, so we can continue from the state we had.
var renderState = workInProgress.memoizedState;
if (renderState !== null) {
// Reset to the "together" mode in case we've started a different
// update in the past but didn't complete it.
renderState.rendering = null;
renderState.tail = null;
renderState.lastEffect = null;
}
pushSuspenseContext(workInProgress, suspenseStackCursor.current);
if (_hasChildWork) {
break;
} else {
// If none of the children had any work, that means that none of
// them got retried so they'll still be blocked in the same way
// as before. We can fast bail out.
return null;
}
}
case OffscreenComponent:
case LegacyHiddenComponent:
{
// Need to check if the tree still needs to be deferred. This is
// almost identical to the logic used in the normal update path,
// so we'll just enter that. The only difference is we'll bail out
// at the next level instead of this one, because the child props
// have not changed. Which is fine.
// TODO: Probably should refactor `beginWork` to split the bailout
// path from the normal path. I'm tempted to do a labeled break here
// but I won't :)
workInProgress.lanes = NoLanes;
return updateOffscreenComponent(current, workInProgress, renderLanes);
}
}
return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
}
function beginWork(current, workInProgress, renderLanes) {
{
if (workInProgress._debugNeedsRemount && current !== null) {
// This will restart the begin phase with a new fiber.
return remountFiber(current, workInProgress, createFiberFromTypeAndProps(workInProgress.type, workInProgress.key, workInProgress.pendingProps, workInProgress._debugOwner || null, workInProgress.mode, workInProgress.lanes));
}
}
if (current !== null) {
var oldProps = current.memoizedProps;
var newProps = workInProgress.pendingProps;
if (oldProps !== newProps || hasContextChanged() || ( // Force a re-render if the implementation changed due to hot reload:
workInProgress.type !== current.type )) {
// If props or context changed, mark the fiber as having performed work.
// This may be unset if the props are determined to be equal later (memo).
didReceiveUpdate = true;
} else {
// Neither props nor legacy context changes. Check if there's a pending
// update or context change.
var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current, renderLanes);
if (!hasScheduledUpdateOrContext && // If this is the second pass of an error or suspense boundary, there
// may not be work scheduled on `current`, so we check for this flag.
(workInProgress.flags & DidCapture) === NoFlags) {
// No pending updates or context. Bail out now.
didReceiveUpdate = false;
return attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress, renderLanes);
}
if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) {
// This is a special case that only exists for legacy mode.
// See https://github.com/facebook/react/pull/19216.
didReceiveUpdate = true;
} else {
// An update was scheduled on this fiber, but there are no new props
// nor legacy context. Set this to false. If an update queue or context
// consumer produces a changed value, it will set this to true. Otherwise,
// the component will assume the children have not changed and bail out.
didReceiveUpdate = false;
}
}
} else {
didReceiveUpdate = false;
if (getIsHydrating() && isForkedChild(workInProgress)) {
// Check if this child belongs to a list of muliple children in
// its parent.
//
// In a true multi-threaded implementation, we would render children on
// parallel threads. This would represent the beginning of a new render
// thread for this subtree.
//
// We only use this for id generation during hydration, which is why the
// logic is located in this special branch.
var slotIndex = workInProgress.index;
var numberOfForks = getForksAtLevel();
pushTreeId(workInProgress, numberOfForks, slotIndex);
}
} // Before entering the begin phase, clear pending update priority.
// TODO: This assumes that we're about to evaluate the component and process
// the update queue. However, there's an exception: SimpleMemoComponent
// sometimes bails out later in the begin phase. This indicates that we should
// move this assignment out of the common path and into each branch.
workInProgress.lanes = NoLanes;
switch (workInProgress.tag) {
case IndeterminateComponent:
{
return mountIndeterminateComponent(current, workInProgress, workInProgress.type, renderLanes);
}
case LazyComponent:
{
var elementType = workInProgress.elementType;
return mountLazyComponent(current, workInProgress, elementType, renderLanes);
}
case FunctionComponent:
{
var Component = workInProgress.type;
var unresolvedProps = workInProgress.pendingProps;
var resolvedProps = workInProgress.elementType === Component ? unresolvedProps : resolveDefaultProps(Component, unresolvedProps);
return updateFunctionComponent(current, workInProgress, Component, resolvedProps, renderLanes);
}
case ClassComponent:
{
var _Component = workInProgress.type;
var _unresolvedProps = workInProgress.pendingProps;
var _resolvedProps = workInProgress.elementType === _Component ? _unresolvedProps : resolveDefaultProps(_Component, _unresolvedProps);
return updateClassComponent(current, workInProgress, _Component, _resolvedProps, renderLanes);
}
case HostRoot:
return updateHostRoot(current, workInProgress, renderLanes);
case HostComponent:
return updateHostComponent(current, workInProgress, renderLanes);
case HostText:
return updateHostText(current, workInProgress);
case SuspenseComponent:
return updateSuspenseComponent(current, workInProgress, renderLanes);
case HostPortal:
return updatePortalComponent(current, workInProgress, renderLanes);
case ForwardRef:
{
var type = workInProgress.type;
var _unresolvedProps2 = workInProgress.pendingProps;
var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);
return updateForwardRef(current, workInProgress, type, _resolvedProps2, renderLanes);
}
case Fragment:
return updateFragment(current, workInProgress, renderLanes);
case Mode:
return updateMode(current, workInProgress, renderLanes);
case Profiler:
return updateProfiler(current, workInProgress, renderLanes);
case ContextProvider:
return updateContextProvider(current, workInProgress, renderLanes);
case ContextConsumer:
return updateContextConsumer(current, workInProgress, renderLanes);
case MemoComponent:
{
var _type2 = workInProgress.type;
var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props.
var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);
{
if (workInProgress.type !== workInProgress.elementType) {
var outerPropTypes = _type2.propTypes;
if (outerPropTypes) {
checkPropTypes(outerPropTypes, _resolvedProps3, // Resolved for outer only
'prop', getComponentNameFromType(_type2));
}
}
}
_resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
return updateMemoComponent(current, workInProgress, _type2, _resolvedProps3, renderLanes);
}
case SimpleMemoComponent:
{
return updateSimpleMemoComponent(current, workInProgress, workInProgress.type, workInProgress.pendingProps, renderLanes);
}
case IncompleteClassComponent:
{
var _Component2 = workInProgress.type;
var _unresolvedProps4 = workInProgress.pendingProps;
var _resolvedProps4 = workInProgress.elementType === _Component2 ? _unresolvedProps4 : resolveDefaultProps(_Component2, _unresolvedProps4);
return mountIncompleteClassComponent(current, workInProgress, _Component2, _resolvedProps4, renderLanes);
}
case SuspenseListComponent:
{
return updateSuspenseListComponent(current, workInProgress, renderLanes);
}
case ScopeComponent:
{
break;
}
case OffscreenComponent:
{
return updateOffscreenComponent(current, workInProgress, renderLanes);
}
}
throw new Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in " + 'React. Please file an issue.');
}
function markUpdate(workInProgress) {
// Tag the fiber with an update effect. This turns a Placement into
// a PlacementAndUpdate.
workInProgress.flags |= Update;
}
function markRef$1(workInProgress) {
workInProgress.flags |= Ref;
{
workInProgress.flags |= RefStatic;
}
}
var appendAllChildren;
var updateHostContainer;
var updateHostComponent$1;
var updateHostText$1;
{
// Mutation mode
appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
// We only have the top Fiber that was created but we need recurse down its
// children to find all the terminal nodes.
var node = workInProgress.child;
while (node !== null) {
if (node.tag === HostComponent || node.tag === HostText) {
appendInitialChild(parent, node.stateNode);
} else if (node.tag === HostPortal) ; else if (node.child !== null) {
node.child.return = node;
node = node.child;
continue;
}
if (node === workInProgress) {
return;
}
while (node.sibling === null) {
if (node.return === null || node.return === workInProgress) {
return;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
}
};
updateHostContainer = function (current, workInProgress) {// Noop
};
updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
// If we have an alternate, that means this is an update and we need to
// schedule a side-effect to do the updates.
var oldProps = current.memoizedProps;
if (oldProps === newProps) {
// In mutation mode, this is sufficient for a bailout because
// we won't touch this node even if children changed.
return;
} // If we get updated because one of our children updated, we don't
// have newProps so we'll have to reuse them.
// TODO: Split the update API as separate for the props vs. children.
// Even better would be if children weren't special cased at all tho.
var instance = workInProgress.stateNode;
var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host
// component is hitting the resume path. Figure out why. Possibly
// related to `hidden`.
var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); // TODO: Type this specific to this type of component.
workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there
// is a new ref we mark this as an update. All the work is done in commitWork.
if (updatePayload) {
markUpdate(workInProgress);
}
};
updateHostText$1 = function (current, workInProgress, oldText, newText) {
// If the text differs, mark it as an update. All the work in done in commitWork.
if (oldText !== newText) {
markUpdate(workInProgress);
}
};
}
function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
if (getIsHydrating()) {
// If we're hydrating, we should consume as many items as we can
// so we don't leave any behind.
return;
}
switch (renderState.tailMode) {
case 'hidden':
{
// Any insertions at the end of the tail list after this point
// should be invisible. If there are already mounted boundaries
// anything before them are not considered for collapsing.
// Therefore we need to go through the whole tail to find if
// there are any.
var tailNode = renderState.tail;
var lastTailNode = null;
while (tailNode !== null) {
if (tailNode.alternate !== null) {
lastTailNode = tailNode;
}
tailNode = tailNode.sibling;
} // Next we're simply going to delete all insertions after the
// last rendered item.
if (lastTailNode === null) {
// All remaining items in the tail are insertions.
renderState.tail = null;
} else {
// Detach the insertion after the last node that was already
// inserted.
lastTailNode.sibling = null;
}
break;
}
case 'collapsed':
{
// Any insertions at the end of the tail list after this point
// should be invisible. If there are already mounted boundaries
// anything before them are not considered for collapsing.
// Therefore we need to go through the whole tail to find if
// there are any.
var _tailNode = renderState.tail;
var _lastTailNode = null;
while (_tailNode !== null) {
if (_tailNode.alternate !== null) {
_lastTailNode = _tailNode;
}
_tailNode = _tailNode.sibling;
} // Next we're simply going to delete all insertions after the
// last rendered item.
if (_lastTailNode === null) {
// All remaining items in the tail are insertions.
if (!hasRenderedATailFallback && renderState.tail !== null) {
// We suspended during the head. We want to show at least one
// row at the tail. So we'll keep on and cut off the rest.
renderState.tail.sibling = null;
} else {
renderState.tail = null;
}
} else {
// Detach the insertion after the last node that was already
// inserted.
_lastTailNode.sibling = null;
}
break;
}
}
}
function bubbleProperties(completedWork) {
var didBailout = completedWork.alternate !== null && completedWork.alternate.child === completedWork.child;
var newChildLanes = NoLanes;
var subtreeFlags = NoFlags;
if (!didBailout) {
// Bubble up the earliest expiration time.
if ( (completedWork.mode & ProfileMode) !== NoMode) {
// In profiling mode, resetChildExpirationTime is also used to reset
// profiler durations.
var actualDuration = completedWork.actualDuration;
var treeBaseDuration = completedWork.selfBaseDuration;
var child = completedWork.child;
while (child !== null) {
newChildLanes = mergeLanes(newChildLanes, mergeLanes(child.lanes, child.childLanes));
subtreeFlags |= child.subtreeFlags;
subtreeFlags |= child.flags; // When a fiber is cloned, its actualDuration is reset to 0. This value will
// only be updated if work is done on the fiber (i.e. it doesn't bailout).
// When work is done, it should bubble to the parent's actualDuration. If
// the fiber has not been cloned though, (meaning no work was done), then
// this value will reflect the amount of time spent working on a previous
// render. In that case it should not bubble. We determine whether it was
// cloned by comparing the child pointer.
actualDuration += child.actualDuration;
treeBaseDuration += child.treeBaseDuration;
child = child.sibling;
}
completedWork.actualDuration = actualDuration;
completedWork.treeBaseDuration = treeBaseDuration;
} else {
var _child = completedWork.child;
while (_child !== null) {
newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child.lanes, _child.childLanes));
subtreeFlags |= _child.subtreeFlags;
subtreeFlags |= _child.flags; // Update the return pointer so the tree is consistent. This is a code
// smell because it assumes the commit phase is never concurrent with
// the render phase. Will address during refactor to alternate model.
_child.return = completedWork;
_child = _child.sibling;
}
}
completedWork.subtreeFlags |= subtreeFlags;
} else {
// Bubble up the earliest expiration time.
if ( (completedWork.mode & ProfileMode) !== NoMode) {
// In profiling mode, resetChildExpirationTime is also used to reset
// profiler durations.
var _treeBaseDuration = completedWork.selfBaseDuration;
var _child2 = completedWork.child;
while (_child2 !== null) {
newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child2.lanes, _child2.childLanes)); // "Static" flags share the lifetime of the fiber/hook they belong to,
// so we should bubble those up even during a bailout. All the other
// flags have a lifetime only of a single render + commit, so we should
// ignore them.
subtreeFlags |= _child2.subtreeFlags & StaticMask;
subtreeFlags |= _child2.flags & StaticMask;
_treeBaseDuration += _child2.treeBaseDuration;
_child2 = _child2.sibling;
}
completedWork.treeBaseDuration = _treeBaseDuration;
} else {
var _child3 = completedWork.child;
while (_child3 !== null) {
newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child3.lanes, _child3.childLanes)); // "Static" flags share the lifetime of the fiber/hook they belong to,
// so we should bubble those up even during a bailout. All the other
// flags have a lifetime only of a single render + commit, so we should
// ignore them.
subtreeFlags |= _child3.subtreeFlags & StaticMask;
subtreeFlags |= _child3.flags & StaticMask; // Update the return pointer so the tree is consistent. This is a code
// smell because it assumes the commit phase is never concurrent with
// the render phase. Will address during refactor to alternate model.
_child3.return = completedWork;
_child3 = _child3.sibling;
}
}
completedWork.subtreeFlags |= subtreeFlags;
}
completedWork.childLanes = newChildLanes;
return didBailout;
}
function completeDehydratedSuspenseBoundary(current, workInProgress, nextState) {
if (hasUnhydratedTailNodes() && (workInProgress.mode & ConcurrentMode) !== NoMode && (workInProgress.flags & DidCapture) === NoFlags) {
warnIfUnhydratedTailNodes(workInProgress);
resetHydrationState();
workInProgress.flags |= ForceClientRender | Incomplete | ShouldCapture;
return false;
}
var wasHydrated = popHydrationState(workInProgress);
if (nextState !== null && nextState.dehydrated !== null) {
// We might be inside a hydration state the first time we're picking up this
// Suspense boundary, and also after we've reentered it for further hydration.
if (current === null) {
if (!wasHydrated) {
throw new Error('A dehydrated suspense component was completed without a hydrated node. ' + 'This is probably a bug in React.');
}
prepareToHydrateHostSuspenseInstance(workInProgress);
bubbleProperties(workInProgress);
{
if ((workInProgress.mode & ProfileMode) !== NoMode) {
var isTimedOutSuspense = nextState !== null;
if (isTimedOutSuspense) {
// Don't count time spent in a timed out Suspense subtree as part of the base duration.
var primaryChildFragment = workInProgress.child;
if (primaryChildFragment !== null) {
// $FlowFixMe Flow doesn't support type casting in combination with the -= operator
workInProgress.treeBaseDuration -= primaryChildFragment.treeBaseDuration;
}
}
}
}
return false;
} else {
// We might have reentered this boundary to hydrate it. If so, we need to reset the hydration
// state since we're now exiting out of it. popHydrationState doesn't do that for us.
resetHydrationState();
if ((workInProgress.flags & DidCapture) === NoFlags) {
// This boundary did not suspend so it's now hydrated and unsuspended.
workInProgress.memoizedState = null;
} // If nothing suspended, we need to schedule an effect to mark this boundary
// as having hydrated so events know that they're free to be invoked.
// It's also a signal to replay events and the suspense callback.
// If something suspended, schedule an effect to attach retry listeners.
// So we might as well always mark this.
workInProgress.flags |= Update;
bubbleProperties(workInProgress);
{
if ((workInProgress.mode & ProfileMode) !== NoMode) {
var _isTimedOutSuspense = nextState !== null;
if (_isTimedOutSuspense) {
// Don't count time spent in a timed out Suspense subtree as part of the base duration.
var _primaryChildFragment = workInProgress.child;
if (_primaryChildFragment !== null) {
// $FlowFixMe Flow doesn't support type casting in combination with the -= operator
workInProgress.treeBaseDuration -= _primaryChildFragment.treeBaseDuration;
}
}
}
}
return false;
}
} else {
// Successfully completed this tree. If this was a forced client render,
// there may have been recoverable errors during first hydration
// attempt. If so, add them to a queue so we can log them in the
// commit phase.
upgradeHydrationErrorsToRecoverable(); // Fall through to normal Suspense path
return true;
}
}
function completeWork(current, workInProgress, renderLanes) {
var newProps = workInProgress.pendingProps; // Note: This intentionally doesn't check if we're hydrating because comparing
// to the current tree provider fiber is just as fast and less error-prone.
// Ideally we would have a special version of the work loop only
// for hydration.
popTreeContext(workInProgress);
switch (workInProgress.tag) {
case IndeterminateComponent:
case LazyComponent:
case SimpleMemoComponent:
case FunctionComponent:
case ForwardRef:
case Fragment:
case Mode:
case Profiler:
case ContextConsumer:
case MemoComponent:
bubbleProperties(workInProgress);
return null;
case ClassComponent:
{
var Component = workInProgress.type;
if (isContextProvider(Component)) {
popContext(workInProgress);
}
bubbleProperties(workInProgress);
return null;
}
case HostRoot:
{
var fiberRoot = workInProgress.stateNode;
popHostContainer(workInProgress);
popTopLevelContextObject(workInProgress);
resetWorkInProgressVersions();
if (fiberRoot.pendingContext) {
fiberRoot.context = fiberRoot.pendingContext;
fiberRoot.pendingContext = null;
}
if (current === null || current.child === null) {
// If we hydrated, pop so that we can delete any remaining children
// that weren't hydrated.
var wasHydrated = popHydrationState(workInProgress);
if (wasHydrated) {
// If we hydrated, then we'll need to schedule an update for
// the commit side-effects on the root.
markUpdate(workInProgress);
} else {
if (current !== null) {
var prevState = current.memoizedState;
if ( // Check if this is a client root
!prevState.isDehydrated || // Check if we reverted to client rendering (e.g. due to an error)
(workInProgress.flags & ForceClientRender) !== NoFlags) {
// Schedule an effect to clear this container at the start of the
// next commit. This handles the case of React rendering into a
// container with previous children. It's also safe to do for
// updates too, because current.child would only be null if the
// previous render was null (so the container would already
// be empty).
workInProgress.flags |= Snapshot; // If this was a forced client render, there may have been
// recoverable errors during first hydration attempt. If so, add
// them to a queue so we can log them in the commit phase.
upgradeHydrationErrorsToRecoverable();
}
}
}
}
updateHostContainer(current, workInProgress);
bubbleProperties(workInProgress);
return null;
}
case HostComponent:
{
popHostContext(workInProgress);
var rootContainerInstance = getRootHostContainer();
var type = workInProgress.type;
if (current !== null && workInProgress.stateNode != null) {
updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);
if (current.ref !== workInProgress.ref) {
markRef$1(workInProgress);
}
} else {
if (!newProps) {
if (workInProgress.stateNode === null) {
throw new Error('We must have new props for new mounts. This error is likely ' + 'caused by a bug in React. Please file an issue.');
} // This can happen when we abort work.
bubbleProperties(workInProgress);
return null;
}
var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context
// "stack" as the parent. Then append children as we go in beginWork
// or completeWork depending on whether we want to add them top->down or
// bottom->up. Top->down is faster in IE11.
var _wasHydrated = popHydrationState(workInProgress);
if (_wasHydrated) {
// TODO: Move this and createInstance step into the beginPhase
// to consolidate.
if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) {
// If changes to the hydrated node need to be applied at the
// commit-phase we mark this as such.
markUpdate(workInProgress);
}
} else {
var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress);
appendAllChildren(instance, workInProgress, false, false);
workInProgress.stateNode = instance; // Certain renderers require commit-time effects for initial mount.
// (eg DOM renderer supports auto-focus for certain elements).
// Make sure such renderers get scheduled for later work.
if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance)) {
markUpdate(workInProgress);
}
}
if (workInProgress.ref !== null) {
// If there is a ref on a host node we need to schedule a callback
markRef$1(workInProgress);
}
}
bubbleProperties(workInProgress);
return null;
}
case HostText:
{
var newText = newProps;
if (current && workInProgress.stateNode != null) {
var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need
// to schedule a side-effect to do the updates.
updateHostText$1(current, workInProgress, oldText, newText);
} else {
if (typeof newText !== 'string') {
if (workInProgress.stateNode === null) {
throw new Error('We must have new props for new mounts. This error is likely ' + 'caused by a bug in React. Please file an issue.');
} // This can happen when we abort work.
}
var _rootContainerInstance = getRootHostContainer();
var _currentHostContext = getHostContext();
var _wasHydrated2 = popHydrationState(workInProgress);
if (_wasHydrated2) {
if (prepareToHydrateHostTextInstance(workInProgress)) {
markUpdate(workInProgress);
}
} else {
workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress);
}
}
bubbleProperties(workInProgress);
return null;
}
case SuspenseComponent:
{
popSuspenseContext(workInProgress);
var nextState = workInProgress.memoizedState; // Special path for dehydrated boundaries. We may eventually move this
// to its own fiber type so that we can add other kinds of hydration
// boundaries that aren't associated with a Suspense tree. In anticipation
// of such a refactor, all the hydration logic is contained in
// this branch.
if (current === null || current.memoizedState !== null && current.memoizedState.dehydrated !== null) {
var fallthroughToNormalSuspensePath = completeDehydratedSuspenseBoundary(current, workInProgress, nextState);
if (!fallthroughToNormalSuspensePath) {
if (workInProgress.flags & ShouldCapture) {
// Special case. There were remaining unhydrated nodes. We treat
// this as a mismatch. Revert to client rendering.
return workInProgress;
} else {
// Did not finish hydrating, either because this is the initial
// render or because something suspended.
return null;
}
} // Continue with the normal Suspense path.
}
if ((workInProgress.flags & DidCapture) !== NoFlags) {
// Something suspended. Re-render with the fallback children.
workInProgress.lanes = renderLanes; // Do not reset the effect list.
if ( (workInProgress.mode & ProfileMode) !== NoMode) {
transferActualDuration(workInProgress);
} // Don't bubble properties in this case.
return workInProgress;
}
var nextDidTimeout = nextState !== null;
var prevDidTimeout = current !== null && current.memoizedState !== null;
// a passive effect, which is when we process the transitions
if (nextDidTimeout !== prevDidTimeout) {
// an effect to toggle the subtree's visibility. When we switch from
// fallback -> primary, the inner Offscreen fiber schedules this effect
// as part of its normal complete phase. But when we switch from
// primary -> fallback, the inner Offscreen fiber does not have a complete
// phase. So we need to schedule its effect here.
//
// We also use this flag to connect/disconnect the effects, but the same
// logic applies: when re-connecting, the Offscreen fiber's complete
// phase will handle scheduling the effect. It's only when the fallback
// is active that we have to do anything special.
if (nextDidTimeout) {
var _offscreenFiber2 = workInProgress.child;
_offscreenFiber2.flags |= Visibility; // TODO: This will still suspend a synchronous tree if anything
// in the concurrent tree already suspended during this render.
// This is a known bug.
if ((workInProgress.mode & ConcurrentMode) !== NoMode) {
// TODO: Move this back to throwException because this is too late
// if this is a large tree which is common for initial loads. We
// don't know if we should restart a render or not until we get
// this marker, and this is too late.
// If this render already had a ping or lower pri updates,
// and this is the first time we know we're going to suspend we
// should be able to immediately restart from within throwException.
var hasInvisibleChildContext = current === null && (workInProgress.memoizedProps.unstable_avoidThisFallback !== true || !enableSuspenseAvoidThisFallback);
if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) {
// If this was in an invisible tree or a new render, then showing
// this boundary is ok.
renderDidSuspend();
} else {
// Otherwise, we're going to have to hide content so we should
// suspend for longer if possible.
renderDidSuspendDelayIfPossible();
}
}
}
}
var wakeables = workInProgress.updateQueue;
if (wakeables !== null) {
// Schedule an effect to attach a retry listener to the promise.
// TODO: Move to passive phase
workInProgress.flags |= Update;
}
bubbleProperties(workInProgress);
{
if ((workInProgress.mode & ProfileMode) !== NoMode) {
if (nextDidTimeout) {
// Don't count time spent in a timed out Suspense subtree as part of the base duration.
var primaryChildFragment = workInProgress.child;
if (primaryChildFragment !== null) {
// $FlowFixMe Flow doesn't support type casting in combination with the -= operator
workInProgress.treeBaseDuration -= primaryChildFragment.treeBaseDuration;
}
}
}
}
return null;
}
case HostPortal:
popHostContainer(workInProgress);
updateHostContainer(current, workInProgress);
if (current === null) {
preparePortalMount(workInProgress.stateNode.containerInfo);
}
bubbleProperties(workInProgress);
return null;
case ContextProvider:
// Pop provider fiber
var context = workInProgress.type._context;
popProvider(context, workInProgress);
bubbleProperties(workInProgress);
return null;
case IncompleteClassComponent:
{
// Same as class component case. I put it down here so that the tags are
// sequential to ensure this switch is compiled to a jump table.
var _Component = workInProgress.type;
if (isContextProvider(_Component)) {
popContext(workInProgress);
}
bubbleProperties(workInProgress);
return null;
}
case SuspenseListComponent:
{
popSuspenseContext(workInProgress);
var renderState = workInProgress.memoizedState;
if (renderState === null) {
// We're running in the default, "independent" mode.
// We don't do anything in this mode.
bubbleProperties(workInProgress);
return null;
}
var didSuspendAlready = (workInProgress.flags & DidCapture) !== NoFlags;
var renderedTail = renderState.rendering;
if (renderedTail === null) {
// We just rendered the head.
if (!didSuspendAlready) {
// This is the first pass. We need to figure out if anything is still
// suspended in the rendered set.
// If new content unsuspended, but there's still some content that
// didn't. Then we need to do a second pass that forces everything
// to keep showing their fallbacks.
// We might be suspended if something in this render pass suspended, or
// something in the previous committed pass suspended. Otherwise,
// there's no chance so we can skip the expensive call to
// findFirstSuspended.
var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.flags & DidCapture) === NoFlags);
if (!cannotBeSuspended) {
var row = workInProgress.child;
while (row !== null) {
var suspended = findFirstSuspended(row);
if (suspended !== null) {
didSuspendAlready = true;
workInProgress.flags |= DidCapture;
cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as
// part of the second pass. In that case nothing will subscribe to
// its thenables. Instead, we'll transfer its thenables to the
// SuspenseList so that it can retry if they resolve.
// There might be multiple of these in the list but since we're
// going to wait for all of them anyway, it doesn't really matter
// which ones gets to ping. In theory we could get clever and keep
// track of how many dependencies remain but it gets tricky because
// in the meantime, we can add/remove/change items and dependencies.
// We might bail out of the loop before finding any but that
// doesn't matter since that means that the other boundaries that
// we did find already has their listeners attached.
var newThenables = suspended.updateQueue;
if (newThenables !== null) {
workInProgress.updateQueue = newThenables;
workInProgress.flags |= Update;
} // Rerender the whole list, but this time, we'll force fallbacks
// to stay in place.
// Reset the effect flags before doing the second pass since that's now invalid.
// Reset the child fibers to their original state.
workInProgress.subtreeFlags = NoFlags;
resetChildFibers(workInProgress, renderLanes); // Set up the Suspense Context to force suspense and immediately
// rerender the children.
pushSuspenseContext(workInProgress, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback)); // Don't bubble properties in this case.
return workInProgress.child;
}
row = row.sibling;
}
}
if (renderState.tail !== null && now() > getRenderTargetTime()) {
// We have already passed our CPU deadline but we still have rows
// left in the tail. We'll just give up further attempts to render
// the main content and only render fallbacks.
workInProgress.flags |= DidCapture;
didSuspendAlready = true;
cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this
// to get it started back up to attempt the next item. While in terms
// of priority this work has the same priority as this current render,
// it's not part of the same transition once the transition has
// committed. If it's sync, we still want to yield so that it can be
// painted. Conceptually, this is really the same as pinging.
// We can use any RetryLane even if it's the one currently rendering
// since we're leaving it behind on this node.
workInProgress.lanes = SomeRetryLane;
}
} else {
cutOffTailIfNeeded(renderState, false);
} // Next we're going to render the tail.
} else {
// Append the rendered row to the child list.
if (!didSuspendAlready) {
var _suspended = findFirstSuspended(renderedTail);
if (_suspended !== null) {
workInProgress.flags |= DidCapture;
didSuspendAlready = true; // Ensure we transfer the update queue to the parent so that it doesn't
// get lost if this row ends up dropped during a second pass.
var _newThenables = _suspended.updateQueue;
if (_newThenables !== null) {
workInProgress.updateQueue = _newThenables;
workInProgress.flags |= Update;
}
cutOffTailIfNeeded(renderState, true); // This might have been modified.
if (renderState.tail === null && renderState.tailMode === 'hidden' && !renderedTail.alternate && !getIsHydrating() // We don't cut it if we're hydrating.
) {
// We're done.
bubbleProperties(workInProgress);
return null;
}
} else if ( // The time it took to render last row is greater than the remaining
// time we have to render. So rendering one more row would likely
// exceed it.
now() * 2 - renderState.renderingStartTime > getRenderTargetTime() && renderLanes !== OffscreenLane) {
// We have now passed our CPU deadline and we'll just give up further
// attempts to render the main content and only render fallbacks.
// The assumption is that this is usually faster.
workInProgress.flags |= DidCapture;
didSuspendAlready = true;
cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this
// to get it started back up to attempt the next item. While in terms
// of priority this work has the same priority as this current render,
// it's not part of the same transition once the transition has
// committed. If it's sync, we still want to yield so that it can be
// painted. Conceptually, this is really the same as pinging.
// We can use any RetryLane even if it's the one currently rendering
// since we're leaving it behind on this node.
workInProgress.lanes = SomeRetryLane;
}
}
if (renderState.isBackwards) {
// The effect list of the backwards tail will have been added
// to the end. This breaks the guarantee that life-cycles fire in
// sibling order but that isn't a strong guarantee promised by React.
// Especially since these might also just pop in during future commits.
// Append to the beginning of the list.
renderedTail.sibling = workInProgress.child;
workInProgress.child = renderedTail;
} else {
var previousSibling = renderState.last;
if (previousSibling !== null) {
previousSibling.sibling = renderedTail;
} else {
workInProgress.child = renderedTail;
}
renderState.last = renderedTail;
}
}
if (renderState.tail !== null) {
// We still have tail rows to render.
// Pop a row.
var next = renderState.tail;
renderState.rendering = next;
renderState.tail = next.sibling;
renderState.renderingStartTime = now();
next.sibling = null; // Restore the context.
// TODO: We can probably just avoid popping it instead and only
// setting it the first time we go from not suspended to suspended.
var suspenseContext = suspenseStackCursor.current;
if (didSuspendAlready) {
suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
} else {
suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
}
pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row.
// Don't bubble properties in this case.
return next;
}
bubbleProperties(workInProgress);
return null;
}
case ScopeComponent:
{
break;
}
case OffscreenComponent:
case LegacyHiddenComponent:
{
popRenderLanes(workInProgress);
var _nextState = workInProgress.memoizedState;
var nextIsHidden = _nextState !== null;
if (current !== null) {
var _prevState = current.memoizedState;
var prevIsHidden = _prevState !== null;
if (prevIsHidden !== nextIsHidden && ( // LegacyHidden doesn't do any hiding — it only pre-renders.
!enableLegacyHidden )) {
workInProgress.flags |= Visibility;
}
}
if (!nextIsHidden || (workInProgress.mode & ConcurrentMode) === NoMode) {
bubbleProperties(workInProgress);
} else {
// Don't bubble properties for hidden children unless we're rendering
// at offscreen priority.
if (includesSomeLane(subtreeRenderLanes, OffscreenLane)) {
bubbleProperties(workInProgress);
{
// Check if there was an insertion or update in the hidden subtree.
// If so, we need to hide those nodes in the commit phase, so
// schedule a visibility effect.
if ( workInProgress.subtreeFlags & (Placement | Update)) {
workInProgress.flags |= Visibility;
}
}
}
}
return null;
}
case CacheComponent:
{
return null;
}
case TracingMarkerComponent:
{
return null;
}
}
throw new Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in " + 'React. Please file an issue.');
}
function unwindWork(current, workInProgress, renderLanes) {
// Note: This intentionally doesn't check if we're hydrating because comparing
// to the current tree provider fiber is just as fast and less error-prone.
// Ideally we would have a special version of the work loop only
// for hydration.
popTreeContext(workInProgress);
switch (workInProgress.tag) {
case ClassComponent:
{
var Component = workInProgress.type;
if (isContextProvider(Component)) {
popContext(workInProgress);
}
var flags = workInProgress.flags;
if (flags & ShouldCapture) {
workInProgress.flags = flags & ~ShouldCapture | DidCapture;
if ( (workInProgress.mode & ProfileMode) !== NoMode) {
transferActualDuration(workInProgress);
}
return workInProgress;
}
return null;
}
case HostRoot:
{
var root = workInProgress.stateNode;
popHostContainer(workInProgress);
popTopLevelContextObject(workInProgress);
resetWorkInProgressVersions();
var _flags = workInProgress.flags;
if ((_flags & ShouldCapture) !== NoFlags && (_flags & DidCapture) === NoFlags) {
// There was an error during render that wasn't captured by a suspense
// boundary. Do a second pass on the root to unmount the children.
workInProgress.flags = _flags & ~ShouldCapture | DidCapture;
return workInProgress;
} // We unwound to the root without completing it. Exit.
return null;
}
case HostComponent:
{
// TODO: popHydrationState
popHostContext(workInProgress);
return null;
}
case SuspenseComponent:
{
popSuspenseContext(workInProgress);
var suspenseState = workInProgress.memoizedState;
if (suspenseState !== null && suspenseState.dehydrated !== null) {
if (workInProgress.alternate === null) {
throw new Error('Threw in newly mounted dehydrated component. This is likely a bug in ' + 'React. Please file an issue.');
}
resetHydrationState();
}
var _flags2 = workInProgress.flags;
if (_flags2 & ShouldCapture) {
workInProgress.flags = _flags2 & ~ShouldCapture | DidCapture; // Captured a suspense effect. Re-render the boundary.
if ( (workInProgress.mode & ProfileMode) !== NoMode) {
transferActualDuration(workInProgress);
}
return workInProgress;
}
return null;
}
case SuspenseListComponent:
{
popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been
// caught by a nested boundary. If not, it should bubble through.
return null;
}
case HostPortal:
popHostContainer(workInProgress);
return null;
case ContextProvider:
var context = workInProgress.type._context;
popProvider(context, workInProgress);
return null;
case OffscreenComponent:
case LegacyHiddenComponent:
popRenderLanes(workInProgress);
return null;
case CacheComponent:
return null;
default:
return null;
}
}
function unwindInterruptedWork(current, interruptedWork, renderLanes) {
// Note: This intentionally doesn't check if we're hydrating because comparing
// to the current tree provider fiber is just as fast and less error-prone.
// Ideally we would have a special version of the work loop only
// for hydration.
popTreeContext(interruptedWork);
switch (interruptedWork.tag) {
case ClassComponent:
{
var childContextTypes = interruptedWork.type.childContextTypes;
if (childContextTypes !== null && childContextTypes !== undefined) {
popContext(interruptedWork);
}
break;
}
case HostRoot:
{
var root = interruptedWork.stateNode;
popHostContainer(interruptedWork);
popTopLevelContextObject(interruptedWork);
resetWorkInProgressVersions();
break;
}
case HostComponent:
{
popHostContext(interruptedWork);
break;
}
case HostPortal:
popHostContainer(interruptedWork);
break;
case SuspenseComponent:
popSuspenseContext(interruptedWork);
break;
case SuspenseListComponent:
popSuspenseContext(interruptedWork);
break;
case ContextProvider:
var context = interruptedWork.type._context;
popProvider(context, interruptedWork);
break;
case OffscreenComponent:
case LegacyHiddenComponent:
popRenderLanes(interruptedWork);
break;
}
}
var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
{
didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
} // Used during the commit phase to track the state of the Offscreen component stack.
// Allows us to avoid traversing the return path to find the nearest Offscreen ancestor.
// Only used when enableSuspenseLayoutEffectSemantics is enabled.
var offscreenSubtreeIsHidden = false;
var offscreenSubtreeWasHidden = false;
var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;
var nextEffect = null; // Used for Profiling builds to track updaters.
var inProgressLanes = null;
var inProgressRoot = null;
function reportUncaughtErrorInDEV(error) {
// Wrapping each small part of the commit phase into a guarded
// callback is a bit too slow (https://github.com/facebook/react/pull/21666).
// But we rely on it to surface errors to DEV tools like overlays
// (https://github.com/facebook/react/issues/21712).
// As a compromise, rethrow only caught errors in a guard.
{
invokeGuardedCallback(null, function () {
throw error;
});
clearCaughtError();
}
}
var callComponentWillUnmountWithTimer = function (current, instance) {
instance.props = current.memoizedProps;
instance.state = current.memoizedState;
if ( current.mode & ProfileMode) {
try {
startLayoutEffectTimer();
instance.componentWillUnmount();
} finally {
recordLayoutEffectDuration(current);
}
} else {
instance.componentWillUnmount();
}
}; // Capture errors so they don't interrupt mounting.
function safelyCallCommitHookLayoutEffectListMount(current, nearestMountedAncestor) {
try {
commitHookEffectListMount(Layout, current);
} catch (error) {
captureCommitPhaseError(current, nearestMountedAncestor, error);
}
} // Capture errors so they don't interrupt unmounting.
function safelyCallComponentWillUnmount(current, nearestMountedAncestor, instance) {
try {
callComponentWillUnmountWithTimer(current, instance);
} catch (error) {
captureCommitPhaseError(current, nearestMountedAncestor, error);
}
} // Capture errors so they don't interrupt mounting.
function safelyCallComponentDidMount(current, nearestMountedAncestor, instance) {
try {
instance.componentDidMount();
} catch (error) {
captureCommitPhaseError(current, nearestMountedAncestor, error);
}
} // Capture errors so they don't interrupt mounting.
function safelyAttachRef(current, nearestMountedAncestor) {
try {
commitAttachRef(current);
} catch (error) {
captureCommitPhaseError(current, nearestMountedAncestor, error);
}
}
function safelyDetachRef(current, nearestMountedAncestor) {
var ref = current.ref;
if (ref !== null) {
if (typeof ref === 'function') {
var retVal;
try {
if (enableProfilerTimer && enableProfilerCommitHooks && current.mode & ProfileMode) {
try {
startLayoutEffectTimer();
retVal = ref(null);
} finally {
recordLayoutEffectDuration(current);
}
} else {
retVal = ref(null);
}
} catch (error) {
captureCommitPhaseError(current, nearestMountedAncestor, error);
}
{
if (typeof retVal === 'function') {
error('Unexpected return value from a callback ref in %s. ' + 'A callback ref should not return a function.', getComponentNameFromFiber(current));
}
}
} else {
ref.current = null;
}
}
}
function safelyCallDestroy(current, nearestMountedAncestor, destroy) {
try {
destroy();
} catch (error) {
captureCommitPhaseError(current, nearestMountedAncestor, error);
}
}
var focusedInstanceHandle = null;
var shouldFireAfterActiveInstanceBlur = false;
function commitBeforeMutationEffects(root, firstChild) {
focusedInstanceHandle = prepareForCommit(root.containerInfo);
nextEffect = firstChild;
commitBeforeMutationEffects_begin(); // We no longer need to track the active instance fiber
var shouldFire = shouldFireAfterActiveInstanceBlur;
shouldFireAfterActiveInstanceBlur = false;
focusedInstanceHandle = null;
return shouldFire;
}
function commitBeforeMutationEffects_begin() {
while (nextEffect !== null) {
var fiber = nextEffect; // This phase is only used for beforeActiveInstanceBlur.
var child = fiber.child;
if ((fiber.subtreeFlags & BeforeMutationMask) !== NoFlags && child !== null) {
child.return = fiber;
nextEffect = child;
} else {
commitBeforeMutationEffects_complete();
}
}
}
function commitBeforeMutationEffects_complete() {
while (nextEffect !== null) {
var fiber = nextEffect;
setCurrentFiber(fiber);
try {
commitBeforeMutationEffectsOnFiber(fiber);
} catch (error) {
captureCommitPhaseError(fiber, fiber.return, error);
}
resetCurrentFiber();
var sibling = fiber.sibling;
if (sibling !== null) {
sibling.return = fiber.return;
nextEffect = sibling;
return;
}
nextEffect = fiber.return;
}
}
function commitBeforeMutationEffectsOnFiber(finishedWork) {
var current = finishedWork.alternate;
var flags = finishedWork.flags;
if ((flags & Snapshot) !== NoFlags) {
setCurrentFiber(finishedWork);
switch (finishedWork.tag) {
case FunctionComponent:
case ForwardRef:
case SimpleMemoComponent:
{
break;
}
case ClassComponent:
{
if (current !== null) {
var prevProps = current.memoizedProps;
var prevState = current.memoizedState;
var instance = finishedWork.stateNode; // We could update instance props and state here,
// but instead we rely on them being set during last render.
// TODO: revisit this when we implement resuming.
{
if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
if (instance.props !== finishedWork.memoizedProps) {
error('Expected %s props to match memoized props before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
}
if (instance.state !== finishedWork.memoizedState) {
error('Expected %s state to match memoized state before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
}
}
}
var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);
{
var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;
if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
didWarnSet.add(finishedWork.type);
error('%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentNameFromFiber(finishedWork));
}
}
instance.__reactInternalSnapshotBeforeUpdate = snapshot;
}
break;
}
case HostRoot:
{
{
var root = finishedWork.stateNode;
clearContainer(root.containerInfo);
}
break;
}
case HostComponent:
case HostText:
case HostPortal:
case IncompleteClassComponent:
// Nothing to do for these component types
break;
default:
{
throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.');
}
}
resetCurrentFiber();
}
}
function commitHookEffectListUnmount(flags, finishedWork, nearestMountedAncestor) {
var updateQueue = finishedWork.updateQueue;
var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
if (lastEffect !== null) {
var firstEffect = lastEffect.next;
var effect = firstEffect;
do {
if ((effect.tag & flags) === flags) {
// Unmount
var destroy = effect.destroy;
effect.destroy = undefined;
if (destroy !== undefined) {
{
if ((flags & Passive$1) !== NoFlags$1) {
markComponentPassiveEffectUnmountStarted(finishedWork);
} else if ((flags & Layout) !== NoFlags$1) {
markComponentLayoutEffectUnmountStarted(finishedWork);
}
}
{
if ((flags & Insertion) !== NoFlags$1) {
setIsRunningInsertionEffect(true);
}
}
safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy);
{
if ((flags & Insertion) !== NoFlags$1) {
setIsRunningInsertionEffect(false);
}
}
{
if ((flags & Passive$1) !== NoFlags$1) {
markComponentPassiveEffectUnmountStopped();
} else if ((flags & Layout) !== NoFlags$1) {
markComponentLayoutEffectUnmountStopped();
}
}
}
}
effect = effect.next;
} while (effect !== firstEffect);
}
}
function commitHookEffectListMount(flags, finishedWork) {
var updateQueue = finishedWork.updateQueue;
var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
if (lastEffect !== null) {
var firstEffect = lastEffect.next;
var effect = firstEffect;
do {
if ((effect.tag & flags) === flags) {
{
if ((flags & Passive$1) !== NoFlags$1) {
markComponentPassiveEffectMountStarted(finishedWork);
} else if ((flags & Layout) !== NoFlags$1) {
markComponentLayoutEffectMountStarted(finishedWork);
}
} // Mount
var create = effect.create;
{
if ((flags & Insertion) !== NoFlags$1) {
setIsRunningInsertionEffect(true);
}
}
effect.destroy = create();
{
if ((flags & Insertion) !== NoFlags$1) {
setIsRunningInsertionEffect(false);
}
}
{
if ((flags & Passive$1) !== NoFlags$1) {
markComponentPassiveEffectMountStopped();
} else if ((flags & Layout) !== NoFlags$1) {
markComponentLayoutEffectMountStopped();
}
}
{
var destroy = effect.destroy;
if (destroy !== undefined && typeof destroy !== 'function') {
var hookName = void 0;
if ((effect.tag & Layout) !== NoFlags) {
hookName = 'useLayoutEffect';
} else if ((effect.tag & Insertion) !== NoFlags) {
hookName = 'useInsertionEffect';
} else {
hookName = 'useEffect';
}
var addendum = void 0;
if (destroy === null) {
addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';
} else if (typeof destroy.then === 'function') {
addendum = '\n\nIt looks like you wrote ' + hookName + '(async () => ...) or returned a Promise. ' + 'Instead, write the async function inside your effect ' + 'and call it immediately:\n\n' + hookName + '(() => {\n' + ' async function fetchData() {\n' + ' // You can await here\n' + ' const response = await MyAPI.getData(someId);\n' + ' // ...\n' + ' }\n' + ' fetchData();\n' + "}, [someId]); // Or [] if effect doesn't need props or state\n\n" + 'Learn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching';
} else {
addendum = ' You returned: ' + destroy;
}
error('%s must not return anything besides a function, ' + 'which is used for clean-up.%s', hookName, addendum);
}
}
}
effect = effect.next;
} while (effect !== firstEffect);
}
}
function commitPassiveEffectDurations(finishedRoot, finishedWork) {
{
// Only Profilers with work in their subtree will have an Update effect scheduled.
if ((finishedWork.flags & Update) !== NoFlags) {
switch (finishedWork.tag) {
case Profiler:
{
var passiveEffectDuration = finishedWork.stateNode.passiveEffectDuration;
var _finishedWork$memoize = finishedWork.memoizedProps,
id = _finishedWork$memoize.id,
onPostCommit = _finishedWork$memoize.onPostCommit; // This value will still reflect the previous commit phase.
// It does not get reset until the start of the next commit phase.
var commitTime = getCommitTime();
var phase = finishedWork.alternate === null ? 'mount' : 'update';
{
if (isCurrentUpdateNested()) {
phase = 'nested-update';
}
}
if (typeof onPostCommit === 'function') {
onPostCommit(id, phase, passiveEffectDuration, commitTime);
} // Bubble times to the next nearest ancestor Profiler.
// After we process that Profiler, we'll bubble further up.
var parentFiber = finishedWork.return;
outer: while (parentFiber !== null) {
switch (parentFiber.tag) {
case HostRoot:
var root = parentFiber.stateNode;
root.passiveEffectDuration += passiveEffectDuration;
break outer;
case Profiler:
var parentStateNode = parentFiber.stateNode;
parentStateNode.passiveEffectDuration += passiveEffectDuration;
break outer;
}
parentFiber = parentFiber.return;
}
break;
}
}
}
}
}
function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork, committedLanes) {
if ((finishedWork.flags & LayoutMask) !== NoFlags) {
switch (finishedWork.tag) {
case FunctionComponent:
case ForwardRef:
case SimpleMemoComponent:
{
if ( !offscreenSubtreeWasHidden) {
// At this point layout effects have already been destroyed (during mutation phase).
// This is done to prevent sibling component effects from interfering with each other,
// e.g. a destroy function in one component should never override a ref set
// by a create function in another component during the same commit.
if ( finishedWork.mode & ProfileMode) {
try {
startLayoutEffectTimer();
commitHookEffectListMount(Layout | HasEffect, finishedWork);
} finally {
recordLayoutEffectDuration(finishedWork);
}
} else {
commitHookEffectListMount(Layout | HasEffect, finishedWork);
}
}
break;
}
case ClassComponent:
{
var instance = finishedWork.stateNode;
if (finishedWork.flags & Update) {
if (!offscreenSubtreeWasHidden) {
if (current === null) {
// We could update instance props and state here,
// but instead we rely on them being set during last render.
// TODO: revisit this when we implement resuming.
{
if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
if (instance.props !== finishedWork.memoizedProps) {
error('Expected %s props to match memoized props before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
}
if (instance.state !== finishedWork.memoizedState) {
error('Expected %s state to match memoized state before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
}
}
}
if ( finishedWork.mode & ProfileMode) {
try {
startLayoutEffectTimer();
instance.componentDidMount();
} finally {
recordLayoutEffectDuration(finishedWork);
}
} else {
instance.componentDidMount();
}
} else {
var prevProps = finishedWork.elementType === finishedWork.type ? current.memoizedProps : resolveDefaultProps(finishedWork.type, current.memoizedProps);
var prevState = current.memoizedState; // We could update instance props and state here,
// but instead we rely on them being set during last render.
// TODO: revisit this when we implement resuming.
{
if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
if (instance.props !== finishedWork.memoizedProps) {
error('Expected %s props to match memoized props before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
}
if (instance.state !== finishedWork.memoizedState) {
error('Expected %s state to match memoized state before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
}
}
}
if ( finishedWork.mode & ProfileMode) {
try {
startLayoutEffectTimer();
instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
} finally {
recordLayoutEffectDuration(finishedWork);
}
} else {
instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
}
}
}
} // TODO: I think this is now always non-null by the time it reaches the
// commit phase. Consider removing the type check.
var updateQueue = finishedWork.updateQueue;
if (updateQueue !== null) {
{
if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
if (instance.props !== finishedWork.memoizedProps) {
error('Expected %s props to match memoized props before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
}
if (instance.state !== finishedWork.memoizedState) {
error('Expected %s state to match memoized state before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
}
}
} // We could update instance props and state here,
// but instead we rely on them being set during last render.
// TODO: revisit this when we implement resuming.
commitUpdateQueue(finishedWork, updateQueue, instance);
}
break;
}
case HostRoot:
{
// TODO: I think this is now always non-null by the time it reaches the
// commit phase. Consider removing the type check.
var _updateQueue = finishedWork.updateQueue;
if (_updateQueue !== null) {
var _instance = null;
if (finishedWork.child !== null) {
switch (finishedWork.child.tag) {
case HostComponent:
_instance = getPublicInstance(finishedWork.child.stateNode);
break;
case ClassComponent:
_instance = finishedWork.child.stateNode;
break;
}
}
commitUpdateQueue(finishedWork, _updateQueue, _instance);
}
break;
}
case HostComponent:
{
var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted
// (eg DOM renderer may schedule auto-focus for inputs and form controls).
// These effects should only be committed when components are first mounted,
// aka when there is no current/alternate.
if (current === null && finishedWork.flags & Update) {
var type = finishedWork.type;
var props = finishedWork.memoizedProps;
commitMount(_instance2, type, props);
}
break;
}
case HostText:
{
// We have no life-cycles associated with text.
break;
}
case HostPortal:
{
// We have no life-cycles associated with portals.
break;
}
case Profiler:
{
{
var _finishedWork$memoize2 = finishedWork.memoizedProps,
onCommit = _finishedWork$memoize2.onCommit,
onRender = _finishedWork$memoize2.onRender;
var effectDuration = finishedWork.stateNode.effectDuration;
var commitTime = getCommitTime();
var phase = current === null ? 'mount' : 'update';
{
if (isCurrentUpdateNested()) {
phase = 'nested-update';
}
}
if (typeof onRender === 'function') {
onRender(finishedWork.memoizedProps.id, phase, finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, commitTime);
}
{
if (typeof onCommit === 'function') {
onCommit(finishedWork.memoizedProps.id, phase, effectDuration, commitTime);
} // Schedule a passive effect for this Profiler to call onPostCommit hooks.
// This effect should be scheduled even if there is no onPostCommit callback for this Profiler,
// because the effect is also where times bubble to parent Profilers.
enqueuePendingPassiveProfilerEffect(finishedWork); // Propagate layout effect durations to the next nearest Profiler ancestor.
// Do not reset these values until the next render so DevTools has a chance to read them first.
var parentFiber = finishedWork.return;
outer: while (parentFiber !== null) {
switch (parentFiber.tag) {
case HostRoot:
var root = parentFiber.stateNode;
root.effectDuration += effectDuration;
break outer;
case Profiler:
var parentStateNode = parentFiber.stateNode;
parentStateNode.effectDuration += effectDuration;
break outer;
}
parentFiber = parentFiber.return;
}
}
}
break;
}
case SuspenseComponent:
{
commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
break;
}
case SuspenseListComponent:
case IncompleteClassComponent:
case ScopeComponent:
case OffscreenComponent:
case LegacyHiddenComponent:
case TracingMarkerComponent:
{
break;
}
default:
throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.');
}
}
if ( !offscreenSubtreeWasHidden) {
{
if (finishedWork.flags & Ref) {
commitAttachRef(finishedWork);
}
}
}
}
function reappearLayoutEffectsOnFiber(node) {
// Turn on layout effects in a tree that previously disappeared.
// TODO (Offscreen) Check: flags & LayoutStatic
switch (node.tag) {
case FunctionComponent:
case ForwardRef:
case SimpleMemoComponent:
{
if ( node.mode & ProfileMode) {
try {
startLayoutEffectTimer();
safelyCallCommitHookLayoutEffectListMount(node, node.return);
} finally {
recordLayoutEffectDuration(node);
}
} else {
safelyCallCommitHookLayoutEffectListMount(node, node.return);
}
break;
}
case ClassComponent:
{
var instance = node.stateNode;
if (typeof instance.componentDidMount === 'function') {
safelyCallComponentDidMount(node, node.return, instance);
}
safelyAttachRef(node, node.return);
break;
}
case HostComponent:
{
safelyAttachRef(node, node.return);
break;
}
}
}
function hideOrUnhideAllChildren(finishedWork, isHidden) {
// Only hide or unhide the top-most host nodes.
var hostSubtreeRoot = null;
{
// We only have the top Fiber that was inserted but we need to recurse down its
// children to find all the terminal nodes.
var node = finishedWork;
while (true) {
if (node.tag === HostComponent) {
if (hostSubtreeRoot === null) {
hostSubtreeRoot = node;
try {
var instance = node.stateNode;
if (isHidden) {
hideInstance(instance);
} else {
unhideInstance(node.stateNode, node.memoizedProps);
}
} catch (error) {
captureCommitPhaseError(finishedWork, finishedWork.return, error);
}
}
} else if (node.tag === HostText) {
if (hostSubtreeRoot === null) {
try {
var _instance3 = node.stateNode;
if (isHidden) {
hideTextInstance(_instance3);
} else {
unhideTextInstance(_instance3, node.memoizedProps);
}
} catch (error) {
captureCommitPhaseError(finishedWork, finishedWork.return, error);
}
}
} else if ((node.tag === OffscreenComponent || node.tag === LegacyHiddenComponent) && node.memoizedState !== null && node !== finishedWork) ; else if (node.child !== null) {
node.child.return = node;
node = node.child;
continue;
}
if (node === finishedWork) {
return;
}
while (node.sibling === null) {
if (node.return === null || node.return === finishedWork) {
return;
}
if (hostSubtreeRoot === node) {
hostSubtreeRoot = null;
}
node = node.return;
}
if (hostSubtreeRoot === node) {
hostSubtreeRoot = null;
}
node.sibling.return = node.return;
node = node.sibling;
}
}
}
function commitAttachRef(finishedWork) {
var ref = finishedWork.ref;
if (ref !== null) {
var instance = finishedWork.stateNode;
var instanceToUse;
switch (finishedWork.tag) {
case HostComponent:
instanceToUse = getPublicInstance(instance);
break;
default:
instanceToUse = instance;
} // Moved outside to ensure DCE works with this flag
if (typeof ref === 'function') {
var retVal;
if ( finishedWork.mode & ProfileMode) {
try {
startLayoutEffectTimer();
retVal = ref(instanceToUse);
} finally {
recordLayoutEffectDuration(finishedWork);
}
} else {
retVal = ref(instanceToUse);
}
{
if (typeof retVal === 'function') {
error('Unexpected return value from a callback ref in %s. ' + 'A callback ref should not return a function.', getComponentNameFromFiber(finishedWork));
}
}
} else {
{
if (!ref.hasOwnProperty('current')) {
error('Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().', getComponentNameFromFiber(finishedWork));
}
}
ref.current = instanceToUse;
}
}
}
function detachFiberMutation(fiber) {
// Cut off the return pointer to disconnect it from the tree.
// This enables us to detect and warn against state updates on an unmounted component.
// It also prevents events from bubbling from within disconnected components.
//
// Ideally, we should also clear the child pointer of the parent alternate to let this
// get GC:ed but we don't know which for sure which parent is the current
// one so we'll settle for GC:ing the subtree of this child.
// This child itself will be GC:ed when the parent updates the next time.
//
// Note that we can't clear child or sibling pointers yet.
// They're needed for passive effects and for findDOMNode.
// We defer those fields, and all other cleanup, to the passive phase (see detachFiberAfterEffects).
//
// Don't reset the alternate yet, either. We need that so we can detach the
// alternate's fields in the passive phase. Clearing the return pointer is
// sufficient for findDOMNode semantics.
var alternate = fiber.alternate;
if (alternate !== null) {
alternate.return = null;
}
fiber.return = null;
}
function detachFiberAfterEffects(fiber) {
var alternate = fiber.alternate;
if (alternate !== null) {
fiber.alternate = null;
detachFiberAfterEffects(alternate);
} // Note: Defensively using negation instead of < in case
// `deletedTreeCleanUpLevel` is undefined.
{
// Clear cyclical Fiber fields. This level alone is designed to roughly
// approximate the planned Fiber refactor. In that world, `setState` will be
// bound to a special "instance" object instead of a Fiber. The Instance
// object will not have any of these fields. It will only be connected to
// the fiber tree via a single link at the root. So if this level alone is
// sufficient to fix memory issues, that bodes well for our plans.
fiber.child = null;
fiber.deletions = null;
fiber.sibling = null; // The `stateNode` is cyclical because on host nodes it points to the host
// tree, which has its own pointers to children, parents, and siblings.
// The other host nodes also point back to fibers, so we should detach that
// one, too.
if (fiber.tag === HostComponent) {
var hostInstance = fiber.stateNode;
if (hostInstance !== null) {
detachDeletedInstance(hostInstance);
}
}
fiber.stateNode = null; // I'm intentionally not clearing the `return` field in this level. We
// already disconnect the `return` pointer at the root of the deleted
// subtree (in `detachFiberMutation`). Besides, `return` by itself is not
// cyclical — it's only cyclical when combined with `child`, `sibling`, and
// `alternate`. But we'll clear it in the next level anyway, just in case.
{
fiber._debugOwner = null;
}
{
// Theoretically, nothing in here should be necessary, because we already
// disconnected the fiber from the tree. So even if something leaks this
// particular fiber, it won't leak anything else
//
// The purpose of this branch is to be super aggressive so we can measure
// if there's any difference in memory impact. If there is, that could
// indicate a React leak we don't know about.
fiber.return = null;
fiber.dependencies = null;
fiber.memoizedProps = null;
fiber.memoizedState = null;
fiber.pendingProps = null;
fiber.stateNode = null; // TODO: Move to `commitPassiveUnmountInsideDeletedTreeOnFiber` instead.
fiber.updateQueue = null;
}
}
}
function getHostParentFiber(fiber) {
var parent = fiber.return;
while (parent !== null) {
if (isHostParent(parent)) {
return parent;
}
parent = parent.return;
}
throw new Error('Expected to find a host parent. This error is likely caused by a bug ' + 'in React. Please file an issue.');
}
function isHostParent(fiber) {
return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
}
function getHostSibling(fiber) {
// We're going to search forward into the tree until we find a sibling host
// node. Unfortunately, if multiple insertions are done in a row we have to
// search past them. This leads to exponential search for the next sibling.
// TODO: Find a more efficient way to do this.
var node = fiber;
siblings: while (true) {
// If we didn't find anything, let's try the next sibling.
while (node.sibling === null) {
if (node.return === null || isHostParent(node.return)) {
// If we pop out of the root or hit the parent the fiber we are the
// last sibling.
return null;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) {
// If it is not host node and, we might have a host node inside it.
// Try to search down until we find one.
if (node.flags & Placement) {
// If we don't have a child, try the siblings instead.
continue siblings;
} // If we don't have a child, try the siblings instead.
// We also skip portals because they are not part of this host tree.
if (node.child === null || node.tag === HostPortal) {
continue siblings;
} else {
node.child.return = node;
node = node.child;
}
} // Check if this host node is stable or about to be placed.
if (!(node.flags & Placement)) {
// Found it!
return node.stateNode;
}
}
}
function commitPlacement(finishedWork) {
var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together.
switch (parentFiber.tag) {
case HostComponent:
{
var parent = parentFiber.stateNode;
if (parentFiber.flags & ContentReset) {
// Reset the text content of the parent before doing any insertions
resetTextContent(parent); // Clear ContentReset from the effect tag
parentFiber.flags &= ~ContentReset;
}
var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its
// children to find all the terminal nodes.
insertOrAppendPlacementNode(finishedWork, before, parent);
break;
}
case HostRoot:
case HostPortal:
{
var _parent = parentFiber.stateNode.containerInfo;
var _before = getHostSibling(finishedWork);
insertOrAppendPlacementNodeIntoContainer(finishedWork, _before, _parent);
break;
}
// eslint-disable-next-line-no-fallthrough
default:
throw new Error('Invalid host parent fiber. This error is likely caused by a bug ' + 'in React. Please file an issue.');
}
}
function insertOrAppendPlacementNodeIntoContainer(node, before, parent) {
var tag = node.tag;
var isHost = tag === HostComponent || tag === HostText;
if (isHost) {
var stateNode = node.stateNode;
if (before) {
insertInContainerBefore(parent, stateNode, before);
} else {
appendChildToContainer(parent, stateNode);
}
} else if (tag === HostPortal) ; else {
var child = node.child;
if (child !== null) {
insertOrAppendPlacementNodeIntoContainer(child, before, parent);
var sibling = child.sibling;
while (sibling !== null) {
insertOrAppendPlacementNodeIntoContainer(sibling, before, parent);
sibling = sibling.sibling;
}
}
}
}
function insertOrAppendPlacementNode(node, before, parent) {
var tag = node.tag;
var isHost = tag === HostComponent || tag === HostText;
if (isHost) {
var stateNode = node.stateNode;
if (before) {
insertBefore(parent, stateNode, before);
} else {
appendChild(parent, stateNode);
}
} else if (tag === HostPortal) ; else {
var child = node.child;
if (child !== null) {
insertOrAppendPlacementNode(child, before, parent);
var sibling = child.sibling;
while (sibling !== null) {
insertOrAppendPlacementNode(sibling, before, parent);
sibling = sibling.sibling;
}
}
}
} // These are tracked on the stack as we recursively traverse a
// deleted subtree.
// TODO: Update these during the whole mutation phase, not just during
// a deletion.
var hostParent = null;
var hostParentIsContainer = false;
function commitDeletionEffects(root, returnFiber, deletedFiber) {
{
// We only have the top Fiber that was deleted but we need to recurse down its
// children to find all the terminal nodes.
// Recursively delete all host nodes from the parent, detach refs, clean
// up mounted layout effects, and call componentWillUnmount.
// We only need to remove the topmost host child in each branch. But then we
// still need to keep traversing to unmount effects, refs, and cWU. TODO: We
// could split this into two separate traversals functions, where the second
// one doesn't include any removeChild logic. This is maybe the same
// function as "disappearLayoutEffects" (or whatever that turns into after
// the layout phase is refactored to use recursion).
// Before starting, find the nearest host parent on the stack so we know
// which instance/container to remove the children from.
// TODO: Instead of searching up the fiber return path on every deletion, we
// can track the nearest host component on the JS stack as we traverse the
// tree during the commit phase. This would make insertions faster, too.
var parent = returnFiber;
findParent: while (parent !== null) {
switch (parent.tag) {
case HostComponent:
{
hostParent = parent.stateNode;
hostParentIsContainer = false;
break findParent;
}
case HostRoot:
{
hostParent = parent.stateNode.containerInfo;
hostParentIsContainer = true;
break findParent;
}
case HostPortal:
{
hostParent = parent.stateNode.containerInfo;
hostParentIsContainer = true;
break findParent;
}
}
parent = parent.return;
}
if (hostParent === null) {
throw new Error('Expected to find a host parent. This error is likely caused by ' + 'a bug in React. Please file an issue.');
}
commitDeletionEffectsOnFiber(root, returnFiber, deletedFiber);
hostParent = null;
hostParentIsContainer = false;
}
detachFiberMutation(deletedFiber);
}
function recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, parent) {
// TODO: Use a static flag to skip trees that don't have unmount effects
var child = parent.child;
while (child !== null) {
commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, child);
child = child.sibling;
}
}
function commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, deletedFiber) {
onCommitUnmount(deletedFiber); // The cases in this outer switch modify the stack before they traverse
// into their subtree. There are simpler cases in the inner switch
// that don't modify the stack.
switch (deletedFiber.tag) {
case HostComponent:
{
if (!offscreenSubtreeWasHidden) {
safelyDetachRef(deletedFiber, nearestMountedAncestor);
} // Intentional fallthrough to next branch
}
// eslint-disable-next-line-no-fallthrough
case HostText:
{
// We only need to remove the nearest host child. Set the host parent
// to `null` on the stack to indicate that nested children don't
// need to be removed.
{
var prevHostParent = hostParent;
var prevHostParentIsContainer = hostParentIsContainer;
hostParent = null;
recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
hostParent = prevHostParent;
hostParentIsContainer = prevHostParentIsContainer;
if (hostParent !== null) {
// Now that all the child effects have unmounted, we can remove the
// node from the tree.
if (hostParentIsContainer) {
removeChildFromContainer(hostParent, deletedFiber.stateNode);
} else {
removeChild(hostParent, deletedFiber.stateNode);
}
}
}
return;
}
case DehydratedFragment:
{
// Delete the dehydrated suspense boundary and all of its content.
{
if (hostParent !== null) {
if (hostParentIsContainer) {
clearSuspenseBoundaryFromContainer(hostParent, deletedFiber.stateNode);
} else {
clearSuspenseBoundary(hostParent, deletedFiber.stateNode);
}
}
}
return;
}
case HostPortal:
{
{
// When we go into a portal, it becomes the parent to remove from.
var _prevHostParent = hostParent;
var _prevHostParentIsContainer = hostParentIsContainer;
hostParent = deletedFiber.stateNode.containerInfo;
hostParentIsContainer = true;
recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
hostParent = _prevHostParent;
hostParentIsContainer = _prevHostParentIsContainer;
}
return;
}
case FunctionComponent:
case ForwardRef:
case MemoComponent:
case SimpleMemoComponent:
{
if (!offscreenSubtreeWasHidden) {
var updateQueue = deletedFiber.updateQueue;
if (updateQueue !== null) {
var lastEffect = updateQueue.lastEffect;
if (lastEffect !== null) {
var firstEffect = lastEffect.next;
var effect = firstEffect;
do {
var _effect = effect,
destroy = _effect.destroy,
tag = _effect.tag;
if (destroy !== undefined) {
if ((tag & Insertion) !== NoFlags$1) {
safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy);
} else if ((tag & Layout) !== NoFlags$1) {
{
markComponentLayoutEffectUnmountStarted(deletedFiber);
}
if ( deletedFiber.mode & ProfileMode) {
startLayoutEffectTimer();
safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy);
recordLayoutEffectDuration(deletedFiber);
} else {
safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy);
}
{
markComponentLayoutEffectUnmountStopped();
}
}
}
effect = effect.next;
} while (effect !== firstEffect);
}
}
}
recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
return;
}
case ClassComponent:
{
if (!offscreenSubtreeWasHidden) {
safelyDetachRef(deletedFiber, nearestMountedAncestor);
var instance = deletedFiber.stateNode;
if (typeof instance.componentWillUnmount === 'function') {
safelyCallComponentWillUnmount(deletedFiber, nearestMountedAncestor, instance);
}
}
recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
return;
}
case ScopeComponent:
{
recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
return;
}
case OffscreenComponent:
{
if ( // TODO: Remove this dead flag
deletedFiber.mode & ConcurrentMode) {
// If this offscreen component is hidden, we already unmounted it. Before
// deleting the children, track that it's already unmounted so that we
// don't attempt to unmount the effects again.
// TODO: If the tree is hidden, in most cases we should be able to skip
// over the nested children entirely. An exception is we haven't yet found
// the topmost host node to delete, which we already track on the stack.
// But the other case is portals, which need to be detached no matter how
// deeply they are nested. We should use a subtree flag to track whether a
// subtree includes a nested portal.
var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || deletedFiber.memoizedState !== null;
recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
} else {
recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
}
break;
}
default:
{
recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
return;
}
}
}
function commitSuspenseCallback(finishedWork) {
// TODO: Move this to passive phase
var newState = finishedWork.memoizedState;
}
function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {
var newState = finishedWork.memoizedState;
if (newState === null) {
var current = finishedWork.alternate;
if (current !== null) {
var prevState = current.memoizedState;
if (prevState !== null) {
var suspenseInstance = prevState.dehydrated;
if (suspenseInstance !== null) {
commitHydratedSuspenseInstance(suspenseInstance);
}
}
}
}
}
function attachSuspenseRetryListeners(finishedWork) {
// If this boundary just timed out, then it will have a set of wakeables.
// For each wakeable, attach a listener so that when it resolves, React
// attempts to re-render the boundary in the primary (pre-timeout) state.
var wakeables = finishedWork.updateQueue;
if (wakeables !== null) {
finishedWork.updateQueue = null;
var retryCache = finishedWork.stateNode;
if (retryCache === null) {
retryCache = finishedWork.stateNode = new PossiblyWeakSet();
}
wakeables.forEach(function (wakeable) {
// Memoize using the boundary fiber to prevent redundant listeners.
var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable);
if (!retryCache.has(wakeable)) {
retryCache.add(wakeable);
{
if (isDevToolsPresent) {
if (inProgressLanes !== null && inProgressRoot !== null) {
// If we have pending work still, associate the original updaters with it.
restorePendingUpdaters(inProgressRoot, inProgressLanes);
} else {
throw Error('Expected finished root and lanes to be set. This is a bug in React.');
}
}
}
wakeable.then(retry, retry);
}
});
}
} // This function detects when a Suspense boundary goes from visible to hidden.
function commitMutationEffects(root, finishedWork, committedLanes) {
inProgressLanes = committedLanes;
inProgressRoot = root;
setCurrentFiber(finishedWork);
commitMutationEffectsOnFiber(finishedWork, root);
setCurrentFiber(finishedWork);
inProgressLanes = null;
inProgressRoot = null;
}
function recursivelyTraverseMutationEffects(root, parentFiber, lanes) {
// Deletions effects can be scheduled on any fiber type. They need to happen
// before the children effects hae fired.
var deletions = parentFiber.deletions;
if (deletions !== null) {
for (var i = 0; i < deletions.length; i++) {
var childToDelete = deletions[i];
try {
commitDeletionEffects(root, parentFiber, childToDelete);
} catch (error) {
captureCommitPhaseError(childToDelete, parentFiber, error);
}
}
}
var prevDebugFiber = getCurrentFiber();
if (parentFiber.subtreeFlags & MutationMask) {
var child = parentFiber.child;
while (child !== null) {
setCurrentFiber(child);
commitMutationEffectsOnFiber(child, root);
child = child.sibling;
}
}
setCurrentFiber(prevDebugFiber);
}
function commitMutationEffectsOnFiber(finishedWork, root, lanes) {
var current = finishedWork.alternate;
var flags = finishedWork.flags; // The effect flag should be checked *after* we refine the type of fiber,
// because the fiber tag is more specific. An exception is any flag related
// to reconcilation, because those can be set on all fiber types.
switch (finishedWork.tag) {
case FunctionComponent:
case ForwardRef:
case MemoComponent:
case SimpleMemoComponent:
{
recursivelyTraverseMutationEffects(root, finishedWork);
commitReconciliationEffects(finishedWork);
if (flags & Update) {
try {
commitHookEffectListUnmount(Insertion | HasEffect, finishedWork, finishedWork.return);
commitHookEffectListMount(Insertion | HasEffect, finishedWork);
} catch (error) {
captureCommitPhaseError(finishedWork, finishedWork.return, error);
} // Layout effects are destroyed during the mutation phase so that all
// destroy functions for all fibers are called before any create functions.
// This prevents sibling component effects from interfering with each other,
// e.g. a destroy function in one component should never override a ref set
// by a create function in another component during the same commit.
if ( finishedWork.mode & ProfileMode) {
try {
startLayoutEffectTimer();
commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return);
} catch (error) {
captureCommitPhaseError(finishedWork, finishedWork.return, error);
}
recordLayoutEffectDuration(finishedWork);
} else {
try {
commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return);
} catch (error) {
captureCommitPhaseError(finishedWork, finishedWork.return, error);
}
}
}
return;
}
case ClassComponent:
{
recursivelyTraverseMutationEffects(root, finishedWork);
commitReconciliationEffects(finishedWork);
if (flags & Ref) {
if (current !== null) {
safelyDetachRef(current, current.return);
}
}
return;
}
case HostComponent:
{
recursivelyTraverseMutationEffects(root, finishedWork);
commitReconciliationEffects(finishedWork);
if (flags & Ref) {
if (current !== null) {
safelyDetachRef(current, current.return);
}
}
{
// TODO: ContentReset gets cleared by the children during the commit
// phase. This is a refactor hazard because it means we must read
// flags the flags after `commitReconciliationEffects` has already run;
// the order matters. We should refactor so that ContentReset does not
// rely on mutating the flag during commit. Like by setting a flag
// during the render phase instead.
if (finishedWork.flags & ContentReset) {
var instance = finishedWork.stateNode;
try {
resetTextContent(instance);
} catch (error) {
captureCommitPhaseError(finishedWork, finishedWork.return, error);
}
}
if (flags & Update) {
var _instance4 = finishedWork.stateNode;
if (_instance4 != null) {
// Commit the work prepared earlier.
var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
// as the newProps. The updatePayload will contain the real change in
// this case.
var oldProps = current !== null ? current.memoizedProps : newProps;
var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components.
var updatePayload = finishedWork.updateQueue;
finishedWork.updateQueue = null;
if (updatePayload !== null) {
try {
commitUpdate(_instance4, updatePayload, type, oldProps, newProps, finishedWork);
} catch (error) {
captureCommitPhaseError(finishedWork, finishedWork.return, error);
}
}
}
}
}
return;
}
case HostText:
{
recursivelyTraverseMutationEffects(root, finishedWork);
commitReconciliationEffects(finishedWork);
if (flags & Update) {
{
if (finishedWork.stateNode === null) {
throw new Error('This should have a text node initialized. This error is likely ' + 'caused by a bug in React. Please file an issue.');
}
var textInstance = finishedWork.stateNode;
var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
// as the newProps. The updatePayload will contain the real change in
// this case.
var oldText = current !== null ? current.memoizedProps : newText;
try {
commitTextUpdate(textInstance, oldText, newText);
} catch (error) {
captureCommitPhaseError(finishedWork, finishedWork.return, error);
}
}
}
return;
}
case HostRoot:
{
recursivelyTraverseMutationEffects(root, finishedWork);
commitReconciliationEffects(finishedWork);
if (flags & Update) {
{
if (current !== null) {
var prevRootState = current.memoizedState;
if (prevRootState.isDehydrated) {
try {
commitHydratedContainer(root.containerInfo);
} catch (error) {
captureCommitPhaseError(finishedWork, finishedWork.return, error);
}
}
}
}
}
return;
}
case HostPortal:
{
recursivelyTraverseMutationEffects(root, finishedWork);
commitReconciliationEffects(finishedWork);
return;
}
case SuspenseComponent:
{
recursivelyTraverseMutationEffects(root, finishedWork);
commitReconciliationEffects(finishedWork);
var offscreenFiber = finishedWork.child;
if (offscreenFiber.flags & Visibility) {
var offscreenInstance = offscreenFiber.stateNode;
var newState = offscreenFiber.memoizedState;
var isHidden = newState !== null; // Track the current state on the Offscreen instance so we can
// read it during an event
offscreenInstance.isHidden = isHidden;
if (isHidden) {
var wasHidden = offscreenFiber.alternate !== null && offscreenFiber.alternate.memoizedState !== null;
if (!wasHidden) {
// TODO: Move to passive phase
markCommitTimeOfFallback();
}
}
}
if (flags & Update) {
try {
commitSuspenseCallback(finishedWork);
} catch (error) {
captureCommitPhaseError(finishedWork, finishedWork.return, error);
}
attachSuspenseRetryListeners(finishedWork);
}
return;
}
case OffscreenComponent:
{
var _wasHidden = current !== null && current.memoizedState !== null;
if ( // TODO: Remove this dead flag
finishedWork.mode & ConcurrentMode) {
// Before committing the children, track on the stack whether this
// offscreen subtree was already hidden, so that we don't unmount the
// effects again.
var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || _wasHidden;
recursivelyTraverseMutationEffects(root, finishedWork);
offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
} else {
recursivelyTraverseMutationEffects(root, finishedWork);
}
commitReconciliationEffects(finishedWork);
if (flags & Visibility) {
var _offscreenInstance = finishedWork.stateNode;
var _newState = finishedWork.memoizedState;
var _isHidden = _newState !== null;
var offscreenBoundary = finishedWork; // Track the current state on the Offscreen instance so we can
// read it during an event
_offscreenInstance.isHidden = _isHidden;
{
if (_isHidden) {
if (!_wasHidden) {
if ((offscreenBoundary.mode & ConcurrentMode) !== NoMode) {
nextEffect = offscreenBoundary;
var offscreenChild = offscreenBoundary.child;
while (offscreenChild !== null) {
nextEffect = offscreenChild;
disappearLayoutEffects_begin(offscreenChild);
offscreenChild = offscreenChild.sibling;
}
}
}
}
}
{
// TODO: This needs to run whenever there's an insertion or update
// inside a hidden Offscreen tree.
hideOrUnhideAllChildren(offscreenBoundary, _isHidden);
}
}
return;
}
case SuspenseListComponent:
{
recursivelyTraverseMutationEffects(root, finishedWork);
commitReconciliationEffects(finishedWork);
if (flags & Update) {
attachSuspenseRetryListeners(finishedWork);
}
return;
}
case ScopeComponent:
{
return;
}
default:
{
recursivelyTraverseMutationEffects(root, finishedWork);
commitReconciliationEffects(finishedWork);
return;
}
}
}
function commitReconciliationEffects(finishedWork) {
// Placement effects (insertions, reorders) can be scheduled on any fiber
// type. They needs to happen after the children effects have fired, but
// before the effects on this fiber have fired.
var flags = finishedWork.flags;
if (flags & Placement) {
try {
commitPlacement(finishedWork);
} catch (error) {
captureCommitPhaseError(finishedWork, finishedWork.return, error);
} // Clear the "placement" from effect tag so that we know that this is
// inserted, before any life-cycles like componentDidMount gets called.
// TODO: findDOMNode doesn't rely on this any more but isMounted does
// and isMounted is deprecated anyway so we should be able to kill this.
finishedWork.flags &= ~Placement;
}
if (flags & Hydrating) {
finishedWork.flags &= ~Hydrating;
}
}
function commitLayoutEffects(finishedWork, root, committedLanes) {
inProgressLanes = committedLanes;
inProgressRoot = root;
nextEffect = finishedWork;
commitLayoutEffects_begin(finishedWork, root, committedLanes);
inProgressLanes = null;
inProgressRoot = null;
}
function commitLayoutEffects_begin(subtreeRoot, root, committedLanes) {
// Suspense layout effects semantics don't change for legacy roots.
var isModernRoot = (subtreeRoot.mode & ConcurrentMode) !== NoMode;
while (nextEffect !== null) {
var fiber = nextEffect;
var firstChild = fiber.child;
if ( fiber.tag === OffscreenComponent && isModernRoot) {
// Keep track of the current Offscreen stack's state.
var isHidden = fiber.memoizedState !== null;
var newOffscreenSubtreeIsHidden = isHidden || offscreenSubtreeIsHidden;
if (newOffscreenSubtreeIsHidden) {
// The Offscreen tree is hidden. Skip over its layout effects.
commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes);
continue;
} else {
// TODO (Offscreen) Also check: subtreeFlags & LayoutMask
var current = fiber.alternate;
var wasHidden = current !== null && current.memoizedState !== null;
var newOffscreenSubtreeWasHidden = wasHidden || offscreenSubtreeWasHidden;
var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden;
var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; // Traverse the Offscreen subtree with the current Offscreen as the root.
offscreenSubtreeIsHidden = newOffscreenSubtreeIsHidden;
offscreenSubtreeWasHidden = newOffscreenSubtreeWasHidden;
if (offscreenSubtreeWasHidden && !prevOffscreenSubtreeWasHidden) {
// This is the root of a reappearing boundary. Turn its layout effects
// back on.
nextEffect = fiber;
reappearLayoutEffects_begin(fiber);
}
var child = firstChild;
while (child !== null) {
nextEffect = child;
commitLayoutEffects_begin(child, // New root; bubble back up to here and stop.
root, committedLanes);
child = child.sibling;
} // Restore Offscreen state and resume in our-progress traversal.
nextEffect = fiber;
offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden;
offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes);
continue;
}
}
if ((fiber.subtreeFlags & LayoutMask) !== NoFlags && firstChild !== null) {
firstChild.return = fiber;
nextEffect = firstChild;
} else {
commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes);
}
}
}
function commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes) {
while (nextEffect !== null) {
var fiber = nextEffect;
if ((fiber.flags & LayoutMask) !== NoFlags) {
var current = fiber.alternate;
setCurrentFiber(fiber);
try {
commitLayoutEffectOnFiber(root, current, fiber, committedLanes);
} catch (error) {
captureCommitPhaseError(fiber, fiber.return, error);
}
resetCurrentFiber();
}
if (fiber === subtreeRoot) {
nextEffect = null;
return;
}
var sibling = fiber.sibling;
if (sibling !== null) {
sibling.return = fiber.return;
nextEffect = sibling;
return;
}
nextEffect = fiber.return;
}
}
function disappearLayoutEffects_begin(subtreeRoot) {
while (nextEffect !== null) {
var fiber = nextEffect;
var firstChild = fiber.child; // TODO (Offscreen) Check: flags & (RefStatic | LayoutStatic)
switch (fiber.tag) {
case FunctionComponent:
case ForwardRef:
case MemoComponent:
case SimpleMemoComponent:
{
if ( fiber.mode & ProfileMode) {
try {
startLayoutEffectTimer();
commitHookEffectListUnmount(Layout, fiber, fiber.return);
} finally {
recordLayoutEffectDuration(fiber);
}
} else {
commitHookEffectListUnmount(Layout, fiber, fiber.return);
}
break;
}
case ClassComponent:
{
// TODO (Offscreen) Check: flags & RefStatic
safelyDetachRef(fiber, fiber.return);
var instance = fiber.stateNode;
if (typeof instance.componentWillUnmount === 'function') {
safelyCallComponentWillUnmount(fiber, fiber.return, instance);
}
break;
}
case HostComponent:
{
safelyDetachRef(fiber, fiber.return);
break;
}
case OffscreenComponent:
{
// Check if this is a
var isHidden = fiber.memoizedState !== null;
if (isHidden) {
// Nested Offscreen tree is already hidden. Don't disappear
// its effects.
disappearLayoutEffects_complete(subtreeRoot);
continue;
}
break;
}
} // TODO (Offscreen) Check: subtreeFlags & LayoutStatic
if (firstChild !== null) {
firstChild.return = fiber;
nextEffect = firstChild;
} else {
disappearLayoutEffects_complete(subtreeRoot);
}
}
}
function disappearLayoutEffects_complete(subtreeRoot) {
while (nextEffect !== null) {
var fiber = nextEffect;
if (fiber === subtreeRoot) {
nextEffect = null;
return;
}
var sibling = fiber.sibling;
if (sibling !== null) {
sibling.return = fiber.return;
nextEffect = sibling;
return;
}
nextEffect = fiber.return;
}
}
function reappearLayoutEffects_begin(subtreeRoot) {
while (nextEffect !== null) {
var fiber = nextEffect;
var firstChild = fiber.child;
if (fiber.tag === OffscreenComponent) {
var isHidden = fiber.memoizedState !== null;
if (isHidden) {
// Nested Offscreen tree is still hidden. Don't re-appear its effects.
reappearLayoutEffects_complete(subtreeRoot);
continue;
}
} // TODO (Offscreen) Check: subtreeFlags & LayoutStatic
if (firstChild !== null) {
// This node may have been reused from a previous render, so we can't
// assume its return pointer is correct.
firstChild.return = fiber;
nextEffect = firstChild;
} else {
reappearLayoutEffects_complete(subtreeRoot);
}
}
}
function reappearLayoutEffects_complete(subtreeRoot) {
while (nextEffect !== null) {
var fiber = nextEffect; // TODO (Offscreen) Check: flags & LayoutStatic
setCurrentFiber(fiber);
try {
reappearLayoutEffectsOnFiber(fiber);
} catch (error) {
captureCommitPhaseError(fiber, fiber.return, error);
}
resetCurrentFiber();
if (fiber === subtreeRoot) {
nextEffect = null;
return;
}
var sibling = fiber.sibling;
if (sibling !== null) {
// This node may have been reused from a previous render, so we can't
// assume its return pointer is correct.
sibling.return = fiber.return;
nextEffect = sibling;
return;
}
nextEffect = fiber.return;
}
}
function commitPassiveMountEffects(root, finishedWork, committedLanes, committedTransitions) {
nextEffect = finishedWork;
commitPassiveMountEffects_begin(finishedWork, root, committedLanes, committedTransitions);
}
function commitPassiveMountEffects_begin(subtreeRoot, root, committedLanes, committedTransitions) {
while (nextEffect !== null) {
var fiber = nextEffect;
var firstChild = fiber.child;
if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && firstChild !== null) {
firstChild.return = fiber;
nextEffect = firstChild;
} else {
commitPassiveMountEffects_complete(subtreeRoot, root, committedLanes, committedTransitions);
}
}
}
function commitPassiveMountEffects_complete(subtreeRoot, root, committedLanes, committedTransitions) {
while (nextEffect !== null) {
var fiber = nextEffect;
if ((fiber.flags & Passive) !== NoFlags) {
setCurrentFiber(fiber);
try {
commitPassiveMountOnFiber(root, fiber, committedLanes, committedTransitions);
} catch (error) {
captureCommitPhaseError(fiber, fiber.return, error);
}
resetCurrentFiber();
}
if (fiber === subtreeRoot) {
nextEffect = null;
return;
}
var sibling = fiber.sibling;
if (sibling !== null) {
sibling.return = fiber.return;
nextEffect = sibling;
return;
}
nextEffect = fiber.return;
}
}
function commitPassiveMountOnFiber(finishedRoot, finishedWork, committedLanes, committedTransitions) {
switch (finishedWork.tag) {
case FunctionComponent:
case ForwardRef:
case SimpleMemoComponent:
{
if ( finishedWork.mode & ProfileMode) {
startPassiveEffectTimer();
try {
commitHookEffectListMount(Passive$1 | HasEffect, finishedWork);
} finally {
recordPassiveEffectDuration(finishedWork);
}
} else {
commitHookEffectListMount(Passive$1 | HasEffect, finishedWork);
}
break;
}
}
}
function commitPassiveUnmountEffects(firstChild) {
nextEffect = firstChild;
commitPassiveUnmountEffects_begin();
}
function commitPassiveUnmountEffects_begin() {
while (nextEffect !== null) {
var fiber = nextEffect;
var child = fiber.child;
if ((nextEffect.flags & ChildDeletion) !== NoFlags) {
var deletions = fiber.deletions;
if (deletions !== null) {
for (var i = 0; i < deletions.length; i++) {
var fiberToDelete = deletions[i];
nextEffect = fiberToDelete;
commitPassiveUnmountEffectsInsideOfDeletedTree_begin(fiberToDelete, fiber);
}
{
// A fiber was deleted from this parent fiber, but it's still part of
// the previous (alternate) parent fiber's list of children. Because
// children are a linked list, an earlier sibling that's still alive
// will be connected to the deleted fiber via its `alternate`:
//
// live fiber
// --alternate--> previous live fiber
// --sibling--> deleted fiber
//
// We can't disconnect `alternate` on nodes that haven't been deleted
// yet, but we can disconnect the `sibling` and `child` pointers.
var previousFiber = fiber.alternate;
if (previousFiber !== null) {
var detachedChild = previousFiber.child;
if (detachedChild !== null) {
previousFiber.child = null;
do {
var detachedSibling = detachedChild.sibling;
detachedChild.sibling = null;
detachedChild = detachedSibling;
} while (detachedChild !== null);
}
}
}
nextEffect = fiber;
}
}
if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && child !== null) {
child.return = fiber;
nextEffect = child;
} else {
commitPassiveUnmountEffects_complete();
}
}
}
function commitPassiveUnmountEffects_complete() {
while (nextEffect !== null) {
var fiber = nextEffect;
if ((fiber.flags & Passive) !== NoFlags) {
setCurrentFiber(fiber);
commitPassiveUnmountOnFiber(fiber);
resetCurrentFiber();
}
var sibling = fiber.sibling;
if (sibling !== null) {
sibling.return = fiber.return;
nextEffect = sibling;
return;
}
nextEffect = fiber.return;
}
}
function commitPassiveUnmountOnFiber(finishedWork) {
switch (finishedWork.tag) {
case FunctionComponent:
case ForwardRef:
case SimpleMemoComponent:
{
if ( finishedWork.mode & ProfileMode) {
startPassiveEffectTimer();
commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return);
recordPassiveEffectDuration(finishedWork);
} else {
commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return);
}
break;
}
}
}
function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor) {
while (nextEffect !== null) {
var fiber = nextEffect; // Deletion effects fire in parent -> child order
// TODO: Check if fiber has a PassiveStatic flag
setCurrentFiber(fiber);
commitPassiveUnmountInsideDeletedTreeOnFiber(fiber, nearestMountedAncestor);
resetCurrentFiber();
var child = fiber.child; // TODO: Only traverse subtree if it has a PassiveStatic flag. (But, if we
// do this, still need to handle `deletedTreeCleanUpLevel` correctly.)
if (child !== null) {
child.return = fiber;
nextEffect = child;
} else {
commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot);
}
}
}
function commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot) {
while (nextEffect !== null) {
var fiber = nextEffect;
var sibling = fiber.sibling;
var returnFiber = fiber.return;
{
// Recursively traverse the entire deleted tree and clean up fiber fields.
// This is more aggressive than ideal, and the long term goal is to only
// have to detach the deleted tree at the root.
detachFiberAfterEffects(fiber);
if (fiber === deletedSubtreeRoot) {
nextEffect = null;
return;
}
}
if (sibling !== null) {
sibling.return = returnFiber;
nextEffect = sibling;
return;
}
nextEffect = returnFiber;
}
}
function commitPassiveUnmountInsideDeletedTreeOnFiber(current, nearestMountedAncestor) {
switch (current.tag) {
case FunctionComponent:
case ForwardRef:
case SimpleMemoComponent:
{
if ( current.mode & ProfileMode) {
startPassiveEffectTimer();
commitHookEffectListUnmount(Passive$1, current, nearestMountedAncestor);
recordPassiveEffectDuration(current);
} else {
commitHookEffectListUnmount(Passive$1, current, nearestMountedAncestor);
}
break;
}
}
} // TODO: Reuse reappearLayoutEffects traversal here?
function invokeLayoutEffectMountInDEV(fiber) {
{
// We don't need to re-check StrictEffectsMode here.
// This function is only called if that check has already passed.
switch (fiber.tag) {
case FunctionComponent:
case ForwardRef:
case SimpleMemoComponent:
{
try {
commitHookEffectListMount(Layout | HasEffect, fiber);
} catch (error) {
captureCommitPhaseError(fiber, fiber.return, error);
}
break;
}
case ClassComponent:
{
var instance = fiber.stateNode;
try {
instance.componentDidMount();
} catch (error) {
captureCommitPhaseError(fiber, fiber.return, error);
}
break;
}
}
}
}
function invokePassiveEffectMountInDEV(fiber) {
{
// We don't need to re-check StrictEffectsMode here.
// This function is only called if that check has already passed.
switch (fiber.tag) {
case FunctionComponent:
case ForwardRef:
case SimpleMemoComponent:
{
try {
commitHookEffectListMount(Passive$1 | HasEffect, fiber);
} catch (error) {
captureCommitPhaseError(fiber, fiber.return, error);
}
break;
}
}
}
}
function invokeLayoutEffectUnmountInDEV(fiber) {
{
// We don't need to re-check StrictEffectsMode here.
// This function is only called if that check has already passed.
switch (fiber.tag) {
case FunctionComponent:
case ForwardRef:
case SimpleMemoComponent:
{
try {
commitHookEffectListUnmount(Layout | HasEffect, fiber, fiber.return);
} catch (error) {
captureCommitPhaseError(fiber, fiber.return, error);
}
break;
}
case ClassComponent:
{
var instance = fiber.stateNode;
if (typeof instance.componentWillUnmount === 'function') {
safelyCallComponentWillUnmount(fiber, fiber.return, instance);
}
break;
}
}
}
}
function invokePassiveEffectUnmountInDEV(fiber) {
{
// We don't need to re-check StrictEffectsMode here.
// This function is only called if that check has already passed.
switch (fiber.tag) {
case FunctionComponent:
case ForwardRef:
case SimpleMemoComponent:
{
try {
commitHookEffectListUnmount(Passive$1 | HasEffect, fiber, fiber.return);
} catch (error) {
captureCommitPhaseError(fiber, fiber.return, error);
}
}
}
}
}
var COMPONENT_TYPE = 0;
var HAS_PSEUDO_CLASS_TYPE = 1;
var ROLE_TYPE = 2;
var TEST_NAME_TYPE = 3;
var TEXT_TYPE = 4;
if (typeof Symbol === 'function' && Symbol.for) {
var symbolFor = Symbol.for;
COMPONENT_TYPE = symbolFor('selector.component');
HAS_PSEUDO_CLASS_TYPE = symbolFor('selector.has_pseudo_class');
ROLE_TYPE = symbolFor('selector.role');
TEST_NAME_TYPE = symbolFor('selector.test_id');
TEXT_TYPE = symbolFor('selector.text');
}
var commitHooks = [];
function onCommitRoot$1() {
{
commitHooks.forEach(function (commitHook) {
return commitHook();
});
}
}
var ReactCurrentActQueue = ReactSharedInternals.ReactCurrentActQueue;
function isLegacyActEnvironment(fiber) {
{
// Legacy mode. We preserve the behavior of React 17's act. It assumes an
// act environment whenever `jest` is defined, but you can still turn off
// spurious warnings by setting IS_REACT_ACT_ENVIRONMENT explicitly
// to false.
var isReactActEnvironmentGlobal = // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global
typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' ? IS_REACT_ACT_ENVIRONMENT : undefined; // $FlowExpectedError - Flow doesn't know about jest
var jestIsDefined = typeof jest !== 'undefined';
return jestIsDefined && isReactActEnvironmentGlobal !== false;
}
}
function isConcurrentActEnvironment() {
{
var isReactActEnvironmentGlobal = // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global
typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' ? IS_REACT_ACT_ENVIRONMENT : undefined;
if (!isReactActEnvironmentGlobal && ReactCurrentActQueue.current !== null) {
// TODO: Include link to relevant documentation page.
error('The current testing environment is not configured to support ' + 'act(...)');
}
return isReactActEnvironmentGlobal;
}
}
var ceil = Math.ceil;
var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher,
ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner,
ReactCurrentBatchConfig$3 = ReactSharedInternals.ReactCurrentBatchConfig,
ReactCurrentActQueue$1 = ReactSharedInternals.ReactCurrentActQueue;
var NoContext =
/* */
0;
var BatchedContext =
/* */
1;
var RenderContext =
/* */
2;
var CommitContext =
/* */
4;
var RootInProgress = 0;
var RootFatalErrored = 1;
var RootErrored = 2;
var RootSuspended = 3;
var RootSuspendedWithDelay = 4;
var RootCompleted = 5;
var RootDidNotComplete = 6; // Describes where we are in the React execution stack
var executionContext = NoContext; // The root we're working on
var workInProgressRoot = null; // The fiber we're working on
var workInProgress = null; // The lanes we're rendering
var workInProgressRootRenderLanes = NoLanes; // Stack that allows components to change the render lanes for its subtree
// This is a superset of the lanes we started working on at the root. The only
// case where it's different from `workInProgressRootRenderLanes` is when we
// enter a subtree that is hidden and needs to be unhidden: Suspense and
// Offscreen component.
//
// Most things in the work loop should deal with workInProgressRootRenderLanes.
// Most things in begin/complete phases should deal with subtreeRenderLanes.
var subtreeRenderLanes = NoLanes;
var subtreeRenderLanesCursor = createCursor(NoLanes); // Whether to root completed, errored, suspended, etc.
var workInProgressRootExitStatus = RootInProgress; // A fatal error, if one is thrown
var workInProgressRootFatalError = null; // "Included" lanes refer to lanes that were worked on during this render. It's
// slightly different than `renderLanes` because `renderLanes` can change as you
// enter and exit an Offscreen tree. This value is the combination of all render
// lanes for the entire render phase.
var workInProgressRootIncludedLanes = NoLanes; // The work left over by components that were visited during this render. Only
// includes unprocessed updates, not work in bailed out children.
var workInProgressRootSkippedLanes = NoLanes; // Lanes that were updated (in an interleaved event) during this render.
var workInProgressRootInterleavedUpdatedLanes = NoLanes; // Lanes that were updated during the render phase (*not* an interleaved event).
var workInProgressRootPingedLanes = NoLanes; // Errors that are thrown during the render phase.
var workInProgressRootConcurrentErrors = null; // These are errors that we recovered from without surfacing them to the UI.
// We will log them once the tree commits.
var workInProgressRootRecoverableErrors = null; // The most recent time we committed a fallback. This lets us ensure a train
// model where we don't commit new loading states in too quick succession.
var globalMostRecentFallbackTime = 0;
var FALLBACK_THROTTLE_MS = 500; // The absolute time for when we should start giving up on rendering
// more and prefer CPU suspense heuristics instead.
var workInProgressRootRenderTargetTime = Infinity; // How long a render is supposed to take before we start following CPU
// suspense heuristics and opt out of rendering more content.
var RENDER_TIMEOUT_MS = 500;
var workInProgressTransitions = null;
function resetRenderTimer() {
workInProgressRootRenderTargetTime = now() + RENDER_TIMEOUT_MS;
}
function getRenderTargetTime() {
return workInProgressRootRenderTargetTime;
}
var hasUncaughtError = false;
var firstUncaughtError = null;
var legacyErrorBoundariesThatAlreadyFailed = null; // Only used when enableProfilerNestedUpdateScheduledHook is true;
var rootDoesHavePassiveEffects = false;
var rootWithPendingPassiveEffects = null;
var pendingPassiveEffectsLanes = NoLanes;
var pendingPassiveProfilerEffects = [];
var pendingPassiveTransitions = null; // Use these to prevent an infinite loop of nested updates
var NESTED_UPDATE_LIMIT = 50;
var nestedUpdateCount = 0;
var rootWithNestedUpdates = null;
var isFlushingPassiveEffects = false;
var didScheduleUpdateDuringPassiveEffects = false;
var NESTED_PASSIVE_UPDATE_LIMIT = 50;
var nestedPassiveUpdateCount = 0;
var rootWithPassiveNestedUpdates = null; // If two updates are scheduled within the same event, we should treat their
// event times as simultaneous, even if the actual clock time has advanced
// between the first and second call.
var currentEventTime = NoTimestamp;
var currentEventTransitionLane = NoLanes;
var isRunningInsertionEffect = false;
function getWorkInProgressRoot() {
return workInProgressRoot;
}
function requestEventTime() {
if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
// We're inside React, so it's fine to read the actual time.
return now();
} // We're not inside React, so we may be in the middle of a browser event.
if (currentEventTime !== NoTimestamp) {
// Use the same start time for all updates until we enter React again.
return currentEventTime;
} // This is the first update since React yielded. Compute a new start time.
currentEventTime = now();
return currentEventTime;
}
function requestUpdateLane(fiber) {
// Special cases
var mode = fiber.mode;
if ((mode & ConcurrentMode) === NoMode) {
return SyncLane;
} else if ( (executionContext & RenderContext) !== NoContext && workInProgressRootRenderLanes !== NoLanes) {
// This is a render phase update. These are not officially supported. The
// old behavior is to give this the same "thread" (lanes) as
// whatever is currently rendering. So if you call `setState` on a component
// that happens later in the same render, it will flush. Ideally, we want to
// remove the special case and treat them as if they came from an
// interleaved event. Regardless, this pattern is not officially supported.
// This behavior is only a fallback. The flag only exists until we can roll
// out the setState warning, since existing code might accidentally rely on
// the current behavior.
return pickArbitraryLane(workInProgressRootRenderLanes);
}
var isTransition = requestCurrentTransition() !== NoTransition;
if (isTransition) {
if ( ReactCurrentBatchConfig$3.transition !== null) {
var transition = ReactCurrentBatchConfig$3.transition;
if (!transition._updatedFibers) {
transition._updatedFibers = new Set();
}
transition._updatedFibers.add(fiber);
} // The algorithm for assigning an update to a lane should be stable for all
// updates at the same priority within the same event. To do this, the
// inputs to the algorithm must be the same.
//
// The trick we use is to cache the first of each of these inputs within an
// event. Then reset the cached values once we can be sure the event is
// over. Our heuristic for that is whenever we enter a concurrent work loop.
if (currentEventTransitionLane === NoLane) {
// All transitions within the same event are assigned the same lane.
currentEventTransitionLane = claimNextTransitionLane();
}
return currentEventTransitionLane;
} // Updates originating inside certain React methods, like flushSync, have
// their priority set by tracking it with a context variable.
//
// The opaque type returned by the host config is internally a lane, so we can
// use that directly.
// TODO: Move this type conversion to the event priority module.
var updateLane = getCurrentUpdatePriority();
if (updateLane !== NoLane) {
return updateLane;
} // This update originated outside React. Ask the host environment for an
// appropriate priority, based on the type of event.
//
// The opaque type returned by the host config is internally a lane, so we can
// use that directly.
// TODO: Move this type conversion to the event priority module.
var eventLane = getCurrentEventPriority();
return eventLane;
}
function requestRetryLane(fiber) {
// This is a fork of `requestUpdateLane` designed specifically for Suspense
// "retries" — a special update that attempts to flip a Suspense boundary
// from its placeholder state to its primary/resolved state.
// Special cases
var mode = fiber.mode;
if ((mode & ConcurrentMode) === NoMode) {
return SyncLane;
}
return claimNextRetryLane();
}
function scheduleUpdateOnFiber(root, fiber, lane, eventTime) {
checkForNestedUpdates();
{
if (isRunningInsertionEffect) {
error('useInsertionEffect must not schedule updates.');
}
}
{
if (isFlushingPassiveEffects) {
didScheduleUpdateDuringPassiveEffects = true;
}
} // Mark that the root has a pending update.
markRootUpdated(root, lane, eventTime);
if ((executionContext & RenderContext) !== NoLanes && root === workInProgressRoot) {
// This update was dispatched during the render phase. This is a mistake
// if the update originates from user space (with the exception of local
// hook updates, which are handled differently and don't reach this
// function), but there are some internal React features that use this as
// an implementation detail, like selective hydration.
warnAboutRenderPhaseUpdatesInDEV(fiber); // Track lanes that were updated during the render phase
} else {
// This is a normal update, scheduled from outside the render phase. For
// example, during an input event.
{
if (isDevToolsPresent) {
addFiberToLanesMap(root, fiber, lane);
}
}
warnIfUpdatesNotWrappedWithActDEV(fiber);
if (root === workInProgressRoot) {
// Received an update to a tree that's in the middle of rendering. Mark
// that there was an interleaved update work on this root. Unless the
// `deferRenderPhaseUpdateToNextBatch` flag is off and this is a render
// phase update. In that case, we don't treat render phase updates as if
// they were interleaved, for backwards compat reasons.
if ( (executionContext & RenderContext) === NoContext) {
workInProgressRootInterleavedUpdatedLanes = mergeLanes(workInProgressRootInterleavedUpdatedLanes, lane);
}
if (workInProgressRootExitStatus === RootSuspendedWithDelay) {
// The root already suspended with a delay, which means this render
// definitely won't finish. Since we have a new update, let's mark it as
// suspended now, right before marking the incoming update. This has the
// effect of interrupting the current render and switching to the update.
// TODO: Make sure this doesn't override pings that happen while we've
// already started rendering.
markRootSuspended$1(root, workInProgressRootRenderLanes);
}
}
ensureRootIsScheduled(root, eventTime);
if (lane === SyncLane && executionContext === NoContext && (fiber.mode & ConcurrentMode) === NoMode && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode.
!( ReactCurrentActQueue$1.isBatchingLegacy)) {
// Flush the synchronous work now, unless we're already working or inside
// a batch. This is intentionally inside scheduleUpdateOnFiber instead of
// scheduleCallbackForFiber to preserve the ability to schedule a callback
// without immediately flushing it. We only do this for user-initiated
// updates, to preserve historical behavior of legacy mode.
resetRenderTimer();
flushSyncCallbacksOnlyInLegacyMode();
}
}
}
function scheduleInitialHydrationOnRoot(root, lane, eventTime) {
// This is a special fork of scheduleUpdateOnFiber that is only used to
// schedule the initial hydration of a root that has just been created. Most
// of the stuff in scheduleUpdateOnFiber can be skipped.
//
// The main reason for this separate path, though, is to distinguish the
// initial children from subsequent updates. In fully client-rendered roots
// (createRoot instead of hydrateRoot), all top-level renders are modeled as
// updates, but hydration roots are special because the initial render must
// match what was rendered on the server.
var current = root.current;
current.lanes = lane;
markRootUpdated(root, lane, eventTime);
ensureRootIsScheduled(root, eventTime);
}
function isUnsafeClassRenderPhaseUpdate(fiber) {
// Check if this is a render phase update. Only called by class components,
// which special (deprecated) behavior for UNSAFE_componentWillReceive props.
return (// TODO: Remove outdated deferRenderPhaseUpdateToNextBatch experiment. We
// decided not to enable it.
(executionContext & RenderContext) !== NoContext
);
} // Use this function to schedule a task for a root. There's only one task per
// root; if a task was already scheduled, we'll check to make sure the priority
// of the existing task is the same as the priority of the next level that the
// root has work on. This function is called on every update, and right before
// exiting a task.
function ensureRootIsScheduled(root, currentTime) {
var existingCallbackNode = root.callbackNode; // Check if any lanes are being starved by other work. If so, mark them as
// expired so we know to work on those next.
markStarvedLanesAsExpired(root, currentTime); // Determine the next lanes to work on, and their priority.
var nextLanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes);
if (nextLanes === NoLanes) {
// Special case: There's nothing to work on.
if (existingCallbackNode !== null) {
cancelCallback$1(existingCallbackNode);
}
root.callbackNode = null;
root.callbackPriority = NoLane;
return;
} // We use the highest priority lane to represent the priority of the callback.
var newCallbackPriority = getHighestPriorityLane(nextLanes); // Check if there's an existing task. We may be able to reuse it.
var existingCallbackPriority = root.callbackPriority;
if (existingCallbackPriority === newCallbackPriority && // Special case related to `act`. If the currently scheduled task is a
// Scheduler task, rather than an `act` task, cancel it and re-scheduled
// on the `act` queue.
!( ReactCurrentActQueue$1.current !== null && existingCallbackNode !== fakeActCallbackNode)) {
{
// If we're going to re-use an existing task, it needs to exist.
// Assume that discrete update microtasks are non-cancellable and null.
// TODO: Temporary until we confirm this warning is not fired.
if (existingCallbackNode == null && existingCallbackPriority !== SyncLane) {
error('Expected scheduled callback to exist. This error is likely caused by a bug in React. Please file an issue.');
}
} // The priority hasn't changed. We can reuse the existing task. Exit.
return;
}
if (existingCallbackNode != null) {
// Cancel the existing callback. We'll schedule a new one below.
cancelCallback$1(existingCallbackNode);
} // Schedule a new callback.
var newCallbackNode;
if (newCallbackPriority === SyncLane) {
// Special case: Sync React callbacks are scheduled on a special
// internal queue
if (root.tag === LegacyRoot) {
if ( ReactCurrentActQueue$1.isBatchingLegacy !== null) {
ReactCurrentActQueue$1.didScheduleLegacyUpdate = true;
}
scheduleLegacySyncCallback(performSyncWorkOnRoot.bind(null, root));
} else {
scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));
}
{
// Flush the queue in a microtask.
if ( ReactCurrentActQueue$1.current !== null) {
// Inside `act`, use our internal `act` queue so that these get flushed
// at the end of the current scope even when using the sync version
// of `act`.
ReactCurrentActQueue$1.current.push(flushSyncCallbacks);
} else {
scheduleMicrotask(function () {
// In Safari, appending an iframe forces microtasks to run.
// https://github.com/facebook/react/issues/22459
// We don't support running callbacks in the middle of render
// or commit so we need to check against that.
if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
// Note that this would still prematurely flush the callbacks
// if this happens outside render or commit phase (e.g. in an event).
flushSyncCallbacks();
}
});
}
}
newCallbackNode = null;
} else {
var schedulerPriorityLevel;
switch (lanesToEventPriority(nextLanes)) {
case DiscreteEventPriority:
schedulerPriorityLevel = ImmediatePriority;
break;
case ContinuousEventPriority:
schedulerPriorityLevel = UserBlockingPriority;
break;
case DefaultEventPriority:
schedulerPriorityLevel = NormalPriority;
break;
case IdleEventPriority:
schedulerPriorityLevel = IdlePriority;
break;
default:
schedulerPriorityLevel = NormalPriority;
break;
}
newCallbackNode = scheduleCallback$1(schedulerPriorityLevel, performConcurrentWorkOnRoot.bind(null, root));
}
root.callbackPriority = newCallbackPriority;
root.callbackNode = newCallbackNode;
} // This is the entry point for every concurrent task, i.e. anything that
// goes through Scheduler.
function performConcurrentWorkOnRoot(root, didTimeout) {
{
resetNestedUpdateFlag();
} // Since we know we're in a React event, we can clear the current
// event time. The next update will compute a new event time.
currentEventTime = NoTimestamp;
currentEventTransitionLane = NoLanes;
if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
throw new Error('Should not already be working.');
} // Flush any pending passive effects before deciding which lanes to work on,
// in case they schedule additional work.
var originalCallbackNode = root.callbackNode;
var didFlushPassiveEffects = flushPassiveEffects();
if (didFlushPassiveEffects) {
// Something in the passive effect phase may have canceled the current task.
// Check if the task node for this root was changed.
if (root.callbackNode !== originalCallbackNode) {
// The current task was canceled. Exit. We don't need to call
// `ensureRootIsScheduled` because the check above implies either that
// there's a new task, or that there's no remaining work on this root.
return null;
}
} // Determine the next lanes to work on, using the fields stored
// on the root.
var lanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes);
if (lanes === NoLanes) {
// Defensive coding. This is never expected to happen.
return null;
} // We disable time-slicing in some cases: if the work has been CPU-bound
// for too long ("expired" work, to prevent starvation), or we're in
// sync-updates-by-default mode.
// TODO: We only check `didTimeout` defensively, to account for a Scheduler
// bug we're still investigating. Once the bug in Scheduler is fixed,
// we can remove this, since we track expiration ourselves.
var shouldTimeSlice = !includesBlockingLane(root, lanes) && !includesExpiredLane(root, lanes) && ( !didTimeout);
var exitStatus = shouldTimeSlice ? renderRootConcurrent(root, lanes) : renderRootSync(root, lanes);
if (exitStatus !== RootInProgress) {
if (exitStatus === RootErrored) {
// If something threw an error, try rendering one more time. We'll
// render synchronously to block concurrent data mutations, and we'll
// includes all pending updates are included. If it still fails after
// the second attempt, we'll give up and commit the resulting tree.
var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root);
if (errorRetryLanes !== NoLanes) {
lanes = errorRetryLanes;
exitStatus = recoverFromConcurrentError(root, errorRetryLanes);
}
}
if (exitStatus === RootFatalErrored) {
var fatalError = workInProgressRootFatalError;
prepareFreshStack(root, NoLanes);
markRootSuspended$1(root, lanes);
ensureRootIsScheduled(root, now());
throw fatalError;
}
if (exitStatus === RootDidNotComplete) {
// The render unwound without completing the tree. This happens in special
// cases where need to exit the current render without producing a
// consistent tree or committing.
//
// This should only happen during a concurrent render, not a discrete or
// synchronous update. We should have already checked for this when we
// unwound the stack.
markRootSuspended$1(root, lanes);
} else {
// The render completed.
// Check if this render may have yielded to a concurrent event, and if so,
// confirm that any newly rendered stores are consistent.
// TODO: It's possible that even a concurrent render may never have yielded
// to the main thread, if it was fast enough, or if it expired. We could
// skip the consistency check in that case, too.
var renderWasConcurrent = !includesBlockingLane(root, lanes);
var finishedWork = root.current.alternate;
if (renderWasConcurrent && !isRenderConsistentWithExternalStores(finishedWork)) {
// A store was mutated in an interleaved event. Render again,
// synchronously, to block further mutations.
exitStatus = renderRootSync(root, lanes); // We need to check again if something threw
if (exitStatus === RootErrored) {
var _errorRetryLanes = getLanesToRetrySynchronouslyOnError(root);
if (_errorRetryLanes !== NoLanes) {
lanes = _errorRetryLanes;
exitStatus = recoverFromConcurrentError(root, _errorRetryLanes); // We assume the tree is now consistent because we didn't yield to any
// concurrent events.
}
}
if (exitStatus === RootFatalErrored) {
var _fatalError = workInProgressRootFatalError;
prepareFreshStack(root, NoLanes);
markRootSuspended$1(root, lanes);
ensureRootIsScheduled(root, now());
throw _fatalError;
}
} // We now have a consistent tree. The next step is either to commit it,
// or, if something suspended, wait to commit it after a timeout.
root.finishedWork = finishedWork;
root.finishedLanes = lanes;
finishConcurrentRender(root, exitStatus, lanes);
}
}
ensureRootIsScheduled(root, now());
if (root.callbackNode === originalCallbackNode) {
// The task node scheduled for this root is the same one that's
// currently executed. Need to return a continuation.
return performConcurrentWorkOnRoot.bind(null, root);
}
return null;
}
function recoverFromConcurrentError(root, errorRetryLanes) {
// If an error occurred during hydration, discard server response and fall
// back to client side render.
// Before rendering again, save the errors from the previous attempt.
var errorsFromFirstAttempt = workInProgressRootConcurrentErrors;
if (isRootDehydrated(root)) {
// The shell failed to hydrate. Set a flag to force a client rendering
// during the next attempt. To do this, we call prepareFreshStack now
// to create the root work-in-progress fiber. This is a bit weird in terms
// of factoring, because it relies on renderRootSync not calling
// prepareFreshStack again in the call below, which happens because the
// root and lanes haven't changed.
//
// TODO: I think what we should do is set ForceClientRender inside
// throwException, like we do for nested Suspense boundaries. The reason
// it's here instead is so we can switch to the synchronous work loop, too.
// Something to consider for a future refactor.
var rootWorkInProgress = prepareFreshStack(root, errorRetryLanes);
rootWorkInProgress.flags |= ForceClientRender;
{
errorHydratingContainer(root.containerInfo);
}
}
var exitStatus = renderRootSync(root, errorRetryLanes);
if (exitStatus !== RootErrored) {
// Successfully finished rendering on retry
// The errors from the failed first attempt have been recovered. Add
// them to the collection of recoverable errors. We'll log them in the
// commit phase.
var errorsFromSecondAttempt = workInProgressRootRecoverableErrors;
workInProgressRootRecoverableErrors = errorsFromFirstAttempt; // The errors from the second attempt should be queued after the errors
// from the first attempt, to preserve the causal sequence.
if (errorsFromSecondAttempt !== null) {
queueRecoverableErrors(errorsFromSecondAttempt);
}
}
return exitStatus;
}
function queueRecoverableErrors(errors) {
if (workInProgressRootRecoverableErrors === null) {
workInProgressRootRecoverableErrors = errors;
} else {
workInProgressRootRecoverableErrors.push.apply(workInProgressRootRecoverableErrors, errors);
}
}
function finishConcurrentRender(root, exitStatus, lanes) {
switch (exitStatus) {
case RootInProgress:
case RootFatalErrored:
{
throw new Error('Root did not complete. This is a bug in React.');
}
// Flow knows about invariant, so it complains if I add a break
// statement, but eslint doesn't know about invariant, so it complains
// if I do. eslint-disable-next-line no-fallthrough
case RootErrored:
{
// We should have already attempted to retry this tree. If we reached
// this point, it errored again. Commit it.
commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions);
break;
}
case RootSuspended:
{
markRootSuspended$1(root, lanes); // We have an acceptable loading state. We need to figure out if we
// should immediately commit it or wait a bit.
if (includesOnlyRetries(lanes) && // do not delay if we're inside an act() scope
!shouldForceFlushFallbacksInDEV()) {
// This render only included retries, no updates. Throttle committing
// retries so that we don't show too many loading states too quickly.
var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); // Don't bother with a very short suspense time.
if (msUntilTimeout > 10) {
var nextLanes = getNextLanes(root, NoLanes);
if (nextLanes !== NoLanes) {
// There's additional work on this root.
break;
}
var suspendedLanes = root.suspendedLanes;
if (!isSubsetOfLanes(suspendedLanes, lanes)) {
// We should prefer to render the fallback of at the last
// suspended level. Ping the last suspended level to try
// rendering it again.
// FIXME: What if the suspended lanes are Idle? Should not restart.
var eventTime = requestEventTime();
markRootPinged(root, suspendedLanes);
break;
} // The render is suspended, it hasn't timed out, and there's no
// lower priority work to do. Instead of committing the fallback
// immediately, wait for more data to arrive.
root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors, workInProgressTransitions), msUntilTimeout);
break;
}
} // The work expired. Commit immediately.
commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions);
break;
}
case RootSuspendedWithDelay:
{
markRootSuspended$1(root, lanes);
if (includesOnlyTransitions(lanes)) {
// This is a transition, so we should exit without committing a
// placeholder and without scheduling a timeout. Delay indefinitely
// until we receive more data.
break;
}
if (!shouldForceFlushFallbacksInDEV()) {
// This is not a transition, but we did trigger an avoided state.
// Schedule a placeholder to display after a short delay, using the Just
// Noticeable Difference.
// TODO: Is the JND optimization worth the added complexity? If this is
// the only reason we track the event time, then probably not.
// Consider removing.
var mostRecentEventTime = getMostRecentEventTime(root, lanes);
var eventTimeMs = mostRecentEventTime;
var timeElapsedMs = now() - eventTimeMs;
var _msUntilTimeout = jnd(timeElapsedMs) - timeElapsedMs; // Don't bother with a very short suspense time.
if (_msUntilTimeout > 10) {
// Instead of committing the fallback immediately, wait for more data
// to arrive.
root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors, workInProgressTransitions), _msUntilTimeout);
break;
}
} // Commit the placeholder.
commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions);
break;
}
case RootCompleted:
{
// The work completed. Ready to commit.
commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions);
break;
}
default:
{
throw new Error('Unknown root exit status.');
}
}
}
function isRenderConsistentWithExternalStores(finishedWork) {
// Search the rendered tree for external store reads, and check whether the
// stores were mutated in a concurrent event. Intentionally using an iterative
// loop instead of recursion so we can exit early.
var node = finishedWork;
while (true) {
if (node.flags & StoreConsistency) {
var updateQueue = node.updateQueue;
if (updateQueue !== null) {
var checks = updateQueue.stores;
if (checks !== null) {
for (var i = 0; i < checks.length; i++) {
var check = checks[i];
var getSnapshot = check.getSnapshot;
var renderedValue = check.value;
try {
if (!objectIs(getSnapshot(), renderedValue)) {
// Found an inconsistent store.
return false;
}
} catch (error) {
// If `getSnapshot` throws, return `false`. This will schedule
// a re-render, and the error will be rethrown during render.
return false;
}
}
}
}
}
var child = node.child;
if (node.subtreeFlags & StoreConsistency && child !== null) {
child.return = node;
node = child;
continue;
}
if (node === finishedWork) {
return true;
}
while (node.sibling === null) {
if (node.return === null || node.return === finishedWork) {
return true;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
} // Flow doesn't know this is unreachable, but eslint does
// eslint-disable-next-line no-unreachable
return true;
}
function markRootSuspended$1(root, suspendedLanes) {
// When suspending, we should always exclude lanes that were pinged or (more
// rarely, since we try to avoid it) updated during the render phase.
// TODO: Lol maybe there's a better way to factor this besides this
// obnoxiously named function :)
suspendedLanes = removeLanes(suspendedLanes, workInProgressRootPingedLanes);
suspendedLanes = removeLanes(suspendedLanes, workInProgressRootInterleavedUpdatedLanes);
markRootSuspended(root, suspendedLanes);
} // This is the entry point for synchronous tasks that don't go
// through Scheduler
function performSyncWorkOnRoot(root) {
{
syncNestedUpdateFlag();
}
if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
throw new Error('Should not already be working.');
}
flushPassiveEffects();
var lanes = getNextLanes(root, NoLanes);
if (!includesSomeLane(lanes, SyncLane)) {
// There's no remaining sync work left.
ensureRootIsScheduled(root, now());
return null;
}
var exitStatus = renderRootSync(root, lanes);
if (root.tag !== LegacyRoot && exitStatus === RootErrored) {
// If something threw an error, try rendering one more time. We'll render
// synchronously to block concurrent data mutations, and we'll includes
// all pending updates are included. If it still fails after the second
// attempt, we'll give up and commit the resulting tree.
var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root);
if (errorRetryLanes !== NoLanes) {
lanes = errorRetryLanes;
exitStatus = recoverFromConcurrentError(root, errorRetryLanes);
}
}
if (exitStatus === RootFatalErrored) {
var fatalError = workInProgressRootFatalError;
prepareFreshStack(root, NoLanes);
markRootSuspended$1(root, lanes);
ensureRootIsScheduled(root, now());
throw fatalError;
}
if (exitStatus === RootDidNotComplete) {
throw new Error('Root did not complete. This is a bug in React.');
} // We now have a consistent tree. Because this is a sync render, we
// will commit it even if something suspended.
var finishedWork = root.current.alternate;
root.finishedWork = finishedWork;
root.finishedLanes = lanes;
commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); // Before exiting, make sure there's a callback scheduled for the next
// pending level.
ensureRootIsScheduled(root, now());
return null;
}
function flushRoot(root, lanes) {
if (lanes !== NoLanes) {
markRootEntangled(root, mergeLanes(lanes, SyncLane));
ensureRootIsScheduled(root, now());
if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
resetRenderTimer();
flushSyncCallbacks();
}
}
}
function batchedUpdates$1(fn, a) {
var prevExecutionContext = executionContext;
executionContext |= BatchedContext;
try {
return fn(a);
} finally {
executionContext = prevExecutionContext; // If there were legacy sync updates, flush them at the end of the outer
// most batchedUpdates-like method.
if (executionContext === NoContext && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode.
!( ReactCurrentActQueue$1.isBatchingLegacy)) {
resetRenderTimer();
flushSyncCallbacksOnlyInLegacyMode();
}
}
}
function discreteUpdates(fn, a, b, c, d) {
var previousPriority = getCurrentUpdatePriority();
var prevTransition = ReactCurrentBatchConfig$3.transition;
try {
ReactCurrentBatchConfig$3.transition = null;
setCurrentUpdatePriority(DiscreteEventPriority);
return fn(a, b, c, d);
} finally {
setCurrentUpdatePriority(previousPriority);
ReactCurrentBatchConfig$3.transition = prevTransition;
if (executionContext === NoContext) {
resetRenderTimer();
}
}
} // Overload the definition to the two valid signatures.
// Warning, this opts-out of checking the function body.
// eslint-disable-next-line no-redeclare
function flushSync(fn) {
// In legacy mode, we flush pending passive effects at the beginning of the
// next event, not at the end of the previous one.
if (rootWithPendingPassiveEffects !== null && rootWithPendingPassiveEffects.tag === LegacyRoot && (executionContext & (RenderContext | CommitContext)) === NoContext) {
flushPassiveEffects();
}
var prevExecutionContext = executionContext;
executionContext |= BatchedContext;
var prevTransition = ReactCurrentBatchConfig$3.transition;
var previousPriority = getCurrentUpdatePriority();
try {
ReactCurrentBatchConfig$3.transition = null;
setCurrentUpdatePriority(DiscreteEventPriority);
if (fn) {
return fn();
} else {
return undefined;
}
} finally {
setCurrentUpdatePriority(previousPriority);
ReactCurrentBatchConfig$3.transition = prevTransition;
executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch.
// Note that this will happen even if batchedUpdates is higher up
// the stack.
if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
flushSyncCallbacks();
}
}
}
function isAlreadyRendering() {
// Used by the renderer to print a warning if certain APIs are called from
// the wrong context.
return (executionContext & (RenderContext | CommitContext)) !== NoContext;
}
function pushRenderLanes(fiber, lanes) {
push(subtreeRenderLanesCursor, subtreeRenderLanes, fiber);
subtreeRenderLanes = mergeLanes(subtreeRenderLanes, lanes);
workInProgressRootIncludedLanes = mergeLanes(workInProgressRootIncludedLanes, lanes);
}
function popRenderLanes(fiber) {
subtreeRenderLanes = subtreeRenderLanesCursor.current;
pop(subtreeRenderLanesCursor, fiber);
}
function prepareFreshStack(root, lanes) {
root.finishedWork = null;
root.finishedLanes = NoLanes;
var timeoutHandle = root.timeoutHandle;
if (timeoutHandle !== noTimeout) {
// The root previous suspended and scheduled a timeout to commit a fallback
// state. Now that we have additional work, cancel the timeout.
root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
cancelTimeout(timeoutHandle);
}
if (workInProgress !== null) {
var interruptedWork = workInProgress.return;
while (interruptedWork !== null) {
var current = interruptedWork.alternate;
unwindInterruptedWork(current, interruptedWork);
interruptedWork = interruptedWork.return;
}
}
workInProgressRoot = root;
var rootWorkInProgress = createWorkInProgress(root.current, null);
workInProgress = rootWorkInProgress;
workInProgressRootRenderLanes = subtreeRenderLanes = workInProgressRootIncludedLanes = lanes;
workInProgressRootExitStatus = RootInProgress;
workInProgressRootFatalError = null;
workInProgressRootSkippedLanes = NoLanes;
workInProgressRootInterleavedUpdatedLanes = NoLanes;
workInProgressRootPingedLanes = NoLanes;
workInProgressRootConcurrentErrors = null;
workInProgressRootRecoverableErrors = null;
finishQueueingConcurrentUpdates();
{
ReactStrictModeWarnings.discardPendingWarnings();
}
return rootWorkInProgress;
}
function handleError(root, thrownValue) {
do {
var erroredWork = workInProgress;
try {
// Reset module-level state that was set during the render phase.
resetContextDependencies();
resetHooksAfterThrow();
resetCurrentFiber(); // TODO: I found and added this missing line while investigating a
// separate issue. Write a regression test using string refs.
ReactCurrentOwner$2.current = null;
if (erroredWork === null || erroredWork.return === null) {
// Expected to be working on a non-root fiber. This is a fatal error
// because there's no ancestor that can handle it; the root is
// supposed to capture all errors that weren't caught by an error
// boundary.
workInProgressRootExitStatus = RootFatalErrored;
workInProgressRootFatalError = thrownValue; // Set `workInProgress` to null. This represents advancing to the next
// sibling, or the parent if there are no siblings. But since the root
// has no siblings nor a parent, we set it to null. Usually this is
// handled by `completeUnitOfWork` or `unwindWork`, but since we're
// intentionally not calling those, we need set it here.
// TODO: Consider calling `unwindWork` to pop the contexts.
workInProgress = null;
return;
}
if (enableProfilerTimer && erroredWork.mode & ProfileMode) {
// Record the time spent rendering before an error was thrown. This
// avoids inaccurate Profiler durations in the case of a
// suspended render.
stopProfilerTimerIfRunningAndRecordDelta(erroredWork, true);
}
if (enableSchedulingProfiler) {
markComponentRenderStopped();
if (thrownValue !== null && typeof thrownValue === 'object' && typeof thrownValue.then === 'function') {
var wakeable = thrownValue;
markComponentSuspended(erroredWork, wakeable, workInProgressRootRenderLanes);
} else {
markComponentErrored(erroredWork, thrownValue, workInProgressRootRenderLanes);
}
}
throwException(root, erroredWork.return, erroredWork, thrownValue, workInProgressRootRenderLanes);
completeUnitOfWork(erroredWork);
} catch (yetAnotherThrownValue) {
// Something in the return path also threw.
thrownValue = yetAnotherThrownValue;
if (workInProgress === erroredWork && erroredWork !== null) {
// If this boundary has already errored, then we had trouble processing
// the error. Bubble it to the next boundary.
erroredWork = erroredWork.return;
workInProgress = erroredWork;
} else {
erroredWork = workInProgress;
}
continue;
} // Return to the normal work loop.
return;
} while (true);
}
function pushDispatcher() {
var prevDispatcher = ReactCurrentDispatcher$2.current;
ReactCurrentDispatcher$2.current = ContextOnlyDispatcher;
if (prevDispatcher === null) {
// The React isomorphic package does not include a default dispatcher.
// Instead the first renderer will lazily attach one, in order to give
// nicer error messages.
return ContextOnlyDispatcher;
} else {
return prevDispatcher;
}
}
function popDispatcher(prevDispatcher) {
ReactCurrentDispatcher$2.current = prevDispatcher;
}
function markCommitTimeOfFallback() {
globalMostRecentFallbackTime = now();
}
function markSkippedUpdateLanes(lane) {
workInProgressRootSkippedLanes = mergeLanes(lane, workInProgressRootSkippedLanes);
}
function renderDidSuspend() {
if (workInProgressRootExitStatus === RootInProgress) {
workInProgressRootExitStatus = RootSuspended;
}
}
function renderDidSuspendDelayIfPossible() {
if (workInProgressRootExitStatus === RootInProgress || workInProgressRootExitStatus === RootSuspended || workInProgressRootExitStatus === RootErrored) {
workInProgressRootExitStatus = RootSuspendedWithDelay;
} // Check if there are updates that we skipped tree that might have unblocked
// this render.
if (workInProgressRoot !== null && (includesNonIdleWork(workInProgressRootSkippedLanes) || includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes))) {
// Mark the current render as suspended so that we switch to working on
// the updates that were skipped. Usually we only suspend at the end of
// the render phase.
// TODO: We should probably always mark the root as suspended immediately
// (inside this function), since by suspending at the end of the render
// phase introduces a potential mistake where we suspend lanes that were
// pinged or updated while we were rendering.
markRootSuspended$1(workInProgressRoot, workInProgressRootRenderLanes);
}
}
function renderDidError(error) {
if (workInProgressRootExitStatus !== RootSuspendedWithDelay) {
workInProgressRootExitStatus = RootErrored;
}
if (workInProgressRootConcurrentErrors === null) {
workInProgressRootConcurrentErrors = [error];
} else {
workInProgressRootConcurrentErrors.push(error);
}
} // Called during render to determine if anything has suspended.
// Returns false if we're not sure.
function renderHasNotSuspendedYet() {
// If something errored or completed, we can't really be sure,
// so those are false.
return workInProgressRootExitStatus === RootInProgress;
}
function renderRootSync(root, lanes) {
var prevExecutionContext = executionContext;
executionContext |= RenderContext;
var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack
// and prepare a fresh one. Otherwise we'll continue where we left off.
if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) {
{
if (isDevToolsPresent) {
var memoizedUpdaters = root.memoizedUpdaters;
if (memoizedUpdaters.size > 0) {
restorePendingUpdaters(root, workInProgressRootRenderLanes);
memoizedUpdaters.clear();
} // At this point, move Fibers that scheduled the upcoming work from the Map to the Set.
// If we bailout on this work, we'll move them back (like above).
// It's important to move them now in case the work spawns more work at the same priority with different updaters.
// That way we can keep the current update and future updates separate.
movePendingFibersToMemoized(root, lanes);
}
}
workInProgressTransitions = getTransitionsForLanes();
prepareFreshStack(root, lanes);
}
{
markRenderStarted(lanes);
}
do {
try {
workLoopSync();
break;
} catch (thrownValue) {
handleError(root, thrownValue);
}
} while (true);
resetContextDependencies();
executionContext = prevExecutionContext;
popDispatcher(prevDispatcher);
if (workInProgress !== null) {
// This is a sync render, so we should have finished the whole tree.
throw new Error('Cannot commit an incomplete root. This error is likely caused by a ' + 'bug in React. Please file an issue.');
}
{
markRenderStopped();
} // Set this to null to indicate there's no in-progress render.
workInProgressRoot = null;
workInProgressRootRenderLanes = NoLanes;
return workInProgressRootExitStatus;
} // The work loop is an extremely hot path. Tell Closure not to inline it.
/** @noinline */
function workLoopSync() {
// Already timed out, so perform work without checking if we need to yield.
while (workInProgress !== null) {
performUnitOfWork(workInProgress);
}
}
function renderRootConcurrent(root, lanes) {
var prevExecutionContext = executionContext;
executionContext |= RenderContext;
var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack
// and prepare a fresh one. Otherwise we'll continue where we left off.
if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) {
{
if (isDevToolsPresent) {
var memoizedUpdaters = root.memoizedUpdaters;
if (memoizedUpdaters.size > 0) {
restorePendingUpdaters(root, workInProgressRootRenderLanes);
memoizedUpdaters.clear();
} // At this point, move Fibers that scheduled the upcoming work from the Map to the Set.
// If we bailout on this work, we'll move them back (like above).
// It's important to move them now in case the work spawns more work at the same priority with different updaters.
// That way we can keep the current update and future updates separate.
movePendingFibersToMemoized(root, lanes);
}
}
workInProgressTransitions = getTransitionsForLanes();
resetRenderTimer();
prepareFreshStack(root, lanes);
}
{
markRenderStarted(lanes);
}
do {
try {
workLoopConcurrent();
break;
} catch (thrownValue) {
handleError(root, thrownValue);
}
} while (true);
resetContextDependencies();
popDispatcher(prevDispatcher);
executionContext = prevExecutionContext;
if (workInProgress !== null) {
// Still work remaining.
{
markRenderYielded();
}
return RootInProgress;
} else {
// Completed the tree.
{
markRenderStopped();
} // Set this to null to indicate there's no in-progress render.
workInProgressRoot = null;
workInProgressRootRenderLanes = NoLanes; // Return the final exit status.
return workInProgressRootExitStatus;
}
}
/** @noinline */
function workLoopConcurrent() {
// Perform work until Scheduler asks us to yield
while (workInProgress !== null && !shouldYield()) {
performUnitOfWork(workInProgress);
}
}
function performUnitOfWork(unitOfWork) {
// The current, flushed, state of this fiber is the alternate. Ideally
// nothing should rely on this, but relying on it here means that we don't
// need an additional field on the work in progress.
var current = unitOfWork.alternate;
setCurrentFiber(unitOfWork);
var next;
if ( (unitOfWork.mode & ProfileMode) !== NoMode) {
startProfilerTimer(unitOfWork);
next = beginWork$1(current, unitOfWork, subtreeRenderLanes);
stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
} else {
next = beginWork$1(current, unitOfWork, subtreeRenderLanes);
}
resetCurrentFiber();
unitOfWork.memoizedProps = unitOfWork.pendingProps;
if (next === null) {
// If this doesn't spawn new work, complete the current work.
completeUnitOfWork(unitOfWork);
} else {
workInProgress = next;
}
ReactCurrentOwner$2.current = null;
}
function completeUnitOfWork(unitOfWork) {
// Attempt to complete the current unit of work, then move to the next
// sibling. If there are no more siblings, return to the parent fiber.
var completedWork = unitOfWork;
do {
// The current, flushed, state of this fiber is the alternate. Ideally
// nothing should rely on this, but relying on it here means that we don't
// need an additional field on the work in progress.
var current = completedWork.alternate;
var returnFiber = completedWork.return; // Check if the work completed or if something threw.
if ((completedWork.flags & Incomplete) === NoFlags) {
setCurrentFiber(completedWork);
var next = void 0;
if ( (completedWork.mode & ProfileMode) === NoMode) {
next = completeWork(current, completedWork, subtreeRenderLanes);
} else {
startProfilerTimer(completedWork);
next = completeWork(current, completedWork, subtreeRenderLanes); // Update render duration assuming we didn't error.
stopProfilerTimerIfRunningAndRecordDelta(completedWork, false);
}
resetCurrentFiber();
if (next !== null) {
// Completing this fiber spawned new work. Work on that next.
workInProgress = next;
return;
}
} else {
// This fiber did not complete because something threw. Pop values off
// the stack without entering the complete phase. If this is a boundary,
// capture values if possible.
var _next = unwindWork(current, completedWork); // Because this fiber did not complete, don't reset its lanes.
if (_next !== null) {
// If completing this work spawned new work, do that next. We'll come
// back here again.
// Since we're restarting, remove anything that is not a host effect
// from the effect tag.
_next.flags &= HostEffectMask;
workInProgress = _next;
return;
}
if ( (completedWork.mode & ProfileMode) !== NoMode) {
// Record the render duration for the fiber that errored.
stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); // Include the time spent working on failed children before continuing.
var actualDuration = completedWork.actualDuration;
var child = completedWork.child;
while (child !== null) {
actualDuration += child.actualDuration;
child = child.sibling;
}
completedWork.actualDuration = actualDuration;
}
if (returnFiber !== null) {
// Mark the parent fiber as incomplete and clear its subtree flags.
returnFiber.flags |= Incomplete;
returnFiber.subtreeFlags = NoFlags;
returnFiber.deletions = null;
} else {
// We've unwound all the way to the root.
workInProgressRootExitStatus = RootDidNotComplete;
workInProgress = null;
return;
}
}
var siblingFiber = completedWork.sibling;
if (siblingFiber !== null) {
// If there is more work to do in this returnFiber, do that next.
workInProgress = siblingFiber;
return;
} // Otherwise, return to the parent
completedWork = returnFiber; // Update the next thing we're working on in case something throws.
workInProgress = completedWork;
} while (completedWork !== null); // We've reached the root.
if (workInProgressRootExitStatus === RootInProgress) {
workInProgressRootExitStatus = RootCompleted;
}
}
function commitRoot(root, recoverableErrors, transitions) {
// TODO: This no longer makes any sense. We already wrap the mutation and
// layout phases. Should be able to remove.
var previousUpdateLanePriority = getCurrentUpdatePriority();
var prevTransition = ReactCurrentBatchConfig$3.transition;
try {
ReactCurrentBatchConfig$3.transition = null;
setCurrentUpdatePriority(DiscreteEventPriority);
commitRootImpl(root, recoverableErrors, transitions, previousUpdateLanePriority);
} finally {
ReactCurrentBatchConfig$3.transition = prevTransition;
setCurrentUpdatePriority(previousUpdateLanePriority);
}
return null;
}
function commitRootImpl(root, recoverableErrors, transitions, renderPriorityLevel) {
do {
// `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which
// means `flushPassiveEffects` will sometimes result in additional
// passive effects. So we need to keep flushing in a loop until there are
// no more pending effects.
// TODO: Might be better if `flushPassiveEffects` did not automatically
// flush synchronous work at the end, to avoid factoring hazards like this.
flushPassiveEffects();
} while (rootWithPendingPassiveEffects !== null);
flushRenderPhaseStrictModeWarningsInDEV();
if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
throw new Error('Should not already be working.');
}
var finishedWork = root.finishedWork;
var lanes = root.finishedLanes;
{
markCommitStarted(lanes);
}
if (finishedWork === null) {
{
markCommitStopped();
}
return null;
} else {
{
if (lanes === NoLanes) {
error('root.finishedLanes should not be empty during a commit. This is a ' + 'bug in React.');
}
}
}
root.finishedWork = null;
root.finishedLanes = NoLanes;
if (finishedWork === root.current) {
throw new Error('Cannot commit the same tree as before. This error is likely caused by ' + 'a bug in React. Please file an issue.');
} // commitRoot never returns a continuation; it always finishes synchronously.
// So we can clear these now to allow a new callback to be scheduled.
root.callbackNode = null;
root.callbackPriority = NoLane; // Update the first and last pending times on this root. The new first
// pending time is whatever is left on the root fiber.
var remainingLanes = mergeLanes(finishedWork.lanes, finishedWork.childLanes);
markRootFinished(root, remainingLanes);
if (root === workInProgressRoot) {
// We can reset these now that they are finished.
workInProgressRoot = null;
workInProgress = null;
workInProgressRootRenderLanes = NoLanes;
} // If there are pending passive effects, schedule a callback to process them.
// Do this as early as possible, so it is queued before anything else that
// might get scheduled in the commit phase. (See #16714.)
// TODO: Delete all other places that schedule the passive effect callback
// They're redundant.
if ((finishedWork.subtreeFlags & PassiveMask) !== NoFlags || (finishedWork.flags & PassiveMask) !== NoFlags) {
if (!rootDoesHavePassiveEffects) {
rootDoesHavePassiveEffects = true;
// to store it in pendingPassiveTransitions until they get processed
// We need to pass this through as an argument to commitRoot
// because workInProgressTransitions might have changed between
// the previous render and commit if we throttle the commit
// with setTimeout
pendingPassiveTransitions = transitions;
scheduleCallback$1(NormalPriority, function () {
flushPassiveEffects(); // This render triggered passive effects: release the root cache pool
// *after* passive effects fire to avoid freeing a cache pool that may
// be referenced by a node in the tree (HostRoot, Cache boundary etc)
return null;
});
}
} // Check if there are any effects in the whole tree.
// TODO: This is left over from the effect list implementation, where we had
// to check for the existence of `firstEffect` to satisfy Flow. I think the
// only other reason this optimization exists is because it affects profiling.
// Reconsider whether this is necessary.
var subtreeHasEffects = (finishedWork.subtreeFlags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags;
var rootHasEffect = (finishedWork.flags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags;
if (subtreeHasEffects || rootHasEffect) {
var prevTransition = ReactCurrentBatchConfig$3.transition;
ReactCurrentBatchConfig$3.transition = null;
var previousPriority = getCurrentUpdatePriority();
setCurrentUpdatePriority(DiscreteEventPriority);
var prevExecutionContext = executionContext;
executionContext |= CommitContext; // Reset this to null before calling lifecycles
ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass
// of the effect list for each phase: all mutation effects come before all
// layout effects, and so on.
// The first phase a "before mutation" phase. We use this phase to read the
// state of the host tree right before we mutate it. This is where
// getSnapshotBeforeUpdate is called.
var shouldFireAfterActiveInstanceBlur = commitBeforeMutationEffects(root, finishedWork);
{
// Mark the current commit time to be shared by all Profilers in this
// batch. This enables them to be grouped later.
recordCommitTime();
}
commitMutationEffects(root, finishedWork, lanes);
resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after
// the mutation phase, so that the previous tree is still current during
// componentWillUnmount, but before the layout phase, so that the finished
// work is current during componentDidMount/Update.
root.current = finishedWork; // The next phase is the layout phase, where we call effects that read
{
markLayoutEffectsStarted(lanes);
}
commitLayoutEffects(finishedWork, root, lanes);
{
markLayoutEffectsStopped();
}
// opportunity to paint.
requestPaint();
executionContext = prevExecutionContext; // Reset the priority to the previous non-sync value.
setCurrentUpdatePriority(previousPriority);
ReactCurrentBatchConfig$3.transition = prevTransition;
} else {
// No effects.
root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were
// no effects.
// TODO: Maybe there's a better way to report this.
{
recordCommitTime();
}
}
var rootDidHavePassiveEffects = rootDoesHavePassiveEffects;
if (rootDoesHavePassiveEffects) {
// This commit has passive effects. Stash a reference to them. But don't
// schedule a callback until after flushing layout work.
rootDoesHavePassiveEffects = false;
rootWithPendingPassiveEffects = root;
pendingPassiveEffectsLanes = lanes;
} else {
{
nestedPassiveUpdateCount = 0;
rootWithPassiveNestedUpdates = null;
}
} // Read this again, since an effect might have updated it
remainingLanes = root.pendingLanes; // Check if there's remaining work on this root
// TODO: This is part of the `componentDidCatch` implementation. Its purpose
// is to detect whether something might have called setState inside
// `componentDidCatch`. The mechanism is known to be flawed because `setState`
// inside `componentDidCatch` is itself flawed — that's why we recommend
// `getDerivedStateFromError` instead. However, it could be improved by
// checking if remainingLanes includes Sync work, instead of whether there's
// any work remaining at all (which would also include stuff like Suspense
// retries or transitions). It's been like this for a while, though, so fixing
// it probably isn't that urgent.
if (remainingLanes === NoLanes) {
// If there's no remaining work, we can clear the set of already failed
// error boundaries.
legacyErrorBoundariesThatAlreadyFailed = null;
}
{
if (!rootDidHavePassiveEffects) {
commitDoubleInvokeEffectsInDEV(root.current, false);
}
}
onCommitRoot(finishedWork.stateNode, renderPriorityLevel);
{
if (isDevToolsPresent) {
root.memoizedUpdaters.clear();
}
}
{
onCommitRoot$1();
} // Always call this before exiting `commitRoot`, to ensure that any
// additional work on this root is scheduled.
ensureRootIsScheduled(root, now());
if (recoverableErrors !== null) {
// There were errors during this render, but recovered from them without
// needing to surface it to the UI. We log them here.
var onRecoverableError = root.onRecoverableError;
for (var i = 0; i < recoverableErrors.length; i++) {
var recoverableError = recoverableErrors[i];
var componentStack = recoverableError.stack;
var digest = recoverableError.digest;
onRecoverableError(recoverableError.value, {
componentStack: componentStack,
digest: digest
});
}
}
if (hasUncaughtError) {
hasUncaughtError = false;
var error$1 = firstUncaughtError;
firstUncaughtError = null;
throw error$1;
} // If the passive effects are the result of a discrete render, flush them
// synchronously at the end of the current task so that the result is
// immediately observable. Otherwise, we assume that they are not
// order-dependent and do not need to be observed by external systems, so we
// can wait until after paint.
// TODO: We can optimize this by not scheduling the callback earlier. Since we
// currently schedule the callback in multiple places, will wait until those
// are consolidated.
if (includesSomeLane(pendingPassiveEffectsLanes, SyncLane) && root.tag !== LegacyRoot) {
flushPassiveEffects();
} // Read this again, since a passive effect might have updated it
remainingLanes = root.pendingLanes;
if (includesSomeLane(remainingLanes, SyncLane)) {
{
markNestedUpdateScheduled();
} // Count the number of times the root synchronously re-renders without
// finishing. If there are too many, it indicates an infinite update loop.
if (root === rootWithNestedUpdates) {
nestedUpdateCount++;
} else {
nestedUpdateCount = 0;
rootWithNestedUpdates = root;
}
} else {
nestedUpdateCount = 0;
} // If layout work was scheduled, flush it now.
flushSyncCallbacks();
{
markCommitStopped();
}
return null;
}
function flushPassiveEffects() {
// Returns whether passive effects were flushed.
// TODO: Combine this check with the one in flushPassiveEFfectsImpl. We should
// probably just combine the two functions. I believe they were only separate
// in the first place because we used to wrap it with
// `Scheduler.runWithPriority`, which accepts a function. But now we track the
// priority within React itself, so we can mutate the variable directly.
if (rootWithPendingPassiveEffects !== null) {
var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes);
var priority = lowerEventPriority(DefaultEventPriority, renderPriority);
var prevTransition = ReactCurrentBatchConfig$3.transition;
var previousPriority = getCurrentUpdatePriority();
try {
ReactCurrentBatchConfig$3.transition = null;
setCurrentUpdatePriority(priority);
return flushPassiveEffectsImpl();
} finally {
setCurrentUpdatePriority(previousPriority);
ReactCurrentBatchConfig$3.transition = prevTransition; // Once passive effects have run for the tree - giving components a
}
}
return false;
}
function enqueuePendingPassiveProfilerEffect(fiber) {
{
pendingPassiveProfilerEffects.push(fiber);
if (!rootDoesHavePassiveEffects) {
rootDoesHavePassiveEffects = true;
scheduleCallback$1(NormalPriority, function () {
flushPassiveEffects();
return null;
});
}
}
}
function flushPassiveEffectsImpl() {
if (rootWithPendingPassiveEffects === null) {
return false;
} // Cache and clear the transitions flag
var transitions = pendingPassiveTransitions;
pendingPassiveTransitions = null;
var root = rootWithPendingPassiveEffects;
var lanes = pendingPassiveEffectsLanes;
rootWithPendingPassiveEffects = null; // TODO: This is sometimes out of sync with rootWithPendingPassiveEffects.
// Figure out why and fix it. It's not causing any known issues (probably
// because it's only used for profiling), but it's a refactor hazard.
pendingPassiveEffectsLanes = NoLanes;
if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
throw new Error('Cannot flush passive effects while already rendering.');
}
{
isFlushingPassiveEffects = true;
didScheduleUpdateDuringPassiveEffects = false;
}
{
markPassiveEffectsStarted(lanes);
}
var prevExecutionContext = executionContext;
executionContext |= CommitContext;
commitPassiveUnmountEffects(root.current);
commitPassiveMountEffects(root, root.current, lanes, transitions); // TODO: Move to commitPassiveMountEffects
{
var profilerEffects = pendingPassiveProfilerEffects;
pendingPassiveProfilerEffects = [];
for (var i = 0; i < profilerEffects.length; i++) {
var _fiber = profilerEffects[i];
commitPassiveEffectDurations(root, _fiber);
}
}
{
markPassiveEffectsStopped();
}
{
commitDoubleInvokeEffectsInDEV(root.current, true);
}
executionContext = prevExecutionContext;
flushSyncCallbacks();
{
// If additional passive effects were scheduled, increment a counter. If this
// exceeds the limit, we'll fire a warning.
if (didScheduleUpdateDuringPassiveEffects) {
if (root === rootWithPassiveNestedUpdates) {
nestedPassiveUpdateCount++;
} else {
nestedPassiveUpdateCount = 0;
rootWithPassiveNestedUpdates = root;
}
} else {
nestedPassiveUpdateCount = 0;
}
isFlushingPassiveEffects = false;
didScheduleUpdateDuringPassiveEffects = false;
} // TODO: Move to commitPassiveMountEffects
onPostCommitRoot(root);
{
var stateNode = root.current.stateNode;
stateNode.effectDuration = 0;
stateNode.passiveEffectDuration = 0;
}
return true;
}
function isAlreadyFailedLegacyErrorBoundary(instance) {
return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
}
function markLegacyErrorBoundaryAsFailed(instance) {
if (legacyErrorBoundariesThatAlreadyFailed === null) {
legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
} else {
legacyErrorBoundariesThatAlreadyFailed.add(instance);
}
}
function prepareToThrowUncaughtError(error) {
if (!hasUncaughtError) {
hasUncaughtError = true;
firstUncaughtError = error;
}
}
var onUncaughtError = prepareToThrowUncaughtError;
function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {
var errorInfo = createCapturedValueAtFiber(error, sourceFiber);
var update = createRootErrorUpdate(rootFiber, errorInfo, SyncLane);
var root = enqueueUpdate(rootFiber, update, SyncLane);
var eventTime = requestEventTime();
if (root !== null) {
markRootUpdated(root, SyncLane, eventTime);
ensureRootIsScheduled(root, eventTime);
}
}
function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error$1) {
{
reportUncaughtErrorInDEV(error$1);
setIsRunningInsertionEffect(false);
}
if (sourceFiber.tag === HostRoot) {
// Error was thrown at the root. There is no parent, so the root
// itself should capture it.
captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error$1);
return;
}
var fiber = null;
{
fiber = nearestMountedAncestor;
}
while (fiber !== null) {
if (fiber.tag === HostRoot) {
captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error$1);
return;
} else if (fiber.tag === ClassComponent) {
var ctor = fiber.type;
var instance = fiber.stateNode;
if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {
var errorInfo = createCapturedValueAtFiber(error$1, sourceFiber);
var update = createClassErrorUpdate(fiber, errorInfo, SyncLane);
var root = enqueueUpdate(fiber, update, SyncLane);
var eventTime = requestEventTime();
if (root !== null) {
markRootUpdated(root, SyncLane, eventTime);
ensureRootIsScheduled(root, eventTime);
}
return;
}
}
fiber = fiber.return;
}
{
// TODO: Until we re-land skipUnmountedBoundaries (see #20147), this warning
// will fire for errors that are thrown by destroy functions inside deleted
// trees. What it should instead do is propagate the error to the parent of
// the deleted tree. In the meantime, do not add this warning to the
// allowlist; this is only for our internal use.
error('Internal React error: Attempted to capture a commit phase error ' + 'inside a detached tree. This indicates a bug in React. Likely ' + 'causes include deleting the same fiber more than once, committing an ' + 'already-finished tree, or an inconsistent return pointer.\n\n' + 'Error message:\n\n%s', error$1);
}
}
function pingSuspendedRoot(root, wakeable, pingedLanes) {
var pingCache = root.pingCache;
if (pingCache !== null) {
// The wakeable resolved, so we no longer need to memoize, because it will
// never be thrown again.
pingCache.delete(wakeable);
}
var eventTime = requestEventTime();
markRootPinged(root, pingedLanes);
warnIfSuspenseResolutionNotWrappedWithActDEV(root);
if (workInProgressRoot === root && isSubsetOfLanes(workInProgressRootRenderLanes, pingedLanes)) {
// Received a ping at the same priority level at which we're currently
// rendering. We might want to restart this render. This should mirror
// the logic of whether or not a root suspends once it completes.
// TODO: If we're rendering sync either due to Sync, Batched or expired,
// we should probably never restart.
// If we're suspended with delay, or if it's a retry, we'll always suspend
// so we can always restart.
if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && includesOnlyRetries(workInProgressRootRenderLanes) && now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) {
// Restart from the root.
prepareFreshStack(root, NoLanes);
} else {
// Even though we can't restart right now, we might get an
// opportunity later. So we mark this render as having a ping.
workInProgressRootPingedLanes = mergeLanes(workInProgressRootPingedLanes, pingedLanes);
}
}
ensureRootIsScheduled(root, eventTime);
}
function retryTimedOutBoundary(boundaryFiber, retryLane) {
// The boundary fiber (a Suspense component or SuspenseList component)
// previously was rendered in its fallback state. One of the promises that
// suspended it has resolved, which means at least part of the tree was
// likely unblocked. Try rendering again, at a new lanes.
if (retryLane === NoLane) {
// TODO: Assign this to `suspenseState.retryLane`? to avoid
// unnecessary entanglement?
retryLane = requestRetryLane(boundaryFiber);
} // TODO: Special case idle priority?
var eventTime = requestEventTime();
var root = enqueueConcurrentRenderForLane(boundaryFiber, retryLane);
if (root !== null) {
markRootUpdated(root, retryLane, eventTime);
ensureRootIsScheduled(root, eventTime);
}
}
function retryDehydratedSuspenseBoundary(boundaryFiber) {
var suspenseState = boundaryFiber.memoizedState;
var retryLane = NoLane;
if (suspenseState !== null) {
retryLane = suspenseState.retryLane;
}
retryTimedOutBoundary(boundaryFiber, retryLane);
}
function resolveRetryWakeable(boundaryFiber, wakeable) {
var retryLane = NoLane; // Default
var retryCache;
switch (boundaryFiber.tag) {
case SuspenseComponent:
retryCache = boundaryFiber.stateNode;
var suspenseState = boundaryFiber.memoizedState;
if (suspenseState !== null) {
retryLane = suspenseState.retryLane;
}
break;
case SuspenseListComponent:
retryCache = boundaryFiber.stateNode;
break;
default:
throw new Error('Pinged unknown suspense boundary type. ' + 'This is probably a bug in React.');
}
if (retryCache !== null) {
// The wakeable resolved, so we no longer need to memoize, because it will
// never be thrown again.
retryCache.delete(wakeable);
}
retryTimedOutBoundary(boundaryFiber, retryLane);
} // Computes the next Just Noticeable Difference (JND) boundary.
// The theory is that a person can't tell the difference between small differences in time.
// Therefore, if we wait a bit longer than necessary that won't translate to a noticeable
// difference in the experience. However, waiting for longer might mean that we can avoid
// showing an intermediate loading state. The longer we have already waited, the harder it
// is to tell small differences in time. Therefore, the longer we've already waited,
// the longer we can wait additionally. At some point we have to give up though.
// We pick a train model where the next boundary commits at a consistent schedule.
// These particular numbers are vague estimates. We expect to adjust them based on research.
function jnd(timeElapsed) {
return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3000 ? 3000 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960;
}
function checkForNestedUpdates() {
if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
nestedUpdateCount = 0;
rootWithNestedUpdates = null;
throw new Error('Maximum update depth exceeded. This can happen when a component ' + 'repeatedly calls setState inside componentWillUpdate or ' + 'componentDidUpdate. React limits the number of nested updates to ' + 'prevent infinite loops.');
}
{
if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) {
nestedPassiveUpdateCount = 0;
rootWithPassiveNestedUpdates = null;
error('Maximum update depth exceeded. This can happen when a component ' + "calls setState inside useEffect, but useEffect either doesn't " + 'have a dependency array, or one of the dependencies changes on ' + 'every render.');
}
}
}
function flushRenderPhaseStrictModeWarningsInDEV() {
{
ReactStrictModeWarnings.flushLegacyContextWarning();
{
ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
}
}
}
function commitDoubleInvokeEffectsInDEV(fiber, hasPassiveEffects) {
{
// TODO (StrictEffects) Should we set a marker on the root if it contains strict effects
// so we don't traverse unnecessarily? similar to subtreeFlags but just at the root level.
// Maybe not a big deal since this is DEV only behavior.
setCurrentFiber(fiber);
invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectUnmountInDEV);
if (hasPassiveEffects) {
invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectUnmountInDEV);
}
invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectMountInDEV);
if (hasPassiveEffects) {
invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectMountInDEV);
}
resetCurrentFiber();
}
}
function invokeEffectsInDev(firstChild, fiberFlags, invokeEffectFn) {
{
// We don't need to re-check StrictEffectsMode here.
// This function is only called if that check has already passed.
var current = firstChild;
var subtreeRoot = null;
while (current !== null) {
var primarySubtreeFlag = current.subtreeFlags & fiberFlags;
if (current !== subtreeRoot && current.child !== null && primarySubtreeFlag !== NoFlags) {
current = current.child;
} else {
if ((current.flags & fiberFlags) !== NoFlags) {
invokeEffectFn(current);
}
if (current.sibling !== null) {
current = current.sibling;
} else {
current = subtreeRoot = current.return;
}
}
}
}
}
var didWarnStateUpdateForNotYetMountedComponent = null;
function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) {
{
if ((executionContext & RenderContext) !== NoContext) {
// We let the other warning about render phase updates deal with this one.
return;
}
if (!(fiber.mode & ConcurrentMode)) {
return;
}
var tag = fiber.tag;
if (tag !== IndeterminateComponent && tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent) {
// Only warn for user-defined components, not internal ones like Suspense.
return;
} // We show the whole stack but dedupe on the top component's name because
// the problematic code almost always lies inside that component.
var componentName = getComponentNameFromFiber(fiber) || 'ReactComponent';
if (didWarnStateUpdateForNotYetMountedComponent !== null) {
if (didWarnStateUpdateForNotYetMountedComponent.has(componentName)) {
return;
}
didWarnStateUpdateForNotYetMountedComponent.add(componentName);
} else {
didWarnStateUpdateForNotYetMountedComponent = new Set([componentName]);
}
var previousFiber = current;
try {
setCurrentFiber(fiber);
error("Can't perform a React state update on a component that hasn't mounted yet. " + 'This indicates that you have a side-effect in your render function that ' + 'asynchronously later calls tries to update the component. Move this work to ' + 'useEffect instead.');
} finally {
if (previousFiber) {
setCurrentFiber(fiber);
} else {
resetCurrentFiber();
}
}
}
}
var beginWork$1;
{
var dummyFiber = null;
beginWork$1 = function (current, unitOfWork, lanes) {
// If a component throws an error, we replay it again in a synchronously
// dispatched event, so that the debugger will treat it as an uncaught
// error See ReactErrorUtils for more information.
// Before entering the begin phase, copy the work-in-progress onto a dummy
// fiber. If beginWork throws, we'll use this to reset the state.
var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork);
try {
return beginWork(current, unitOfWork, lanes);
} catch (originalError) {
if (didSuspendOrErrorWhileHydratingDEV() || originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') {
// Don't replay promises.
// Don't replay errors if we are hydrating and have already suspended or handled an error
throw originalError;
} // Keep this code in sync with handleError; any changes here must have
// corresponding changes there.
resetContextDependencies();
resetHooksAfterThrow(); // Don't reset current debug fiber, since we're about to work on the
// same fiber again.
// Unwind the failed stack frame
unwindInterruptedWork(current, unitOfWork); // Restore the original properties of the fiber.
assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy);
if ( unitOfWork.mode & ProfileMode) {
// Reset the profiler timer.
startProfilerTimer(unitOfWork);
} // Run beginWork again.
invokeGuardedCallback(null, beginWork, null, current, unitOfWork, lanes);
if (hasCaughtError()) {
var replayError = clearCaughtError();
if (typeof replayError === 'object' && replayError !== null && replayError._suppressLogging && typeof originalError === 'object' && originalError !== null && !originalError._suppressLogging) {
// If suppressed, let the flag carry over to the original error which is the one we'll rethrow.
originalError._suppressLogging = true;
}
} // We always throw the original error in case the second render pass is not idempotent.
// This can happen if a memoized function or CommonJS module doesn't throw after first invocation.
throw originalError;
}
};
}
var didWarnAboutUpdateInRender = false;
var didWarnAboutUpdateInRenderForAnotherComponent;
{
didWarnAboutUpdateInRenderForAnotherComponent = new Set();
}
function warnAboutRenderPhaseUpdatesInDEV(fiber) {
{
if (isRendering && !getIsUpdatingOpaqueValueInRenderPhaseInDEV()) {
switch (fiber.tag) {
case FunctionComponent:
case ForwardRef:
case SimpleMemoComponent:
{
var renderingComponentName = workInProgress && getComponentNameFromFiber(workInProgress) || 'Unknown'; // Dedupe by the rendering component because it's the one that needs to be fixed.
var dedupeKey = renderingComponentName;
if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) {
didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey);
var setStateComponentName = getComponentNameFromFiber(fiber) || 'Unknown';
error('Cannot update a component (`%s`) while rendering a ' + 'different component (`%s`). To locate the bad setState() call inside `%s`, ' + 'follow the stack trace as described in https://reactjs.org/link/setstate-in-render', setStateComponentName, renderingComponentName, renderingComponentName);
}
break;
}
case ClassComponent:
{
if (!didWarnAboutUpdateInRender) {
error('Cannot update during an existing state transition (such as ' + 'within `render`). Render methods should be a pure ' + 'function of props and state.');
didWarnAboutUpdateInRender = true;
}
break;
}
}
}
}
}
function restorePendingUpdaters(root, lanes) {
{
if (isDevToolsPresent) {
var memoizedUpdaters = root.memoizedUpdaters;
memoizedUpdaters.forEach(function (schedulingFiber) {
addFiberToLanesMap(root, schedulingFiber, lanes);
}); // This function intentionally does not clear memoized updaters.
// Those may still be relevant to the current commit
// and a future one (e.g. Suspense).
}
}
}
var fakeActCallbackNode = {};
function scheduleCallback$1(priorityLevel, callback) {
{
// If we're currently inside an `act` scope, bypass Scheduler and push to
// the `act` queue instead.
var actQueue = ReactCurrentActQueue$1.current;
if (actQueue !== null) {
actQueue.push(callback);
return fakeActCallbackNode;
} else {
return scheduleCallback(priorityLevel, callback);
}
}
}
function cancelCallback$1(callbackNode) {
if ( callbackNode === fakeActCallbackNode) {
return;
} // In production, always call Scheduler. This function will be stripped out.
return cancelCallback(callbackNode);
}
function shouldForceFlushFallbacksInDEV() {
// Never force flush in production. This function should get stripped out.
return ReactCurrentActQueue$1.current !== null;
}
function warnIfUpdatesNotWrappedWithActDEV(fiber) {
{
if (fiber.mode & ConcurrentMode) {
if (!isConcurrentActEnvironment()) {
// Not in an act environment. No need to warn.
return;
}
} else {
// Legacy mode has additional cases where we suppress a warning.
if (!isLegacyActEnvironment()) {
// Not in an act environment. No need to warn.
return;
}
if (executionContext !== NoContext) {
// Legacy mode doesn't warn if the update is batched, i.e.
// batchedUpdates or flushSync.
return;
}
if (fiber.tag !== FunctionComponent && fiber.tag !== ForwardRef && fiber.tag !== SimpleMemoComponent) {
// For backwards compatibility with pre-hooks code, legacy mode only
// warns for updates that originate from a hook.
return;
}
}
if (ReactCurrentActQueue$1.current === null) {
var previousFiber = current;
try {
setCurrentFiber(fiber);
error('An update to %s inside a test was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be ' + 'wrapped into act(...):\n\n' + 'act(() => {\n' + ' /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://reactjs.org/link/wrap-tests-with-act', getComponentNameFromFiber(fiber));
} finally {
if (previousFiber) {
setCurrentFiber(fiber);
} else {
resetCurrentFiber();
}
}
}
}
}
function warnIfSuspenseResolutionNotWrappedWithActDEV(root) {
{
if (root.tag !== LegacyRoot && isConcurrentActEnvironment() && ReactCurrentActQueue$1.current === null) {
error('A suspended resource finished loading inside a test, but the event ' + 'was not wrapped in act(...).\n\n' + 'When testing, code that resolves suspended data should be wrapped ' + 'into act(...):\n\n' + 'act(() => {\n' + ' /* finish loading suspended data */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://reactjs.org/link/wrap-tests-with-act');
}
}
}
function setIsRunningInsertionEffect(isRunning) {
{
isRunningInsertionEffect = isRunning;
}
}
/* eslint-disable react-internal/prod-error-codes */
var resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below.
var failedBoundaries = null;
var setRefreshHandler = function (handler) {
{
resolveFamily = handler;
}
};
function resolveFunctionForHotReloading(type) {
{
if (resolveFamily === null) {
// Hot reloading is disabled.
return type;
}
var family = resolveFamily(type);
if (family === undefined) {
return type;
} // Use the latest known implementation.
return family.current;
}
}
function resolveClassForHotReloading(type) {
// No implementation differences.
return resolveFunctionForHotReloading(type);
}
function resolveForwardRefForHotReloading(type) {
{
if (resolveFamily === null) {
// Hot reloading is disabled.
return type;
}
var family = resolveFamily(type);
if (family === undefined) {
// Check if we're dealing with a real forwardRef. Don't want to crash early.
if (type !== null && type !== undefined && typeof type.render === 'function') {
// ForwardRef is special because its resolved .type is an object,
// but it's possible that we only have its inner render function in the map.
// If that inner render function is different, we'll build a new forwardRef type.
var currentRender = resolveFunctionForHotReloading(type.render);
if (type.render !== currentRender) {
var syntheticType = {
$$typeof: REACT_FORWARD_REF_TYPE,
render: currentRender
};
if (type.displayName !== undefined) {
syntheticType.displayName = type.displayName;
}
return syntheticType;
}
}
return type;
} // Use the latest known implementation.
return family.current;
}
}
function isCompatibleFamilyForHotReloading(fiber, element) {
{
if (resolveFamily === null) {
// Hot reloading is disabled.
return false;
}
var prevType = fiber.elementType;
var nextType = element.type; // If we got here, we know types aren't === equal.
var needsCompareFamilies = false;
var $$typeofNextType = typeof nextType === 'object' && nextType !== null ? nextType.$$typeof : null;
switch (fiber.tag) {
case ClassComponent:
{
if (typeof nextType === 'function') {
needsCompareFamilies = true;
}
break;
}
case FunctionComponent:
{
if (typeof nextType === 'function') {
needsCompareFamilies = true;
} else if ($$typeofNextType === REACT_LAZY_TYPE) {
// We don't know the inner type yet.
// We're going to assume that the lazy inner type is stable,
// and so it is sufficient to avoid reconciling it away.
// We're not going to unwrap or actually use the new lazy type.
needsCompareFamilies = true;
}
break;
}
case ForwardRef:
{
if ($$typeofNextType === REACT_FORWARD_REF_TYPE) {
needsCompareFamilies = true;
} else if ($$typeofNextType === REACT_LAZY_TYPE) {
needsCompareFamilies = true;
}
break;
}
case MemoComponent:
case SimpleMemoComponent:
{
if ($$typeofNextType === REACT_MEMO_TYPE) {
// TODO: if it was but can no longer be simple,
// we shouldn't set this.
needsCompareFamilies = true;
} else if ($$typeofNextType === REACT_LAZY_TYPE) {
needsCompareFamilies = true;
}
break;
}
default:
return false;
} // Check if both types have a family and it's the same one.
if (needsCompareFamilies) {
// Note: memo() and forwardRef() we'll compare outer rather than inner type.
// This means both of them need to be registered to preserve state.
// If we unwrapped and compared the inner types for wrappers instead,
// then we would risk falsely saying two separate memo(Foo)
// calls are equivalent because they wrap the same Foo function.
var prevFamily = resolveFamily(prevType);
if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) {
return true;
}
}
return false;
}
}
function markFailedErrorBoundaryForHotReloading(fiber) {
{
if (resolveFamily === null) {
// Hot reloading is disabled.
return;
}
if (typeof WeakSet !== 'function') {
return;
}
if (failedBoundaries === null) {
failedBoundaries = new WeakSet();
}
failedBoundaries.add(fiber);
}
}
var scheduleRefresh = function (root, update) {
{
if (resolveFamily === null) {
// Hot reloading is disabled.
return;
}
var staleFamilies = update.staleFamilies,
updatedFamilies = update.updatedFamilies;
flushPassiveEffects();
flushSync(function () {
scheduleFibersWithFamiliesRecursively(root.current, updatedFamilies, staleFamilies);
});
}
};
var scheduleRoot = function (root, element) {
{
if (root.context !== emptyContextObject) {
// Super edge case: root has a legacy _renderSubtree context
// but we don't know the parentComponent so we can't pass it.
// Just ignore. We'll delete this with _renderSubtree code path later.
return;
}
flushPassiveEffects();
flushSync(function () {
updateContainer(element, root, null, null);
});
}
};
function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) {
{
var alternate = fiber.alternate,
child = fiber.child,
sibling = fiber.sibling,
tag = fiber.tag,
type = fiber.type;
var candidateType = null;
switch (tag) {
case FunctionComponent:
case SimpleMemoComponent:
case ClassComponent:
candidateType = type;
break;
case ForwardRef:
candidateType = type.render;
break;
}
if (resolveFamily === null) {
throw new Error('Expected resolveFamily to be set during hot reload.');
}
var needsRender = false;
var needsRemount = false;
if (candidateType !== null) {
var family = resolveFamily(candidateType);
if (family !== undefined) {
if (staleFamilies.has(family)) {
needsRemount = true;
} else if (updatedFamilies.has(family)) {
if (tag === ClassComponent) {
needsRemount = true;
} else {
needsRender = true;
}
}
}
}
if (failedBoundaries !== null) {
if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) {
needsRemount = true;
}
}
if (needsRemount) {
fiber._debugNeedsRemount = true;
}
if (needsRemount || needsRender) {
var _root = enqueueConcurrentRenderForLane(fiber, SyncLane);
if (_root !== null) {
scheduleUpdateOnFiber(_root, fiber, SyncLane, NoTimestamp);
}
}
if (child !== null && !needsRemount) {
scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies);
}
if (sibling !== null) {
scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies);
}
}
}
var findHostInstancesForRefresh = function (root, families) {
{
var hostInstances = new Set();
var types = new Set(families.map(function (family) {
return family.current;
}));
findHostInstancesForMatchingFibersRecursively(root.current, types, hostInstances);
return hostInstances;
}
};
function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) {
{
var child = fiber.child,
sibling = fiber.sibling,
tag = fiber.tag,
type = fiber.type;
var candidateType = null;
switch (tag) {
case FunctionComponent:
case SimpleMemoComponent:
case ClassComponent:
candidateType = type;
break;
case ForwardRef:
candidateType = type.render;
break;
}
var didMatch = false;
if (candidateType !== null) {
if (types.has(candidateType)) {
didMatch = true;
}
}
if (didMatch) {
// We have a match. This only drills down to the closest host components.
// There's no need to search deeper because for the purpose of giving
// visual feedback, "flashing" outermost parent rectangles is sufficient.
findHostInstancesForFiberShallowly(fiber, hostInstances);
} else {
// If there's no match, maybe there will be one further down in the child tree.
if (child !== null) {
findHostInstancesForMatchingFibersRecursively(child, types, hostInstances);
}
}
if (sibling !== null) {
findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances);
}
}
}
function findHostInstancesForFiberShallowly(fiber, hostInstances) {
{
var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances);
if (foundHostInstances) {
return;
} // If we didn't find any host children, fallback to closest host parent.
var node = fiber;
while (true) {
switch (node.tag) {
case HostComponent:
hostInstances.add(node.stateNode);
return;
case HostPortal:
hostInstances.add(node.stateNode.containerInfo);
return;
case HostRoot:
hostInstances.add(node.stateNode.containerInfo);
return;
}
if (node.return === null) {
throw new Error('Expected to reach root first.');
}
node = node.return;
}
}
}
function findChildHostInstancesForFiberShallowly(fiber, hostInstances) {
{
var node = fiber;
var foundHostInstances = false;
while (true) {
if (node.tag === HostComponent) {
// We got a match.
foundHostInstances = true;
hostInstances.add(node.stateNode); // There may still be more, so keep searching.
} else if (node.child !== null) {
node.child.return = node;
node = node.child;
continue;
}
if (node === fiber) {
return foundHostInstances;
}
while (node.sibling === null) {
if (node.return === null || node.return === fiber) {
return foundHostInstances;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
}
}
return false;
}
var hasBadMapPolyfill;
{
hasBadMapPolyfill = false;
try {
var nonExtensibleObject = Object.preventExtensions({});
/* eslint-disable no-new */
new Map([[nonExtensibleObject, null]]);
new Set([nonExtensibleObject]);
/* eslint-enable no-new */
} catch (e) {
// TODO: Consider warning about bad polyfills
hasBadMapPolyfill = true;
}
}
function FiberNode(tag, pendingProps, key, mode) {
// Instance
this.tag = tag;
this.key = key;
this.elementType = null;
this.type = null;
this.stateNode = null; // Fiber
this.return = null;
this.child = null;
this.sibling = null;
this.index = 0;
this.ref = null;
this.pendingProps = pendingProps;
this.memoizedProps = null;
this.updateQueue = null;
this.memoizedState = null;
this.dependencies = null;
this.mode = mode; // Effects
this.flags = NoFlags;
this.subtreeFlags = NoFlags;
this.deletions = null;
this.lanes = NoLanes;
this.childLanes = NoLanes;
this.alternate = null;
{
// Note: The following is done to avoid a v8 performance cliff.
//
// Initializing the fields below to smis and later updating them with
// double values will cause Fibers to end up having separate shapes.
// This behavior/bug has something to do with Object.preventExtension().
// Fortunately this only impacts DEV builds.
// Unfortunately it makes React unusably slow for some applications.
// To work around this, initialize the fields below with doubles.
//
// Learn more about this here:
// https://github.com/facebook/react/issues/14365
// https://bugs.chromium.org/p/v8/issues/detail?id=8538
this.actualDuration = Number.NaN;
this.actualStartTime = Number.NaN;
this.selfBaseDuration = Number.NaN;
this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization.
// This won't trigger the performance cliff mentioned above,
// and it simplifies other profiler code (including DevTools).
this.actualDuration = 0;
this.actualStartTime = -1;
this.selfBaseDuration = 0;
this.treeBaseDuration = 0;
}
{
// This isn't directly used but is handy for debugging internals:
this._debugSource = null;
this._debugOwner = null;
this._debugNeedsRemount = false;
this._debugHookTypes = null;
if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
Object.preventExtensions(this);
}
}
} // This is a constructor function, rather than a POJO constructor, still
// please ensure we do the following:
// 1) Nobody should add any instance methods on this. Instance methods can be
// more difficult to predict when they get optimized and they are almost
// never inlined properly in static compilers.
// 2) Nobody should rely on `instanceof Fiber` for type testing. We should
// always know when it is a fiber.
// 3) We might want to experiment with using numeric keys since they are easier
// to optimize in a non-JIT environment.
// 4) We can easily go from a constructor to a createFiber object literal if that
// is faster.
// 5) It should be easy to port this to a C struct and keep a C implementation
// compatible.
var createFiber = function (tag, pendingProps, key, mode) {
// $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
return new FiberNode(tag, pendingProps, key, mode);
};
function shouldConstruct$1(Component) {
var prototype = Component.prototype;
return !!(prototype && prototype.isReactComponent);
}
function isSimpleFunctionComponent(type) {
return typeof type === 'function' && !shouldConstruct$1(type) && type.defaultProps === undefined;
}
function resolveLazyComponentTag(Component) {
if (typeof Component === 'function') {
return shouldConstruct$1(Component) ? ClassComponent : FunctionComponent;
} else if (Component !== undefined && Component !== null) {
var $$typeof = Component.$$typeof;
if ($$typeof === REACT_FORWARD_REF_TYPE) {
return ForwardRef;
}
if ($$typeof === REACT_MEMO_TYPE) {
return MemoComponent;
}
}
return IndeterminateComponent;
} // This is used to create an alternate fiber to do work on.
function createWorkInProgress(current, pendingProps) {
var workInProgress = current.alternate;
if (workInProgress === null) {
// We use a double buffering pooling technique because we know that we'll
// only ever need at most two versions of a tree. We pool the "other" unused
// node that we're free to reuse. This is lazily created to avoid allocating
// extra objects for things that are never updated. It also allow us to
// reclaim the extra memory if needed.
workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
workInProgress.elementType = current.elementType;
workInProgress.type = current.type;
workInProgress.stateNode = current.stateNode;
{
// DEV-only fields
workInProgress._debugSource = current._debugSource;
workInProgress._debugOwner = current._debugOwner;
workInProgress._debugHookTypes = current._debugHookTypes;
}
workInProgress.alternate = current;
current.alternate = workInProgress;
} else {
workInProgress.pendingProps = pendingProps; // Needed because Blocks store data on type.
workInProgress.type = current.type; // We already have an alternate.
// Reset the effect tag.
workInProgress.flags = NoFlags; // The effects are no longer valid.
workInProgress.subtreeFlags = NoFlags;
workInProgress.deletions = null;
{
// We intentionally reset, rather than copy, actualDuration & actualStartTime.
// This prevents time from endlessly accumulating in new commits.
// This has the downside of resetting values for different priority renders,
// But works for yielding (the common case) and should support resuming.
workInProgress.actualDuration = 0;
workInProgress.actualStartTime = -1;
}
} // Reset all effects except static ones.
// Static effects are not specific to a render.
workInProgress.flags = current.flags & StaticMask;
workInProgress.childLanes = current.childLanes;
workInProgress.lanes = current.lanes;
workInProgress.child = current.child;
workInProgress.memoizedProps = current.memoizedProps;
workInProgress.memoizedState = current.memoizedState;
workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so
// it cannot be shared with the current fiber.
var currentDependencies = current.dependencies;
workInProgress.dependencies = currentDependencies === null ? null : {
lanes: currentDependencies.lanes,
firstContext: currentDependencies.firstContext
}; // These will be overridden during the parent's reconciliation
workInProgress.sibling = current.sibling;
workInProgress.index = current.index;
workInProgress.ref = current.ref;
{
workInProgress.selfBaseDuration = current.selfBaseDuration;
workInProgress.treeBaseDuration = current.treeBaseDuration;
}
{
workInProgress._debugNeedsRemount = current._debugNeedsRemount;
switch (workInProgress.tag) {
case IndeterminateComponent:
case FunctionComponent:
case SimpleMemoComponent:
workInProgress.type = resolveFunctionForHotReloading(current.type);
break;
case ClassComponent:
workInProgress.type = resolveClassForHotReloading(current.type);
break;
case ForwardRef:
workInProgress.type = resolveForwardRefForHotReloading(current.type);
break;
}
}
return workInProgress;
} // Used to reuse a Fiber for a second pass.
function resetWorkInProgress(workInProgress, renderLanes) {
// This resets the Fiber to what createFiber or createWorkInProgress would
// have set the values to before during the first pass. Ideally this wouldn't
// be necessary but unfortunately many code paths reads from the workInProgress
// when they should be reading from current and writing to workInProgress.
// We assume pendingProps, index, key, ref, return are still untouched to
// avoid doing another reconciliation.
// Reset the effect flags but keep any Placement tags, since that's something
// that child fiber is setting, not the reconciliation.
workInProgress.flags &= StaticMask | Placement; // The effects are no longer valid.
var current = workInProgress.alternate;
if (current === null) {
// Reset to createFiber's initial values.
workInProgress.childLanes = NoLanes;
workInProgress.lanes = renderLanes;
workInProgress.child = null;
workInProgress.subtreeFlags = NoFlags;
workInProgress.memoizedProps = null;
workInProgress.memoizedState = null;
workInProgress.updateQueue = null;
workInProgress.dependencies = null;
workInProgress.stateNode = null;
{
// Note: We don't reset the actualTime counts. It's useful to accumulate
// actual time across multiple render passes.
workInProgress.selfBaseDuration = 0;
workInProgress.treeBaseDuration = 0;
}
} else {
// Reset to the cloned values that createWorkInProgress would've.
workInProgress.childLanes = current.childLanes;
workInProgress.lanes = current.lanes;
workInProgress.child = current.child;
workInProgress.subtreeFlags = NoFlags;
workInProgress.deletions = null;
workInProgress.memoizedProps = current.memoizedProps;
workInProgress.memoizedState = current.memoizedState;
workInProgress.updateQueue = current.updateQueue; // Needed because Blocks store data on type.
workInProgress.type = current.type; // Clone the dependencies object. This is mutated during the render phase, so
// it cannot be shared with the current fiber.
var currentDependencies = current.dependencies;
workInProgress.dependencies = currentDependencies === null ? null : {
lanes: currentDependencies.lanes,
firstContext: currentDependencies.firstContext
};
{
// Note: We don't reset the actualTime counts. It's useful to accumulate
// actual time across multiple render passes.
workInProgress.selfBaseDuration = current.selfBaseDuration;
workInProgress.treeBaseDuration = current.treeBaseDuration;
}
}
return workInProgress;
}
function createHostRootFiber(tag, isStrictMode, concurrentUpdatesByDefaultOverride) {
var mode;
if (tag === ConcurrentRoot) {
mode = ConcurrentMode;
if (isStrictMode === true) {
mode |= StrictLegacyMode;
{
mode |= StrictEffectsMode;
}
}
} else {
mode = NoMode;
}
if ( isDevToolsPresent) {
// Always collect profile timings when DevTools are present.
// This enables DevTools to start capturing timing at any point–
// Without some nodes in the tree having empty base times.
mode |= ProfileMode;
}
return createFiber(HostRoot, null, null, mode);
}
function createFiberFromTypeAndProps(type, // React$ElementType
key, pendingProps, owner, mode, lanes) {
var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy.
var resolvedType = type;
if (typeof type === 'function') {
if (shouldConstruct$1(type)) {
fiberTag = ClassComponent;
{
resolvedType = resolveClassForHotReloading(resolvedType);
}
} else {
{
resolvedType = resolveFunctionForHotReloading(resolvedType);
}
}
} else if (typeof type === 'string') {
fiberTag = HostComponent;
} else {
getTag: switch (type) {
case REACT_FRAGMENT_TYPE:
return createFiberFromFragment(pendingProps.children, mode, lanes, key);
case REACT_STRICT_MODE_TYPE:
fiberTag = Mode;
mode |= StrictLegacyMode;
if ( (mode & ConcurrentMode) !== NoMode) {
// Strict effects should never run on legacy roots
mode |= StrictEffectsMode;
}
break;
case REACT_PROFILER_TYPE:
return createFiberFromProfiler(pendingProps, mode, lanes, key);
case REACT_SUSPENSE_TYPE:
return createFiberFromSuspense(pendingProps, mode, lanes, key);
case REACT_SUSPENSE_LIST_TYPE:
return createFiberFromSuspenseList(pendingProps, mode, lanes, key);
case REACT_OFFSCREEN_TYPE:
return createFiberFromOffscreen(pendingProps, mode, lanes, key);
case REACT_LEGACY_HIDDEN_TYPE:
// eslint-disable-next-line no-fallthrough
case REACT_SCOPE_TYPE:
// eslint-disable-next-line no-fallthrough
case REACT_CACHE_TYPE:
// eslint-disable-next-line no-fallthrough
case REACT_TRACING_MARKER_TYPE:
// eslint-disable-next-line no-fallthrough
case REACT_DEBUG_TRACING_MODE_TYPE:
// eslint-disable-next-line no-fallthrough
default:
{
if (typeof type === 'object' && type !== null) {
switch (type.$$typeof) {
case REACT_PROVIDER_TYPE:
fiberTag = ContextProvider;
break getTag;
case REACT_CONTEXT_TYPE:
// This is a consumer
fiberTag = ContextConsumer;
break getTag;
case REACT_FORWARD_REF_TYPE:
fiberTag = ForwardRef;
{
resolvedType = resolveForwardRefForHotReloading(resolvedType);
}
break getTag;
case REACT_MEMO_TYPE:
fiberTag = MemoComponent;
break getTag;
case REACT_LAZY_TYPE:
fiberTag = LazyComponent;
resolvedType = null;
break getTag;
}
}
var info = '';
{
if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.';
}
var ownerName = owner ? getComponentNameFromFiber(owner) : null;
if (ownerName) {
info += '\n\nCheck the render method of `' + ownerName + '`.';
}
}
throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + ("but got: " + (type == null ? type : typeof type) + "." + info));
}
}
}
var fiber = createFiber(fiberTag, pendingProps, key, mode);
fiber.elementType = type;
fiber.type = resolvedType;
fiber.lanes = lanes;
{
fiber._debugOwner = owner;
}
return fiber;
}
function createFiberFromElement(element, mode, lanes) {
var owner = null;
{
owner = element._owner;
}
var type = element.type;
var key = element.key;
var pendingProps = element.props;
var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes);
{
fiber._debugSource = element._source;
fiber._debugOwner = element._owner;
}
return fiber;
}
function createFiberFromFragment(elements, mode, lanes, key) {
var fiber = createFiber(Fragment, elements, key, mode);
fiber.lanes = lanes;
return fiber;
}
function createFiberFromProfiler(pendingProps, mode, lanes, key) {
{
if (typeof pendingProps.id !== 'string') {
error('Profiler must specify an "id" of type `string` as a prop. Received the type `%s` instead.', typeof pendingProps.id);
}
}
var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode);
fiber.elementType = REACT_PROFILER_TYPE;
fiber.lanes = lanes;
{
fiber.stateNode = {
effectDuration: 0,
passiveEffectDuration: 0
};
}
return fiber;
}
function createFiberFromSuspense(pendingProps, mode, lanes, key) {
var fiber = createFiber(SuspenseComponent, pendingProps, key, mode);
fiber.elementType = REACT_SUSPENSE_TYPE;
fiber.lanes = lanes;
return fiber;
}
function createFiberFromSuspenseList(pendingProps, mode, lanes, key) {
var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode);
fiber.elementType = REACT_SUSPENSE_LIST_TYPE;
fiber.lanes = lanes;
return fiber;
}
function createFiberFromOffscreen(pendingProps, mode, lanes, key) {
var fiber = createFiber(OffscreenComponent, pendingProps, key, mode);
fiber.elementType = REACT_OFFSCREEN_TYPE;
fiber.lanes = lanes;
var primaryChildInstance = {
isHidden: false
};
fiber.stateNode = primaryChildInstance;
return fiber;
}
function createFiberFromText(content, mode, lanes) {
var fiber = createFiber(HostText, content, null, mode);
fiber.lanes = lanes;
return fiber;
}
function createFiberFromHostInstanceForDeletion() {
var fiber = createFiber(HostComponent, null, null, NoMode);
fiber.elementType = 'DELETED';
return fiber;
}
function createFiberFromDehydratedFragment(dehydratedNode) {
var fiber = createFiber(DehydratedFragment, null, null, NoMode);
fiber.stateNode = dehydratedNode;
return fiber;
}
function createFiberFromPortal(portal, mode, lanes) {
var pendingProps = portal.children !== null ? portal.children : [];
var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
fiber.lanes = lanes;
fiber.stateNode = {
containerInfo: portal.containerInfo,
pendingChildren: null,
// Used by persistent updates
implementation: portal.implementation
};
return fiber;
} // Used for stashing WIP properties to replay failed work in DEV.
function assignFiberPropertiesInDEV(target, source) {
if (target === null) {
// This Fiber's initial properties will always be overwritten.
// We only use a Fiber to ensure the same hidden class so DEV isn't slow.
target = createFiber(IndeterminateComponent, null, null, NoMode);
} // This is intentionally written as a list of all properties.
// We tried to use Object.assign() instead but this is called in
// the hottest path, and Object.assign() was too slow:
// https://github.com/facebook/react/issues/12502
// This code is DEV-only so size is not a concern.
target.tag = source.tag;
target.key = source.key;
target.elementType = source.elementType;
target.type = source.type;
target.stateNode = source.stateNode;
target.return = source.return;
target.child = source.child;
target.sibling = source.sibling;
target.index = source.index;
target.ref = source.ref;
target.pendingProps = source.pendingProps;
target.memoizedProps = source.memoizedProps;
target.updateQueue = source.updateQueue;
target.memoizedState = source.memoizedState;
target.dependencies = source.dependencies;
target.mode = source.mode;
target.flags = source.flags;
target.subtreeFlags = source.subtreeFlags;
target.deletions = source.deletions;
target.lanes = source.lanes;
target.childLanes = source.childLanes;
target.alternate = source.alternate;
{
target.actualDuration = source.actualDuration;
target.actualStartTime = source.actualStartTime;
target.selfBaseDuration = source.selfBaseDuration;
target.treeBaseDuration = source.treeBaseDuration;
}
target._debugSource = source._debugSource;
target._debugOwner = source._debugOwner;
target._debugNeedsRemount = source._debugNeedsRemount;
target._debugHookTypes = source._debugHookTypes;
return target;
}
function FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError) {
this.tag = tag;
this.containerInfo = containerInfo;
this.pendingChildren = null;
this.current = null;
this.pingCache = null;
this.finishedWork = null;
this.timeoutHandle = noTimeout;
this.context = null;
this.pendingContext = null;
this.callbackNode = null;
this.callbackPriority = NoLane;
this.eventTimes = createLaneMap(NoLanes);
this.expirationTimes = createLaneMap(NoTimestamp);
this.pendingLanes = NoLanes;
this.suspendedLanes = NoLanes;
this.pingedLanes = NoLanes;
this.expiredLanes = NoLanes;
this.mutableReadLanes = NoLanes;
this.finishedLanes = NoLanes;
this.entangledLanes = NoLanes;
this.entanglements = createLaneMap(NoLanes);
this.identifierPrefix = identifierPrefix;
this.onRecoverableError = onRecoverableError;
{
this.mutableSourceEagerHydrationData = null;
}
{
this.effectDuration = 0;
this.passiveEffectDuration = 0;
}
{
this.memoizedUpdaters = new Set();
var pendingUpdatersLaneMap = this.pendingUpdatersLaneMap = [];
for (var _i = 0; _i < TotalLanes; _i++) {
pendingUpdatersLaneMap.push(new Set());
}
}
{
switch (tag) {
case ConcurrentRoot:
this._debugRootType = hydrate ? 'hydrateRoot()' : 'createRoot()';
break;
case LegacyRoot:
this._debugRootType = hydrate ? 'hydrate()' : 'render()';
break;
}
}
}
function createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, // TODO: We have several of these arguments that are conceptually part of the
// host config, but because they are passed in at runtime, we have to thread
// them through the root constructor. Perhaps we should put them all into a
// single type, like a DynamicHostConfig that is defined by the renderer.
identifierPrefix, onRecoverableError, transitionCallbacks) {
var root = new FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError);
// stateNode is any.
var uninitializedFiber = createHostRootFiber(tag, isStrictMode);
root.current = uninitializedFiber;
uninitializedFiber.stateNode = root;
{
var _initialState = {
element: initialChildren,
isDehydrated: hydrate,
cache: null,
// not enabled yet
transitions: null,
pendingSuspenseBoundaries: null
};
uninitializedFiber.memoizedState = _initialState;
}
initializeUpdateQueue(uninitializedFiber);
return root;
}
var ReactVersion = '18.2.0';
function createPortal(children, containerInfo, // TODO: figure out the API for cross-renderer implementation.
implementation) {
var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
{
checkKeyStringCoercion(key);
}
return {
// This tag allow us to uniquely identify this as a React Portal
$$typeof: REACT_PORTAL_TYPE,
key: key == null ? null : '' + key,
children: children,
containerInfo: containerInfo,
implementation: implementation
};
}
var didWarnAboutNestedUpdates;
var didWarnAboutFindNodeInStrictMode;
{
didWarnAboutNestedUpdates = false;
didWarnAboutFindNodeInStrictMode = {};
}
function getContextForSubtree(parentComponent) {
if (!parentComponent) {
return emptyContextObject;
}
var fiber = get(parentComponent);
var parentContext = findCurrentUnmaskedContext(fiber);
if (fiber.tag === ClassComponent) {
var Component = fiber.type;
if (isContextProvider(Component)) {
return processChildContext(fiber, Component, parentContext);
}
}
return parentContext;
}
function findHostInstanceWithWarning(component, methodName) {
{
var fiber = get(component);
if (fiber === undefined) {
if (typeof component.render === 'function') {
throw new Error('Unable to find node on an unmounted component.');
} else {
var keys = Object.keys(component).join(',');
throw new Error("Argument appears to not be a ReactComponent. Keys: " + keys);
}
}
var hostFiber = findCurrentHostFiber(fiber);
if (hostFiber === null) {
return null;
}
if (hostFiber.mode & StrictLegacyMode) {
var componentName = getComponentNameFromFiber(fiber) || 'Component';
if (!didWarnAboutFindNodeInStrictMode[componentName]) {
didWarnAboutFindNodeInStrictMode[componentName] = true;
var previousFiber = current;
try {
setCurrentFiber(hostFiber);
if (fiber.mode & StrictLegacyMode) {
error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which is inside StrictMode. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node', methodName, methodName, componentName);
} else {
error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which renders StrictMode children. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node', methodName, methodName, componentName);
}
} finally {
// Ideally this should reset to previous but this shouldn't be called in
// render and there's another warning for that anyway.
if (previousFiber) {
setCurrentFiber(previousFiber);
} else {
resetCurrentFiber();
}
}
}
}
return hostFiber.stateNode;
}
}
function createContainer(containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) {
var hydrate = false;
var initialChildren = null;
return createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError);
}
function createHydrationContainer(initialChildren, // TODO: Remove `callback` when we delete legacy mode.
callback, containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) {
var hydrate = true;
var root = createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); // TODO: Move this to FiberRoot constructor
root.context = getContextForSubtree(null); // Schedule the initial render. In a hydration root, this is different from
// a regular update because the initial render must match was was rendered
// on the server.
// NOTE: This update intentionally doesn't have a payload. We're only using
// the update to schedule work on the root fiber (and, for legacy roots, to
// enqueue the callback if one is provided).
var current = root.current;
var eventTime = requestEventTime();
var lane = requestUpdateLane(current);
var update = createUpdate(eventTime, lane);
update.callback = callback !== undefined && callback !== null ? callback : null;
enqueueUpdate(current, update, lane);
scheduleInitialHydrationOnRoot(root, lane, eventTime);
return root;
}
function updateContainer(element, container, parentComponent, callback) {
{
onScheduleRoot(container, element);
}
var current$1 = container.current;
var eventTime = requestEventTime();
var lane = requestUpdateLane(current$1);
{
markRenderScheduled(lane);
}
var context = getContextForSubtree(parentComponent);
if (container.context === null) {
container.context = context;
} else {
container.pendingContext = context;
}
{
if (isRendering && current !== null && !didWarnAboutNestedUpdates) {
didWarnAboutNestedUpdates = true;
error('Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + 'Check the render method of %s.', getComponentNameFromFiber(current) || 'Unknown');
}
}
var update = createUpdate(eventTime, lane); // Caution: React DevTools currently depends on this property
// being called "element".
update.payload = {
element: element
};
callback = callback === undefined ? null : callback;
if (callback !== null) {
{
if (typeof callback !== 'function') {
error('render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback);
}
}
update.callback = callback;
}
var root = enqueueUpdate(current$1, update, lane);
if (root !== null) {
scheduleUpdateOnFiber(root, current$1, lane, eventTime);
entangleTransitions(root, current$1, lane);
}
return lane;
}
function getPublicRootInstance(container) {
var containerFiber = container.current;
if (!containerFiber.child) {
return null;
}
switch (containerFiber.child.tag) {
case HostComponent:
return getPublicInstance(containerFiber.child.stateNode);
default:
return containerFiber.child.stateNode;
}
}
function attemptSynchronousHydration$1(fiber) {
switch (fiber.tag) {
case HostRoot:
{
var root = fiber.stateNode;
if (isRootDehydrated(root)) {
// Flush the first scheduled "update".
var lanes = getHighestPriorityPendingLanes(root);
flushRoot(root, lanes);
}
break;
}
case SuspenseComponent:
{
flushSync(function () {
var root = enqueueConcurrentRenderForLane(fiber, SyncLane);
if (root !== null) {
var eventTime = requestEventTime();
scheduleUpdateOnFiber(root, fiber, SyncLane, eventTime);
}
}); // If we're still blocked after this, we need to increase
// the priority of any promises resolving within this
// boundary so that they next attempt also has higher pri.
var retryLane = SyncLane;
markRetryLaneIfNotHydrated(fiber, retryLane);
break;
}
}
}
function markRetryLaneImpl(fiber, retryLane) {
var suspenseState = fiber.memoizedState;
if (suspenseState !== null && suspenseState.dehydrated !== null) {
suspenseState.retryLane = higherPriorityLane(suspenseState.retryLane, retryLane);
}
} // Increases the priority of thenables when they resolve within this boundary.
function markRetryLaneIfNotHydrated(fiber, retryLane) {
markRetryLaneImpl(fiber, retryLane);
var alternate = fiber.alternate;
if (alternate) {
markRetryLaneImpl(alternate, retryLane);
}
}
function attemptContinuousHydration$1(fiber) {
if (fiber.tag !== SuspenseComponent) {
// We ignore HostRoots here because we can't increase
// their priority and they should not suspend on I/O,
// since you have to wrap anything that might suspend in
// Suspense.
return;
}
var lane = SelectiveHydrationLane;
var root = enqueueConcurrentRenderForLane(fiber, lane);
if (root !== null) {
var eventTime = requestEventTime();
scheduleUpdateOnFiber(root, fiber, lane, eventTime);
}
markRetryLaneIfNotHydrated(fiber, lane);
}
function attemptHydrationAtCurrentPriority$1(fiber) {
if (fiber.tag !== SuspenseComponent) {
// We ignore HostRoots here because we can't increase
// their priority other than synchronously flush it.
return;
}
var lane = requestUpdateLane(fiber);
var root = enqueueConcurrentRenderForLane(fiber, lane);
if (root !== null) {
var eventTime = requestEventTime();
scheduleUpdateOnFiber(root, fiber, lane, eventTime);
}
markRetryLaneIfNotHydrated(fiber, lane);
}
function findHostInstanceWithNoPortals(fiber) {
var hostFiber = findCurrentHostFiberWithNoPortals(fiber);
if (hostFiber === null) {
return null;
}
return hostFiber.stateNode;
}
var shouldErrorImpl = function (fiber) {
return null;
};
function shouldError(fiber) {
return shouldErrorImpl(fiber);
}
var shouldSuspendImpl = function (fiber) {
return false;
};
function shouldSuspend(fiber) {
return shouldSuspendImpl(fiber);
}
var overrideHookState = null;
var overrideHookStateDeletePath = null;
var overrideHookStateRenamePath = null;
var overrideProps = null;
var overridePropsDeletePath = null;
var overridePropsRenamePath = null;
var scheduleUpdate = null;
var setErrorHandler = null;
var setSuspenseHandler = null;
{
var copyWithDeleteImpl = function (obj, path, index) {
var key = path[index];
var updated = isArray(obj) ? obj.slice() : assign({}, obj);
if (index + 1 === path.length) {
if (isArray(updated)) {
updated.splice(key, 1);
} else {
delete updated[key];
}
return updated;
} // $FlowFixMe number or string is fine here
updated[key] = copyWithDeleteImpl(obj[key], path, index + 1);
return updated;
};
var copyWithDelete = function (obj, path) {
return copyWithDeleteImpl(obj, path, 0);
};
var copyWithRenameImpl = function (obj, oldPath, newPath, index) {
var oldKey = oldPath[index];
var updated = isArray(obj) ? obj.slice() : assign({}, obj);
if (index + 1 === oldPath.length) {
var newKey = newPath[index]; // $FlowFixMe number or string is fine here
updated[newKey] = updated[oldKey];
if (isArray(updated)) {
updated.splice(oldKey, 1);
} else {
delete updated[oldKey];
}
} else {
// $FlowFixMe number or string is fine here
updated[oldKey] = copyWithRenameImpl( // $FlowFixMe number or string is fine here
obj[oldKey], oldPath, newPath, index + 1);
}
return updated;
};
var copyWithRename = function (obj, oldPath, newPath) {
if (oldPath.length !== newPath.length) {
warn('copyWithRename() expects paths of the same length');
return;
} else {
for (var i = 0; i < newPath.length - 1; i++) {
if (oldPath[i] !== newPath[i]) {
warn('copyWithRename() expects paths to be the same except for the deepest key');
return;
}
}
}
return copyWithRenameImpl(obj, oldPath, newPath, 0);
};
var copyWithSetImpl = function (obj, path, index, value) {
if (index >= path.length) {
return value;
}
var key = path[index];
var updated = isArray(obj) ? obj.slice() : assign({}, obj); // $FlowFixMe number or string is fine here
updated[key] = copyWithSetImpl(obj[key], path, index + 1, value);
return updated;
};
var copyWithSet = function (obj, path, value) {
return copyWithSetImpl(obj, path, 0, value);
};
var findHook = function (fiber, id) {
// For now, the "id" of stateful hooks is just the stateful hook index.
// This may change in the future with e.g. nested hooks.
var currentHook = fiber.memoizedState;
while (currentHook !== null && id > 0) {
currentHook = currentHook.next;
id--;
}
return currentHook;
}; // Support DevTools editable values for useState and useReducer.
overrideHookState = function (fiber, id, path, value) {
var hook = findHook(fiber, id);
if (hook !== null) {
var newState = copyWithSet(hook.memoizedState, path, value);
hook.memoizedState = newState;
hook.baseState = newState; // We aren't actually adding an update to the queue,
// because there is no update we can add for useReducer hooks that won't trigger an error.
// (There's no appropriate action type for DevTools overrides.)
// As a result though, React will see the scheduled update as a noop and bailout.
// Shallow cloning props works as a workaround for now to bypass the bailout check.
fiber.memoizedProps = assign({}, fiber.memoizedProps);
var root = enqueueConcurrentRenderForLane(fiber, SyncLane);
if (root !== null) {
scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
}
}
};
overrideHookStateDeletePath = function (fiber, id, path) {
var hook = findHook(fiber, id);
if (hook !== null) {
var newState = copyWithDelete(hook.memoizedState, path);
hook.memoizedState = newState;
hook.baseState = newState; // We aren't actually adding an update to the queue,
// because there is no update we can add for useReducer hooks that won't trigger an error.
// (There's no appropriate action type for DevTools overrides.)
// As a result though, React will see the scheduled update as a noop and bailout.
// Shallow cloning props works as a workaround for now to bypass the bailout check.
fiber.memoizedProps = assign({}, fiber.memoizedProps);
var root = enqueueConcurrentRenderForLane(fiber, SyncLane);
if (root !== null) {
scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
}
}
};
overrideHookStateRenamePath = function (fiber, id, oldPath, newPath) {
var hook = findHook(fiber, id);
if (hook !== null) {
var newState = copyWithRename(hook.memoizedState, oldPath, newPath);
hook.memoizedState = newState;
hook.baseState = newState; // We aren't actually adding an update to the queue,
// because there is no update we can add for useReducer hooks that won't trigger an error.
// (There's no appropriate action type for DevTools overrides.)
// As a result though, React will see the scheduled update as a noop and bailout.
// Shallow cloning props works as a workaround for now to bypass the bailout check.
fiber.memoizedProps = assign({}, fiber.memoizedProps);
var root = enqueueConcurrentRenderForLane(fiber, SyncLane);
if (root !== null) {
scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
}
}
}; // Support DevTools props for function components, forwardRef, memo, host components, etc.
overrideProps = function (fiber, path, value) {
fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);
if (fiber.alternate) {
fiber.alternate.pendingProps = fiber.pendingProps;
}
var root = enqueueConcurrentRenderForLane(fiber, SyncLane);
if (root !== null) {
scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
}
};
overridePropsDeletePath = function (fiber, path) {
fiber.pendingProps = copyWithDelete(fiber.memoizedProps, path);
if (fiber.alternate) {
fiber.alternate.pendingProps = fiber.pendingProps;
}
var root = enqueueConcurrentRenderForLane(fiber, SyncLane);
if (root !== null) {
scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
}
};
overridePropsRenamePath = function (fiber, oldPath, newPath) {
fiber.pendingProps = copyWithRename(fiber.memoizedProps, oldPath, newPath);
if (fiber.alternate) {
fiber.alternate.pendingProps = fiber.pendingProps;
}
var root = enqueueConcurrentRenderForLane(fiber, SyncLane);
if (root !== null) {
scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
}
};
scheduleUpdate = function (fiber) {
var root = enqueueConcurrentRenderForLane(fiber, SyncLane);
if (root !== null) {
scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
}
};
setErrorHandler = function (newShouldErrorImpl) {
shouldErrorImpl = newShouldErrorImpl;
};
setSuspenseHandler = function (newShouldSuspendImpl) {
shouldSuspendImpl = newShouldSuspendImpl;
};
}
function findHostInstanceByFiber(fiber) {
var hostFiber = findCurrentHostFiber(fiber);
if (hostFiber === null) {
return null;
}
return hostFiber.stateNode;
}
function emptyFindFiberByHostInstance(instance) {
return null;
}
function getCurrentFiberForDevTools() {
return current;
}
function injectIntoDevTools(devToolsConfig) {
var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
return injectInternals({
bundleType: devToolsConfig.bundleType,
version: devToolsConfig.version,
rendererPackageName: devToolsConfig.rendererPackageName,
rendererConfig: devToolsConfig.rendererConfig,
overrideHookState: overrideHookState,
overrideHookStateDeletePath: overrideHookStateDeletePath,
overrideHookStateRenamePath: overrideHookStateRenamePath,
overrideProps: overrideProps,
overridePropsDeletePath: overridePropsDeletePath,
overridePropsRenamePath: overridePropsRenamePath,
setErrorHandler: setErrorHandler,
setSuspenseHandler: setSuspenseHandler,
scheduleUpdate: scheduleUpdate,
currentDispatcherRef: ReactCurrentDispatcher,
findHostInstanceByFiber: findHostInstanceByFiber,
findFiberByHostInstance: findFiberByHostInstance || emptyFindFiberByHostInstance,
// React Refresh
findHostInstancesForRefresh: findHostInstancesForRefresh ,
scheduleRefresh: scheduleRefresh ,
scheduleRoot: scheduleRoot ,
setRefreshHandler: setRefreshHandler ,
// Enables DevTools to append owner stacks to error messages in DEV mode.
getCurrentFiber: getCurrentFiberForDevTools ,
// Enables DevTools to detect reconciler version rather than renderer version
// which may not match for third party renderers.
reconcilerVersion: ReactVersion
});
}
/* global reportError */
var defaultOnRecoverableError = typeof reportError === 'function' ? // In modern browsers, reportError will dispatch an error event,
// emulating an uncaught JavaScript error.
reportError : function (error) {
// In older browsers and test environments, fallback to console.error.
// eslint-disable-next-line react-internal/no-production-logging
console['error'](error);
};
function ReactDOMRoot(internalRoot) {
this._internalRoot = internalRoot;
}
ReactDOMHydrationRoot.prototype.render = ReactDOMRoot.prototype.render = function (children) {
var root = this._internalRoot;
if (root === null) {
throw new Error('Cannot update an unmounted root.');
}
{
if (typeof arguments[1] === 'function') {
error('render(...): does not support the second callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().');
} else if (isValidContainer(arguments[1])) {
error('You passed a container to the second argument of root.render(...). ' + "You don't need to pass it again since you already passed it to create the root.");
} else if (typeof arguments[1] !== 'undefined') {
error('You passed a second argument to root.render(...) but it only accepts ' + 'one argument.');
}
var container = root.containerInfo;
if (container.nodeType !== COMMENT_NODE) {
var hostInstance = findHostInstanceWithNoPortals(root.current);
if (hostInstance) {
if (hostInstance.parentNode !== container) {
error('render(...): It looks like the React-rendered content of the ' + 'root container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + "root.unmount() to empty a root's container.");
}
}
}
}
updateContainer(children, root, null, null);
};
ReactDOMHydrationRoot.prototype.unmount = ReactDOMRoot.prototype.unmount = function () {
{
if (typeof arguments[0] === 'function') {
error('unmount(...): does not support a callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().');
}
}
var root = this._internalRoot;
if (root !== null) {
this._internalRoot = null;
var container = root.containerInfo;
{
if (isAlreadyRendering()) {
error('Attempted to synchronously unmount a root while React was already ' + 'rendering. React cannot finish unmounting the root until the ' + 'current render has completed, which may lead to a race condition.');
}
}
flushSync(function () {
updateContainer(null, root, null, null);
});
unmarkContainerAsRoot(container);
}
};
function createRoot(container, options) {
if (!isValidContainer(container)) {
throw new Error('createRoot(...): Target container is not a DOM element.');
}
warnIfReactDOMContainerInDEV(container);
var isStrictMode = false;
var concurrentUpdatesByDefaultOverride = false;
var identifierPrefix = '';
var onRecoverableError = defaultOnRecoverableError;
var transitionCallbacks = null;
if (options !== null && options !== undefined) {
{
if (options.hydrate) {
warn('hydrate through createRoot is deprecated. Use ReactDOMClient.hydrateRoot(container, <App />) instead.');
} else {
if (typeof options === 'object' && options !== null && options.$$typeof === REACT_ELEMENT_TYPE) {
error('You passed a JSX element to createRoot. You probably meant to ' + 'call root.render instead. ' + 'Example usage:\n\n' + ' let root = createRoot(domContainer);\n' + ' root.render(<App />);');
}
}
}
if (options.unstable_strictMode === true) {
isStrictMode = true;
}
if (options.identifierPrefix !== undefined) {
identifierPrefix = options.identifierPrefix;
}
if (options.onRecoverableError !== undefined) {
onRecoverableError = options.onRecoverableError;
}
if (options.transitionCallbacks !== undefined) {
transitionCallbacks = options.transitionCallbacks;
}
}
var root = createContainer(container, ConcurrentRoot, null, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError);
markContainerAsRoot(root.current, container);
var rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container;
listenToAllSupportedEvents(rootContainerElement);
return new ReactDOMRoot(root);
}
function ReactDOMHydrationRoot(internalRoot) {
this._internalRoot = internalRoot;
}
function scheduleHydration(target) {
if (target) {
queueExplicitHydrationTarget(target);
}
}
ReactDOMHydrationRoot.prototype.unstable_scheduleHydration = scheduleHydration;
function hydrateRoot(container, initialChildren, options) {
if (!isValidContainer(container)) {
throw new Error('hydrateRoot(...): Target container is not a DOM element.');
}
warnIfReactDOMContainerInDEV(container);
{
if (initialChildren === undefined) {
error('Must provide initial children as second argument to hydrateRoot. ' + 'Example usage: hydrateRoot(domContainer, <App />)');
}
} // For now we reuse the whole bag of options since they contain
// the hydration callbacks.
var hydrationCallbacks = options != null ? options : null; // TODO: Delete this option
var mutableSources = options != null && options.hydratedSources || null;
var isStrictMode = false;
var concurrentUpdatesByDefaultOverride = false;
var identifierPrefix = '';
var onRecoverableError = defaultOnRecoverableError;
if (options !== null && options !== undefined) {
if (options.unstable_strictMode === true) {
isStrictMode = true;
}
if (options.identifierPrefix !== undefined) {
identifierPrefix = options.identifierPrefix;
}
if (options.onRecoverableError !== undefined) {
onRecoverableError = options.onRecoverableError;
}
}
var root = createHydrationContainer(initialChildren, null, container, ConcurrentRoot, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError);
markContainerAsRoot(root.current, container); // This can't be a comment node since hydration doesn't work on comment nodes anyway.
listenToAllSupportedEvents(container);
if (mutableSources) {
for (var i = 0; i < mutableSources.length; i++) {
var mutableSource = mutableSources[i];
registerMutableSourceForHydration(root, mutableSource);
}
}
return new ReactDOMHydrationRoot(root);
}
function isValidContainer(node) {
return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || !disableCommentsAsDOMContainers ));
} // TODO: Remove this function which also includes comment nodes.
// We only use it in places that are currently more relaxed.
function isValidContainerLegacy(node) {
return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || node.nodeType === COMMENT_NODE && node.nodeValue === ' react-mount-point-unstable '));
}
function warnIfReactDOMContainerInDEV(container) {
{
if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === 'BODY') {
error('createRoot(): Creating roots directly with document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try using a container element created ' + 'for your app.');
}
if (isContainerMarkedAsRoot(container)) {
if (container._reactRootContainer) {
error('You are calling ReactDOMClient.createRoot() on a container that was previously ' + 'passed to ReactDOM.render(). This is not supported.');
} else {
error('You are calling ReactDOMClient.createRoot() on a container that ' + 'has already been passed to createRoot() before. Instead, call ' + 'root.render() on the existing root instead if you want to update it.');
}
}
}
}
var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner;
var topLevelUpdateWarnings;
{
topLevelUpdateWarnings = function (container) {
if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {
var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer.current);
if (hostInstance) {
if (hostInstance.parentNode !== container) {
error('render(...): It looks like the React-rendered content of this ' + 'container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + 'ReactDOM.unmountComponentAtNode to empty a container.');
}
}
}
var isRootRenderedBySomeReact = !!container._reactRootContainer;
var rootEl = getReactRootElementInContainer(container);
var hasNonRootReactChild = !!(rootEl && getInstanceFromNode(rootEl));
if (hasNonRootReactChild && !isRootRenderedBySomeReact) {
error('render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.');
}
if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === 'BODY') {
error('render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.');
}
};
}
function getReactRootElementInContainer(container) {
if (!container) {
return null;
}
if (container.nodeType === DOCUMENT_NODE) {
return container.documentElement;
} else {
return container.firstChild;
}
}
function noopOnRecoverableError() {// This isn't reachable because onRecoverableError isn't called in the
// legacy API.
}
function legacyCreateRootFromDOMContainer(container, initialChildren, parentComponent, callback, isHydrationContainer) {
if (isHydrationContainer) {
if (typeof callback === 'function') {
var originalCallback = callback;
callback = function () {
var instance = getPublicRootInstance(root);
originalCallback.call(instance);
};
}
var root = createHydrationContainer(initialChildren, callback, container, LegacyRoot, null, // hydrationCallbacks
false, // isStrictMode
false, // concurrentUpdatesByDefaultOverride,
'', // identifierPrefix
noopOnRecoverableError);
container._reactRootContainer = root;
markContainerAsRoot(root.current, container);
var rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container;
listenToAllSupportedEvents(rootContainerElement);
flushSync();
return root;
} else {
// First clear any existing content.
var rootSibling;
while (rootSibling = container.lastChild) {
container.removeChild(rootSibling);
}
if (typeof callback === 'function') {
var _originalCallback = callback;
callback = function () {
var instance = getPublicRootInstance(_root);
_originalCallback.call(instance);
};
}
var _root = createContainer(container, LegacyRoot, null, // hydrationCallbacks
false, // isStrictMode
false, // concurrentUpdatesByDefaultOverride,
'', // identifierPrefix
noopOnRecoverableError);
container._reactRootContainer = _root;
markContainerAsRoot(_root.current, container);
var _rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container;
listenToAllSupportedEvents(_rootContainerElement); // Initial mount should not be batched.
flushSync(function () {
updateContainer(initialChildren, _root, parentComponent, callback);
});
return _root;
}
}
function warnOnInvalidCallback$1(callback, callerName) {
{
if (callback !== null && typeof callback !== 'function') {
error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
}
}
}
function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) {
{
topLevelUpdateWarnings(container);
warnOnInvalidCallback$1(callback === undefined ? null : callback, 'render');
}
var maybeRoot = container._reactRootContainer;
var root;
if (!maybeRoot) {
// Initial mount
root = legacyCreateRootFromDOMContainer(container, children, parentComponent, callback, forceHydrate);
} else {
root = maybeRoot;
if (typeof callback === 'function') {
var originalCallback = callback;
callback = function () {
var instance = getPublicRootInstance(root);
originalCallback.call(instance);
};
} // Update
updateContainer(children, root, parentComponent, callback);
}
return getPublicRootInstance(root);
}
function findDOMNode(componentOrElement) {
{
var owner = ReactCurrentOwner$3.current;
if (owner !== null && owner.stateNode !== null) {
var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;
if (!warnedAboutRefsInRender) {
error('%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentNameFromType(owner.type) || 'A component');
}
owner.stateNode._warnedAboutRefsInRender = true;
}
}
if (componentOrElement == null) {
return null;
}
if (componentOrElement.nodeType === ELEMENT_NODE) {
return componentOrElement;
}
{
return findHostInstanceWithWarning(componentOrElement, 'findDOMNode');
}
}
function hydrate(element, container, callback) {
{
error('ReactDOM.hydrate is no longer supported in React 18. Use hydrateRoot ' + 'instead. Until you switch to the new API, your app will behave as ' + "if it's running React 17. Learn " + 'more: https://reactjs.org/link/switch-to-createroot');
}
if (!isValidContainerLegacy(container)) {
throw new Error('Target container is not a DOM element.');
}
{
var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;
if (isModernRoot) {
error('You are calling ReactDOM.hydrate() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. ' + 'Did you mean to call hydrateRoot(container, element)?');
}
} // TODO: throw or warn if we couldn't hydrate?
return legacyRenderSubtreeIntoContainer(null, element, container, true, callback);
}
function render(element, container, callback) {
{
error('ReactDOM.render is no longer supported in React 18. Use createRoot ' + 'instead. Until you switch to the new API, your app will behave as ' + "if it's running React 17. Learn " + 'more: https://reactjs.org/link/switch-to-createroot');
}
if (!isValidContainerLegacy(container)) {
throw new Error('Target container is not a DOM element.');
}
{
var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;
if (isModernRoot) {
error('You are calling ReactDOM.render() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. ' + 'Did you mean to call root.render(element)?');
}
}
return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
}
function unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {
{
error('ReactDOM.unstable_renderSubtreeIntoContainer() is no longer supported ' + 'in React 18. Consider using a portal instead. Until you switch to ' + "the createRoot API, your app will behave as if it's running React " + '17. Learn more: https://reactjs.org/link/switch-to-createroot');
}
if (!isValidContainerLegacy(containerNode)) {
throw new Error('Target container is not a DOM element.');
}
if (parentComponent == null || !has(parentComponent)) {
throw new Error('parentComponent must be a valid React Component');
}
return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback);
}
function unmountComponentAtNode(container) {
if (!isValidContainerLegacy(container)) {
throw new Error('unmountComponentAtNode(...): Target container is not a DOM element.');
}
{
var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;
if (isModernRoot) {
error('You are calling ReactDOM.unmountComponentAtNode() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. Did you mean to call root.unmount()?');
}
}
if (container._reactRootContainer) {
{
var rootEl = getReactRootElementInContainer(container);
var renderedByDifferentReact = rootEl && !getInstanceFromNode(rootEl);
if (renderedByDifferentReact) {
error("unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by another copy of React.');
}
} // Unmount should not be batched.
flushSync(function () {
legacyRenderSubtreeIntoContainer(null, null, container, false, function () {
// $FlowFixMe This should probably use `delete container._reactRootContainer`
container._reactRootContainer = null;
unmarkContainerAsRoot(container);
});
}); // If you call unmountComponentAtNode twice in quick succession, you'll
// get `true` twice. That's probably fine?
return true;
} else {
{
var _rootEl = getReactRootElementInContainer(container);
var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode(_rootEl)); // Check if the container itself is a React root node.
var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainerLegacy(container.parentNode) && !!container.parentNode._reactRootContainer;
if (hasNonRootReactChild) {
error("unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.');
}
}
return false;
}
}
setAttemptSynchronousHydration(attemptSynchronousHydration$1);
setAttemptContinuousHydration(attemptContinuousHydration$1);
setAttemptHydrationAtCurrentPriority(attemptHydrationAtCurrentPriority$1);
setGetCurrentUpdatePriority(getCurrentUpdatePriority);
setAttemptHydrationAtPriority(runWithPriority);
{
if (typeof Map !== 'function' || // $FlowIssue Flow incorrectly thinks Map has no prototype
Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' || // $FlowIssue Flow incorrectly thinks Set has no prototype
Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') {
error('React depends on Map and Set built-in types. Make sure that you load a ' + 'polyfill in older browsers. https://reactjs.org/link/react-polyfills');
}
}
setRestoreImplementation(restoreControlledState$3);
setBatchingImplementation(batchedUpdates$1, discreteUpdates, flushSync);
function createPortal$1(children, container) {
var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
if (!isValidContainer(container)) {
throw new Error('Target container is not a DOM element.');
} // TODO: pass ReactDOM portal implementation as third argument
// $FlowFixMe The Flow type is opaque but there's no way to actually create it.
return createPortal(children, container, null, key);
}
function renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {
return unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback);
}
var Internals = {
usingClientEntryPoint: false,
// Keep in sync with ReactTestUtils.js.
// This is an array for better minification.
Events: [getInstanceFromNode, getNodeFromInstance, getFiberCurrentPropsFromNode, enqueueStateRestore, restoreStateIfNeeded, batchedUpdates$1]
};
function createRoot$1(container, options) {
{
if (!Internals.usingClientEntryPoint && !true) {
error('You are importing createRoot from "react-dom" which is not supported. ' + 'You should instead import it from "react-dom/client".');
}
}
return createRoot(container, options);
}
function hydrateRoot$1(container, initialChildren, options) {
{
if (!Internals.usingClientEntryPoint && !true) {
error('You are importing hydrateRoot from "react-dom" which is not supported. ' + 'You should instead import it from "react-dom/client".');
}
}
return hydrateRoot(container, initialChildren, options);
} // Overload the definition to the two valid signatures.
// Warning, this opts-out of checking the function body.
// eslint-disable-next-line no-redeclare
function flushSync$1(fn) {
{
if (isAlreadyRendering()) {
error('flushSync was called from inside a lifecycle method. React cannot ' + 'flush when React is already rendering. Consider moving this call to ' + 'a scheduler task or micro task.');
}
}
return flushSync(fn);
}
var foundDevTools = injectIntoDevTools({
findFiberByHostInstance: getClosestInstanceFromNode,
bundleType: 1 ,
version: ReactVersion,
rendererPackageName: 'react-dom'
});
{
if (!foundDevTools && canUseDOM && window.top === window.self) {
// If we're in Chrome or Firefox, provide a download link if not installed.
if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
var protocol = window.location.protocol; // Don't warn in exotic cases like chrome-extension://.
if (/^(https?|file):$/.test(protocol)) {
// eslint-disable-next-line react-internal/no-production-logging
console.info('%cDownload the React DevTools ' + 'for a better development experience: ' + 'https://reactjs.org/link/react-devtools' + (protocol === 'file:' ? '\nYou might need to use a local HTTP server (instead of file://): ' + 'https://reactjs.org/link/react-devtools-faq' : ''), 'font-weight:bold');
}
}
}
}
exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = Internals;
exports.createPortal = createPortal$1;
exports.createRoot = createRoot$1;
exports.findDOMNode = findDOMNode;
exports.flushSync = flushSync$1;
exports.hydrate = hydrate;
exports.hydrateRoot = hydrateRoot$1;
exports.render = render;
exports.unmountComponentAtNode = unmountComponentAtNode;
exports.unstable_batchedUpdates = batchedUpdates$1;
exports.unstable_renderSubtreeIntoContainer = renderSubtreeIntoContainer;
exports.version = ReactVersion;
})));
vendor/regenerator-runtime.min.js 0000666 00000014717 15123355174 0013203 0 ustar 00 var runtime=function(t){"use strict";var r,e=Object.prototype,n=e.hasOwnProperty,o=Object.defineProperty||function(t,r,e){t[r]=e.value},i=(w="function"==typeof Symbol?Symbol:{}).iterator||"@@iterator",a=w.asyncIterator||"@@asyncIterator",c=w.toStringTag||"@@toStringTag";function u(t,r,e){return Object.defineProperty(t,r,{value:e,enumerable:!0,configurable:!0,writable:!0}),t[r]}try{u({},"")}catch(e){u=function(t,r,e){return t[r]=e}}function h(t,e,n,i){var a,c,u,h;e=e&&e.prototype instanceof v?e:v,e=Object.create(e.prototype),i=new O(i||[]);return o(e,"_invoke",{value:(a=t,c=n,u=i,h=f,function(t,e){if(h===p)throw new Error("Generator is already running");if(h===y){if("throw"===t)throw e;return G()}for(u.method=t,u.arg=e;;){var n=u.delegate;if(n&&(n=function t(e,n){var o=n.method,i=e.iterator[o];return i===r?(n.delegate=null,"throw"===o&&e.iterator.return&&(n.method="return",n.arg=r,t(e,n),"throw"===n.method)||"return"!==o&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+o+"' method")),g):"throw"===(o=l(i,e.iterator,n.arg)).type?(n.method="throw",n.arg=o.arg,n.delegate=null,g):(i=o.arg)?i.done?(n[e.resultName]=i.value,n.next=e.nextLoc,"return"!==n.method&&(n.method="next",n.arg=r),n.delegate=null,g):i:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,g)}(n,u),n)){if(n===g)continue;return n}if("next"===u.method)u.sent=u._sent=u.arg;else if("throw"===u.method){if(h===f)throw h=y,u.arg;u.dispatchException(u.arg)}else"return"===u.method&&u.abrupt("return",u.arg);if(h=p,"normal"===(n=l(a,c,u)).type){if(h=u.done?y:s,n.arg!==g)return{value:n.arg,done:u.done}}else"throw"===n.type&&(h=y,u.method="throw",u.arg=n.arg)}})}),e}function l(t,r,e){try{return{type:"normal",arg:t.call(r,e)}}catch(t){return{type:"throw",arg:t}}}t.wrap=h;var f="suspendedStart",s="suspendedYield",p="executing",y="completed",g={};function v(){}function d(){}function m(){}var w,b,L=((b=(b=(u(w={},i,(function(){return this})),Object.getPrototypeOf))&&b(b(k([]))))&&b!==e&&n.call(b,i)&&(w=b),m.prototype=v.prototype=Object.create(w));function x(t){["next","throw","return"].forEach((function(r){u(t,r,(function(t){return this._invoke(r,t)}))}))}function E(t,r){var e;o(this,"_invoke",{value:function(o,i){function a(){return new r((function(e,a){!function e(o,i,a,c){var u;if("throw"!==(o=l(t[o],t,i)).type)return(i=(u=o.arg).value)&&"object"==typeof i&&n.call(i,"__await")?r.resolve(i.__await).then((function(t){e("next",t,a,c)}),(function(t){e("throw",t,a,c)})):r.resolve(i).then((function(t){u.value=t,a(u)}),(function(t){return e("throw",t,a,c)}));c(o.arg)}(o,i,e,a)}))}return e=e?e.then(a,a):a()}})}function j(t){var r={tryLoc:t[0]};1 in t&&(r.catchLoc=t[1]),2 in t&&(r.finallyLoc=t[2],r.afterLoc=t[3]),this.tryEntries.push(r)}function _(t){var r=t.completion||{};r.type="normal",delete r.arg,t.completion=r}function O(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(j,this),this.reset(!0)}function k(t){if(t){var e,o=t[i];if(o)return o.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length))return e=-1,(o=function o(){for(;++e<t.length;)if(n.call(t,e))return o.value=t[e],o.done=!1,o;return o.value=r,o.done=!0,o}).next=o}return{next:G}}function G(){return{value:r,done:!0}}return o(L,"constructor",{value:d.prototype=m,configurable:!0}),o(m,"constructor",{value:d,configurable:!0}),d.displayName=u(m,c,"GeneratorFunction"),t.isGeneratorFunction=function(t){return!!(t="function"==typeof t&&t.constructor)&&(t===d||"GeneratorFunction"===(t.displayName||t.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,m):(t.__proto__=m,u(t,c,"GeneratorFunction")),t.prototype=Object.create(L),t},t.awrap=function(t){return{__await:t}},x(E.prototype),u(E.prototype,a,(function(){return this})),t.AsyncIterator=E,t.async=function(r,e,n,o,i){void 0===i&&(i=Promise);var a=new E(h(r,e,n,o),i);return t.isGeneratorFunction(e)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},x(L),u(L,c,"Generator"),u(L,i,(function(){return this})),u(L,"toString",(function(){return"[object Generator]"})),t.keys=function(t){var r,e=Object(t),n=[];for(r in e)n.push(r);return n.reverse(),function t(){for(;n.length;){var r=n.pop();if(r in e)return t.value=r,t.done=!1,t}return t.done=!0,t}},t.values=k,O.prototype={constructor:O,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=r,this.done=!1,this.delegate=null,this.method="next",this.arg=r,this.tryEntries.forEach(_),!t)for(var e in this)"t"===e.charAt(0)&&n.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=r)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function o(n,o){return c.type="throw",c.arg=t,e.next=n,o&&(e.method="next",e.arg=r),!!o}for(var i=this.tryEntries.length-1;0<=i;--i){var a=this.tryEntries[i],c=a.completion;if("root"===a.tryLoc)return o("end");if(a.tryLoc<=this.prev){var u=n.call(a,"catchLoc"),h=n.call(a,"finallyLoc");if(u&&h){if(this.prev<a.catchLoc)return o(a.catchLoc,!0);if(this.prev<a.finallyLoc)return o(a.finallyLoc)}else if(u){if(this.prev<a.catchLoc)return o(a.catchLoc,!0)}else{if(!h)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return o(a.finallyLoc)}}}},abrupt:function(t,r){for(var e=this.tryEntries.length-1;0<=e;--e){var o=this.tryEntries[e];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}var a=(i=i&&("break"===t||"continue"===t)&&i.tryLoc<=r&&r<=i.finallyLoc?null:i)?i.completion:{};return a.type=t,a.arg=r,i?(this.method="next",this.next=i.finallyLoc,g):this.complete(a)},complete:function(t,r){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&r&&(this.next=r),g},finish:function(t){for(var r=this.tryEntries.length-1;0<=r;--r){var e=this.tryEntries[r];if(e.finallyLoc===t)return this.complete(e.completion,e.afterLoc),_(e),g}},catch:function(t){for(var r=this.tryEntries.length-1;0<=r;--r){var e,n,o=this.tryEntries[r];if(o.tryLoc===t)return"throw"===(e=o.completion).type&&(n=e.arg,_(o)),n}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:k(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=r),g}},t}("object"==typeof module?module.exports:{});try{regeneratorRuntime=runtime}catch(t){"object"==typeof globalThis?globalThis.regeneratorRuntime=runtime:Function("r","regeneratorRuntime = r")(runtime)} vendor/wp-polyfill-element-closest.min.js 0000666 00000000652 15123355174 0014555 0 ustar 00 !function(e){var t=window.Element.prototype;"function"!=typeof t.matches&&(t.matches=t.msMatchesSelector||t.mozMatchesSelector||t.webkitMatchesSelector||function(e){for(var t=(this.document||this.ownerDocument).querySelectorAll(e),o=0;t[o]&&t[o]!==this;)++o;return Boolean(t[o])}),"function"!=typeof t.closest&&(t.closest=function(e){for(var t=this;t&&1===t.nodeType;){if(t.matches(e))return t;t=t.parentNode}return null})}(); vendor/wp-polyfill-url.js 0000666 00000327374 15123355174 0011507 0 ustar 00 (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
module.exports = function (it) {
if (typeof it != 'function') {
throw TypeError(String(it) + ' is not a function');
} return it;
};
},{}],2:[function(require,module,exports){
var isObject = require('../internals/is-object');
module.exports = function (it) {
if (!isObject(it) && it !== null) {
throw TypeError("Can't set " + String(it) + ' as a prototype');
} return it;
};
},{"../internals/is-object":37}],3:[function(require,module,exports){
var wellKnownSymbol = require('../internals/well-known-symbol');
var create = require('../internals/object-create');
var definePropertyModule = require('../internals/object-define-property');
var UNSCOPABLES = wellKnownSymbol('unscopables');
var ArrayPrototype = Array.prototype;
// Array.prototype[@@unscopables]
// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
if (ArrayPrototype[UNSCOPABLES] == undefined) {
definePropertyModule.f(ArrayPrototype, UNSCOPABLES, {
configurable: true,
value: create(null)
});
}
// add a key to Array.prototype[@@unscopables]
module.exports = function (key) {
ArrayPrototype[UNSCOPABLES][key] = true;
};
},{"../internals/object-create":45,"../internals/object-define-property":47,"../internals/well-known-symbol":77}],4:[function(require,module,exports){
module.exports = function (it, Constructor, name) {
if (!(it instanceof Constructor)) {
throw TypeError('Incorrect ' + (name ? name + ' ' : '') + 'invocation');
} return it;
};
},{}],5:[function(require,module,exports){
var isObject = require('../internals/is-object');
module.exports = function (it) {
if (!isObject(it)) {
throw TypeError(String(it) + ' is not an object');
} return it;
};
},{"../internals/is-object":37}],6:[function(require,module,exports){
'use strict';
var bind = require('../internals/function-bind-context');
var toObject = require('../internals/to-object');
var callWithSafeIterationClosing = require('../internals/call-with-safe-iteration-closing');
var isArrayIteratorMethod = require('../internals/is-array-iterator-method');
var toLength = require('../internals/to-length');
var createProperty = require('../internals/create-property');
var getIteratorMethod = require('../internals/get-iterator-method');
// `Array.from` method implementation
// https://tc39.github.io/ecma262/#sec-array.from
module.exports = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
var O = toObject(arrayLike);
var C = typeof this == 'function' ? this : Array;
var argumentsLength = arguments.length;
var mapfn = argumentsLength > 1 ? arguments[1] : undefined;
var mapping = mapfn !== undefined;
var iteratorMethod = getIteratorMethod(O);
var index = 0;
var length, result, step, iterator, next, value;
if (mapping) mapfn = bind(mapfn, argumentsLength > 2 ? arguments[2] : undefined, 2);
// if the target is not iterable or it's an array with the default iterator - use a simple case
if (iteratorMethod != undefined && !(C == Array && isArrayIteratorMethod(iteratorMethod))) {
iterator = iteratorMethod.call(O);
next = iterator.next;
result = new C();
for (;!(step = next.call(iterator)).done; index++) {
value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value;
createProperty(result, index, value);
}
} else {
length = toLength(O.length);
result = new C(length);
for (;length > index; index++) {
value = mapping ? mapfn(O[index], index) : O[index];
createProperty(result, index, value);
}
}
result.length = index;
return result;
};
},{"../internals/call-with-safe-iteration-closing":8,"../internals/create-property":16,"../internals/function-bind-context":23,"../internals/get-iterator-method":25,"../internals/is-array-iterator-method":35,"../internals/to-length":71,"../internals/to-object":72}],7:[function(require,module,exports){
var toIndexedObject = require('../internals/to-indexed-object');
var toLength = require('../internals/to-length');
var toAbsoluteIndex = require('../internals/to-absolute-index');
// `Array.prototype.{ indexOf, includes }` methods implementation
var createMethod = function (IS_INCLUDES) {
return function ($this, el, fromIndex) {
var O = toIndexedObject($this);
var length = toLength(O.length);
var index = toAbsoluteIndex(fromIndex, length);
var value;
// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare
if (IS_INCLUDES && el != el) while (length > index) {
value = O[index++];
// eslint-disable-next-line no-self-compare
if (value != value) return true;
// Array#indexOf ignores holes, Array#includes - not
} else for (;length > index; index++) {
if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
module.exports = {
// `Array.prototype.includes` method
// https://tc39.github.io/ecma262/#sec-array.prototype.includes
includes: createMethod(true),
// `Array.prototype.indexOf` method
// https://tc39.github.io/ecma262/#sec-array.prototype.indexof
indexOf: createMethod(false)
};
},{"../internals/to-absolute-index":68,"../internals/to-indexed-object":69,"../internals/to-length":71}],8:[function(require,module,exports){
var anObject = require('../internals/an-object');
// call something on iterator step with safe closing on error
module.exports = function (iterator, fn, value, ENTRIES) {
try {
return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch (error) {
var returnMethod = iterator['return'];
if (returnMethod !== undefined) anObject(returnMethod.call(iterator));
throw error;
}
};
},{"../internals/an-object":5}],9:[function(require,module,exports){
var toString = {}.toString;
module.exports = function (it) {
return toString.call(it).slice(8, -1);
};
},{}],10:[function(require,module,exports){
var TO_STRING_TAG_SUPPORT = require('../internals/to-string-tag-support');
var classofRaw = require('../internals/classof-raw');
var wellKnownSymbol = require('../internals/well-known-symbol');
var TO_STRING_TAG = wellKnownSymbol('toStringTag');
// ES3 wrong here
var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function (it, key) {
try {
return it[key];
} catch (error) { /* empty */ }
};
// getting tag from ES6+ `Object.prototype.toString`
module.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) {
var O, tag, result;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (tag = tryGet(O = Object(it), TO_STRING_TAG)) == 'string' ? tag
// builtinTag case
: CORRECT_ARGUMENTS ? classofRaw(O)
// ES3 arguments fallback
: (result = classofRaw(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : result;
};
},{"../internals/classof-raw":9,"../internals/to-string-tag-support":74,"../internals/well-known-symbol":77}],11:[function(require,module,exports){
var has = require('../internals/has');
var ownKeys = require('../internals/own-keys');
var getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor');
var definePropertyModule = require('../internals/object-define-property');
module.exports = function (target, source) {
var keys = ownKeys(source);
var defineProperty = definePropertyModule.f;
var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key));
}
};
},{"../internals/has":28,"../internals/object-define-property":47,"../internals/object-get-own-property-descriptor":48,"../internals/own-keys":56}],12:[function(require,module,exports){
var fails = require('../internals/fails');
module.exports = !fails(function () {
function F() { /* empty */ }
F.prototype.constructor = null;
return Object.getPrototypeOf(new F()) !== F.prototype;
});
},{"../internals/fails":22}],13:[function(require,module,exports){
'use strict';
var IteratorPrototype = require('../internals/iterators-core').IteratorPrototype;
var create = require('../internals/object-create');
var createPropertyDescriptor = require('../internals/create-property-descriptor');
var setToStringTag = require('../internals/set-to-string-tag');
var Iterators = require('../internals/iterators');
var returnThis = function () { return this; };
module.exports = function (IteratorConstructor, NAME, next) {
var TO_STRING_TAG = NAME + ' Iterator';
IteratorConstructor.prototype = create(IteratorPrototype, { next: createPropertyDescriptor(1, next) });
setToStringTag(IteratorConstructor, TO_STRING_TAG, false, true);
Iterators[TO_STRING_TAG] = returnThis;
return IteratorConstructor;
};
},{"../internals/create-property-descriptor":15,"../internals/iterators":40,"../internals/iterators-core":39,"../internals/object-create":45,"../internals/set-to-string-tag":62}],14:[function(require,module,exports){
var DESCRIPTORS = require('../internals/descriptors');
var definePropertyModule = require('../internals/object-define-property');
var createPropertyDescriptor = require('../internals/create-property-descriptor');
module.exports = DESCRIPTORS ? function (object, key, value) {
return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));
} : function (object, key, value) {
object[key] = value;
return object;
};
},{"../internals/create-property-descriptor":15,"../internals/descriptors":18,"../internals/object-define-property":47}],15:[function(require,module,exports){
module.exports = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
},{}],16:[function(require,module,exports){
'use strict';
var toPrimitive = require('../internals/to-primitive');
var definePropertyModule = require('../internals/object-define-property');
var createPropertyDescriptor = require('../internals/create-property-descriptor');
module.exports = function (object, key, value) {
var propertyKey = toPrimitive(key);
if (propertyKey in object) definePropertyModule.f(object, propertyKey, createPropertyDescriptor(0, value));
else object[propertyKey] = value;
};
},{"../internals/create-property-descriptor":15,"../internals/object-define-property":47,"../internals/to-primitive":73}],17:[function(require,module,exports){
'use strict';
var $ = require('../internals/export');
var createIteratorConstructor = require('../internals/create-iterator-constructor');
var getPrototypeOf = require('../internals/object-get-prototype-of');
var setPrototypeOf = require('../internals/object-set-prototype-of');
var setToStringTag = require('../internals/set-to-string-tag');
var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
var redefine = require('../internals/redefine');
var wellKnownSymbol = require('../internals/well-known-symbol');
var IS_PURE = require('../internals/is-pure');
var Iterators = require('../internals/iterators');
var IteratorsCore = require('../internals/iterators-core');
var IteratorPrototype = IteratorsCore.IteratorPrototype;
var BUGGY_SAFARI_ITERATORS = IteratorsCore.BUGGY_SAFARI_ITERATORS;
var ITERATOR = wellKnownSymbol('iterator');
var KEYS = 'keys';
var VALUES = 'values';
var ENTRIES = 'entries';
var returnThis = function () { return this; };
module.exports = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) {
createIteratorConstructor(IteratorConstructor, NAME, next);
var getIterationMethod = function (KIND) {
if (KIND === DEFAULT && defaultIterator) return defaultIterator;
if (!BUGGY_SAFARI_ITERATORS && KIND in IterablePrototype) return IterablePrototype[KIND];
switch (KIND) {
case KEYS: return function keys() { return new IteratorConstructor(this, KIND); };
case VALUES: return function values() { return new IteratorConstructor(this, KIND); };
case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); };
} return function () { return new IteratorConstructor(this); };
};
var TO_STRING_TAG = NAME + ' Iterator';
var INCORRECT_VALUES_NAME = false;
var IterablePrototype = Iterable.prototype;
var nativeIterator = IterablePrototype[ITERATOR]
|| IterablePrototype['@@iterator']
|| DEFAULT && IterablePrototype[DEFAULT];
var defaultIterator = !BUGGY_SAFARI_ITERATORS && nativeIterator || getIterationMethod(DEFAULT);
var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator;
var CurrentIteratorPrototype, methods, KEY;
// fix native
if (anyNativeIterator) {
CurrentIteratorPrototype = getPrototypeOf(anyNativeIterator.call(new Iterable()));
if (IteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) {
if (!IS_PURE && getPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype) {
if (setPrototypeOf) {
setPrototypeOf(CurrentIteratorPrototype, IteratorPrototype);
} else if (typeof CurrentIteratorPrototype[ITERATOR] != 'function') {
createNonEnumerableProperty(CurrentIteratorPrototype, ITERATOR, returnThis);
}
}
// Set @@toStringTag to native iterators
setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true, true);
if (IS_PURE) Iterators[TO_STRING_TAG] = returnThis;
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if (DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) {
INCORRECT_VALUES_NAME = true;
defaultIterator = function values() { return nativeIterator.call(this); };
}
// define iterator
if ((!IS_PURE || FORCED) && IterablePrototype[ITERATOR] !== defaultIterator) {
createNonEnumerableProperty(IterablePrototype, ITERATOR, defaultIterator);
}
Iterators[NAME] = defaultIterator;
// export additional methods
if (DEFAULT) {
methods = {
values: getIterationMethod(VALUES),
keys: IS_SET ? defaultIterator : getIterationMethod(KEYS),
entries: getIterationMethod(ENTRIES)
};
if (FORCED) for (KEY in methods) {
if (BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) {
redefine(IterablePrototype, KEY, methods[KEY]);
}
} else $({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME }, methods);
}
return methods;
};
},{"../internals/create-iterator-constructor":13,"../internals/create-non-enumerable-property":14,"../internals/export":21,"../internals/is-pure":38,"../internals/iterators":40,"../internals/iterators-core":39,"../internals/object-get-prototype-of":51,"../internals/object-set-prototype-of":55,"../internals/redefine":59,"../internals/set-to-string-tag":62,"../internals/well-known-symbol":77}],18:[function(require,module,exports){
var fails = require('../internals/fails');
// Thank's IE8 for his funny defineProperty
module.exports = !fails(function () {
return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7;
});
},{"../internals/fails":22}],19:[function(require,module,exports){
var global = require('../internals/global');
var isObject = require('../internals/is-object');
var document = global.document;
// typeof document.createElement is 'object' in old IE
var EXISTS = isObject(document) && isObject(document.createElement);
module.exports = function (it) {
return EXISTS ? document.createElement(it) : {};
};
},{"../internals/global":27,"../internals/is-object":37}],20:[function(require,module,exports){
// IE8- don't enum bug keys
module.exports = [
'constructor',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toLocaleString',
'toString',
'valueOf'
];
},{}],21:[function(require,module,exports){
var global = require('../internals/global');
var getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f;
var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
var redefine = require('../internals/redefine');
var setGlobal = require('../internals/set-global');
var copyConstructorProperties = require('../internals/copy-constructor-properties');
var isForced = require('../internals/is-forced');
/*
options.target - name of the target object
options.global - target is the global object
options.stat - export as static methods of target
options.proto - export as prototype methods of target
options.real - real prototype method for the `pure` version
options.forced - export even if the native feature is available
options.bind - bind methods to the target, required for the `pure` version
options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
options.unsafe - use the simple assignment of property instead of delete + defineProperty
options.sham - add a flag to not completely full polyfills
options.enumerable - export as enumerable property
options.noTargetGet - prevent calling a getter on target
*/
module.exports = function (options, source) {
var TARGET = options.target;
var GLOBAL = options.global;
var STATIC = options.stat;
var FORCED, target, key, targetProperty, sourceProperty, descriptor;
if (GLOBAL) {
target = global;
} else if (STATIC) {
target = global[TARGET] || setGlobal(TARGET, {});
} else {
target = (global[TARGET] || {}).prototype;
}
if (target) for (key in source) {
sourceProperty = source[key];
if (options.noTargetGet) {
descriptor = getOwnPropertyDescriptor(target, key);
targetProperty = descriptor && descriptor.value;
} else targetProperty = target[key];
FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
// contained in target
if (!FORCED && targetProperty !== undefined) {
if (typeof sourceProperty === typeof targetProperty) continue;
copyConstructorProperties(sourceProperty, targetProperty);
}
// add a flag to not completely full polyfills
if (options.sham || (targetProperty && targetProperty.sham)) {
createNonEnumerableProperty(sourceProperty, 'sham', true);
}
// extend global
redefine(target, key, sourceProperty, options);
}
};
},{"../internals/copy-constructor-properties":11,"../internals/create-non-enumerable-property":14,"../internals/global":27,"../internals/is-forced":36,"../internals/object-get-own-property-descriptor":48,"../internals/redefine":59,"../internals/set-global":61}],22:[function(require,module,exports){
module.exports = function (exec) {
try {
return !!exec();
} catch (error) {
return true;
}
};
},{}],23:[function(require,module,exports){
var aFunction = require('../internals/a-function');
// optional / simple context binding
module.exports = function (fn, that, length) {
aFunction(fn);
if (that === undefined) return fn;
switch (length) {
case 0: return function () {
return fn.call(that);
};
case 1: return function (a) {
return fn.call(that, a);
};
case 2: return function (a, b) {
return fn.call(that, a, b);
};
case 3: return function (a, b, c) {
return fn.call(that, a, b, c);
};
}
return function (/* ...args */) {
return fn.apply(that, arguments);
};
};
},{"../internals/a-function":1}],24:[function(require,module,exports){
var path = require('../internals/path');
var global = require('../internals/global');
var aFunction = function (variable) {
return typeof variable == 'function' ? variable : undefined;
};
module.exports = function (namespace, method) {
return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global[namespace])
: path[namespace] && path[namespace][method] || global[namespace] && global[namespace][method];
};
},{"../internals/global":27,"../internals/path":57}],25:[function(require,module,exports){
var classof = require('../internals/classof');
var Iterators = require('../internals/iterators');
var wellKnownSymbol = require('../internals/well-known-symbol');
var ITERATOR = wellKnownSymbol('iterator');
module.exports = function (it) {
if (it != undefined) return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
},{"../internals/classof":10,"../internals/iterators":40,"../internals/well-known-symbol":77}],26:[function(require,module,exports){
var anObject = require('../internals/an-object');
var getIteratorMethod = require('../internals/get-iterator-method');
module.exports = function (it) {
var iteratorMethod = getIteratorMethod(it);
if (typeof iteratorMethod != 'function') {
throw TypeError(String(it) + ' is not iterable');
} return anObject(iteratorMethod.call(it));
};
},{"../internals/an-object":5,"../internals/get-iterator-method":25}],27:[function(require,module,exports){
(function (global){
var check = function (it) {
return it && it.Math == Math && it;
};
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
module.exports =
// eslint-disable-next-line no-undef
check(typeof globalThis == 'object' && globalThis) ||
check(typeof window == 'object' && window) ||
check(typeof self == 'object' && self) ||
check(typeof global == 'object' && global) ||
// eslint-disable-next-line no-new-func
Function('return this')();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],28:[function(require,module,exports){
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function (it, key) {
return hasOwnProperty.call(it, key);
};
},{}],29:[function(require,module,exports){
module.exports = {};
},{}],30:[function(require,module,exports){
var getBuiltIn = require('../internals/get-built-in');
module.exports = getBuiltIn('document', 'documentElement');
},{"../internals/get-built-in":24}],31:[function(require,module,exports){
var DESCRIPTORS = require('../internals/descriptors');
var fails = require('../internals/fails');
var createElement = require('../internals/document-create-element');
// Thank's IE8 for his funny defineProperty
module.exports = !DESCRIPTORS && !fails(function () {
return Object.defineProperty(createElement('div'), 'a', {
get: function () { return 7; }
}).a != 7;
});
},{"../internals/descriptors":18,"../internals/document-create-element":19,"../internals/fails":22}],32:[function(require,module,exports){
var fails = require('../internals/fails');
var classof = require('../internals/classof-raw');
var split = ''.split;
// fallback for non-array-like ES3 and non-enumerable old V8 strings
module.exports = fails(function () {
// throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
// eslint-disable-next-line no-prototype-builtins
return !Object('z').propertyIsEnumerable(0);
}) ? function (it) {
return classof(it) == 'String' ? split.call(it, '') : Object(it);
} : Object;
},{"../internals/classof-raw":9,"../internals/fails":22}],33:[function(require,module,exports){
var store = require('../internals/shared-store');
var functionToString = Function.toString;
// this helper broken in `3.4.1-3.4.4`, so we can't use `shared` helper
if (typeof store.inspectSource != 'function') {
store.inspectSource = function (it) {
return functionToString.call(it);
};
}
module.exports = store.inspectSource;
},{"../internals/shared-store":64}],34:[function(require,module,exports){
var NATIVE_WEAK_MAP = require('../internals/native-weak-map');
var global = require('../internals/global');
var isObject = require('../internals/is-object');
var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
var objectHas = require('../internals/has');
var sharedKey = require('../internals/shared-key');
var hiddenKeys = require('../internals/hidden-keys');
var WeakMap = global.WeakMap;
var set, get, has;
var enforce = function (it) {
return has(it) ? get(it) : set(it, {});
};
var getterFor = function (TYPE) {
return function (it) {
var state;
if (!isObject(it) || (state = get(it)).type !== TYPE) {
throw TypeError('Incompatible receiver, ' + TYPE + ' required');
} return state;
};
};
if (NATIVE_WEAK_MAP) {
var store = new WeakMap();
var wmget = store.get;
var wmhas = store.has;
var wmset = store.set;
set = function (it, metadata) {
wmset.call(store, it, metadata);
return metadata;
};
get = function (it) {
return wmget.call(store, it) || {};
};
has = function (it) {
return wmhas.call(store, it);
};
} else {
var STATE = sharedKey('state');
hiddenKeys[STATE] = true;
set = function (it, metadata) {
createNonEnumerableProperty(it, STATE, metadata);
return metadata;
};
get = function (it) {
return objectHas(it, STATE) ? it[STATE] : {};
};
has = function (it) {
return objectHas(it, STATE);
};
}
module.exports = {
set: set,
get: get,
has: has,
enforce: enforce,
getterFor: getterFor
};
},{"../internals/create-non-enumerable-property":14,"../internals/global":27,"../internals/has":28,"../internals/hidden-keys":29,"../internals/is-object":37,"../internals/native-weak-map":43,"../internals/shared-key":63}],35:[function(require,module,exports){
var wellKnownSymbol = require('../internals/well-known-symbol');
var Iterators = require('../internals/iterators');
var ITERATOR = wellKnownSymbol('iterator');
var ArrayPrototype = Array.prototype;
// check on default Array iterator
module.exports = function (it) {
return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it);
};
},{"../internals/iterators":40,"../internals/well-known-symbol":77}],36:[function(require,module,exports){
var fails = require('../internals/fails');
var replacement = /#|\.prototype\./;
var isForced = function (feature, detection) {
var value = data[normalize(feature)];
return value == POLYFILL ? true
: value == NATIVE ? false
: typeof detection == 'function' ? fails(detection)
: !!detection;
};
var normalize = isForced.normalize = function (string) {
return String(string).replace(replacement, '.').toLowerCase();
};
var data = isForced.data = {};
var NATIVE = isForced.NATIVE = 'N';
var POLYFILL = isForced.POLYFILL = 'P';
module.exports = isForced;
},{"../internals/fails":22}],37:[function(require,module,exports){
module.exports = function (it) {
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
},{}],38:[function(require,module,exports){
module.exports = false;
},{}],39:[function(require,module,exports){
'use strict';
var getPrototypeOf = require('../internals/object-get-prototype-of');
var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
var has = require('../internals/has');
var wellKnownSymbol = require('../internals/well-known-symbol');
var IS_PURE = require('../internals/is-pure');
var ITERATOR = wellKnownSymbol('iterator');
var BUGGY_SAFARI_ITERATORS = false;
var returnThis = function () { return this; };
// `%IteratorPrototype%` object
// https://tc39.github.io/ecma262/#sec-%iteratorprototype%-object
var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;
if ([].keys) {
arrayIterator = [].keys();
// Safari 8 has buggy iterators w/o `next`
if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;
else {
PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator));
if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;
}
}
if (IteratorPrototype == undefined) IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
if (!IS_PURE && !has(IteratorPrototype, ITERATOR)) {
createNonEnumerableProperty(IteratorPrototype, ITERATOR, returnThis);
}
module.exports = {
IteratorPrototype: IteratorPrototype,
BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS
};
},{"../internals/create-non-enumerable-property":14,"../internals/has":28,"../internals/is-pure":38,"../internals/object-get-prototype-of":51,"../internals/well-known-symbol":77}],40:[function(require,module,exports){
arguments[4][29][0].apply(exports,arguments)
},{"dup":29}],41:[function(require,module,exports){
var fails = require('../internals/fails');
module.exports = !!Object.getOwnPropertySymbols && !fails(function () {
// Chrome 38 Symbol has incorrect toString conversion
// eslint-disable-next-line no-undef
return !String(Symbol());
});
},{"../internals/fails":22}],42:[function(require,module,exports){
var fails = require('../internals/fails');
var wellKnownSymbol = require('../internals/well-known-symbol');
var IS_PURE = require('../internals/is-pure');
var ITERATOR = wellKnownSymbol('iterator');
module.exports = !fails(function () {
var url = new URL('b?a=1&b=2&c=3', 'http://a');
var searchParams = url.searchParams;
var result = '';
url.pathname = 'c%20d';
searchParams.forEach(function (value, key) {
searchParams['delete']('b');
result += key + value;
});
return (IS_PURE && !url.toJSON)
|| !searchParams.sort
|| url.href !== 'http://a/c%20d?a=1&c=3'
|| searchParams.get('c') !== '3'
|| String(new URLSearchParams('?a=1')) !== 'a=1'
|| !searchParams[ITERATOR]
// throws in Edge
|| new URL('https://a@b').username !== 'a'
|| new URLSearchParams(new URLSearchParams('a=b')).get('a') !== 'b'
// not punycoded in Edge
|| new URL('http://тест').host !== 'xn--e1aybc'
// not escaped in Chrome 62-
|| new URL('http://a#б').hash !== '#%D0%B1'
// fails in Chrome 66-
|| result !== 'a1c3'
// throws in Safari
|| new URL('http://x', undefined).host !== 'x';
});
},{"../internals/fails":22,"../internals/is-pure":38,"../internals/well-known-symbol":77}],43:[function(require,module,exports){
var global = require('../internals/global');
var inspectSource = require('../internals/inspect-source');
var WeakMap = global.WeakMap;
module.exports = typeof WeakMap === 'function' && /native code/.test(inspectSource(WeakMap));
},{"../internals/global":27,"../internals/inspect-source":33}],44:[function(require,module,exports){
'use strict';
var DESCRIPTORS = require('../internals/descriptors');
var fails = require('../internals/fails');
var objectKeys = require('../internals/object-keys');
var getOwnPropertySymbolsModule = require('../internals/object-get-own-property-symbols');
var propertyIsEnumerableModule = require('../internals/object-property-is-enumerable');
var toObject = require('../internals/to-object');
var IndexedObject = require('../internals/indexed-object');
var nativeAssign = Object.assign;
var defineProperty = Object.defineProperty;
// `Object.assign` method
// https://tc39.github.io/ecma262/#sec-object.assign
module.exports = !nativeAssign || fails(function () {
// should have correct order of operations (Edge bug)
if (DESCRIPTORS && nativeAssign({ b: 1 }, nativeAssign(defineProperty({}, 'a', {
enumerable: true,
get: function () {
defineProperty(this, 'b', {
value: 3,
enumerable: false
});
}
}), { b: 2 })).b !== 1) return true;
// should work with symbols and should have deterministic property order (V8 bug)
var A = {};
var B = {};
// eslint-disable-next-line no-undef
var symbol = Symbol();
var alphabet = 'abcdefghijklmnopqrst';
A[symbol] = 7;
alphabet.split('').forEach(function (chr) { B[chr] = chr; });
return nativeAssign({}, A)[symbol] != 7 || objectKeys(nativeAssign({}, B)).join('') != alphabet;
}) ? function assign(target, source) { // eslint-disable-line no-unused-vars
var T = toObject(target);
var argumentsLength = arguments.length;
var index = 1;
var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
var propertyIsEnumerable = propertyIsEnumerableModule.f;
while (argumentsLength > index) {
var S = IndexedObject(arguments[index++]);
var keys = getOwnPropertySymbols ? objectKeys(S).concat(getOwnPropertySymbols(S)) : objectKeys(S);
var length = keys.length;
var j = 0;
var key;
while (length > j) {
key = keys[j++];
if (!DESCRIPTORS || propertyIsEnumerable.call(S, key)) T[key] = S[key];
}
} return T;
} : nativeAssign;
},{"../internals/descriptors":18,"../internals/fails":22,"../internals/indexed-object":32,"../internals/object-get-own-property-symbols":50,"../internals/object-keys":53,"../internals/object-property-is-enumerable":54,"../internals/to-object":72}],45:[function(require,module,exports){
var anObject = require('../internals/an-object');
var defineProperties = require('../internals/object-define-properties');
var enumBugKeys = require('../internals/enum-bug-keys');
var hiddenKeys = require('../internals/hidden-keys');
var html = require('../internals/html');
var documentCreateElement = require('../internals/document-create-element');
var sharedKey = require('../internals/shared-key');
var GT = '>';
var LT = '<';
var PROTOTYPE = 'prototype';
var SCRIPT = 'script';
var IE_PROTO = sharedKey('IE_PROTO');
var EmptyConstructor = function () { /* empty */ };
var scriptTag = function (content) {
return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;
};
// Create object with fake `null` prototype: use ActiveX Object with cleared prototype
var NullProtoObjectViaActiveX = function (activeXDocument) {
activeXDocument.write(scriptTag(''));
activeXDocument.close();
var temp = activeXDocument.parentWindow.Object;
activeXDocument = null; // avoid memory leak
return temp;
};
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var NullProtoObjectViaIFrame = function () {
// Thrash, waste and sodomy: IE GC bug
var iframe = documentCreateElement('iframe');
var JS = 'java' + SCRIPT + ':';
var iframeDocument;
iframe.style.display = 'none';
html.appendChild(iframe);
// https://github.com/zloirock/core-js/issues/475
iframe.src = String(JS);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(scriptTag('document.F=Object'));
iframeDocument.close();
return iframeDocument.F;
};
// Check for document.domain and active x support
// No need to use active x approach when document.domain is not set
// see https://github.com/es-shims/es5-shim/issues/150
// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
// avoid IE GC bug
var activeXDocument;
var NullProtoObject = function () {
try {
/* global ActiveXObject */
activeXDocument = document.domain && new ActiveXObject('htmlfile');
} catch (error) { /* ignore */ }
NullProtoObject = activeXDocument ? NullProtoObjectViaActiveX(activeXDocument) : NullProtoObjectViaIFrame();
var length = enumBugKeys.length;
while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];
return NullProtoObject();
};
hiddenKeys[IE_PROTO] = true;
// `Object.create` method
// https://tc39.github.io/ecma262/#sec-object.create
module.exports = Object.create || function create(O, Properties) {
var result;
if (O !== null) {
EmptyConstructor[PROTOTYPE] = anObject(O);
result = new EmptyConstructor();
EmptyConstructor[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = NullProtoObject();
return Properties === undefined ? result : defineProperties(result, Properties);
};
},{"../internals/an-object":5,"../internals/document-create-element":19,"../internals/enum-bug-keys":20,"../internals/hidden-keys":29,"../internals/html":30,"../internals/object-define-properties":46,"../internals/shared-key":63}],46:[function(require,module,exports){
var DESCRIPTORS = require('../internals/descriptors');
var definePropertyModule = require('../internals/object-define-property');
var anObject = require('../internals/an-object');
var objectKeys = require('../internals/object-keys');
// `Object.defineProperties` method
// https://tc39.github.io/ecma262/#sec-object.defineproperties
module.exports = DESCRIPTORS ? Object.defineProperties : function defineProperties(O, Properties) {
anObject(O);
var keys = objectKeys(Properties);
var length = keys.length;
var index = 0;
var key;
while (length > index) definePropertyModule.f(O, key = keys[index++], Properties[key]);
return O;
};
},{"../internals/an-object":5,"../internals/descriptors":18,"../internals/object-define-property":47,"../internals/object-keys":53}],47:[function(require,module,exports){
var DESCRIPTORS = require('../internals/descriptors');
var IE8_DOM_DEFINE = require('../internals/ie8-dom-define');
var anObject = require('../internals/an-object');
var toPrimitive = require('../internals/to-primitive');
var nativeDefineProperty = Object.defineProperty;
// `Object.defineProperty` method
// https://tc39.github.io/ecma262/#sec-object.defineproperty
exports.f = DESCRIPTORS ? nativeDefineProperty : function defineProperty(O, P, Attributes) {
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if (IE8_DOM_DEFINE) try {
return nativeDefineProperty(O, P, Attributes);
} catch (error) { /* empty */ }
if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
},{"../internals/an-object":5,"../internals/descriptors":18,"../internals/ie8-dom-define":31,"../internals/to-primitive":73}],48:[function(require,module,exports){
var DESCRIPTORS = require('../internals/descriptors');
var propertyIsEnumerableModule = require('../internals/object-property-is-enumerable');
var createPropertyDescriptor = require('../internals/create-property-descriptor');
var toIndexedObject = require('../internals/to-indexed-object');
var toPrimitive = require('../internals/to-primitive');
var has = require('../internals/has');
var IE8_DOM_DEFINE = require('../internals/ie8-dom-define');
var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// `Object.getOwnPropertyDescriptor` method
// https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor
exports.f = DESCRIPTORS ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
O = toIndexedObject(O);
P = toPrimitive(P, true);
if (IE8_DOM_DEFINE) try {
return nativeGetOwnPropertyDescriptor(O, P);
} catch (error) { /* empty */ }
if (has(O, P)) return createPropertyDescriptor(!propertyIsEnumerableModule.f.call(O, P), O[P]);
};
},{"../internals/create-property-descriptor":15,"../internals/descriptors":18,"../internals/has":28,"../internals/ie8-dom-define":31,"../internals/object-property-is-enumerable":54,"../internals/to-indexed-object":69,"../internals/to-primitive":73}],49:[function(require,module,exports){
var internalObjectKeys = require('../internals/object-keys-internal');
var enumBugKeys = require('../internals/enum-bug-keys');
var hiddenKeys = enumBugKeys.concat('length', 'prototype');
// `Object.getOwnPropertyNames` method
// https://tc39.github.io/ecma262/#sec-object.getownpropertynames
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
return internalObjectKeys(O, hiddenKeys);
};
},{"../internals/enum-bug-keys":20,"../internals/object-keys-internal":52}],50:[function(require,module,exports){
exports.f = Object.getOwnPropertySymbols;
},{}],51:[function(require,module,exports){
var has = require('../internals/has');
var toObject = require('../internals/to-object');
var sharedKey = require('../internals/shared-key');
var CORRECT_PROTOTYPE_GETTER = require('../internals/correct-prototype-getter');
var IE_PROTO = sharedKey('IE_PROTO');
var ObjectPrototype = Object.prototype;
// `Object.getPrototypeOf` method
// https://tc39.github.io/ecma262/#sec-object.getprototypeof
module.exports = CORRECT_PROTOTYPE_GETTER ? Object.getPrototypeOf : function (O) {
O = toObject(O);
if (has(O, IE_PROTO)) return O[IE_PROTO];
if (typeof O.constructor == 'function' && O instanceof O.constructor) {
return O.constructor.prototype;
} return O instanceof Object ? ObjectPrototype : null;
};
},{"../internals/correct-prototype-getter":12,"../internals/has":28,"../internals/shared-key":63,"../internals/to-object":72}],52:[function(require,module,exports){
var has = require('../internals/has');
var toIndexedObject = require('../internals/to-indexed-object');
var indexOf = require('../internals/array-includes').indexOf;
var hiddenKeys = require('../internals/hidden-keys');
module.exports = function (object, names) {
var O = toIndexedObject(object);
var i = 0;
var result = [];
var key;
for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while (names.length > i) if (has(O, key = names[i++])) {
~indexOf(result, key) || result.push(key);
}
return result;
};
},{"../internals/array-includes":7,"../internals/has":28,"../internals/hidden-keys":29,"../internals/to-indexed-object":69}],53:[function(require,module,exports){
var internalObjectKeys = require('../internals/object-keys-internal');
var enumBugKeys = require('../internals/enum-bug-keys');
// `Object.keys` method
// https://tc39.github.io/ecma262/#sec-object.keys
module.exports = Object.keys || function keys(O) {
return internalObjectKeys(O, enumBugKeys);
};
},{"../internals/enum-bug-keys":20,"../internals/object-keys-internal":52}],54:[function(require,module,exports){
'use strict';
var nativePropertyIsEnumerable = {}.propertyIsEnumerable;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// Nashorn ~ JDK8 bug
var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1);
// `Object.prototype.propertyIsEnumerable` method implementation
// https://tc39.github.io/ecma262/#sec-object.prototype.propertyisenumerable
exports.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
var descriptor = getOwnPropertyDescriptor(this, V);
return !!descriptor && descriptor.enumerable;
} : nativePropertyIsEnumerable;
},{}],55:[function(require,module,exports){
var anObject = require('../internals/an-object');
var aPossiblePrototype = require('../internals/a-possible-prototype');
// `Object.setPrototypeOf` method
// https://tc39.github.io/ecma262/#sec-object.setprototypeof
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
module.exports = Object.setPrototypeOf || ('__proto__' in {} ? function () {
var CORRECT_SETTER = false;
var test = {};
var setter;
try {
setter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set;
setter.call(test, []);
CORRECT_SETTER = test instanceof Array;
} catch (error) { /* empty */ }
return function setPrototypeOf(O, proto) {
anObject(O);
aPossiblePrototype(proto);
if (CORRECT_SETTER) setter.call(O, proto);
else O.__proto__ = proto;
return O;
};
}() : undefined);
},{"../internals/a-possible-prototype":2,"../internals/an-object":5}],56:[function(require,module,exports){
var getBuiltIn = require('../internals/get-built-in');
var getOwnPropertyNamesModule = require('../internals/object-get-own-property-names');
var getOwnPropertySymbolsModule = require('../internals/object-get-own-property-symbols');
var anObject = require('../internals/an-object');
// all object keys, includes non-enumerable and symbols
module.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
var keys = getOwnPropertyNamesModule.f(anObject(it));
var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys;
};
},{"../internals/an-object":5,"../internals/get-built-in":24,"../internals/object-get-own-property-names":49,"../internals/object-get-own-property-symbols":50}],57:[function(require,module,exports){
var global = require('../internals/global');
module.exports = global;
},{"../internals/global":27}],58:[function(require,module,exports){
var redefine = require('../internals/redefine');
module.exports = function (target, src, options) {
for (var key in src) redefine(target, key, src[key], options);
return target;
};
},{"../internals/redefine":59}],59:[function(require,module,exports){
var global = require('../internals/global');
var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
var has = require('../internals/has');
var setGlobal = require('../internals/set-global');
var inspectSource = require('../internals/inspect-source');
var InternalStateModule = require('../internals/internal-state');
var getInternalState = InternalStateModule.get;
var enforceInternalState = InternalStateModule.enforce;
var TEMPLATE = String(String).split('String');
(module.exports = function (O, key, value, options) {
var unsafe = options ? !!options.unsafe : false;
var simple = options ? !!options.enumerable : false;
var noTargetGet = options ? !!options.noTargetGet : false;
if (typeof value == 'function') {
if (typeof key == 'string' && !has(value, 'name')) createNonEnumerableProperty(value, 'name', key);
enforceInternalState(value).source = TEMPLATE.join(typeof key == 'string' ? key : '');
}
if (O === global) {
if (simple) O[key] = value;
else setGlobal(key, value);
return;
} else if (!unsafe) {
delete O[key];
} else if (!noTargetGet && O[key]) {
simple = true;
}
if (simple) O[key] = value;
else createNonEnumerableProperty(O, key, value);
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, 'toString', function toString() {
return typeof this == 'function' && getInternalState(this).source || inspectSource(this);
});
},{"../internals/create-non-enumerable-property":14,"../internals/global":27,"../internals/has":28,"../internals/inspect-source":33,"../internals/internal-state":34,"../internals/set-global":61}],60:[function(require,module,exports){
// `RequireObjectCoercible` abstract operation
// https://tc39.github.io/ecma262/#sec-requireobjectcoercible
module.exports = function (it) {
if (it == undefined) throw TypeError("Can't call method on " + it);
return it;
};
},{}],61:[function(require,module,exports){
var global = require('../internals/global');
var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
module.exports = function (key, value) {
try {
createNonEnumerableProperty(global, key, value);
} catch (error) {
global[key] = value;
} return value;
};
},{"../internals/create-non-enumerable-property":14,"../internals/global":27}],62:[function(require,module,exports){
var defineProperty = require('../internals/object-define-property').f;
var has = require('../internals/has');
var wellKnownSymbol = require('../internals/well-known-symbol');
var TO_STRING_TAG = wellKnownSymbol('toStringTag');
module.exports = function (it, TAG, STATIC) {
if (it && !has(it = STATIC ? it : it.prototype, TO_STRING_TAG)) {
defineProperty(it, TO_STRING_TAG, { configurable: true, value: TAG });
}
};
},{"../internals/has":28,"../internals/object-define-property":47,"../internals/well-known-symbol":77}],63:[function(require,module,exports){
var shared = require('../internals/shared');
var uid = require('../internals/uid');
var keys = shared('keys');
module.exports = function (key) {
return keys[key] || (keys[key] = uid(key));
};
},{"../internals/shared":65,"../internals/uid":75}],64:[function(require,module,exports){
var global = require('../internals/global');
var setGlobal = require('../internals/set-global');
var SHARED = '__core-js_shared__';
var store = global[SHARED] || setGlobal(SHARED, {});
module.exports = store;
},{"../internals/global":27,"../internals/set-global":61}],65:[function(require,module,exports){
var IS_PURE = require('../internals/is-pure');
var store = require('../internals/shared-store');
(module.exports = function (key, value) {
return store[key] || (store[key] = value !== undefined ? value : {});
})('versions', []).push({
version: '3.6.4',
mode: IS_PURE ? 'pure' : 'global',
copyright: '© 2020 Denis Pushkarev (zloirock.ru)'
});
},{"../internals/is-pure":38,"../internals/shared-store":64}],66:[function(require,module,exports){
var toInteger = require('../internals/to-integer');
var requireObjectCoercible = require('../internals/require-object-coercible');
// `String.prototype.{ codePointAt, at }` methods implementation
var createMethod = function (CONVERT_TO_STRING) {
return function ($this, pos) {
var S = String(requireObjectCoercible($this));
var position = toInteger(pos);
var size = S.length;
var first, second;
if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined;
first = S.charCodeAt(position);
return first < 0xD800 || first > 0xDBFF || position + 1 === size
|| (second = S.charCodeAt(position + 1)) < 0xDC00 || second > 0xDFFF
? CONVERT_TO_STRING ? S.charAt(position) : first
: CONVERT_TO_STRING ? S.slice(position, position + 2) : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000;
};
};
module.exports = {
// `String.prototype.codePointAt` method
// https://tc39.github.io/ecma262/#sec-string.prototype.codepointat
codeAt: createMethod(false),
// `String.prototype.at` method
// https://github.com/mathiasbynens/String.prototype.at
charAt: createMethod(true)
};
},{"../internals/require-object-coercible":60,"../internals/to-integer":70}],67:[function(require,module,exports){
'use strict';
// based on https://github.com/bestiejs/punycode.js/blob/master/punycode.js
var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
var base = 36;
var tMin = 1;
var tMax = 26;
var skew = 38;
var damp = 700;
var initialBias = 72;
var initialN = 128; // 0x80
var delimiter = '-'; // '\x2D'
var regexNonASCII = /[^\0-\u007E]/; // non-ASCII chars
var regexSeparators = /[.\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
var OVERFLOW_ERROR = 'Overflow: input needs wider integers to process';
var baseMinusTMin = base - tMin;
var floor = Math.floor;
var stringFromCharCode = String.fromCharCode;
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
*/
var ucs2decode = function (string) {
var output = [];
var counter = 0;
var length = string.length;
while (counter < length) {
var value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// It's a high surrogate, and there is a next character.
var extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // Low surrogate.
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// It's an unmatched surrogate; only append this code unit, in case the
// next code unit is the high surrogate of a surrogate pair.
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
};
/**
* Converts a digit/integer into a basic code point.
*/
var digitToBasic = function (digit) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26);
};
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* https://tools.ietf.org/html/rfc3492#section-3.4
*/
var adapt = function (delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
};
/**
* Converts a string of Unicode symbols (e.g. a domain name label) to a
* Punycode string of ASCII-only symbols.
*/
// eslint-disable-next-line max-statements
var encode = function (input) {
var output = [];
// Convert the input in UCS-2 to an array of Unicode code points.
input = ucs2decode(input);
// Cache the length.
var inputLength = input.length;
// Initialize the state.
var n = initialN;
var delta = 0;
var bias = initialBias;
var i, currentValue;
// Handle the basic code points.
for (i = 0; i < input.length; i++) {
currentValue = input[i];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
var basicLength = output.length; // number of basic code points.
var handledCPCount = basicLength; // number of code points that have been handled;
// Finish the basic string with a delimiter unless it's empty.
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next larger one:
var m = maxInt;
for (i = 0; i < input.length; i++) {
currentValue = input[i];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>, but guard against overflow.
var handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
throw RangeError(OVERFLOW_ERROR);
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (i = 0; i < input.length; i++) {
currentValue = input[i];
if (currentValue < n && ++delta > maxInt) {
throw RangeError(OVERFLOW_ERROR);
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer.
var q = delta;
for (var k = base; /* no condition */; k += base) {
var t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) break;
var qMinusT = q - t;
var baseMinusT = base - t;
output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT)));
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
};
module.exports = function (input) {
var encoded = [];
var labels = input.toLowerCase().replace(regexSeparators, '\u002E').split('.');
var i, label;
for (i = 0; i < labels.length; i++) {
label = labels[i];
encoded.push(regexNonASCII.test(label) ? 'xn--' + encode(label) : label);
}
return encoded.join('.');
};
},{}],68:[function(require,module,exports){
var toInteger = require('../internals/to-integer');
var max = Math.max;
var min = Math.min;
// Helper for a popular repeating case of the spec:
// Let integer be ? ToInteger(index).
// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
module.exports = function (index, length) {
var integer = toInteger(index);
return integer < 0 ? max(integer + length, 0) : min(integer, length);
};
},{"../internals/to-integer":70}],69:[function(require,module,exports){
// toObject with fallback for non-array-like ES3 strings
var IndexedObject = require('../internals/indexed-object');
var requireObjectCoercible = require('../internals/require-object-coercible');
module.exports = function (it) {
return IndexedObject(requireObjectCoercible(it));
};
},{"../internals/indexed-object":32,"../internals/require-object-coercible":60}],70:[function(require,module,exports){
var ceil = Math.ceil;
var floor = Math.floor;
// `ToInteger` abstract operation
// https://tc39.github.io/ecma262/#sec-tointeger
module.exports = function (argument) {
return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument);
};
},{}],71:[function(require,module,exports){
var toInteger = require('../internals/to-integer');
var min = Math.min;
// `ToLength` abstract operation
// https://tc39.github.io/ecma262/#sec-tolength
module.exports = function (argument) {
return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
};
},{"../internals/to-integer":70}],72:[function(require,module,exports){
var requireObjectCoercible = require('../internals/require-object-coercible');
// `ToObject` abstract operation
// https://tc39.github.io/ecma262/#sec-toobject
module.exports = function (argument) {
return Object(requireObjectCoercible(argument));
};
},{"../internals/require-object-coercible":60}],73:[function(require,module,exports){
var isObject = require('../internals/is-object');
// `ToPrimitive` abstract operation
// https://tc39.github.io/ecma262/#sec-toprimitive
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function (input, PREFERRED_STRING) {
if (!isObject(input)) return input;
var fn, val;
if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val;
if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
throw TypeError("Can't convert object to primitive value");
};
},{"../internals/is-object":37}],74:[function(require,module,exports){
var wellKnownSymbol = require('../internals/well-known-symbol');
var TO_STRING_TAG = wellKnownSymbol('toStringTag');
var test = {};
test[TO_STRING_TAG] = 'z';
module.exports = String(test) === '[object z]';
},{"../internals/well-known-symbol":77}],75:[function(require,module,exports){
var id = 0;
var postfix = Math.random();
module.exports = function (key) {
return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36);
};
},{}],76:[function(require,module,exports){
var NATIVE_SYMBOL = require('../internals/native-symbol');
module.exports = NATIVE_SYMBOL
// eslint-disable-next-line no-undef
&& !Symbol.sham
// eslint-disable-next-line no-undef
&& typeof Symbol.iterator == 'symbol';
},{"../internals/native-symbol":41}],77:[function(require,module,exports){
var global = require('../internals/global');
var shared = require('../internals/shared');
var has = require('../internals/has');
var uid = require('../internals/uid');
var NATIVE_SYMBOL = require('../internals/native-symbol');
var USE_SYMBOL_AS_UID = require('../internals/use-symbol-as-uid');
var WellKnownSymbolsStore = shared('wks');
var Symbol = global.Symbol;
var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol : Symbol && Symbol.withoutSetter || uid;
module.exports = function (name) {
if (!has(WellKnownSymbolsStore, name)) {
if (NATIVE_SYMBOL && has(Symbol, name)) WellKnownSymbolsStore[name] = Symbol[name];
else WellKnownSymbolsStore[name] = createWellKnownSymbol('Symbol.' + name);
} return WellKnownSymbolsStore[name];
};
},{"../internals/global":27,"../internals/has":28,"../internals/native-symbol":41,"../internals/shared":65,"../internals/uid":75,"../internals/use-symbol-as-uid":76}],78:[function(require,module,exports){
'use strict';
var toIndexedObject = require('../internals/to-indexed-object');
var addToUnscopables = require('../internals/add-to-unscopables');
var Iterators = require('../internals/iterators');
var InternalStateModule = require('../internals/internal-state');
var defineIterator = require('../internals/define-iterator');
var ARRAY_ITERATOR = 'Array Iterator';
var setInternalState = InternalStateModule.set;
var getInternalState = InternalStateModule.getterFor(ARRAY_ITERATOR);
// `Array.prototype.entries` method
// https://tc39.github.io/ecma262/#sec-array.prototype.entries
// `Array.prototype.keys` method
// https://tc39.github.io/ecma262/#sec-array.prototype.keys
// `Array.prototype.values` method
// https://tc39.github.io/ecma262/#sec-array.prototype.values
// `Array.prototype[@@iterator]` method
// https://tc39.github.io/ecma262/#sec-array.prototype-@@iterator
// `CreateArrayIterator` internal method
// https://tc39.github.io/ecma262/#sec-createarrayiterator
module.exports = defineIterator(Array, 'Array', function (iterated, kind) {
setInternalState(this, {
type: ARRAY_ITERATOR,
target: toIndexedObject(iterated), // target
index: 0, // next index
kind: kind // kind
});
// `%ArrayIteratorPrototype%.next` method
// https://tc39.github.io/ecma262/#sec-%arrayiteratorprototype%.next
}, function () {
var state = getInternalState(this);
var target = state.target;
var kind = state.kind;
var index = state.index++;
if (!target || index >= target.length) {
state.target = undefined;
return { value: undefined, done: true };
}
if (kind == 'keys') return { value: index, done: false };
if (kind == 'values') return { value: target[index], done: false };
return { value: [index, target[index]], done: false };
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values%
// https://tc39.github.io/ecma262/#sec-createunmappedargumentsobject
// https://tc39.github.io/ecma262/#sec-createmappedargumentsobject
Iterators.Arguments = Iterators.Array;
// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
},{"../internals/add-to-unscopables":3,"../internals/define-iterator":17,"../internals/internal-state":34,"../internals/iterators":40,"../internals/to-indexed-object":69}],79:[function(require,module,exports){
'use strict';
var charAt = require('../internals/string-multibyte').charAt;
var InternalStateModule = require('../internals/internal-state');
var defineIterator = require('../internals/define-iterator');
var STRING_ITERATOR = 'String Iterator';
var setInternalState = InternalStateModule.set;
var getInternalState = InternalStateModule.getterFor(STRING_ITERATOR);
// `String.prototype[@@iterator]` method
// https://tc39.github.io/ecma262/#sec-string.prototype-@@iterator
defineIterator(String, 'String', function (iterated) {
setInternalState(this, {
type: STRING_ITERATOR,
string: String(iterated),
index: 0
});
// `%StringIteratorPrototype%.next` method
// https://tc39.github.io/ecma262/#sec-%stringiteratorprototype%.next
}, function next() {
var state = getInternalState(this);
var string = state.string;
var index = state.index;
var point;
if (index >= string.length) return { value: undefined, done: true };
point = charAt(string, index);
state.index += point.length;
return { value: point, done: false };
});
},{"../internals/define-iterator":17,"../internals/internal-state":34,"../internals/string-multibyte":66}],80:[function(require,module,exports){
'use strict';
// TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env`
require('../modules/es.array.iterator');
var $ = require('../internals/export');
var getBuiltIn = require('../internals/get-built-in');
var USE_NATIVE_URL = require('../internals/native-url');
var redefine = require('../internals/redefine');
var redefineAll = require('../internals/redefine-all');
var setToStringTag = require('../internals/set-to-string-tag');
var createIteratorConstructor = require('../internals/create-iterator-constructor');
var InternalStateModule = require('../internals/internal-state');
var anInstance = require('../internals/an-instance');
var hasOwn = require('../internals/has');
var bind = require('../internals/function-bind-context');
var classof = require('../internals/classof');
var anObject = require('../internals/an-object');
var isObject = require('../internals/is-object');
var create = require('../internals/object-create');
var createPropertyDescriptor = require('../internals/create-property-descriptor');
var getIterator = require('../internals/get-iterator');
var getIteratorMethod = require('../internals/get-iterator-method');
var wellKnownSymbol = require('../internals/well-known-symbol');
var $fetch = getBuiltIn('fetch');
var Headers = getBuiltIn('Headers');
var ITERATOR = wellKnownSymbol('iterator');
var URL_SEARCH_PARAMS = 'URLSearchParams';
var URL_SEARCH_PARAMS_ITERATOR = URL_SEARCH_PARAMS + 'Iterator';
var setInternalState = InternalStateModule.set;
var getInternalParamsState = InternalStateModule.getterFor(URL_SEARCH_PARAMS);
var getInternalIteratorState = InternalStateModule.getterFor(URL_SEARCH_PARAMS_ITERATOR);
var plus = /\+/g;
var sequences = Array(4);
var percentSequence = function (bytes) {
return sequences[bytes - 1] || (sequences[bytes - 1] = RegExp('((?:%[\\da-f]{2}){' + bytes + '})', 'gi'));
};
var percentDecode = function (sequence) {
try {
return decodeURIComponent(sequence);
} catch (error) {
return sequence;
}
};
var deserialize = function (it) {
var result = it.replace(plus, ' ');
var bytes = 4;
try {
return decodeURIComponent(result);
} catch (error) {
while (bytes) {
result = result.replace(percentSequence(bytes--), percentDecode);
}
return result;
}
};
var find = /[!'()~]|%20/g;
var replace = {
'!': '%21',
"'": '%27',
'(': '%28',
')': '%29',
'~': '%7E',
'%20': '+'
};
var replacer = function (match) {
return replace[match];
};
var serialize = function (it) {
return encodeURIComponent(it).replace(find, replacer);
};
var parseSearchParams = function (result, query) {
if (query) {
var attributes = query.split('&');
var index = 0;
var attribute, entry;
while (index < attributes.length) {
attribute = attributes[index++];
if (attribute.length) {
entry = attribute.split('=');
result.push({
key: deserialize(entry.shift()),
value: deserialize(entry.join('='))
});
}
}
}
};
var updateSearchParams = function (query) {
this.entries.length = 0;
parseSearchParams(this.entries, query);
};
var validateArgumentsLength = function (passed, required) {
if (passed < required) throw TypeError('Not enough arguments');
};
var URLSearchParamsIterator = createIteratorConstructor(function Iterator(params, kind) {
setInternalState(this, {
type: URL_SEARCH_PARAMS_ITERATOR,
iterator: getIterator(getInternalParamsState(params).entries),
kind: kind
});
}, 'Iterator', function next() {
var state = getInternalIteratorState(this);
var kind = state.kind;
var step = state.iterator.next();
var entry = step.value;
if (!step.done) {
step.value = kind === 'keys' ? entry.key : kind === 'values' ? entry.value : [entry.key, entry.value];
} return step;
});
// `URLSearchParams` constructor
// https://url.spec.whatwg.org/#interface-urlsearchparams
var URLSearchParamsConstructor = function URLSearchParams(/* init */) {
anInstance(this, URLSearchParamsConstructor, URL_SEARCH_PARAMS);
var init = arguments.length > 0 ? arguments[0] : undefined;
var that = this;
var entries = [];
var iteratorMethod, iterator, next, step, entryIterator, entryNext, first, second, key;
setInternalState(that, {
type: URL_SEARCH_PARAMS,
entries: entries,
updateURL: function () { /* empty */ },
updateSearchParams: updateSearchParams
});
if (init !== undefined) {
if (isObject(init)) {
iteratorMethod = getIteratorMethod(init);
if (typeof iteratorMethod === 'function') {
iterator = iteratorMethod.call(init);
next = iterator.next;
while (!(step = next.call(iterator)).done) {
entryIterator = getIterator(anObject(step.value));
entryNext = entryIterator.next;
if (
(first = entryNext.call(entryIterator)).done ||
(second = entryNext.call(entryIterator)).done ||
!entryNext.call(entryIterator).done
) throw TypeError('Expected sequence with length 2');
entries.push({ key: first.value + '', value: second.value + '' });
}
} else for (key in init) if (hasOwn(init, key)) entries.push({ key: key, value: init[key] + '' });
} else {
parseSearchParams(entries, typeof init === 'string' ? init.charAt(0) === '?' ? init.slice(1) : init : init + '');
}
}
};
var URLSearchParamsPrototype = URLSearchParamsConstructor.prototype;
redefineAll(URLSearchParamsPrototype, {
// `URLSearchParams.prototype.appent` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-append
append: function append(name, value) {
validateArgumentsLength(arguments.length, 2);
var state = getInternalParamsState(this);
state.entries.push({ key: name + '', value: value + '' });
state.updateURL();
},
// `URLSearchParams.prototype.delete` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-delete
'delete': function (name) {
validateArgumentsLength(arguments.length, 1);
var state = getInternalParamsState(this);
var entries = state.entries;
var key = name + '';
var index = 0;
while (index < entries.length) {
if (entries[index].key === key) entries.splice(index, 1);
else index++;
}
state.updateURL();
},
// `URLSearchParams.prototype.get` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-get
get: function get(name) {
validateArgumentsLength(arguments.length, 1);
var entries = getInternalParamsState(this).entries;
var key = name + '';
var index = 0;
for (; index < entries.length; index++) {
if (entries[index].key === key) return entries[index].value;
}
return null;
},
// `URLSearchParams.prototype.getAll` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-getall
getAll: function getAll(name) {
validateArgumentsLength(arguments.length, 1);
var entries = getInternalParamsState(this).entries;
var key = name + '';
var result = [];
var index = 0;
for (; index < entries.length; index++) {
if (entries[index].key === key) result.push(entries[index].value);
}
return result;
},
// `URLSearchParams.prototype.has` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-has
has: function has(name) {
validateArgumentsLength(arguments.length, 1);
var entries = getInternalParamsState(this).entries;
var key = name + '';
var index = 0;
while (index < entries.length) {
if (entries[index++].key === key) return true;
}
return false;
},
// `URLSearchParams.prototype.set` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-set
set: function set(name, value) {
validateArgumentsLength(arguments.length, 1);
var state = getInternalParamsState(this);
var entries = state.entries;
var found = false;
var key = name + '';
var val = value + '';
var index = 0;
var entry;
for (; index < entries.length; index++) {
entry = entries[index];
if (entry.key === key) {
if (found) entries.splice(index--, 1);
else {
found = true;
entry.value = val;
}
}
}
if (!found) entries.push({ key: key, value: val });
state.updateURL();
},
// `URLSearchParams.prototype.sort` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-sort
sort: function sort() {
var state = getInternalParamsState(this);
var entries = state.entries;
// Array#sort is not stable in some engines
var slice = entries.slice();
var entry, entriesIndex, sliceIndex;
entries.length = 0;
for (sliceIndex = 0; sliceIndex < slice.length; sliceIndex++) {
entry = slice[sliceIndex];
for (entriesIndex = 0; entriesIndex < sliceIndex; entriesIndex++) {
if (entries[entriesIndex].key > entry.key) {
entries.splice(entriesIndex, 0, entry);
break;
}
}
if (entriesIndex === sliceIndex) entries.push(entry);
}
state.updateURL();
},
// `URLSearchParams.prototype.forEach` method
forEach: function forEach(callback /* , thisArg */) {
var entries = getInternalParamsState(this).entries;
var boundFunction = bind(callback, arguments.length > 1 ? arguments[1] : undefined, 3);
var index = 0;
var entry;
while (index < entries.length) {
entry = entries[index++];
boundFunction(entry.value, entry.key, this);
}
},
// `URLSearchParams.prototype.keys` method
keys: function keys() {
return new URLSearchParamsIterator(this, 'keys');
},
// `URLSearchParams.prototype.values` method
values: function values() {
return new URLSearchParamsIterator(this, 'values');
},
// `URLSearchParams.prototype.entries` method
entries: function entries() {
return new URLSearchParamsIterator(this, 'entries');
}
}, { enumerable: true });
// `URLSearchParams.prototype[@@iterator]` method
redefine(URLSearchParamsPrototype, ITERATOR, URLSearchParamsPrototype.entries);
// `URLSearchParams.prototype.toString` method
// https://url.spec.whatwg.org/#urlsearchparams-stringification-behavior
redefine(URLSearchParamsPrototype, 'toString', function toString() {
var entries = getInternalParamsState(this).entries;
var result = [];
var index = 0;
var entry;
while (index < entries.length) {
entry = entries[index++];
result.push(serialize(entry.key) + '=' + serialize(entry.value));
} return result.join('&');
}, { enumerable: true });
setToStringTag(URLSearchParamsConstructor, URL_SEARCH_PARAMS);
$({ global: true, forced: !USE_NATIVE_URL }, {
URLSearchParams: URLSearchParamsConstructor
});
// Wrap `fetch` for correct work with polyfilled `URLSearchParams`
// https://github.com/zloirock/core-js/issues/674
if (!USE_NATIVE_URL && typeof $fetch == 'function' && typeof Headers == 'function') {
$({ global: true, enumerable: true, forced: true }, {
fetch: function fetch(input /* , init */) {
var args = [input];
var init, body, headers;
if (arguments.length > 1) {
init = arguments[1];
if (isObject(init)) {
body = init.body;
if (classof(body) === URL_SEARCH_PARAMS) {
headers = init.headers ? new Headers(init.headers) : new Headers();
if (!headers.has('content-type')) {
headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
}
init = create(init, {
body: createPropertyDescriptor(0, String(body)),
headers: createPropertyDescriptor(0, headers)
});
}
}
args.push(init);
} return $fetch.apply(this, args);
}
});
}
module.exports = {
URLSearchParams: URLSearchParamsConstructor,
getState: getInternalParamsState
};
},{"../internals/an-instance":4,"../internals/an-object":5,"../internals/classof":10,"../internals/create-iterator-constructor":13,"../internals/create-property-descriptor":15,"../internals/export":21,"../internals/function-bind-context":23,"../internals/get-built-in":24,"../internals/get-iterator":26,"../internals/get-iterator-method":25,"../internals/has":28,"../internals/internal-state":34,"../internals/is-object":37,"../internals/native-url":42,"../internals/object-create":45,"../internals/redefine":59,"../internals/redefine-all":58,"../internals/set-to-string-tag":62,"../internals/well-known-symbol":77,"../modules/es.array.iterator":78}],81:[function(require,module,exports){
'use strict';
// TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env`
require('../modules/es.string.iterator');
var $ = require('../internals/export');
var DESCRIPTORS = require('../internals/descriptors');
var USE_NATIVE_URL = require('../internals/native-url');
var global = require('../internals/global');
var defineProperties = require('../internals/object-define-properties');
var redefine = require('../internals/redefine');
var anInstance = require('../internals/an-instance');
var has = require('../internals/has');
var assign = require('../internals/object-assign');
var arrayFrom = require('../internals/array-from');
var codeAt = require('../internals/string-multibyte').codeAt;
var toASCII = require('../internals/string-punycode-to-ascii');
var setToStringTag = require('../internals/set-to-string-tag');
var URLSearchParamsModule = require('../modules/web.url-search-params');
var InternalStateModule = require('../internals/internal-state');
var NativeURL = global.URL;
var URLSearchParams = URLSearchParamsModule.URLSearchParams;
var getInternalSearchParamsState = URLSearchParamsModule.getState;
var setInternalState = InternalStateModule.set;
var getInternalURLState = InternalStateModule.getterFor('URL');
var floor = Math.floor;
var pow = Math.pow;
var INVALID_AUTHORITY = 'Invalid authority';
var INVALID_SCHEME = 'Invalid scheme';
var INVALID_HOST = 'Invalid host';
var INVALID_PORT = 'Invalid port';
var ALPHA = /[A-Za-z]/;
var ALPHANUMERIC = /[\d+\-.A-Za-z]/;
var DIGIT = /\d/;
var HEX_START = /^(0x|0X)/;
var OCT = /^[0-7]+$/;
var DEC = /^\d+$/;
var HEX = /^[\dA-Fa-f]+$/;
// eslint-disable-next-line no-control-regex
var FORBIDDEN_HOST_CODE_POINT = /[\u0000\u0009\u000A\u000D #%/:?@[\\]]/;
// eslint-disable-next-line no-control-regex
var FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT = /[\u0000\u0009\u000A\u000D #/:?@[\\]]/;
// eslint-disable-next-line no-control-regex
var LEADING_AND_TRAILING_C0_CONTROL_OR_SPACE = /^[\u0000-\u001F ]+|[\u0000-\u001F ]+$/g;
// eslint-disable-next-line no-control-regex
var TAB_AND_NEW_LINE = /[\u0009\u000A\u000D]/g;
var EOF;
var parseHost = function (url, input) {
var result, codePoints, index;
if (input.charAt(0) == '[') {
if (input.charAt(input.length - 1) != ']') return INVALID_HOST;
result = parseIPv6(input.slice(1, -1));
if (!result) return INVALID_HOST;
url.host = result;
// opaque host
} else if (!isSpecial(url)) {
if (FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT.test(input)) return INVALID_HOST;
result = '';
codePoints = arrayFrom(input);
for (index = 0; index < codePoints.length; index++) {
result += percentEncode(codePoints[index], C0ControlPercentEncodeSet);
}
url.host = result;
} else {
input = toASCII(input);
if (FORBIDDEN_HOST_CODE_POINT.test(input)) return INVALID_HOST;
result = parseIPv4(input);
if (result === null) return INVALID_HOST;
url.host = result;
}
};
var parseIPv4 = function (input) {
var parts = input.split('.');
var partsLength, numbers, index, part, radix, number, ipv4;
if (parts.length && parts[parts.length - 1] == '') {
parts.pop();
}
partsLength = parts.length;
if (partsLength > 4) return input;
numbers = [];
for (index = 0; index < partsLength; index++) {
part = parts[index];
if (part == '') return input;
radix = 10;
if (part.length > 1 && part.charAt(0) == '0') {
radix = HEX_START.test(part) ? 16 : 8;
part = part.slice(radix == 8 ? 1 : 2);
}
if (part === '') {
number = 0;
} else {
if (!(radix == 10 ? DEC : radix == 8 ? OCT : HEX).test(part)) return input;
number = parseInt(part, radix);
}
numbers.push(number);
}
for (index = 0; index < partsLength; index++) {
number = numbers[index];
if (index == partsLength - 1) {
if (number >= pow(256, 5 - partsLength)) return null;
} else if (number > 255) return null;
}
ipv4 = numbers.pop();
for (index = 0; index < numbers.length; index++) {
ipv4 += numbers[index] * pow(256, 3 - index);
}
return ipv4;
};
// eslint-disable-next-line max-statements
var parseIPv6 = function (input) {
var address = [0, 0, 0, 0, 0, 0, 0, 0];
var pieceIndex = 0;
var compress = null;
var pointer = 0;
var value, length, numbersSeen, ipv4Piece, number, swaps, swap;
var char = function () {
return input.charAt(pointer);
};
if (char() == ':') {
if (input.charAt(1) != ':') return;
pointer += 2;
pieceIndex++;
compress = pieceIndex;
}
while (char()) {
if (pieceIndex == 8) return;
if (char() == ':') {
if (compress !== null) return;
pointer++;
pieceIndex++;
compress = pieceIndex;
continue;
}
value = length = 0;
while (length < 4 && HEX.test(char())) {
value = value * 16 + parseInt(char(), 16);
pointer++;
length++;
}
if (char() == '.') {
if (length == 0) return;
pointer -= length;
if (pieceIndex > 6) return;
numbersSeen = 0;
while (char()) {
ipv4Piece = null;
if (numbersSeen > 0) {
if (char() == '.' && numbersSeen < 4) pointer++;
else return;
}
if (!DIGIT.test(char())) return;
while (DIGIT.test(char())) {
number = parseInt(char(), 10);
if (ipv4Piece === null) ipv4Piece = number;
else if (ipv4Piece == 0) return;
else ipv4Piece = ipv4Piece * 10 + number;
if (ipv4Piece > 255) return;
pointer++;
}
address[pieceIndex] = address[pieceIndex] * 256 + ipv4Piece;
numbersSeen++;
if (numbersSeen == 2 || numbersSeen == 4) pieceIndex++;
}
if (numbersSeen != 4) return;
break;
} else if (char() == ':') {
pointer++;
if (!char()) return;
} else if (char()) return;
address[pieceIndex++] = value;
}
if (compress !== null) {
swaps = pieceIndex - compress;
pieceIndex = 7;
while (pieceIndex != 0 && swaps > 0) {
swap = address[pieceIndex];
address[pieceIndex--] = address[compress + swaps - 1];
address[compress + --swaps] = swap;
}
} else if (pieceIndex != 8) return;
return address;
};
var findLongestZeroSequence = function (ipv6) {
var maxIndex = null;
var maxLength = 1;
var currStart = null;
var currLength = 0;
var index = 0;
for (; index < 8; index++) {
if (ipv6[index] !== 0) {
if (currLength > maxLength) {
maxIndex = currStart;
maxLength = currLength;
}
currStart = null;
currLength = 0;
} else {
if (currStart === null) currStart = index;
++currLength;
}
}
if (currLength > maxLength) {
maxIndex = currStart;
maxLength = currLength;
}
return maxIndex;
};
var serializeHost = function (host) {
var result, index, compress, ignore0;
// ipv4
if (typeof host == 'number') {
result = [];
for (index = 0; index < 4; index++) {
result.unshift(host % 256);
host = floor(host / 256);
} return result.join('.');
// ipv6
} else if (typeof host == 'object') {
result = '';
compress = findLongestZeroSequence(host);
for (index = 0; index < 8; index++) {
if (ignore0 && host[index] === 0) continue;
if (ignore0) ignore0 = false;
if (compress === index) {
result += index ? ':' : '::';
ignore0 = true;
} else {
result += host[index].toString(16);
if (index < 7) result += ':';
}
}
return '[' + result + ']';
} return host;
};
var C0ControlPercentEncodeSet = {};
var fragmentPercentEncodeSet = assign({}, C0ControlPercentEncodeSet, {
' ': 1, '"': 1, '<': 1, '>': 1, '`': 1
});
var pathPercentEncodeSet = assign({}, fragmentPercentEncodeSet, {
'#': 1, '?': 1, '{': 1, '}': 1
});
var userinfoPercentEncodeSet = assign({}, pathPercentEncodeSet, {
'/': 1, ':': 1, ';': 1, '=': 1, '@': 1, '[': 1, '\\': 1, ']': 1, '^': 1, '|': 1
});
var percentEncode = function (char, set) {
var code = codeAt(char, 0);
return code > 0x20 && code < 0x7F && !has(set, char) ? char : encodeURIComponent(char);
};
var specialSchemes = {
ftp: 21,
file: null,
http: 80,
https: 443,
ws: 80,
wss: 443
};
var isSpecial = function (url) {
return has(specialSchemes, url.scheme);
};
var includesCredentials = function (url) {
return url.username != '' || url.password != '';
};
var cannotHaveUsernamePasswordPort = function (url) {
return !url.host || url.cannotBeABaseURL || url.scheme == 'file';
};
var isWindowsDriveLetter = function (string, normalized) {
var second;
return string.length == 2 && ALPHA.test(string.charAt(0))
&& ((second = string.charAt(1)) == ':' || (!normalized && second == '|'));
};
var startsWithWindowsDriveLetter = function (string) {
var third;
return string.length > 1 && isWindowsDriveLetter(string.slice(0, 2)) && (
string.length == 2 ||
((third = string.charAt(2)) === '/' || third === '\\' || third === '?' || third === '#')
);
};
var shortenURLsPath = function (url) {
var path = url.path;
var pathSize = path.length;
if (pathSize && (url.scheme != 'file' || pathSize != 1 || !isWindowsDriveLetter(path[0], true))) {
path.pop();
}
};
var isSingleDot = function (segment) {
return segment === '.' || segment.toLowerCase() === '%2e';
};
var isDoubleDot = function (segment) {
segment = segment.toLowerCase();
return segment === '..' || segment === '%2e.' || segment === '.%2e' || segment === '%2e%2e';
};
// States:
var SCHEME_START = {};
var SCHEME = {};
var NO_SCHEME = {};
var SPECIAL_RELATIVE_OR_AUTHORITY = {};
var PATH_OR_AUTHORITY = {};
var RELATIVE = {};
var RELATIVE_SLASH = {};
var SPECIAL_AUTHORITY_SLASHES = {};
var SPECIAL_AUTHORITY_IGNORE_SLASHES = {};
var AUTHORITY = {};
var HOST = {};
var HOSTNAME = {};
var PORT = {};
var FILE = {};
var FILE_SLASH = {};
var FILE_HOST = {};
var PATH_START = {};
var PATH = {};
var CANNOT_BE_A_BASE_URL_PATH = {};
var QUERY = {};
var FRAGMENT = {};
// eslint-disable-next-line max-statements
var parseURL = function (url, input, stateOverride, base) {
var state = stateOverride || SCHEME_START;
var pointer = 0;
var buffer = '';
var seenAt = false;
var seenBracket = false;
var seenPasswordToken = false;
var codePoints, char, bufferCodePoints, failure;
if (!stateOverride) {
url.scheme = '';
url.username = '';
url.password = '';
url.host = null;
url.port = null;
url.path = [];
url.query = null;
url.fragment = null;
url.cannotBeABaseURL = false;
input = input.replace(LEADING_AND_TRAILING_C0_CONTROL_OR_SPACE, '');
}
input = input.replace(TAB_AND_NEW_LINE, '');
codePoints = arrayFrom(input);
while (pointer <= codePoints.length) {
char = codePoints[pointer];
switch (state) {
case SCHEME_START:
if (char && ALPHA.test(char)) {
buffer += char.toLowerCase();
state = SCHEME;
} else if (!stateOverride) {
state = NO_SCHEME;
continue;
} else return INVALID_SCHEME;
break;
case SCHEME:
if (char && (ALPHANUMERIC.test(char) || char == '+' || char == '-' || char == '.')) {
buffer += char.toLowerCase();
} else if (char == ':') {
if (stateOverride && (
(isSpecial(url) != has(specialSchemes, buffer)) ||
(buffer == 'file' && (includesCredentials(url) || url.port !== null)) ||
(url.scheme == 'file' && !url.host)
)) return;
url.scheme = buffer;
if (stateOverride) {
if (isSpecial(url) && specialSchemes[url.scheme] == url.port) url.port = null;
return;
}
buffer = '';
if (url.scheme == 'file') {
state = FILE;
} else if (isSpecial(url) && base && base.scheme == url.scheme) {
state = SPECIAL_RELATIVE_OR_AUTHORITY;
} else if (isSpecial(url)) {
state = SPECIAL_AUTHORITY_SLASHES;
} else if (codePoints[pointer + 1] == '/') {
state = PATH_OR_AUTHORITY;
pointer++;
} else {
url.cannotBeABaseURL = true;
url.path.push('');
state = CANNOT_BE_A_BASE_URL_PATH;
}
} else if (!stateOverride) {
buffer = '';
state = NO_SCHEME;
pointer = 0;
continue;
} else return INVALID_SCHEME;
break;
case NO_SCHEME:
if (!base || (base.cannotBeABaseURL && char != '#')) return INVALID_SCHEME;
if (base.cannotBeABaseURL && char == '#') {
url.scheme = base.scheme;
url.path = base.path.slice();
url.query = base.query;
url.fragment = '';
url.cannotBeABaseURL = true;
state = FRAGMENT;
break;
}
state = base.scheme == 'file' ? FILE : RELATIVE;
continue;
case SPECIAL_RELATIVE_OR_AUTHORITY:
if (char == '/' && codePoints[pointer + 1] == '/') {
state = SPECIAL_AUTHORITY_IGNORE_SLASHES;
pointer++;
} else {
state = RELATIVE;
continue;
} break;
case PATH_OR_AUTHORITY:
if (char == '/') {
state = AUTHORITY;
break;
} else {
state = PATH;
continue;
}
case RELATIVE:
url.scheme = base.scheme;
if (char == EOF) {
url.username = base.username;
url.password = base.password;
url.host = base.host;
url.port = base.port;
url.path = base.path.slice();
url.query = base.query;
} else if (char == '/' || (char == '\\' && isSpecial(url))) {
state = RELATIVE_SLASH;
} else if (char == '?') {
url.username = base.username;
url.password = base.password;
url.host = base.host;
url.port = base.port;
url.path = base.path.slice();
url.query = '';
state = QUERY;
} else if (char == '#') {
url.username = base.username;
url.password = base.password;
url.host = base.host;
url.port = base.port;
url.path = base.path.slice();
url.query = base.query;
url.fragment = '';
state = FRAGMENT;
} else {
url.username = base.username;
url.password = base.password;
url.host = base.host;
url.port = base.port;
url.path = base.path.slice();
url.path.pop();
state = PATH;
continue;
} break;
case RELATIVE_SLASH:
if (isSpecial(url) && (char == '/' || char == '\\')) {
state = SPECIAL_AUTHORITY_IGNORE_SLASHES;
} else if (char == '/') {
state = AUTHORITY;
} else {
url.username = base.username;
url.password = base.password;
url.host = base.host;
url.port = base.port;
state = PATH;
continue;
} break;
case SPECIAL_AUTHORITY_SLASHES:
state = SPECIAL_AUTHORITY_IGNORE_SLASHES;
if (char != '/' || buffer.charAt(pointer + 1) != '/') continue;
pointer++;
break;
case SPECIAL_AUTHORITY_IGNORE_SLASHES:
if (char != '/' && char != '\\') {
state = AUTHORITY;
continue;
} break;
case AUTHORITY:
if (char == '@') {
if (seenAt) buffer = '%40' + buffer;
seenAt = true;
bufferCodePoints = arrayFrom(buffer);
for (var i = 0; i < bufferCodePoints.length; i++) {
var codePoint = bufferCodePoints[i];
if (codePoint == ':' && !seenPasswordToken) {
seenPasswordToken = true;
continue;
}
var encodedCodePoints = percentEncode(codePoint, userinfoPercentEncodeSet);
if (seenPasswordToken) url.password += encodedCodePoints;
else url.username += encodedCodePoints;
}
buffer = '';
} else if (
char == EOF || char == '/' || char == '?' || char == '#' ||
(char == '\\' && isSpecial(url))
) {
if (seenAt && buffer == '') return INVALID_AUTHORITY;
pointer -= arrayFrom(buffer).length + 1;
buffer = '';
state = HOST;
} else buffer += char;
break;
case HOST:
case HOSTNAME:
if (stateOverride && url.scheme == 'file') {
state = FILE_HOST;
continue;
} else if (char == ':' && !seenBracket) {
if (buffer == '') return INVALID_HOST;
failure = parseHost(url, buffer);
if (failure) return failure;
buffer = '';
state = PORT;
if (stateOverride == HOSTNAME) return;
} else if (
char == EOF || char == '/' || char == '?' || char == '#' ||
(char == '\\' && isSpecial(url))
) {
if (isSpecial(url) && buffer == '') return INVALID_HOST;
if (stateOverride && buffer == '' && (includesCredentials(url) || url.port !== null)) return;
failure = parseHost(url, buffer);
if (failure) return failure;
buffer = '';
state = PATH_START;
if (stateOverride) return;
continue;
} else {
if (char == '[') seenBracket = true;
else if (char == ']') seenBracket = false;
buffer += char;
} break;
case PORT:
if (DIGIT.test(char)) {
buffer += char;
} else if (
char == EOF || char == '/' || char == '?' || char == '#' ||
(char == '\\' && isSpecial(url)) ||
stateOverride
) {
if (buffer != '') {
var port = parseInt(buffer, 10);
if (port > 0xFFFF) return INVALID_PORT;
url.port = (isSpecial(url) && port === specialSchemes[url.scheme]) ? null : port;
buffer = '';
}
if (stateOverride) return;
state = PATH_START;
continue;
} else return INVALID_PORT;
break;
case FILE:
url.scheme = 'file';
if (char == '/' || char == '\\') state = FILE_SLASH;
else if (base && base.scheme == 'file') {
if (char == EOF) {
url.host = base.host;
url.path = base.path.slice();
url.query = base.query;
} else if (char == '?') {
url.host = base.host;
url.path = base.path.slice();
url.query = '';
state = QUERY;
} else if (char == '#') {
url.host = base.host;
url.path = base.path.slice();
url.query = base.query;
url.fragment = '';
state = FRAGMENT;
} else {
if (!startsWithWindowsDriveLetter(codePoints.slice(pointer).join(''))) {
url.host = base.host;
url.path = base.path.slice();
shortenURLsPath(url);
}
state = PATH;
continue;
}
} else {
state = PATH;
continue;
} break;
case FILE_SLASH:
if (char == '/' || char == '\\') {
state = FILE_HOST;
break;
}
if (base && base.scheme == 'file' && !startsWithWindowsDriveLetter(codePoints.slice(pointer).join(''))) {
if (isWindowsDriveLetter(base.path[0], true)) url.path.push(base.path[0]);
else url.host = base.host;
}
state = PATH;
continue;
case FILE_HOST:
if (char == EOF || char == '/' || char == '\\' || char == '?' || char == '#') {
if (!stateOverride && isWindowsDriveLetter(buffer)) {
state = PATH;
} else if (buffer == '') {
url.host = '';
if (stateOverride) return;
state = PATH_START;
} else {
failure = parseHost(url, buffer);
if (failure) return failure;
if (url.host == 'localhost') url.host = '';
if (stateOverride) return;
buffer = '';
state = PATH_START;
} continue;
} else buffer += char;
break;
case PATH_START:
if (isSpecial(url)) {
state = PATH;
if (char != '/' && char != '\\') continue;
} else if (!stateOverride && char == '?') {
url.query = '';
state = QUERY;
} else if (!stateOverride && char == '#') {
url.fragment = '';
state = FRAGMENT;
} else if (char != EOF) {
state = PATH;
if (char != '/') continue;
} break;
case PATH:
if (
char == EOF || char == '/' ||
(char == '\\' && isSpecial(url)) ||
(!stateOverride && (char == '?' || char == '#'))
) {
if (isDoubleDot(buffer)) {
shortenURLsPath(url);
if (char != '/' && !(char == '\\' && isSpecial(url))) {
url.path.push('');
}
} else if (isSingleDot(buffer)) {
if (char != '/' && !(char == '\\' && isSpecial(url))) {
url.path.push('');
}
} else {
if (url.scheme == 'file' && !url.path.length && isWindowsDriveLetter(buffer)) {
if (url.host) url.host = '';
buffer = buffer.charAt(0) + ':'; // normalize windows drive letter
}
url.path.push(buffer);
}
buffer = '';
if (url.scheme == 'file' && (char == EOF || char == '?' || char == '#')) {
while (url.path.length > 1 && url.path[0] === '') {
url.path.shift();
}
}
if (char == '?') {
url.query = '';
state = QUERY;
} else if (char == '#') {
url.fragment = '';
state = FRAGMENT;
}
} else {
buffer += percentEncode(char, pathPercentEncodeSet);
} break;
case CANNOT_BE_A_BASE_URL_PATH:
if (char == '?') {
url.query = '';
state = QUERY;
} else if (char == '#') {
url.fragment = '';
state = FRAGMENT;
} else if (char != EOF) {
url.path[0] += percentEncode(char, C0ControlPercentEncodeSet);
} break;
case QUERY:
if (!stateOverride && char == '#') {
url.fragment = '';
state = FRAGMENT;
} else if (char != EOF) {
if (char == "'" && isSpecial(url)) url.query += '%27';
else if (char == '#') url.query += '%23';
else url.query += percentEncode(char, C0ControlPercentEncodeSet);
} break;
case FRAGMENT:
if (char != EOF) url.fragment += percentEncode(char, fragmentPercentEncodeSet);
break;
}
pointer++;
}
};
// `URL` constructor
// https://url.spec.whatwg.org/#url-class
var URLConstructor = function URL(url /* , base */) {
var that = anInstance(this, URLConstructor, 'URL');
var base = arguments.length > 1 ? arguments[1] : undefined;
var urlString = String(url);
var state = setInternalState(that, { type: 'URL' });
var baseState, failure;
if (base !== undefined) {
if (base instanceof URLConstructor) baseState = getInternalURLState(base);
else {
failure = parseURL(baseState = {}, String(base));
if (failure) throw TypeError(failure);
}
}
failure = parseURL(state, urlString, null, baseState);
if (failure) throw TypeError(failure);
var searchParams = state.searchParams = new URLSearchParams();
var searchParamsState = getInternalSearchParamsState(searchParams);
searchParamsState.updateSearchParams(state.query);
searchParamsState.updateURL = function () {
state.query = String(searchParams) || null;
};
if (!DESCRIPTORS) {
that.href = serializeURL.call(that);
that.origin = getOrigin.call(that);
that.protocol = getProtocol.call(that);
that.username = getUsername.call(that);
that.password = getPassword.call(that);
that.host = getHost.call(that);
that.hostname = getHostname.call(that);
that.port = getPort.call(that);
that.pathname = getPathname.call(that);
that.search = getSearch.call(that);
that.searchParams = getSearchParams.call(that);
that.hash = getHash.call(that);
}
};
var URLPrototype = URLConstructor.prototype;
var serializeURL = function () {
var url = getInternalURLState(this);
var scheme = url.scheme;
var username = url.username;
var password = url.password;
var host = url.host;
var port = url.port;
var path = url.path;
var query = url.query;
var fragment = url.fragment;
var output = scheme + ':';
if (host !== null) {
output += '//';
if (includesCredentials(url)) {
output += username + (password ? ':' + password : '') + '@';
}
output += serializeHost(host);
if (port !== null) output += ':' + port;
} else if (scheme == 'file') output += '//';
output += url.cannotBeABaseURL ? path[0] : path.length ? '/' + path.join('/') : '';
if (query !== null) output += '?' + query;
if (fragment !== null) output += '#' + fragment;
return output;
};
var getOrigin = function () {
var url = getInternalURLState(this);
var scheme = url.scheme;
var port = url.port;
if (scheme == 'blob') try {
return new URL(scheme.path[0]).origin;
} catch (error) {
return 'null';
}
if (scheme == 'file' || !isSpecial(url)) return 'null';
return scheme + '://' + serializeHost(url.host) + (port !== null ? ':' + port : '');
};
var getProtocol = function () {
return getInternalURLState(this).scheme + ':';
};
var getUsername = function () {
return getInternalURLState(this).username;
};
var getPassword = function () {
return getInternalURLState(this).password;
};
var getHost = function () {
var url = getInternalURLState(this);
var host = url.host;
var port = url.port;
return host === null ? ''
: port === null ? serializeHost(host)
: serializeHost(host) + ':' + port;
};
var getHostname = function () {
var host = getInternalURLState(this).host;
return host === null ? '' : serializeHost(host);
};
var getPort = function () {
var port = getInternalURLState(this).port;
return port === null ? '' : String(port);
};
var getPathname = function () {
var url = getInternalURLState(this);
var path = url.path;
return url.cannotBeABaseURL ? path[0] : path.length ? '/' + path.join('/') : '';
};
var getSearch = function () {
var query = getInternalURLState(this).query;
return query ? '?' + query : '';
};
var getSearchParams = function () {
return getInternalURLState(this).searchParams;
};
var getHash = function () {
var fragment = getInternalURLState(this).fragment;
return fragment ? '#' + fragment : '';
};
var accessorDescriptor = function (getter, setter) {
return { get: getter, set: setter, configurable: true, enumerable: true };
};
if (DESCRIPTORS) {
defineProperties(URLPrototype, {
// `URL.prototype.href` accessors pair
// https://url.spec.whatwg.org/#dom-url-href
href: accessorDescriptor(serializeURL, function (href) {
var url = getInternalURLState(this);
var urlString = String(href);
var failure = parseURL(url, urlString);
if (failure) throw TypeError(failure);
getInternalSearchParamsState(url.searchParams).updateSearchParams(url.query);
}),
// `URL.prototype.origin` getter
// https://url.spec.whatwg.org/#dom-url-origin
origin: accessorDescriptor(getOrigin),
// `URL.prototype.protocol` accessors pair
// https://url.spec.whatwg.org/#dom-url-protocol
protocol: accessorDescriptor(getProtocol, function (protocol) {
var url = getInternalURLState(this);
parseURL(url, String(protocol) + ':', SCHEME_START);
}),
// `URL.prototype.username` accessors pair
// https://url.spec.whatwg.org/#dom-url-username
username: accessorDescriptor(getUsername, function (username) {
var url = getInternalURLState(this);
var codePoints = arrayFrom(String(username));
if (cannotHaveUsernamePasswordPort(url)) return;
url.username = '';
for (var i = 0; i < codePoints.length; i++) {
url.username += percentEncode(codePoints[i], userinfoPercentEncodeSet);
}
}),
// `URL.prototype.password` accessors pair
// https://url.spec.whatwg.org/#dom-url-password
password: accessorDescriptor(getPassword, function (password) {
var url = getInternalURLState(this);
var codePoints = arrayFrom(String(password));
if (cannotHaveUsernamePasswordPort(url)) return;
url.password = '';
for (var i = 0; i < codePoints.length; i++) {
url.password += percentEncode(codePoints[i], userinfoPercentEncodeSet);
}
}),
// `URL.prototype.host` accessors pair
// https://url.spec.whatwg.org/#dom-url-host
host: accessorDescriptor(getHost, function (host) {
var url = getInternalURLState(this);
if (url.cannotBeABaseURL) return;
parseURL(url, String(host), HOST);
}),
// `URL.prototype.hostname` accessors pair
// https://url.spec.whatwg.org/#dom-url-hostname
hostname: accessorDescriptor(getHostname, function (hostname) {
var url = getInternalURLState(this);
if (url.cannotBeABaseURL) return;
parseURL(url, String(hostname), HOSTNAME);
}),
// `URL.prototype.port` accessors pair
// https://url.spec.whatwg.org/#dom-url-port
port: accessorDescriptor(getPort, function (port) {
var url = getInternalURLState(this);
if (cannotHaveUsernamePasswordPort(url)) return;
port = String(port);
if (port == '') url.port = null;
else parseURL(url, port, PORT);
}),
// `URL.prototype.pathname` accessors pair
// https://url.spec.whatwg.org/#dom-url-pathname
pathname: accessorDescriptor(getPathname, function (pathname) {
var url = getInternalURLState(this);
if (url.cannotBeABaseURL) return;
url.path = [];
parseURL(url, pathname + '', PATH_START);
}),
// `URL.prototype.search` accessors pair
// https://url.spec.whatwg.org/#dom-url-search
search: accessorDescriptor(getSearch, function (search) {
var url = getInternalURLState(this);
search = String(search);
if (search == '') {
url.query = null;
} else {
if ('?' == search.charAt(0)) search = search.slice(1);
url.query = '';
parseURL(url, search, QUERY);
}
getInternalSearchParamsState(url.searchParams).updateSearchParams(url.query);
}),
// `URL.prototype.searchParams` getter
// https://url.spec.whatwg.org/#dom-url-searchparams
searchParams: accessorDescriptor(getSearchParams),
// `URL.prototype.hash` accessors pair
// https://url.spec.whatwg.org/#dom-url-hash
hash: accessorDescriptor(getHash, function (hash) {
var url = getInternalURLState(this);
hash = String(hash);
if (hash == '') {
url.fragment = null;
return;
}
if ('#' == hash.charAt(0)) hash = hash.slice(1);
url.fragment = '';
parseURL(url, hash, FRAGMENT);
})
});
}
// `URL.prototype.toJSON` method
// https://url.spec.whatwg.org/#dom-url-tojson
redefine(URLPrototype, 'toJSON', function toJSON() {
return serializeURL.call(this);
}, { enumerable: true });
// `URL.prototype.toString` method
// https://url.spec.whatwg.org/#URL-stringification-behavior
redefine(URLPrototype, 'toString', function toString() {
return serializeURL.call(this);
}, { enumerable: true });
if (NativeURL) {
var nativeCreateObjectURL = NativeURL.createObjectURL;
var nativeRevokeObjectURL = NativeURL.revokeObjectURL;
// `URL.createObjectURL` method
// https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
// eslint-disable-next-line no-unused-vars
if (nativeCreateObjectURL) redefine(URLConstructor, 'createObjectURL', function createObjectURL(blob) {
return nativeCreateObjectURL.apply(NativeURL, arguments);
});
// `URL.revokeObjectURL` method
// https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL
// eslint-disable-next-line no-unused-vars
if (nativeRevokeObjectURL) redefine(URLConstructor, 'revokeObjectURL', function revokeObjectURL(url) {
return nativeRevokeObjectURL.apply(NativeURL, arguments);
});
}
setToStringTag(URLConstructor, 'URL');
$({ global: true, forced: !USE_NATIVE_URL, sham: !DESCRIPTORS }, {
URL: URLConstructor
});
},{"../internals/an-instance":4,"../internals/array-from":6,"../internals/descriptors":18,"../internals/export":21,"../internals/global":27,"../internals/has":28,"../internals/internal-state":34,"../internals/native-url":42,"../internals/object-assign":44,"../internals/object-define-properties":46,"../internals/redefine":59,"../internals/set-to-string-tag":62,"../internals/string-multibyte":66,"../internals/string-punycode-to-ascii":67,"../modules/es.string.iterator":79,"../modules/web.url-search-params":80}],82:[function(require,module,exports){
'use strict';
var $ = require('../internals/export');
// `URL.prototype.toJSON` method
// https://url.spec.whatwg.org/#dom-url-tojson
$({ target: 'URL', proto: true, enumerable: true }, {
toJSON: function toJSON() {
return URL.prototype.toString.call(this);
}
});
},{"../internals/export":21}],83:[function(require,module,exports){
require('../modules/web.url');
require('../modules/web.url.to-json');
require('../modules/web.url-search-params');
var path = require('../internals/path');
module.exports = path.URL;
},{"../internals/path":57,"../modules/web.url":81,"../modules/web.url-search-params":80,"../modules/web.url.to-json":82}]},{},[83]);
vendor/wp-polyfill-inert.min.js 0000666 00000017753 15123355174 0012605 0 ustar 00 !function(e){"object"==typeof exports&&"undefined"!=typeof module||"function"!=typeof define||!define.amd?e():define("inert",e)}((function(){"use strict";var e,t,n,i,o,r,s=function(e,t,n){return t&&a(e.prototype,t),n&&a(e,n),e};function a(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function d(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(e,t){d(this,u),this._inertManager=t,this._rootElement=e,this._managedNodes=new Set,this._rootElement.hasAttribute("aria-hidden")?this._savedAriaHidden=this._rootElement.getAttribute("aria-hidden"):this._savedAriaHidden=null,this._rootElement.setAttribute("aria-hidden","true"),this._makeSubtreeUnfocusable(this._rootElement),this._observer=new MutationObserver(this._onMutation.bind(this)),this._observer.observe(this._rootElement,{attributes:!0,childList:!0,subtree:!0})}function h(e,t){d(this,h),this._node=e,this._overrodeFocusMethod=!1,this._inertRoots=new Set([t]),this._savedTabIndex=null,this._destroyed=!1,this.ensureUntabbable()}function l(e){if(d(this,l),!e)throw new Error("Missing required argument; InertManager needs to wrap a document.");this._document=e,this._managedNodes=new Map,this._inertRoots=new Map,this._observer=new MutationObserver(this._watchForInert.bind(this)),_(e.head||e.body||e.documentElement),"loading"===e.readyState?e.addEventListener("DOMContentLoaded",this._onDocumentLoaded.bind(this)):this._onDocumentLoaded()}function c(e,t,n){if(e.nodeType==Node.ELEMENT_NODE){var i=e;if(s=(t&&t(i),i.shadowRoot))return void c(s,t,s);if("content"==i.localName){for(var o=(s=i).getDistributedNodes?s.getDistributedNodes():[],r=0;r<o.length;r++)c(o[r],t,n);return}if("slot"==i.localName){for(var s,a=(s=i).assignedNodes?s.assignedNodes({flatten:!0}):[],d=0;d<a.length;d++)c(a[d],t,n);return}}for(var u=e.firstChild;null!=u;)c(u,t,n),u=u.nextSibling}function _(e){var t;e.querySelector("style#inert-style, link#inert-style")||((t=document.createElement("style")).setAttribute("id","inert-style"),t.textContent="\n[inert] {\n pointer-events: none;\n cursor: default;\n}\n\n[inert], [inert] * {\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n",e.appendChild(t))}"undefined"!=typeof window&&(e=Array.prototype.slice,t=Element.prototype.matches||Element.prototype.msMatchesSelector,n=["a[href]","area[href]","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","button:not([disabled])","details","summary","iframe","object","embed","[contenteditable]"].join(","),s(u,[{key:"destructor",value:function(){this._observer.disconnect(),this._rootElement&&(null!==this._savedAriaHidden?this._rootElement.setAttribute("aria-hidden",this._savedAriaHidden):this._rootElement.removeAttribute("aria-hidden")),this._managedNodes.forEach((function(e){this._unmanageNode(e.node)}),this),this._observer=null,this._rootElement=null,this._managedNodes=null,this._inertManager=null}},{key:"_makeSubtreeUnfocusable",value:function(e){var t=this,n=(c(e,(function(e){return t._visitNode(e)})),document.activeElement);if(!document.body.contains(e)){for(var i=e,o=void 0;i;){if(i.nodeType===Node.DOCUMENT_FRAGMENT_NODE){o=i;break}i=i.parentNode}o&&(n=o.activeElement)}e.contains(n)&&(n.blur(),n===document.activeElement&&document.body.focus())}},{key:"_visitNode",value:function(e){e.nodeType===Node.ELEMENT_NODE&&(e!==this._rootElement&&e.hasAttribute("inert")&&this._adoptInertRoot(e),(t.call(e,n)||e.hasAttribute("tabindex"))&&this._manageNode(e))}},{key:"_manageNode",value:function(e){e=this._inertManager.register(e,this),this._managedNodes.add(e)}},{key:"_unmanageNode",value:function(e){(e=this._inertManager.deregister(e,this))&&this._managedNodes.delete(e)}},{key:"_unmanageSubtree",value:function(e){var t=this;c(e,(function(e){return t._unmanageNode(e)}))}},{key:"_adoptInertRoot",value:function(e){var t=this._inertManager.getInertRoot(e);t||(this._inertManager.setInert(e,!0),t=this._inertManager.getInertRoot(e)),t.managedNodes.forEach((function(e){this._manageNode(e.node)}),this)}},{key:"_onMutation",value:function(t,n){t.forEach((function(t){var n,i=t.target;"childList"===t.type?(e.call(t.addedNodes).forEach((function(e){this._makeSubtreeUnfocusable(e)}),this),e.call(t.removedNodes).forEach((function(e){this._unmanageSubtree(e)}),this)):"attributes"===t.type&&("tabindex"===t.attributeName?this._manageNode(i):i!==this._rootElement&&"inert"===t.attributeName&&i.hasAttribute("inert")&&(this._adoptInertRoot(i),n=this._inertManager.getInertRoot(i),this._managedNodes.forEach((function(e){i.contains(e.node)&&n._manageNode(e.node)}))))}),this)}},{key:"managedNodes",get:function(){return new Set(this._managedNodes)}},{key:"hasSavedAriaHidden",get:function(){return null!==this._savedAriaHidden}},{key:"savedAriaHidden",set:function(e){this._savedAriaHidden=e},get:function(){return this._savedAriaHidden}}]),i=u,s(h,[{key:"destructor",value:function(){var e;this._throwIfDestroyed(),this._node&&this._node.nodeType===Node.ELEMENT_NODE&&(e=this._node,null!==this._savedTabIndex?e.setAttribute("tabindex",this._savedTabIndex):e.removeAttribute("tabindex"),this._overrodeFocusMethod&&delete e.focus),this._node=null,this._inertRoots=null,this._destroyed=!0}},{key:"_throwIfDestroyed",value:function(){if(this.destroyed)throw new Error("Trying to access destroyed InertNode")}},{key:"ensureUntabbable",value:function(){var e;this.node.nodeType===Node.ELEMENT_NODE&&(e=this.node,t.call(e,n)?-1===e.tabIndex&&this.hasSavedTabIndex||(e.hasAttribute("tabindex")&&(this._savedTabIndex=e.tabIndex),e.setAttribute("tabindex","-1"),e.nodeType===Node.ELEMENT_NODE&&(e.focus=function(){},this._overrodeFocusMethod=!0)):e.hasAttribute("tabindex")&&(this._savedTabIndex=e.tabIndex,e.removeAttribute("tabindex")))}},{key:"addInertRoot",value:function(e){this._throwIfDestroyed(),this._inertRoots.add(e)}},{key:"removeInertRoot",value:function(e){this._throwIfDestroyed(),this._inertRoots.delete(e),0===this._inertRoots.size&&this.destructor()}},{key:"destroyed",get:function(){return this._destroyed}},{key:"hasSavedTabIndex",get:function(){return null!==this._savedTabIndex}},{key:"node",get:function(){return this._throwIfDestroyed(),this._node}},{key:"savedTabIndex",set:function(e){this._throwIfDestroyed(),this._savedTabIndex=e},get:function(){return this._throwIfDestroyed(),this._savedTabIndex}}]),o=h,s(l,[{key:"setInert",value:function(e,t){if(t){if(!this._inertRoots.has(e)&&(t=new i(e,this),e.setAttribute("inert",""),this._inertRoots.set(e,t),!this._document.body.contains(e)))for(var n=e.parentNode;n;)11===n.nodeType&&_(n),n=n.parentNode}else this._inertRoots.has(e)&&(this._inertRoots.get(e).destructor(),this._inertRoots.delete(e),e.removeAttribute("inert"))}},{key:"getInertRoot",value:function(e){return this._inertRoots.get(e)}},{key:"register",value:function(e,t){var n=this._managedNodes.get(e);return void 0!==n?n.addInertRoot(t):n=new o(e,t),this._managedNodes.set(e,n),n}},{key:"deregister",value:function(e,t){var n=this._managedNodes.get(e);return n?(n.removeInertRoot(t),n.destroyed&&this._managedNodes.delete(e),n):null}},{key:"_onDocumentLoaded",value:function(){e.call(this._document.querySelectorAll("[inert]")).forEach((function(e){this.setInert(e,!0)}),this),this._observer.observe(this._document.body||this._document.documentElement,{attributes:!0,subtree:!0,childList:!0})}},{key:"_watchForInert",value:function(n,i){var o=this;n.forEach((function(n){switch(n.type){case"childList":e.call(n.addedNodes).forEach((function(n){var i;n.nodeType===Node.ELEMENT_NODE&&(i=e.call(n.querySelectorAll("[inert]")),t.call(n,"[inert]")&&i.unshift(n),i.forEach((function(e){this.setInert(e,!0)}),o))}),o);break;case"attributes":if("inert"!==n.attributeName)return;var i=n.target,r=i.hasAttribute("inert");o.setInert(i,r)}}),this)}}]),s=l,HTMLElement.prototype.hasOwnProperty("inert")||(r=new s(document),Object.defineProperty(HTMLElement.prototype,"inert",{enumerable:!0,get:function(){return this.hasAttribute("inert")},set:function(e){r.setInert(this,e)}})))})); vendor/wp-polyfill-dom-rect.min.js 0000666 00000001541 15123355174 0013162 0 ustar 00 !function(){function e(e){return void 0===e?0:Number(e)}function n(e,n){return!(e===n||isNaN(e)&&isNaN(n))}self.DOMRect=function(t,i,u,r){var o,f,c,a,m=e(t),b=e(i),d=e(u),g=e(r);Object.defineProperties(this,{x:{get:function(){return m},set:function(e){n(m,e)&&(m=e,o=f=void 0)},enumerable:!0},y:{get:function(){return b},set:function(e){n(b,e)&&(b=e,c=a=void 0)},enumerable:!0},width:{get:function(){return d},set:function(e){n(d,e)&&(d=e,o=f=void 0)},enumerable:!0},height:{get:function(){return g},set:function(e){n(g,e)&&(g=e,c=a=void 0)},enumerable:!0},left:{get:function(){return o=void 0===o?m+Math.min(0,d):o},enumerable:!0},right:{get:function(){return f=void 0===f?m+Math.max(0,d):f},enumerable:!0},top:{get:function(){return c=void 0===c?b+Math.min(0,g):c},enumerable:!0},bottom:{get:function(){return a=void 0===a?b+Math.max(0,g):a},enumerable:!0}})}}(); vendor/wp-polyfill-formdata.min.js 0000666 00000021106 15123355174 0013244 0 ustar 00 /*! formdata-polyfill. MIT License. Jimmy W?rting <https://jimmy.warting.se/opensource> */
!function(){var t;function e(t){var e=0;return function(){return e<t.length?{done:!1,value:t[e++]}:{done:!0}}}var n="function"==typeof Object.defineProperties?Object.defineProperty:function(t,e,n){return t==Array.prototype||t==Object.prototype||(t[e]=n.value),t};var r,o=function(t){t=["object"==typeof globalThis&&globalThis,t,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof global&&global];for(var e=0;e<t.length;++e){var n=t[e];if(n&&n.Math==Math)return n}throw Error("Cannot find global object")}(this);function i(t,e){if(e)t:{var r=o;t=t.split(".");for(var i=0;i<t.length-1;i++){var a=t[i];if(!(a in r))break t;r=r[a]}(e=e(i=r[t=t[t.length-1]]))!=i&&null!=e&&n(r,t,{configurable:!0,writable:!0,value:e})}}function a(t){return(t={next:t})[Symbol.iterator]=function(){return this},t}function u(t){var n="undefined"!=typeof Symbol&&Symbol.iterator&&t[Symbol.iterator];return n?n.call(t):{next:e(t)}}if(i("Symbol",(function(t){function e(t,e){this.A=t,n(this,"description",{configurable:!0,writable:!0,value:e})}if(t)return t;e.prototype.toString=function(){return this.A};var r="jscomp_symbol_"+(1e9*Math.random()>>>0)+"_",o=0;return function t(n){if(this instanceof t)throw new TypeError("Symbol is not a constructor");return new e(r+(n||"")+"_"+o++,n)}})),i("Symbol.iterator",(function(t){if(t)return t;t=Symbol("Symbol.iterator");for(var r="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),i=0;i<r.length;i++){var u=o[r[i]];"function"==typeof u&&"function"!=typeof u.prototype[t]&&n(u.prototype,t,{configurable:!0,writable:!0,value:function(){return a(e(this))}})}return t})),"function"==typeof Object.setPrototypeOf)r=Object.setPrototypeOf;else{var l;t:{var s={};try{s.__proto__={a:!0},l=s.a;break t}catch(t){}l=!1}r=l?function(t,e){if(t.__proto__=e,t.__proto__!==e)throw new TypeError(t+" is not extensible");return t}:null}var f=r;function c(){this.m=!1,this.j=null,this.v=void 0,this.h=1,this.u=this.C=0,this.l=null}function h(t){if(t.m)throw new TypeError("Generator is already running");t.m=!0}function p(t,e){return t.h=3,{value:e}}function y(t){this.g=new c,this.G=t}function v(t,e,n,r){try{var o=e.call(t.g.j,n);if(!(o instanceof Object))throw new TypeError("Iterator result "+o+" is not an object");if(!o.done)return t.g.m=!1,o;var i=o.value}catch(e){return t.g.j=null,t.g.s(e),g(t)}return t.g.j=null,r.call(t.g,i),g(t)}function g(t){for(;t.g.h;)try{var e=t.G(t.g);if(e)return t.g.m=!1,{value:e.value,done:!1}}catch(e){t.g.v=void 0,t.g.s(e)}if(t.g.m=!1,t.g.l){if(e=t.g.l,t.g.l=null,e.F)throw e.D;return{value:e.return,done:!0}}return{value:void 0,done:!0}}function d(t){this.next=function(e){return t.o(e)},this.throw=function(e){return t.s(e)},this.return=function(e){return function(t,e){h(t.g);var n=t.g.j;return n?v(t,"return"in n?n.return:function(t){return{value:t,done:!0}},e,t.g.return):(t.g.return(e),g(t))}(t,e)},this[Symbol.iterator]=function(){return this}}function b(t,e){return e=new d(new y(e)),f&&t.prototype&&f(e,t.prototype),e}if(c.prototype.o=function(t){this.v=t},c.prototype.s=function(t){this.l={D:t,F:!0},this.h=this.C||this.u},c.prototype.return=function(t){this.l={return:t},this.h=this.u},y.prototype.o=function(t){return h(this.g),this.g.j?v(this,this.g.j.next,t,this.g.o):(this.g.o(t),g(this))},y.prototype.s=function(t){return h(this.g),this.g.j?v(this,this.g.j.throw,t,this.g.o):(this.g.s(t),g(this))},i("Array.prototype.entries",(function(t){return t||function(){return function(t,e){t instanceof String&&(t+="");var n=0,r=!1,o={next:function(){if(!r&&n<t.length){var o=n++;return{value:e(o,t[o]),done:!1}}return r=!0,{done:!0,value:void 0}}};return o[Symbol.iterator]=function(){return o},o}(this,(function(t,e){return[t,e]}))}})),"undefined"!=typeof Blob&&("undefined"==typeof FormData||!FormData.prototype.keys)){var m=function(t,e){for(var n=0;n<t.length;n++)e(t[n])},w=function(t){return t.replace(/\r?\n|\r/g,"\r\n")},S=function(t,e,n){return e instanceof Blob?(n=void 0!==n?String(n+""):"string"==typeof e.name?e.name:"blob",e.name===n&&"[object Blob]"!==Object.prototype.toString.call(e)||(e=new File([e],n)),[String(t),e]):[String(t),String(e)]},j=function(t,e){if(t.length<e)throw new TypeError(e+" argument required, but only "+t.length+" present.")},x="object"==typeof globalThis?globalThis:"object"==typeof window?window:"object"==typeof self?self:this,_=x.FormData,F=x.XMLHttpRequest&&x.XMLHttpRequest.prototype.send,A=x.Request&&x.fetch,M=x.navigator&&x.navigator.sendBeacon,D=x.Element&&x.Element.prototype,B=x.Symbol&&Symbol.toStringTag;B&&(Blob.prototype[B]||(Blob.prototype[B]="Blob"),"File"in x&&!File.prototype[B]&&(File.prototype[B]="File"));try{new File([],"")}catch(t){x.File=function(t,e,n){return t=new Blob(t,n||{}),Object.defineProperties(t,{name:{value:e},lastModified:{value:+(n&&void 0!==n.lastModified?new Date(n.lastModified):new Date)},toString:{value:function(){return"[object File]"}}}),B&&Object.defineProperty(t,B,{value:"File"}),t}}var T=function(t){return t.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22")},q=function(t){this.i=[];var e=this;t&&m(t.elements,(function(t){if(t.name&&!t.disabled&&"submit"!==t.type&&"button"!==t.type&&!t.matches("form fieldset[disabled] *"))if("file"===t.type){var n=t.files&&t.files.length?t.files:[new File([],"",{type:"application/octet-stream"})];m(n,(function(n){e.append(t.name,n)}))}else"select-multiple"===t.type||"select-one"===t.type?m(t.options,(function(n){!n.disabled&&n.selected&&e.append(t.name,n.value)})):"checkbox"===t.type||"radio"===t.type?t.checked&&e.append(t.name,t.value):(n="textarea"===t.type?w(t.value):t.value,e.append(t.name,n))}))};if((t=q.prototype).append=function(t,e,n){j(arguments,2),this.i.push(S(t,e,n))},t.delete=function(t){j(arguments,1);var e=[];t=String(t),m(this.i,(function(n){n[0]!==t&&e.push(n)})),this.i=e},t.entries=function t(){var e,n=this;return b(t,(function(t){if(1==t.h&&(e=0),3!=t.h)return e<n.i.length?t=p(t,n.i[e]):(t.h=0,t=void 0),t;e++,t.h=2}))},t.forEach=function(t,e){j(arguments,1);for(var n=u(this),r=n.next();!r.done;r=n.next()){var o=u(r.value);r=o.next().value,o=o.next().value,t.call(e,o,r,this)}},t.get=function(t){j(arguments,1);var e=this.i;t=String(t);for(var n=0;n<e.length;n++)if(e[n][0]===t)return e[n][1];return null},t.getAll=function(t){j(arguments,1);var e=[];return t=String(t),m(this.i,(function(n){n[0]===t&&e.push(n[1])})),e},t.has=function(t){j(arguments,1),t=String(t);for(var e=0;e<this.i.length;e++)if(this.i[e][0]===t)return!0;return!1},t.keys=function t(){var e,n,r,o,i=this;return b(t,(function(t){if(1==t.h&&(e=u(i),n=e.next()),3!=t.h)return n.done?void(t.h=0):(r=n.value,o=u(r),p(t,o.next().value));n=e.next(),t.h=2}))},t.set=function(t,e,n){j(arguments,2),t=String(t);var r=[],o=S(t,e,n),i=!0;m(this.i,(function(e){e[0]===t?i&&(i=!r.push(o)):r.push(e)})),i&&r.push(o),this.i=r},t.values=function t(){var e,n,r,o,i=this;return b(t,(function(t){if(1==t.h&&(e=u(i),n=e.next()),3!=t.h)return n.done?void(t.h=0):(r=n.value,(o=u(r)).next(),p(t,o.next().value));n=e.next(),t.h=2}))},q.prototype._asNative=function(){for(var t=new _,e=u(this),n=e.next();!n.done;n=e.next()){var r=u(n.value);n=r.next().value,r=r.next().value,t.append(n,r)}return t},q.prototype._blob=function(){var t="----formdata-polyfill-"+Math.random(),e=[],n="--"+t+'\r\nContent-Disposition: form-data; name="';return this.forEach((function(t,r){return"string"==typeof t?e.push(n+T(w(r))+'"\r\n\r\n'+w(t)+"\r\n"):e.push(n+T(w(r))+'"; filename="'+T(t.name)+'"\r\nContent-Type: '+(t.type||"application/octet-stream")+"\r\n\r\n",t,"\r\n")})),e.push("--"+t+"--"),new Blob(e,{type:"multipart/form-data; boundary="+t})},q.prototype[Symbol.iterator]=function(){return this.entries()},q.prototype.toString=function(){return"[object FormData]"},D&&!D.matches&&(D.matches=D.matchesSelector||D.mozMatchesSelector||D.msMatchesSelector||D.oMatchesSelector||D.webkitMatchesSelector||function(t){for(var e=(t=(this.document||this.ownerDocument).querySelectorAll(t)).length;0<=--e&&t.item(e)!==this;);return-1<e}),B&&(q.prototype[B]="FormData"),F){var O=x.XMLHttpRequest.prototype.setRequestHeader;x.XMLHttpRequest.prototype.setRequestHeader=function(t,e){O.call(this,t,e),"content-type"===t.toLowerCase()&&(this.B=!0)},x.XMLHttpRequest.prototype.send=function(t){t instanceof q?(t=t._blob(),this.B||this.setRequestHeader("Content-Type",t.type),F.call(this,t)):F.call(this,t)}}A&&(x.fetch=function(t,e){return e&&e.body&&e.body instanceof q&&(e.body=e.body._blob()),A.call(this,t,e)}),M&&(x.navigator.sendBeacon=function(t,e){return e instanceof q&&(e=e._asNative()),M.call(this,t,e)}),x.FormData=q}}(); vendor/lodash.js 0000666 00002046542 15123355174 0007700 0 ustar 00 /**
* @license
* Lodash <https://lodash.com/>
* Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
;(function() {
/** Used as a safe reference for `undefined` in pre-ES5 environments. */
var undefined;
/** Used as the semantic version number. */
var VERSION = '4.17.21';
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/** Error message constants. */
var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.',
FUNC_ERROR_TEXT = 'Expected a function',
INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`';
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_BOUND_FLAG = 4,
WRAP_CURRY_FLAG = 8,
WRAP_CURRY_RIGHT_FLAG = 16,
WRAP_PARTIAL_FLAG = 32,
WRAP_PARTIAL_RIGHT_FLAG = 64,
WRAP_ARY_FLAG = 128,
WRAP_REARG_FLAG = 256,
WRAP_FLIP_FLAG = 512;
/** Used as default options for `_.truncate`. */
var DEFAULT_TRUNC_LENGTH = 30,
DEFAULT_TRUNC_OMISSION = '...';
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
HOT_SPAN = 16;
/** Used to indicate the type of lazy iteratees. */
var LAZY_FILTER_FLAG = 1,
LAZY_MAP_FLAG = 2,
LAZY_WHILE_FLAG = 3;
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
MAX_SAFE_INTEGER = 9007199254740991,
MAX_INTEGER = 1.7976931348623157e+308,
NAN = 0 / 0;
/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295,
MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
/** Used to associate wrap methods with their bit flags. */
var wrapFlags = [
['ary', WRAP_ARY_FLAG],
['bind', WRAP_BIND_FLAG],
['bindKey', WRAP_BIND_KEY_FLAG],
['curry', WRAP_CURRY_FLAG],
['curryRight', WRAP_CURRY_RIGHT_FLAG],
['flip', WRAP_FLIP_FLAG],
['partial', WRAP_PARTIAL_FLAG],
['partialRight', WRAP_PARTIAL_RIGHT_FLAG],
['rearg', WRAP_REARG_FLAG]
];
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
asyncTag = '[object AsyncFunction]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
domExcTag = '[object DOMException]',
errorTag = '[object Error]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
nullTag = '[object Null]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
proxyTag = '[object Proxy]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]',
undefinedTag = '[object Undefined]',
weakMapTag = '[object WeakMap]',
weakSetTag = '[object WeakSet]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to match empty string literals in compiled template source. */
var reEmptyStringLeading = /\b__p \+= '';/g,
reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
/** Used to match HTML entities and HTML characters. */
var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g,
reUnescapedHtml = /[&<>"']/g,
reHasEscapedHtml = RegExp(reEscapedHtml.source),
reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
/** Used to match template delimiters. */
var reEscape = /<%-([\s\S]+?)%>/g,
reEvaluate = /<%([\s\S]+?)%>/g,
reInterpolate = /<%=([\s\S]+?)%>/g;
/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
reIsPlainProp = /^\w*$/,
rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g,
reHasRegExpChar = RegExp(reRegExpChar.source);
/** Used to match leading whitespace. */
var reTrimStart = /^\s+/;
/** Used to match a single whitespace character. */
var reWhitespace = /\s/;
/** Used to match wrap detail comments. */
var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,
reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
reSplitDetails = /,? & /;
/** Used to match words composed of alphanumeric characters. */
var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
/**
* Used to validate the `validate` option in `_.template` variable.
*
* Forbids characters which could potentially change the meaning of the function argument definition:
* - "()," (modification of function parameters)
* - "=" (default value)
* - "[]{}" (destructuring of function parameters)
* - "/" (beginning of a comment)
* - whitespace
*/
var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/**
* Used to match
* [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).
*/
var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/** Used to match Latin Unicode letters (excluding mathematical operators). */
var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
/** Used to ensure capturing order of template delimiters. */
var reNoMatch = /($^)/;
/** Used to match unescaped characters in compiled string literals. */
var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
rsDingbatRange = '\\u2700-\\u27bf',
rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
rsPunctuationRange = '\\u2000-\\u206f',
rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',
rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
rsVarRange = '\\ufe0e\\ufe0f',
rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
/** Used to compose unicode capture groups. */
var rsApos = "['\u2019]",
rsAstral = '[' + rsAstralRange + ']',
rsBreak = '[' + rsBreakRange + ']',
rsCombo = '[' + rsComboRange + ']',
rsDigits = '\\d+',
rsDingbat = '[' + rsDingbatRange + ']',
rsLower = '[' + rsLowerRange + ']',
rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
rsFitz = '\\ud83c[\\udffb-\\udfff]',
rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
rsNonAstral = '[^' + rsAstralRange + ']',
rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
rsUpper = '[' + rsUpperRange + ']',
rsZWJ = '\\u200d';
/** Used to compose unicode regexes. */
var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',
rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',
rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
reOptMod = rsModifier + '?',
rsOptVar = '[' + rsVarRange + ']?',
rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])',
rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])',
rsSeq = rsOptVar + reOptMod + rsOptJoin,
rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
/** Used to match apostrophes. */
var reApos = RegExp(rsApos, 'g');
/**
* Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
* [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
*/
var reComboMark = RegExp(rsCombo, 'g');
/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
/** Used to match complex or compound words. */
var reUnicodeWord = RegExp([
rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',
rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,
rsUpper + '+' + rsOptContrUpper,
rsOrdUpper,
rsOrdLower,
rsDigits,
rsEmoji
].join('|'), 'g');
/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
/** Used to detect strings that need a more robust regexp to match words. */
var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
/** Used to assign default `context` object properties. */
var contextProps = [
'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array',
'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object',
'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array',
'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap',
'_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout'
];
/** Used to make template sourceURLs easier to identify. */
var templateCounter = -1;
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] =
cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
cloneableTags[boolTag] = cloneableTags[dateTag] =
cloneableTags[float32Tag] = cloneableTags[float64Tag] =
cloneableTags[int8Tag] = cloneableTags[int16Tag] =
cloneableTags[int32Tag] = cloneableTags[mapTag] =
cloneableTags[numberTag] = cloneableTags[objectTag] =
cloneableTags[regexpTag] = cloneableTags[setTag] =
cloneableTags[stringTag] = cloneableTags[symbolTag] =
cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] =
cloneableTags[weakMapTag] = false;
/** Used to map Latin Unicode letters to basic Latin letters. */
var deburredLetters = {
// Latin-1 Supplement block.
'\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
'\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
'\xc7': 'C', '\xe7': 'c',
'\xd0': 'D', '\xf0': 'd',
'\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
'\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
'\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
'\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
'\xd1': 'N', '\xf1': 'n',
'\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
'\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
'\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
'\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
'\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
'\xc6': 'Ae', '\xe6': 'ae',
'\xde': 'Th', '\xfe': 'th',
'\xdf': 'ss',
// Latin Extended-A block.
'\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
'\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
'\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
'\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
'\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
'\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
'\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
'\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
'\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
'\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
'\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
'\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
'\u0134': 'J', '\u0135': 'j',
'\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
'\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
'\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
'\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
'\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
'\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
'\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
'\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
'\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
'\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
'\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
'\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
'\u0163': 't', '\u0165': 't', '\u0167': 't',
'\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
'\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
'\u0174': 'W', '\u0175': 'w',
'\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
'\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
'\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
'\u0132': 'IJ', '\u0133': 'ij',
'\u0152': 'Oe', '\u0153': 'oe',
'\u0149': "'n", '\u017f': 's'
};
/** Used to map characters to HTML entities. */
var htmlEscapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
/** Used to map HTML entities to characters. */
var htmlUnescapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': "'"
};
/** Used to escape characters for inclusion in compiled string literals. */
var stringEscapes = {
'\\': '\\',
"'": "'",
'\n': 'n',
'\r': 'r',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
/** Built-in method references without a dependency on `root`. */
var freeParseFloat = parseFloat,
freeParseInt = parseInt;
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
// Use `util.types` for Node.js 10+.
var types = freeModule && freeModule.require && freeModule.require('util').types;
if (types) {
return types;
}
// Legacy `process.binding('util')` for Node.js < 10.
return freeProcess && freeProcess.binding && freeProcess.binding('util');
} catch (e) {}
}());
/* Node.js helper references. */
var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer,
nodeIsDate = nodeUtil && nodeUtil.isDate,
nodeIsMap = nodeUtil && nodeUtil.isMap,
nodeIsRegExp = nodeUtil && nodeUtil.isRegExp,
nodeIsSet = nodeUtil && nodeUtil.isSet,
nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
/*--------------------------------------------------------------------------*/
/**
* A faster alternative to `Function#apply`, this function invokes `func`
* with the `this` binding of `thisArg` and the arguments of `args`.
*
* @private
* @param {Function} func The function to invoke.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} args The arguments to invoke `func` with.
* @returns {*} Returns the result of `func`.
*/
function apply(func, thisArg, args) {
switch (args.length) {
case 0: return func.call(thisArg);
case 1: return func.call(thisArg, args[0]);
case 2: return func.call(thisArg, args[0], args[1]);
case 3: return func.call(thisArg, args[0], args[1], args[2]);
}
return func.apply(thisArg, args);
}
/**
* A specialized version of `baseAggregator` for arrays.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform keys.
* @param {Object} accumulator The initial aggregated object.
* @returns {Function} Returns `accumulator`.
*/
function arrayAggregator(array, setter, iteratee, accumulator) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
var value = array[index];
setter(accumulator, value, iteratee(value), array);
}
return accumulator;
}
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
/**
* A specialized version of `_.forEachRight` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEachRight(array, iteratee) {
var length = array == null ? 0 : array.length;
while (length--) {
if (iteratee(array[length], length, array) === false) {
break;
}
}
return array;
}
/**
* A specialized version of `_.every` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
*/
function arrayEvery(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (!predicate(array[index], index, array)) {
return false;
}
}
return true;
}
/**
* A specialized version of `_.filter` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function arrayFilter(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[resIndex++] = value;
}
}
return result;
}
/**
* A specialized version of `_.includes` for arrays without support for
* specifying an index to search from.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludes(array, value) {
var length = array == null ? 0 : array.length;
return !!length && baseIndexOf(array, value, 0) > -1;
}
/**
* This function is like `arrayIncludes` except that it accepts a comparator.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @param {Function} comparator The comparator invoked per element.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludesWith(array, value, comparator) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (comparator(value, array[index])) {
return true;
}
}
return false;
}
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
/**
* A specialized version of `_.reduce` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the first element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduce(array, iteratee, accumulator, initAccum) {
var index = -1,
length = array == null ? 0 : array.length;
if (initAccum && length) {
accumulator = array[++index];
}
while (++index < length) {
accumulator = iteratee(accumulator, array[index], index, array);
}
return accumulator;
}
/**
* A specialized version of `_.reduceRight` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the last element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduceRight(array, iteratee, accumulator, initAccum) {
var length = array == null ? 0 : array.length;
if (initAccum && length) {
accumulator = array[--length];
}
while (length--) {
accumulator = iteratee(accumulator, array[length], length, array);
}
return accumulator;
}
/**
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
/**
* Gets the size of an ASCII `string`.
*
* @private
* @param {string} string The string inspect.
* @returns {number} Returns the string size.
*/
var asciiSize = baseProperty('length');
/**
* Converts an ASCII `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function asciiToArray(string) {
return string.split('');
}
/**
* Splits an ASCII `string` into an array of its words.
*
* @private
* @param {string} The string to inspect.
* @returns {Array} Returns the words of `string`.
*/
function asciiWords(string) {
return string.match(reAsciiWord) || [];
}
/**
* The base implementation of methods like `_.findKey` and `_.findLastKey`,
* without support for iteratee shorthands, which iterates over `collection`
* using `eachFunc`.
*
* @private
* @param {Array|Object} collection The collection to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {Function} eachFunc The function to iterate over `collection`.
* @returns {*} Returns the found element or its key, else `undefined`.
*/
function baseFindKey(collection, predicate, eachFunc) {
var result;
eachFunc(collection, function(value, key, collection) {
if (predicate(value, key, collection)) {
result = key;
return false;
}
});
return result;
}
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {number} fromIndex The index to search from.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseFindIndex(array, predicate, fromIndex, fromRight) {
var length = array.length,
index = fromIndex + (fromRight ? 1 : -1);
while ((fromRight ? index-- : ++index < length)) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
/**
* The base implementation of `_.indexOf` without `fromIndex` bounds checks.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseIndexOf(array, value, fromIndex) {
return value === value
? strictIndexOf(array, value, fromIndex)
: baseFindIndex(array, baseIsNaN, fromIndex);
}
/**
* This function is like `baseIndexOf` except that it accepts a comparator.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @param {Function} comparator The comparator invoked per element.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseIndexOfWith(array, value, fromIndex, comparator) {
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (comparator(array[index], value)) {
return index;
}
}
return -1;
}
/**
* The base implementation of `_.isNaN` without support for number objects.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
*/
function baseIsNaN(value) {
return value !== value;
}
/**
* The base implementation of `_.mean` and `_.meanBy` without support for
* iteratee shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {number} Returns the mean.
*/
function baseMean(array, iteratee) {
var length = array == null ? 0 : array.length;
return length ? (baseSum(array, iteratee) / length) : NAN;
}
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* The base implementation of `_.propertyOf` without support for deep paths.
*
* @private
* @param {Object} object The object to query.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyOf(object) {
return function(key) {
return object == null ? undefined : object[key];
};
}
/**
* The base implementation of `_.reduce` and `_.reduceRight`, without support
* for iteratee shorthands, which iterates over `collection` using `eachFunc`.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} accumulator The initial value.
* @param {boolean} initAccum Specify using the first or last element of
* `collection` as the initial value.
* @param {Function} eachFunc The function to iterate over `collection`.
* @returns {*} Returns the accumulated value.
*/
function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
eachFunc(collection, function(value, index, collection) {
accumulator = initAccum
? (initAccum = false, value)
: iteratee(accumulator, value, index, collection);
});
return accumulator;
}
/**
* The base implementation of `_.sortBy` which uses `comparer` to define the
* sort order of `array` and replaces criteria objects with their corresponding
* values.
*
* @private
* @param {Array} array The array to sort.
* @param {Function} comparer The function to define sort order.
* @returns {Array} Returns `array`.
*/
function baseSortBy(array, comparer) {
var length = array.length;
array.sort(comparer);
while (length--) {
array[length] = array[length].value;
}
return array;
}
/**
* The base implementation of `_.sum` and `_.sumBy` without support for
* iteratee shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {number} Returns the sum.
*/
function baseSum(array, iteratee) {
var result,
index = -1,
length = array.length;
while (++index < length) {
var current = iteratee(array[index]);
if (current !== undefined) {
result = result === undefined ? current : (result + current);
}
}
return result;
}
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
/**
* The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array
* of key-value pairs for `object` corresponding to the property names of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the key-value pairs.
*/
function baseToPairs(object, props) {
return arrayMap(props, function(key) {
return [key, object[key]];
});
}
/**
* The base implementation of `_.trim`.
*
* @private
* @param {string} string The string to trim.
* @returns {string} Returns the trimmed string.
*/
function baseTrim(string) {
return string
? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')
: string;
}
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/
function baseUnary(func) {
return function(value) {
return func(value);
};
}
/**
* The base implementation of `_.values` and `_.valuesIn` which creates an
* array of `object` property values corresponding to the property names
* of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the array of property values.
*/
function baseValues(object, props) {
return arrayMap(props, function(key) {
return object[key];
});
}
/**
* Checks if a `cache` value for `key` exists.
*
* @private
* @param {Object} cache The cache to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function cacheHas(cache, key) {
return cache.has(key);
}
/**
* Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the first unmatched string symbol.
*/
function charsStartIndex(strSymbols, chrSymbols) {
var index = -1,
length = strSymbols.length;
while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the last unmatched string symbol.
*/
function charsEndIndex(strSymbols, chrSymbols) {
var index = strSymbols.length;
while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
/**
* Gets the number of `placeholder` occurrences in `array`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} placeholder The placeholder to search for.
* @returns {number} Returns the placeholder count.
*/
function countHolders(array, placeholder) {
var length = array.length,
result = 0;
while (length--) {
if (array[length] === placeholder) {
++result;
}
}
return result;
}
/**
* Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
* letters to basic Latin letters.
*
* @private
* @param {string} letter The matched letter to deburr.
* @returns {string} Returns the deburred letter.
*/
var deburrLetter = basePropertyOf(deburredLetters);
/**
* Used by `_.escape` to convert characters to HTML entities.
*
* @private
* @param {string} chr The matched character to escape.
* @returns {string} Returns the escaped character.
*/
var escapeHtmlChar = basePropertyOf(htmlEscapes);
/**
* Used by `_.template` to escape characters for inclusion in compiled string literals.
*
* @private
* @param {string} chr The matched character to escape.
* @returns {string} Returns the escaped character.
*/
function escapeStringChar(chr) {
return '\\' + stringEscapes[chr];
}
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
/**
* Checks if `string` contains Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a symbol is found, else `false`.
*/
function hasUnicode(string) {
return reHasUnicode.test(string);
}
/**
* Checks if `string` contains a word composed of Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a word is found, else `false`.
*/
function hasUnicodeWord(string) {
return reHasUnicodeWord.test(string);
}
/**
* Converts `iterator` to an array.
*
* @private
* @param {Object} iterator The iterator to convert.
* @returns {Array} Returns the converted array.
*/
function iteratorToArray(iterator) {
var data,
result = [];
while (!(data = iterator.next()).done) {
result.push(data.value);
}
return result;
}
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
/**
* Replaces all `placeholder` elements in `array` with an internal placeholder
* and returns an array of their indexes.
*
* @private
* @param {Array} array The array to modify.
* @param {*} placeholder The placeholder to replace.
* @returns {Array} Returns the new array of placeholder indexes.
*/
function replaceHolders(array, placeholder) {
var index = -1,
length = array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value === placeholder || value === PLACEHOLDER) {
array[index] = PLACEHOLDER;
result[resIndex++] = index;
}
}
return result;
}
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
/**
* Converts `set` to its value-value pairs.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the value-value pairs.
*/
function setToPairs(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = [value, value];
});
return result;
}
/**
* A specialized version of `_.indexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function strictIndexOf(array, value, fromIndex) {
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* A specialized version of `_.lastIndexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function strictLastIndexOf(array, value, fromIndex) {
var index = fromIndex + 1;
while (index--) {
if (array[index] === value) {
return index;
}
}
return index;
}
/**
* Gets the number of symbols in `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the string size.
*/
function stringSize(string) {
return hasUnicode(string)
? unicodeSize(string)
: asciiSize(string);
}
/**
* Converts `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function stringToArray(string) {
return hasUnicode(string)
? unicodeToArray(string)
: asciiToArray(string);
}
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
* character of `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the index of the last non-whitespace character.
*/
function trimmedEndIndex(string) {
var index = string.length;
while (index-- && reWhitespace.test(string.charAt(index))) {}
return index;
}
/**
* Used by `_.unescape` to convert HTML entities to characters.
*
* @private
* @param {string} chr The matched character to unescape.
* @returns {string} Returns the unescaped character.
*/
var unescapeHtmlChar = basePropertyOf(htmlUnescapes);
/**
* Gets the size of a Unicode `string`.
*
* @private
* @param {string} string The string inspect.
* @returns {number} Returns the string size.
*/
function unicodeSize(string) {
var result = reUnicode.lastIndex = 0;
while (reUnicode.test(string)) {
++result;
}
return result;
}
/**
* Converts a Unicode `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function unicodeToArray(string) {
return string.match(reUnicode) || [];
}
/**
* Splits a Unicode `string` into an array of its words.
*
* @private
* @param {string} The string to inspect.
* @returns {Array} Returns the words of `string`.
*/
function unicodeWords(string) {
return string.match(reUnicodeWord) || [];
}
/*--------------------------------------------------------------------------*/
/**
* Create a new pristine `lodash` function using the `context` object.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Util
* @param {Object} [context=root] The context object.
* @returns {Function} Returns a new `lodash` function.
* @example
*
* _.mixin({ 'foo': _.constant('foo') });
*
* var lodash = _.runInContext();
* lodash.mixin({ 'bar': lodash.constant('bar') });
*
* _.isFunction(_.foo);
* // => true
* _.isFunction(_.bar);
* // => false
*
* lodash.isFunction(lodash.foo);
* // => false
* lodash.isFunction(lodash.bar);
* // => true
*
* // Create a suped-up `defer` in Node.js.
* var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
*/
var runInContext = (function runInContext(context) {
context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps));
/** Built-in constructor references. */
var Array = context.Array,
Date = context.Date,
Error = context.Error,
Function = context.Function,
Math = context.Math,
Object = context.Object,
RegExp = context.RegExp,
String = context.String,
TypeError = context.TypeError;
/** Used for built-in method references. */
var arrayProto = Array.prototype,
funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to detect overreaching core-js shims. */
var coreJsData = context['__core-js_shared__'];
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to generate unique IDs. */
var idCounter = 0;
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString.call(Object);
/** Used to restore the original `_` reference in `_.noConflict`. */
var oldDash = root._;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/** Built-in value references. */
var Buffer = moduleExports ? context.Buffer : undefined,
Symbol = context.Symbol,
Uint8Array = context.Uint8Array,
allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined,
getPrototype = overArg(Object.getPrototypeOf, Object),
objectCreate = Object.create,
propertyIsEnumerable = objectProto.propertyIsEnumerable,
splice = arrayProto.splice,
spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined,
symIterator = Symbol ? Symbol.iterator : undefined,
symToStringTag = Symbol ? Symbol.toStringTag : undefined;
var defineProperty = (function() {
try {
var func = getNative(Object, 'defineProperty');
func({}, '', {});
return func;
} catch (e) {}
}());
/** Mocked built-ins. */
var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout,
ctxNow = Date && Date.now !== root.Date.now && Date.now,
ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeCeil = Math.ceil,
nativeFloor = Math.floor,
nativeGetSymbols = Object.getOwnPropertySymbols,
nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
nativeIsFinite = context.isFinite,
nativeJoin = arrayProto.join,
nativeKeys = overArg(Object.keys, Object),
nativeMax = Math.max,
nativeMin = Math.min,
nativeNow = Date.now,
nativeParseInt = context.parseInt,
nativeRandom = Math.random,
nativeReverse = arrayProto.reverse;
/* Built-in method references that are verified to be native. */
var DataView = getNative(context, 'DataView'),
Map = getNative(context, 'Map'),
Promise = getNative(context, 'Promise'),
Set = getNative(context, 'Set'),
WeakMap = getNative(context, 'WeakMap'),
nativeCreate = getNative(Object, 'create');
/** Used to store function metadata. */
var metaMap = WeakMap && new WeakMap;
/** Used to lookup unminified function names. */
var realNames = {};
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,
symbolToString = symbolProto ? symbolProto.toString : undefined;
/*------------------------------------------------------------------------*/
/**
* Creates a `lodash` object which wraps `value` to enable implicit method
* chain sequences. Methods that operate on and return arrays, collections,
* and functions can be chained together. Methods that retrieve a single value
* or may return a primitive value will automatically end the chain sequence
* and return the unwrapped value. Otherwise, the value must be unwrapped
* with `_#value`.
*
* Explicit chain sequences, which must be unwrapped with `_#value`, may be
* enabled using `_.chain`.
*
* The execution of chained methods is lazy, that is, it's deferred until
* `_#value` is implicitly or explicitly called.
*
* Lazy evaluation allows several methods to support shortcut fusion.
* Shortcut fusion is an optimization to merge iteratee calls; this avoids
* the creation of intermediate arrays and can greatly reduce the number of
* iteratee executions. Sections of a chain sequence qualify for shortcut
* fusion if the section is applied to an array and iteratees accept only
* one argument. The heuristic for whether a section qualifies for shortcut
* fusion is subject to change.
*
* Chaining is supported in custom builds as long as the `_#value` method is
* directly or indirectly included in the build.
*
* In addition to lodash methods, wrappers have `Array` and `String` methods.
*
* The wrapper `Array` methods are:
* `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
*
* The wrapper `String` methods are:
* `replace` and `split`
*
* The wrapper methods that support shortcut fusion are:
* `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
* `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
* `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
*
* The chainable wrapper methods are:
* `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
* `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
* `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
* `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
* `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
* `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
* `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
* `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
* `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
* `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
* `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
* `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
* `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
* `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
* `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
* `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
* `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
* `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
* `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
* `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
* `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
* `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
* `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
* `zipObject`, `zipObjectDeep`, and `zipWith`
*
* The wrapper methods that are **not** chainable by default are:
* `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
* `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
* `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
* `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
* `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
* `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
* `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
* `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
* `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
* `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
* `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
* `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
* `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
* `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
* `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
* `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
* `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
* `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
* `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
* `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
* `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
* `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
* `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
* `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
* `upperFirst`, `value`, and `words`
*
* @name _
* @constructor
* @category Seq
* @param {*} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var wrapped = _([1, 2, 3]);
*
* // Returns an unwrapped value.
* wrapped.reduce(_.add);
* // => 6
*
* // Returns a wrapped value.
* var squares = wrapped.map(square);
*
* _.isArray(squares);
* // => false
*
* _.isArray(squares.value());
* // => true
*/
function lodash(value) {
if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
if (value instanceof LodashWrapper) {
return value;
}
if (hasOwnProperty.call(value, '__wrapped__')) {
return wrapperClone(value);
}
}
return new LodashWrapper(value);
}
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} proto The object to inherit from.
* @returns {Object} Returns the new object.
*/
var baseCreate = (function() {
function object() {}
return function(proto) {
if (!isObject(proto)) {
return {};
}
if (objectCreate) {
return objectCreate(proto);
}
object.prototype = proto;
var result = new object;
object.prototype = undefined;
return result;
};
}());
/**
* The function whose prototype chain sequence wrappers inherit from.
*
* @private
*/
function baseLodash() {
// No operation performed.
}
/**
* The base constructor for creating `lodash` wrapper objects.
*
* @private
* @param {*} value The value to wrap.
* @param {boolean} [chainAll] Enable explicit method chain sequences.
*/
function LodashWrapper(value, chainAll) {
this.__wrapped__ = value;
this.__actions__ = [];
this.__chain__ = !!chainAll;
this.__index__ = 0;
this.__values__ = undefined;
}
/**
* By default, the template delimiters used by lodash are like those in
* embedded Ruby (ERB) as well as ES2015 template strings. Change the
* following template settings to use alternative delimiters.
*
* @static
* @memberOf _
* @type {Object}
*/
lodash.templateSettings = {
/**
* Used to detect `data` property values to be HTML-escaped.
*
* @memberOf _.templateSettings
* @type {RegExp}
*/
'escape': reEscape,
/**
* Used to detect code to be evaluated.
*
* @memberOf _.templateSettings
* @type {RegExp}
*/
'evaluate': reEvaluate,
/**
* Used to detect `data` property values to inject.
*
* @memberOf _.templateSettings
* @type {RegExp}
*/
'interpolate': reInterpolate,
/**
* Used to reference the data object in the template text.
*
* @memberOf _.templateSettings
* @type {string}
*/
'variable': '',
/**
* Used to import variables into the compiled template.
*
* @memberOf _.templateSettings
* @type {Object}
*/
'imports': {
/**
* A reference to the `lodash` function.
*
* @memberOf _.templateSettings.imports
* @type {Function}
*/
'_': lodash
}
};
// Ensure wrappers are instances of `baseLodash`.
lodash.prototype = baseLodash.prototype;
lodash.prototype.constructor = lodash;
LodashWrapper.prototype = baseCreate(baseLodash.prototype);
LodashWrapper.prototype.constructor = LodashWrapper;
/*------------------------------------------------------------------------*/
/**
* Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
*
* @private
* @constructor
* @param {*} value The value to wrap.
*/
function LazyWrapper(value) {
this.__wrapped__ = value;
this.__actions__ = [];
this.__dir__ = 1;
this.__filtered__ = false;
this.__iteratees__ = [];
this.__takeCount__ = MAX_ARRAY_LENGTH;
this.__views__ = [];
}
/**
* Creates a clone of the lazy wrapper object.
*
* @private
* @name clone
* @memberOf LazyWrapper
* @returns {Object} Returns the cloned `LazyWrapper` object.
*/
function lazyClone() {
var result = new LazyWrapper(this.__wrapped__);
result.__actions__ = copyArray(this.__actions__);
result.__dir__ = this.__dir__;
result.__filtered__ = this.__filtered__;
result.__iteratees__ = copyArray(this.__iteratees__);
result.__takeCount__ = this.__takeCount__;
result.__views__ = copyArray(this.__views__);
return result;
}
/**
* Reverses the direction of lazy iteration.
*
* @private
* @name reverse
* @memberOf LazyWrapper
* @returns {Object} Returns the new reversed `LazyWrapper` object.
*/
function lazyReverse() {
if (this.__filtered__) {
var result = new LazyWrapper(this);
result.__dir__ = -1;
result.__filtered__ = true;
} else {
result = this.clone();
result.__dir__ *= -1;
}
return result;
}
/**
* Extracts the unwrapped value from its lazy wrapper.
*
* @private
* @name value
* @memberOf LazyWrapper
* @returns {*} Returns the unwrapped value.
*/
function lazyValue() {
var array = this.__wrapped__.value(),
dir = this.__dir__,
isArr = isArray(array),
isRight = dir < 0,
arrLength = isArr ? array.length : 0,
view = getView(0, arrLength, this.__views__),
start = view.start,
end = view.end,
length = end - start,
index = isRight ? end : (start - 1),
iteratees = this.__iteratees__,
iterLength = iteratees.length,
resIndex = 0,
takeCount = nativeMin(length, this.__takeCount__);
if (!isArr || (!isRight && arrLength == length && takeCount == length)) {
return baseWrapperValue(array, this.__actions__);
}
var result = [];
outer:
while (length-- && resIndex < takeCount) {
index += dir;
var iterIndex = -1,
value = array[index];
while (++iterIndex < iterLength) {
var data = iteratees[iterIndex],
iteratee = data.iteratee,
type = data.type,
computed = iteratee(value);
if (type == LAZY_MAP_FLAG) {
value = computed;
} else if (!computed) {
if (type == LAZY_FILTER_FLAG) {
continue outer;
} else {
break outer;
}
}
}
result[resIndex++] = value;
}
return result;
}
// Ensure `LazyWrapper` is an instance of `baseLodash`.
LazyWrapper.prototype = baseCreate(baseLodash.prototype);
LazyWrapper.prototype.constructor = LazyWrapper;
/*------------------------------------------------------------------------*/
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
this.size = 0;
}
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(data, key) ? data[key] : undefined;
}
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
}
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
return this;
}
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
/*------------------------------------------------------------------------*/
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--this.size;
return true;
}
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return assocIndexOf(this.__data__, key) > -1;
}
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
/*------------------------------------------------------------------------*/
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.size = 0;
this.__data__ = {
'hash': new Hash,
'map': new (Map || ListCache),
'string': new Hash
};
}
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete(key) {
var result = getMapData(this, key)['delete'](key);
this.size -= result ? 1 : 0;
return result;
}
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return getMapData(this, key).get(key);
}
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return getMapData(this, key).has(key);
}
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
var data = getMapData(this, key),
size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
/*------------------------------------------------------------------------*/
/**
*
* Creates an array cache object to store unique values.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function SetCache(values) {
var index = -1,
length = values == null ? 0 : values.length;
this.__data__ = new MapCache;
while (++index < length) {
this.add(values[index]);
}
}
/**
* Adds `value` to the array cache.
*
* @private
* @name add
* @memberOf SetCache
* @alias push
* @param {*} value The value to cache.
* @returns {Object} Returns the cache instance.
*/
function setCacheAdd(value) {
this.__data__.set(value, HASH_UNDEFINED);
return this;
}
/**
* Checks if `value` is in the array cache.
*
* @private
* @name has
* @memberOf SetCache
* @param {*} value The value to search for.
* @returns {number} Returns `true` if `value` is found, else `false`.
*/
function setCacheHas(value) {
return this.__data__.has(value);
}
// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;
/*------------------------------------------------------------------------*/
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
var data = this.__data__ = new ListCache(entries);
this.size = data.size;
}
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new ListCache;
this.size = 0;
}
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
result = data['delete'](key);
this.size = data.size;
return result;
}
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof ListCache) {
var pairs = data.__data__;
if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new MapCache(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
/*------------------------------------------------------------------------*/
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = isArray(value),
isArg = !isArr && isArguments(value),
isBuff = !isArr && !isArg && isBuffer(value),
isType = !isArr && !isArg && !isBuff && isTypedArray(value),
skipIndexes = isArr || isArg || isBuff || isType,
result = skipIndexes ? baseTimes(value.length, String) : [],
length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
/**
* A specialized version of `_.sample` for arrays.
*
* @private
* @param {Array} array The array to sample.
* @returns {*} Returns the random element.
*/
function arraySample(array) {
var length = array.length;
return length ? array[baseRandom(0, length - 1)] : undefined;
}
/**
* A specialized version of `_.sampleSize` for arrays.
*
* @private
* @param {Array} array The array to sample.
* @param {number} n The number of elements to sample.
* @returns {Array} Returns the random elements.
*/
function arraySampleSize(array, n) {
return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length));
}
/**
* A specialized version of `_.shuffle` for arrays.
*
* @private
* @param {Array} array The array to shuffle.
* @returns {Array} Returns the new shuffled array.
*/
function arrayShuffle(array) {
return shuffleSelf(copyArray(array));
}
/**
* This function is like `assignValue` except that it doesn't assign
* `undefined` values.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignMergeValue(object, key, value) {
if ((value !== undefined && !eq(object[key], value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
/**
* Aggregates elements of `collection` on `accumulator` with keys transformed
* by `iteratee` and values set by `setter`.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform keys.
* @param {Object} accumulator The initial aggregated object.
* @returns {Function} Returns `accumulator`.
*/
function baseAggregator(collection, setter, iteratee, accumulator) {
baseEach(collection, function(value, key, collection) {
setter(accumulator, value, iteratee(value), collection);
});
return accumulator;
}
/**
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return object && copyObject(source, keys(source), object);
}
/**
* The base implementation of `_.assignIn` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssignIn(object, source) {
return object && copyObject(source, keysIn(source), object);
}
/**
* The base implementation of `assignValue` and `assignMergeValue` without
* value checks.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function baseAssignValue(object, key, value) {
if (key == '__proto__' && defineProperty) {
defineProperty(object, key, {
'configurable': true,
'enumerable': true,
'value': value,
'writable': true
});
} else {
object[key] = value;
}
}
/**
* The base implementation of `_.at` without support for individual paths.
*
* @private
* @param {Object} object The object to iterate over.
* @param {string[]} paths The property paths to pick.
* @returns {Array} Returns the picked elements.
*/
function baseAt(object, paths) {
var index = -1,
length = paths.length,
result = Array(length),
skip = object == null;
while (++index < length) {
result[index] = skip ? undefined : get(object, paths[index]);
}
return result;
}
/**
* The base implementation of `_.clamp` which doesn't coerce arguments.
*
* @private
* @param {number} number The number to clamp.
* @param {number} [lower] The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the clamped number.
*/
function baseClamp(number, lower, upper) {
if (number === number) {
if (upper !== undefined) {
number = number <= upper ? number : upper;
}
if (lower !== undefined) {
number = number >= lower ? number : lower;
}
}
return number;
}
/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} bitmask The bitmask flags.
* 1 - Deep clone
* 2 - Flatten inherited properties
* 4 - Clone symbols
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, bitmask, customizer, key, object, stack) {
var result,
isDeep = bitmask & CLONE_DEEP_FLAG,
isFlat = bitmask & CLONE_FLAT_FLAG,
isFull = bitmask & CLONE_SYMBOLS_FLAG;
if (customizer) {
result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== undefined) {
return result;
}
if (!isObject(value)) {
return value;
}
var isArr = isArray(value);
if (isArr) {
result = initCloneArray(value);
if (!isDeep) {
return copyArray(value, result);
}
} else {
var tag = getTag(value),
isFunc = tag == funcTag || tag == genTag;
if (isBuffer(value)) {
return cloneBuffer(value, isDeep);
}
if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
result = (isFlat || isFunc) ? {} : initCloneObject(value);
if (!isDeep) {
return isFlat
? copySymbolsIn(value, baseAssignIn(result, value))
: copySymbols(value, baseAssign(result, value));
}
} else {
if (!cloneableTags[tag]) {
return object ? value : {};
}
result = initCloneByTag(value, tag, isDeep);
}
}
// Check for circular references and return its corresponding clone.
stack || (stack = new Stack);
var stacked = stack.get(value);
if (stacked) {
return stacked;
}
stack.set(value, result);
if (isSet(value)) {
value.forEach(function(subValue) {
result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
});
} else if (isMap(value)) {
value.forEach(function(subValue, key) {
result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
}
var keysFunc = isFull
? (isFlat ? getAllKeysIn : getAllKeys)
: (isFlat ? keysIn : keys);
var props = isArr ? undefined : keysFunc(value);
arrayEach(props || value, function(subValue, key) {
if (props) {
key = subValue;
subValue = value[key];
}
// Recursively populate clone (susceptible to call stack limits).
assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
return result;
}
/**
* The base implementation of `_.conforms` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property predicates to conform to.
* @returns {Function} Returns the new spec function.
*/
function baseConforms(source) {
var props = keys(source);
return function(object) {
return baseConformsTo(object, source, props);
};
}
/**
* The base implementation of `_.conformsTo` which accepts `props` to check.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property predicates to conform to.
* @returns {boolean} Returns `true` if `object` conforms, else `false`.
*/
function baseConformsTo(object, source, props) {
var length = props.length;
if (object == null) {
return !length;
}
object = Object(object);
while (length--) {
var key = props[length],
predicate = source[key],
value = object[key];
if ((value === undefined && !(key in object)) || !predicate(value)) {
return false;
}
}
return true;
}
/**
* The base implementation of `_.delay` and `_.defer` which accepts `args`
* to provide to `func`.
*
* @private
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @param {Array} args The arguments to provide to `func`.
* @returns {number|Object} Returns the timer id or timeout object.
*/
function baseDelay(func, wait, args) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return setTimeout(function() { func.apply(undefined, args); }, wait);
}
/**
* The base implementation of methods like `_.difference` without support
* for excluding multiple arrays or iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Array} values The values to exclude.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
*/
function baseDifference(array, values, iteratee, comparator) {
var index = -1,
includes = arrayIncludes,
isCommon = true,
length = array.length,
result = [],
valuesLength = values.length;
if (!length) {
return result;
}
if (iteratee) {
values = arrayMap(values, baseUnary(iteratee));
}
if (comparator) {
includes = arrayIncludesWith;
isCommon = false;
}
else if (values.length >= LARGE_ARRAY_SIZE) {
includes = cacheHas;
isCommon = false;
values = new SetCache(values);
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee == null ? value : iteratee(value);
value = (comparator || value !== 0) ? value : 0;
if (isCommon && computed === computed) {
var valuesIndex = valuesLength;
while (valuesIndex--) {
if (values[valuesIndex] === computed) {
continue outer;
}
}
result.push(value);
}
else if (!includes(values, computed, comparator)) {
result.push(value);
}
}
return result;
}
/**
* The base implementation of `_.forEach` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
*/
var baseEach = createBaseEach(baseForOwn);
/**
* The base implementation of `_.forEachRight` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
*/
var baseEachRight = createBaseEach(baseForOwnRight, true);
/**
* The base implementation of `_.every` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`
*/
function baseEvery(collection, predicate) {
var result = true;
baseEach(collection, function(value, index, collection) {
result = !!predicate(value, index, collection);
return result;
});
return result;
}
/**
* The base implementation of methods like `_.max` and `_.min` which accepts a
* `comparator` to determine the extremum value.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The iteratee invoked per iteration.
* @param {Function} comparator The comparator used to compare values.
* @returns {*} Returns the extremum value.
*/
function baseExtremum(array, iteratee, comparator) {
var index = -1,
length = array.length;
while (++index < length) {
var value = array[index],
current = iteratee(value);
if (current != null && (computed === undefined
? (current === current && !isSymbol(current))
: comparator(current, computed)
)) {
var computed = current,
result = value;
}
}
return result;
}
/**
* The base implementation of `_.fill` without an iteratee call guard.
*
* @private
* @param {Array} array The array to fill.
* @param {*} value The value to fill `array` with.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns `array`.
*/
function baseFill(array, value, start, end) {
var length = array.length;
start = toInteger(start);
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = (end === undefined || end > length) ? length : toInteger(end);
if (end < 0) {
end += length;
}
end = start > end ? 0 : toLength(end);
while (start < end) {
array[start++] = value;
}
return array;
}
/**
* The base implementation of `_.filter` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function baseFilter(collection, predicate) {
var result = [];
baseEach(collection, function(value, index, collection) {
if (predicate(value, index, collection)) {
result.push(value);
}
});
return result;
}
/**
* The base implementation of `_.flatten` with support for restricting flattening.
*
* @private
* @param {Array} array The array to flatten.
* @param {number} depth The maximum recursion depth.
* @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
* @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened array.
*/
function baseFlatten(array, depth, predicate, isStrict, result) {
var index = -1,
length = array.length;
predicate || (predicate = isFlattenable);
result || (result = []);
while (++index < length) {
var value = array[index];
if (depth > 0 && predicate(value)) {
if (depth > 1) {
// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value, depth - 1, predicate, isStrict, result);
} else {
arrayPush(result, value);
}
} else if (!isStrict) {
result[result.length] = value;
}
}
return result;
}
/**
* The base implementation of `baseForOwn` which iterates over `object`
* properties returned by `keysFunc` and invokes `iteratee` for each property.
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = createBaseFor();
/**
* This function is like `baseFor` except that it iterates over properties
* in the opposite order.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseForRight = createBaseFor(true);
/**
* The base implementation of `_.forOwn` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return object && baseFor(object, iteratee, keys);
}
/**
* The base implementation of `_.forOwnRight` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwnRight(object, iteratee) {
return object && baseForRight(object, iteratee, keys);
}
/**
* The base implementation of `_.functions` which creates an array of
* `object` function property names filtered from `props`.
*
* @private
* @param {Object} object The object to inspect.
* @param {Array} props The property names to filter.
* @returns {Array} Returns the function names.
*/
function baseFunctions(object, props) {
return arrayFilter(props, function(key) {
return isFunction(object[key]);
});
}
/**
* The base implementation of `_.get` without support for default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @returns {*} Returns the resolved value.
*/
function baseGet(object, path) {
path = castPath(path, object);
var index = 0,
length = path.length;
while (object != null && index < length) {
object = object[toKey(path[index++])];
}
return (index && index == length) ? object : undefined;
}
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
return (symToStringTag && symToStringTag in Object(value))
? getRawTag(value)
: objectToString(value);
}
/**
* The base implementation of `_.gt` which doesn't coerce arguments.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is greater than `other`,
* else `false`.
*/
function baseGt(value, other) {
return value > other;
}
/**
* The base implementation of `_.has` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHas(object, key) {
return object != null && hasOwnProperty.call(object, key);
}
/**
* The base implementation of `_.hasIn` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHasIn(object, key) {
return object != null && key in Object(object);
}
/**
* The base implementation of `_.inRange` which doesn't coerce arguments.
*
* @private
* @param {number} number The number to check.
* @param {number} start The start of the range.
* @param {number} end The end of the range.
* @returns {boolean} Returns `true` if `number` is in the range, else `false`.
*/
function baseInRange(number, start, end) {
return number >= nativeMin(start, end) && number < nativeMax(start, end);
}
/**
* The base implementation of methods like `_.intersection`, without support
* for iteratee shorthands, that accepts an array of arrays to inspect.
*
* @private
* @param {Array} arrays The arrays to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of shared values.
*/
function baseIntersection(arrays, iteratee, comparator) {
var includes = comparator ? arrayIncludesWith : arrayIncludes,
length = arrays[0].length,
othLength = arrays.length,
othIndex = othLength,
caches = Array(othLength),
maxLength = Infinity,
result = [];
while (othIndex--) {
var array = arrays[othIndex];
if (othIndex && iteratee) {
array = arrayMap(array, baseUnary(iteratee));
}
maxLength = nativeMin(array.length, maxLength);
caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))
? new SetCache(othIndex && array)
: undefined;
}
array = arrays[0];
var index = -1,
seen = caches[0];
outer:
while (++index < length && result.length < maxLength) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
value = (comparator || value !== 0) ? value : 0;
if (!(seen
? cacheHas(seen, computed)
: includes(result, computed, comparator)
)) {
othIndex = othLength;
while (--othIndex) {
var cache = caches[othIndex];
if (!(cache
? cacheHas(cache, computed)
: includes(arrays[othIndex], computed, comparator))
) {
continue outer;
}
}
if (seen) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
/**
* The base implementation of `_.invert` and `_.invertBy` which inverts
* `object` with values transformed by `iteratee` and set by `setter`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform values.
* @param {Object} accumulator The initial inverted object.
* @returns {Function} Returns `accumulator`.
*/
function baseInverter(object, setter, iteratee, accumulator) {
baseForOwn(object, function(value, key, object) {
setter(accumulator, iteratee(value), key, object);
});
return accumulator;
}
/**
* The base implementation of `_.invoke` without support for individual
* method arguments.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the method to invoke.
* @param {Array} args The arguments to invoke the method with.
* @returns {*} Returns the result of the invoked method.
*/
function baseInvoke(object, path, args) {
path = castPath(path, object);
object = parent(object, path);
var func = object == null ? object : object[toKey(last(path))];
return func == null ? undefined : apply(func, object, args);
}
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/
function baseIsArguments(value) {
return isObjectLike(value) && baseGetTag(value) == argsTag;
}
/**
* The base implementation of `_.isArrayBuffer` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
*/
function baseIsArrayBuffer(value) {
return isObjectLike(value) && baseGetTag(value) == arrayBufferTag;
}
/**
* The base implementation of `_.isDate` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a date object, else `false`.
*/
function baseIsDate(value) {
return isObjectLike(value) && baseGetTag(value) == dateTag;
}
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {boolean} bitmask The bitmask flags.
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Function} [customizer] The function to customize comparisons.
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = objIsArr ? arrayTag : getTag(object),
othTag = othIsArr ? arrayTag : getTag(other);
objTag = objTag == argsTag ? objectTag : objTag;
othTag = othTag == argsTag ? objectTag : othTag;
var objIsObj = objTag == objectTag,
othIsObj = othTag == objectTag,
isSameTag = objTag == othTag;
if (isSameTag && isBuffer(object)) {
if (!isBuffer(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new Stack);
return (objIsArr || isTypedArray(object))
? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
: equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack);
return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack);
return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
/**
* The base implementation of `_.isMap` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
*/
function baseIsMap(value) {
return isObjectLike(value) && getTag(value) == mapTag;
}
/**
* The base implementation of `_.isMatch` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Array} matchData The property names, values, and compare flags to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
function baseIsMatch(object, source, matchData, customizer) {
var index = matchData.length,
length = index,
noCustomizer = !customizer;
if (object == null) {
return !length;
}
object = Object(object);
while (index--) {
var data = matchData[index];
if ((noCustomizer && data[2])
? data[1] !== object[data[0]]
: !(data[0] in object)
) {
return false;
}
}
while (++index < length) {
data = matchData[index];
var key = data[0],
objValue = object[key],
srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === undefined && !(key in object)) {
return false;
}
} else {
var stack = new Stack;
if (customizer) {
var result = customizer(objValue, srcValue, key, object, source, stack);
}
if (!(result === undefined
? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)
: result
)) {
return false;
}
}
}
return true;
}
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
/**
* The base implementation of `_.isRegExp` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
*/
function baseIsRegExp(value) {
return isObjectLike(value) && baseGetTag(value) == regexpTag;
}
/**
* The base implementation of `_.isSet` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
*/
function baseIsSet(value) {
return isObjectLike(value) && getTag(value) == setTag;
}
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}
/**
* The base implementation of `_.iteratee`.
*
* @private
* @param {*} [value=_.identity] The value to convert to an iteratee.
* @returns {Function} Returns the iteratee.
*/
function baseIteratee(value) {
// Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
// See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
if (typeof value == 'function') {
return value;
}
if (value == null) {
return identity;
}
if (typeof value == 'object') {
return isArray(value)
? baseMatchesProperty(value[0], value[1])
: baseMatches(value);
}
return property(value);
}
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
/**
* The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeysIn(object) {
if (!isObject(object)) {
return nativeKeysIn(object);
}
var isProto = isPrototype(object),
result = [];
for (var key in object) {
if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
return result;
}
/**
* The base implementation of `_.lt` which doesn't coerce arguments.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is less than `other`,
* else `false`.
*/
function baseLt(value, other) {
return value < other;
}
/**
* The base implementation of `_.map` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function baseMap(collection, iteratee) {
var index = -1,
result = isArrayLike(collection) ? Array(collection.length) : [];
baseEach(collection, function(value, key, collection) {
result[++index] = iteratee(value, key, collection);
});
return result;
}
/**
* The base implementation of `_.matches` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatches(source) {
var matchData = getMatchData(source);
if (matchData.length == 1 && matchData[0][2]) {
return matchesStrictComparable(matchData[0][0], matchData[0][1]);
}
return function(object) {
return object === source || baseIsMatch(object, source, matchData);
};
}
/**
* The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatchesProperty(path, srcValue) {
if (isKey(path) && isStrictComparable(srcValue)) {
return matchesStrictComparable(toKey(path), srcValue);
}
return function(object) {
var objValue = get(object, path);
return (objValue === undefined && objValue === srcValue)
? hasIn(object, path)
: baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
};
}
/**
* The base implementation of `_.merge` without support for multiple sources.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {number} srcIndex The index of `source`.
* @param {Function} [customizer] The function to customize merged values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMerge(object, source, srcIndex, customizer, stack) {
if (object === source) {
return;
}
baseFor(source, function(srcValue, key) {
stack || (stack = new Stack);
if (isObject(srcValue)) {
baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
}
else {
var newValue = customizer
? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)
: undefined;
if (newValue === undefined) {
newValue = srcValue;
}
assignMergeValue(object, key, newValue);
}
}, keysIn);
}
/**
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {number} srcIndex The index of `source`.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize assigned values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
var objValue = safeGet(object, key),
srcValue = safeGet(source, key),
stacked = stack.get(srcValue);
if (stacked) {
assignMergeValue(object, key, stacked);
return;
}
var newValue = customizer
? customizer(objValue, srcValue, (key + ''), object, source, stack)
: undefined;
var isCommon = newValue === undefined;
if (isCommon) {
var isArr = isArray(srcValue),
isBuff = !isArr && isBuffer(srcValue),
isTyped = !isArr && !isBuff && isTypedArray(srcValue);
newValue = srcValue;
if (isArr || isBuff || isTyped) {
if (isArray(objValue)) {
newValue = objValue;
}
else if (isArrayLikeObject(objValue)) {
newValue = copyArray(objValue);
}
else if (isBuff) {
isCommon = false;
newValue = cloneBuffer(srcValue, true);
}
else if (isTyped) {
isCommon = false;
newValue = cloneTypedArray(srcValue, true);
}
else {
newValue = [];
}
}
else if (isPlainObject(srcValue) || isArguments(srcValue)) {
newValue = objValue;
if (isArguments(objValue)) {
newValue = toPlainObject(objValue);
}
else if (!isObject(objValue) || isFunction(objValue)) {
newValue = initCloneObject(srcValue);
}
}
else {
isCommon = false;
}
}
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, newValue);
mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
stack['delete'](srcValue);
}
assignMergeValue(object, key, newValue);
}
/**
* The base implementation of `_.nth` which doesn't coerce arguments.
*
* @private
* @param {Array} array The array to query.
* @param {number} n The index of the element to return.
* @returns {*} Returns the nth element of `array`.
*/
function baseNth(array, n) {
var length = array.length;
if (!length) {
return;
}
n += n < 0 ? length : 0;
return isIndex(n, length) ? array[n] : undefined;
}
/**
* The base implementation of `_.orderBy` without param guards.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
* @param {string[]} orders The sort orders of `iteratees`.
* @returns {Array} Returns the new sorted array.
*/
function baseOrderBy(collection, iteratees, orders) {
if (iteratees.length) {
iteratees = arrayMap(iteratees, function(iteratee) {
if (isArray(iteratee)) {
return function(value) {
return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);
}
}
return iteratee;
});
} else {
iteratees = [identity];
}
var index = -1;
iteratees = arrayMap(iteratees, baseUnary(getIteratee()));
var result = baseMap(collection, function(value, key, collection) {
var criteria = arrayMap(iteratees, function(iteratee) {
return iteratee(value);
});
return { 'criteria': criteria, 'index': ++index, 'value': value };
});
return baseSortBy(result, function(object, other) {
return compareMultiple(object, other, orders);
});
}
/**
* The base implementation of `_.pick` without support for individual
* property identifiers.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @returns {Object} Returns the new object.
*/
function basePick(object, paths) {
return basePickBy(object, paths, function(value, path) {
return hasIn(object, path);
});
}
/**
* The base implementation of `_.pickBy` without support for iteratee shorthands.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @param {Function} predicate The function invoked per property.
* @returns {Object} Returns the new object.
*/
function basePickBy(object, paths, predicate) {
var index = -1,
length = paths.length,
result = {};
while (++index < length) {
var path = paths[index],
value = baseGet(object, path);
if (predicate(value, path)) {
baseSet(result, castPath(path, object), value);
}
}
return result;
}
/**
* A specialized version of `baseProperty` which supports deep paths.
*
* @private
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyDeep(path) {
return function(object) {
return baseGet(object, path);
};
}
/**
* The base implementation of `_.pullAllBy` without support for iteratee
* shorthands.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns `array`.
*/
function basePullAll(array, values, iteratee, comparator) {
var indexOf = comparator ? baseIndexOfWith : baseIndexOf,
index = -1,
length = values.length,
seen = array;
if (array === values) {
values = copyArray(values);
}
if (iteratee) {
seen = arrayMap(array, baseUnary(iteratee));
}
while (++index < length) {
var fromIndex = 0,
value = values[index],
computed = iteratee ? iteratee(value) : value;
while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {
if (seen !== array) {
splice.call(seen, fromIndex, 1);
}
splice.call(array, fromIndex, 1);
}
}
return array;
}
/**
* The base implementation of `_.pullAt` without support for individual
* indexes or capturing the removed elements.
*
* @private
* @param {Array} array The array to modify.
* @param {number[]} indexes The indexes of elements to remove.
* @returns {Array} Returns `array`.
*/
function basePullAt(array, indexes) {
var length = array ? indexes.length : 0,
lastIndex = length - 1;
while (length--) {
var index = indexes[length];
if (length == lastIndex || index !== previous) {
var previous = index;
if (isIndex(index)) {
splice.call(array, index, 1);
} else {
baseUnset(array, index);
}
}
}
return array;
}
/**
* The base implementation of `_.random` without support for returning
* floating-point numbers.
*
* @private
* @param {number} lower The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the random number.
*/
function baseRandom(lower, upper) {
return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
}
/**
* The base implementation of `_.range` and `_.rangeRight` which doesn't
* coerce arguments.
*
* @private
* @param {number} start The start of the range.
* @param {number} end The end of the range.
* @param {number} step The value to increment or decrement by.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Array} Returns the range of numbers.
*/
function baseRange(start, end, step, fromRight) {
var index = -1,
length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
result = Array(length);
while (length--) {
result[fromRight ? length : ++index] = start;
start += step;
}
return result;
}
/**
* The base implementation of `_.repeat` which doesn't coerce arguments.
*
* @private
* @param {string} string The string to repeat.
* @param {number} n The number of times to repeat the string.
* @returns {string} Returns the repeated string.
*/
function baseRepeat(string, n) {
var result = '';
if (!string || n < 1 || n > MAX_SAFE_INTEGER) {
return result;
}
// Leverage the exponentiation by squaring algorithm for a faster repeat.
// See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
do {
if (n % 2) {
result += string;
}
n = nativeFloor(n / 2);
if (n) {
string += string;
}
} while (n);
return result;
}
/**
* The base implementation of `_.rest` which doesn't validate or coerce arguments.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
*/
function baseRest(func, start) {
return setToString(overRest(func, start, identity), func + '');
}
/**
* The base implementation of `_.sample`.
*
* @private
* @param {Array|Object} collection The collection to sample.
* @returns {*} Returns the random element.
*/
function baseSample(collection) {
return arraySample(values(collection));
}
/**
* The base implementation of `_.sampleSize` without param guards.
*
* @private
* @param {Array|Object} collection The collection to sample.
* @param {number} n The number of elements to sample.
* @returns {Array} Returns the random elements.
*/
function baseSampleSize(collection, n) {
var array = values(collection);
return shuffleSelf(array, baseClamp(n, 0, array.length));
}
/**
* The base implementation of `_.set`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @param {Function} [customizer] The function to customize path creation.
* @returns {Object} Returns `object`.
*/
function baseSet(object, path, value, customizer) {
if (!isObject(object)) {
return object;
}
path = castPath(path, object);
var index = -1,
length = path.length,
lastIndex = length - 1,
nested = object;
while (nested != null && ++index < length) {
var key = toKey(path[index]),
newValue = value;
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
return object;
}
if (index != lastIndex) {
var objValue = nested[key];
newValue = customizer ? customizer(objValue, key, nested) : undefined;
if (newValue === undefined) {
newValue = isObject(objValue)
? objValue
: (isIndex(path[index + 1]) ? [] : {});
}
}
assignValue(nested, key, newValue);
nested = nested[key];
}
return object;
}
/**
* The base implementation of `setData` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var baseSetData = !metaMap ? identity : function(func, data) {
metaMap.set(func, data);
return func;
};
/**
* The base implementation of `setToString` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var baseSetToString = !defineProperty ? identity : function(func, string) {
return defineProperty(func, 'toString', {
'configurable': true,
'enumerable': false,
'value': constant(string),
'writable': true
});
};
/**
* The base implementation of `_.shuffle`.
*
* @private
* @param {Array|Object} collection The collection to shuffle.
* @returns {Array} Returns the new shuffled array.
*/
function baseShuffle(collection) {
return shuffleSelf(values(collection));
}
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = end > length ? length : end;
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
/**
* The base implementation of `_.some` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function baseSome(collection, predicate) {
var result;
baseEach(collection, function(value, index, collection) {
result = predicate(value, index, collection);
return !result;
});
return !!result;
}
/**
* The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which
* performs a binary search of `array` to determine the index at which `value`
* should be inserted into `array` in order to maintain its sort order.
*
* @private
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {boolean} [retHighest] Specify returning the highest qualified index.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
*/
function baseSortedIndex(array, value, retHighest) {
var low = 0,
high = array == null ? low : array.length;
if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
while (low < high) {
var mid = (low + high) >>> 1,
computed = array[mid];
if (computed !== null && !isSymbol(computed) &&
(retHighest ? (computed <= value) : (computed < value))) {
low = mid + 1;
} else {
high = mid;
}
}
return high;
}
return baseSortedIndexBy(array, value, identity, retHighest);
}
/**
* The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`
* which invokes `iteratee` for `value` and each element of `array` to compute
* their sort ranking. The iteratee is invoked with one argument; (value).
*
* @private
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function} iteratee The iteratee invoked per element.
* @param {boolean} [retHighest] Specify returning the highest qualified index.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
*/
function baseSortedIndexBy(array, value, iteratee, retHighest) {
var low = 0,
high = array == null ? 0 : array.length;
if (high === 0) {
return 0;
}
value = iteratee(value);
var valIsNaN = value !== value,
valIsNull = value === null,
valIsSymbol = isSymbol(value),
valIsUndefined = value === undefined;
while (low < high) {
var mid = nativeFloor((low + high) / 2),
computed = iteratee(array[mid]),
othIsDefined = computed !== undefined,
othIsNull = computed === null,
othIsReflexive = computed === computed,
othIsSymbol = isSymbol(computed);
if (valIsNaN) {
var setLow = retHighest || othIsReflexive;
} else if (valIsUndefined) {
setLow = othIsReflexive && (retHighest || othIsDefined);
} else if (valIsNull) {
setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);
} else if (valIsSymbol) {
setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);
} else if (othIsNull || othIsSymbol) {
setLow = false;
} else {
setLow = retHighest ? (computed <= value) : (computed < value);
}
if (setLow) {
low = mid + 1;
} else {
high = mid;
}
}
return nativeMin(high, MAX_ARRAY_INDEX);
}
/**
* The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @returns {Array} Returns the new duplicate free array.
*/
function baseSortedUniq(array, iteratee) {
var index = -1,
length = array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
if (!index || !eq(computed, seen)) {
var seen = computed;
result[resIndex++] = value === 0 ? 0 : value;
}
}
return result;
}
/**
* The base implementation of `_.toNumber` which doesn't ensure correct
* conversions of binary, hexadecimal, or octal string values.
*
* @private
* @param {*} value The value to process.
* @returns {number} Returns the number.
*/
function baseToNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
return +value;
}
/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (isArray(value)) {
// Recursively convert values (susceptible to call stack limits).
return arrayMap(value, baseToString) + '';
}
if (isSymbol(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
/**
* The base implementation of `_.uniqBy` without support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new duplicate free array.
*/
function baseUniq(array, iteratee, comparator) {
var index = -1,
includes = arrayIncludes,
length = array.length,
isCommon = true,
result = [],
seen = result;
if (comparator) {
isCommon = false;
includes = arrayIncludesWith;
}
else if (length >= LARGE_ARRAY_SIZE) {
var set = iteratee ? null : createSet(array);
if (set) {
return setToArray(set);
}
isCommon = false;
includes = cacheHas;
seen = new SetCache;
}
else {
seen = iteratee ? [] : result;
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
value = (comparator || value !== 0) ? value : 0;
if (isCommon && computed === computed) {
var seenIndex = seen.length;
while (seenIndex--) {
if (seen[seenIndex] === computed) {
continue outer;
}
}
if (iteratee) {
seen.push(computed);
}
result.push(value);
}
else if (!includes(seen, computed, comparator)) {
if (seen !== result) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
/**
* The base implementation of `_.unset`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The property path to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
*/
function baseUnset(object, path) {
path = castPath(path, object);
object = parent(object, path);
return object == null || delete object[toKey(last(path))];
}
/**
* The base implementation of `_.update`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to update.
* @param {Function} updater The function to produce the updated value.
* @param {Function} [customizer] The function to customize path creation.
* @returns {Object} Returns `object`.
*/
function baseUpdate(object, path, updater, customizer) {
return baseSet(object, path, updater(baseGet(object, path)), customizer);
}
/**
* The base implementation of methods like `_.dropWhile` and `_.takeWhile`
* without support for iteratee shorthands.
*
* @private
* @param {Array} array The array to query.
* @param {Function} predicate The function invoked per iteration.
* @param {boolean} [isDrop] Specify dropping elements instead of taking them.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Array} Returns the slice of `array`.
*/
function baseWhile(array, predicate, isDrop, fromRight) {
var length = array.length,
index = fromRight ? length : -1;
while ((fromRight ? index-- : ++index < length) &&
predicate(array[index], index, array)) {}
return isDrop
? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))
: baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));
}
/**
* The base implementation of `wrapperValue` which returns the result of
* performing a sequence of actions on the unwrapped `value`, where each
* successive action is supplied the return value of the previous.
*
* @private
* @param {*} value The unwrapped value.
* @param {Array} actions Actions to perform to resolve the unwrapped value.
* @returns {*} Returns the resolved value.
*/
function baseWrapperValue(value, actions) {
var result = value;
if (result instanceof LazyWrapper) {
result = result.value();
}
return arrayReduce(actions, function(result, action) {
return action.func.apply(action.thisArg, arrayPush([result], action.args));
}, result);
}
/**
* The base implementation of methods like `_.xor`, without support for
* iteratee shorthands, that accepts an array of arrays to inspect.
*
* @private
* @param {Array} arrays The arrays to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of values.
*/
function baseXor(arrays, iteratee, comparator) {
var length = arrays.length;
if (length < 2) {
return length ? baseUniq(arrays[0]) : [];
}
var index = -1,
result = Array(length);
while (++index < length) {
var array = arrays[index],
othIndex = -1;
while (++othIndex < length) {
if (othIndex != index) {
result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator);
}
}
}
return baseUniq(baseFlatten(result, 1), iteratee, comparator);
}
/**
* This base implementation of `_.zipObject` which assigns values using `assignFunc`.
*
* @private
* @param {Array} props The property identifiers.
* @param {Array} values The property values.
* @param {Function} assignFunc The function to assign values.
* @returns {Object} Returns the new object.
*/
function baseZipObject(props, values, assignFunc) {
var index = -1,
length = props.length,
valsLength = values.length,
result = {};
while (++index < length) {
var value = index < valsLength ? values[index] : undefined;
assignFunc(result, props[index], value);
}
return result;
}
/**
* Casts `value` to an empty array if it's not an array like object.
*
* @private
* @param {*} value The value to inspect.
* @returns {Array|Object} Returns the cast array-like object.
*/
function castArrayLikeObject(value) {
return isArrayLikeObject(value) ? value : [];
}
/**
* Casts `value` to `identity` if it's not a function.
*
* @private
* @param {*} value The value to inspect.
* @returns {Function} Returns cast function.
*/
function castFunction(value) {
return typeof value == 'function' ? value : identity;
}
/**
* Casts `value` to a path array if it's not one.
*
* @private
* @param {*} value The value to inspect.
* @param {Object} [object] The object to query keys on.
* @returns {Array} Returns the cast property path array.
*/
function castPath(value, object) {
if (isArray(value)) {
return value;
}
return isKey(value, object) ? [value] : stringToPath(toString(value));
}
/**
* A `baseRest` alias which can be replaced with `identity` by module
* replacement plugins.
*
* @private
* @type {Function}
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
*/
var castRest = baseRest;
/**
* Casts `array` to a slice if it's needed.
*
* @private
* @param {Array} array The array to inspect.
* @param {number} start The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the cast slice.
*/
function castSlice(array, start, end) {
var length = array.length;
end = end === undefined ? length : end;
return (!start && end >= length) ? array : baseSlice(array, start, end);
}
/**
* A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout).
*
* @private
* @param {number|Object} id The timer id or timeout object of the timer to clear.
*/
var clearTimeout = ctxClearTimeout || function(id) {
return root.clearTimeout(id);
};
/**
* Creates a clone of `buffer`.
*
* @private
* @param {Buffer} buffer The buffer to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Buffer} Returns the cloned buffer.
*/
function cloneBuffer(buffer, isDeep) {
if (isDeep) {
return buffer.slice();
}
var length = buffer.length,
result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
buffer.copy(result);
return result;
}
/**
* Creates a clone of `arrayBuffer`.
*
* @private
* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
new Uint8Array(result).set(new Uint8Array(arrayBuffer));
return result;
}
/**
* Creates a clone of `dataView`.
*
* @private
* @param {Object} dataView The data view to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned data view.
*/
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
/**
* Creates a clone of `regexp`.
*
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
*/
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
result.lastIndex = regexp.lastIndex;
return result;
}
/**
* Creates a clone of the `symbol` object.
*
* @private
* @param {Object} symbol The symbol object to clone.
* @returns {Object} Returns the cloned symbol object.
*/
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
/**
* Creates a clone of `typedArray`.
*
* @private
* @param {Object} typedArray The typed array to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned typed array.
*/
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
/**
* Compares values to sort them in ascending order.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {number} Returns the sort order indicator for `value`.
*/
function compareAscending(value, other) {
if (value !== other) {
var valIsDefined = value !== undefined,
valIsNull = value === null,
valIsReflexive = value === value,
valIsSymbol = isSymbol(value);
var othIsDefined = other !== undefined,
othIsNull = other === null,
othIsReflexive = other === other,
othIsSymbol = isSymbol(other);
if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
(valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
(valIsNull && othIsDefined && othIsReflexive) ||
(!valIsDefined && othIsReflexive) ||
!valIsReflexive) {
return 1;
}
if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
(othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
(othIsNull && valIsDefined && valIsReflexive) ||
(!othIsDefined && valIsReflexive) ||
!othIsReflexive) {
return -1;
}
}
return 0;
}
/**
* Used by `_.orderBy` to compare multiple properties of a value to another
* and stable sort them.
*
* If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
* specify an order of "desc" for descending or "asc" for ascending sort order
* of corresponding values.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {boolean[]|string[]} orders The order to sort by for each property.
* @returns {number} Returns the sort order indicator for `object`.
*/
function compareMultiple(object, other, orders) {
var index = -1,
objCriteria = object.criteria,
othCriteria = other.criteria,
length = objCriteria.length,
ordersLength = orders.length;
while (++index < length) {
var result = compareAscending(objCriteria[index], othCriteria[index]);
if (result) {
if (index >= ordersLength) {
return result;
}
var order = orders[index];
return result * (order == 'desc' ? -1 : 1);
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to provide the same value for
// `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
// for more details.
//
// This also ensures a stable sort in V8 and other engines.
// See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
return object.index - other.index;
}
/**
* Creates an array that is the composition of partially applied arguments,
* placeholders, and provided arguments into a single array of arguments.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to prepend to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgs(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersLength = holders.length,
leftIndex = -1,
leftLength = partials.length,
rangeLength = nativeMax(argsLength - holdersLength, 0),
result = Array(leftLength + rangeLength),
isUncurried = !isCurried;
while (++leftIndex < leftLength) {
result[leftIndex] = partials[leftIndex];
}
while (++argsIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[holders[argsIndex]] = args[argsIndex];
}
}
while (rangeLength--) {
result[leftIndex++] = args[argsIndex++];
}
return result;
}
/**
* This function is like `composeArgs` except that the arguments composition
* is tailored for `_.partialRight`.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to append to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgsRight(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersIndex = -1,
holdersLength = holders.length,
rightIndex = -1,
rightLength = partials.length,
rangeLength = nativeMax(argsLength - holdersLength, 0),
result = Array(rangeLength + rightLength),
isUncurried = !isCurried;
while (++argsIndex < rangeLength) {
result[argsIndex] = args[argsIndex];
}
var offset = argsIndex;
while (++rightIndex < rightLength) {
result[offset + rightIndex] = partials[rightIndex];
}
while (++holdersIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[offset + holders[holdersIndex]] = args[argsIndex++];
}
}
return result;
}
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function copyArray(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/
function copyObject(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
var newValue = customizer
? customizer(object[key], source[key], key, object, source)
: undefined;
if (newValue === undefined) {
newValue = source[key];
}
if (isNew) {
baseAssignValue(object, key, newValue);
} else {
assignValue(object, key, newValue);
}
}
return object;
}
/**
* Copies own symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbols(source, object) {
return copyObject(source, getSymbols(source), object);
}
/**
* Copies own and inherited symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbolsIn(source, object) {
return copyObject(source, getSymbolsIn(source), object);
}
/**
* Creates a function like `_.groupBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} [initializer] The accumulator object initializer.
* @returns {Function} Returns the new aggregator function.
*/
function createAggregator(setter, initializer) {
return function(collection, iteratee) {
var func = isArray(collection) ? arrayAggregator : baseAggregator,
accumulator = initializer ? initializer() : {};
return func(collection, setter, getIteratee(iteratee, 2), accumulator);
};
}
/**
* Creates a function like `_.assign`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return baseRest(function(object, sources) {
var index = -1,
length = sources.length,
customizer = length > 1 ? sources[length - 1] : undefined,
guard = length > 2 ? sources[2] : undefined;
customizer = (assigner.length > 3 && typeof customizer == 'function')
? (length--, customizer)
: undefined;
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
object = Object(object);
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, index, customizer);
}
}
return object;
});
}
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
if (collection == null) {
return collection;
}
if (!isArrayLike(collection)) {
return eachFunc(collection, iteratee);
}
var length = collection.length,
index = fromRight ? length : -1,
iterable = Object(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
/**
* Creates a base function for methods like `_.forIn` and `_.forOwn`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var index = -1,
iterable = Object(object),
props = keysFunc(object),
length = props.length;
while (length--) {
var key = props[fromRight ? length : ++index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
/**
* Creates a function that wraps `func` to invoke it with the optional `this`
* binding of `thisArg`.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createBind(func, bitmask, thisArg) {
var isBind = bitmask & WRAP_BIND_FLAG,
Ctor = createCtor(func);
function wrapper() {
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return fn.apply(isBind ? thisArg : this, arguments);
}
return wrapper;
}
/**
* Creates a function like `_.lowerFirst`.
*
* @private
* @param {string} methodName The name of the `String` case method to use.
* @returns {Function} Returns the new case function.
*/
function createCaseFirst(methodName) {
return function(string) {
string = toString(string);
var strSymbols = hasUnicode(string)
? stringToArray(string)
: undefined;
var chr = strSymbols
? strSymbols[0]
: string.charAt(0);
var trailing = strSymbols
? castSlice(strSymbols, 1).join('')
: string.slice(1);
return chr[methodName]() + trailing;
};
}
/**
* Creates a function like `_.camelCase`.
*
* @private
* @param {Function} callback The function to combine each word.
* @returns {Function} Returns the new compounder function.
*/
function createCompounder(callback) {
return function(string) {
return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
};
}
/**
* Creates a function that produces an instance of `Ctor` regardless of
* whether it was invoked as part of a `new` expression or by `call` or `apply`.
*
* @private
* @param {Function} Ctor The constructor to wrap.
* @returns {Function} Returns the new wrapped function.
*/
function createCtor(Ctor) {
return function() {
// Use a `switch` statement to work with class constructors. See
// http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
// for more details.
var args = arguments;
switch (args.length) {
case 0: return new Ctor;
case 1: return new Ctor(args[0]);
case 2: return new Ctor(args[0], args[1]);
case 3: return new Ctor(args[0], args[1], args[2]);
case 4: return new Ctor(args[0], args[1], args[2], args[3]);
case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
}
var thisBinding = baseCreate(Ctor.prototype),
result = Ctor.apply(thisBinding, args);
// Mimic the constructor's `return` behavior.
// See https://es5.github.io/#x13.2.2 for more details.
return isObject(result) ? result : thisBinding;
};
}
/**
* Creates a function that wraps `func` to enable currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {number} arity The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createCurry(func, bitmask, arity) {
var Ctor = createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length,
placeholder = getHolder(wrapper);
while (index--) {
args[index] = arguments[index];
}
var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
? []
: replaceHolders(args, placeholder);
length -= holders.length;
if (length < arity) {
return createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, undefined,
args, holders, undefined, undefined, arity - length);
}
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return apply(fn, this, args);
}
return wrapper;
}
/**
* Creates a `_.find` or `_.findLast` function.
*
* @private
* @param {Function} findIndexFunc The function to find the collection index.
* @returns {Function} Returns the new find function.
*/
function createFind(findIndexFunc) {
return function(collection, predicate, fromIndex) {
var iterable = Object(collection);
if (!isArrayLike(collection)) {
var iteratee = getIteratee(predicate, 3);
collection = keys(collection);
predicate = function(key) { return iteratee(iterable[key], key, iterable); };
}
var index = findIndexFunc(collection, predicate, fromIndex);
return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
};
}
/**
* Creates a `_.flow` or `_.flowRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new flow function.
*/
function createFlow(fromRight) {
return flatRest(function(funcs) {
var length = funcs.length,
index = length,
prereq = LodashWrapper.prototype.thru;
if (fromRight) {
funcs.reverse();
}
while (index--) {
var func = funcs[index];
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
if (prereq && !wrapper && getFuncName(func) == 'wrapper') {
var wrapper = new LodashWrapper([], true);
}
}
index = wrapper ? index : length;
while (++index < length) {
func = funcs[index];
var funcName = getFuncName(func),
data = funcName == 'wrapper' ? getData(func) : undefined;
if (data && isLaziable(data[0]) &&
data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) &&
!data[4].length && data[9] == 1
) {
wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
} else {
wrapper = (func.length == 1 && isLaziable(func))
? wrapper[funcName]()
: wrapper.thru(func);
}
}
return function() {
var args = arguments,
value = args[0];
if (wrapper && args.length == 1 && isArray(value)) {
return wrapper.plant(value).value();
}
var index = 0,
result = length ? funcs[index].apply(this, args) : value;
while (++index < length) {
result = funcs[index].call(this, result);
}
return result;
};
});
}
/**
* Creates a function that wraps `func` to invoke it with optional `this`
* binding of `thisArg`, partial application, and currying.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [partialsRight] The arguments to append to those provided
* to the new function.
* @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
var isAry = bitmask & WRAP_ARY_FLAG,
isBind = bitmask & WRAP_BIND_FLAG,
isBindKey = bitmask & WRAP_BIND_KEY_FLAG,
isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),
isFlip = bitmask & WRAP_FLIP_FLAG,
Ctor = isBindKey ? undefined : createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length;
while (index--) {
args[index] = arguments[index];
}
if (isCurried) {
var placeholder = getHolder(wrapper),
holdersCount = countHolders(args, placeholder);
}
if (partials) {
args = composeArgs(args, partials, holders, isCurried);
}
if (partialsRight) {
args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
}
length -= holdersCount;
if (isCurried && length < arity) {
var newHolders = replaceHolders(args, placeholder);
return createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, thisArg,
args, newHolders, argPos, ary, arity - length
);
}
var thisBinding = isBind ? thisArg : this,
fn = isBindKey ? thisBinding[func] : func;
length = args.length;
if (argPos) {
args = reorder(args, argPos);
} else if (isFlip && length > 1) {
args.reverse();
}
if (isAry && ary < length) {
args.length = ary;
}
if (this && this !== root && this instanceof wrapper) {
fn = Ctor || createCtor(fn);
}
return fn.apply(thisBinding, args);
}
return wrapper;
}
/**
* Creates a function like `_.invertBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} toIteratee The function to resolve iteratees.
* @returns {Function} Returns the new inverter function.
*/
function createInverter(setter, toIteratee) {
return function(object, iteratee) {
return baseInverter(object, setter, toIteratee(iteratee), {});
};
}
/**
* Creates a function that performs a mathematical operation on two values.
*
* @private
* @param {Function} operator The function to perform the operation.
* @param {number} [defaultValue] The value used for `undefined` arguments.
* @returns {Function} Returns the new mathematical operation function.
*/
function createMathOperation(operator, defaultValue) {
return function(value, other) {
var result;
if (value === undefined && other === undefined) {
return defaultValue;
}
if (value !== undefined) {
result = value;
}
if (other !== undefined) {
if (result === undefined) {
return other;
}
if (typeof value == 'string' || typeof other == 'string') {
value = baseToString(value);
other = baseToString(other);
} else {
value = baseToNumber(value);
other = baseToNumber(other);
}
result = operator(value, other);
}
return result;
};
}
/**
* Creates a function like `_.over`.
*
* @private
* @param {Function} arrayFunc The function to iterate over iteratees.
* @returns {Function} Returns the new over function.
*/
function createOver(arrayFunc) {
return flatRest(function(iteratees) {
iteratees = arrayMap(iteratees, baseUnary(getIteratee()));
return baseRest(function(args) {
var thisArg = this;
return arrayFunc(iteratees, function(iteratee) {
return apply(iteratee, thisArg, args);
});
});
});
}
/**
* Creates the padding for `string` based on `length`. The `chars` string
* is truncated if the number of characters exceeds `length`.
*
* @private
* @param {number} length The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padding for `string`.
*/
function createPadding(length, chars) {
chars = chars === undefined ? ' ' : baseToString(chars);
var charsLength = chars.length;
if (charsLength < 2) {
return charsLength ? baseRepeat(chars, length) : chars;
}
var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));
return hasUnicode(chars)
? castSlice(stringToArray(result), 0, length).join('')
: result.slice(0, length);
}
/**
* Creates a function that wraps `func` to invoke it with the `this` binding
* of `thisArg` and `partials` prepended to the arguments it receives.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} partials The arguments to prepend to those provided to
* the new function.
* @returns {Function} Returns the new wrapped function.
*/
function createPartial(func, bitmask, thisArg, partials) {
var isBind = bitmask & WRAP_BIND_FLAG,
Ctor = createCtor(func);
function wrapper() {
var argsIndex = -1,
argsLength = arguments.length,
leftIndex = -1,
leftLength = partials.length,
args = Array(leftLength + argsLength),
fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
while (++leftIndex < leftLength) {
args[leftIndex] = partials[leftIndex];
}
while (argsLength--) {
args[leftIndex++] = arguments[++argsIndex];
}
return apply(fn, isBind ? thisArg : this, args);
}
return wrapper;
}
/**
* Creates a `_.range` or `_.rangeRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new range function.
*/
function createRange(fromRight) {
return function(start, end, step) {
if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {
end = step = undefined;
}
// Ensure the sign of `-0` is preserved.
start = toFinite(start);
if (end === undefined) {
end = start;
start = 0;
} else {
end = toFinite(end);
}
step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);
return baseRange(start, end, step, fromRight);
};
}
/**
* Creates a function that performs a relational operation on two values.
*
* @private
* @param {Function} operator The function to perform the operation.
* @returns {Function} Returns the new relational operation function.
*/
function createRelationalOperation(operator) {
return function(value, other) {
if (!(typeof value == 'string' && typeof other == 'string')) {
value = toNumber(value);
other = toNumber(other);
}
return operator(value, other);
};
}
/**
* Creates a function that wraps `func` to continue currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {Function} wrapFunc The function to create the `func` wrapper.
* @param {*} placeholder The placeholder value.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
var isCurry = bitmask & WRAP_CURRY_FLAG,
newHolders = isCurry ? holders : undefined,
newHoldersRight = isCurry ? undefined : holders,
newPartials = isCurry ? partials : undefined,
newPartialsRight = isCurry ? undefined : partials;
bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);
bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);
if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {
bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);
}
var newData = [
func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
newHoldersRight, argPos, ary, arity
];
var result = wrapFunc.apply(undefined, newData);
if (isLaziable(func)) {
setData(result, newData);
}
result.placeholder = placeholder;
return setWrapToString(result, func, bitmask);
}
/**
* Creates a function like `_.round`.
*
* @private
* @param {string} methodName The name of the `Math` method to use when rounding.
* @returns {Function} Returns the new round function.
*/
function createRound(methodName) {
var func = Math[methodName];
return function(number, precision) {
number = toNumber(number);
precision = precision == null ? 0 : nativeMin(toInteger(precision), 292);
if (precision && nativeIsFinite(number)) {
// Shift with exponential notation to avoid floating-point issues.
// See [MDN](https://mdn.io/round#Examples) for more details.
var pair = (toString(number) + 'e').split('e'),
value = func(pair[0] + 'e' + (+pair[1] + precision));
pair = (toString(value) + 'e').split('e');
return +(pair[0] + 'e' + (+pair[1] - precision));
}
return func(number);
};
}
/**
* Creates a set object of `values`.
*
* @private
* @param {Array} values The values to add to the set.
* @returns {Object} Returns the new set.
*/
var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {
return new Set(values);
};
/**
* Creates a `_.toPairs` or `_.toPairsIn` function.
*
* @private
* @param {Function} keysFunc The function to get the keys of a given object.
* @returns {Function} Returns the new pairs function.
*/
function createToPairs(keysFunc) {
return function(object) {
var tag = getTag(object);
if (tag == mapTag) {
return mapToArray(object);
}
if (tag == setTag) {
return setToPairs(object);
}
return baseToPairs(object, keysFunc(object));
};
}
/**
* Creates a function that either curries or invokes `func` with optional
* `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags.
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry` or `_.curryRight` of a bound function
* 8 - `_.curry`
* 16 - `_.curryRight`
* 32 - `_.partial`
* 64 - `_.partialRight`
* 128 - `_.rearg`
* 256 - `_.ary`
* 512 - `_.flip`
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to be partially applied.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
if (!isBindKey && typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
var length = partials ? partials.length : 0;
if (!length) {
bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
partials = holders = undefined;
}
ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
arity = arity === undefined ? arity : toInteger(arity);
length -= holders ? holders.length : 0;
if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
var partialsRight = partials,
holdersRight = holders;
partials = holders = undefined;
}
var data = isBindKey ? undefined : getData(func);
var newData = [
func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
argPos, ary, arity
];
if (data) {
mergeData(newData, data);
}
func = newData[0];
bitmask = newData[1];
thisArg = newData[2];
partials = newData[3];
holders = newData[4];
arity = newData[9] = newData[9] === undefined
? (isBindKey ? 0 : func.length)
: nativeMax(newData[9] - length, 0);
if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
}
if (!bitmask || bitmask == WRAP_BIND_FLAG) {
var result = createBind(func, bitmask, thisArg);
} else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
result = createCurry(func, bitmask, arity);
} else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
result = createPartial(func, bitmask, thisArg, partials);
} else {
result = createHybrid.apply(undefined, newData);
}
var setter = data ? baseSetData : setData;
return setWrapToString(setter(result, newData), func, bitmask);
}
/**
* Used by `_.defaults` to customize its `_.assignIn` use to assign properties
* of source objects to the destination object for all destination properties
* that resolve to `undefined`.
*
* @private
* @param {*} objValue The destination value.
* @param {*} srcValue The source value.
* @param {string} key The key of the property to assign.
* @param {Object} object The parent object of `objValue`.
* @returns {*} Returns the value to assign.
*/
function customDefaultsAssignIn(objValue, srcValue, key, object) {
if (objValue === undefined ||
(eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {
return srcValue;
}
return objValue;
}
/**
* Used by `_.defaultsDeep` to customize its `_.merge` use to merge source
* objects into destination objects that are passed thru.
*
* @private
* @param {*} objValue The destination value.
* @param {*} srcValue The source value.
* @param {string} key The key of the property to merge.
* @param {Object} object The parent object of `objValue`.
* @param {Object} source The parent object of `srcValue`.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
* @returns {*} Returns the value to assign.
*/
function customDefaultsMerge(objValue, srcValue, key, object, source, stack) {
if (isObject(objValue) && isObject(srcValue)) {
// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, objValue);
baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack);
stack['delete'](srcValue);
}
return objValue;
}
/**
* Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
* objects.
*
* @private
* @param {*} value The value to inspect.
* @param {string} key The key of the property to inspect.
* @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
*/
function customOmitClone(value) {
return isPlainObject(value) ? undefined : value;
}
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
// Check that cyclic values are equal.
var arrStacked = stack.get(array);
var othStacked = stack.get(other);
if (arrStacked && othStacked) {
return arrStacked == other && othStacked == array;
}
var index = -1,
result = true,
seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
stack.set(array, other);
stack.set(other, array);
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
if (customizer) {
var compared = isPartial
? customizer(othValue, arrValue, index, other, array, stack)
: customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== undefined) {
if (compared) {
continue;
}
result = false;
break;
}
// Recursively compare arrays (susceptible to call stack limits).
if (seen) {
if (!arraySome(other, function(othValue, othIndex) {
if (!cacheHas(seen, othIndex) &&
(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
return seen.push(othIndex);
}
})) {
result = false;
break;
}
} else if (!(
arrValue === othValue ||
equalFunc(arrValue, othValue, bitmask, customizer, stack)
)) {
result = false;
break;
}
}
stack['delete'](array);
stack['delete'](other);
return result;
}
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch (tag) {
case dataViewTag:
if ((object.byteLength != other.byteLength) ||
(object.byteOffset != other.byteOffset)) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag:
if ((object.byteLength != other.byteLength) ||
!equalFunc(new Uint8Array(object), new Uint8Array(other))) {
return false;
}
return true;
case boolTag:
case dateTag:
case numberTag:
// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return eq(+object, +other);
case errorTag:
return object.name == other.name && object.message == other.message;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case mapTag:
var convert = mapToArray;
case setTag:
var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
convert || (convert = setToArray);
if (object.size != other.size && !isPartial) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= COMPARE_UNORDERED_FLAG;
// Recursively compare objects (susceptible to call stack limits).
stack.set(object, other);
var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
stack['delete'](object);
return result;
case symbolTag:
if (symbolValueOf) {
return symbolValueOf.call(object) == symbolValueOf.call(other);
}
}
return false;
}
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
objProps = getAllKeys(object),
objLength = objProps.length,
othProps = getAllKeys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
return false;
}
}
// Check that cyclic values are equal.
var objStacked = stack.get(object);
var othStacked = stack.get(other);
if (objStacked && othStacked) {
return objStacked == other && othStacked == object;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key];
if (customizer) {
var compared = isPartial
? customizer(othValue, objValue, key, other, object, stack)
: customizer(objValue, othValue, key, object, other, stack);
}
// Recursively compare objects (susceptible to call stack limits).
if (!(compared === undefined
? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
: compared
)) {
result = false;
break;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
result = false;
}
}
stack['delete'](object);
stack['delete'](other);
return result;
}
/**
* A specialized version of `baseRest` which flattens the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
*/
function flatRest(func) {
return setToString(overRest(func, undefined, flatten), func + '');
}
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeys(object) {
return baseGetAllKeys(object, keys, getSymbols);
}
/**
* Creates an array of own and inherited enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeysIn(object) {
return baseGetAllKeys(object, keysIn, getSymbolsIn);
}
/**
* Gets metadata for `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {*} Returns the metadata for `func`.
*/
var getData = !metaMap ? noop : function(func) {
return metaMap.get(func);
};
/**
* Gets the name of `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {string} Returns the function name.
*/
function getFuncName(func) {
var result = (func.name + ''),
array = realNames[result],
length = hasOwnProperty.call(realNames, result) ? array.length : 0;
while (length--) {
var data = array[length],
otherFunc = data.func;
if (otherFunc == null || otherFunc == func) {
return data.name;
}
}
return result;
}
/**
* Gets the argument placeholder value for `func`.
*
* @private
* @param {Function} func The function to inspect.
* @returns {*} Returns the placeholder value.
*/
function getHolder(func) {
var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func;
return object.placeholder;
}
/**
* Gets the appropriate "iteratee" function. If `_.iteratee` is customized,
* this function returns the custom method, otherwise it returns `baseIteratee`.
* If arguments are provided, the chosen function is invoked with them and
* its result is returned.
*
* @private
* @param {*} [value] The value to convert to an iteratee.
* @param {number} [arity] The arity of the created iteratee.
* @returns {Function} Returns the chosen function or its result.
*/
function getIteratee() {
var result = lodash.iteratee || iteratee;
result = result === iteratee ? baseIteratee : result;
return arguments.length ? result(arguments[0], arguments[1]) : result;
}
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData(map, key) {
var data = map.__data__;
return isKeyable(key)
? data[typeof key == 'string' ? 'string' : 'hash']
: data.map;
}
/**
* Gets the property names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/
function getMatchData(object) {
var result = keys(object),
length = result.length;
while (length--) {
var key = result[length],
value = object[key];
result[length] = [key, value, isStrictComparable(value)];
}
return result;
}
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = getValue(object, key);
return baseIsNative(value) ? value : undefined;
}
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
/**
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return arrayFilter(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable.call(object, symbol);
});
};
/**
* Creates an array of the own and inherited enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
var result = [];
while (object) {
arrayPush(result, getSymbols(object));
object = getPrototype(object);
}
return result;
};
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
(Map && getTag(new Map) != mapTag) ||
(Promise && getTag(Promise.resolve()) != promiseTag) ||
(Set && getTag(new Set) != setTag) ||
(WeakMap && getTag(new WeakMap) != weakMapTag)) {
getTag = function(value) {
var result = baseGetTag(value),
Ctor = result == objectTag ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : '';
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag;
case mapCtorString: return mapTag;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag;
case weakMapCtorString: return weakMapTag;
}
}
return result;
};
}
/**
* Gets the view, applying any `transforms` to the `start` and `end` positions.
*
* @private
* @param {number} start The start of the view.
* @param {number} end The end of the view.
* @param {Array} transforms The transformations to apply to the view.
* @returns {Object} Returns an object containing the `start` and `end`
* positions of the view.
*/
function getView(start, end, transforms) {
var index = -1,
length = transforms.length;
while (++index < length) {
var data = transforms[index],
size = data.size;
switch (data.type) {
case 'drop': start += size; break;
case 'dropRight': end -= size; break;
case 'take': end = nativeMin(end, start + size); break;
case 'takeRight': start = nativeMax(start, end - size); break;
}
}
return { 'start': start, 'end': end };
}
/**
* Extracts wrapper details from the `source` body comment.
*
* @private
* @param {string} source The source to inspect.
* @returns {Array} Returns the wrapper details.
*/
function getWrapDetails(source) {
var match = source.match(reWrapDetails);
return match ? match[1].split(reSplitDetails) : [];
}
/**
* Checks if `path` exists on `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @param {Function} hasFunc The function to check properties.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
*/
function hasPath(object, path, hasFunc) {
path = castPath(path, object);
var index = -1,
length = path.length,
result = false;
while (++index < length) {
var key = toKey(path[index]);
if (!(result = object != null && hasFunc(object, key))) {
break;
}
object = object[key];
}
if (result || ++index != length) {
return result;
}
length = object == null ? 0 : object.length;
return !!length && isLength(length) && isIndex(key, length) &&
(isArray(object) || isArguments(object));
}
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = new array.constructor(length);
// Add properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneObject(object) {
return (typeof object.constructor == 'function' && !isPrototype(object))
? baseCreate(getPrototype(object))
: {};
}
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneByTag(object, tag, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag:
return cloneArrayBuffer(object);
case boolTag:
case dateTag:
return new Ctor(+object);
case dataViewTag:
return cloneDataView(object, isDeep);
case float32Tag: case float64Tag:
case int8Tag: case int16Tag: case int32Tag:
case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
return cloneTypedArray(object, isDeep);
case mapTag:
return new Ctor;
case numberTag:
case stringTag:
return new Ctor(object);
case regexpTag:
return cloneRegExp(object);
case setTag:
return new Ctor;
case symbolTag:
return cloneSymbol(object);
}
}
/**
* Inserts wrapper `details` in a comment at the top of the `source` body.
*
* @private
* @param {string} source The source to modify.
* @returns {Array} details The details to insert.
* @returns {string} Returns the modified source.
*/
function insertWrapDetails(source, details) {
var length = details.length;
if (!length) {
return source;
}
var lastIndex = length - 1;
details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
details = details.join(length > 2 ? ', ' : ' ');
return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
}
/**
* Checks if `value` is a flattenable `arguments` object or array.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
*/
function isFlattenable(value) {
return isArray(value) || isArguments(value) ||
!!(spreadableSymbol && value && value[spreadableSymbol]);
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
var type = typeof value;
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(type == 'number' ||
(type != 'symbol' && reIsUint.test(value))) &&
(value > -1 && value % 1 == 0 && value < length);
}
/**
* Checks if the given arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call,
* else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)
) {
return eq(object[index], value);
}
return false;
}
/**
* Checks if `value` is a property name and not a property path.
*
* @private
* @param {*} value The value to check.
* @param {Object} [object] The object to query keys on.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*/
function isKey(value, object) {
if (isArray(value)) {
return false;
}
var type = typeof value;
if (type == 'number' || type == 'symbol' || type == 'boolean' ||
value == null || isSymbol(value)) {
return true;
}
return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
(object != null && value in Object(object));
}
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
/**
* Checks if `func` has a lazy counterpart.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` has a lazy counterpart,
* else `false`.
*/
function isLaziable(func) {
var funcName = getFuncName(func),
other = lodash[funcName];
if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {
return false;
}
if (func === other) {
return true;
}
var data = getData(other);
return !!data && func === data[0];
}
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked(func) {
return !!maskSrcKey && (maskSrcKey in func);
}
/**
* Checks if `func` is capable of being masked.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `func` is maskable, else `false`.
*/
var isMaskable = coreJsData ? isFunction : stubFalse;
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && !isObject(value);
}
/**
* A specialized version of `matchesProperty` for source values suitable
* for strict equality comparisons, i.e. `===`.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function matchesStrictComparable(key, srcValue) {
return function(object) {
if (object == null) {
return false;
}
return object[key] === srcValue &&
(srcValue !== undefined || (key in Object(object)));
};
}
/**
* A specialized version of `_.memoize` which clears the memoized function's
* cache when it exceeds `MAX_MEMOIZE_SIZE`.
*
* @private
* @param {Function} func The function to have its output memoized.
* @returns {Function} Returns the new memoized function.
*/
function memoizeCapped(func) {
var result = memoize(func, function(key) {
if (cache.size === MAX_MEMOIZE_SIZE) {
cache.clear();
}
return key;
});
var cache = result.cache;
return result;
}
/**
* Merges the function metadata of `source` into `data`.
*
* Merging metadata reduces the number of wrappers used to invoke a function.
* This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
* may be applied regardless of execution order. Methods like `_.ary` and
* `_.rearg` modify function arguments, making the order in which they are
* executed important, preventing the merging of metadata. However, we make
* an exception for a safe combined case where curried functions have `_.ary`
* and or `_.rearg` applied.
*
* @private
* @param {Array} data The destination metadata.
* @param {Array} source The source metadata.
* @returns {Array} Returns `data`.
*/
function mergeData(data, source) {
var bitmask = data[1],
srcBitmask = source[1],
newBitmask = bitmask | srcBitmask,
isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);
var isCombo =
((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||
((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||
((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));
// Exit early if metadata can't be merged.
if (!(isCommon || isCombo)) {
return data;
}
// Use source `thisArg` if available.
if (srcBitmask & WRAP_BIND_FLAG) {
data[2] = source[2];
// Set when currying a bound function.
newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;
}
// Compose partial arguments.
var value = source[3];
if (value) {
var partials = data[3];
data[3] = partials ? composeArgs(partials, value, source[4]) : value;
data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];
}
// Compose partial right arguments.
value = source[5];
if (value) {
partials = data[5];
data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;
data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];
}
// Use source `argPos` if available.
value = source[7];
if (value) {
data[7] = value;
}
// Use source `ary` if it's smaller.
if (srcBitmask & WRAP_ARY_FLAG) {
data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
}
// Use source `arity` if one is not provided.
if (data[9] == null) {
data[9] = source[9];
}
// Use source `func` and merge bitmasks.
data[0] = source[0];
data[1] = newBitmask;
return data;
}
/**
* This function is like
* [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* except that it includes inherited enumerable properties.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function nativeKeysIn(object) {
var result = [];
if (object != null) {
for (var key in Object(object)) {
result.push(key);
}
}
return result;
}
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return nativeObjectToString.call(value);
}
/**
* A specialized version of `baseRest` which transforms the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @param {Function} transform The rest array transform.
* @returns {Function} Returns the new function.
*/
function overRest(func, start, transform) {
start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
index = -1;
var otherArgs = Array(start + 1);
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = transform(array);
return apply(func, this, otherArgs);
};
}
/**
* Gets the parent value at `path` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} path The path to get the parent value of.
* @returns {*} Returns the parent value.
*/
function parent(object, path) {
return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));
}
/**
* Reorder `array` according to the specified indexes where the element at
* the first index is assigned as the first element, the element at
* the second index is assigned as the second element, and so on.
*
* @private
* @param {Array} array The array to reorder.
* @param {Array} indexes The arranged array indexes.
* @returns {Array} Returns `array`.
*/
function reorder(array, indexes) {
var arrLength = array.length,
length = nativeMin(indexes.length, arrLength),
oldArray = copyArray(array);
while (length--) {
var index = indexes[length];
array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
}
return array;
}
/**
* Gets the value at `key`, unless `key` is "__proto__" or "constructor".
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function safeGet(object, key) {
if (key === 'constructor' && typeof object[key] === 'function') {
return;
}
if (key == '__proto__') {
return;
}
return object[key];
}
/**
* Sets metadata for `func`.
*
* **Note:** If this function becomes hot, i.e. is invoked a lot in a short
* period of time, it will trip its breaker and transition to an identity
* function to avoid garbage collection pauses in V8. See
* [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
* for more details.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var setData = shortOut(baseSetData);
/**
* A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout).
*
* @private
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @returns {number|Object} Returns the timer id or timeout object.
*/
var setTimeout = ctxSetTimeout || function(func, wait) {
return root.setTimeout(func, wait);
};
/**
* Sets the `toString` method of `func` to return `string`.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var setToString = shortOut(baseSetToString);
/**
* Sets the `toString` method of `wrapper` to mimic the source of `reference`
* with wrapper details in a comment at the top of the source body.
*
* @private
* @param {Function} wrapper The function to modify.
* @param {Function} reference The reference function.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Function} Returns `wrapper`.
*/
function setWrapToString(wrapper, reference, bitmask) {
var source = (reference + '');
return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));
}
/**
* Creates a function that'll short out and invoke `identity` instead
* of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
* milliseconds.
*
* @private
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new shortable function.
*/
function shortOut(func) {
var count = 0,
lastCalled = 0;
return function() {
var stamp = nativeNow(),
remaining = HOT_SPAN - (stamp - lastCalled);
lastCalled = stamp;
if (remaining > 0) {
if (++count >= HOT_COUNT) {
return arguments[0];
}
} else {
count = 0;
}
return func.apply(undefined, arguments);
};
}
/**
* A specialized version of `_.shuffle` which mutates and sets the size of `array`.
*
* @private
* @param {Array} array The array to shuffle.
* @param {number} [size=array.length] The size of `array`.
* @returns {Array} Returns `array`.
*/
function shuffleSelf(array, size) {
var index = -1,
length = array.length,
lastIndex = length - 1;
size = size === undefined ? length : size;
while (++index < size) {
var rand = baseRandom(index, lastIndex),
value = array[rand];
array[rand] = array[index];
array[index] = value;
}
array.length = size;
return array;
}
/**
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/
var stringToPath = memoizeCapped(function(string) {
var result = [];
if (string.charCodeAt(0) === 46 /* . */) {
result.push('');
}
string.replace(rePropName, function(match, number, quote, subString) {
result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
});
return result;
});
/**
* Converts `value` to a string key if it's not a string or symbol.
*
* @private
* @param {*} value The value to inspect.
* @returns {string|symbol} Returns the key.
*/
function toKey(value) {
if (typeof value == 'string' || isSymbol(value)) {
return value;
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
/**
* Updates wrapper `details` based on `bitmask` flags.
*
* @private
* @returns {Array} details The details to modify.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Array} Returns `details`.
*/
function updateWrapDetails(details, bitmask) {
arrayEach(wrapFlags, function(pair) {
var value = '_.' + pair[0];
if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {
details.push(value);
}
});
return details.sort();
}
/**
* Creates a clone of `wrapper`.
*
* @private
* @param {Object} wrapper The wrapper to clone.
* @returns {Object} Returns the cloned wrapper.
*/
function wrapperClone(wrapper) {
if (wrapper instanceof LazyWrapper) {
return wrapper.clone();
}
var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
result.__actions__ = copyArray(wrapper.__actions__);
result.__index__ = wrapper.__index__;
result.__values__ = wrapper.__values__;
return result;
}
/*------------------------------------------------------------------------*/
/**
* Creates an array of elements split into groups the length of `size`.
* If `array` can't be split evenly, the final chunk will be the remaining
* elements.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to process.
* @param {number} [size=1] The length of each chunk
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the new array of chunks.
* @example
*
* _.chunk(['a', 'b', 'c', 'd'], 2);
* // => [['a', 'b'], ['c', 'd']]
*
* _.chunk(['a', 'b', 'c', 'd'], 3);
* // => [['a', 'b', 'c'], ['d']]
*/
function chunk(array, size, guard) {
if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {
size = 1;
} else {
size = nativeMax(toInteger(size), 0);
}
var length = array == null ? 0 : array.length;
if (!length || size < 1) {
return [];
}
var index = 0,
resIndex = 0,
result = Array(nativeCeil(length / size));
while (index < length) {
result[resIndex++] = baseSlice(array, index, (index += size));
}
return result;
}
/**
* Creates an array with all falsey values removed. The values `false`, `null`,
* `0`, `""`, `undefined`, and `NaN` are falsey.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to compact.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.compact([0, 1, false, 2, '', 3]);
* // => [1, 2, 3]
*/
function compact(array) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value) {
result[resIndex++] = value;
}
}
return result;
}
/**
* Creates a new array concatenating `array` with any additional arrays
* and/or values.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to concatenate.
* @param {...*} [values] The values to concatenate.
* @returns {Array} Returns the new concatenated array.
* @example
*
* var array = [1];
* var other = _.concat(array, 2, [3], [[4]]);
*
* console.log(other);
* // => [1, 2, 3, [4]]
*
* console.log(array);
* // => [1]
*/
function concat() {
var length = arguments.length;
if (!length) {
return [];
}
var args = Array(length - 1),
array = arguments[0],
index = length;
while (index--) {
args[index - 1] = arguments[index];
}
return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));
}
/**
* Creates an array of `array` values not included in the other given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* **Note:** Unlike `_.pullAll`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @see _.without, _.xor
* @example
*
* _.difference([2, 1], [2, 3]);
* // => [1]
*/
var difference = baseRest(function(array, values) {
return isArrayLikeObject(array)
? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))
: [];
});
/**
* This method is like `_.difference` except that it accepts `iteratee` which
* is invoked for each element of `array` and `values` to generate the criterion
* by which they're compared. The order and references of result values are
* determined by the first array. The iteratee is invoked with one argument:
* (value).
*
* **Note:** Unlike `_.pullAllBy`, this method returns a new array.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);
* // => [1.2]
*
* // The `_.property` iteratee shorthand.
* _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');
* // => [{ 'x': 2 }]
*/
var differenceBy = baseRest(function(array, values) {
var iteratee = last(values);
if (isArrayLikeObject(iteratee)) {
iteratee = undefined;
}
return isArrayLikeObject(array)
? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2))
: [];
});
/**
* This method is like `_.difference` except that it accepts `comparator`
* which is invoked to compare elements of `array` to `values`. The order and
* references of result values are determined by the first array. The comparator
* is invoked with two arguments: (arrVal, othVal).
*
* **Note:** Unlike `_.pullAllWith`, this method returns a new array.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
*
* _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);
* // => [{ 'x': 2, 'y': 1 }]
*/
var differenceWith = baseRest(function(array, values) {
var comparator = last(values);
if (isArrayLikeObject(comparator)) {
comparator = undefined;
}
return isArrayLikeObject(array)
? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator)
: [];
});
/**
* Creates a slice of `array` with `n` elements dropped from the beginning.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to drop.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.drop([1, 2, 3]);
* // => [2, 3]
*
* _.drop([1, 2, 3], 2);
* // => [3]
*
* _.drop([1, 2, 3], 5);
* // => []
*
* _.drop([1, 2, 3], 0);
* // => [1, 2, 3]
*/
function drop(array, n, guard) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
return baseSlice(array, n < 0 ? 0 : n, length);
}
/**
* Creates a slice of `array` with `n` elements dropped from the end.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to drop.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.dropRight([1, 2, 3]);
* // => [1, 2]
*
* _.dropRight([1, 2, 3], 2);
* // => [1]
*
* _.dropRight([1, 2, 3], 5);
* // => []
*
* _.dropRight([1, 2, 3], 0);
* // => [1, 2, 3]
*/
function dropRight(array, n, guard) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
n = length - n;
return baseSlice(array, 0, n < 0 ? 0 : n);
}
/**
* Creates a slice of `array` excluding elements dropped from the end.
* Elements are dropped until `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.dropRightWhile(users, function(o) { return !o.active; });
* // => objects for ['barney']
*
* // The `_.matches` iteratee shorthand.
* _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });
* // => objects for ['barney', 'fred']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.dropRightWhile(users, ['active', false]);
* // => objects for ['barney']
*
* // The `_.property` iteratee shorthand.
* _.dropRightWhile(users, 'active');
* // => objects for ['barney', 'fred', 'pebbles']
*/
function dropRightWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3), true, true)
: [];
}
/**
* Creates a slice of `array` excluding elements dropped from the beginning.
* Elements are dropped until `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.dropWhile(users, function(o) { return !o.active; });
* // => objects for ['pebbles']
*
* // The `_.matches` iteratee shorthand.
* _.dropWhile(users, { 'user': 'barney', 'active': false });
* // => objects for ['fred', 'pebbles']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.dropWhile(users, ['active', false]);
* // => objects for ['pebbles']
*
* // The `_.property` iteratee shorthand.
* _.dropWhile(users, 'active');
* // => objects for ['barney', 'fred', 'pebbles']
*/
function dropWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3), true)
: [];
}
/**
* Fills elements of `array` with `value` from `start` up to, but not
* including, `end`.
*
* **Note:** This method mutates `array`.
*
* @static
* @memberOf _
* @since 3.2.0
* @category Array
* @param {Array} array The array to fill.
* @param {*} value The value to fill `array` with.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns `array`.
* @example
*
* var array = [1, 2, 3];
*
* _.fill(array, 'a');
* console.log(array);
* // => ['a', 'a', 'a']
*
* _.fill(Array(3), 2);
* // => [2, 2, 2]
*
* _.fill([4, 6, 8, 10], '*', 1, 3);
* // => [4, '*', '*', 10]
*/
function fill(array, value, start, end) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
start = 0;
end = length;
}
return baseFill(array, value, start, end);
}
/**
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.findIndex(users, function(o) { return o.user == 'barney'; });
* // => 0
*
* // The `_.matches` iteratee shorthand.
* _.findIndex(users, { 'user': 'fred', 'active': false });
* // => 1
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findIndex(users, ['active', false]);
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.findIndex(users, 'active');
* // => 2
*/
function findIndex(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseFindIndex(array, getIteratee(predicate, 3), index);
}
/**
* This method is like `_.findIndex` except that it iterates over elements
* of `collection` from right to left.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=array.length-1] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
* // => 2
*
* // The `_.matches` iteratee shorthand.
* _.findLastIndex(users, { 'user': 'barney', 'active': true });
* // => 0
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findLastIndex(users, ['active', false]);
* // => 2
*
* // The `_.property` iteratee shorthand.
* _.findLastIndex(users, 'active');
* // => 0
*/
function findLastIndex(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = length - 1;
if (fromIndex !== undefined) {
index = toInteger(fromIndex);
index = fromIndex < 0
? nativeMax(length + index, 0)
: nativeMin(index, length - 1);
}
return baseFindIndex(array, getIteratee(predicate, 3), index, true);
}
/**
* Flattens `array` a single level deep.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flatten([1, [2, [3, [4]], 5]]);
* // => [1, 2, [3, [4]], 5]
*/
function flatten(array) {
var length = array == null ? 0 : array.length;
return length ? baseFlatten(array, 1) : [];
}
/**
* Recursively flattens `array`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flattenDeep([1, [2, [3, [4]], 5]]);
* // => [1, 2, 3, 4, 5]
*/
function flattenDeep(array) {
var length = array == null ? 0 : array.length;
return length ? baseFlatten(array, INFINITY) : [];
}
/**
* Recursively flatten `array` up to `depth` times.
*
* @static
* @memberOf _
* @since 4.4.0
* @category Array
* @param {Array} array The array to flatten.
* @param {number} [depth=1] The maximum recursion depth.
* @returns {Array} Returns the new flattened array.
* @example
*
* var array = [1, [2, [3, [4]], 5]];
*
* _.flattenDepth(array, 1);
* // => [1, 2, [3, [4]], 5]
*
* _.flattenDepth(array, 2);
* // => [1, 2, 3, [4], 5]
*/
function flattenDepth(array, depth) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
depth = depth === undefined ? 1 : toInteger(depth);
return baseFlatten(array, depth);
}
/**
* The inverse of `_.toPairs`; this method returns an object composed
* from key-value `pairs`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} pairs The key-value pairs.
* @returns {Object} Returns the new object.
* @example
*
* _.fromPairs([['a', 1], ['b', 2]]);
* // => { 'a': 1, 'b': 2 }
*/
function fromPairs(pairs) {
var index = -1,
length = pairs == null ? 0 : pairs.length,
result = {};
while (++index < length) {
var pair = pairs[index];
result[pair[0]] = pair[1];
}
return result;
}
/**
* Gets the first element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias first
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the first element of `array`.
* @example
*
* _.head([1, 2, 3]);
* // => 1
*
* _.head([]);
* // => undefined
*/
function head(array) {
return (array && array.length) ? array[0] : undefined;
}
/**
* Gets the index at which the first occurrence of `value` is found in `array`
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. If `fromIndex` is negative, it's used as the
* offset from the end of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.indexOf([1, 2, 1, 2], 2);
* // => 1
*
* // Search from the `fromIndex`.
* _.indexOf([1, 2, 1, 2], 2, 2);
* // => 3
*/
function indexOf(array, value, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseIndexOf(array, value, index);
}
/**
* Gets all but the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.initial([1, 2, 3]);
* // => [1, 2]
*/
function initial(array) {
var length = array == null ? 0 : array.length;
return length ? baseSlice(array, 0, -1) : [];
}
/**
* Creates an array of unique values that are included in all given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* _.intersection([2, 1], [2, 3]);
* // => [2]
*/
var intersection = baseRest(function(arrays) {
var mapped = arrayMap(arrays, castArrayLikeObject);
return (mapped.length && mapped[0] === arrays[0])
? baseIntersection(mapped)
: [];
});
/**
* This method is like `_.intersection` except that it accepts `iteratee`
* which is invoked for each element of each `arrays` to generate the criterion
* by which they're compared. The order and references of result values are
* determined by the first array. The iteratee is invoked with one argument:
* (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);
* // => [2.1]
*
* // The `_.property` iteratee shorthand.
* _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }]
*/
var intersectionBy = baseRest(function(arrays) {
var iteratee = last(arrays),
mapped = arrayMap(arrays, castArrayLikeObject);
if (iteratee === last(mapped)) {
iteratee = undefined;
} else {
mapped.pop();
}
return (mapped.length && mapped[0] === arrays[0])
? baseIntersection(mapped, getIteratee(iteratee, 2))
: [];
});
/**
* This method is like `_.intersection` except that it accepts `comparator`
* which is invoked to compare elements of `arrays`. The order and references
* of result values are determined by the first array. The comparator is
* invoked with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
* var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.intersectionWith(objects, others, _.isEqual);
* // => [{ 'x': 1, 'y': 2 }]
*/
var intersectionWith = baseRest(function(arrays) {
var comparator = last(arrays),
mapped = arrayMap(arrays, castArrayLikeObject);
comparator = typeof comparator == 'function' ? comparator : undefined;
if (comparator) {
mapped.pop();
}
return (mapped.length && mapped[0] === arrays[0])
? baseIntersection(mapped, undefined, comparator)
: [];
});
/**
* Converts all elements in `array` into a string separated by `separator`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to convert.
* @param {string} [separator=','] The element separator.
* @returns {string} Returns the joined string.
* @example
*
* _.join(['a', 'b', 'c'], '~');
* // => 'a~b~c'
*/
function join(array, separator) {
return array == null ? '' : nativeJoin.call(array, separator);
}
/**
* Gets the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the last element of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*/
function last(array) {
var length = array == null ? 0 : array.length;
return length ? array[length - 1] : undefined;
}
/**
* This method is like `_.indexOf` except that it iterates over elements of
* `array` from right to left.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=array.length-1] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.lastIndexOf([1, 2, 1, 2], 2);
* // => 3
*
* // Search from the `fromIndex`.
* _.lastIndexOf([1, 2, 1, 2], 2, 2);
* // => 1
*/
function lastIndexOf(array, value, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = length;
if (fromIndex !== undefined) {
index = toInteger(fromIndex);
index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1);
}
return value === value
? strictLastIndexOf(array, value, index)
: baseFindIndex(array, baseIsNaN, index, true);
}
/**
* Gets the element at index `n` of `array`. If `n` is negative, the nth
* element from the end is returned.
*
* @static
* @memberOf _
* @since 4.11.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=0] The index of the element to return.
* @returns {*} Returns the nth element of `array`.
* @example
*
* var array = ['a', 'b', 'c', 'd'];
*
* _.nth(array, 1);
* // => 'b'
*
* _.nth(array, -2);
* // => 'c';
*/
function nth(array, n) {
return (array && array.length) ? baseNth(array, toInteger(n)) : undefined;
}
/**
* Removes all given values from `array` using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`
* to remove elements from an array by predicate.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {...*} [values] The values to remove.
* @returns {Array} Returns `array`.
* @example
*
* var array = ['a', 'b', 'c', 'a', 'b', 'c'];
*
* _.pull(array, 'a', 'c');
* console.log(array);
* // => ['b', 'b']
*/
var pull = baseRest(pullAll);
/**
* This method is like `_.pull` except that it accepts an array of values to remove.
*
* **Note:** Unlike `_.difference`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @returns {Array} Returns `array`.
* @example
*
* var array = ['a', 'b', 'c', 'a', 'b', 'c'];
*
* _.pullAll(array, ['a', 'c']);
* console.log(array);
* // => ['b', 'b']
*/
function pullAll(array, values) {
return (array && array.length && values && values.length)
? basePullAll(array, values)
: array;
}
/**
* This method is like `_.pullAll` except that it accepts `iteratee` which is
* invoked for each element of `array` and `values` to generate the criterion
* by which they're compared. The iteratee is invoked with one argument: (value).
*
* **Note:** Unlike `_.differenceBy`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns `array`.
* @example
*
* var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
*
* _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');
* console.log(array);
* // => [{ 'x': 2 }]
*/
function pullAllBy(array, values, iteratee) {
return (array && array.length && values && values.length)
? basePullAll(array, values, getIteratee(iteratee, 2))
: array;
}
/**
* This method is like `_.pullAll` except that it accepts `comparator` which
* is invoked to compare elements of `array` to `values`. The comparator is
* invoked with two arguments: (arrVal, othVal).
*
* **Note:** Unlike `_.differenceWith`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.6.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns `array`.
* @example
*
* var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];
*
* _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);
* console.log(array);
* // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]
*/
function pullAllWith(array, values, comparator) {
return (array && array.length && values && values.length)
? basePullAll(array, values, undefined, comparator)
: array;
}
/**
* Removes elements from `array` corresponding to `indexes` and returns an
* array of removed elements.
*
* **Note:** Unlike `_.at`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {...(number|number[])} [indexes] The indexes of elements to remove.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* var array = ['a', 'b', 'c', 'd'];
* var pulled = _.pullAt(array, [1, 3]);
*
* console.log(array);
* // => ['a', 'c']
*
* console.log(pulled);
* // => ['b', 'd']
*/
var pullAt = flatRest(function(array, indexes) {
var length = array == null ? 0 : array.length,
result = baseAt(array, indexes);
basePullAt(array, arrayMap(indexes, function(index) {
return isIndex(index, length) ? +index : index;
}).sort(compareAscending));
return result;
});
/**
* Removes all elements from `array` that `predicate` returns truthy for
* and returns an array of the removed elements. The predicate is invoked
* with three arguments: (value, index, array).
*
* **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
* to pull elements from an array by value.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* var array = [1, 2, 3, 4];
* var evens = _.remove(array, function(n) {
* return n % 2 == 0;
* });
*
* console.log(array);
* // => [1, 3]
*
* console.log(evens);
* // => [2, 4]
*/
function remove(array, predicate) {
var result = [];
if (!(array && array.length)) {
return result;
}
var index = -1,
indexes = [],
length = array.length;
predicate = getIteratee(predicate, 3);
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result.push(value);
indexes.push(index);
}
}
basePullAt(array, indexes);
return result;
}
/**
* Reverses `array` so that the first element becomes the last, the second
* element becomes the second to last, and so on.
*
* **Note:** This method mutates `array` and is based on
* [`Array#reverse`](https://mdn.io/Array/reverse).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @returns {Array} Returns `array`.
* @example
*
* var array = [1, 2, 3];
*
* _.reverse(array);
* // => [3, 2, 1]
*
* console.log(array);
* // => [3, 2, 1]
*/
function reverse(array) {
return array == null ? array : nativeReverse.call(array);
}
/**
* Creates a slice of `array` from `start` up to, but not including, `end`.
*
* **Note:** This method is used instead of
* [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are
* returned.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function slice(array, start, end) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
start = 0;
end = length;
}
else {
start = start == null ? 0 : toInteger(start);
end = end === undefined ? length : toInteger(end);
}
return baseSlice(array, start, end);
}
/**
* Uses a binary search to determine the lowest index at which `value`
* should be inserted into `array` in order to maintain its sort order.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* _.sortedIndex([30, 50], 40);
* // => 1
*/
function sortedIndex(array, value) {
return baseSortedIndex(array, value);
}
/**
* This method is like `_.sortedIndex` except that it accepts `iteratee`
* which is invoked for `value` and each element of `array` to compute their
* sort ranking. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* var objects = [{ 'x': 4 }, { 'x': 5 }];
*
* _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.sortedIndexBy(objects, { 'x': 4 }, 'x');
* // => 0
*/
function sortedIndexBy(array, value, iteratee) {
return baseSortedIndexBy(array, value, getIteratee(iteratee, 2));
}
/**
* This method is like `_.indexOf` except that it performs a binary
* search on a sorted `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.sortedIndexOf([4, 5, 5, 5, 6], 5);
* // => 1
*/
function sortedIndexOf(array, value) {
var length = array == null ? 0 : array.length;
if (length) {
var index = baseSortedIndex(array, value);
if (index < length && eq(array[index], value)) {
return index;
}
}
return -1;
}
/**
* This method is like `_.sortedIndex` except that it returns the highest
* index at which `value` should be inserted into `array` in order to
* maintain its sort order.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* _.sortedLastIndex([4, 5, 5, 5, 6], 5);
* // => 4
*/
function sortedLastIndex(array, value) {
return baseSortedIndex(array, value, true);
}
/**
* This method is like `_.sortedLastIndex` except that it accepts `iteratee`
* which is invoked for `value` and each element of `array` to compute their
* sort ranking. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* var objects = [{ 'x': 4 }, { 'x': 5 }];
*
* _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
* // => 1
*
* // The `_.property` iteratee shorthand.
* _.sortedLastIndexBy(objects, { 'x': 4 }, 'x');
* // => 1
*/
function sortedLastIndexBy(array, value, iteratee) {
return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true);
}
/**
* This method is like `_.lastIndexOf` except that it performs a binary
* search on a sorted `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.sortedLastIndexOf([4, 5, 5, 5, 6], 5);
* // => 3
*/
function sortedLastIndexOf(array, value) {
var length = array == null ? 0 : array.length;
if (length) {
var index = baseSortedIndex(array, value, true) - 1;
if (eq(array[index], value)) {
return index;
}
}
return -1;
}
/**
* This method is like `_.uniq` except that it's designed and optimized
* for sorted arrays.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.sortedUniq([1, 1, 2]);
* // => [1, 2]
*/
function sortedUniq(array) {
return (array && array.length)
? baseSortedUniq(array)
: [];
}
/**
* This method is like `_.uniqBy` except that it's designed and optimized
* for sorted arrays.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);
* // => [1.1, 2.3]
*/
function sortedUniqBy(array, iteratee) {
return (array && array.length)
? baseSortedUniq(array, getIteratee(iteratee, 2))
: [];
}
/**
* Gets all but the first element of `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to query.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.tail([1, 2, 3]);
* // => [2, 3]
*/
function tail(array) {
var length = array == null ? 0 : array.length;
return length ? baseSlice(array, 1, length) : [];
}
/**
* Creates a slice of `array` with `n` elements taken from the beginning.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to take.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.take([1, 2, 3]);
* // => [1]
*
* _.take([1, 2, 3], 2);
* // => [1, 2]
*
* _.take([1, 2, 3], 5);
* // => [1, 2, 3]
*
* _.take([1, 2, 3], 0);
* // => []
*/
function take(array, n, guard) {
if (!(array && array.length)) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
return baseSlice(array, 0, n < 0 ? 0 : n);
}
/**
* Creates a slice of `array` with `n` elements taken from the end.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to take.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.takeRight([1, 2, 3]);
* // => [3]
*
* _.takeRight([1, 2, 3], 2);
* // => [2, 3]
*
* _.takeRight([1, 2, 3], 5);
* // => [1, 2, 3]
*
* _.takeRight([1, 2, 3], 0);
* // => []
*/
function takeRight(array, n, guard) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
n = length - n;
return baseSlice(array, n < 0 ? 0 : n, length);
}
/**
* Creates a slice of `array` with elements taken from the end. Elements are
* taken until `predicate` returns falsey. The predicate is invoked with
* three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.takeRightWhile(users, function(o) { return !o.active; });
* // => objects for ['fred', 'pebbles']
*
* // The `_.matches` iteratee shorthand.
* _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });
* // => objects for ['pebbles']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.takeRightWhile(users, ['active', false]);
* // => objects for ['fred', 'pebbles']
*
* // The `_.property` iteratee shorthand.
* _.takeRightWhile(users, 'active');
* // => []
*/
function takeRightWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3), false, true)
: [];
}
/**
* Creates a slice of `array` with elements taken from the beginning. Elements
* are taken until `predicate` returns falsey. The predicate is invoked with
* three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.takeWhile(users, function(o) { return !o.active; });
* // => objects for ['barney', 'fred']
*
* // The `_.matches` iteratee shorthand.
* _.takeWhile(users, { 'user': 'barney', 'active': false });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.takeWhile(users, ['active', false]);
* // => objects for ['barney', 'fred']
*
* // The `_.property` iteratee shorthand.
* _.takeWhile(users, 'active');
* // => []
*/
function takeWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3))
: [];
}
/**
* Creates an array of unique values, in order, from all given arrays using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of combined values.
* @example
*
* _.union([2], [1, 2]);
* // => [2, 1]
*/
var union = baseRest(function(arrays) {
return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));
});
/**
* This method is like `_.union` except that it accepts `iteratee` which is
* invoked for each element of each `arrays` to generate the criterion by
* which uniqueness is computed. Result values are chosen from the first
* array in which the value occurs. The iteratee is invoked with one argument:
* (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of combined values.
* @example
*
* _.unionBy([2.1], [1.2, 2.3], Math.floor);
* // => [2.1, 1.2]
*
* // The `_.property` iteratee shorthand.
* _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }, { 'x': 2 }]
*/
var unionBy = baseRest(function(arrays) {
var iteratee = last(arrays);
if (isArrayLikeObject(iteratee)) {
iteratee = undefined;
}
return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2));
});
/**
* This method is like `_.union` except that it accepts `comparator` which
* is invoked to compare elements of `arrays`. Result values are chosen from
* the first array in which the value occurs. The comparator is invoked
* with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of combined values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
* var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.unionWith(objects, others, _.isEqual);
* // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
*/
var unionWith = baseRest(function(arrays) {
var comparator = last(arrays);
comparator = typeof comparator == 'function' ? comparator : undefined;
return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator);
});
/**
* Creates a duplicate-free version of an array, using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons, in which only the first occurrence of each element
* is kept. The order of result values is determined by the order they occur
* in the array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.uniq([2, 1, 2]);
* // => [2, 1]
*/
function uniq(array) {
return (array && array.length) ? baseUniq(array) : [];
}
/**
* This method is like `_.uniq` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the criterion by which
* uniqueness is computed. The order of result values is determined by the
* order they occur in the array. The iteratee is invoked with one argument:
* (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.uniqBy([2.1, 1.2, 2.3], Math.floor);
* // => [2.1, 1.2]
*
* // The `_.property` iteratee shorthand.
* _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }, { 'x': 2 }]
*/
function uniqBy(array, iteratee) {
return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : [];
}
/**
* This method is like `_.uniq` except that it accepts `comparator` which
* is invoked to compare elements of `array`. The order of result values is
* determined by the order they occur in the array.The comparator is invoked
* with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.uniqWith(objects, _.isEqual);
* // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
*/
function uniqWith(array, comparator) {
comparator = typeof comparator == 'function' ? comparator : undefined;
return (array && array.length) ? baseUniq(array, undefined, comparator) : [];
}
/**
* This method is like `_.zip` except that it accepts an array of grouped
* elements and creates an array regrouping the elements to their pre-zip
* configuration.
*
* @static
* @memberOf _
* @since 1.2.0
* @category Array
* @param {Array} array The array of grouped elements to process.
* @returns {Array} Returns the new array of regrouped elements.
* @example
*
* var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);
* // => [['a', 1, true], ['b', 2, false]]
*
* _.unzip(zipped);
* // => [['a', 'b'], [1, 2], [true, false]]
*/
function unzip(array) {
if (!(array && array.length)) {
return [];
}
var length = 0;
array = arrayFilter(array, function(group) {
if (isArrayLikeObject(group)) {
length = nativeMax(group.length, length);
return true;
}
});
return baseTimes(length, function(index) {
return arrayMap(array, baseProperty(index));
});
}
/**
* This method is like `_.unzip` except that it accepts `iteratee` to specify
* how regrouped values should be combined. The iteratee is invoked with the
* elements of each group: (...group).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Array
* @param {Array} array The array of grouped elements to process.
* @param {Function} [iteratee=_.identity] The function to combine
* regrouped values.
* @returns {Array} Returns the new array of regrouped elements.
* @example
*
* var zipped = _.zip([1, 2], [10, 20], [100, 200]);
* // => [[1, 10, 100], [2, 20, 200]]
*
* _.unzipWith(zipped, _.add);
* // => [3, 30, 300]
*/
function unzipWith(array, iteratee) {
if (!(array && array.length)) {
return [];
}
var result = unzip(array);
if (iteratee == null) {
return result;
}
return arrayMap(result, function(group) {
return apply(iteratee, undefined, group);
});
}
/**
* Creates an array excluding all given values using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* **Note:** Unlike `_.pull`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...*} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @see _.difference, _.xor
* @example
*
* _.without([2, 1, 2, 3], 1, 2);
* // => [3]
*/
var without = baseRest(function(array, values) {
return isArrayLikeObject(array)
? baseDifference(array, values)
: [];
});
/**
* Creates an array of unique values that is the
* [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
* of the given arrays. The order of result values is determined by the order
* they occur in the arrays.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of filtered values.
* @see _.difference, _.without
* @example
*
* _.xor([2, 1], [2, 3]);
* // => [1, 3]
*/
var xor = baseRest(function(arrays) {
return baseXor(arrayFilter(arrays, isArrayLikeObject));
});
/**
* This method is like `_.xor` except that it accepts `iteratee` which is
* invoked for each element of each `arrays` to generate the criterion by
* which by which they're compared. The order of result values is determined
* by the order they occur in the arrays. The iteratee is invoked with one
* argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);
* // => [1.2, 3.4]
*
* // The `_.property` iteratee shorthand.
* _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 2 }]
*/
var xorBy = baseRest(function(arrays) {
var iteratee = last(arrays);
if (isArrayLikeObject(iteratee)) {
iteratee = undefined;
}
return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2));
});
/**
* This method is like `_.xor` except that it accepts `comparator` which is
* invoked to compare elements of `arrays`. The order of result values is
* determined by the order they occur in the arrays. The comparator is invoked
* with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
* var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.xorWith(objects, others, _.isEqual);
* // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
*/
var xorWith = baseRest(function(arrays) {
var comparator = last(arrays);
comparator = typeof comparator == 'function' ? comparator : undefined;
return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator);
});
/**
* Creates an array of grouped elements, the first of which contains the
* first elements of the given arrays, the second of which contains the
* second elements of the given arrays, and so on.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to process.
* @returns {Array} Returns the new array of grouped elements.
* @example
*
* _.zip(['a', 'b'], [1, 2], [true, false]);
* // => [['a', 1, true], ['b', 2, false]]
*/
var zip = baseRest(unzip);
/**
* This method is like `_.fromPairs` except that it accepts two arrays,
* one of property identifiers and one of corresponding values.
*
* @static
* @memberOf _
* @since 0.4.0
* @category Array
* @param {Array} [props=[]] The property identifiers.
* @param {Array} [values=[]] The property values.
* @returns {Object} Returns the new object.
* @example
*
* _.zipObject(['a', 'b'], [1, 2]);
* // => { 'a': 1, 'b': 2 }
*/
function zipObject(props, values) {
return baseZipObject(props || [], values || [], assignValue);
}
/**
* This method is like `_.zipObject` except that it supports property paths.
*
* @static
* @memberOf _
* @since 4.1.0
* @category Array
* @param {Array} [props=[]] The property identifiers.
* @param {Array} [values=[]] The property values.
* @returns {Object} Returns the new object.
* @example
*
* _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);
* // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }
*/
function zipObjectDeep(props, values) {
return baseZipObject(props || [], values || [], baseSet);
}
/**
* This method is like `_.zip` except that it accepts `iteratee` to specify
* how grouped values should be combined. The iteratee is invoked with the
* elements of each group: (...group).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Array
* @param {...Array} [arrays] The arrays to process.
* @param {Function} [iteratee=_.identity] The function to combine
* grouped values.
* @returns {Array} Returns the new array of grouped elements.
* @example
*
* _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {
* return a + b + c;
* });
* // => [111, 222]
*/
var zipWith = baseRest(function(arrays) {
var length = arrays.length,
iteratee = length > 1 ? arrays[length - 1] : undefined;
iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined;
return unzipWith(arrays, iteratee);
});
/*------------------------------------------------------------------------*/
/**
* Creates a `lodash` wrapper instance that wraps `value` with explicit method
* chain sequences enabled. The result of such sequences must be unwrapped
* with `_#value`.
*
* @static
* @memberOf _
* @since 1.3.0
* @category Seq
* @param {*} value The value to wrap.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'pebbles', 'age': 1 }
* ];
*
* var youngest = _
* .chain(users)
* .sortBy('age')
* .map(function(o) {
* return o.user + ' is ' + o.age;
* })
* .head()
* .value();
* // => 'pebbles is 1'
*/
function chain(value) {
var result = lodash(value);
result.__chain__ = true;
return result;
}
/**
* This method invokes `interceptor` and returns `value`. The interceptor
* is invoked with one argument; (value). The purpose of this method is to
* "tap into" a method chain sequence in order to modify intermediate results.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Seq
* @param {*} value The value to provide to `interceptor`.
* @param {Function} interceptor The function to invoke.
* @returns {*} Returns `value`.
* @example
*
* _([1, 2, 3])
* .tap(function(array) {
* // Mutate input array.
* array.pop();
* })
* .reverse()
* .value();
* // => [2, 1]
*/
function tap(value, interceptor) {
interceptor(value);
return value;
}
/**
* This method is like `_.tap` except that it returns the result of `interceptor`.
* The purpose of this method is to "pass thru" values replacing intermediate
* results in a method chain sequence.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Seq
* @param {*} value The value to provide to `interceptor`.
* @param {Function} interceptor The function to invoke.
* @returns {*} Returns the result of `interceptor`.
* @example
*
* _(' abc ')
* .chain()
* .trim()
* .thru(function(value) {
* return [value];
* })
* .value();
* // => ['abc']
*/
function thru(value, interceptor) {
return interceptor(value);
}
/**
* This method is the wrapper version of `_.at`.
*
* @name at
* @memberOf _
* @since 1.0.0
* @category Seq
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
*
* _(object).at(['a[0].b.c', 'a[1]']).value();
* // => [3, 4]
*/
var wrapperAt = flatRest(function(paths) {
var length = paths.length,
start = length ? paths[0] : 0,
value = this.__wrapped__,
interceptor = function(object) { return baseAt(object, paths); };
if (length > 1 || this.__actions__.length ||
!(value instanceof LazyWrapper) || !isIndex(start)) {
return this.thru(interceptor);
}
value = value.slice(start, +start + (length ? 1 : 0));
value.__actions__.push({
'func': thru,
'args': [interceptor],
'thisArg': undefined
});
return new LodashWrapper(value, this.__chain__).thru(function(array) {
if (length && !array.length) {
array.push(undefined);
}
return array;
});
});
/**
* Creates a `lodash` wrapper instance with explicit method chain sequences enabled.
*
* @name chain
* @memberOf _
* @since 0.1.0
* @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 }
* ];
*
* // A sequence without explicit chaining.
* _(users).head();
* // => { 'user': 'barney', 'age': 36 }
*
* // A sequence with explicit chaining.
* _(users)
* .chain()
* .head()
* .pick('user')
* .value();
* // => { 'user': 'barney' }
*/
function wrapperChain() {
return chain(this);
}
/**
* Executes the chain sequence and returns the wrapped result.
*
* @name commit
* @memberOf _
* @since 3.2.0
* @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var array = [1, 2];
* var wrapped = _(array).push(3);
*
* console.log(array);
* // => [1, 2]
*
* wrapped = wrapped.commit();
* console.log(array);
* // => [1, 2, 3]
*
* wrapped.last();
* // => 3
*
* console.log(array);
* // => [1, 2, 3]
*/
function wrapperCommit() {
return new LodashWrapper(this.value(), this.__chain__);
}
/**
* Gets the next value on a wrapped object following the
* [iterator protocol](https://mdn.io/iteration_protocols#iterator).
*
* @name next
* @memberOf _
* @since 4.0.0
* @category Seq
* @returns {Object} Returns the next iterator value.
* @example
*
* var wrapped = _([1, 2]);
*
* wrapped.next();
* // => { 'done': false, 'value': 1 }
*
* wrapped.next();
* // => { 'done': false, 'value': 2 }
*
* wrapped.next();
* // => { 'done': true, 'value': undefined }
*/
function wrapperNext() {
if (this.__values__ === undefined) {
this.__values__ = toArray(this.value());
}
var done = this.__index__ >= this.__values__.length,
value = done ? undefined : this.__values__[this.__index__++];
return { 'done': done, 'value': value };
}
/**
* Enables the wrapper to be iterable.
*
* @name Symbol.iterator
* @memberOf _
* @since 4.0.0
* @category Seq
* @returns {Object} Returns the wrapper object.
* @example
*
* var wrapped = _([1, 2]);
*
* wrapped[Symbol.iterator]() === wrapped;
* // => true
*
* Array.from(wrapped);
* // => [1, 2]
*/
function wrapperToIterator() {
return this;
}
/**
* Creates a clone of the chain sequence planting `value` as the wrapped value.
*
* @name plant
* @memberOf _
* @since 3.2.0
* @category Seq
* @param {*} value The value to plant.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var wrapped = _([1, 2]).map(square);
* var other = wrapped.plant([3, 4]);
*
* other.value();
* // => [9, 16]
*
* wrapped.value();
* // => [1, 4]
*/
function wrapperPlant(value) {
var result,
parent = this;
while (parent instanceof baseLodash) {
var clone = wrapperClone(parent);
clone.__index__ = 0;
clone.__values__ = undefined;
if (result) {
previous.__wrapped__ = clone;
} else {
result = clone;
}
var previous = clone;
parent = parent.__wrapped__;
}
previous.__wrapped__ = value;
return result;
}
/**
* This method is the wrapper version of `_.reverse`.
*
* **Note:** This method mutates the wrapped array.
*
* @name reverse
* @memberOf _
* @since 0.1.0
* @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var array = [1, 2, 3];
*
* _(array).reverse().value()
* // => [3, 2, 1]
*
* console.log(array);
* // => [3, 2, 1]
*/
function wrapperReverse() {
var value = this.__wrapped__;
if (value instanceof LazyWrapper) {
var wrapped = value;
if (this.__actions__.length) {
wrapped = new LazyWrapper(this);
}
wrapped = wrapped.reverse();
wrapped.__actions__.push({
'func': thru,
'args': [reverse],
'thisArg': undefined
});
return new LodashWrapper(wrapped, this.__chain__);
}
return this.thru(reverse);
}
/**
* Executes the chain sequence to resolve the unwrapped value.
*
* @name value
* @memberOf _
* @since 0.1.0
* @alias toJSON, valueOf
* @category Seq
* @returns {*} Returns the resolved unwrapped value.
* @example
*
* _([1, 2, 3]).value();
* // => [1, 2, 3]
*/
function wrapperValue() {
return baseWrapperValue(this.__wrapped__, this.__actions__);
}
/*------------------------------------------------------------------------*/
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The corresponding value of
* each key is the number of times the key was returned by `iteratee`. The
* iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.5.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.countBy([6.1, 4.2, 6.3], Math.floor);
* // => { '4': 1, '6': 2 }
*
* // The `_.property` iteratee shorthand.
* _.countBy(['one', 'two', 'three'], 'length');
* // => { '3': 2, '5': 1 }
*/
var countBy = createAggregator(function(result, value, key) {
if (hasOwnProperty.call(result, key)) {
++result[key];
} else {
baseAssignValue(result, key, 1);
}
});
/**
* Checks if `predicate` returns truthy for **all** elements of `collection`.
* Iteration is stopped once `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index|key, collection).
*
* **Note:** This method returns `true` for
* [empty collections](https://en.wikipedia.org/wiki/Empty_set) because
* [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of
* elements of empty collections.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
* @example
*
* _.every([true, 1, null, 'yes'], Boolean);
* // => false
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.every(users, { 'user': 'barney', 'active': false });
* // => false
*
* // The `_.matchesProperty` iteratee shorthand.
* _.every(users, ['active', false]);
* // => true
*
* // The `_.property` iteratee shorthand.
* _.every(users, 'active');
* // => false
*/
function every(collection, predicate, guard) {
var func = isArray(collection) ? arrayEvery : baseEvery;
if (guard && isIterateeCall(collection, predicate, guard)) {
predicate = undefined;
}
return func(collection, getIteratee(predicate, 3));
}
/**
* Iterates over elements of `collection`, returning an array of all elements
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* **Note:** Unlike `_.remove`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
* @see _.reject
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* _.filter(users, function(o) { return !o.active; });
* // => objects for ['fred']
*
* // The `_.matches` iteratee shorthand.
* _.filter(users, { 'age': 36, 'active': true });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.filter(users, ['active', false]);
* // => objects for ['fred']
*
* // The `_.property` iteratee shorthand.
* _.filter(users, 'active');
* // => objects for ['barney']
*
* // Combining several predicates using `_.overEvery` or `_.overSome`.
* _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));
* // => objects for ['fred', 'barney']
*/
function filter(collection, predicate) {
var func = isArray(collection) ? arrayFilter : baseFilter;
return func(collection, getIteratee(predicate, 3));
}
/**
* Iterates over elements of `collection`, returning the first element
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false },
* { 'user': 'pebbles', 'age': 1, 'active': true }
* ];
*
* _.find(users, function(o) { return o.age < 40; });
* // => object for 'barney'
*
* // The `_.matches` iteratee shorthand.
* _.find(users, { 'age': 1, 'active': true });
* // => object for 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.find(users, ['active', false]);
* // => object for 'fred'
*
* // The `_.property` iteratee shorthand.
* _.find(users, 'active');
* // => object for 'barney'
*/
var find = createFind(findIndex);
/**
* This method is like `_.find` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Collection
* @param {Array|Object} collection The collection to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=collection.length-1] The index to search from.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* _.findLast([1, 2, 3, 4], function(n) {
* return n % 2 == 1;
* });
* // => 3
*/
var findLast = createFind(findLastIndex);
/**
* Creates a flattened array of values by running each element in `collection`
* thru `iteratee` and flattening the mapped results. The iteratee is invoked
* with three arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new flattened array.
* @example
*
* function duplicate(n) {
* return [n, n];
* }
*
* _.flatMap([1, 2], duplicate);
* // => [1, 1, 2, 2]
*/
function flatMap(collection, iteratee) {
return baseFlatten(map(collection, iteratee), 1);
}
/**
* This method is like `_.flatMap` except that it recursively flattens the
* mapped results.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new flattened array.
* @example
*
* function duplicate(n) {
* return [[[n, n]]];
* }
*
* _.flatMapDeep([1, 2], duplicate);
* // => [1, 1, 2, 2]
*/
function flatMapDeep(collection, iteratee) {
return baseFlatten(map(collection, iteratee), INFINITY);
}
/**
* This method is like `_.flatMap` except that it recursively flattens the
* mapped results up to `depth` times.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {number} [depth=1] The maximum recursion depth.
* @returns {Array} Returns the new flattened array.
* @example
*
* function duplicate(n) {
* return [[[n, n]]];
* }
*
* _.flatMapDepth([1, 2], duplicate, 2);
* // => [[1, 1], [2, 2]]
*/
function flatMapDepth(collection, iteratee, depth) {
depth = depth === undefined ? 1 : toInteger(depth);
return baseFlatten(map(collection, iteratee), depth);
}
/**
* Iterates over elements of `collection` and invokes `iteratee` for each element.
* The iteratee is invoked with three arguments: (value, index|key, collection).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* **Note:** As with other "Collections" methods, objects with a "length"
* property are iterated like arrays. To avoid this behavior use `_.forIn`
* or `_.forOwn` for object iteration.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias each
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
* @see _.forEachRight
* @example
*
* _.forEach([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `1` then `2`.
*
* _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forEach(collection, iteratee) {
var func = isArray(collection) ? arrayEach : baseEach;
return func(collection, getIteratee(iteratee, 3));
}
/**
* This method is like `_.forEach` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @since 2.0.0
* @alias eachRight
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
* @see _.forEach
* @example
*
* _.forEachRight([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `2` then `1`.
*/
function forEachRight(collection, iteratee) {
var func = isArray(collection) ? arrayEachRight : baseEachRight;
return func(collection, getIteratee(iteratee, 3));
}
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The order of grouped values
* is determined by the order they occur in `collection`. The corresponding
* value of each key is an array of elements responsible for generating the
* key. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.groupBy([6.1, 4.2, 6.3], Math.floor);
* // => { '4': [4.2], '6': [6.1, 6.3] }
*
* // The `_.property` iteratee shorthand.
* _.groupBy(['one', 'two', 'three'], 'length');
* // => { '3': ['one', 'two'], '5': ['three'] }
*/
var groupBy = createAggregator(function(result, value, key) {
if (hasOwnProperty.call(result, key)) {
result[key].push(value);
} else {
baseAssignValue(result, key, [value]);
}
});
/**
* Checks if `value` is in `collection`. If `collection` is a string, it's
* checked for a substring of `value`, otherwise
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* is used for equality comparisons. If `fromIndex` is negative, it's used as
* the offset from the end of `collection`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {boolean} Returns `true` if `value` is found, else `false`.
* @example
*
* _.includes([1, 2, 3], 1);
* // => true
*
* _.includes([1, 2, 3], 1, 2);
* // => false
*
* _.includes({ 'a': 1, 'b': 2 }, 1);
* // => true
*
* _.includes('abcd', 'bc');
* // => true
*/
function includes(collection, value, fromIndex, guard) {
collection = isArrayLike(collection) ? collection : values(collection);
fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;
var length = collection.length;
if (fromIndex < 0) {
fromIndex = nativeMax(length + fromIndex, 0);
}
return isString(collection)
? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
: (!!length && baseIndexOf(collection, value, fromIndex) > -1);
}
/**
* Invokes the method at `path` of each element in `collection`, returning
* an array of the results of each invoked method. Any additional arguments
* are provided to each invoked method. If `path` is a function, it's invoked
* for, and `this` bound to, each element in `collection`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Array|Function|string} path The path of the method to invoke or
* the function invoked per iteration.
* @param {...*} [args] The arguments to invoke each method with.
* @returns {Array} Returns the array of results.
* @example
*
* _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
* // => [[1, 5, 7], [1, 2, 3]]
*
* _.invokeMap([123, 456], String.prototype.split, '');
* // => [['1', '2', '3'], ['4', '5', '6']]
*/
var invokeMap = baseRest(function(collection, path, args) {
var index = -1,
isFunc = typeof path == 'function',
result = isArrayLike(collection) ? Array(collection.length) : [];
baseEach(collection, function(value) {
result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args);
});
return result;
});
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The corresponding value of
* each key is the last element responsible for generating the key. The
* iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* var array = [
* { 'dir': 'left', 'code': 97 },
* { 'dir': 'right', 'code': 100 }
* ];
*
* _.keyBy(array, function(o) {
* return String.fromCharCode(o.code);
* });
* // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
*
* _.keyBy(array, 'dir');
* // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
*/
var keyBy = createAggregator(function(result, value, key) {
baseAssignValue(result, key, value);
});
/**
* Creates an array of values by running each element in `collection` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
*
* The guarded methods are:
* `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
* `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
* `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
* `template`, `trim`, `trimEnd`, `trimStart`, and `words`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
* @example
*
* function square(n) {
* return n * n;
* }
*
* _.map([4, 8], square);
* // => [16, 64]
*
* _.map({ 'a': 4, 'b': 8 }, square);
* // => [16, 64] (iteration order is not guaranteed)
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* // The `_.property` iteratee shorthand.
* _.map(users, 'user');
* // => ['barney', 'fred']
*/
function map(collection, iteratee) {
var func = isArray(collection) ? arrayMap : baseMap;
return func(collection, getIteratee(iteratee, 3));
}
/**
* This method is like `_.sortBy` except that it allows specifying the sort
* orders of the iteratees to sort by. If `orders` is unspecified, all values
* are sorted in ascending order. Otherwise, specify an order of "desc" for
* descending or "asc" for ascending sort order of corresponding values.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
* The iteratees to sort by.
* @param {string[]} [orders] The sort orders of `iteratees`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 34 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'barney', 'age': 36 }
* ];
*
* // Sort by `user` in ascending order and by `age` in descending order.
* _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
*/
function orderBy(collection, iteratees, orders, guard) {
if (collection == null) {
return [];
}
if (!isArray(iteratees)) {
iteratees = iteratees == null ? [] : [iteratees];
}
orders = guard ? undefined : orders;
if (!isArray(orders)) {
orders = orders == null ? [] : [orders];
}
return baseOrderBy(collection, iteratees, orders);
}
/**
* Creates an array of elements split into two groups, the first of which
* contains elements `predicate` returns truthy for, the second of which
* contains elements `predicate` returns falsey for. The predicate is
* invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the array of grouped elements.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true },
* { 'user': 'pebbles', 'age': 1, 'active': false }
* ];
*
* _.partition(users, function(o) { return o.active; });
* // => objects for [['fred'], ['barney', 'pebbles']]
*
* // The `_.matches` iteratee shorthand.
* _.partition(users, { 'age': 1, 'active': false });
* // => objects for [['pebbles'], ['barney', 'fred']]
*
* // The `_.matchesProperty` iteratee shorthand.
* _.partition(users, ['active', false]);
* // => objects for [['barney', 'pebbles'], ['fred']]
*
* // The `_.property` iteratee shorthand.
* _.partition(users, 'active');
* // => objects for [['fred'], ['barney', 'pebbles']]
*/
var partition = createAggregator(function(result, value, key) {
result[key ? 0 : 1].push(value);
}, function() { return [[], []]; });
/**
* Reduces `collection` to a value which is the accumulated result of running
* each element in `collection` thru `iteratee`, where each successive
* invocation is supplied the return value of the previous. If `accumulator`
* is not given, the first element of `collection` is used as the initial
* value. The iteratee is invoked with four arguments:
* (accumulator, value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.reduce`, `_.reduceRight`, and `_.transform`.
*
* The guarded methods are:
* `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
* and `sortBy`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @returns {*} Returns the accumulated value.
* @see _.reduceRight
* @example
*
* _.reduce([1, 2], function(sum, n) {
* return sum + n;
* }, 0);
* // => 3
*
* _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
* (result[value] || (result[value] = [])).push(key);
* return result;
* }, {});
* // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
*/
function reduce(collection, iteratee, accumulator) {
var func = isArray(collection) ? arrayReduce : baseReduce,
initAccum = arguments.length < 3;
return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach);
}
/**
* This method is like `_.reduce` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @returns {*} Returns the accumulated value.
* @see _.reduce
* @example
*
* var array = [[0, 1], [2, 3], [4, 5]];
*
* _.reduceRight(array, function(flattened, other) {
* return flattened.concat(other);
* }, []);
* // => [4, 5, 2, 3, 0, 1]
*/
function reduceRight(collection, iteratee, accumulator) {
var func = isArray(collection) ? arrayReduceRight : baseReduce,
initAccum = arguments.length < 3;
return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight);
}
/**
* The opposite of `_.filter`; this method returns the elements of `collection`
* that `predicate` does **not** return truthy for.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
* @see _.filter
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true }
* ];
*
* _.reject(users, function(o) { return !o.active; });
* // => objects for ['fred']
*
* // The `_.matches` iteratee shorthand.
* _.reject(users, { 'age': 40, 'active': true });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.reject(users, ['active', false]);
* // => objects for ['fred']
*
* // The `_.property` iteratee shorthand.
* _.reject(users, 'active');
* // => objects for ['barney']
*/
function reject(collection, predicate) {
var func = isArray(collection) ? arrayFilter : baseFilter;
return func(collection, negate(getIteratee(predicate, 3)));
}
/**
* Gets a random element from `collection`.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Collection
* @param {Array|Object} collection The collection to sample.
* @returns {*} Returns the random element.
* @example
*
* _.sample([1, 2, 3, 4]);
* // => 2
*/
function sample(collection) {
var func = isArray(collection) ? arraySample : baseSample;
return func(collection);
}
/**
* Gets `n` random elements at unique keys from `collection` up to the
* size of `collection`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to sample.
* @param {number} [n=1] The number of elements to sample.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the random elements.
* @example
*
* _.sampleSize([1, 2, 3], 2);
* // => [3, 1]
*
* _.sampleSize([1, 2, 3], 4);
* // => [2, 3, 1]
*/
function sampleSize(collection, n, guard) {
if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) {
n = 1;
} else {
n = toInteger(n);
}
var func = isArray(collection) ? arraySampleSize : baseSampleSize;
return func(collection, n);
}
/**
* Creates an array of shuffled values, using a version of the
* [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to shuffle.
* @returns {Array} Returns the new shuffled array.
* @example
*
* _.shuffle([1, 2, 3, 4]);
* // => [4, 1, 3, 2]
*/
function shuffle(collection) {
var func = isArray(collection) ? arrayShuffle : baseShuffle;
return func(collection);
}
/**
* Gets the size of `collection` by returning its length for array-like
* values or the number of own enumerable string keyed properties for objects.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @returns {number} Returns the collection size.
* @example
*
* _.size([1, 2, 3]);
* // => 3
*
* _.size({ 'a': 1, 'b': 2 });
* // => 2
*
* _.size('pebbles');
* // => 7
*/
function size(collection) {
if (collection == null) {
return 0;
}
if (isArrayLike(collection)) {
return isString(collection) ? stringSize(collection) : collection.length;
}
var tag = getTag(collection);
if (tag == mapTag || tag == setTag) {
return collection.size;
}
return baseKeys(collection).length;
}
/**
* Checks if `predicate` returns truthy for **any** element of `collection`.
* Iteration is stopped once `predicate` returns truthy. The predicate is
* invoked with three arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
* @example
*
* _.some([null, 0, 'yes', false], Boolean);
* // => true
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.some(users, { 'user': 'barney', 'active': false });
* // => false
*
* // The `_.matchesProperty` iteratee shorthand.
* _.some(users, ['active', false]);
* // => true
*
* // The `_.property` iteratee shorthand.
* _.some(users, 'active');
* // => true
*/
function some(collection, predicate, guard) {
var func = isArray(collection) ? arraySome : baseSome;
if (guard && isIterateeCall(collection, predicate, guard)) {
predicate = undefined;
}
return func(collection, getIteratee(predicate, 3));
}
/**
* Creates an array of elements, sorted in ascending order by the results of
* running each element in a collection thru each iteratee. This method
* performs a stable sort, that is, it preserves the original sort order of
* equal elements. The iteratees are invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {...(Function|Function[])} [iteratees=[_.identity]]
* The iteratees to sort by.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 30 },
* { 'user': 'barney', 'age': 34 }
* ];
*
* _.sortBy(users, [function(o) { return o.user; }]);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]
*
* _.sortBy(users, ['user', 'age']);
* // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]
*/
var sortBy = baseRest(function(collection, iteratees) {
if (collection == null) {
return [];
}
var length = iteratees.length;
if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
iteratees = [];
} else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
iteratees = [iteratees[0]];
}
return baseOrderBy(collection, baseFlatten(iteratees, 1), []);
});
/*------------------------------------------------------------------------*/
/**
* Gets the timestamp of the number of milliseconds that have elapsed since
* the Unix epoch (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Date
* @returns {number} Returns the timestamp.
* @example
*
* _.defer(function(stamp) {
* console.log(_.now() - stamp);
* }, _.now());
* // => Logs the number of milliseconds it took for the deferred invocation.
*/
var now = ctxNow || function() {
return root.Date.now();
};
/*------------------------------------------------------------------------*/
/**
* The opposite of `_.before`; this method creates a function that invokes
* `func` once it's called `n` or more times.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {number} n The number of calls before `func` is invoked.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var saves = ['profile', 'settings'];
*
* var done = _.after(saves.length, function() {
* console.log('done saving!');
* });
*
* _.forEach(saves, function(type) {
* asyncSave({ 'type': type, 'complete': done });
* });
* // => Logs 'done saving!' after the two async saves have completed.
*/
function after(n, func) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
n = toInteger(n);
return function() {
if (--n < 1) {
return func.apply(this, arguments);
}
};
}
/**
* Creates a function that invokes `func`, with up to `n` arguments,
* ignoring any additional arguments.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} func The function to cap arguments for.
* @param {number} [n=func.length] The arity cap.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new capped function.
* @example
*
* _.map(['6', '8', '10'], _.ary(parseInt, 1));
* // => [6, 8, 10]
*/
function ary(func, n, guard) {
n = guard ? undefined : n;
n = (func && n == null) ? func.length : n;
return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);
}
/**
* Creates a function that invokes `func`, with the `this` binding and arguments
* of the created function, while it's called less than `n` times. Subsequent
* calls to the created function return the result of the last `func` invocation.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {number} n The number of calls at which `func` is no longer invoked.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* jQuery(element).on('click', _.before(5, addContactToList));
* // => Allows adding up to 4 contacts to the list.
*/
function before(n, func) {
var result;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
n = toInteger(n);
return function() {
if (--n > 0) {
result = func.apply(this, arguments);
}
if (n <= 1) {
func = undefined;
}
return result;
};
}
/**
* Creates a function that invokes `func` with the `this` binding of `thisArg`
* and `partials` prepended to the arguments it receives.
*
* The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for partially applied arguments.
*
* **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
* property of bound functions.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* function greet(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
*
* var object = { 'user': 'fred' };
*
* var bound = _.bind(greet, object, 'hi');
* bound('!');
* // => 'hi fred!'
*
* // Bound with placeholders.
* var bound = _.bind(greet, object, _, '!');
* bound('hi');
* // => 'hi fred!'
*/
var bind = baseRest(function(func, thisArg, partials) {
var bitmask = WRAP_BIND_FLAG;
if (partials.length) {
var holders = replaceHolders(partials, getHolder(bind));
bitmask |= WRAP_PARTIAL_FLAG;
}
return createWrap(func, bitmask, thisArg, partials, holders);
});
/**
* Creates a function that invokes the method at `object[key]` with `partials`
* prepended to the arguments it receives.
*
* This method differs from `_.bind` by allowing bound functions to reference
* methods that may be redefined or don't yet exist. See
* [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
* for more details.
*
* The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* @static
* @memberOf _
* @since 0.10.0
* @category Function
* @param {Object} object The object to invoke the method on.
* @param {string} key The key of the method.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* var object = {
* 'user': 'fred',
* 'greet': function(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
* };
*
* var bound = _.bindKey(object, 'greet', 'hi');
* bound('!');
* // => 'hi fred!'
*
* object.greet = function(greeting, punctuation) {
* return greeting + 'ya ' + this.user + punctuation;
* };
*
* bound('!');
* // => 'hiya fred!'
*
* // Bound with placeholders.
* var bound = _.bindKey(object, 'greet', _, '!');
* bound('hi');
* // => 'hiya fred!'
*/
var bindKey = baseRest(function(object, key, partials) {
var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;
if (partials.length) {
var holders = replaceHolders(partials, getHolder(bindKey));
bitmask |= WRAP_PARTIAL_FLAG;
}
return createWrap(key, bitmask, object, partials, holders);
});
/**
* Creates a function that accepts arguments of `func` and either invokes
* `func` returning its result, if at least `arity` number of arguments have
* been provided, or returns a function that accepts the remaining `func`
* arguments, and so on. The arity of `func` may be specified if `func.length`
* is not sufficient.
*
* The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for provided arguments.
*
* **Note:** This method doesn't set the "length" property of curried functions.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Function
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new curried function.
* @example
*
* var abc = function(a, b, c) {
* return [a, b, c];
* };
*
* var curried = _.curry(abc);
*
* curried(1)(2)(3);
* // => [1, 2, 3]
*
* curried(1, 2)(3);
* // => [1, 2, 3]
*
* curried(1, 2, 3);
* // => [1, 2, 3]
*
* // Curried with placeholders.
* curried(1)(_, 3)(2);
* // => [1, 2, 3]
*/
function curry(func, arity, guard) {
arity = guard ? undefined : arity;
var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
result.placeholder = curry.placeholder;
return result;
}
/**
* This method is like `_.curry` except that arguments are applied to `func`
* in the manner of `_.partialRight` instead of `_.partial`.
*
* The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for provided arguments.
*
* **Note:** This method doesn't set the "length" property of curried functions.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new curried function.
* @example
*
* var abc = function(a, b, c) {
* return [a, b, c];
* };
*
* var curried = _.curryRight(abc);
*
* curried(3)(2)(1);
* // => [1, 2, 3]
*
* curried(2, 3)(1);
* // => [1, 2, 3]
*
* curried(1, 2, 3);
* // => [1, 2, 3]
*
* // Curried with placeholders.
* curried(3)(1, _)(2);
* // => [1, 2, 3]
*/
function curryRight(func, arity, guard) {
arity = guard ? undefined : arity;
var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
result.placeholder = curryRight.placeholder;
return result;
}
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
* delayed `func` invocations and a `flush` method to immediately invoke them.
* Provide `options` to indicate whether `func` should be invoked on the
* leading and/or trailing edge of the `wait` timeout. The `func` is invoked
* with the last arguments provided to the debounced function. Subsequent
* calls to the debounced function return the result of the last `func`
* invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the debounced function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to debounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=false]
* Specify invoking on the leading edge of the timeout.
* @param {number} [options.maxWait]
* The maximum time `func` is allowed to be delayed before it's invoked.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // Avoid costly calculations while the window size is in flux.
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // Invoke `sendMail` when clicked, debouncing subsequent calls.
* jQuery(element).on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // Ensure `batchLog` is invoked once after 1 second of debounced calls.
* var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
* var source = new EventSource('/stream');
* jQuery(source).on('message', debounced);
*
* // Cancel the trailing debounced invocation.
* jQuery(window).on('popstate', debounced.cancel);
*/
function debounce(func, wait, options) {
var lastArgs,
lastThis,
maxWait,
result,
timerId,
lastCallTime,
lastInvokeTime = 0,
leading = false,
maxing = false,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = toNumber(wait) || 0;
if (isObject(options)) {
leading = !!options.leading;
maxing = 'maxWait' in options;
maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
function invokeFunc(time) {
var args = lastArgs,
thisArg = lastThis;
lastArgs = lastThis = undefined;
lastInvokeTime = time;
result = func.apply(thisArg, args);
return result;
}
function leadingEdge(time) {
// Reset any `maxWait` timer.
lastInvokeTime = time;
// Start the timer for the trailing edge.
timerId = setTimeout(timerExpired, wait);
// Invoke the leading edge.
return leading ? invokeFunc(time) : result;
}
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime,
timeWaiting = wait - timeSinceLastCall;
return maxing
? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)
: timeWaiting;
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime;
// Either this is the first call, activity has stopped and we're at the
// trailing edge, the system time has gone backwards and we're treating
// it as the trailing edge, or we've hit the `maxWait` limit.
return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
(timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
}
function timerExpired() {
var time = now();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
// Restart the timer.
timerId = setTimeout(timerExpired, remainingWait(time));
}
function trailingEdge(time) {
timerId = undefined;
// Only invoke if we have `lastArgs` which means `func` has been
// debounced at least once.
if (trailing && lastArgs) {
return invokeFunc(time);
}
lastArgs = lastThis = undefined;
return result;
}
function cancel() {
if (timerId !== undefined) {
clearTimeout(timerId);
}
lastInvokeTime = 0;
lastArgs = lastCallTime = lastThis = timerId = undefined;
}
function flush() {
return timerId === undefined ? result : trailingEdge(now());
}
function debounced() {
var time = now(),
isInvoking = shouldInvoke(time);
lastArgs = arguments;
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (timerId === undefined) {
return leadingEdge(lastCallTime);
}
if (maxing) {
// Handle invocations in a tight loop.
clearTimeout(timerId);
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === undefined) {
timerId = setTimeout(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}
/**
* Defers invoking the `func` until the current call stack has cleared. Any
* additional arguments are provided to `func` when it's invoked.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to defer.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {number} Returns the timer id.
* @example
*
* _.defer(function(text) {
* console.log(text);
* }, 'deferred');
* // => Logs 'deferred' after one millisecond.
*/
var defer = baseRest(function(func, args) {
return baseDelay(func, 1, args);
});
/**
* Invokes `func` after `wait` milliseconds. Any additional arguments are
* provided to `func` when it's invoked.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {number} Returns the timer id.
* @example
*
* _.delay(function(text) {
* console.log(text);
* }, 1000, 'later');
* // => Logs 'later' after one second.
*/
var delay = baseRest(function(func, wait, args) {
return baseDelay(func, toNumber(wait) || 0, args);
});
/**
* Creates a function that invokes `func` with arguments reversed.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Function
* @param {Function} func The function to flip arguments for.
* @returns {Function} Returns the new flipped function.
* @example
*
* var flipped = _.flip(function() {
* return _.toArray(arguments);
* });
*
* flipped('a', 'b', 'c', 'd');
* // => ['d', 'c', 'b', 'a']
*/
function flip(func) {
return createWrap(func, WRAP_FLIP_FLAG);
}
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided, it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is used as the map cache key. The `func`
* is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the
* [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
* method interface of `clear`, `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoized function.
* @example
*
* var object = { 'a': 1, 'b': 2 };
* var other = { 'c': 3, 'd': 4 };
*
* var values = _.memoize(_.values);
* values(object);
* // => [1, 2]
*
* values(other);
* // => [3, 4]
*
* object.a = 2;
* values(object);
* // => [1, 2]
*
* // Modify the result cache.
* values.cache.set(object, ['a', 'b']);
* values(object);
* // => ['a', 'b']
*
* // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
*/
function memoize(func, resolver) {
if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var args = arguments,
key = resolver ? resolver.apply(this, args) : args[0],
cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
memoized.cache = cache.set(key, result) || cache;
return result;
};
memoized.cache = new (memoize.Cache || MapCache);
return memoized;
}
// Expose `MapCache`.
memoize.Cache = MapCache;
/**
* Creates a function that negates the result of the predicate `func`. The
* `func` predicate is invoked with the `this` binding and arguments of the
* created function.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} predicate The predicate to negate.
* @returns {Function} Returns the new negated function.
* @example
*
* function isEven(n) {
* return n % 2 == 0;
* }
*
* _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
* // => [1, 3, 5]
*/
function negate(predicate) {
if (typeof predicate != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return function() {
var args = arguments;
switch (args.length) {
case 0: return !predicate.call(this);
case 1: return !predicate.call(this, args[0]);
case 2: return !predicate.call(this, args[0], args[1]);
case 3: return !predicate.call(this, args[0], args[1], args[2]);
}
return !predicate.apply(this, args);
};
}
/**
* Creates a function that is restricted to invoking `func` once. Repeat calls
* to the function return the value of the first invocation. The `func` is
* invoked with the `this` binding and arguments of the created function.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var initialize = _.once(createApplication);
* initialize();
* initialize();
* // => `createApplication` is invoked once
*/
function once(func) {
return before(2, func);
}
/**
* Creates a function that invokes `func` with its arguments transformed.
*
* @static
* @since 4.0.0
* @memberOf _
* @category Function
* @param {Function} func The function to wrap.
* @param {...(Function|Function[])} [transforms=[_.identity]]
* The argument transforms.
* @returns {Function} Returns the new function.
* @example
*
* function doubled(n) {
* return n * 2;
* }
*
* function square(n) {
* return n * n;
* }
*
* var func = _.overArgs(function(x, y) {
* return [x, y];
* }, [square, doubled]);
*
* func(9, 3);
* // => [81, 6]
*
* func(10, 5);
* // => [100, 10]
*/
var overArgs = castRest(function(func, transforms) {
transforms = (transforms.length == 1 && isArray(transforms[0]))
? arrayMap(transforms[0], baseUnary(getIteratee()))
: arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee()));
var funcsLength = transforms.length;
return baseRest(function(args) {
var index = -1,
length = nativeMin(args.length, funcsLength);
while (++index < length) {
args[index] = transforms[index].call(this, args[index]);
}
return apply(func, this, args);
});
});
/**
* Creates a function that invokes `func` with `partials` prepended to the
* arguments it receives. This method is like `_.bind` except it does **not**
* alter the `this` binding.
*
* The `_.partial.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 0.2.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var sayHelloTo = _.partial(greet, 'hello');
* sayHelloTo('fred');
* // => 'hello fred'
*
* // Partially applied with placeholders.
* var greetFred = _.partial(greet, _, 'fred');
* greetFred('hi');
* // => 'hi fred'
*/
var partial = baseRest(function(func, partials) {
var holders = replaceHolders(partials, getHolder(partial));
return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders);
});
/**
* This method is like `_.partial` except that partially applied arguments
* are appended to the arguments it receives.
*
* The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var greetFred = _.partialRight(greet, 'fred');
* greetFred('hi');
* // => 'hi fred'
*
* // Partially applied with placeholders.
* var sayHelloTo = _.partialRight(greet, 'hello', _);
* sayHelloTo('fred');
* // => 'hello fred'
*/
var partialRight = baseRest(function(func, partials) {
var holders = replaceHolders(partials, getHolder(partialRight));
return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders);
});
/**
* Creates a function that invokes `func` with arguments arranged according
* to the specified `indexes` where the argument value at the first index is
* provided as the first argument, the argument value at the second index is
* provided as the second argument, and so on.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} func The function to rearrange arguments for.
* @param {...(number|number[])} indexes The arranged argument indexes.
* @returns {Function} Returns the new function.
* @example
*
* var rearged = _.rearg(function(a, b, c) {
* return [a, b, c];
* }, [2, 0, 1]);
*
* rearged('b', 'c', 'a')
* // => ['a', 'b', 'c']
*/
var rearg = flatRest(function(func, indexes) {
return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);
});
/**
* Creates a function that invokes `func` with the `this` binding of the
* created function and arguments from `start` and beyond provided as
* an array.
*
* **Note:** This method is based on the
* [rest parameter](https://mdn.io/rest_parameters).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Function
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.rest(function(what, names) {
* return what + ' ' + _.initial(names).join(', ') +
* (_.size(names) > 1 ? ', & ' : '') + _.last(names);
* });
*
* say('hello', 'fred', 'barney', 'pebbles');
* // => 'hello fred, barney, & pebbles'
*/
function rest(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
start = start === undefined ? start : toInteger(start);
return baseRest(func, start);
}
/**
* Creates a function that invokes `func` with the `this` binding of the
* create function and an array of arguments much like
* [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply).
*
* **Note:** This method is based on the
* [spread operator](https://mdn.io/spread_operator).
*
* @static
* @memberOf _
* @since 3.2.0
* @category Function
* @param {Function} func The function to spread arguments over.
* @param {number} [start=0] The start position of the spread.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.spread(function(who, what) {
* return who + ' says ' + what;
* });
*
* say(['fred', 'hello']);
* // => 'fred says hello'
*
* var numbers = Promise.all([
* Promise.resolve(40),
* Promise.resolve(36)
* ]);
*
* numbers.then(_.spread(function(x, y) {
* return x + y;
* }));
* // => a Promise of 76
*/
function spread(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
start = start == null ? 0 : nativeMax(toInteger(start), 0);
return baseRest(function(args) {
var array = args[start],
otherArgs = castSlice(args, 0, start);
if (array) {
arrayPush(otherArgs, array);
}
return apply(func, this, otherArgs);
});
}
/**
* Creates a throttled function that only invokes `func` at most once per
* every `wait` milliseconds. The throttled function comes with a `cancel`
* method to cancel delayed `func` invocations and a `flush` method to
* immediately invoke them. Provide `options` to indicate whether `func`
* should be invoked on the leading and/or trailing edge of the `wait`
* timeout. The `func` is invoked with the last arguments provided to the
* throttled function. Subsequent calls to the throttled function return the
* result of the last `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the throttled function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.throttle` and `_.debounce`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to throttle.
* @param {number} [wait=0] The number of milliseconds to throttle invocations to.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=true]
* Specify invoking on the leading edge of the timeout.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new throttled function.
* @example
*
* // Avoid excessively updating the position while scrolling.
* jQuery(window).on('scroll', _.throttle(updatePosition, 100));
*
* // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
* var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
* jQuery(element).on('click', throttled);
*
* // Cancel the trailing throttled invocation.
* jQuery(window).on('popstate', throttled.cancel);
*/
function throttle(func, wait, options) {
var leading = true,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
if (isObject(options)) {
leading = 'leading' in options ? !!options.leading : leading;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
return debounce(func, wait, {
'leading': leading,
'maxWait': wait,
'trailing': trailing
});
}
/**
* Creates a function that accepts up to one argument, ignoring any
* additional arguments.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Function
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
* @example
*
* _.map(['6', '8', '10'], _.unary(parseInt));
* // => [6, 8, 10]
*/
function unary(func) {
return ary(func, 1);
}
/**
* Creates a function that provides `value` to `wrapper` as its first
* argument. Any additional arguments provided to the function are appended
* to those provided to the `wrapper`. The wrapper is invoked with the `this`
* binding of the created function.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {*} value The value to wrap.
* @param {Function} [wrapper=identity] The wrapper function.
* @returns {Function} Returns the new function.
* @example
*
* var p = _.wrap(_.escape, function(func, text) {
* return '<p>' + func(text) + '</p>';
* });
*
* p('fred, barney, & pebbles');
* // => '<p>fred, barney, & pebbles</p>'
*/
function wrap(value, wrapper) {
return partial(castFunction(wrapper), value);
}
/*------------------------------------------------------------------------*/
/**
* Casts `value` as an array if it's not one.
*
* @static
* @memberOf _
* @since 4.4.0
* @category Lang
* @param {*} value The value to inspect.
* @returns {Array} Returns the cast array.
* @example
*
* _.castArray(1);
* // => [1]
*
* _.castArray({ 'a': 1 });
* // => [{ 'a': 1 }]
*
* _.castArray('abc');
* // => ['abc']
*
* _.castArray(null);
* // => [null]
*
* _.castArray(undefined);
* // => [undefined]
*
* _.castArray();
* // => []
*
* var array = [1, 2, 3];
* console.log(_.castArray(array) === array);
* // => true
*/
function castArray() {
if (!arguments.length) {
return [];
}
var value = arguments[0];
return isArray(value) ? value : [value];
}
/**
* Creates a shallow clone of `value`.
*
* **Note:** This method is loosely based on the
* [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
* and supports cloning arrays, array buffers, booleans, date objects, maps,
* numbers, `Object` objects, regexes, sets, strings, symbols, and typed
* arrays. The own enumerable properties of `arguments` objects are cloned
* as plain objects. An empty object is returned for uncloneable values such
* as error objects, functions, DOM nodes, and WeakMaps.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to clone.
* @returns {*} Returns the cloned value.
* @see _.cloneDeep
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var shallow = _.clone(objects);
* console.log(shallow[0] === objects[0]);
* // => true
*/
function clone(value) {
return baseClone(value, CLONE_SYMBOLS_FLAG);
}
/**
* This method is like `_.clone` except that it accepts `customizer` which
* is invoked to produce the cloned value. If `customizer` returns `undefined`,
* cloning is handled by the method instead. The `customizer` is invoked with
* up to four arguments; (value [, index|key, object, stack]).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to clone.
* @param {Function} [customizer] The function to customize cloning.
* @returns {*} Returns the cloned value.
* @see _.cloneDeepWith
* @example
*
* function customizer(value) {
* if (_.isElement(value)) {
* return value.cloneNode(false);
* }
* }
*
* var el = _.cloneWith(document.body, customizer);
*
* console.log(el === document.body);
* // => false
* console.log(el.nodeName);
* // => 'BODY'
* console.log(el.childNodes.length);
* // => 0
*/
function cloneWith(value, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return baseClone(value, CLONE_SYMBOLS_FLAG, customizer);
}
/**
* This method is like `_.clone` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Lang
* @param {*} value The value to recursively clone.
* @returns {*} Returns the deep cloned value.
* @see _.clone
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var deep = _.cloneDeep(objects);
* console.log(deep[0] === objects[0]);
* // => false
*/
function cloneDeep(value) {
return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);
}
/**
* This method is like `_.cloneWith` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to recursively clone.
* @param {Function} [customizer] The function to customize cloning.
* @returns {*} Returns the deep cloned value.
* @see _.cloneWith
* @example
*
* function customizer(value) {
* if (_.isElement(value)) {
* return value.cloneNode(true);
* }
* }
*
* var el = _.cloneDeepWith(document.body, customizer);
*
* console.log(el === document.body);
* // => false
* console.log(el.nodeName);
* // => 'BODY'
* console.log(el.childNodes.length);
* // => 20
*/
function cloneDeepWith(value, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer);
}
/**
* Checks if `object` conforms to `source` by invoking the predicate
* properties of `source` with the corresponding property values of `object`.
*
* **Note:** This method is equivalent to `_.conforms` when `source` is
* partially applied.
*
* @static
* @memberOf _
* @since 4.14.0
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property predicates to conform to.
* @returns {boolean} Returns `true` if `object` conforms, else `false`.
* @example
*
* var object = { 'a': 1, 'b': 2 };
*
* _.conformsTo(object, { 'b': function(n) { return n > 1; } });
* // => true
*
* _.conformsTo(object, { 'b': function(n) { return n > 2; } });
* // => false
*/
function conformsTo(object, source) {
return source == null || baseConformsTo(object, source, keys(source));
}
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
/**
* Checks if `value` is greater than `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is greater than `other`,
* else `false`.
* @see _.lt
* @example
*
* _.gt(3, 1);
* // => true
*
* _.gt(3, 3);
* // => false
*
* _.gt(1, 3);
* // => false
*/
var gt = createRelationalOperation(baseGt);
/**
* Checks if `value` is greater than or equal to `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is greater than or equal to
* `other`, else `false`.
* @see _.lte
* @example
*
* _.gte(3, 1);
* // => true
*
* _.gte(3, 3);
* // => true
*
* _.gte(1, 3);
* // => false
*/
var gte = createRelationalOperation(function(value, other) {
return value >= other;
});
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
!propertyIsEnumerable.call(value, 'callee');
};
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
/**
* Checks if `value` is classified as an `ArrayBuffer` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
* @example
*
* _.isArrayBuffer(new ArrayBuffer(2));
* // => true
*
* _.isArrayBuffer(new Array(2));
* // => false
*/
var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer;
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
/**
* Checks if `value` is classified as a boolean primitive or object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a boolean, else `false`.
* @example
*
* _.isBoolean(false);
* // => true
*
* _.isBoolean(null);
* // => false
*/
function isBoolean(value) {
return value === true || value === false ||
(isObjectLike(value) && baseGetTag(value) == boolTag);
}
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || stubFalse;
/**
* Checks if `value` is classified as a `Date` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a date object, else `false`.
* @example
*
* _.isDate(new Date);
* // => true
*
* _.isDate('Mon April 23 2012');
* // => false
*/
var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate;
/**
* Checks if `value` is likely a DOM element.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
* @example
*
* _.isElement(document.body);
* // => true
*
* _.isElement('<body>');
* // => false
*/
function isElement(value) {
return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value);
}
/**
* Checks if `value` is an empty object, collection, map, or set.
*
* Objects are considered empty if they have no own enumerable string keyed
* properties.
*
* Array-like values such as `arguments` objects, arrays, buffers, strings, or
* jQuery-like collections are considered empty if they have a `length` of `0`.
* Similarly, maps and sets are considered empty if they have a `size` of `0`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
* @example
*
* _.isEmpty(null);
* // => true
*
* _.isEmpty(true);
* // => true
*
* _.isEmpty(1);
* // => true
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({ 'a': 1 });
* // => false
*/
function isEmpty(value) {
if (value == null) {
return true;
}
if (isArrayLike(value) &&
(isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
isBuffer(value) || isTypedArray(value) || isArguments(value))) {
return !value.length;
}
var tag = getTag(value);
if (tag == mapTag || tag == setTag) {
return !value.size;
}
if (isPrototype(value)) {
return !baseKeys(value).length;
}
for (var key in value) {
if (hasOwnProperty.call(value, key)) {
return false;
}
}
return true;
}
/**
* Performs a deep comparison between two values to determine if they are
* equivalent.
*
* **Note:** This method supports comparing arrays, array buffers, booleans,
* date objects, error objects, maps, numbers, `Object` objects, regexes,
* sets, strings, symbols, and typed arrays. `Object` objects are compared
* by their own, not inherited, enumerable properties. Functions and DOM
* nodes are compared by strict equality, i.e. `===`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.isEqual(object, other);
* // => true
*
* object === other;
* // => false
*/
function isEqual(value, other) {
return baseIsEqual(value, other);
}
/**
* This method is like `_.isEqual` except that it accepts `customizer` which
* is invoked to compare values. If `customizer` returns `undefined`, comparisons
* are handled by the method instead. The `customizer` is invoked with up to
* six arguments: (objValue, othValue [, index|key, object, other, stack]).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* function isGreeting(value) {
* return /^h(?:i|ello)$/.test(value);
* }
*
* function customizer(objValue, othValue) {
* if (isGreeting(objValue) && isGreeting(othValue)) {
* return true;
* }
* }
*
* var array = ['hello', 'goodbye'];
* var other = ['hi', 'goodbye'];
*
* _.isEqualWith(array, other, customizer);
* // => true
*/
function isEqualWith(value, other, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
var result = customizer ? customizer(value, other) : undefined;
return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result;
}
/**
* Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
* `SyntaxError`, `TypeError`, or `URIError` object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an error object, else `false`.
* @example
*
* _.isError(new Error);
* // => true
*
* _.isError(Error);
* // => false
*/
function isError(value) {
if (!isObjectLike(value)) {
return false;
}
var tag = baseGetTag(value);
return tag == errorTag || tag == domExcTag ||
(typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value));
}
/**
* Checks if `value` is a finite primitive number.
*
* **Note:** This method is based on
* [`Number.isFinite`](https://mdn.io/Number/isFinite).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
* @example
*
* _.isFinite(3);
* // => true
*
* _.isFinite(Number.MIN_VALUE);
* // => true
*
* _.isFinite(Infinity);
* // => false
*
* _.isFinite('3');
* // => false
*/
function isFinite(value) {
return typeof value == 'number' && nativeIsFinite(value);
}
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
if (!isObject(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
/**
* Checks if `value` is an integer.
*
* **Note:** This method is based on
* [`Number.isInteger`](https://mdn.io/Number/isInteger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an integer, else `false`.
* @example
*
* _.isInteger(3);
* // => true
*
* _.isInteger(Number.MIN_VALUE);
* // => false
*
* _.isInteger(Infinity);
* // => false
*
* _.isInteger('3');
* // => false
*/
function isInteger(value) {
return typeof value == 'number' && value == toInteger(value);
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
/**
* Checks if `value` is classified as a `Map` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
* @example
*
* _.isMap(new Map);
* // => true
*
* _.isMap(new WeakMap);
* // => false
*/
var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;
/**
* Performs a partial deep comparison between `object` and `source` to
* determine if `object` contains equivalent property values.
*
* **Note:** This method is equivalent to `_.matches` when `source` is
* partially applied.
*
* Partial comparisons will match empty array and empty object `source`
* values against any array or object value, respectively. See `_.isEqual`
* for a list of supported value comparisons.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
* @example
*
* var object = { 'a': 1, 'b': 2 };
*
* _.isMatch(object, { 'b': 2 });
* // => true
*
* _.isMatch(object, { 'b': 1 });
* // => false
*/
function isMatch(object, source) {
return object === source || baseIsMatch(object, source, getMatchData(source));
}
/**
* This method is like `_.isMatch` except that it accepts `customizer` which
* is invoked to compare values. If `customizer` returns `undefined`, comparisons
* are handled by the method instead. The `customizer` is invoked with five
* arguments: (objValue, srcValue, index|key, object, source).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
* @example
*
* function isGreeting(value) {
* return /^h(?:i|ello)$/.test(value);
* }
*
* function customizer(objValue, srcValue) {
* if (isGreeting(objValue) && isGreeting(srcValue)) {
* return true;
* }
* }
*
* var object = { 'greeting': 'hello' };
* var source = { 'greeting': 'hi' };
*
* _.isMatchWith(object, source, customizer);
* // => true
*/
function isMatchWith(object, source, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return baseIsMatch(object, source, getMatchData(source), customizer);
}
/**
* Checks if `value` is `NaN`.
*
* **Note:** This method is based on
* [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
* global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
* `undefined` and other non-number values.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
*/
function isNaN(value) {
// An `NaN` primitive is the only value that is not equal to itself.
// Perform the `toStringTag` check first to avoid errors with some
// ActiveX objects in IE.
return isNumber(value) && value != +value;
}
/**
* Checks if `value` is a pristine native function.
*
* **Note:** This method can't reliably detect native functions in the presence
* of the core-js package because core-js circumvents this kind of detection.
* Despite multiple requests, the core-js maintainer has made it clear: any
* attempt to fix the detection will be obstructed. As a result, we're left
* with little choice but to throw an error. Unfortunately, this also affects
* packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill),
* which rely on core-js.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (isMaskable(value)) {
throw new Error(CORE_ERROR_TEXT);
}
return baseIsNative(value);
}
/**
* Checks if `value` is `null`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `null`, else `false`.
* @example
*
* _.isNull(null);
* // => true
*
* _.isNull(void 0);
* // => false
*/
function isNull(value) {
return value === null;
}
/**
* Checks if `value` is `null` or `undefined`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is nullish, else `false`.
* @example
*
* _.isNil(null);
* // => true
*
* _.isNil(void 0);
* // => true
*
* _.isNil(NaN);
* // => false
*/
function isNil(value) {
return value == null;
}
/**
* Checks if `value` is classified as a `Number` primitive or object.
*
* **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
* classified as numbers, use the `_.isFinite` method.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a number, else `false`.
* @example
*
* _.isNumber(3);
* // => true
*
* _.isNumber(Number.MIN_VALUE);
* // => true
*
* _.isNumber(Infinity);
* // => true
*
* _.isNumber('3');
* // => false
*/
function isNumber(value) {
return typeof value == 'number' ||
(isObjectLike(value) && baseGetTag(value) == numberTag);
}
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
return false;
}
var proto = getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
return typeof Ctor == 'function' && Ctor instanceof Ctor &&
funcToString.call(Ctor) == objectCtorString;
}
/**
* Checks if `value` is classified as a `RegExp` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
* @example
*
* _.isRegExp(/abc/);
* // => true
*
* _.isRegExp('/abc/');
* // => false
*/
var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;
/**
* Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754
* double precision number which isn't the result of a rounded unsafe integer.
*
* **Note:** This method is based on
* [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.
* @example
*
* _.isSafeInteger(3);
* // => true
*
* _.isSafeInteger(Number.MIN_VALUE);
* // => false
*
* _.isSafeInteger(Infinity);
* // => false
*
* _.isSafeInteger('3');
* // => false
*/
function isSafeInteger(value) {
return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is classified as a `Set` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
* @example
*
* _.isSet(new Set);
* // => true
*
* _.isSet(new WeakSet);
* // => false
*/
var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a string, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
}
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && baseGetTag(value) == symbolTag);
}
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
/**
* Checks if `value` is `undefined`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*
* _.isUndefined(null);
* // => false
*/
function isUndefined(value) {
return value === undefined;
}
/**
* Checks if `value` is classified as a `WeakMap` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a weak map, else `false`.
* @example
*
* _.isWeakMap(new WeakMap);
* // => true
*
* _.isWeakMap(new Map);
* // => false
*/
function isWeakMap(value) {
return isObjectLike(value) && getTag(value) == weakMapTag;
}
/**
* Checks if `value` is classified as a `WeakSet` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a weak set, else `false`.
* @example
*
* _.isWeakSet(new WeakSet);
* // => true
*
* _.isWeakSet(new Set);
* // => false
*/
function isWeakSet(value) {
return isObjectLike(value) && baseGetTag(value) == weakSetTag;
}
/**
* Checks if `value` is less than `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is less than `other`,
* else `false`.
* @see _.gt
* @example
*
* _.lt(1, 3);
* // => true
*
* _.lt(3, 3);
* // => false
*
* _.lt(3, 1);
* // => false
*/
var lt = createRelationalOperation(baseLt);
/**
* Checks if `value` is less than or equal to `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is less than or equal to
* `other`, else `false`.
* @see _.gte
* @example
*
* _.lte(1, 3);
* // => true
*
* _.lte(3, 3);
* // => true
*
* _.lte(3, 1);
* // => false
*/
var lte = createRelationalOperation(function(value, other) {
return value <= other;
});
/**
* Converts `value` to an array.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to convert.
* @returns {Array} Returns the converted array.
* @example
*
* _.toArray({ 'a': 1, 'b': 2 });
* // => [1, 2]
*
* _.toArray('abc');
* // => ['a', 'b', 'c']
*
* _.toArray(1);
* // => []
*
* _.toArray(null);
* // => []
*/
function toArray(value) {
if (!value) {
return [];
}
if (isArrayLike(value)) {
return isString(value) ? stringToArray(value) : copyArray(value);
}
if (symIterator && value[symIterator]) {
return iteratorToArray(value[symIterator]());
}
var tag = getTag(value),
func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);
return func(value);
}
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber(value);
if (value === INFINITY || value === -INFINITY) {
var sign = (value < 0 ? -1 : 1);
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
/**
* Converts `value` to an integer.
*
* **Note:** This method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
*/
function toInteger(value) {
var result = toFinite(value),
remainder = result % 1;
return result === result ? (remainder ? result - remainder : result) : 0;
}
/**
* Converts `value` to an integer suitable for use as the length of an
* array-like object.
*
* **Note:** This method is based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toLength(3.2);
* // => 3
*
* _.toLength(Number.MIN_VALUE);
* // => 0
*
* _.toLength(Infinity);
* // => 4294967295
*
* _.toLength('3.2');
* // => 3
*/
function toLength(value) {
return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;
}
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = baseTrim(value);
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
/**
* Converts `value` to a plain object flattening inherited enumerable string
* keyed properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/
function toPlainObject(value) {
return copyObject(value, keysIn(value));
}
/**
* Converts `value` to a safe integer. A safe integer can be compared and
* represented correctly.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toSafeInteger(3.2);
* // => 3
*
* _.toSafeInteger(Number.MIN_VALUE);
* // => 0
*
* _.toSafeInteger(Infinity);
* // => 9007199254740991
*
* _.toSafeInteger('3.2');
* // => 3
*/
function toSafeInteger(value) {
return value
? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)
: (value === 0 ? value : 0);
}
/**
* Converts `value` to a string. An empty string is returned for `null`
* and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/
function toString(value) {
return value == null ? '' : baseToString(value);
}
/*------------------------------------------------------------------------*/
/**
* Assigns own enumerable string keyed properties of source objects to the
* destination object. Source objects are applied from left to right.
* Subsequent sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object` and is loosely based on
* [`Object.assign`](https://mdn.io/Object/assign).
*
* @static
* @memberOf _
* @since 0.10.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.assignIn
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* function Bar() {
* this.c = 3;
* }
*
* Foo.prototype.b = 2;
* Bar.prototype.d = 4;
*
* _.assign({ 'a': 0 }, new Foo, new Bar);
* // => { 'a': 1, 'c': 3 }
*/
var assign = createAssigner(function(object, source) {
if (isPrototype(source) || isArrayLike(source)) {
copyObject(source, keys(source), object);
return;
}
for (var key in source) {
if (hasOwnProperty.call(source, key)) {
assignValue(object, key, source[key]);
}
}
});
/**
* This method is like `_.assign` except that it iterates over own and
* inherited source properties.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias extend
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.assign
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* function Bar() {
* this.c = 3;
* }
*
* Foo.prototype.b = 2;
* Bar.prototype.d = 4;
*
* _.assignIn({ 'a': 0 }, new Foo, new Bar);
* // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
*/
var assignIn = createAssigner(function(object, source) {
copyObject(source, keysIn(source), object);
});
/**
* This method is like `_.assignIn` except that it accepts `customizer`
* which is invoked to produce the assigned values. If `customizer` returns
* `undefined`, assignment is handled by the method instead. The `customizer`
* is invoked with five arguments: (objValue, srcValue, key, object, source).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias extendWith
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @see _.assignWith
* @example
*
* function customizer(objValue, srcValue) {
* return _.isUndefined(objValue) ? srcValue : objValue;
* }
*
* var defaults = _.partialRight(_.assignInWith, customizer);
*
* defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
copyObject(source, keysIn(source), object, customizer);
});
/**
* This method is like `_.assign` except that it accepts `customizer`
* which is invoked to produce the assigned values. If `customizer` returns
* `undefined`, assignment is handled by the method instead. The `customizer`
* is invoked with five arguments: (objValue, srcValue, key, object, source).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @see _.assignInWith
* @example
*
* function customizer(objValue, srcValue) {
* return _.isUndefined(objValue) ? srcValue : objValue;
* }
*
* var defaults = _.partialRight(_.assignWith, customizer);
*
* defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var assignWith = createAssigner(function(object, source, srcIndex, customizer) {
copyObject(source, keys(source), object, customizer);
});
/**
* Creates an array of values corresponding to `paths` of `object`.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Array} Returns the picked values.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
*
* _.at(object, ['a[0].b.c', 'a[1]']);
* // => [3, 4]
*/
var at = flatRest(baseAt);
/**
* Creates an object that inherits from the `prototype` object. If a
* `properties` object is given, its own enumerable string keyed properties
* are assigned to the created object.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Object
* @param {Object} prototype The object to inherit from.
* @param {Object} [properties] The properties to assign to the object.
* @returns {Object} Returns the new object.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* function Circle() {
* Shape.call(this);
* }
*
* Circle.prototype = _.create(Shape.prototype, {
* 'constructor': Circle
* });
*
* var circle = new Circle;
* circle instanceof Circle;
* // => true
*
* circle instanceof Shape;
* // => true
*/
function create(prototype, properties) {
var result = baseCreate(prototype);
return properties == null ? result : baseAssign(result, properties);
}
/**
* Assigns own and inherited enumerable string keyed properties of source
* objects to the destination object for all destination properties that
* resolve to `undefined`. Source objects are applied from left to right.
* Once a property is set, additional values of the same property are ignored.
*
* **Note:** This method mutates `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.defaultsDeep
* @example
*
* _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var defaults = baseRest(function(object, sources) {
object = Object(object);
var index = -1;
var length = sources.length;
var guard = length > 2 ? sources[2] : undefined;
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
length = 1;
}
while (++index < length) {
var source = sources[index];
var props = keysIn(source);
var propsIndex = -1;
var propsLength = props.length;
while (++propsIndex < propsLength) {
var key = props[propsIndex];
var value = object[key];
if (value === undefined ||
(eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {
object[key] = source[key];
}
}
}
return object;
});
/**
* This method is like `_.defaults` except that it recursively assigns
* default properties.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.defaults
* @example
*
* _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });
* // => { 'a': { 'b': 2, 'c': 3 } }
*/
var defaultsDeep = baseRest(function(args) {
args.push(undefined, customDefaultsMerge);
return apply(mergeWith, undefined, args);
});
/**
* This method is like `_.find` except that it returns the key of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Object
* @param {Object} object The object to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {string|undefined} Returns the key of the matched element,
* else `undefined`.
* @example
*
* var users = {
* 'barney': { 'age': 36, 'active': true },
* 'fred': { 'age': 40, 'active': false },
* 'pebbles': { 'age': 1, 'active': true }
* };
*
* _.findKey(users, function(o) { return o.age < 40; });
* // => 'barney' (iteration order is not guaranteed)
*
* // The `_.matches` iteratee shorthand.
* _.findKey(users, { 'age': 1, 'active': true });
* // => 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findKey(users, ['active', false]);
* // => 'fred'
*
* // The `_.property` iteratee shorthand.
* _.findKey(users, 'active');
* // => 'barney'
*/
function findKey(object, predicate) {
return baseFindKey(object, getIteratee(predicate, 3), baseForOwn);
}
/**
* This method is like `_.findKey` except that it iterates over elements of
* a collection in the opposite order.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Object
* @param {Object} object The object to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {string|undefined} Returns the key of the matched element,
* else `undefined`.
* @example
*
* var users = {
* 'barney': { 'age': 36, 'active': true },
* 'fred': { 'age': 40, 'active': false },
* 'pebbles': { 'age': 1, 'active': true }
* };
*
* _.findLastKey(users, function(o) { return o.age < 40; });
* // => returns 'pebbles' assuming `_.findKey` returns 'barney'
*
* // The `_.matches` iteratee shorthand.
* _.findLastKey(users, { 'age': 36, 'active': true });
* // => 'barney'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findLastKey(users, ['active', false]);
* // => 'fred'
*
* // The `_.property` iteratee shorthand.
* _.findLastKey(users, 'active');
* // => 'pebbles'
*/
function findLastKey(object, predicate) {
return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);
}
/**
* Iterates over own and inherited enumerable string keyed properties of an
* object and invokes `iteratee` for each property. The iteratee is invoked
* with three arguments: (value, key, object). Iteratee functions may exit
* iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 0.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forInRight
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forIn(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).
*/
function forIn(object, iteratee) {
return object == null
? object
: baseFor(object, getIteratee(iteratee, 3), keysIn);
}
/**
* This method is like `_.forIn` except that it iterates over properties of
* `object` in the opposite order.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forIn
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forInRight(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.
*/
function forInRight(object, iteratee) {
return object == null
? object
: baseForRight(object, getIteratee(iteratee, 3), keysIn);
}
/**
* Iterates over own enumerable string keyed properties of an object and
* invokes `iteratee` for each property. The iteratee is invoked with three
* arguments: (value, key, object). Iteratee functions may exit iteration
* early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 0.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forOwnRight
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forOwn(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forOwn(object, iteratee) {
return object && baseForOwn(object, getIteratee(iteratee, 3));
}
/**
* This method is like `_.forOwn` except that it iterates over properties of
* `object` in the opposite order.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forOwn
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forOwnRight(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.
*/
function forOwnRight(object, iteratee) {
return object && baseForOwnRight(object, getIteratee(iteratee, 3));
}
/**
* Creates an array of function property names from own enumerable properties
* of `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the function names.
* @see _.functionsIn
* @example
*
* function Foo() {
* this.a = _.constant('a');
* this.b = _.constant('b');
* }
*
* Foo.prototype.c = _.constant('c');
*
* _.functions(new Foo);
* // => ['a', 'b']
*/
function functions(object) {
return object == null ? [] : baseFunctions(object, keys(object));
}
/**
* Creates an array of function property names from own and inherited
* enumerable properties of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the function names.
* @see _.functions
* @example
*
* function Foo() {
* this.a = _.constant('a');
* this.b = _.constant('b');
* }
*
* Foo.prototype.c = _.constant('c');
*
* _.functionsIn(new Foo);
* // => ['a', 'b', 'c']
*/
function functionsIn(object) {
return object == null ? [] : baseFunctions(object, keysIn(object));
}
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
}
/**
* Checks if `path` is a direct property of `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = { 'a': { 'b': 2 } };
* var other = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.has(object, 'a');
* // => true
*
* _.has(object, 'a.b');
* // => true
*
* _.has(object, ['a', 'b']);
* // => true
*
* _.has(other, 'a');
* // => false
*/
function has(object, path) {
return object != null && hasPath(object, path, baseHas);
}
/**
* Checks if `path` is a direct or inherited property of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.hasIn(object, 'a');
* // => true
*
* _.hasIn(object, 'a.b');
* // => true
*
* _.hasIn(object, ['a', 'b']);
* // => true
*
* _.hasIn(object, 'b');
* // => false
*/
function hasIn(object, path) {
return object != null && hasPath(object, path, baseHasIn);
}
/**
* Creates an object composed of the inverted keys and values of `object`.
* If `object` contains duplicate values, subsequent values overwrite
* property assignments of previous values.
*
* @static
* @memberOf _
* @since 0.7.0
* @category Object
* @param {Object} object The object to invert.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invert(object);
* // => { '1': 'c', '2': 'b' }
*/
var invert = createInverter(function(result, value, key) {
if (value != null &&
typeof value.toString != 'function') {
value = nativeObjectToString.call(value);
}
result[value] = key;
}, constant(identity));
/**
* This method is like `_.invert` except that the inverted object is generated
* from the results of running each element of `object` thru `iteratee`. The
* corresponding inverted value of each inverted key is an array of keys
* responsible for generating the inverted value. The iteratee is invoked
* with one argument: (value).
*
* @static
* @memberOf _
* @since 4.1.0
* @category Object
* @param {Object} object The object to invert.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invertBy(object);
* // => { '1': ['a', 'c'], '2': ['b'] }
*
* _.invertBy(object, function(value) {
* return 'group' + value;
* });
* // => { 'group1': ['a', 'c'], 'group2': ['b'] }
*/
var invertBy = createInverter(function(result, value, key) {
if (value != null &&
typeof value.toString != 'function') {
value = nativeObjectToString.call(value);
}
if (hasOwnProperty.call(result, value)) {
result[value].push(key);
} else {
result[value] = [key];
}
}, getIteratee);
/**
* Invokes the method at `path` of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the method to invoke.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {*} Returns the result of the invoked method.
* @example
*
* var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };
*
* _.invoke(object, 'a[0].b.c.slice', 1, 3);
* // => [2, 3]
*/
var invoke = baseRest(baseInvoke);
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
}
/**
* The opposite of `_.mapValues`; this method creates an object with the
* same values as `object` and keys generated by running each own enumerable
* string keyed property of `object` thru `iteratee`. The iteratee is invoked
* with three arguments: (value, key, object).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapValues
* @example
*
* _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
* return key + value;
* });
* // => { 'a1': 1, 'b2': 2 }
*/
function mapKeys(object, iteratee) {
var result = {};
iteratee = getIteratee(iteratee, 3);
baseForOwn(object, function(value, key, object) {
baseAssignValue(result, iteratee(value, key, object), value);
});
return result;
}
/**
* Creates an object with the same keys as `object` and values generated
* by running each own enumerable string keyed property of `object` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, key, object).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapKeys
* @example
*
* var users = {
* 'fred': { 'user': 'fred', 'age': 40 },
* 'pebbles': { 'user': 'pebbles', 'age': 1 }
* };
*
* _.mapValues(users, function(o) { return o.age; });
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*
* // The `_.property` iteratee shorthand.
* _.mapValues(users, 'age');
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*/
function mapValues(object, iteratee) {
var result = {};
iteratee = getIteratee(iteratee, 3);
baseForOwn(object, function(value, key, object) {
baseAssignValue(result, key, iteratee(value, key, object));
});
return result;
}
/**
* This method is like `_.assign` except that it recursively merges own and
* inherited enumerable string keyed properties of source objects into the
* destination object. Source properties that resolve to `undefined` are
* skipped if a destination value exists. Array and plain object properties
* are merged recursively. Other objects and value types are overridden by
* assignment. Source objects are applied from left to right. Subsequent
* sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @example
*
* var object = {
* 'a': [{ 'b': 2 }, { 'd': 4 }]
* };
*
* var other = {
* 'a': [{ 'c': 3 }, { 'e': 5 }]
* };
*
* _.merge(object, other);
* // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
*/
var merge = createAssigner(function(object, source, srcIndex) {
baseMerge(object, source, srcIndex);
});
/**
* This method is like `_.merge` except that it accepts `customizer` which
* is invoked to produce the merged values of the destination and source
* properties. If `customizer` returns `undefined`, merging is handled by the
* method instead. The `customizer` is invoked with six arguments:
* (objValue, srcValue, key, object, source, stack).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} customizer The function to customize assigned values.
* @returns {Object} Returns `object`.
* @example
*
* function customizer(objValue, srcValue) {
* if (_.isArray(objValue)) {
* return objValue.concat(srcValue);
* }
* }
*
* var object = { 'a': [1], 'b': [2] };
* var other = { 'a': [3], 'b': [4] };
*
* _.mergeWith(object, other, customizer);
* // => { 'a': [1, 3], 'b': [2, 4] }
*/
var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {
baseMerge(object, source, srcIndex, customizer);
});
/**
* The opposite of `_.pick`; this method creates an object composed of the
* own and inherited enumerable property paths of `object` that are not omitted.
*
* **Note:** This method is considerably slower than `_.pick`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to omit.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omit(object, ['a', 'c']);
* // => { 'b': '2' }
*/
var omit = flatRest(function(object, paths) {
var result = {};
if (object == null) {
return result;
}
var isDeep = false;
paths = arrayMap(paths, function(path) {
path = castPath(path, object);
isDeep || (isDeep = path.length > 1);
return path;
});
copyObject(object, getAllKeysIn(object), result);
if (isDeep) {
result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);
}
var length = paths.length;
while (length--) {
baseUnset(result, paths[length]);
}
return result;
});
/**
* The opposite of `_.pickBy`; this method creates an object composed of
* the own and inherited enumerable string keyed properties of `object` that
* `predicate` doesn't return truthy for. The predicate is invoked with two
* arguments: (value, key).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The source object.
* @param {Function} [predicate=_.identity] The function invoked per property.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omitBy(object, _.isNumber);
* // => { 'b': '2' }
*/
function omitBy(object, predicate) {
return pickBy(object, negate(getIteratee(predicate)));
}
/**
* Creates an object composed of the picked `object` properties.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pick(object, ['a', 'c']);
* // => { 'a': 1, 'c': 3 }
*/
var pick = flatRest(function(object, paths) {
return object == null ? {} : basePick(object, paths);
});
/**
* Creates an object composed of the `object` properties `predicate` returns
* truthy for. The predicate is invoked with two arguments: (value, key).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The source object.
* @param {Function} [predicate=_.identity] The function invoked per property.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pickBy(object, _.isNumber);
* // => { 'a': 1, 'c': 3 }
*/
function pickBy(object, predicate) {
if (object == null) {
return {};
}
var props = arrayMap(getAllKeysIn(object), function(prop) {
return [prop];
});
predicate = getIteratee(predicate);
return basePickBy(object, props, function(value, path) {
return predicate(value, path[0]);
});
}
/**
* This method is like `_.get` except that if the resolved value is a
* function it's invoked with the `this` binding of its parent object and
* its result is returned.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to resolve.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
*
* _.result(object, 'a[0].b.c1');
* // => 3
*
* _.result(object, 'a[0].b.c2');
* // => 4
*
* _.result(object, 'a[0].b.c3', 'default');
* // => 'default'
*
* _.result(object, 'a[0].b.c3', _.constant('default'));
* // => 'default'
*/
function result(object, path, defaultValue) {
path = castPath(path, object);
var index = -1,
length = path.length;
// Ensure the loop is entered when path is empty.
if (!length) {
length = 1;
object = undefined;
}
while (++index < length) {
var value = object == null ? undefined : object[toKey(path[index])];
if (value === undefined) {
index = length;
value = defaultValue;
}
object = isFunction(value) ? value.call(object) : value;
}
return object;
}
/**
* Sets the value at `path` of `object`. If a portion of `path` doesn't exist,
* it's created. Arrays are created for missing index properties while objects
* are created for all other missing properties. Use `_.setWith` to customize
* `path` creation.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @returns {Object} Returns `object`.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.set(object, 'a[0].b.c', 4);
* console.log(object.a[0].b.c);
* // => 4
*
* _.set(object, ['x', '0', 'y', 'z'], 5);
* console.log(object.x[0].y.z);
* // => 5
*/
function set(object, path, value) {
return object == null ? object : baseSet(object, path, value);
}
/**
* This method is like `_.set` except that it accepts `customizer` which is
* invoked to produce the objects of `path`. If `customizer` returns `undefined`
* path creation is handled by the method instead. The `customizer` is invoked
* with three arguments: (nsValue, key, nsObject).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @example
*
* var object = {};
*
* _.setWith(object, '[0][1]', 'a', Object);
* // => { '0': { '1': 'a' } }
*/
function setWith(object, path, value, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return object == null ? object : baseSet(object, path, value, customizer);
}
/**
* Creates an array of own enumerable string keyed-value pairs for `object`
* which can be consumed by `_.fromPairs`. If `object` is a map or set, its
* entries are returned.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias entries
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the key-value pairs.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.toPairs(new Foo);
* // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
*/
var toPairs = createToPairs(keys);
/**
* Creates an array of own and inherited enumerable string keyed-value pairs
* for `object` which can be consumed by `_.fromPairs`. If `object` is a map
* or set, its entries are returned.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias entriesIn
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the key-value pairs.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.toPairsIn(new Foo);
* // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)
*/
var toPairsIn = createToPairs(keysIn);
/**
* An alternative to `_.reduce`; this method transforms `object` to a new
* `accumulator` object which is the result of running each of its own
* enumerable string keyed properties thru `iteratee`, with each invocation
* potentially mutating the `accumulator` object. If `accumulator` is not
* provided, a new object with the same `[[Prototype]]` will be used. The
* iteratee is invoked with four arguments: (accumulator, value, key, object).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 1.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The custom accumulator value.
* @returns {*} Returns the accumulated value.
* @example
*
* _.transform([2, 3, 4], function(result, n) {
* result.push(n *= n);
* return n % 2 == 0;
* }, []);
* // => [4, 9]
*
* _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
* (result[value] || (result[value] = [])).push(key);
* }, {});
* // => { '1': ['a', 'c'], '2': ['b'] }
*/
function transform(object, iteratee, accumulator) {
var isArr = isArray(object),
isArrLike = isArr || isBuffer(object) || isTypedArray(object);
iteratee = getIteratee(iteratee, 4);
if (accumulator == null) {
var Ctor = object && object.constructor;
if (isArrLike) {
accumulator = isArr ? new Ctor : [];
}
else if (isObject(object)) {
accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};
}
else {
accumulator = {};
}
}
(isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {
return iteratee(accumulator, value, index, object);
});
return accumulator;
}
/**
* Removes the property at `path` of `object`.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 7 } }] };
* _.unset(object, 'a[0].b.c');
* // => true
*
* console.log(object);
* // => { 'a': [{ 'b': {} }] };
*
* _.unset(object, ['a', '0', 'b', 'c']);
* // => true
*
* console.log(object);
* // => { 'a': [{ 'b': {} }] };
*/
function unset(object, path) {
return object == null ? true : baseUnset(object, path);
}
/**
* This method is like `_.set` except that accepts `updater` to produce the
* value to set. Use `_.updateWith` to customize `path` creation. The `updater`
* is invoked with one argument: (value).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.6.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {Function} updater The function to produce the updated value.
* @returns {Object} Returns `object`.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.update(object, 'a[0].b.c', function(n) { return n * n; });
* console.log(object.a[0].b.c);
* // => 9
*
* _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });
* console.log(object.x[0].y.z);
* // => 0
*/
function update(object, path, updater) {
return object == null ? object : baseUpdate(object, path, castFunction(updater));
}
/**
* This method is like `_.update` except that it accepts `customizer` which is
* invoked to produce the objects of `path`. If `customizer` returns `undefined`
* path creation is handled by the method instead. The `customizer` is invoked
* with three arguments: (nsValue, key, nsObject).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.6.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {Function} updater The function to produce the updated value.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @example
*
* var object = {};
*
* _.updateWith(object, '[0][1]', _.constant('a'), Object);
* // => { '0': { '1': 'a' } }
*/
function updateWith(object, path, updater, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);
}
/**
* Creates an array of the own enumerable string keyed property values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.values(new Foo);
* // => [1, 2] (iteration order is not guaranteed)
*
* _.values('hi');
* // => ['h', 'i']
*/
function values(object) {
return object == null ? [] : baseValues(object, keys(object));
}
/**
* Creates an array of the own and inherited enumerable string keyed property
* values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.valuesIn(new Foo);
* // => [1, 2, 3] (iteration order is not guaranteed)
*/
function valuesIn(object) {
return object == null ? [] : baseValues(object, keysIn(object));
}
/*------------------------------------------------------------------------*/
/**
* Clamps `number` within the inclusive `lower` and `upper` bounds.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Number
* @param {number} number The number to clamp.
* @param {number} [lower] The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the clamped number.
* @example
*
* _.clamp(-10, -5, 5);
* // => -5
*
* _.clamp(10, -5, 5);
* // => 5
*/
function clamp(number, lower, upper) {
if (upper === undefined) {
upper = lower;
lower = undefined;
}
if (upper !== undefined) {
upper = toNumber(upper);
upper = upper === upper ? upper : 0;
}
if (lower !== undefined) {
lower = toNumber(lower);
lower = lower === lower ? lower : 0;
}
return baseClamp(toNumber(number), lower, upper);
}
/**
* Checks if `n` is between `start` and up to, but not including, `end`. If
* `end` is not specified, it's set to `start` with `start` then set to `0`.
* If `start` is greater than `end` the params are swapped to support
* negative ranges.
*
* @static
* @memberOf _
* @since 3.3.0
* @category Number
* @param {number} number The number to check.
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @returns {boolean} Returns `true` if `number` is in the range, else `false`.
* @see _.range, _.rangeRight
* @example
*
* _.inRange(3, 2, 4);
* // => true
*
* _.inRange(4, 8);
* // => true
*
* _.inRange(4, 2);
* // => false
*
* _.inRange(2, 2);
* // => false
*
* _.inRange(1.2, 2);
* // => true
*
* _.inRange(5.2, 4);
* // => false
*
* _.inRange(-3, -2, -6);
* // => true
*/
function inRange(number, start, end) {
start = toFinite(start);
if (end === undefined) {
end = start;
start = 0;
} else {
end = toFinite(end);
}
number = toNumber(number);
return baseInRange(number, start, end);
}
/**
* Produces a random number between the inclusive `lower` and `upper` bounds.
* If only one argument is provided a number between `0` and the given number
* is returned. If `floating` is `true`, or either `lower` or `upper` are
* floats, a floating-point number is returned instead of an integer.
*
* **Note:** JavaScript follows the IEEE-754 standard for resolving
* floating-point values which can produce unexpected results.
*
* @static
* @memberOf _
* @since 0.7.0
* @category Number
* @param {number} [lower=0] The lower bound.
* @param {number} [upper=1] The upper bound.
* @param {boolean} [floating] Specify returning a floating-point number.
* @returns {number} Returns the random number.
* @example
*
* _.random(0, 5);
* // => an integer between 0 and 5
*
* _.random(5);
* // => also an integer between 0 and 5
*
* _.random(5, true);
* // => a floating-point number between 0 and 5
*
* _.random(1.2, 5.2);
* // => a floating-point number between 1.2 and 5.2
*/
function random(lower, upper, floating) {
if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {
upper = floating = undefined;
}
if (floating === undefined) {
if (typeof upper == 'boolean') {
floating = upper;
upper = undefined;
}
else if (typeof lower == 'boolean') {
floating = lower;
lower = undefined;
}
}
if (lower === undefined && upper === undefined) {
lower = 0;
upper = 1;
}
else {
lower = toFinite(lower);
if (upper === undefined) {
upper = lower;
lower = 0;
} else {
upper = toFinite(upper);
}
}
if (lower > upper) {
var temp = lower;
lower = upper;
upper = temp;
}
if (floating || lower % 1 || upper % 1) {
var rand = nativeRandom();
return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);
}
return baseRandom(lower, upper);
}
/*------------------------------------------------------------------------*/
/**
* Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the camel cased string.
* @example
*
* _.camelCase('Foo Bar');
* // => 'fooBar'
*
* _.camelCase('--foo-bar--');
* // => 'fooBar'
*
* _.camelCase('__FOO_BAR__');
* // => 'fooBar'
*/
var camelCase = createCompounder(function(result, word, index) {
word = word.toLowerCase();
return result + (index ? capitalize(word) : word);
});
/**
* Converts the first character of `string` to upper case and the remaining
* to lower case.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to capitalize.
* @returns {string} Returns the capitalized string.
* @example
*
* _.capitalize('FRED');
* // => 'Fred'
*/
function capitalize(string) {
return upperFirst(toString(string).toLowerCase());
}
/**
* Deburrs `string` by converting
* [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
* and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
* letters to basic Latin letters and removing
* [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to deburr.
* @returns {string} Returns the deburred string.
* @example
*
* _.deburr('déjà vu');
* // => 'deja vu'
*/
function deburr(string) {
string = toString(string);
return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
}
/**
* Checks if `string` ends with the given target string.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {string} [target] The string to search for.
* @param {number} [position=string.length] The position to search up to.
* @returns {boolean} Returns `true` if `string` ends with `target`,
* else `false`.
* @example
*
* _.endsWith('abc', 'c');
* // => true
*
* _.endsWith('abc', 'b');
* // => false
*
* _.endsWith('abc', 'b', 2);
* // => true
*/
function endsWith(string, target, position) {
string = toString(string);
target = baseToString(target);
var length = string.length;
position = position === undefined
? length
: baseClamp(toInteger(position), 0, length);
var end = position;
position -= target.length;
return position >= 0 && string.slice(position, end) == target;
}
/**
* Converts the characters "&", "<", ">", '"', and "'" in `string` to their
* corresponding HTML entities.
*
* **Note:** No other characters are escaped. To escape additional
* characters use a third-party library like [_he_](https://mths.be/he).
*
* Though the ">" character is escaped for symmetry, characters like
* ">" and "/" don't need escaping in HTML and have no special meaning
* unless they're part of a tag or unquoted attribute value. See
* [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
* (under "semi-related fun fact") for more details.
*
* When working with HTML you should always
* [quote attribute values](http://wonko.com/post/html-escaping) to reduce
* XSS vectors.
*
* @static
* @since 0.1.0
* @memberOf _
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escape('fred, barney, & pebbles');
* // => 'fred, barney, & pebbles'
*/
function escape(string) {
string = toString(string);
return (string && reHasUnescapedHtml.test(string))
? string.replace(reUnescapedHtml, escapeHtmlChar)
: string;
}
/**
* Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
* "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escapeRegExp('[lodash](https://lodash.com/)');
* // => '\[lodash\]\(https://lodash\.com/\)'
*/
function escapeRegExp(string) {
string = toString(string);
return (string && reHasRegExpChar.test(string))
? string.replace(reRegExpChar, '\\$&')
: string;
}
/**
* Converts `string` to
* [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the kebab cased string.
* @example
*
* _.kebabCase('Foo Bar');
* // => 'foo-bar'
*
* _.kebabCase('fooBar');
* // => 'foo-bar'
*
* _.kebabCase('__FOO_BAR__');
* // => 'foo-bar'
*/
var kebabCase = createCompounder(function(result, word, index) {
return result + (index ? '-' : '') + word.toLowerCase();
});
/**
* Converts `string`, as space separated words, to lower case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the lower cased string.
* @example
*
* _.lowerCase('--Foo-Bar--');
* // => 'foo bar'
*
* _.lowerCase('fooBar');
* // => 'foo bar'
*
* _.lowerCase('__FOO_BAR__');
* // => 'foo bar'
*/
var lowerCase = createCompounder(function(result, word, index) {
return result + (index ? ' ' : '') + word.toLowerCase();
});
/**
* Converts the first character of `string` to lower case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.lowerFirst('Fred');
* // => 'fred'
*
* _.lowerFirst('FRED');
* // => 'fRED'
*/
var lowerFirst = createCaseFirst('toLowerCase');
/**
* Pads `string` on the left and right sides if it's shorter than `length`.
* Padding characters are truncated if they can't be evenly divided by `length`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.pad('abc', 8);
* // => ' abc '
*
* _.pad('abc', 8, '_-');
* // => '_-abc_-_'
*
* _.pad('abc', 3);
* // => 'abc'
*/
function pad(string, length, chars) {
string = toString(string);
length = toInteger(length);
var strLength = length ? stringSize(string) : 0;
if (!length || strLength >= length) {
return string;
}
var mid = (length - strLength) / 2;
return (
createPadding(nativeFloor(mid), chars) +
string +
createPadding(nativeCeil(mid), chars)
);
}
/**
* Pads `string` on the right side if it's shorter than `length`. Padding
* characters are truncated if they exceed `length`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.padEnd('abc', 6);
* // => 'abc '
*
* _.padEnd('abc', 6, '_-');
* // => 'abc_-_'
*
* _.padEnd('abc', 3);
* // => 'abc'
*/
function padEnd(string, length, chars) {
string = toString(string);
length = toInteger(length);
var strLength = length ? stringSize(string) : 0;
return (length && strLength < length)
? (string + createPadding(length - strLength, chars))
: string;
}
/**
* Pads `string` on the left side if it's shorter than `length`. Padding
* characters are truncated if they exceed `length`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.padStart('abc', 6);
* // => ' abc'
*
* _.padStart('abc', 6, '_-');
* // => '_-_abc'
*
* _.padStart('abc', 3);
* // => 'abc'
*/
function padStart(string, length, chars) {
string = toString(string);
length = toInteger(length);
var strLength = length ? stringSize(string) : 0;
return (length && strLength < length)
? (createPadding(length - strLength, chars) + string)
: string;
}
/**
* Converts `string` to an integer of the specified radix. If `radix` is
* `undefined` or `0`, a `radix` of `10` is used unless `value` is a
* hexadecimal, in which case a `radix` of `16` is used.
*
* **Note:** This method aligns with the
* [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.
*
* @static
* @memberOf _
* @since 1.1.0
* @category String
* @param {string} string The string to convert.
* @param {number} [radix=10] The radix to interpret `value` by.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {number} Returns the converted integer.
* @example
*
* _.parseInt('08');
* // => 8
*
* _.map(['6', '08', '10'], _.parseInt);
* // => [6, 8, 10]
*/
function parseInt(string, radix, guard) {
if (guard || radix == null) {
radix = 0;
} else if (radix) {
radix = +radix;
}
return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0);
}
/**
* Repeats the given string `n` times.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to repeat.
* @param {number} [n=1] The number of times to repeat the string.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the repeated string.
* @example
*
* _.repeat('*', 3);
* // => '***'
*
* _.repeat('abc', 2);
* // => 'abcabc'
*
* _.repeat('abc', 0);
* // => ''
*/
function repeat(string, n, guard) {
if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) {
n = 1;
} else {
n = toInteger(n);
}
return baseRepeat(toString(string), n);
}
/**
* Replaces matches for `pattern` in `string` with `replacement`.
*
* **Note:** This method is based on
* [`String#replace`](https://mdn.io/String/replace).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to modify.
* @param {RegExp|string} pattern The pattern to replace.
* @param {Function|string} replacement The match replacement.
* @returns {string} Returns the modified string.
* @example
*
* _.replace('Hi Fred', 'Fred', 'Barney');
* // => 'Hi Barney'
*/
function replace() {
var args = arguments,
string = toString(args[0]);
return args.length < 3 ? string : string.replace(args[1], args[2]);
}
/**
* Converts `string` to
* [snake case](https://en.wikipedia.org/wiki/Snake_case).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the snake cased string.
* @example
*
* _.snakeCase('Foo Bar');
* // => 'foo_bar'
*
* _.snakeCase('fooBar');
* // => 'foo_bar'
*
* _.snakeCase('--FOO-BAR--');
* // => 'foo_bar'
*/
var snakeCase = createCompounder(function(result, word, index) {
return result + (index ? '_' : '') + word.toLowerCase();
});
/**
* Splits `string` by `separator`.
*
* **Note:** This method is based on
* [`String#split`](https://mdn.io/String/split).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to split.
* @param {RegExp|string} separator The separator pattern to split by.
* @param {number} [limit] The length to truncate results to.
* @returns {Array} Returns the string segments.
* @example
*
* _.split('a-b-c', '-', 2);
* // => ['a', 'b']
*/
function split(string, separator, limit) {
if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {
separator = limit = undefined;
}
limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;
if (!limit) {
return [];
}
string = toString(string);
if (string && (
typeof separator == 'string' ||
(separator != null && !isRegExp(separator))
)) {
separator = baseToString(separator);
if (!separator && hasUnicode(string)) {
return castSlice(stringToArray(string), 0, limit);
}
}
return string.split(separator, limit);
}
/**
* Converts `string` to
* [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
*
* @static
* @memberOf _
* @since 3.1.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the start cased string.
* @example
*
* _.startCase('--foo-bar--');
* // => 'Foo Bar'
*
* _.startCase('fooBar');
* // => 'Foo Bar'
*
* _.startCase('__FOO_BAR__');
* // => 'FOO BAR'
*/
var startCase = createCompounder(function(result, word, index) {
return result + (index ? ' ' : '') + upperFirst(word);
});
/**
* Checks if `string` starts with the given target string.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {string} [target] The string to search for.
* @param {number} [position=0] The position to search from.
* @returns {boolean} Returns `true` if `string` starts with `target`,
* else `false`.
* @example
*
* _.startsWith('abc', 'a');
* // => true
*
* _.startsWith('abc', 'b');
* // => false
*
* _.startsWith('abc', 'b', 1);
* // => true
*/
function startsWith(string, target, position) {
string = toString(string);
position = position == null
? 0
: baseClamp(toInteger(position), 0, string.length);
target = baseToString(target);
return string.slice(position, position + target.length) == target;
}
/**
* Creates a compiled template function that can interpolate data properties
* in "interpolate" delimiters, HTML-escape interpolated data properties in
* "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
* properties may be accessed as free variables in the template. If a setting
* object is given, it takes precedence over `_.templateSettings` values.
*
* **Note:** In the development build `_.template` utilizes
* [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
* for easier debugging.
*
* For more information on precompiling templates see
* [lodash's custom builds documentation](https://lodash.com/custom-builds).
*
* For more information on Chrome extension sandboxes see
* [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
*
* @static
* @since 0.1.0
* @memberOf _
* @category String
* @param {string} [string=''] The template string.
* @param {Object} [options={}] The options object.
* @param {RegExp} [options.escape=_.templateSettings.escape]
* The HTML "escape" delimiter.
* @param {RegExp} [options.evaluate=_.templateSettings.evaluate]
* The "evaluate" delimiter.
* @param {Object} [options.imports=_.templateSettings.imports]
* An object to import into the template as free variables.
* @param {RegExp} [options.interpolate=_.templateSettings.interpolate]
* The "interpolate" delimiter.
* @param {string} [options.sourceURL='lodash.templateSources[n]']
* The sourceURL of the compiled template.
* @param {string} [options.variable='obj']
* The data object variable name.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the compiled template function.
* @example
*
* // Use the "interpolate" delimiter to create a compiled template.
* var compiled = _.template('hello <%= user %>!');
* compiled({ 'user': 'fred' });
* // => 'hello fred!'
*
* // Use the HTML "escape" delimiter to escape data property values.
* var compiled = _.template('<b><%- value %></b>');
* compiled({ 'value': '<script>' });
* // => '<b><script></b>'
*
* // Use the "evaluate" delimiter to execute JavaScript and generate HTML.
* var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
* // Use the internal `print` function in "evaluate" delimiters.
* var compiled = _.template('<% print("hello " + user); %>!');
* compiled({ 'user': 'barney' });
* // => 'hello barney!'
*
* // Use the ES template literal delimiter as an "interpolate" delimiter.
* // Disable support by replacing the "interpolate" delimiter.
* var compiled = _.template('hello ${ user }!');
* compiled({ 'user': 'pebbles' });
* // => 'hello pebbles!'
*
* // Use backslashes to treat delimiters as plain text.
* var compiled = _.template('<%= "\\<%- value %\\>" %>');
* compiled({ 'value': 'ignored' });
* // => '<%- value %>'
*
* // Use the `imports` option to import `jQuery` as `jq`.
* var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
* var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
* // Use the `sourceURL` option to specify a custom sourceURL for the template.
* var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
* compiled(data);
* // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
*
* // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
* var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
* compiled.source;
* // => function(data) {
* // var __t, __p = '';
* // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
* // return __p;
* // }
*
* // Use custom template delimiters.
* _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
* var compiled = _.template('hello {{ user }}!');
* compiled({ 'user': 'mustache' });
* // => 'hello mustache!'
*
* // Use the `source` property to inline compiled templates for meaningful
* // line numbers in error messages and stack traces.
* fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\
* var JST = {\
* "main": ' + _.template(mainText).source + '\
* };\
* ');
*/
function template(string, options, guard) {
// Based on John Resig's `tmpl` implementation
// (http://ejohn.org/blog/javascript-micro-templating/)
// and Laura Doktorova's doT.js (https://github.com/olado/doT).
var settings = lodash.templateSettings;
if (guard && isIterateeCall(string, options, guard)) {
options = undefined;
}
string = toString(string);
options = assignInWith({}, options, settings, customDefaultsAssignIn);
var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn),
importsKeys = keys(imports),
importsValues = baseValues(imports, importsKeys);
var isEscaping,
isEvaluating,
index = 0,
interpolate = options.interpolate || reNoMatch,
source = "__p += '";
// Compile the regexp to match each delimiter.
var reDelimiters = RegExp(
(options.escape || reNoMatch).source + '|' +
interpolate.source + '|' +
(interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
(options.evaluate || reNoMatch).source + '|$'
, 'g');
// Use a sourceURL for easier debugging.
// The sourceURL gets injected into the source that's eval-ed, so be careful
// to normalize all kinds of whitespace, so e.g. newlines (and unicode versions of it) can't sneak in
// and escape the comment, thus injecting code that gets evaled.
var sourceURL = '//# sourceURL=' +
(hasOwnProperty.call(options, 'sourceURL')
? (options.sourceURL + '').replace(/\s/g, ' ')
: ('lodash.templateSources[' + (++templateCounter) + ']')
) + '\n';
string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
interpolateValue || (interpolateValue = esTemplateValue);
// Escape characters that can't be included in string literals.
source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
// Replace delimiters with snippets.
if (escapeValue) {
isEscaping = true;
source += "' +\n__e(" + escapeValue + ") +\n'";
}
if (evaluateValue) {
isEvaluating = true;
source += "';\n" + evaluateValue + ";\n__p += '";
}
if (interpolateValue) {
source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
}
index = offset + match.length;
// The JS engine embedded in Adobe products needs `match` returned in
// order to produce the correct `offset` value.
return match;
});
source += "';\n";
// If `variable` is not specified wrap a with-statement around the generated
// code to add the data object to the top of the scope chain.
var variable = hasOwnProperty.call(options, 'variable') && options.variable;
if (!variable) {
source = 'with (obj) {\n' + source + '\n}\n';
}
// Throw an error if a forbidden character was found in `variable`, to prevent
// potential command injection attacks.
else if (reForbiddenIdentifierChars.test(variable)) {
throw new Error(INVALID_TEMPL_VAR_ERROR_TEXT);
}
// Cleanup code by stripping empty strings.
source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
.replace(reEmptyStringMiddle, '$1')
.replace(reEmptyStringTrailing, '$1;');
// Frame code as the function body.
source = 'function(' + (variable || 'obj') + ') {\n' +
(variable
? ''
: 'obj || (obj = {});\n'
) +
"var __t, __p = ''" +
(isEscaping
? ', __e = _.escape'
: ''
) +
(isEvaluating
? ', __j = Array.prototype.join;\n' +
"function print() { __p += __j.call(arguments, '') }\n"
: ';\n'
) +
source +
'return __p\n}';
var result = attempt(function() {
return Function(importsKeys, sourceURL + 'return ' + source)
.apply(undefined, importsValues);
});
// Provide the compiled function's source by its `toString` method or
// the `source` property as a convenience for inlining compiled templates.
result.source = source;
if (isError(result)) {
throw result;
}
return result;
}
/**
* Converts `string`, as a whole, to lower case just like
* [String#toLowerCase](https://mdn.io/toLowerCase).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the lower cased string.
* @example
*
* _.toLower('--Foo-Bar--');
* // => '--foo-bar--'
*
* _.toLower('fooBar');
* // => 'foobar'
*
* _.toLower('__FOO_BAR__');
* // => '__foo_bar__'
*/
function toLower(value) {
return toString(value).toLowerCase();
}
/**
* Converts `string`, as a whole, to upper case just like
* [String#toUpperCase](https://mdn.io/toUpperCase).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the upper cased string.
* @example
*
* _.toUpper('--foo-bar--');
* // => '--FOO-BAR--'
*
* _.toUpper('fooBar');
* // => 'FOOBAR'
*
* _.toUpper('__foo_bar__');
* // => '__FOO_BAR__'
*/
function toUpper(value) {
return toString(value).toUpperCase();
}
/**
* Removes leading and trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trim(' abc ');
* // => 'abc'
*
* _.trim('-_-abc-_-', '_-');
* // => 'abc'
*
* _.map([' foo ', ' bar '], _.trim);
* // => ['foo', 'bar']
*/
function trim(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return baseTrim(string);
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
chrSymbols = stringToArray(chars),
start = charsStartIndex(strSymbols, chrSymbols),
end = charsEndIndex(strSymbols, chrSymbols) + 1;
return castSlice(strSymbols, start, end).join('');
}
/**
* Removes trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trimEnd(' abc ');
* // => ' abc'
*
* _.trimEnd('-_-abc-_-', '_-');
* // => '-_-abc'
*/
function trimEnd(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.slice(0, trimmedEndIndex(string) + 1);
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
end = charsEndIndex(strSymbols, stringToArray(chars)) + 1;
return castSlice(strSymbols, 0, end).join('');
}
/**
* Removes leading whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trimStart(' abc ');
* // => 'abc '
*
* _.trimStart('-_-abc-_-', '_-');
* // => 'abc-_-'
*/
function trimStart(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.replace(reTrimStart, '');
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
start = charsStartIndex(strSymbols, stringToArray(chars));
return castSlice(strSymbols, start).join('');
}
/**
* Truncates `string` if it's longer than the given maximum string length.
* The last characters of the truncated string are replaced with the omission
* string which defaults to "...".
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to truncate.
* @param {Object} [options={}] The options object.
* @param {number} [options.length=30] The maximum string length.
* @param {string} [options.omission='...'] The string to indicate text is omitted.
* @param {RegExp|string} [options.separator] The separator pattern to truncate to.
* @returns {string} Returns the truncated string.
* @example
*
* _.truncate('hi-diddly-ho there, neighborino');
* // => 'hi-diddly-ho there, neighbo...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'length': 24,
* 'separator': ' '
* });
* // => 'hi-diddly-ho there,...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'length': 24,
* 'separator': /,? +/
* });
* // => 'hi-diddly-ho there...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'omission': ' [...]'
* });
* // => 'hi-diddly-ho there, neig [...]'
*/
function truncate(string, options) {
var length = DEFAULT_TRUNC_LENGTH,
omission = DEFAULT_TRUNC_OMISSION;
if (isObject(options)) {
var separator = 'separator' in options ? options.separator : separator;
length = 'length' in options ? toInteger(options.length) : length;
omission = 'omission' in options ? baseToString(options.omission) : omission;
}
string = toString(string);
var strLength = string.length;
if (hasUnicode(string)) {
var strSymbols = stringToArray(string);
strLength = strSymbols.length;
}
if (length >= strLength) {
return string;
}
var end = length - stringSize(omission);
if (end < 1) {
return omission;
}
var result = strSymbols
? castSlice(strSymbols, 0, end).join('')
: string.slice(0, end);
if (separator === undefined) {
return result + omission;
}
if (strSymbols) {
end += (result.length - end);
}
if (isRegExp(separator)) {
if (string.slice(end).search(separator)) {
var match,
substring = result;
if (!separator.global) {
separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g');
}
separator.lastIndex = 0;
while ((match = separator.exec(substring))) {
var newEnd = match.index;
}
result = result.slice(0, newEnd === undefined ? end : newEnd);
}
} else if (string.indexOf(baseToString(separator), end) != end) {
var index = result.lastIndexOf(separator);
if (index > -1) {
result = result.slice(0, index);
}
}
return result + omission;
}
/**
* The inverse of `_.escape`; this method converts the HTML entities
* `&`, `<`, `>`, `"`, and `'` in `string` to
* their corresponding characters.
*
* **Note:** No other HTML entities are unescaped. To unescape additional
* HTML entities use a third-party library like [_he_](https://mths.be/he).
*
* @static
* @memberOf _
* @since 0.6.0
* @category String
* @param {string} [string=''] The string to unescape.
* @returns {string} Returns the unescaped string.
* @example
*
* _.unescape('fred, barney, & pebbles');
* // => 'fred, barney, & pebbles'
*/
function unescape(string) {
string = toString(string);
return (string && reHasEscapedHtml.test(string))
? string.replace(reEscapedHtml, unescapeHtmlChar)
: string;
}
/**
* Converts `string`, as space separated words, to upper case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the upper cased string.
* @example
*
* _.upperCase('--foo-bar');
* // => 'FOO BAR'
*
* _.upperCase('fooBar');
* // => 'FOO BAR'
*
* _.upperCase('__foo_bar__');
* // => 'FOO BAR'
*/
var upperCase = createCompounder(function(result, word, index) {
return result + (index ? ' ' : '') + word.toUpperCase();
});
/**
* Converts the first character of `string` to upper case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.upperFirst('fred');
* // => 'Fred'
*
* _.upperFirst('FRED');
* // => 'FRED'
*/
var upperFirst = createCaseFirst('toUpperCase');
/**
* Splits `string` into an array of its words.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {RegExp|string} [pattern] The pattern to match words.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the words of `string`.
* @example
*
* _.words('fred, barney, & pebbles');
* // => ['fred', 'barney', 'pebbles']
*
* _.words('fred, barney, & pebbles', /[^, ]+/g);
* // => ['fred', 'barney', '&', 'pebbles']
*/
function words(string, pattern, guard) {
string = toString(string);
pattern = guard ? undefined : pattern;
if (pattern === undefined) {
return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
}
return string.match(pattern) || [];
}
/*------------------------------------------------------------------------*/
/**
* Attempts to invoke `func`, returning either the result or the caught error
* object. Any additional arguments are provided to `func` when it's invoked.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {Function} func The function to attempt.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {*} Returns the `func` result or error object.
* @example
*
* // Avoid throwing errors for invalid selectors.
* var elements = _.attempt(function(selector) {
* return document.querySelectorAll(selector);
* }, '>_>');
*
* if (_.isError(elements)) {
* elements = [];
* }
*/
var attempt = baseRest(function(func, args) {
try {
return apply(func, undefined, args);
} catch (e) {
return isError(e) ? e : new Error(e);
}
});
/**
* Binds methods of an object to the object itself, overwriting the existing
* method.
*
* **Note:** This method doesn't set the "length" property of bound functions.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {Object} object The object to bind and assign the bound methods to.
* @param {...(string|string[])} methodNames The object method names to bind.
* @returns {Object} Returns `object`.
* @example
*
* var view = {
* 'label': 'docs',
* 'click': function() {
* console.log('clicked ' + this.label);
* }
* };
*
* _.bindAll(view, ['click']);
* jQuery(element).on('click', view.click);
* // => Logs 'clicked docs' when clicked.
*/
var bindAll = flatRest(function(object, methodNames) {
arrayEach(methodNames, function(key) {
key = toKey(key);
baseAssignValue(object, key, bind(object[key], object));
});
return object;
});
/**
* Creates a function that iterates over `pairs` and invokes the corresponding
* function of the first predicate to return truthy. The predicate-function
* pairs are invoked with the `this` binding and arguments of the created
* function.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {Array} pairs The predicate-function pairs.
* @returns {Function} Returns the new composite function.
* @example
*
* var func = _.cond([
* [_.matches({ 'a': 1 }), _.constant('matches A')],
* [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
* [_.stubTrue, _.constant('no match')]
* ]);
*
* func({ 'a': 1, 'b': 2 });
* // => 'matches A'
*
* func({ 'a': 0, 'b': 1 });
* // => 'matches B'
*
* func({ 'a': '1', 'b': '2' });
* // => 'no match'
*/
function cond(pairs) {
var length = pairs == null ? 0 : pairs.length,
toIteratee = getIteratee();
pairs = !length ? [] : arrayMap(pairs, function(pair) {
if (typeof pair[1] != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return [toIteratee(pair[0]), pair[1]];
});
return baseRest(function(args) {
var index = -1;
while (++index < length) {
var pair = pairs[index];
if (apply(pair[0], this, args)) {
return apply(pair[1], this, args);
}
}
});
}
/**
* Creates a function that invokes the predicate properties of `source` with
* the corresponding property values of a given object, returning `true` if
* all predicates return truthy, else `false`.
*
* **Note:** The created function is equivalent to `_.conformsTo` with
* `source` partially applied.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {Object} source The object of property predicates to conform to.
* @returns {Function} Returns the new spec function.
* @example
*
* var objects = [
* { 'a': 2, 'b': 1 },
* { 'a': 1, 'b': 2 }
* ];
*
* _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } }));
* // => [{ 'a': 1, 'b': 2 }]
*/
function conforms(source) {
return baseConforms(baseClone(source, CLONE_DEEP_FLAG));
}
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new constant function.
* @example
*
* var objects = _.times(2, _.constant({ 'a': 1 }));
*
* console.log(objects);
* // => [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
/**
* Checks `value` to determine whether a default value should be returned in
* its place. The `defaultValue` is returned if `value` is `NaN`, `null`,
* or `undefined`.
*
* @static
* @memberOf _
* @since 4.14.0
* @category Util
* @param {*} value The value to check.
* @param {*} defaultValue The default value.
* @returns {*} Returns the resolved value.
* @example
*
* _.defaultTo(1, 10);
* // => 1
*
* _.defaultTo(undefined, 10);
* // => 10
*/
function defaultTo(value, defaultValue) {
return (value == null || value !== value) ? defaultValue : value;
}
/**
* Creates a function that returns the result of invoking the given functions
* with the `this` binding of the created function, where each successive
* invocation is supplied the return value of the previous.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {...(Function|Function[])} [funcs] The functions to invoke.
* @returns {Function} Returns the new composite function.
* @see _.flowRight
* @example
*
* function square(n) {
* return n * n;
* }
*
* var addSquare = _.flow([_.add, square]);
* addSquare(1, 2);
* // => 9
*/
var flow = createFlow();
/**
* This method is like `_.flow` except that it creates a function that
* invokes the given functions from right to left.
*
* @static
* @since 3.0.0
* @memberOf _
* @category Util
* @param {...(Function|Function[])} [funcs] The functions to invoke.
* @returns {Function} Returns the new composite function.
* @see _.flow
* @example
*
* function square(n) {
* return n * n;
* }
*
* var addSquare = _.flowRight([square, _.add]);
* addSquare(1, 2);
* // => 9
*/
var flowRight = createFlow(true);
/**
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
*/
function identity(value) {
return value;
}
/**
* Creates a function that invokes `func` with the arguments of the created
* function. If `func` is a property name, the created function returns the
* property value for a given element. If `func` is an array or object, the
* created function returns `true` for elements that contain the equivalent
* source properties, otherwise it returns `false`.
*
* @static
* @since 4.0.0
* @memberOf _
* @category Util
* @param {*} [func=_.identity] The value to convert to a callback.
* @returns {Function} Returns the callback.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
* // => [{ 'user': 'barney', 'age': 36, 'active': true }]
*
* // The `_.matchesProperty` iteratee shorthand.
* _.filter(users, _.iteratee(['user', 'fred']));
* // => [{ 'user': 'fred', 'age': 40 }]
*
* // The `_.property` iteratee shorthand.
* _.map(users, _.iteratee('user'));
* // => ['barney', 'fred']
*
* // Create custom iteratee shorthands.
* _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
* return !_.isRegExp(func) ? iteratee(func) : function(string) {
* return func.test(string);
* };
* });
*
* _.filter(['abc', 'def'], /ef/);
* // => ['def']
*/
function iteratee(func) {
return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG));
}
/**
* Creates a function that performs a partial deep comparison between a given
* object and `source`, returning `true` if the given object has equivalent
* property values, else `false`.
*
* **Note:** The created function is equivalent to `_.isMatch` with `source`
* partially applied.
*
* Partial comparisons will match empty array and empty object `source`
* values against any array or object value, respectively. See `_.isEqual`
* for a list of supported value comparisons.
*
* **Note:** Multiple values can be checked by combining several matchers
* using `_.overSome`
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
* @example
*
* var objects = [
* { 'a': 1, 'b': 2, 'c': 3 },
* { 'a': 4, 'b': 5, 'c': 6 }
* ];
*
* _.filter(objects, _.matches({ 'a': 4, 'c': 6 }));
* // => [{ 'a': 4, 'b': 5, 'c': 6 }]
*
* // Checking for several possible values
* _.filter(objects, _.overSome([_.matches({ 'a': 1 }), _.matches({ 'a': 4 })]));
* // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]
*/
function matches(source) {
return baseMatches(baseClone(source, CLONE_DEEP_FLAG));
}
/**
* Creates a function that performs a partial deep comparison between the
* value at `path` of a given object to `srcValue`, returning `true` if the
* object value is equivalent, else `false`.
*
* **Note:** Partial comparisons will match empty array and empty object
* `srcValue` values against any array or object value, respectively. See
* `_.isEqual` for a list of supported value comparisons.
*
* **Note:** Multiple values can be checked by combining several matchers
* using `_.overSome`
*
* @static
* @memberOf _
* @since 3.2.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
* @example
*
* var objects = [
* { 'a': 1, 'b': 2, 'c': 3 },
* { 'a': 4, 'b': 5, 'c': 6 }
* ];
*
* _.find(objects, _.matchesProperty('a', 4));
* // => { 'a': 4, 'b': 5, 'c': 6 }
*
* // Checking for several possible values
* _.filter(objects, _.overSome([_.matchesProperty('a', 1), _.matchesProperty('a', 4)]));
* // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]
*/
function matchesProperty(path, srcValue) {
return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG));
}
/**
* Creates a function that invokes the method at `path` of a given object.
* Any additional arguments are provided to the invoked method.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Util
* @param {Array|string} path The path of the method to invoke.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {Function} Returns the new invoker function.
* @example
*
* var objects = [
* { 'a': { 'b': _.constant(2) } },
* { 'a': { 'b': _.constant(1) } }
* ];
*
* _.map(objects, _.method('a.b'));
* // => [2, 1]
*
* _.map(objects, _.method(['a', 'b']));
* // => [2, 1]
*/
var method = baseRest(function(path, args) {
return function(object) {
return baseInvoke(object, path, args);
};
});
/**
* The opposite of `_.method`; this method creates a function that invokes
* the method at a given path of `object`. Any additional arguments are
* provided to the invoked method.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Util
* @param {Object} object The object to query.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {Function} Returns the new invoker function.
* @example
*
* var array = _.times(3, _.constant),
* object = { 'a': array, 'b': array, 'c': array };
*
* _.map(['a[2]', 'c[0]'], _.methodOf(object));
* // => [2, 0]
*
* _.map([['a', '2'], ['c', '0']], _.methodOf(object));
* // => [2, 0]
*/
var methodOf = baseRest(function(object, args) {
return function(path) {
return baseInvoke(object, path, args);
};
});
/**
* Adds all own enumerable string keyed function properties of a source
* object to the destination object. If `object` is a function, then methods
* are added to its prototype as well.
*
* **Note:** Use `_.runInContext` to create a pristine `lodash` function to
* avoid conflicts caused by modifying the original.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {Function|Object} [object=lodash] The destination object.
* @param {Object} source The object of functions to add.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.chain=true] Specify whether mixins are chainable.
* @returns {Function|Object} Returns `object`.
* @example
*
* function vowels(string) {
* return _.filter(string, function(v) {
* return /[aeiou]/i.test(v);
* });
* }
*
* _.mixin({ 'vowels': vowels });
* _.vowels('fred');
* // => ['e']
*
* _('fred').vowels().value();
* // => ['e']
*
* _.mixin({ 'vowels': vowels }, { 'chain': false });
* _('fred').vowels();
* // => ['e']
*/
function mixin(object, source, options) {
var props = keys(source),
methodNames = baseFunctions(source, props);
if (options == null &&
!(isObject(source) && (methodNames.length || !props.length))) {
options = source;
source = object;
object = this;
methodNames = baseFunctions(source, keys(source));
}
var chain = !(isObject(options) && 'chain' in options) || !!options.chain,
isFunc = isFunction(object);
arrayEach(methodNames, function(methodName) {
var func = source[methodName];
object[methodName] = func;
if (isFunc) {
object.prototype[methodName] = function() {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
};
}
});
return object;
}
/**
* Reverts the `_` variable to its previous value and returns a reference to
* the `lodash` function.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @returns {Function} Returns the `lodash` function.
* @example
*
* var lodash = _.noConflict();
*/
function noConflict() {
if (root._ === this) {
root._ = oldDash;
}
return this;
}
/**
* This method returns `undefined`.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Util
* @example
*
* _.times(2, _.noop);
* // => [undefined, undefined]
*/
function noop() {
// No operation performed.
}
/**
* Creates a function that gets the argument at index `n`. If `n` is negative,
* the nth argument from the end is returned.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {number} [n=0] The index of the argument to return.
* @returns {Function} Returns the new pass-thru function.
* @example
*
* var func = _.nthArg(1);
* func('a', 'b', 'c', 'd');
* // => 'b'
*
* var func = _.nthArg(-2);
* func('a', 'b', 'c', 'd');
* // => 'c'
*/
function nthArg(n) {
n = toInteger(n);
return baseRest(function(args) {
return baseNth(args, n);
});
}
/**
* Creates a function that invokes `iteratees` with the arguments it receives
* and returns their results.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {...(Function|Function[])} [iteratees=[_.identity]]
* The iteratees to invoke.
* @returns {Function} Returns the new function.
* @example
*
* var func = _.over([Math.max, Math.min]);
*
* func(1, 2, 3, 4);
* // => [4, 1]
*/
var over = createOver(arrayMap);
/**
* Creates a function that checks if **all** of the `predicates` return
* truthy when invoked with the arguments it receives.
*
* Following shorthands are possible for providing predicates.
* Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate.
* Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {...(Function|Function[])} [predicates=[_.identity]]
* The predicates to check.
* @returns {Function} Returns the new function.
* @example
*
* var func = _.overEvery([Boolean, isFinite]);
*
* func('1');
* // => true
*
* func(null);
* // => false
*
* func(NaN);
* // => false
*/
var overEvery = createOver(arrayEvery);
/**
* Creates a function that checks if **any** of the `predicates` return
* truthy when invoked with the arguments it receives.
*
* Following shorthands are possible for providing predicates.
* Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate.
* Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {...(Function|Function[])} [predicates=[_.identity]]
* The predicates to check.
* @returns {Function} Returns the new function.
* @example
*
* var func = _.overSome([Boolean, isFinite]);
*
* func('1');
* // => true
*
* func(null);
* // => true
*
* func(NaN);
* // => false
*
* var matchesFunc = _.overSome([{ 'a': 1 }, { 'a': 2 }])
* var matchesPropertyFunc = _.overSome([['a', 1], ['a', 2]])
*/
var overSome = createOver(arraySome);
/**
* Creates a function that returns the value at `path` of a given object.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
* @example
*
* var objects = [
* { 'a': { 'b': 2 } },
* { 'a': { 'b': 1 } }
* ];
*
* _.map(objects, _.property('a.b'));
* // => [2, 1]
*
* _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
* // => [1, 2]
*/
function property(path) {
return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
}
/**
* The opposite of `_.property`; this method creates a function that returns
* the value at a given path of `object`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {Object} object The object to query.
* @returns {Function} Returns the new accessor function.
* @example
*
* var array = [0, 1, 2],
* object = { 'a': array, 'b': array, 'c': array };
*
* _.map(['a[2]', 'c[0]'], _.propertyOf(object));
* // => [2, 0]
*
* _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
* // => [2, 0]
*/
function propertyOf(object) {
return function(path) {
return object == null ? undefined : baseGet(object, path);
};
}
/**
* Creates an array of numbers (positive and/or negative) progressing from
* `start` up to, but not including, `end`. A step of `-1` is used if a negative
* `start` is specified without an `end` or `step`. If `end` is not specified,
* it's set to `start` with `start` then set to `0`.
*
* **Note:** JavaScript follows the IEEE-754 standard for resolving
* floating-point values which can produce unexpected results.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @param {number} [step=1] The value to increment or decrement by.
* @returns {Array} Returns the range of numbers.
* @see _.inRange, _.rangeRight
* @example
*
* _.range(4);
* // => [0, 1, 2, 3]
*
* _.range(-4);
* // => [0, -1, -2, -3]
*
* _.range(1, 5);
* // => [1, 2, 3, 4]
*
* _.range(0, 20, 5);
* // => [0, 5, 10, 15]
*
* _.range(0, -4, -1);
* // => [0, -1, -2, -3]
*
* _.range(1, 4, 0);
* // => [1, 1, 1]
*
* _.range(0);
* // => []
*/
var range = createRange();
/**
* This method is like `_.range` except that it populates values in
* descending order.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @param {number} [step=1] The value to increment or decrement by.
* @returns {Array} Returns the range of numbers.
* @see _.inRange, _.range
* @example
*
* _.rangeRight(4);
* // => [3, 2, 1, 0]
*
* _.rangeRight(-4);
* // => [-3, -2, -1, 0]
*
* _.rangeRight(1, 5);
* // => [4, 3, 2, 1]
*
* _.rangeRight(0, 20, 5);
* // => [15, 10, 5, 0]
*
* _.rangeRight(0, -4, -1);
* // => [-3, -2, -1, 0]
*
* _.rangeRight(1, 4, 0);
* // => [1, 1, 1]
*
* _.rangeRight(0);
* // => []
*/
var rangeRight = createRange(true);
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/
function stubArray() {
return [];
}
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
/**
* This method returns a new empty object.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Object} Returns the new empty object.
* @example
*
* var objects = _.times(2, _.stubObject);
*
* console.log(objects);
* // => [{}, {}]
*
* console.log(objects[0] === objects[1]);
* // => false
*/
function stubObject() {
return {};
}
/**
* This method returns an empty string.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {string} Returns the empty string.
* @example
*
* _.times(2, _.stubString);
* // => ['', '']
*/
function stubString() {
return '';
}
/**
* This method returns `true`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `true`.
* @example
*
* _.times(2, _.stubTrue);
* // => [true, true]
*/
function stubTrue() {
return true;
}
/**
* Invokes the iteratee `n` times, returning an array of the results of
* each invocation. The iteratee is invoked with one argument; (index).
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the array of results.
* @example
*
* _.times(3, String);
* // => ['0', '1', '2']
*
* _.times(4, _.constant(0));
* // => [0, 0, 0, 0]
*/
function times(n, iteratee) {
n = toInteger(n);
if (n < 1 || n > MAX_SAFE_INTEGER) {
return [];
}
var index = MAX_ARRAY_LENGTH,
length = nativeMin(n, MAX_ARRAY_LENGTH);
iteratee = getIteratee(iteratee);
n -= MAX_ARRAY_LENGTH;
var result = baseTimes(length, iteratee);
while (++index < n) {
iteratee(index);
}
return result;
}
/**
* Converts `value` to a property path array.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {*} value The value to convert.
* @returns {Array} Returns the new property path array.
* @example
*
* _.toPath('a.b.c');
* // => ['a', 'b', 'c']
*
* _.toPath('a[0].b.c');
* // => ['a', '0', 'b', 'c']
*/
function toPath(value) {
if (isArray(value)) {
return arrayMap(value, toKey);
}
return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));
}
/**
* Generates a unique ID. If `prefix` is given, the ID is appended to it.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {string} [prefix=''] The value to prefix the ID with.
* @returns {string} Returns the unique ID.
* @example
*
* _.uniqueId('contact_');
* // => 'contact_104'
*
* _.uniqueId();
* // => '105'
*/
function uniqueId(prefix) {
var id = ++idCounter;
return toString(prefix) + id;
}
/*------------------------------------------------------------------------*/
/**
* Adds two numbers.
*
* @static
* @memberOf _
* @since 3.4.0
* @category Math
* @param {number} augend The first number in an addition.
* @param {number} addend The second number in an addition.
* @returns {number} Returns the total.
* @example
*
* _.add(6, 4);
* // => 10
*/
var add = createMathOperation(function(augend, addend) {
return augend + addend;
}, 0);
/**
* Computes `number` rounded up to `precision`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Math
* @param {number} number The number to round up.
* @param {number} [precision=0] The precision to round up to.
* @returns {number} Returns the rounded up number.
* @example
*
* _.ceil(4.006);
* // => 5
*
* _.ceil(6.004, 2);
* // => 6.01
*
* _.ceil(6040, -2);
* // => 6100
*/
var ceil = createRound('ceil');
/**
* Divide two numbers.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Math
* @param {number} dividend The first number in a division.
* @param {number} divisor The second number in a division.
* @returns {number} Returns the quotient.
* @example
*
* _.divide(6, 4);
* // => 1.5
*/
var divide = createMathOperation(function(dividend, divisor) {
return dividend / divisor;
}, 1);
/**
* Computes `number` rounded down to `precision`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Math
* @param {number} number The number to round down.
* @param {number} [precision=0] The precision to round down to.
* @returns {number} Returns the rounded down number.
* @example
*
* _.floor(4.006);
* // => 4
*
* _.floor(0.046, 2);
* // => 0.04
*
* _.floor(4060, -2);
* // => 4000
*/
var floor = createRound('floor');
/**
* Computes the maximum value of `array`. If `array` is empty or falsey,
* `undefined` is returned.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Math
* @param {Array} array The array to iterate over.
* @returns {*} Returns the maximum value.
* @example
*
* _.max([4, 2, 8, 6]);
* // => 8
*
* _.max([]);
* // => undefined
*/
function max(array) {
return (array && array.length)
? baseExtremum(array, identity, baseGt)
: undefined;
}
/**
* This method is like `_.max` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the criterion by which
* the value is ranked. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {*} Returns the maximum value.
* @example
*
* var objects = [{ 'n': 1 }, { 'n': 2 }];
*
* _.maxBy(objects, function(o) { return o.n; });
* // => { 'n': 2 }
*
* // The `_.property` iteratee shorthand.
* _.maxBy(objects, 'n');
* // => { 'n': 2 }
*/
function maxBy(array, iteratee) {
return (array && array.length)
? baseExtremum(array, getIteratee(iteratee, 2), baseGt)
: undefined;
}
/**
* Computes the mean of the values in `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @returns {number} Returns the mean.
* @example
*
* _.mean([4, 2, 8, 6]);
* // => 5
*/
function mean(array) {
return baseMean(array, identity);
}
/**
* This method is like `_.mean` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the value to be averaged.
* The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.7.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the mean.
* @example
*
* var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
*
* _.meanBy(objects, function(o) { return o.n; });
* // => 5
*
* // The `_.property` iteratee shorthand.
* _.meanBy(objects, 'n');
* // => 5
*/
function meanBy(array, iteratee) {
return baseMean(array, getIteratee(iteratee, 2));
}
/**
* Computes the minimum value of `array`. If `array` is empty or falsey,
* `undefined` is returned.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Math
* @param {Array} array The array to iterate over.
* @returns {*} Returns the minimum value.
* @example
*
* _.min([4, 2, 8, 6]);
* // => 2
*
* _.min([]);
* // => undefined
*/
function min(array) {
return (array && array.length)
? baseExtremum(array, identity, baseLt)
: undefined;
}
/**
* This method is like `_.min` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the criterion by which
* the value is ranked. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {*} Returns the minimum value.
* @example
*
* var objects = [{ 'n': 1 }, { 'n': 2 }];
*
* _.minBy(objects, function(o) { return o.n; });
* // => { 'n': 1 }
*
* // The `_.property` iteratee shorthand.
* _.minBy(objects, 'n');
* // => { 'n': 1 }
*/
function minBy(array, iteratee) {
return (array && array.length)
? baseExtremum(array, getIteratee(iteratee, 2), baseLt)
: undefined;
}
/**
* Multiply two numbers.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Math
* @param {number} multiplier The first number in a multiplication.
* @param {number} multiplicand The second number in a multiplication.
* @returns {number} Returns the product.
* @example
*
* _.multiply(6, 4);
* // => 24
*/
var multiply = createMathOperation(function(multiplier, multiplicand) {
return multiplier * multiplicand;
}, 1);
/**
* Computes `number` rounded to `precision`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Math
* @param {number} number The number to round.
* @param {number} [precision=0] The precision to round to.
* @returns {number} Returns the rounded number.
* @example
*
* _.round(4.006);
* // => 4
*
* _.round(4.006, 2);
* // => 4.01
*
* _.round(4060, -2);
* // => 4100
*/
var round = createRound('round');
/**
* Subtract two numbers.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {number} minuend The first number in a subtraction.
* @param {number} subtrahend The second number in a subtraction.
* @returns {number} Returns the difference.
* @example
*
* _.subtract(6, 4);
* // => 2
*/
var subtract = createMathOperation(function(minuend, subtrahend) {
return minuend - subtrahend;
}, 0);
/**
* Computes the sum of the values in `array`.
*
* @static
* @memberOf _
* @since 3.4.0
* @category Math
* @param {Array} array The array to iterate over.
* @returns {number} Returns the sum.
* @example
*
* _.sum([4, 2, 8, 6]);
* // => 20
*/
function sum(array) {
return (array && array.length)
? baseSum(array, identity)
: 0;
}
/**
* This method is like `_.sum` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the value to be summed.
* The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the sum.
* @example
*
* var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
*
* _.sumBy(objects, function(o) { return o.n; });
* // => 20
*
* // The `_.property` iteratee shorthand.
* _.sumBy(objects, 'n');
* // => 20
*/
function sumBy(array, iteratee) {
return (array && array.length)
? baseSum(array, getIteratee(iteratee, 2))
: 0;
}
/*------------------------------------------------------------------------*/
// Add methods that return wrapped values in chain sequences.
lodash.after = after;
lodash.ary = ary;
lodash.assign = assign;
lodash.assignIn = assignIn;
lodash.assignInWith = assignInWith;
lodash.assignWith = assignWith;
lodash.at = at;
lodash.before = before;
lodash.bind = bind;
lodash.bindAll = bindAll;
lodash.bindKey = bindKey;
lodash.castArray = castArray;
lodash.chain = chain;
lodash.chunk = chunk;
lodash.compact = compact;
lodash.concat = concat;
lodash.cond = cond;
lodash.conforms = conforms;
lodash.constant = constant;
lodash.countBy = countBy;
lodash.create = create;
lodash.curry = curry;
lodash.curryRight = curryRight;
lodash.debounce = debounce;
lodash.defaults = defaults;
lodash.defaultsDeep = defaultsDeep;
lodash.defer = defer;
lodash.delay = delay;
lodash.difference = difference;
lodash.differenceBy = differenceBy;
lodash.differenceWith = differenceWith;
lodash.drop = drop;
lodash.dropRight = dropRight;
lodash.dropRightWhile = dropRightWhile;
lodash.dropWhile = dropWhile;
lodash.fill = fill;
lodash.filter = filter;
lodash.flatMap = flatMap;
lodash.flatMapDeep = flatMapDeep;
lodash.flatMapDepth = flatMapDepth;
lodash.flatten = flatten;
lodash.flattenDeep = flattenDeep;
lodash.flattenDepth = flattenDepth;
lodash.flip = flip;
lodash.flow = flow;
lodash.flowRight = flowRight;
lodash.fromPairs = fromPairs;
lodash.functions = functions;
lodash.functionsIn = functionsIn;
lodash.groupBy = groupBy;
lodash.initial = initial;
lodash.intersection = intersection;
lodash.intersectionBy = intersectionBy;
lodash.intersectionWith = intersectionWith;
lodash.invert = invert;
lodash.invertBy = invertBy;
lodash.invokeMap = invokeMap;
lodash.iteratee = iteratee;
lodash.keyBy = keyBy;
lodash.keys = keys;
lodash.keysIn = keysIn;
lodash.map = map;
lodash.mapKeys = mapKeys;
lodash.mapValues = mapValues;
lodash.matches = matches;
lodash.matchesProperty = matchesProperty;
lodash.memoize = memoize;
lodash.merge = merge;
lodash.mergeWith = mergeWith;
lodash.method = method;
lodash.methodOf = methodOf;
lodash.mixin = mixin;
lodash.negate = negate;
lodash.nthArg = nthArg;
lodash.omit = omit;
lodash.omitBy = omitBy;
lodash.once = once;
lodash.orderBy = orderBy;
lodash.over = over;
lodash.overArgs = overArgs;
lodash.overEvery = overEvery;
lodash.overSome = overSome;
lodash.partial = partial;
lodash.partialRight = partialRight;
lodash.partition = partition;
lodash.pick = pick;
lodash.pickBy = pickBy;
lodash.property = property;
lodash.propertyOf = propertyOf;
lodash.pull = pull;
lodash.pullAll = pullAll;
lodash.pullAllBy = pullAllBy;
lodash.pullAllWith = pullAllWith;
lodash.pullAt = pullAt;
lodash.range = range;
lodash.rangeRight = rangeRight;
lodash.rearg = rearg;
lodash.reject = reject;
lodash.remove = remove;
lodash.rest = rest;
lodash.reverse = reverse;
lodash.sampleSize = sampleSize;
lodash.set = set;
lodash.setWith = setWith;
lodash.shuffle = shuffle;
lodash.slice = slice;
lodash.sortBy = sortBy;
lodash.sortedUniq = sortedUniq;
lodash.sortedUniqBy = sortedUniqBy;
lodash.split = split;
lodash.spread = spread;
lodash.tail = tail;
lodash.take = take;
lodash.takeRight = takeRight;
lodash.takeRightWhile = takeRightWhile;
lodash.takeWhile = takeWhile;
lodash.tap = tap;
lodash.throttle = throttle;
lodash.thru = thru;
lodash.toArray = toArray;
lodash.toPairs = toPairs;
lodash.toPairsIn = toPairsIn;
lodash.toPath = toPath;
lodash.toPlainObject = toPlainObject;
lodash.transform = transform;
lodash.unary = unary;
lodash.union = union;
lodash.unionBy = unionBy;
lodash.unionWith = unionWith;
lodash.uniq = uniq;
lodash.uniqBy = uniqBy;
lodash.uniqWith = uniqWith;
lodash.unset = unset;
lodash.unzip = unzip;
lodash.unzipWith = unzipWith;
lodash.update = update;
lodash.updateWith = updateWith;
lodash.values = values;
lodash.valuesIn = valuesIn;
lodash.without = without;
lodash.words = words;
lodash.wrap = wrap;
lodash.xor = xor;
lodash.xorBy = xorBy;
lodash.xorWith = xorWith;
lodash.zip = zip;
lodash.zipObject = zipObject;
lodash.zipObjectDeep = zipObjectDeep;
lodash.zipWith = zipWith;
// Add aliases.
lodash.entries = toPairs;
lodash.entriesIn = toPairsIn;
lodash.extend = assignIn;
lodash.extendWith = assignInWith;
// Add methods to `lodash.prototype`.
mixin(lodash, lodash);
/*------------------------------------------------------------------------*/
// Add methods that return unwrapped values in chain sequences.
lodash.add = add;
lodash.attempt = attempt;
lodash.camelCase = camelCase;
lodash.capitalize = capitalize;
lodash.ceil = ceil;
lodash.clamp = clamp;
lodash.clone = clone;
lodash.cloneDeep = cloneDeep;
lodash.cloneDeepWith = cloneDeepWith;
lodash.cloneWith = cloneWith;
lodash.conformsTo = conformsTo;
lodash.deburr = deburr;
lodash.defaultTo = defaultTo;
lodash.divide = divide;
lodash.endsWith = endsWith;
lodash.eq = eq;
lodash.escape = escape;
lodash.escapeRegExp = escapeRegExp;
lodash.every = every;
lodash.find = find;
lodash.findIndex = findIndex;
lodash.findKey = findKey;
lodash.findLast = findLast;
lodash.findLastIndex = findLastIndex;
lodash.findLastKey = findLastKey;
lodash.floor = floor;
lodash.forEach = forEach;
lodash.forEachRight = forEachRight;
lodash.forIn = forIn;
lodash.forInRight = forInRight;
lodash.forOwn = forOwn;
lodash.forOwnRight = forOwnRight;
lodash.get = get;
lodash.gt = gt;
lodash.gte = gte;
lodash.has = has;
lodash.hasIn = hasIn;
lodash.head = head;
lodash.identity = identity;
lodash.includes = includes;
lodash.indexOf = indexOf;
lodash.inRange = inRange;
lodash.invoke = invoke;
lodash.isArguments = isArguments;
lodash.isArray = isArray;
lodash.isArrayBuffer = isArrayBuffer;
lodash.isArrayLike = isArrayLike;
lodash.isArrayLikeObject = isArrayLikeObject;
lodash.isBoolean = isBoolean;
lodash.isBuffer = isBuffer;
lodash.isDate = isDate;
lodash.isElement = isElement;
lodash.isEmpty = isEmpty;
lodash.isEqual = isEqual;
lodash.isEqualWith = isEqualWith;
lodash.isError = isError;
lodash.isFinite = isFinite;
lodash.isFunction = isFunction;
lodash.isInteger = isInteger;
lodash.isLength = isLength;
lodash.isMap = isMap;
lodash.isMatch = isMatch;
lodash.isMatchWith = isMatchWith;
lodash.isNaN = isNaN;
lodash.isNative = isNative;
lodash.isNil = isNil;
lodash.isNull = isNull;
lodash.isNumber = isNumber;
lodash.isObject = isObject;
lodash.isObjectLike = isObjectLike;
lodash.isPlainObject = isPlainObject;
lodash.isRegExp = isRegExp;
lodash.isSafeInteger = isSafeInteger;
lodash.isSet = isSet;
lodash.isString = isString;
lodash.isSymbol = isSymbol;
lodash.isTypedArray = isTypedArray;
lodash.isUndefined = isUndefined;
lodash.isWeakMap = isWeakMap;
lodash.isWeakSet = isWeakSet;
lodash.join = join;
lodash.kebabCase = kebabCase;
lodash.last = last;
lodash.lastIndexOf = lastIndexOf;
lodash.lowerCase = lowerCase;
lodash.lowerFirst = lowerFirst;
lodash.lt = lt;
lodash.lte = lte;
lodash.max = max;
lodash.maxBy = maxBy;
lodash.mean = mean;
lodash.meanBy = meanBy;
lodash.min = min;
lodash.minBy = minBy;
lodash.stubArray = stubArray;
lodash.stubFalse = stubFalse;
lodash.stubObject = stubObject;
lodash.stubString = stubString;
lodash.stubTrue = stubTrue;
lodash.multiply = multiply;
lodash.nth = nth;
lodash.noConflict = noConflict;
lodash.noop = noop;
lodash.now = now;
lodash.pad = pad;
lodash.padEnd = padEnd;
lodash.padStart = padStart;
lodash.parseInt = parseInt;
lodash.random = random;
lodash.reduce = reduce;
lodash.reduceRight = reduceRight;
lodash.repeat = repeat;
lodash.replace = replace;
lodash.result = result;
lodash.round = round;
lodash.runInContext = runInContext;
lodash.sample = sample;
lodash.size = size;
lodash.snakeCase = snakeCase;
lodash.some = some;
lodash.sortedIndex = sortedIndex;
lodash.sortedIndexBy = sortedIndexBy;
lodash.sortedIndexOf = sortedIndexOf;
lodash.sortedLastIndex = sortedLastIndex;
lodash.sortedLastIndexBy = sortedLastIndexBy;
lodash.sortedLastIndexOf = sortedLastIndexOf;
lodash.startCase = startCase;
lodash.startsWith = startsWith;
lodash.subtract = subtract;
lodash.sum = sum;
lodash.sumBy = sumBy;
lodash.template = template;
lodash.times = times;
lodash.toFinite = toFinite;
lodash.toInteger = toInteger;
lodash.toLength = toLength;
lodash.toLower = toLower;
lodash.toNumber = toNumber;
lodash.toSafeInteger = toSafeInteger;
lodash.toString = toString;
lodash.toUpper = toUpper;
lodash.trim = trim;
lodash.trimEnd = trimEnd;
lodash.trimStart = trimStart;
lodash.truncate = truncate;
lodash.unescape = unescape;
lodash.uniqueId = uniqueId;
lodash.upperCase = upperCase;
lodash.upperFirst = upperFirst;
// Add aliases.
lodash.each = forEach;
lodash.eachRight = forEachRight;
lodash.first = head;
mixin(lodash, (function() {
var source = {};
baseForOwn(lodash, function(func, methodName) {
if (!hasOwnProperty.call(lodash.prototype, methodName)) {
source[methodName] = func;
}
});
return source;
}()), { 'chain': false });
/*------------------------------------------------------------------------*/
/**
* The semantic version number.
*
* @static
* @memberOf _
* @type {string}
*/
lodash.VERSION = VERSION;
// Assign default placeholders.
arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) {
lodash[methodName].placeholder = lodash;
});
// Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
arrayEach(['drop', 'take'], function(methodName, index) {
LazyWrapper.prototype[methodName] = function(n) {
n = n === undefined ? 1 : nativeMax(toInteger(n), 0);
var result = (this.__filtered__ && !index)
? new LazyWrapper(this)
: this.clone();
if (result.__filtered__) {
result.__takeCount__ = nativeMin(n, result.__takeCount__);
} else {
result.__views__.push({
'size': nativeMin(n, MAX_ARRAY_LENGTH),
'type': methodName + (result.__dir__ < 0 ? 'Right' : '')
});
}
return result;
};
LazyWrapper.prototype[methodName + 'Right'] = function(n) {
return this.reverse()[methodName](n).reverse();
};
});
// Add `LazyWrapper` methods that accept an `iteratee` value.
arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) {
var type = index + 1,
isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG;
LazyWrapper.prototype[methodName] = function(iteratee) {
var result = this.clone();
result.__iteratees__.push({
'iteratee': getIteratee(iteratee, 3),
'type': type
});
result.__filtered__ = result.__filtered__ || isFilter;
return result;
};
});
// Add `LazyWrapper` methods for `_.head` and `_.last`.
arrayEach(['head', 'last'], function(methodName, index) {
var takeName = 'take' + (index ? 'Right' : '');
LazyWrapper.prototype[methodName] = function() {
return this[takeName](1).value()[0];
};
});
// Add `LazyWrapper` methods for `_.initial` and `_.tail`.
arrayEach(['initial', 'tail'], function(methodName, index) {
var dropName = 'drop' + (index ? '' : 'Right');
LazyWrapper.prototype[methodName] = function() {
return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
};
});
LazyWrapper.prototype.compact = function() {
return this.filter(identity);
};
LazyWrapper.prototype.find = function(predicate) {
return this.filter(predicate).head();
};
LazyWrapper.prototype.findLast = function(predicate) {
return this.reverse().find(predicate);
};
LazyWrapper.prototype.invokeMap = baseRest(function(path, args) {
if (typeof path == 'function') {
return new LazyWrapper(this);
}
return this.map(function(value) {
return baseInvoke(value, path, args);
});
});
LazyWrapper.prototype.reject = function(predicate) {
return this.filter(negate(getIteratee(predicate)));
};
LazyWrapper.prototype.slice = function(start, end) {
start = toInteger(start);
var result = this;
if (result.__filtered__ && (start > 0 || end < 0)) {
return new LazyWrapper(result);
}
if (start < 0) {
result = result.takeRight(-start);
} else if (start) {
result = result.drop(start);
}
if (end !== undefined) {
end = toInteger(end);
result = end < 0 ? result.dropRight(-end) : result.take(end - start);
}
return result;
};
LazyWrapper.prototype.takeRightWhile = function(predicate) {
return this.reverse().takeWhile(predicate).reverse();
};
LazyWrapper.prototype.toArray = function() {
return this.take(MAX_ARRAY_LENGTH);
};
// Add `LazyWrapper` methods to `lodash.prototype`.
baseForOwn(LazyWrapper.prototype, function(func, methodName) {
var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName),
isTaker = /^(?:head|last)$/.test(methodName),
lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName],
retUnwrapped = isTaker || /^find/.test(methodName);
if (!lodashFunc) {
return;
}
lodash.prototype[methodName] = function() {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
};
});
// Add `Array` methods to `lodash.prototype`.
arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) {
var func = arrayProto[methodName],
chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
retUnwrapped = /^(?:pop|shift)$/.test(methodName);
lodash.prototype[methodName] = function() {
var args = arguments;
if (retUnwrapped && !this.__chain__) {
var value = this.value();
return func.apply(isArray(value) ? value : [], args);
}
return this[chainName](function(value) {
return func.apply(isArray(value) ? value : [], args);
});
};
});
// Map minified method names to their real names.
baseForOwn(LazyWrapper.prototype, function(func, methodName) {
var lodashFunc = lodash[methodName];
if (lodashFunc) {
var key = lodashFunc.name + '';
if (!hasOwnProperty.call(realNames, key)) {
realNames[key] = [];
}
realNames[key].push({ 'name': methodName, 'func': lodashFunc });
}
});
realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{
'name': 'wrapper',
'func': undefined
}];
// Add methods to `LazyWrapper`.
LazyWrapper.prototype.clone = lazyClone;
LazyWrapper.prototype.reverse = lazyReverse;
LazyWrapper.prototype.value = lazyValue;
// Add chain sequence methods to the `lodash` wrapper.
lodash.prototype.at = wrapperAt;
lodash.prototype.chain = wrapperChain;
lodash.prototype.commit = wrapperCommit;
lodash.prototype.next = wrapperNext;
lodash.prototype.plant = wrapperPlant;
lodash.prototype.reverse = wrapperReverse;
lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
// Add lazy aliases.
lodash.prototype.first = lodash.prototype.head;
if (symIterator) {
lodash.prototype[symIterator] = wrapperToIterator;
}
return lodash;
});
/*--------------------------------------------------------------------------*/
// Export lodash.
var _ = runInContext();
// Some AMD build optimizers, like r.js, check for condition patterns like:
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
// Expose Lodash on the global object to prevent errors when Lodash is
// loaded by a script tag in the presence of an AMD loader.
// See http://requirejs.org/docs/errors.html#mismatch for more details.
// Use `_.noConflict` to remove Lodash from the global object.
root._ = _;
// Define as an anonymous module so, through path mapping, it can be
// referenced as the "underscore" module.
define(function() {
return _;
});
}
// Check for `exports` after `define` in case a build optimizer adds it.
else if (freeModule) {
// Export for Node.js.
(freeModule.exports = _)._ = _;
// Export for CommonJS support.
freeExports._ = _;
}
else {
// Export to the global object.
root._ = _;
}
}.call(this));
vendor/wp-polyfill-fetch.min.js 0000666 00000022125 15123355174 0012542 0 ustar 00 !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.WHATWGFetch={})}(this,(function(t){"use strict";var e,r,o="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||void 0!==o&&o,n="URLSearchParams"in o,i="Symbol"in o&&"iterator"in Symbol,s="FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch(t){return!1}}(),a="FormData"in o,h="ArrayBuffer"in o;function u(t){if("string"!=typeof t&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(t)||""===t)throw new TypeError('Invalid character in header field name: "'+t+'"');return t.toLowerCase()}function f(t){return"string"!=typeof t?String(t):t}function c(t){var e={next:function(){var e=t.shift();return{done:void 0===e,value:e}}};return i&&(e[Symbol.iterator]=function(){return e}),e}function d(t){this.map={},t instanceof d?t.forEach((function(t,e){this.append(e,t)}),this):Array.isArray(t)?t.forEach((function(t){this.append(t[0],t[1])}),this):t&&Object.getOwnPropertyNames(t).forEach((function(e){this.append(e,t[e])}),this)}function y(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}function p(t){return new Promise((function(e,r){t.onload=function(){e(t.result)},t.onerror=function(){r(t.error)}}))}function l(t){var e=new FileReader,r=p(e);return e.readAsArrayBuffer(t),r}function b(t){var e;return t.slice?t.slice(0):((e=new Uint8Array(t.byteLength)).set(new Uint8Array(t)),e.buffer)}function m(){return this.bodyUsed=!1,this._initBody=function(t){var e;this.bodyUsed=this.bodyUsed,(this._bodyInit=t)?"string"==typeof t?this._bodyText=t:s&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:a&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:n&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():h&&s&&(e=t)&&DataView.prototype.isPrototypeOf(e)?(this._bodyArrayBuffer=b(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):h&&(ArrayBuffer.prototype.isPrototypeOf(t)||r(t))?this._bodyArrayBuffer=b(t):this._bodyText=t=Object.prototype.toString.call(t):this._bodyText="",this.headers.get("content-type")||("string"==typeof t?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):n&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},s&&(this.blob=function(){var t=y(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?y(this)||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer)):this.blob().then(l)}),this.text=function(){var t,e,r=y(this);if(r)return r;if(this._bodyBlob)return r=this._bodyBlob,e=p(t=new FileReader),t.readAsText(r),e;if(this._bodyArrayBuffer)return Promise.resolve(function(t){for(var e=new Uint8Array(t),r=new Array(e.length),o=0;o<e.length;o++)r[o]=String.fromCharCode(e[o]);return r.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},a&&(this.formData=function(){return this.text().then(T)}),this.json=function(){return this.text().then(JSON.parse)},this}h&&(e=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],r=ArrayBuffer.isView||function(t){return t&&-1<e.indexOf(Object.prototype.toString.call(t))}),d.prototype.append=function(t,e){t=u(t),e=f(e);var r=this.map[t];this.map[t]=r?r+", "+e:e},d.prototype.delete=function(t){delete this.map[u(t)]},d.prototype.get=function(t){return t=u(t),this.has(t)?this.map[t]:null},d.prototype.has=function(t){return this.map.hasOwnProperty(u(t))},d.prototype.set=function(t,e){this.map[u(t)]=f(e)},d.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)},d.prototype.keys=function(){var t=[];return this.forEach((function(e,r){t.push(r)})),c(t)},d.prototype.values=function(){var t=[];return this.forEach((function(e){t.push(e)})),c(t)},d.prototype.entries=function(){var t=[];return this.forEach((function(e,r){t.push([r,e])})),c(t)},i&&(d.prototype[Symbol.iterator]=d.prototype.entries);var w=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function E(t,e){if(!(this instanceof E))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');var r,o=(e=e||{}).body;if(t instanceof E){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new d(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,o||null==t._bodyInit||(o=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"same-origin",!e.headers&&this.headers||(this.headers=new d(e.headers)),this.method=(r=(t=e.method||this.method||"GET").toUpperCase(),-1<w.indexOf(r)?r:t),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&o)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(o),"GET"!==this.method&&"HEAD"!==this.method||"no-store"!==e.cache&&"no-cache"!==e.cache||((r=/([?&])_=[^&]*/).test(this.url)?this.url=this.url.replace(r,"$1_="+(new Date).getTime()):this.url+=(/\?/.test(this.url)?"&":"?")+"_="+(new Date).getTime())}function T(t){var e=new FormData;return t.trim().split("&").forEach((function(t){var r;t&&(r=(t=t.split("=")).shift().replace(/\+/g," "),t=t.join("=").replace(/\+/g," "),e.append(decodeURIComponent(r),decodeURIComponent(t)))})),e}function A(t,e){if(!(this instanceof A))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');e=e||{},this.type="default",this.status=void 0===e.status?200:e.status,this.ok=200<=this.status&&this.status<300,this.statusText=void 0===e.statusText?"":""+e.statusText,this.headers=new d(e.headers),this.url=e.url||"",this._initBody(t)}E.prototype.clone=function(){return new E(this,{body:this._bodyInit})},m.call(E.prototype),m.call(A.prototype),A.prototype.clone=function(){return new A(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new d(this.headers),url:this.url})},A.error=function(){var t=new A(null,{status:0,statusText:""});return t.type="error",t};var _=[301,302,303,307,308];A.redirect=function(t,e){if(-1===_.indexOf(e))throw new RangeError("Invalid status code");return new A(null,{status:e,headers:{location:t}})},t.DOMException=o.DOMException;try{new t.DOMException}catch(c){t.DOMException=function(t,e){this.message=t,this.name=e,e=Error(t),this.stack=e.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function g(e,r){return new Promise((function(n,i){var a=new E(e,r);if(a.signal&&a.signal.aborted)return i(new t.DOMException("Aborted","AbortError"));var u=new XMLHttpRequest;function c(){u.abort()}u.onload=function(){var t,e,r={status:u.status,statusText:u.statusText,headers:(t=u.getAllResponseHeaders()||"",e=new d,t.replace(/\r?\n[\t ]+/g," ").split("\r").map((function(t){return 0===t.indexOf("\n")?t.substr(1,t.length):t})).forEach((function(t){var r=(t=t.split(":")).shift().trim();r&&(t=t.join(":").trim(),e.append(r,t))})),e)},o=(r.url="responseURL"in u?u.responseURL:r.headers.get("X-Request-URL"),"response"in u?u.response:u.responseText);setTimeout((function(){n(new A(o,r))}),0)},u.onerror=function(){setTimeout((function(){i(new TypeError("Network request failed"))}),0)},u.ontimeout=function(){setTimeout((function(){i(new TypeError("Network request failed"))}),0)},u.onabort=function(){setTimeout((function(){i(new t.DOMException("Aborted","AbortError"))}),0)},u.open(a.method,function(t){try{return""===t&&o.location.href?o.location.href:t}catch(e){return t}}(a.url),!0),"include"===a.credentials?u.withCredentials=!0:"omit"===a.credentials&&(u.withCredentials=!1),"responseType"in u&&(s?u.responseType="blob":h&&a.headers.get("Content-Type")&&-1!==a.headers.get("Content-Type").indexOf("application/octet-stream")&&(u.responseType="arraybuffer")),!r||"object"!=typeof r.headers||r.headers instanceof d?a.headers.forEach((function(t,e){u.setRequestHeader(e,t)})):Object.getOwnPropertyNames(r.headers).forEach((function(t){u.setRequestHeader(t,f(r.headers[t]))})),a.signal&&(a.signal.addEventListener("abort",c),u.onreadystatechange=function(){4===u.readyState&&a.signal.removeEventListener("abort",c)}),u.send(void 0===a._bodyInit?null:a._bodyInit)}))}g.polyfill=!0,o.fetch||(o.fetch=g,o.Headers=d,o.Request=E,o.Response=A),t.Headers=d,t.Request=E,t.Response=A,t.fetch=g,Object.defineProperty(t,"__esModule",{value:!0})})); vendor/wp-polyfill-formdata.js 0000666 00000027142 15123355174 0012470 0 ustar 00 /* formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
/* global FormData self Blob File */
/* eslint-disable no-inner-declarations */
if (typeof Blob !== 'undefined' && (typeof FormData === 'undefined' || !FormData.prototype.keys)) {
const global = typeof globalThis === 'object'
? globalThis
: typeof window === 'object'
? window
: typeof self === 'object' ? self : this
// keep a reference to native implementation
const _FormData = global.FormData
// To be monkey patched
const _send = global.XMLHttpRequest && global.XMLHttpRequest.prototype.send
const _fetch = global.Request && global.fetch
const _sendBeacon = global.navigator && global.navigator.sendBeacon
// Might be a worker thread...
const _match = global.Element && global.Element.prototype
// Unable to patch Request/Response constructor correctly #109
// only way is to use ES6 class extend
// https://github.com/babel/babel/issues/1966
const stringTag = global.Symbol && Symbol.toStringTag
// Add missing stringTags to blob and files
if (stringTag) {
if (!Blob.prototype[stringTag]) {
Blob.prototype[stringTag] = 'Blob'
}
if ('File' in global && !File.prototype[stringTag]) {
File.prototype[stringTag] = 'File'
}
}
// Fix so you can construct your own File
try {
new File([], '') // eslint-disable-line
} catch (a) {
global.File = function File (b, d, c) {
const blob = new Blob(b, c || {})
const t = c && void 0 !== c.lastModified ? new Date(c.lastModified) : new Date()
Object.defineProperties(blob, {
name: {
value: d
},
lastModified: {
value: +t
},
toString: {
value () {
return '[object File]'
}
}
})
if (stringTag) {
Object.defineProperty(blob, stringTag, {
value: 'File'
})
}
return blob
}
}
function ensureArgs (args, expected) {
if (args.length < expected) {
throw new TypeError(`${expected} argument required, but only ${args.length} present.`)
}
}
/**
* @param {string} name
* @param {string | undefined} filename
* @returns {[string, File|string]}
*/
function normalizeArgs (name, value, filename) {
if (value instanceof Blob) {
filename = filename !== undefined
? String(filename + '')
: typeof value.name === 'string'
? value.name
: 'blob'
if (value.name !== filename || Object.prototype.toString.call(value) === '[object Blob]') {
value = new File([value], filename)
}
return [String(name), value]
}
return [String(name), String(value)]
}
// normalize line feeds for textarea
// https://html.spec.whatwg.org/multipage/form-elements.html#textarea-line-break-normalisation-transformation
function normalizeLinefeeds (value) {
return value.replace(/\r?\n|\r/g, '\r\n')
}
/**
* @template T
* @param {ArrayLike<T>} arr
* @param {{ (elm: T): void; }} cb
*/
function each (arr, cb) {
for (let i = 0; i < arr.length; i++) {
cb(arr[i])
}
}
const escape = str => str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22')
/**
* @implements {Iterable}
*/
class FormDataPolyfill {
/**
* FormData class
*
* @param {HTMLFormElement=} form
*/
constructor (form) {
/** @type {[string, string|File][]} */
this._data = []
const self = this
form && each(form.elements, (/** @type {HTMLInputElement} */ elm) => {
if (
!elm.name ||
elm.disabled ||
elm.type === 'submit' ||
elm.type === 'button' ||
elm.matches('form fieldset[disabled] *')
) return
if (elm.type === 'file') {
const files = elm.files && elm.files.length
? elm.files
: [new File([], '', { type: 'application/octet-stream' })] // #78
each(files, file => {
self.append(elm.name, file)
})
} else if (elm.type === 'select-multiple' || elm.type === 'select-one') {
each(elm.options, opt => {
!opt.disabled && opt.selected && self.append(elm.name, opt.value)
})
} else if (elm.type === 'checkbox' || elm.type === 'radio') {
if (elm.checked) self.append(elm.name, elm.value)
} else {
const value = elm.type === 'textarea' ? normalizeLinefeeds(elm.value) : elm.value
self.append(elm.name, value)
}
})
}
/**
* Append a field
*
* @param {string} name field name
* @param {string|Blob|File} value string / blob / file
* @param {string=} filename filename to use with blob
* @return {undefined}
*/
append (name, value, filename) {
ensureArgs(arguments, 2)
this._data.push(normalizeArgs(name, value, filename))
}
/**
* Delete all fields values given name
*
* @param {string} name Field name
* @return {undefined}
*/
delete (name) {
ensureArgs(arguments, 1)
const result = []
name = String(name)
each(this._data, entry => {
entry[0] !== name && result.push(entry)
})
this._data = result
}
/**
* Iterate over all fields as [name, value]
*
* @return {Iterator}
*/
* entries () {
for (var i = 0; i < this._data.length; i++) {
yield this._data[i]
}
}
/**
* Iterate over all fields
*
* @param {Function} callback Executed for each item with parameters (value, name, thisArg)
* @param {Object=} thisArg `this` context for callback function
*/
forEach (callback, thisArg) {
ensureArgs(arguments, 1)
for (const [name, value] of this) {
callback.call(thisArg, value, name, this)
}
}
/**
* Return first field value given name
* or null if non existent
*
* @param {string} name Field name
* @return {string|File|null} value Fields value
*/
get (name) {
ensureArgs(arguments, 1)
const entries = this._data
name = String(name)
for (let i = 0; i < entries.length; i++) {
if (entries[i][0] === name) {
return entries[i][1]
}
}
return null
}
/**
* Return all fields values given name
*
* @param {string} name Fields name
* @return {Array} [{String|File}]
*/
getAll (name) {
ensureArgs(arguments, 1)
const result = []
name = String(name)
each(this._data, data => {
data[0] === name && result.push(data[1])
})
return result
}
/**
* Check for field name existence
*
* @param {string} name Field name
* @return {boolean}
*/
has (name) {
ensureArgs(arguments, 1)
name = String(name)
for (let i = 0; i < this._data.length; i++) {
if (this._data[i][0] === name) {
return true
}
}
return false
}
/**
* Iterate over all fields name
*
* @return {Iterator}
*/
* keys () {
for (const [name] of this) {
yield name
}
}
/**
* Overwrite all values given name
*
* @param {string} name Filed name
* @param {string} value Field value
* @param {string=} filename Filename (optional)
*/
set (name, value, filename) {
ensureArgs(arguments, 2)
name = String(name)
/** @type {[string, string|File][]} */
const result = []
const args = normalizeArgs(name, value, filename)
let replace = true
// - replace the first occurrence with same name
// - discards the remaining with same name
// - while keeping the same order items where added
each(this._data, data => {
data[0] === name
? replace && (replace = !result.push(args))
: result.push(data)
})
replace && result.push(args)
this._data = result
}
/**
* Iterate over all fields
*
* @return {Iterator}
*/
* values () {
for (const [, value] of this) {
yield value
}
}
/**
* Return a native (perhaps degraded) FormData with only a `append` method
* Can throw if it's not supported
*
* @return {FormData}
*/
['_asNative'] () {
const fd = new _FormData()
for (const [name, value] of this) {
fd.append(name, value)
}
return fd
}
/**
* [_blob description]
*
* @return {Blob} [description]
*/
['_blob'] () {
const boundary = '----formdata-polyfill-' + Math.random(),
chunks = [],
p = `--${boundary}\r\nContent-Disposition: form-data; name="`
this.forEach((value, name) => typeof value == 'string'
? chunks.push(p + escape(normalizeLinefeeds(name)) + `"\r\n\r\n${normalizeLinefeeds(value)}\r\n`)
: chunks.push(p + escape(normalizeLinefeeds(name)) + `"; filename="${escape(value.name)}"\r\nContent-Type: ${value.type||"application/octet-stream"}\r\n\r\n`, value, `\r\n`))
chunks.push(`--${boundary}--`)
return new Blob(chunks, {
type: "multipart/form-data; boundary=" + boundary
})
}
/**
* The class itself is iterable
* alias for formdata.entries()
*
* @return {Iterator}
*/
[Symbol.iterator] () {
return this.entries()
}
/**
* Create the default string description.
*
* @return {string} [object FormData]
*/
toString () {
return '[object FormData]'
}
}
if (_match && !_match.matches) {
_match.matches =
_match.matchesSelector ||
_match.mozMatchesSelector ||
_match.msMatchesSelector ||
_match.oMatchesSelector ||
_match.webkitMatchesSelector ||
function (s) {
var matches = (this.document || this.ownerDocument).querySelectorAll(s)
var i = matches.length
while (--i >= 0 && matches.item(i) !== this) {}
return i > -1
}
}
if (stringTag) {
/**
* Create the default string description.
* It is accessed internally by the Object.prototype.toString().
*/
FormDataPolyfill.prototype[stringTag] = 'FormData'
}
// Patch xhr's send method to call _blob transparently
if (_send) {
const setRequestHeader = global.XMLHttpRequest.prototype.setRequestHeader
global.XMLHttpRequest.prototype.setRequestHeader = function (name, value) {
setRequestHeader.call(this, name, value)
if (name.toLowerCase() === 'content-type') this._hasContentType = true
}
global.XMLHttpRequest.prototype.send = function (data) {
// need to patch send b/c old IE don't send blob's type (#44)
if (data instanceof FormDataPolyfill) {
const blob = data['_blob']()
if (!this._hasContentType) this.setRequestHeader('Content-Type', blob.type)
_send.call(this, blob)
} else {
_send.call(this, data)
}
}
}
// Patch fetch's function to call _blob transparently
if (_fetch) {
global.fetch = function (input, init) {
if (init && init.body && init.body instanceof FormDataPolyfill) {
init.body = init.body['_blob']()
}
return _fetch.call(this, input, init)
}
}
// Patch navigator.sendBeacon to use native FormData
if (_sendBeacon) {
global.navigator.sendBeacon = function (url, data) {
if (data instanceof FormDataPolyfill) {
data = data['_asNative']()
}
return _sendBeacon.call(this, url, data)
}
}
global['FormData'] = FormDataPolyfill
}
vendor/moment.min.js 0000666 00000161105 15123355174 0010476 0 ustar 00 !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.moment=t()}(this,function(){"use strict";var H;function _(){return H.apply(null,arguments)}function y(e){return e instanceof Array||"[object Array]"===Object.prototype.toString.call(e)}function F(e){return null!=e&&"[object Object]"===Object.prototype.toString.call(e)}function c(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function L(e){if(Object.getOwnPropertyNames)return 0===Object.getOwnPropertyNames(e).length;for(var t in e)if(c(e,t))return;return 1}function g(e){return void 0===e}function w(e){return"number"==typeof e||"[object Number]"===Object.prototype.toString.call(e)}function V(e){return e instanceof Date||"[object Date]"===Object.prototype.toString.call(e)}function G(e,t){for(var n=[],s=e.length,i=0;i<s;++i)n.push(t(e[i],i));return n}function E(e,t){for(var n in t)c(t,n)&&(e[n]=t[n]);return c(t,"toString")&&(e.toString=t.toString),c(t,"valueOf")&&(e.valueOf=t.valueOf),e}function l(e,t,n,s){return Pt(e,t,n,s,!0).utc()}function p(e){return null==e._pf&&(e._pf={empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidEra:null,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],era:null,meridiem:null,rfc2822:!1,weekdayMismatch:!1}),e._pf}function A(e){if(null==e._isValid){var t=p(e),n=j.call(t.parsedDateParts,function(e){return null!=e}),n=!isNaN(e._d.getTime())&&t.overflow<0&&!t.empty&&!t.invalidEra&&!t.invalidMonth&&!t.invalidWeekday&&!t.weekdayMismatch&&!t.nullInput&&!t.invalidFormat&&!t.userInvalidated&&(!t.meridiem||t.meridiem&&n);if(e._strict&&(n=n&&0===t.charsLeftOver&&0===t.unusedTokens.length&&void 0===t.bigHour),null!=Object.isFrozen&&Object.isFrozen(e))return n;e._isValid=n}return e._isValid}function I(e){var t=l(NaN);return null!=e?E(p(t),e):p(t).userInvalidated=!0,t}var j=Array.prototype.some||function(e){for(var t=Object(this),n=t.length>>>0,s=0;s<n;s++)if(s in t&&e.call(this,t[s],s,t))return!0;return!1},Z=_.momentProperties=[],z=!1;function $(e,t){var n,s,i,r=Z.length;if(g(t._isAMomentObject)||(e._isAMomentObject=t._isAMomentObject),g(t._i)||(e._i=t._i),g(t._f)||(e._f=t._f),g(t._l)||(e._l=t._l),g(t._strict)||(e._strict=t._strict),g(t._tzm)||(e._tzm=t._tzm),g(t._isUTC)||(e._isUTC=t._isUTC),g(t._offset)||(e._offset=t._offset),g(t._pf)||(e._pf=p(t)),g(t._locale)||(e._locale=t._locale),0<r)for(n=0;n<r;n++)g(i=t[s=Z[n]])||(e[s]=i);return e}function q(e){$(this,e),this._d=new Date(null!=e._d?e._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),!1===z&&(z=!0,_.updateOffset(this),z=!1)}function v(e){return e instanceof q||null!=e&&null!=e._isAMomentObject}function B(e){!1===_.suppressDeprecationWarnings&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+e)}function e(r,a){var o=!0;return E(function(){if(null!=_.deprecationHandler&&_.deprecationHandler(null,r),o){for(var e,t,n=[],s=arguments.length,i=0;i<s;i++){if(e="","object"==typeof arguments[i]){for(t in e+="\n["+i+"] ",arguments[0])c(arguments[0],t)&&(e+=t+": "+arguments[0][t]+", ");e=e.slice(0,-2)}else e=arguments[i];n.push(e)}B(r+"\nArguments: "+Array.prototype.slice.call(n).join("")+"\n"+(new Error).stack),o=!1}return a.apply(this,arguments)},a)}var J={};function Q(e,t){null!=_.deprecationHandler&&_.deprecationHandler(e,t),J[e]||(B(t),J[e]=!0)}function a(e){return"undefined"!=typeof Function&&e instanceof Function||"[object Function]"===Object.prototype.toString.call(e)}function X(e,t){var n,s=E({},e);for(n in t)c(t,n)&&(F(e[n])&&F(t[n])?(s[n]={},E(s[n],e[n]),E(s[n],t[n])):null!=t[n]?s[n]=t[n]:delete s[n]);for(n in e)c(e,n)&&!c(t,n)&&F(e[n])&&(s[n]=E({},s[n]));return s}function K(e){null!=e&&this.set(e)}_.suppressDeprecationWarnings=!1,_.deprecationHandler=null;var ee=Object.keys||function(e){var t,n=[];for(t in e)c(e,t)&&n.push(t);return n};function r(e,t,n){var s=""+Math.abs(e);return(0<=e?n?"+":"":"-")+Math.pow(10,Math.max(0,t-s.length)).toString().substr(1)+s}var te=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,ne=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,se={},ie={};function s(e,t,n,s){var i="string"==typeof s?function(){return this[s]()}:s;e&&(ie[e]=i),t&&(ie[t[0]]=function(){return r(i.apply(this,arguments),t[1],t[2])}),n&&(ie[n]=function(){return this.localeData().ordinal(i.apply(this,arguments),e)})}function re(e,t){return e.isValid()?(t=ae(t,e.localeData()),se[t]=se[t]||function(s){for(var e,i=s.match(te),t=0,r=i.length;t<r;t++)ie[i[t]]?i[t]=ie[i[t]]:i[t]=(e=i[t]).match(/\[[\s\S]/)?e.replace(/^\[|\]$/g,""):e.replace(/\\/g,"");return function(e){for(var t="",n=0;n<r;n++)t+=a(i[n])?i[n].call(e,s):i[n];return t}}(t),se[t](e)):e.localeData().invalidDate()}function ae(e,t){var n=5;function s(e){return t.longDateFormat(e)||e}for(ne.lastIndex=0;0<=n&&ne.test(e);)e=e.replace(ne,s),ne.lastIndex=0,--n;return e}var oe={};function t(e,t){var n=e.toLowerCase();oe[n]=oe[n+"s"]=oe[t]=e}function o(e){return"string"==typeof e?oe[e]||oe[e.toLowerCase()]:void 0}function ue(e){var t,n,s={};for(n in e)c(e,n)&&(t=o(n))&&(s[t]=e[n]);return s}var le={};function n(e,t){le[e]=t}function he(e){return e%4==0&&e%100!=0||e%400==0}function d(e){return e<0?Math.ceil(e)||0:Math.floor(e)}function h(e){var e=+e,t=0;return t=0!=e&&isFinite(e)?d(e):t}function de(t,n){return function(e){return null!=e?(fe(this,t,e),_.updateOffset(this,n),this):ce(this,t)}}function ce(e,t){return e.isValid()?e._d["get"+(e._isUTC?"UTC":"")+t]():NaN}function fe(e,t,n){e.isValid()&&!isNaN(n)&&("FullYear"===t&&he(e.year())&&1===e.month()&&29===e.date()?(n=h(n),e._d["set"+(e._isUTC?"UTC":"")+t](n,e.month(),We(n,e.month()))):e._d["set"+(e._isUTC?"UTC":"")+t](n))}var i=/\d/,u=/\d\d/,me=/\d{3}/,_e=/\d{4}/,ye=/[+-]?\d{6}/,f=/\d\d?/,ge=/\d\d\d\d?/,we=/\d\d\d\d\d\d?/,pe=/\d{1,3}/,ve=/\d{1,4}/,ke=/[+-]?\d{1,6}/,Me=/\d+/,De=/[+-]?\d+/,Se=/Z|[+-]\d\d:?\d\d/gi,Ye=/Z|[+-]\d\d(?::?\d\d)?/gi,m=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i;function k(e,n,s){be[e]=a(n)?n:function(e,t){return e&&s?s:n}}function Oe(e,t){return c(be,e)?be[e](t._strict,t._locale):new RegExp(M(e.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(e,t,n,s,i){return t||n||s||i})))}function M(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}var be={},xe={};function D(e,n){var t,s,i=n;for("string"==typeof e&&(e=[e]),w(n)&&(i=function(e,t){t[n]=h(e)}),s=e.length,t=0;t<s;t++)xe[e[t]]=i}function Te(e,i){D(e,function(e,t,n,s){n._w=n._w||{},i(e,n._w,n,s)})}var S,Y=0,O=1,b=2,x=3,T=4,N=5,Ne=6,Pe=7,Re=8;function We(e,t){var n;return isNaN(e)||isNaN(t)?NaN:(n=(t%(n=12)+n)%n,e+=(t-n)/12,1==n?he(e)?29:28:31-n%7%2)}S=Array.prototype.indexOf||function(e){for(var t=0;t<this.length;++t)if(this[t]===e)return t;return-1},s("M",["MM",2],"Mo",function(){return this.month()+1}),s("MMM",0,0,function(e){return this.localeData().monthsShort(this,e)}),s("MMMM",0,0,function(e){return this.localeData().months(this,e)}),t("month","M"),n("month",8),k("M",f),k("MM",f,u),k("MMM",function(e,t){return t.monthsShortRegex(e)}),k("MMMM",function(e,t){return t.monthsRegex(e)}),D(["M","MM"],function(e,t){t[O]=h(e)-1}),D(["MMM","MMMM"],function(e,t,n,s){s=n._locale.monthsParse(e,s,n._strict);null!=s?t[O]=s:p(n).invalidMonth=e});var Ce="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),Ue="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),He=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,Fe=m,Le=m;function Ve(e,t){var n;if(e.isValid()){if("string"==typeof t)if(/^\d+$/.test(t))t=h(t);else if(!w(t=e.localeData().monthsParse(t)))return;n=Math.min(e.date(),We(e.year(),t)),e._d["set"+(e._isUTC?"UTC":"")+"Month"](t,n)}}function Ge(e){return null!=e?(Ve(this,e),_.updateOffset(this,!0),this):ce(this,"Month")}function Ee(){function e(e,t){return t.length-e.length}for(var t,n=[],s=[],i=[],r=0;r<12;r++)t=l([2e3,r]),n.push(this.monthsShort(t,"")),s.push(this.months(t,"")),i.push(this.months(t,"")),i.push(this.monthsShort(t,""));for(n.sort(e),s.sort(e),i.sort(e),r=0;r<12;r++)n[r]=M(n[r]),s[r]=M(s[r]);for(r=0;r<24;r++)i[r]=M(i[r]);this._monthsRegex=new RegExp("^("+i.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+s.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+n.join("|")+")","i")}function Ae(e){return he(e)?366:365}s("Y",0,0,function(){var e=this.year();return e<=9999?r(e,4):"+"+e}),s(0,["YY",2],0,function(){return this.year()%100}),s(0,["YYYY",4],0,"year"),s(0,["YYYYY",5],0,"year"),s(0,["YYYYYY",6,!0],0,"year"),t("year","y"),n("year",1),k("Y",De),k("YY",f,u),k("YYYY",ve,_e),k("YYYYY",ke,ye),k("YYYYYY",ke,ye),D(["YYYYY","YYYYYY"],Y),D("YYYY",function(e,t){t[Y]=2===e.length?_.parseTwoDigitYear(e):h(e)}),D("YY",function(e,t){t[Y]=_.parseTwoDigitYear(e)}),D("Y",function(e,t){t[Y]=parseInt(e,10)}),_.parseTwoDigitYear=function(e){return h(e)+(68<h(e)?1900:2e3)};var Ie=de("FullYear",!0);function je(e,t,n,s,i,r,a){var o;return e<100&&0<=e?(o=new Date(e+400,t,n,s,i,r,a),isFinite(o.getFullYear())&&o.setFullYear(e)):o=new Date(e,t,n,s,i,r,a),o}function Ze(e){var t;return e<100&&0<=e?((t=Array.prototype.slice.call(arguments))[0]=e+400,t=new Date(Date.UTC.apply(null,t)),isFinite(t.getUTCFullYear())&&t.setUTCFullYear(e)):t=new Date(Date.UTC.apply(null,arguments)),t}function ze(e,t,n){n=7+t-n;return n-(7+Ze(e,0,n).getUTCDay()-t)%7-1}function $e(e,t,n,s,i){var r,t=1+7*(t-1)+(7+n-s)%7+ze(e,s,i),n=t<=0?Ae(r=e-1)+t:t>Ae(e)?(r=e+1,t-Ae(e)):(r=e,t);return{year:r,dayOfYear:n}}function qe(e,t,n){var s,i,r=ze(e.year(),t,n),r=Math.floor((e.dayOfYear()-r-1)/7)+1;return r<1?s=r+P(i=e.year()-1,t,n):r>P(e.year(),t,n)?(s=r-P(e.year(),t,n),i=e.year()+1):(i=e.year(),s=r),{week:s,year:i}}function P(e,t,n){var s=ze(e,t,n),t=ze(e+1,t,n);return(Ae(e)-s+t)/7}s("w",["ww",2],"wo","week"),s("W",["WW",2],"Wo","isoWeek"),t("week","w"),t("isoWeek","W"),n("week",5),n("isoWeek",5),k("w",f),k("ww",f,u),k("W",f),k("WW",f,u),Te(["w","ww","W","WW"],function(e,t,n,s){t[s.substr(0,1)]=h(e)});function Be(e,t){return e.slice(t,7).concat(e.slice(0,t))}s("d",0,"do","day"),s("dd",0,0,function(e){return this.localeData().weekdaysMin(this,e)}),s("ddd",0,0,function(e){return this.localeData().weekdaysShort(this,e)}),s("dddd",0,0,function(e){return this.localeData().weekdays(this,e)}),s("e",0,0,"weekday"),s("E",0,0,"isoWeekday"),t("day","d"),t("weekday","e"),t("isoWeekday","E"),n("day",11),n("weekday",11),n("isoWeekday",11),k("d",f),k("e",f),k("E",f),k("dd",function(e,t){return t.weekdaysMinRegex(e)}),k("ddd",function(e,t){return t.weekdaysShortRegex(e)}),k("dddd",function(e,t){return t.weekdaysRegex(e)}),Te(["dd","ddd","dddd"],function(e,t,n,s){s=n._locale.weekdaysParse(e,s,n._strict);null!=s?t.d=s:p(n).invalidWeekday=e}),Te(["d","e","E"],function(e,t,n,s){t[s]=h(e)});var Je="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),Qe="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),Xe="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),Ke=m,et=m,tt=m;function nt(){function e(e,t){return t.length-e.length}for(var t,n,s,i=[],r=[],a=[],o=[],u=0;u<7;u++)s=l([2e3,1]).day(u),t=M(this.weekdaysMin(s,"")),n=M(this.weekdaysShort(s,"")),s=M(this.weekdays(s,"")),i.push(t),r.push(n),a.push(s),o.push(t),o.push(n),o.push(s);i.sort(e),r.sort(e),a.sort(e),o.sort(e),this._weekdaysRegex=new RegExp("^("+o.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+a.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+r.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+i.join("|")+")","i")}function st(){return this.hours()%12||12}function it(e,t){s(e,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)})}function rt(e,t){return t._meridiemParse}s("H",["HH",2],0,"hour"),s("h",["hh",2],0,st),s("k",["kk",2],0,function(){return this.hours()||24}),s("hmm",0,0,function(){return""+st.apply(this)+r(this.minutes(),2)}),s("hmmss",0,0,function(){return""+st.apply(this)+r(this.minutes(),2)+r(this.seconds(),2)}),s("Hmm",0,0,function(){return""+this.hours()+r(this.minutes(),2)}),s("Hmmss",0,0,function(){return""+this.hours()+r(this.minutes(),2)+r(this.seconds(),2)}),it("a",!0),it("A",!1),t("hour","h"),n("hour",13),k("a",rt),k("A",rt),k("H",f),k("h",f),k("k",f),k("HH",f,u),k("hh",f,u),k("kk",f,u),k("hmm",ge),k("hmmss",we),k("Hmm",ge),k("Hmmss",we),D(["H","HH"],x),D(["k","kk"],function(e,t,n){e=h(e);t[x]=24===e?0:e}),D(["a","A"],function(e,t,n){n._isPm=n._locale.isPM(e),n._meridiem=e}),D(["h","hh"],function(e,t,n){t[x]=h(e),p(n).bigHour=!0}),D("hmm",function(e,t,n){var s=e.length-2;t[x]=h(e.substr(0,s)),t[T]=h(e.substr(s)),p(n).bigHour=!0}),D("hmmss",function(e,t,n){var s=e.length-4,i=e.length-2;t[x]=h(e.substr(0,s)),t[T]=h(e.substr(s,2)),t[N]=h(e.substr(i)),p(n).bigHour=!0}),D("Hmm",function(e,t,n){var s=e.length-2;t[x]=h(e.substr(0,s)),t[T]=h(e.substr(s))}),D("Hmmss",function(e,t,n){var s=e.length-4,i=e.length-2;t[x]=h(e.substr(0,s)),t[T]=h(e.substr(s,2)),t[N]=h(e.substr(i))});m=de("Hours",!0);var at,ot={calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},longDateFormat:{LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},invalidDate:"Invalid date",ordinal:"%d",dayOfMonthOrdinalParse:/\d{1,2}/,relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",w:"a week",ww:"%d weeks",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},months:Ce,monthsShort:Ue,week:{dow:0,doy:6},weekdays:Je,weekdaysMin:Xe,weekdaysShort:Qe,meridiemParse:/[ap]\.?m?\.?/i},R={},ut={};function lt(e){return e&&e.toLowerCase().replace("_","-")}function ht(e){for(var t,n,s,i,r=0;r<e.length;){for(t=(i=lt(e[r]).split("-")).length,n=(n=lt(e[r+1]))?n.split("-"):null;0<t;){if(s=dt(i.slice(0,t).join("-")))return s;if(n&&n.length>=t&&function(e,t){for(var n=Math.min(e.length,t.length),s=0;s<n;s+=1)if(e[s]!==t[s])return s;return n}(i,n)>=t-1)break;t--}r++}return at}function dt(t){var e;if(void 0===R[t]&&"undefined"!=typeof module&&module&&module.exports&&null!=t.match("^[^/\\\\]*$"))try{e=at._abbr,require("./locale/"+t),ct(e)}catch(e){R[t]=null}return R[t]}function ct(e,t){return e&&((t=g(t)?mt(e):ft(e,t))?at=t:"undefined"!=typeof console&&console.warn&&console.warn("Locale "+e+" not found. Did you forget to load it?")),at._abbr}function ft(e,t){if(null===t)return delete R[e],null;var n,s=ot;if(t.abbr=e,null!=R[e])Q("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),s=R[e]._config;else if(null!=t.parentLocale)if(null!=R[t.parentLocale])s=R[t.parentLocale]._config;else{if(null==(n=dt(t.parentLocale)))return ut[t.parentLocale]||(ut[t.parentLocale]=[]),ut[t.parentLocale].push({name:e,config:t}),null;s=n._config}return R[e]=new K(X(s,t)),ut[e]&&ut[e].forEach(function(e){ft(e.name,e.config)}),ct(e),R[e]}function mt(e){var t;if(!(e=e&&e._locale&&e._locale._abbr?e._locale._abbr:e))return at;if(!y(e)){if(t=dt(e))return t;e=[e]}return ht(e)}function _t(e){var t=e._a;return t&&-2===p(e).overflow&&(t=t[O]<0||11<t[O]?O:t[b]<1||t[b]>We(t[Y],t[O])?b:t[x]<0||24<t[x]||24===t[x]&&(0!==t[T]||0!==t[N]||0!==t[Ne])?x:t[T]<0||59<t[T]?T:t[N]<0||59<t[N]?N:t[Ne]<0||999<t[Ne]?Ne:-1,p(e)._overflowDayOfYear&&(t<Y||b<t)&&(t=b),p(e)._overflowWeeks&&-1===t&&(t=Pe),p(e)._overflowWeekday&&-1===t&&(t=Re),p(e).overflow=t),e}var yt=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,gt=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,wt=/Z|[+-]\d\d(?::?\d\d)?/,pt=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/],["YYYYMM",/\d{6}/,!1],["YYYY",/\d{4}/,!1]],vt=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],kt=/^\/?Date\((-?\d+)/i,Mt=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,Dt={UT:0,GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function St(e){var t,n,s,i,r,a,o=e._i,u=yt.exec(o)||gt.exec(o),o=pt.length,l=vt.length;if(u){for(p(e).iso=!0,t=0,n=o;t<n;t++)if(pt[t][1].exec(u[1])){i=pt[t][0],s=!1!==pt[t][2];break}if(null==i)e._isValid=!1;else{if(u[3]){for(t=0,n=l;t<n;t++)if(vt[t][1].exec(u[3])){r=(u[2]||" ")+vt[t][0];break}if(null==r)return void(e._isValid=!1)}if(s||null==r){if(u[4]){if(!wt.exec(u[4]))return void(e._isValid=!1);a="Z"}e._f=i+(r||"")+(a||""),Tt(e)}else e._isValid=!1}}else e._isValid=!1}function Yt(e,t,n,s,i,r){e=[function(e){e=parseInt(e,10);{if(e<=49)return 2e3+e;if(e<=999)return 1900+e}return e}(e),Ue.indexOf(t),parseInt(n,10),parseInt(s,10),parseInt(i,10)];return r&&e.push(parseInt(r,10)),e}function Ot(e){var t,n,s=Mt.exec(e._i.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").replace(/^\s\s*/,"").replace(/\s\s*$/,""));s?(t=Yt(s[4],s[3],s[2],s[5],s[6],s[7]),function(e,t,n){if(!e||Qe.indexOf(e)===new Date(t[0],t[1],t[2]).getDay())return 1;p(n).weekdayMismatch=!0,n._isValid=!1}(s[1],t,e)&&(e._a=t,e._tzm=(t=s[8],n=s[9],s=s[10],t?Dt[t]:n?0:60*(((t=parseInt(s,10))-(n=t%100))/100)+n),e._d=Ze.apply(null,e._a),e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),p(e).rfc2822=!0)):e._isValid=!1}function bt(e,t,n){return null!=e?e:null!=t?t:n}function xt(e){var t,n,s,i,r,a,o,u,l,h,d,c=[];if(!e._d){for(s=e,i=new Date(_.now()),n=s._useUTC?[i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate()]:[i.getFullYear(),i.getMonth(),i.getDate()],e._w&&null==e._a[b]&&null==e._a[O]&&(null!=(i=(s=e)._w).GG||null!=i.W||null!=i.E?(u=1,l=4,r=bt(i.GG,s._a[Y],qe(W(),1,4).year),a=bt(i.W,1),((o=bt(i.E,1))<1||7<o)&&(h=!0)):(u=s._locale._week.dow,l=s._locale._week.doy,d=qe(W(),u,l),r=bt(i.gg,s._a[Y],d.year),a=bt(i.w,d.week),null!=i.d?((o=i.d)<0||6<o)&&(h=!0):null!=i.e?(o=i.e+u,(i.e<0||6<i.e)&&(h=!0)):o=u),a<1||a>P(r,u,l)?p(s)._overflowWeeks=!0:null!=h?p(s)._overflowWeekday=!0:(d=$e(r,a,o,u,l),s._a[Y]=d.year,s._dayOfYear=d.dayOfYear)),null!=e._dayOfYear&&(i=bt(e._a[Y],n[Y]),(e._dayOfYear>Ae(i)||0===e._dayOfYear)&&(p(e)._overflowDayOfYear=!0),h=Ze(i,0,e._dayOfYear),e._a[O]=h.getUTCMonth(),e._a[b]=h.getUTCDate()),t=0;t<3&&null==e._a[t];++t)e._a[t]=c[t]=n[t];for(;t<7;t++)e._a[t]=c[t]=null==e._a[t]?2===t?1:0:e._a[t];24===e._a[x]&&0===e._a[T]&&0===e._a[N]&&0===e._a[Ne]&&(e._nextDay=!0,e._a[x]=0),e._d=(e._useUTC?Ze:je).apply(null,c),r=e._useUTC?e._d.getUTCDay():e._d.getDay(),null!=e._tzm&&e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),e._nextDay&&(e._a[x]=24),e._w&&void 0!==e._w.d&&e._w.d!==r&&(p(e).weekdayMismatch=!0)}}function Tt(e){if(e._f===_.ISO_8601)St(e);else if(e._f===_.RFC_2822)Ot(e);else{e._a=[],p(e).empty=!0;for(var t,n,s,i,r,a=""+e._i,o=a.length,u=0,l=ae(e._f,e._locale).match(te)||[],h=l.length,d=0;d<h;d++)n=l[d],(t=(a.match(Oe(n,e))||[])[0])&&(0<(s=a.substr(0,a.indexOf(t))).length&&p(e).unusedInput.push(s),a=a.slice(a.indexOf(t)+t.length),u+=t.length),ie[n]?(t?p(e).empty=!1:p(e).unusedTokens.push(n),s=n,r=e,null!=(i=t)&&c(xe,s)&&xe[s](i,r._a,r,s)):e._strict&&!t&&p(e).unusedTokens.push(n);p(e).charsLeftOver=o-u,0<a.length&&p(e).unusedInput.push(a),e._a[x]<=12&&!0===p(e).bigHour&&0<e._a[x]&&(p(e).bigHour=void 0),p(e).parsedDateParts=e._a.slice(0),p(e).meridiem=e._meridiem,e._a[x]=function(e,t,n){if(null==n)return t;return null!=e.meridiemHour?e.meridiemHour(t,n):null!=e.isPM?((e=e.isPM(n))&&t<12&&(t+=12),t=e||12!==t?t:0):t}(e._locale,e._a[x],e._meridiem),null!==(o=p(e).era)&&(e._a[Y]=e._locale.erasConvertYear(o,e._a[Y])),xt(e),_t(e)}}function Nt(e){var t,n,s,i=e._i,r=e._f;if(e._locale=e._locale||mt(e._l),null===i||void 0===r&&""===i)return I({nullInput:!0});if("string"==typeof i&&(e._i=i=e._locale.preparse(i)),v(i))return new q(_t(i));if(V(i))e._d=i;else if(y(r)){var a,o,u,l,h,d,c=e,f=!1,m=c._f.length;if(0===m)p(c).invalidFormat=!0,c._d=new Date(NaN);else{for(l=0;l<m;l++)h=0,d=!1,a=$({},c),null!=c._useUTC&&(a._useUTC=c._useUTC),a._f=c._f[l],Tt(a),A(a)&&(d=!0),h=(h+=p(a).charsLeftOver)+10*p(a).unusedTokens.length,p(a).score=h,f?h<u&&(u=h,o=a):(null==u||h<u||d)&&(u=h,o=a,d)&&(f=!0);E(c,o||a)}}else if(r)Tt(e);else if(g(r=(i=e)._i))i._d=new Date(_.now());else V(r)?i._d=new Date(r.valueOf()):"string"==typeof r?(n=i,null!==(t=kt.exec(n._i))?n._d=new Date(+t[1]):(St(n),!1===n._isValid&&(delete n._isValid,Ot(n),!1===n._isValid)&&(delete n._isValid,n._strict?n._isValid=!1:_.createFromInputFallback(n)))):y(r)?(i._a=G(r.slice(0),function(e){return parseInt(e,10)}),xt(i)):F(r)?(t=i)._d||(s=void 0===(n=ue(t._i)).day?n.date:n.day,t._a=G([n.year,n.month,s,n.hour,n.minute,n.second,n.millisecond],function(e){return e&&parseInt(e,10)}),xt(t)):w(r)?i._d=new Date(r):_.createFromInputFallback(i);return A(e)||(e._d=null),e}function Pt(e,t,n,s,i){var r={};return!0!==t&&!1!==t||(s=t,t=void 0),!0!==n&&!1!==n||(s=n,n=void 0),(F(e)&&L(e)||y(e)&&0===e.length)&&(e=void 0),r._isAMomentObject=!0,r._useUTC=r._isUTC=i,r._l=n,r._i=e,r._f=t,r._strict=s,(i=new q(_t(Nt(i=r))))._nextDay&&(i.add(1,"d"),i._nextDay=void 0),i}function W(e,t,n,s){return Pt(e,t,n,s,!1)}_.createFromInputFallback=e("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",function(e){e._d=new Date(e._i+(e._useUTC?" UTC":""))}),_.ISO_8601=function(){},_.RFC_2822=function(){};ge=e("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=W.apply(null,arguments);return this.isValid()&&e.isValid()?e<this?this:e:I()}),we=e("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=W.apply(null,arguments);return this.isValid()&&e.isValid()?this<e?this:e:I()});function Rt(e,t){var n,s;if(!(t=1===t.length&&y(t[0])?t[0]:t).length)return W();for(n=t[0],s=1;s<t.length;++s)t[s].isValid()&&!t[s][e](n)||(n=t[s]);return n}var Wt=["year","quarter","month","week","day","hour","minute","second","millisecond"];function Ct(e){var e=ue(e),t=e.year||0,n=e.quarter||0,s=e.month||0,i=e.week||e.isoWeek||0,r=e.day||0,a=e.hour||0,o=e.minute||0,u=e.second||0,l=e.millisecond||0;this._isValid=function(e){var t,n,s=!1,i=Wt.length;for(t in e)if(c(e,t)&&(-1===S.call(Wt,t)||null!=e[t]&&isNaN(e[t])))return!1;for(n=0;n<i;++n)if(e[Wt[n]]){if(s)return!1;parseFloat(e[Wt[n]])!==h(e[Wt[n]])&&(s=!0)}return!0}(e),this._milliseconds=+l+1e3*u+6e4*o+1e3*a*60*60,this._days=+r+7*i,this._months=+s+3*n+12*t,this._data={},this._locale=mt(),this._bubble()}function Ut(e){return e instanceof Ct}function Ht(e){return e<0?-1*Math.round(-1*e):Math.round(e)}function Ft(e,n){s(e,0,0,function(){var e=this.utcOffset(),t="+";return e<0&&(e=-e,t="-"),t+r(~~(e/60),2)+n+r(~~e%60,2)})}Ft("Z",":"),Ft("ZZ",""),k("Z",Ye),k("ZZ",Ye),D(["Z","ZZ"],function(e,t,n){n._useUTC=!0,n._tzm=Vt(Ye,e)});var Lt=/([\+\-]|\d\d)/gi;function Vt(e,t){var t=(t||"").match(e);return null===t?null:0===(t=60*(e=((t[t.length-1]||[])+"").match(Lt)||["-",0,0])[1]+h(e[2]))?0:"+"===e[0]?t:-t}function Gt(e,t){var n;return t._isUTC?(t=t.clone(),n=(v(e)||V(e)?e:W(e)).valueOf()-t.valueOf(),t._d.setTime(t._d.valueOf()+n),_.updateOffset(t,!1),t):W(e).local()}function Et(e){return-Math.round(e._d.getTimezoneOffset())}function At(){return!!this.isValid()&&this._isUTC&&0===this._offset}_.updateOffset=function(){};var It=/^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,jt=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function C(e,t){var n,s=e;return Ut(e)?s={ms:e._milliseconds,d:e._days,M:e._months}:w(e)||!isNaN(+e)?(s={},t?s[t]=+e:s.milliseconds=+e):(t=It.exec(e))?(n="-"===t[1]?-1:1,s={y:0,d:h(t[b])*n,h:h(t[x])*n,m:h(t[T])*n,s:h(t[N])*n,ms:h(Ht(1e3*t[Ne]))*n}):(t=jt.exec(e))?(n="-"===t[1]?-1:1,s={y:Zt(t[2],n),M:Zt(t[3],n),w:Zt(t[4],n),d:Zt(t[5],n),h:Zt(t[6],n),m:Zt(t[7],n),s:Zt(t[8],n)}):null==s?s={}:"object"==typeof s&&("from"in s||"to"in s)&&(t=function(e,t){var n;if(!e.isValid()||!t.isValid())return{milliseconds:0,months:0};t=Gt(t,e),e.isBefore(t)?n=zt(e,t):((n=zt(t,e)).milliseconds=-n.milliseconds,n.months=-n.months);return n}(W(s.from),W(s.to)),(s={}).ms=t.milliseconds,s.M=t.months),n=new Ct(s),Ut(e)&&c(e,"_locale")&&(n._locale=e._locale),Ut(e)&&c(e,"_isValid")&&(n._isValid=e._isValid),n}function Zt(e,t){e=e&&parseFloat(e.replace(",","."));return(isNaN(e)?0:e)*t}function zt(e,t){var n={};return n.months=t.month()-e.month()+12*(t.year()-e.year()),e.clone().add(n.months,"M").isAfter(t)&&--n.months,n.milliseconds=+t-+e.clone().add(n.months,"M"),n}function $t(s,i){return function(e,t){var n;return null===t||isNaN(+t)||(Q(i,"moment()."+i+"(period, number) is deprecated. Please use moment()."+i+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),n=e,e=t,t=n),qt(this,C(e,t),s),this}}function qt(e,t,n,s){var i=t._milliseconds,r=Ht(t._days),t=Ht(t._months);e.isValid()&&(s=null==s||s,t&&Ve(e,ce(e,"Month")+t*n),r&&fe(e,"Date",ce(e,"Date")+r*n),i&&e._d.setTime(e._d.valueOf()+i*n),s)&&_.updateOffset(e,r||t)}C.fn=Ct.prototype,C.invalid=function(){return C(NaN)};Ce=$t(1,"add"),Je=$t(-1,"subtract");function Bt(e){return"string"==typeof e||e instanceof String}function Jt(e){return v(e)||V(e)||Bt(e)||w(e)||function(t){var e=y(t),n=!1;e&&(n=0===t.filter(function(e){return!w(e)&&Bt(t)}).length);return e&&n}(e)||function(e){var t,n,s=F(e)&&!L(e),i=!1,r=["years","year","y","months","month","M","days","day","d","dates","date","D","hours","hour","h","minutes","minute","m","seconds","second","s","milliseconds","millisecond","ms"],a=r.length;for(t=0;t<a;t+=1)n=r[t],i=i||c(e,n);return s&&i}(e)||null==e}function Qt(e,t){var n,s;return e.date()<t.date()?-Qt(t,e):-((n=12*(t.year()-e.year())+(t.month()-e.month()))+(t-(s=e.clone().add(n,"months"))<0?(t-s)/(s-e.clone().add(n-1,"months")):(t-s)/(e.clone().add(1+n,"months")-s)))||0}function Xt(e){return void 0===e?this._locale._abbr:(null!=(e=mt(e))&&(this._locale=e),this)}_.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",_.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";Xe=e("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(e){return void 0===e?this.localeData():this.locale(e)});function Kt(){return this._locale}var en=126227808e5;function tn(e,t){return(e%t+t)%t}function nn(e,t,n){return e<100&&0<=e?new Date(e+400,t,n)-en:new Date(e,t,n).valueOf()}function sn(e,t,n){return e<100&&0<=e?Date.UTC(e+400,t,n)-en:Date.UTC(e,t,n)}function rn(e,t){return t.erasAbbrRegex(e)}function an(){for(var e=[],t=[],n=[],s=[],i=this.eras(),r=0,a=i.length;r<a;++r)t.push(M(i[r].name)),e.push(M(i[r].abbr)),n.push(M(i[r].narrow)),s.push(M(i[r].name)),s.push(M(i[r].abbr)),s.push(M(i[r].narrow));this._erasRegex=new RegExp("^("+s.join("|")+")","i"),this._erasNameRegex=new RegExp("^("+t.join("|")+")","i"),this._erasAbbrRegex=new RegExp("^("+e.join("|")+")","i"),this._erasNarrowRegex=new RegExp("^("+n.join("|")+")","i")}function on(e,t){s(0,[e,e.length],0,t)}function un(e,t,n,s,i){var r;return null==e?qe(this,s,i).year:(r=P(e,s,i),function(e,t,n,s,i){e=$e(e,t,n,s,i),t=Ze(e.year,0,e.dayOfYear);return this.year(t.getUTCFullYear()),this.month(t.getUTCMonth()),this.date(t.getUTCDate()),this}.call(this,e,t=r<t?r:t,n,s,i))}s("N",0,0,"eraAbbr"),s("NN",0,0,"eraAbbr"),s("NNN",0,0,"eraAbbr"),s("NNNN",0,0,"eraName"),s("NNNNN",0,0,"eraNarrow"),s("y",["y",1],"yo","eraYear"),s("y",["yy",2],0,"eraYear"),s("y",["yyy",3],0,"eraYear"),s("y",["yyyy",4],0,"eraYear"),k("N",rn),k("NN",rn),k("NNN",rn),k("NNNN",function(e,t){return t.erasNameRegex(e)}),k("NNNNN",function(e,t){return t.erasNarrowRegex(e)}),D(["N","NN","NNN","NNNN","NNNNN"],function(e,t,n,s){s=n._locale.erasParse(e,s,n._strict);s?p(n).era=s:p(n).invalidEra=e}),k("y",Me),k("yy",Me),k("yyy",Me),k("yyyy",Me),k("yo",function(e,t){return t._eraYearOrdinalRegex||Me}),D(["y","yy","yyy","yyyy"],Y),D(["yo"],function(e,t,n,s){var i;n._locale._eraYearOrdinalRegex&&(i=e.match(n._locale._eraYearOrdinalRegex)),n._locale.eraYearOrdinalParse?t[Y]=n._locale.eraYearOrdinalParse(e,i):t[Y]=parseInt(e,10)}),s(0,["gg",2],0,function(){return this.weekYear()%100}),s(0,["GG",2],0,function(){return this.isoWeekYear()%100}),on("gggg","weekYear"),on("ggggg","weekYear"),on("GGGG","isoWeekYear"),on("GGGGG","isoWeekYear"),t("weekYear","gg"),t("isoWeekYear","GG"),n("weekYear",1),n("isoWeekYear",1),k("G",De),k("g",De),k("GG",f,u),k("gg",f,u),k("GGGG",ve,_e),k("gggg",ve,_e),k("GGGGG",ke,ye),k("ggggg",ke,ye),Te(["gggg","ggggg","GGGG","GGGGG"],function(e,t,n,s){t[s.substr(0,2)]=h(e)}),Te(["gg","GG"],function(e,t,n,s){t[s]=_.parseTwoDigitYear(e)}),s("Q",0,"Qo","quarter"),t("quarter","Q"),n("quarter",7),k("Q",i),D("Q",function(e,t){t[O]=3*(h(e)-1)}),s("D",["DD",2],"Do","date"),t("date","D"),n("date",9),k("D",f),k("DD",f,u),k("Do",function(e,t){return e?t._dayOfMonthOrdinalParse||t._ordinalParse:t._dayOfMonthOrdinalParseLenient}),D(["D","DD"],b),D("Do",function(e,t){t[b]=h(e.match(f)[0])});ve=de("Date",!0);s("DDD",["DDDD",3],"DDDo","dayOfYear"),t("dayOfYear","DDD"),n("dayOfYear",4),k("DDD",pe),k("DDDD",me),D(["DDD","DDDD"],function(e,t,n){n._dayOfYear=h(e)}),s("m",["mm",2],0,"minute"),t("minute","m"),n("minute",14),k("m",f),k("mm",f,u),D(["m","mm"],T);var ln,_e=de("Minutes",!1),ke=(s("s",["ss",2],0,"second"),t("second","s"),n("second",15),k("s",f),k("ss",f,u),D(["s","ss"],N),de("Seconds",!1));for(s("S",0,0,function(){return~~(this.millisecond()/100)}),s(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),s(0,["SSS",3],0,"millisecond"),s(0,["SSSS",4],0,function(){return 10*this.millisecond()}),s(0,["SSSSS",5],0,function(){return 100*this.millisecond()}),s(0,["SSSSSS",6],0,function(){return 1e3*this.millisecond()}),s(0,["SSSSSSS",7],0,function(){return 1e4*this.millisecond()}),s(0,["SSSSSSSS",8],0,function(){return 1e5*this.millisecond()}),s(0,["SSSSSSSSS",9],0,function(){return 1e6*this.millisecond()}),t("millisecond","ms"),n("millisecond",16),k("S",pe,i),k("SS",pe,u),k("SSS",pe,me),ln="SSSS";ln.length<=9;ln+="S")k(ln,Me);function hn(e,t){t[Ne]=h(1e3*("0."+e))}for(ln="S";ln.length<=9;ln+="S")D(ln,hn);ye=de("Milliseconds",!1),s("z",0,0,"zoneAbbr"),s("zz",0,0,"zoneName");i=q.prototype;function dn(e){return e}i.add=Ce,i.calendar=function(e,t){1===arguments.length&&(arguments[0]?Jt(arguments[0])?(e=arguments[0],t=void 0):function(e){for(var t=F(e)&&!L(e),n=!1,s=["sameDay","nextDay","lastDay","nextWeek","lastWeek","sameElse"],i=0;i<s.length;i+=1)n=n||c(e,s[i]);return t&&n}(arguments[0])&&(t=arguments[0],e=void 0):t=e=void 0);var e=e||W(),n=Gt(e,this).startOf("day"),n=_.calendarFormat(this,n)||"sameElse",t=t&&(a(t[n])?t[n].call(this,e):t[n]);return this.format(t||this.localeData().calendar(n,this,W(e)))},i.clone=function(){return new q(this)},i.diff=function(e,t,n){var s,i,r;if(!this.isValid())return NaN;if(!(s=Gt(e,this)).isValid())return NaN;switch(i=6e4*(s.utcOffset()-this.utcOffset()),t=o(t)){case"year":r=Qt(this,s)/12;break;case"month":r=Qt(this,s);break;case"quarter":r=Qt(this,s)/3;break;case"second":r=(this-s)/1e3;break;case"minute":r=(this-s)/6e4;break;case"hour":r=(this-s)/36e5;break;case"day":r=(this-s-i)/864e5;break;case"week":r=(this-s-i)/6048e5;break;default:r=this-s}return n?r:d(r)},i.endOf=function(e){var t,n;if(void 0!==(e=o(e))&&"millisecond"!==e&&this.isValid()){switch(n=this._isUTC?sn:nn,e){case"year":t=n(this.year()+1,0,1)-1;break;case"quarter":t=n(this.year(),this.month()-this.month()%3+3,1)-1;break;case"month":t=n(this.year(),this.month()+1,1)-1;break;case"week":t=n(this.year(),this.month(),this.date()-this.weekday()+7)-1;break;case"isoWeek":t=n(this.year(),this.month(),this.date()-(this.isoWeekday()-1)+7)-1;break;case"day":case"date":t=n(this.year(),this.month(),this.date()+1)-1;break;case"hour":t=this._d.valueOf(),t+=36e5-tn(t+(this._isUTC?0:6e4*this.utcOffset()),36e5)-1;break;case"minute":t=this._d.valueOf(),t+=6e4-tn(t,6e4)-1;break;case"second":t=this._d.valueOf(),t+=1e3-tn(t,1e3)-1}this._d.setTime(t),_.updateOffset(this,!0)}return this},i.format=function(e){return e=e||(this.isUtc()?_.defaultFormatUtc:_.defaultFormat),e=re(this,e),this.localeData().postformat(e)},i.from=function(e,t){return this.isValid()&&(v(e)&&e.isValid()||W(e).isValid())?C({to:this,from:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},i.fromNow=function(e){return this.from(W(),e)},i.to=function(e,t){return this.isValid()&&(v(e)&&e.isValid()||W(e).isValid())?C({from:this,to:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},i.toNow=function(e){return this.to(W(),e)},i.get=function(e){return a(this[e=o(e)])?this[e]():this},i.invalidAt=function(){return p(this).overflow},i.isAfter=function(e,t){return e=v(e)?e:W(e),!(!this.isValid()||!e.isValid())&&("millisecond"===(t=o(t)||"millisecond")?this.valueOf()>e.valueOf():e.valueOf()<this.clone().startOf(t).valueOf())},i.isBefore=function(e,t){return e=v(e)?e:W(e),!(!this.isValid()||!e.isValid())&&("millisecond"===(t=o(t)||"millisecond")?this.valueOf()<e.valueOf():this.clone().endOf(t).valueOf()<e.valueOf())},i.isBetween=function(e,t,n,s){return e=v(e)?e:W(e),t=v(t)?t:W(t),!!(this.isValid()&&e.isValid()&&t.isValid())&&("("===(s=s||"()")[0]?this.isAfter(e,n):!this.isBefore(e,n))&&(")"===s[1]?this.isBefore(t,n):!this.isAfter(t,n))},i.isSame=function(e,t){var e=v(e)?e:W(e);return!(!this.isValid()||!e.isValid())&&("millisecond"===(t=o(t)||"millisecond")?this.valueOf()===e.valueOf():(e=e.valueOf(),this.clone().startOf(t).valueOf()<=e&&e<=this.clone().endOf(t).valueOf()))},i.isSameOrAfter=function(e,t){return this.isSame(e,t)||this.isAfter(e,t)},i.isSameOrBefore=function(e,t){return this.isSame(e,t)||this.isBefore(e,t)},i.isValid=function(){return A(this)},i.lang=Xe,i.locale=Xt,i.localeData=Kt,i.max=we,i.min=ge,i.parsingFlags=function(){return E({},p(this))},i.set=function(e,t){if("object"==typeof e)for(var n=function(e){var t,n=[];for(t in e)c(e,t)&&n.push({unit:t,priority:le[t]});return n.sort(function(e,t){return e.priority-t.priority}),n}(e=ue(e)),s=n.length,i=0;i<s;i++)this[n[i].unit](e[n[i].unit]);else if(a(this[e=o(e)]))return this[e](t);return this},i.startOf=function(e){var t,n;if(void 0!==(e=o(e))&&"millisecond"!==e&&this.isValid()){switch(n=this._isUTC?sn:nn,e){case"year":t=n(this.year(),0,1);break;case"quarter":t=n(this.year(),this.month()-this.month()%3,1);break;case"month":t=n(this.year(),this.month(),1);break;case"week":t=n(this.year(),this.month(),this.date()-this.weekday());break;case"isoWeek":t=n(this.year(),this.month(),this.date()-(this.isoWeekday()-1));break;case"day":case"date":t=n(this.year(),this.month(),this.date());break;case"hour":t=this._d.valueOf(),t-=tn(t+(this._isUTC?0:6e4*this.utcOffset()),36e5);break;case"minute":t=this._d.valueOf(),t-=tn(t,6e4);break;case"second":t=this._d.valueOf(),t-=tn(t,1e3)}this._d.setTime(t),_.updateOffset(this,!0)}return this},i.subtract=Je,i.toArray=function(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()]},i.toObject=function(){var e=this;return{years:e.year(),months:e.month(),date:e.date(),hours:e.hours(),minutes:e.minutes(),seconds:e.seconds(),milliseconds:e.milliseconds()}},i.toDate=function(){return new Date(this.valueOf())},i.toISOString=function(e){var t;return this.isValid()?(t=(e=!0!==e)?this.clone().utc():this).year()<0||9999<t.year()?re(t,e?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):a(Date.prototype.toISOString)?e?this.toDate().toISOString():new Date(this.valueOf()+60*this.utcOffset()*1e3).toISOString().replace("Z",re(t,"Z")):re(t,e?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ"):null},i.inspect=function(){var e,t,n;return this.isValid()?(t="moment",e="",this.isLocal()||(t=0===this.utcOffset()?"moment.utc":"moment.parseZone",e="Z"),t="["+t+'("]',n=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",this.format(t+n+"-MM-DD[T]HH:mm:ss.SSS"+(e+'[")]'))):"moment.invalid(/* "+this._i+" */)"},"undefined"!=typeof Symbol&&null!=Symbol.for&&(i[Symbol.for("nodejs.util.inspect.custom")]=function(){return"Moment<"+this.format()+">"}),i.toJSON=function(){return this.isValid()?this.toISOString():null},i.toString=function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},i.unix=function(){return Math.floor(this.valueOf()/1e3)},i.valueOf=function(){return this._d.valueOf()-6e4*(this._offset||0)},i.creationData=function(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}},i.eraName=function(){for(var e,t=this.localeData().eras(),n=0,s=t.length;n<s;++n){if(e=this.clone().startOf("day").valueOf(),t[n].since<=e&&e<=t[n].until)return t[n].name;if(t[n].until<=e&&e<=t[n].since)return t[n].name}return""},i.eraNarrow=function(){for(var e,t=this.localeData().eras(),n=0,s=t.length;n<s;++n){if(e=this.clone().startOf("day").valueOf(),t[n].since<=e&&e<=t[n].until)return t[n].narrow;if(t[n].until<=e&&e<=t[n].since)return t[n].narrow}return""},i.eraAbbr=function(){for(var e,t=this.localeData().eras(),n=0,s=t.length;n<s;++n){if(e=this.clone().startOf("day").valueOf(),t[n].since<=e&&e<=t[n].until)return t[n].abbr;if(t[n].until<=e&&e<=t[n].since)return t[n].abbr}return""},i.eraYear=function(){for(var e,t,n=this.localeData().eras(),s=0,i=n.length;s<i;++s)if(e=n[s].since<=n[s].until?1:-1,t=this.clone().startOf("day").valueOf(),n[s].since<=t&&t<=n[s].until||n[s].until<=t&&t<=n[s].since)return(this.year()-_(n[s].since).year())*e+n[s].offset;return this.year()},i.year=Ie,i.isLeapYear=function(){return he(this.year())},i.weekYear=function(e){return un.call(this,e,this.week(),this.weekday(),this.localeData()._week.dow,this.localeData()._week.doy)},i.isoWeekYear=function(e){return un.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)},i.quarter=i.quarters=function(e){return null==e?Math.ceil((this.month()+1)/3):this.month(3*(e-1)+this.month()%3)},i.month=Ge,i.daysInMonth=function(){return We(this.year(),this.month())},i.week=i.weeks=function(e){var t=this.localeData().week(this);return null==e?t:this.add(7*(e-t),"d")},i.isoWeek=i.isoWeeks=function(e){var t=qe(this,1,4).week;return null==e?t:this.add(7*(e-t),"d")},i.weeksInYear=function(){var e=this.localeData()._week;return P(this.year(),e.dow,e.doy)},i.weeksInWeekYear=function(){var e=this.localeData()._week;return P(this.weekYear(),e.dow,e.doy)},i.isoWeeksInYear=function(){return P(this.year(),1,4)},i.isoWeeksInISOWeekYear=function(){return P(this.isoWeekYear(),1,4)},i.date=ve,i.day=i.days=function(e){var t,n,s;return this.isValid()?(t=this._isUTC?this._d.getUTCDay():this._d.getDay(),null!=e?(n=e,s=this.localeData(),e="string"!=typeof n?n:isNaN(n)?"number"==typeof(n=s.weekdaysParse(n))?n:null:parseInt(n,10),this.add(e-t,"d")):t):null!=e?this:NaN},i.weekday=function(e){var t;return this.isValid()?(t=(this.day()+7-this.localeData()._week.dow)%7,null==e?t:this.add(e-t,"d")):null!=e?this:NaN},i.isoWeekday=function(e){var t,n;return this.isValid()?null!=e?(t=e,n=this.localeData(),n="string"==typeof t?n.weekdaysParse(t)%7||7:isNaN(t)?null:t,this.day(this.day()%7?n:n-7)):this.day()||7:null!=e?this:NaN},i.dayOfYear=function(e){var t=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==e?t:this.add(e-t,"d")},i.hour=i.hours=m,i.minute=i.minutes=_e,i.second=i.seconds=ke,i.millisecond=i.milliseconds=ye,i.utcOffset=function(e,t,n){var s,i=this._offset||0;if(!this.isValid())return null!=e?this:NaN;if(null==e)return this._isUTC?i:Et(this);if("string"==typeof e){if(null===(e=Vt(Ye,e)))return this}else Math.abs(e)<16&&!n&&(e*=60);return!this._isUTC&&t&&(s=Et(this)),this._offset=e,this._isUTC=!0,null!=s&&this.add(s,"m"),i!==e&&(!t||this._changeInProgress?qt(this,C(e-i,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,_.updateOffset(this,!0),this._changeInProgress=null)),this},i.utc=function(e){return this.utcOffset(0,e)},i.local=function(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e)&&this.subtract(Et(this),"m"),this},i.parseZone=function(){var e;return null!=this._tzm?this.utcOffset(this._tzm,!1,!0):"string"==typeof this._i&&(null!=(e=Vt(Se,this._i))?this.utcOffset(e):this.utcOffset(0,!0)),this},i.hasAlignedHourOffset=function(e){return!!this.isValid()&&(e=e?W(e).utcOffset():0,(this.utcOffset()-e)%60==0)},i.isDST=function(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()},i.isLocal=function(){return!!this.isValid()&&!this._isUTC},i.isUtcOffset=function(){return!!this.isValid()&&this._isUTC},i.isUtc=At,i.isUTC=At,i.zoneAbbr=function(){return this._isUTC?"UTC":""},i.zoneName=function(){return this._isUTC?"Coordinated Universal Time":""},i.dates=e("dates accessor is deprecated. Use date instead.",ve),i.months=e("months accessor is deprecated. Use month instead",Ge),i.years=e("years accessor is deprecated. Use year instead",Ie),i.zone=e("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",function(e,t){return null!=e?(this.utcOffset(e="string"!=typeof e?-e:e,t),this):-this.utcOffset()}),i.isDSTShifted=e("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",function(){var e,t;return g(this._isDSTShifted)&&($(e={},this),(e=Nt(e))._a?(t=(e._isUTC?l:W)(e._a),this._isDSTShifted=this.isValid()&&0<function(e,t,n){for(var s=Math.min(e.length,t.length),i=Math.abs(e.length-t.length),r=0,a=0;a<s;a++)(n&&e[a]!==t[a]||!n&&h(e[a])!==h(t[a]))&&r++;return r+i}(e._a,t.toArray())):this._isDSTShifted=!1),this._isDSTShifted});u=K.prototype;function cn(e,t,n,s){var i=mt(),s=l().set(s,t);return i[n](s,e)}function fn(e,t,n){if(w(e)&&(t=e,e=void 0),e=e||"",null!=t)return cn(e,t,n,"month");for(var s=[],i=0;i<12;i++)s[i]=cn(e,i,n,"month");return s}function mn(e,t,n,s){t=("boolean"==typeof e?w(t)&&(n=t,t=void 0):(t=e,e=!1,w(n=t)&&(n=t,t=void 0)),t||"");var i,r=mt(),a=e?r._week.dow:0,o=[];if(null!=n)return cn(t,(n+a)%7,s,"day");for(i=0;i<7;i++)o[i]=cn(t,(i+a)%7,s,"day");return o}u.calendar=function(e,t,n){return a(e=this._calendar[e]||this._calendar.sameElse)?e.call(t,n):e},u.longDateFormat=function(e){var t=this._longDateFormat[e],n=this._longDateFormat[e.toUpperCase()];return t||!n?t:(this._longDateFormat[e]=n.match(te).map(function(e){return"MMMM"===e||"MM"===e||"DD"===e||"dddd"===e?e.slice(1):e}).join(""),this._longDateFormat[e])},u.invalidDate=function(){return this._invalidDate},u.ordinal=function(e){return this._ordinal.replace("%d",e)},u.preparse=dn,u.postformat=dn,u.relativeTime=function(e,t,n,s){var i=this._relativeTime[n];return a(i)?i(e,t,n,s):i.replace(/%d/i,e)},u.pastFuture=function(e,t){return a(e=this._relativeTime[0<e?"future":"past"])?e(t):e.replace(/%s/i,t)},u.set=function(e){var t,n;for(n in e)c(e,n)&&(a(t=e[n])?this[n]=t:this["_"+n]=t);this._config=e,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)},u.eras=function(e,t){for(var n,s=this._eras||mt("en")._eras,i=0,r=s.length;i<r;++i)switch("string"==typeof s[i].since&&(n=_(s[i].since).startOf("day"),s[i].since=n.valueOf()),typeof s[i].until){case"undefined":s[i].until=1/0;break;case"string":n=_(s[i].until).startOf("day").valueOf(),s[i].until=n.valueOf()}return s},u.erasParse=function(e,t,n){var s,i,r,a,o,u=this.eras();for(e=e.toUpperCase(),s=0,i=u.length;s<i;++s)if(r=u[s].name.toUpperCase(),a=u[s].abbr.toUpperCase(),o=u[s].narrow.toUpperCase(),n)switch(t){case"N":case"NN":case"NNN":if(a===e)return u[s];break;case"NNNN":if(r===e)return u[s];break;case"NNNNN":if(o===e)return u[s]}else if(0<=[r,a,o].indexOf(e))return u[s]},u.erasConvertYear=function(e,t){var n=e.since<=e.until?1:-1;return void 0===t?_(e.since).year():_(e.since).year()+(t-e.offset)*n},u.erasAbbrRegex=function(e){return c(this,"_erasAbbrRegex")||an.call(this),e?this._erasAbbrRegex:this._erasRegex},u.erasNameRegex=function(e){return c(this,"_erasNameRegex")||an.call(this),e?this._erasNameRegex:this._erasRegex},u.erasNarrowRegex=function(e){return c(this,"_erasNarrowRegex")||an.call(this),e?this._erasNarrowRegex:this._erasRegex},u.months=function(e,t){return e?(y(this._months)?this._months:this._months[(this._months.isFormat||He).test(t)?"format":"standalone"])[e.month()]:y(this._months)?this._months:this._months.standalone},u.monthsShort=function(e,t){return e?(y(this._monthsShort)?this._monthsShort:this._monthsShort[He.test(t)?"format":"standalone"])[e.month()]:y(this._monthsShort)?this._monthsShort:this._monthsShort.standalone},u.monthsParse=function(e,t,n){var s,i;if(this._monthsParseExact)return function(e,t,n){var s,i,r,e=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],s=0;s<12;++s)r=l([2e3,s]),this._shortMonthsParse[s]=this.monthsShort(r,"").toLocaleLowerCase(),this._longMonthsParse[s]=this.months(r,"").toLocaleLowerCase();return n?"MMM"===t?-1!==(i=S.call(this._shortMonthsParse,e))?i:null:-1!==(i=S.call(this._longMonthsParse,e))?i:null:"MMM"===t?-1!==(i=S.call(this._shortMonthsParse,e))||-1!==(i=S.call(this._longMonthsParse,e))?i:null:-1!==(i=S.call(this._longMonthsParse,e))||-1!==(i=S.call(this._shortMonthsParse,e))?i:null}.call(this,e,t,n);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),s=0;s<12;s++){if(i=l([2e3,s]),n&&!this._longMonthsParse[s]&&(this._longMonthsParse[s]=new RegExp("^"+this.months(i,"").replace(".","")+"$","i"),this._shortMonthsParse[s]=new RegExp("^"+this.monthsShort(i,"").replace(".","")+"$","i")),n||this._monthsParse[s]||(i="^"+this.months(i,"")+"|^"+this.monthsShort(i,""),this._monthsParse[s]=new RegExp(i.replace(".",""),"i")),n&&"MMMM"===t&&this._longMonthsParse[s].test(e))return s;if(n&&"MMM"===t&&this._shortMonthsParse[s].test(e))return s;if(!n&&this._monthsParse[s].test(e))return s}},u.monthsRegex=function(e){return this._monthsParseExact?(c(this,"_monthsRegex")||Ee.call(this),e?this._monthsStrictRegex:this._monthsRegex):(c(this,"_monthsRegex")||(this._monthsRegex=Le),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)},u.monthsShortRegex=function(e){return this._monthsParseExact?(c(this,"_monthsRegex")||Ee.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(c(this,"_monthsShortRegex")||(this._monthsShortRegex=Fe),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)},u.week=function(e){return qe(e,this._week.dow,this._week.doy).week},u.firstDayOfYear=function(){return this._week.doy},u.firstDayOfWeek=function(){return this._week.dow},u.weekdays=function(e,t){return t=y(this._weekdays)?this._weekdays:this._weekdays[e&&!0!==e&&this._weekdays.isFormat.test(t)?"format":"standalone"],!0===e?Be(t,this._week.dow):e?t[e.day()]:t},u.weekdaysMin=function(e){return!0===e?Be(this._weekdaysMin,this._week.dow):e?this._weekdaysMin[e.day()]:this._weekdaysMin},u.weekdaysShort=function(e){return!0===e?Be(this._weekdaysShort,this._week.dow):e?this._weekdaysShort[e.day()]:this._weekdaysShort},u.weekdaysParse=function(e,t,n){var s,i;if(this._weekdaysParseExact)return function(e,t,n){var s,i,r,e=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],s=0;s<7;++s)r=l([2e3,1]).day(s),this._minWeekdaysParse[s]=this.weekdaysMin(r,"").toLocaleLowerCase(),this._shortWeekdaysParse[s]=this.weekdaysShort(r,"").toLocaleLowerCase(),this._weekdaysParse[s]=this.weekdays(r,"").toLocaleLowerCase();return n?"dddd"===t?-1!==(i=S.call(this._weekdaysParse,e))?i:null:"ddd"===t?-1!==(i=S.call(this._shortWeekdaysParse,e))?i:null:-1!==(i=S.call(this._minWeekdaysParse,e))?i:null:"dddd"===t?-1!==(i=S.call(this._weekdaysParse,e))||-1!==(i=S.call(this._shortWeekdaysParse,e))||-1!==(i=S.call(this._minWeekdaysParse,e))?i:null:"ddd"===t?-1!==(i=S.call(this._shortWeekdaysParse,e))||-1!==(i=S.call(this._weekdaysParse,e))||-1!==(i=S.call(this._minWeekdaysParse,e))?i:null:-1!==(i=S.call(this._minWeekdaysParse,e))||-1!==(i=S.call(this._weekdaysParse,e))||-1!==(i=S.call(this._shortWeekdaysParse,e))?i:null}.call(this,e,t,n);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),s=0;s<7;s++){if(i=l([2e3,1]).day(s),n&&!this._fullWeekdaysParse[s]&&(this._fullWeekdaysParse[s]=new RegExp("^"+this.weekdays(i,"").replace(".","\\.?")+"$","i"),this._shortWeekdaysParse[s]=new RegExp("^"+this.weekdaysShort(i,"").replace(".","\\.?")+"$","i"),this._minWeekdaysParse[s]=new RegExp("^"+this.weekdaysMin(i,"").replace(".","\\.?")+"$","i")),this._weekdaysParse[s]||(i="^"+this.weekdays(i,"")+"|^"+this.weekdaysShort(i,"")+"|^"+this.weekdaysMin(i,""),this._weekdaysParse[s]=new RegExp(i.replace(".",""),"i")),n&&"dddd"===t&&this._fullWeekdaysParse[s].test(e))return s;if(n&&"ddd"===t&&this._shortWeekdaysParse[s].test(e))return s;if(n&&"dd"===t&&this._minWeekdaysParse[s].test(e))return s;if(!n&&this._weekdaysParse[s].test(e))return s}},u.weekdaysRegex=function(e){return this._weekdaysParseExact?(c(this,"_weekdaysRegex")||nt.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(c(this,"_weekdaysRegex")||(this._weekdaysRegex=Ke),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)},u.weekdaysShortRegex=function(e){return this._weekdaysParseExact?(c(this,"_weekdaysRegex")||nt.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(c(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=et),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)},u.weekdaysMinRegex=function(e){return this._weekdaysParseExact?(c(this,"_weekdaysRegex")||nt.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(c(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=tt),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)},u.isPM=function(e){return"p"===(e+"").toLowerCase().charAt(0)},u.meridiem=function(e,t,n){return 11<e?n?"pm":"PM":n?"am":"AM"},ct("en",{eras:[{since:"0001-01-01",until:1/0,offset:1,name:"Anno Domini",narrow:"AD",abbr:"AD"},{since:"0000-12-31",until:-1/0,offset:1,name:"Before Christ",narrow:"BC",abbr:"BC"}],dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var t=e%10;return e+(1===h(e%100/10)?"th":1==t?"st":2==t?"nd":3==t?"rd":"th")}}),_.lang=e("moment.lang is deprecated. Use moment.locale instead.",ct),_.langData=e("moment.langData is deprecated. Use moment.localeData instead.",mt);var _n=Math.abs;function yn(e,t,n,s){t=C(t,n);return e._milliseconds+=s*t._milliseconds,e._days+=s*t._days,e._months+=s*t._months,e._bubble()}function gn(e){return e<0?Math.floor(e):Math.ceil(e)}function wn(e){return 4800*e/146097}function pn(e){return 146097*e/4800}function vn(e){return function(){return this.as(e)}}pe=vn("ms"),me=vn("s"),Ce=vn("m"),we=vn("h"),ge=vn("d"),Je=vn("w"),m=vn("M"),_e=vn("Q"),ke=vn("y");function kn(e){return function(){return this.isValid()?this._data[e]:NaN}}var ye=kn("milliseconds"),ve=kn("seconds"),Ie=kn("minutes"),u=kn("hours"),Mn=kn("days"),Dn=kn("months"),Sn=kn("years");var Yn=Math.round,On={ss:44,s:45,m:45,h:22,d:26,w:null,M:11};function bn(e,t,n,s){var i=C(e).abs(),r=Yn(i.as("s")),a=Yn(i.as("m")),o=Yn(i.as("h")),u=Yn(i.as("d")),l=Yn(i.as("M")),h=Yn(i.as("w")),i=Yn(i.as("y")),r=(r<=n.ss?["s",r]:r<n.s&&["ss",r])||(a<=1?["m"]:a<n.m&&["mm",a])||(o<=1?["h"]:o<n.h&&["hh",o])||(u<=1?["d"]:u<n.d&&["dd",u]);return(r=(r=null!=n.w?r||(h<=1?["w"]:h<n.w&&["ww",h]):r)||(l<=1?["M"]:l<n.M&&["MM",l])||(i<=1?["y"]:["yy",i]))[2]=t,r[3]=0<+e,r[4]=s,function(e,t,n,s,i){return i.relativeTime(t||1,!!n,e,s)}.apply(null,r)}var xn=Math.abs;function Tn(e){return(0<e)-(e<0)||+e}function Nn(){var e,t,n,s,i,r,a,o,u,l,h;return this.isValid()?(e=xn(this._milliseconds)/1e3,t=xn(this._days),n=xn(this._months),(o=this.asSeconds())?(s=d(e/60),i=d(s/60),e%=60,s%=60,r=d(n/12),n%=12,a=e?e.toFixed(3).replace(/\.?0+$/,""):"",u=Tn(this._months)!==Tn(o)?"-":"",l=Tn(this._days)!==Tn(o)?"-":"",h=Tn(this._milliseconds)!==Tn(o)?"-":"",(o<0?"-":"")+"P"+(r?u+r+"Y":"")+(n?u+n+"M":"")+(t?l+t+"D":"")+(i||s||e?"T":"")+(i?h+i+"H":"")+(s?h+s+"M":"")+(e?h+a+"S":"")):"P0D"):this.localeData().invalidDate()}var U=Ct.prototype;return U.isValid=function(){return this._isValid},U.abs=function(){var e=this._data;return this._milliseconds=_n(this._milliseconds),this._days=_n(this._days),this._months=_n(this._months),e.milliseconds=_n(e.milliseconds),e.seconds=_n(e.seconds),e.minutes=_n(e.minutes),e.hours=_n(e.hours),e.months=_n(e.months),e.years=_n(e.years),this},U.add=function(e,t){return yn(this,e,t,1)},U.subtract=function(e,t){return yn(this,e,t,-1)},U.as=function(e){if(!this.isValid())return NaN;var t,n,s=this._milliseconds;if("month"===(e=o(e))||"quarter"===e||"year"===e)switch(t=this._days+s/864e5,n=this._months+wn(t),e){case"month":return n;case"quarter":return n/3;case"year":return n/12}else switch(t=this._days+Math.round(pn(this._months)),e){case"week":return t/7+s/6048e5;case"day":return t+s/864e5;case"hour":return 24*t+s/36e5;case"minute":return 1440*t+s/6e4;case"second":return 86400*t+s/1e3;case"millisecond":return Math.floor(864e5*t)+s;default:throw new Error("Unknown unit "+e)}},U.asMilliseconds=pe,U.asSeconds=me,U.asMinutes=Ce,U.asHours=we,U.asDays=ge,U.asWeeks=Je,U.asMonths=m,U.asQuarters=_e,U.asYears=ke,U.valueOf=function(){return this.isValid()?this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*h(this._months/12):NaN},U._bubble=function(){var e=this._milliseconds,t=this._days,n=this._months,s=this._data;return 0<=e&&0<=t&&0<=n||e<=0&&t<=0&&n<=0||(e+=864e5*gn(pn(n)+t),n=t=0),s.milliseconds=e%1e3,e=d(e/1e3),s.seconds=e%60,e=d(e/60),s.minutes=e%60,e=d(e/60),s.hours=e%24,t+=d(e/24),n+=e=d(wn(t)),t-=gn(pn(e)),e=d(n/12),n%=12,s.days=t,s.months=n,s.years=e,this},U.clone=function(){return C(this)},U.get=function(e){return e=o(e),this.isValid()?this[e+"s"]():NaN},U.milliseconds=ye,U.seconds=ve,U.minutes=Ie,U.hours=u,U.days=Mn,U.weeks=function(){return d(this.days()/7)},U.months=Dn,U.years=Sn,U.humanize=function(e,t){var n,s;return this.isValid()?(n=!1,s=On,"object"==typeof e&&(t=e,e=!1),"boolean"==typeof e&&(n=e),"object"==typeof t&&(s=Object.assign({},On,t),null!=t.s)&&null==t.ss&&(s.ss=t.s-1),e=this.localeData(),t=bn(this,!n,s,e),n&&(t=e.pastFuture(+this,t)),e.postformat(t)):this.localeData().invalidDate()},U.toISOString=Nn,U.toString=Nn,U.toJSON=Nn,U.locale=Xt,U.localeData=Kt,U.toIsoString=e("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",Nn),U.lang=Xe,s("X",0,0,"unix"),s("x",0,0,"valueOf"),k("x",De),k("X",/[+-]?\d+(\.\d{1,3})?/),D("X",function(e,t,n){n._d=new Date(1e3*parseFloat(e))}),D("x",function(e,t,n){n._d=new Date(h(e))}),_.version="2.29.4",H=W,_.fn=i,_.min=function(){return Rt("isBefore",[].slice.call(arguments,0))},_.max=function(){return Rt("isAfter",[].slice.call(arguments,0))},_.now=function(){return Date.now?Date.now():+new Date},_.utc=l,_.unix=function(e){return W(1e3*e)},_.months=function(e,t){return fn(e,t,"months")},_.isDate=V,_.locale=ct,_.invalid=I,_.duration=C,_.isMoment=v,_.weekdays=function(e,t,n){return mn(e,t,n,"weekdays")},_.parseZone=function(){return W.apply(null,arguments).parseZone()},_.localeData=mt,_.isDuration=Ut,_.monthsShort=function(e,t){return fn(e,t,"monthsShort")},_.weekdaysMin=function(e,t,n){return mn(e,t,n,"weekdaysMin")},_.defineLocale=ft,_.updateLocale=function(e,t){var n,s;return null!=t?(s=ot,null!=R[e]&&null!=R[e].parentLocale?R[e].set(X(R[e]._config,t)):(t=X(s=null!=(n=dt(e))?n._config:s,t),null==n&&(t.abbr=e),(s=new K(t)).parentLocale=R[e],R[e]=s),ct(e)):null!=R[e]&&(null!=R[e].parentLocale?(R[e]=R[e].parentLocale,e===ct()&&ct(e)):null!=R[e]&&delete R[e]),R[e]},_.locales=function(){return ee(R)},_.weekdaysShort=function(e,t,n){return mn(e,t,n,"weekdaysShort")},_.normalizeUnits=o,_.relativeTimeRounding=function(e){return void 0===e?Yn:"function"==typeof e&&(Yn=e,!0)},_.relativeTimeThreshold=function(e,t){return void 0!==On[e]&&(void 0===t?On[e]:(On[e]=t,"s"===e&&(On.ss=t-1),!0))},_.calendarFormat=function(e,t){return(e=e.diff(t,"days",!0))<-6?"sameElse":e<-1?"lastWeek":e<0?"lastDay":e<1?"sameDay":e<2?"nextDay":e<7?"nextWeek":"sameElse"},_.prototype=i,_.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"GGGG-[W]WW",MONTH:"YYYY-MM"},_}); vendor/react-dom.min.js 0000666 00000374561 15123355174 0011066 0 ustar 00 /**
* @license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
!function(){"use strict";var e,n;e=this,n=function(e,n){function t(e){for(var n="https://reactjs.org/docs/error-decoder.html?invariant="+e,t=1;t<arguments.length;t++)n+="&args[]="+encodeURIComponent(arguments[t]);return"Minified React error #"+e+"; visit "+n+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function r(e,n){l(e,n),l(e+"Capture",n)}function l(e,n){for(ra[e]=n,e=0;e<n.length;e++)ta.add(n[e])}function a(e,n,t,r,l,a,u){this.acceptsBooleans=2===n||3===n||4===n,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=t,this.propertyName=e,this.type=n,this.sanitizeURL=a,this.removeEmptyString=u}function u(e,n,t,r){var l=sa.hasOwnProperty(n)?sa[n]:null;(null!==l?0!==l.type:r||!(2<n.length)||"o"!==n[0]&&"O"!==n[0]||"n"!==n[1]&&"N"!==n[1])&&(function(e,n,t,r){if(null==n||function(e,n,t,r){if(null!==t&&0===t.type)return!1;switch(typeof n){case"function":case"symbol":return!0;case"boolean":return!r&&(null!==t?!t.acceptsBooleans:"data-"!==(e=e.toLowerCase().slice(0,5))&&"aria-"!==e);default:return!1}}(e,n,t,r))return!0;if(r)return!1;if(null!==t)switch(t.type){case 3:return!n;case 4:return!1===n;case 5:return isNaN(n);case 6:return isNaN(n)||1>n}return!1}(n,t,l,r)&&(t=null),r||null===l?function(e){return!!aa.call(ia,e)||!aa.call(oa,e)&&(ua.test(e)?ia[e]=!0:(oa[e]=!0,!1))}(n)&&(null===t?e.removeAttribute(n):e.setAttribute(n,""+t)):l.mustUseProperty?e[l.propertyName]=null===t?3!==l.type&&"":t:(n=l.attributeName,r=l.attributeNamespace,null===t?e.removeAttribute(n):(t=3===(l=l.type)||4===l&&!0===t?"":""+t,r?e.setAttributeNS(r,n,t):e.setAttribute(n,t))))}function o(e){return null===e||"object"!=typeof e?null:"function"==typeof(e=_a&&e[_a]||e["@@iterator"])?e:null}function i(e,n,t){if(void 0===za)try{throw Error()}catch(e){za=(n=e.stack.trim().match(/\n( *(at )?)/))&&n[1]||""}return"\n"+za+e}function s(e,n){if(!e||Ta)return"";Ta=!0;var t=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(n)if(n=function(){throw Error()},Object.defineProperty(n.prototype,"props",{set:function(){throw Error()}}),"object"==typeof Reflect&&Reflect.construct){try{Reflect.construct(n,[])}catch(e){var r=e}Reflect.construct(e,[],n)}else{try{n.call()}catch(e){r=e}e.call(n.prototype)}else{try{throw Error()}catch(e){r=e}e()}}catch(n){if(n&&r&&"string"==typeof n.stack){for(var l=n.stack.split("\n"),a=r.stack.split("\n"),u=l.length-1,o=a.length-1;1<=u&&0<=o&&l[u]!==a[o];)o--;for(;1<=u&&0<=o;u--,o--)if(l[u]!==a[o]){if(1!==u||1!==o)do{if(u--,0>--o||l[u]!==a[o]){var s="\n"+l[u].replace(" at new "," at ");return e.displayName&&s.includes("<anonymous>")&&(s=s.replace("<anonymous>",e.displayName)),s}}while(1<=u&&0<=o);break}}}finally{Ta=!1,Error.prepareStackTrace=t}return(e=e?e.displayName||e.name:"")?i(e):""}function c(e){switch(e.tag){case 5:return i(e.type);case 16:return i("Lazy");case 13:return i("Suspense");case 19:return i("SuspenseList");case 0:case 2:case 15:return e=s(e.type,!1);case 11:return e=s(e.type.render,!1);case 1:return e=s(e.type,!0);default:return""}}function f(e){if(null==e)return null;if("function"==typeof e)return e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case ha:return"Fragment";case ma:return"Portal";case va:return"Profiler";case ga:return"StrictMode";case wa:return"Suspense";case Sa:return"SuspenseList"}if("object"==typeof e)switch(e.$$typeof){case ba:return(e.displayName||"Context")+".Consumer";case ya:return(e._context.displayName||"Context")+".Provider";case ka:var n=e.render;return(e=e.displayName)||(e=""!==(e=n.displayName||n.name||"")?"ForwardRef("+e+")":"ForwardRef"),e;case xa:return null!==(n=e.displayName||null)?n:f(e.type)||"Memo";case Ea:n=e._payload,e=e._init;try{return f(e(n))}catch(e){}}return null}function d(e){var n=e.type;switch(e.tag){case 24:return"Cache";case 9:return(n.displayName||"Context")+".Consumer";case 10:return(n._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=(e=n.render).displayName||e.name||"",n.displayName||(""!==e?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return n;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return f(n);case 8:return n===ga?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"==typeof n)return n.displayName||n.name||null;if("string"==typeof n)return n}return null}function p(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":case"object":return e;default:return""}}function m(e){var n=e.type;return(e=e.nodeName)&&"input"===e.toLowerCase()&&("checkbox"===n||"radio"===n)}function h(e){e._valueTracker||(e._valueTracker=function(e){var n=m(e)?"checked":"value",t=Object.getOwnPropertyDescriptor(e.constructor.prototype,n),r=""+e[n];if(!e.hasOwnProperty(n)&&void 0!==t&&"function"==typeof t.get&&"function"==typeof t.set){var l=t.get,a=t.set;return Object.defineProperty(e,n,{configurable:!0,get:function(){return l.call(this)},set:function(e){r=""+e,a.call(this,e)}}),Object.defineProperty(e,n,{enumerable:t.enumerable}),{getValue:function(){return r},setValue:function(e){r=""+e},stopTracking:function(){e._valueTracker=null,delete e[n]}}}}(e))}function g(e){if(!e)return!1;var n=e._valueTracker;if(!n)return!0;var t=n.getValue(),r="";return e&&(r=m(e)?e.checked?"true":"false":e.value),(e=r)!==t&&(n.setValue(e),!0)}function v(e){if(void 0===(e=e||("undefined"!=typeof document?document:void 0)))return null;try{return e.activeElement||e.body}catch(n){return e.body}}function y(e,n){var t=n.checked;return La({},n,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=t?t:e._wrapperState.initialChecked})}function b(e,n){var t=null==n.defaultValue?"":n.defaultValue,r=null!=n.checked?n.checked:n.defaultChecked;t=p(null!=n.value?n.value:t),e._wrapperState={initialChecked:r,initialValue:t,controlled:"checkbox"===n.type||"radio"===n.type?null!=n.checked:null!=n.value}}function k(e,n){null!=(n=n.checked)&&u(e,"checked",n,!1)}function w(e,n){k(e,n);var t=p(n.value),r=n.type;if(null!=t)"number"===r?(0===t&&""===e.value||e.value!=t)&&(e.value=""+t):e.value!==""+t&&(e.value=""+t);else if("submit"===r||"reset"===r)return void e.removeAttribute("value");n.hasOwnProperty("value")?x(e,n.type,t):n.hasOwnProperty("defaultValue")&&x(e,n.type,p(n.defaultValue)),null==n.checked&&null!=n.defaultChecked&&(e.defaultChecked=!!n.defaultChecked)}function S(e,n,t){if(n.hasOwnProperty("value")||n.hasOwnProperty("defaultValue")){var r=n.type;if(!("submit"!==r&&"reset"!==r||void 0!==n.value&&null!==n.value))return;n=""+e._wrapperState.initialValue,t||n===e.value||(e.value=n),e.defaultValue=n}""!==(t=e.name)&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,""!==t&&(e.name=t)}function x(e,n,t){"number"===n&&v(e.ownerDocument)===e||(null==t?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+t&&(e.defaultValue=""+t))}function E(e,n,t,r){if(e=e.options,n){n={};for(var l=0;l<t.length;l++)n["$"+t[l]]=!0;for(t=0;t<e.length;t++)l=n.hasOwnProperty("$"+e[t].value),e[t].selected!==l&&(e[t].selected=l),l&&r&&(e[t].defaultSelected=!0)}else{for(t=""+p(t),n=null,l=0;l<e.length;l++){if(e[l].value===t)return e[l].selected=!0,void(r&&(e[l].defaultSelected=!0));null!==n||e[l].disabled||(n=e[l])}null!==n&&(n.selected=!0)}}function C(e,n){if(null!=n.dangerouslySetInnerHTML)throw Error(t(91));return La({},n,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue})}function z(e,n){var r=n.value;if(null==r){if(r=n.children,n=n.defaultValue,null!=r){if(null!=n)throw Error(t(92));if(Ma(r)){if(1<r.length)throw Error(t(93));r=r[0]}n=r}null==n&&(n=""),r=n}e._wrapperState={initialValue:p(r)}}function N(e,n){var t=p(n.value),r=p(n.defaultValue);null!=t&&((t=""+t)!==e.value&&(e.value=t),null==n.defaultValue&&e.defaultValue!==t&&(e.defaultValue=t)),null!=r&&(e.defaultValue=""+r)}function P(e,n){(n=e.textContent)===e._wrapperState.initialValue&&""!==n&&null!==n&&(e.value=n)}function _(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function L(e,n){return null==e||"http://www.w3.org/1999/xhtml"===e?_(n):"http://www.w3.org/2000/svg"===e&&"foreignObject"===n?"http://www.w3.org/1999/xhtml":e}function T(e,n,t){return null==n||"boolean"==typeof n||""===n?"":t||"number"!=typeof n||0===n||Da.hasOwnProperty(e)&&Da[e]?(""+n).trim():n+"px"}function M(e,n){for(var t in e=e.style,n)if(n.hasOwnProperty(t)){var r=0===t.indexOf("--"),l=T(t,n[t],r);"float"===t&&(t="cssFloat"),r?e.setProperty(t,l):e[t]=l}}function F(e,n){if(n){if(Ia[e]&&(null!=n.children||null!=n.dangerouslySetInnerHTML))throw Error(t(137,e));if(null!=n.dangerouslySetInnerHTML){if(null!=n.children)throw Error(t(60));if("object"!=typeof n.dangerouslySetInnerHTML||!("__html"in n.dangerouslySetInnerHTML))throw Error(t(61))}if(null!=n.style&&"object"!=typeof n.style)throw Error(t(62))}}function R(e,n){if(-1===e.indexOf("-"))return"string"==typeof n.is;switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}function D(e){return(e=e.target||e.srcElement||window).correspondingUseElement&&(e=e.correspondingUseElement),3===e.nodeType?e.parentNode:e}function O(e){if(e=pn(e)){if("function"!=typeof Va)throw Error(t(280));var n=e.stateNode;n&&(n=hn(n),Va(e.stateNode,e.type,n))}}function I(e){Aa?Ba?Ba.push(e):Ba=[e]:Aa=e}function U(){if(Aa){var e=Aa,n=Ba;if(Ba=Aa=null,O(e),n)for(e=0;e<n.length;e++)O(n[e])}}function V(e,n,t){if(Qa)return e(n,t);Qa=!0;try{return Wa(e,n,t)}finally{Qa=!1,(null!==Aa||null!==Ba)&&(Ha(),U())}}function A(e,n){var r=e.stateNode;if(null===r)return null;var l=hn(r);if(null===l)return null;r=l[n];e:switch(n){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(l=!l.disabled)||(l=!("button"===(e=e.type)||"input"===e||"select"===e||"textarea"===e)),e=!l;break e;default:e=!1}if(e)return null;if(r&&"function"!=typeof r)throw Error(t(231,n,typeof r));return r}function B(e,n,t,r,l,a,u,o,i){Ga=!1,Za=null,Xa.apply(nu,arguments)}function W(e){var n=e,t=e;if(e.alternate)for(;n.return;)n=n.return;else{e=n;do{0!=(4098&(n=e).flags)&&(t=n.return),e=n.return}while(e)}return 3===n.tag?t:null}function H(e){if(13===e.tag){var n=e.memoizedState;if(null===n&&null!==(e=e.alternate)&&(n=e.memoizedState),null!==n)return n.dehydrated}return null}function Q(e){if(W(e)!==e)throw Error(t(188))}function j(e){return null!==(e=function(e){var n=e.alternate;if(!n){if(null===(n=W(e)))throw Error(t(188));return n!==e?null:e}for(var r=e,l=n;;){var a=r.return;if(null===a)break;var u=a.alternate;if(null===u){if(null!==(l=a.return)){r=l;continue}break}if(a.child===u.child){for(u=a.child;u;){if(u===r)return Q(a),e;if(u===l)return Q(a),n;u=u.sibling}throw Error(t(188))}if(r.return!==l.return)r=a,l=u;else{for(var o=!1,i=a.child;i;){if(i===r){o=!0,r=a,l=u;break}if(i===l){o=!0,l=a,r=u;break}i=i.sibling}if(!o){for(i=u.child;i;){if(i===r){o=!0,r=u,l=a;break}if(i===l){o=!0,l=u,r=a;break}i=i.sibling}if(!o)throw Error(t(189))}}if(r.alternate!==l)throw Error(t(190))}if(3!==r.tag)throw Error(t(188));return r.stateNode.current===r?e:n}(e))?$(e):null}function $(e){if(5===e.tag||6===e.tag)return e;for(e=e.child;null!==e;){var n=$(e);if(null!==n)return n;e=e.sibling}return null}function q(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return 4194240&e;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return 130023424&e;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function K(e,n){var t=e.pendingLanes;if(0===t)return 0;var r=0,l=e.suspendedLanes,a=e.pingedLanes,u=268435455&t;if(0!==u){var o=u&~l;0!==o?r=q(o):0!=(a&=u)&&(r=q(a))}else 0!=(u=t&~l)?r=q(u):0!==a&&(r=q(a));if(0===r)return 0;if(0!==n&&n!==r&&0==(n&l)&&((l=r&-r)>=(a=n&-n)||16===l&&0!=(4194240&a)))return n;if(0!=(4&r)&&(r|=16&t),0!==(n=e.entangledLanes))for(e=e.entanglements,n&=r;0<n;)l=1<<(t=31-yu(n)),r|=e[t],n&=~l;return r}function Y(e,n){switch(e){case 1:case 2:case 4:return n+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return n+5e3;default:return-1}}function X(e){return 0!=(e=-1073741825&e.pendingLanes)?e:1073741824&e?1073741824:0}function G(){var e=wu;return 0==(4194240&(wu<<=1))&&(wu=64),e}function Z(e){for(var n=[],t=0;31>t;t++)n.push(e);return n}function J(e,n,t){e.pendingLanes|=n,536870912!==n&&(e.suspendedLanes=0,e.pingedLanes=0),(e=e.eventTimes)[n=31-yu(n)]=t}function ee(e,n){var t=e.entangledLanes|=n;for(e=e.entanglements;t;){var r=31-yu(t),l=1<<r;l&n|e[r]&n&&(e[r]|=n),t&=~l}}function ne(e){return 1<(e&=-e)?4<e?0!=(268435455&e)?16:536870912:4:1}function te(e,n){switch(e){case"focusin":case"focusout":zu=null;break;case"dragenter":case"dragleave":Nu=null;break;case"mouseover":case"mouseout":Pu=null;break;case"pointerover":case"pointerout":_u.delete(n.pointerId);break;case"gotpointercapture":case"lostpointercapture":Lu.delete(n.pointerId)}}function re(e,n,t,r,l,a){return null===e||e.nativeEvent!==a?(e={blockedOn:n,domEventName:t,eventSystemFlags:r,nativeEvent:a,targetContainers:[l]},null!==n&&null!==(n=pn(n))&&Ys(n),e):(e.eventSystemFlags|=r,n=e.targetContainers,null!==l&&-1===n.indexOf(l)&&n.push(l),e)}function le(e){var n=dn(e.target);if(null!==n){var t=W(n);if(null!==t)if(13===(n=t.tag)){if(null!==(n=H(t)))return e.blockedOn=n,void Zs(e.priority,(function(){Xs(t)}))}else if(3===n&&t.stateNode.current.memoizedState.isDehydrated)return void(e.blockedOn=3===t.tag?t.stateNode.containerInfo:null)}e.blockedOn=null}function ae(e){if(null!==e.blockedOn)return!1;for(var n=e.targetContainers;0<n.length;){var t=pe(e.domEventName,e.eventSystemFlags,n[0],e.nativeEvent);if(null!==t)return null!==(n=pn(t))&&Ys(n),e.blockedOn=t,!1;var r=new(t=e.nativeEvent).constructor(t.type,t);Ua=r,t.target.dispatchEvent(r),Ua=null,n.shift()}return!0}function ue(e,n,t){ae(e)&&t.delete(n)}function oe(){Eu=!1,null!==zu&&ae(zu)&&(zu=null),null!==Nu&&ae(Nu)&&(Nu=null),null!==Pu&&ae(Pu)&&(Pu=null),_u.forEach(ue),Lu.forEach(ue)}function ie(e,n){e.blockedOn===n&&(e.blockedOn=null,Eu||(Eu=!0,ru(lu,oe)))}function se(e){if(0<Cu.length){ie(Cu[0],e);for(var n=1;n<Cu.length;n++){var t=Cu[n];t.blockedOn===e&&(t.blockedOn=null)}}for(null!==zu&&ie(zu,e),null!==Nu&&ie(Nu,e),null!==Pu&&ie(Pu,e),n=function(n){return ie(n,e)},_u.forEach(n),Lu.forEach(n),n=0;n<Tu.length;n++)(t=Tu[n]).blockedOn===e&&(t.blockedOn=null);for(;0<Tu.length&&null===(n=Tu[0]).blockedOn;)le(n),null===n.blockedOn&&Tu.shift()}function ce(e,n,t,r){var l=xu,a=Fu.transition;Fu.transition=null;try{xu=1,de(e,n,t,r)}finally{xu=l,Fu.transition=a}}function fe(e,n,t,r){var l=xu,a=Fu.transition;Fu.transition=null;try{xu=4,de(e,n,t,r)}finally{xu=l,Fu.transition=a}}function de(e,n,t,r){if(Ru){var l=pe(e,n,t,r);if(null===l)Ze(e,n,r,Du,t),te(e,r);else if(function(e,n,t,r,l){switch(n){case"focusin":return zu=re(zu,e,n,t,r,l),!0;case"dragenter":return Nu=re(Nu,e,n,t,r,l),!0;case"mouseover":return Pu=re(Pu,e,n,t,r,l),!0;case"pointerover":var a=l.pointerId;return _u.set(a,re(_u.get(a)||null,e,n,t,r,l)),!0;case"gotpointercapture":return a=l.pointerId,Lu.set(a,re(Lu.get(a)||null,e,n,t,r,l)),!0}return!1}(l,e,n,t,r))r.stopPropagation();else if(te(e,r),4&n&&-1<Mu.indexOf(e)){for(;null!==l;){var a=pn(l);if(null!==a&&Ks(a),null===(a=pe(e,n,t,r))&&Ze(e,n,r,Du,t),a===l)break;l=a}null!==l&&r.stopPropagation()}else Ze(e,n,r,null,t)}}function pe(e,n,t,r){if(Du=null,null!==(e=dn(e=D(r))))if(null===(n=W(e)))e=null;else if(13===(t=n.tag)){if(null!==(e=H(n)))return e;e=null}else if(3===t){if(n.stateNode.current.memoizedState.isDehydrated)return 3===n.tag?n.stateNode.containerInfo:null;e=null}else n!==e&&(e=null);return Du=e,null}function me(e){switch(e){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(cu()){case fu:return 1;case du:return 4;case pu:case mu:return 16;case hu:return 536870912;default:return 16}default:return 16}}function he(){if(Uu)return Uu;var e,n,t=Iu,r=t.length,l="value"in Ou?Ou.value:Ou.textContent,a=l.length;for(e=0;e<r&&t[e]===l[e];e++);var u=r-e;for(n=1;n<=u&&t[r-n]===l[a-n];n++);return Uu=l.slice(e,1<n?1-n:void 0)}function ge(e){var n=e.keyCode;return"charCode"in e?0===(e=e.charCode)&&13===n&&(e=13):e=n,10===e&&(e=13),32<=e||13===e?e:0}function ve(){return!0}function ye(){return!1}function be(e){function n(n,t,r,l,a){for(var u in this._reactName=n,this._targetInst=r,this.type=t,this.nativeEvent=l,this.target=a,this.currentTarget=null,e)e.hasOwnProperty(u)&&(n=e[u],this[u]=n?n(l):l[u]);return this.isDefaultPrevented=(null!=l.defaultPrevented?l.defaultPrevented:!1===l.returnValue)?ve:ye,this.isPropagationStopped=ye,this}return La(n.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():"unknown"!=typeof e.returnValue&&(e.returnValue=!1),this.isDefaultPrevented=ve)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():"unknown"!=typeof e.cancelBubble&&(e.cancelBubble=!0),this.isPropagationStopped=ve)},persist:function(){},isPersistent:ve}),n}function ke(e){var n=this.nativeEvent;return n.getModifierState?n.getModifierState(e):!!(e=eo[e])&&!!n[e]}function we(e){return ke}function Se(e,n){switch(e){case"keyup":return-1!==io.indexOf(n.keyCode);case"keydown":return 229!==n.keyCode;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function xe(e){return"object"==typeof(e=e.detail)&&"data"in e?e.data:null}function Ee(e){var n=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===n?!!vo[e.type]:"textarea"===n}function Ce(e,n,t,r){I(r),0<(n=en(n,"onChange")).length&&(t=new Au("onChange","change",null,t,r),e.push({event:t,listeners:n}))}function ze(e){qe(e,0)}function Ne(e){if(g(mn(e)))return e}function Pe(e,n){if("change"===e)return n}function _e(){yo&&(yo.detachEvent("onpropertychange",Le),bo=yo=null)}function Le(e){if("value"===e.propertyName&&Ne(bo)){var n=[];Ce(n,bo,e,D(e)),V(ze,n)}}function Te(e,n,t){"focusin"===e?(_e(),bo=t,(yo=n).attachEvent("onpropertychange",Le)):"focusout"===e&&_e()}function Me(e,n){if("selectionchange"===e||"keyup"===e||"keydown"===e)return Ne(bo)}function Fe(e,n){if("click"===e)return Ne(n)}function Re(e,n){if("input"===e||"change"===e)return Ne(n)}function De(e,n){if(wo(e,n))return!0;if("object"!=typeof e||null===e||"object"!=typeof n||null===n)return!1;var t=Object.keys(e),r=Object.keys(n);if(t.length!==r.length)return!1;for(r=0;r<t.length;r++){var l=t[r];if(!aa.call(n,l)||!wo(e[l],n[l]))return!1}return!0}function Oe(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function Ie(e,n){var t,r=Oe(e);for(e=0;r;){if(3===r.nodeType){if(t=e+r.textContent.length,e<=n&&t>=n)return{node:r,offset:n-e};e=t}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=Oe(r)}}function Ue(e,n){return!(!e||!n)&&(e===n||(!e||3!==e.nodeType)&&(n&&3===n.nodeType?Ue(e,n.parentNode):"contains"in e?e.contains(n):!!e.compareDocumentPosition&&!!(16&e.compareDocumentPosition(n))))}function Ve(){for(var e=window,n=v();n instanceof e.HTMLIFrameElement;){try{var t="string"==typeof n.contentWindow.location.href}catch(e){t=!1}if(!t)break;n=v((e=n.contentWindow).document)}return n}function Ae(e){var n=e&&e.nodeName&&e.nodeName.toLowerCase();return n&&("input"===n&&("text"===e.type||"search"===e.type||"tel"===e.type||"url"===e.type||"password"===e.type)||"textarea"===n||"true"===e.contentEditable)}function Be(e){var n=Ve(),t=e.focusedElem,r=e.selectionRange;if(n!==t&&t&&t.ownerDocument&&Ue(t.ownerDocument.documentElement,t)){if(null!==r&&Ae(t))if(n=r.start,void 0===(e=r.end)&&(e=n),"selectionStart"in t)t.selectionStart=n,t.selectionEnd=Math.min(e,t.value.length);else if((e=(n=t.ownerDocument||document)&&n.defaultView||window).getSelection){e=e.getSelection();var l=t.textContent.length,a=Math.min(r.start,l);r=void 0===r.end?a:Math.min(r.end,l),!e.extend&&a>r&&(l=r,r=a,a=l),l=Ie(t,a);var u=Ie(t,r);l&&u&&(1!==e.rangeCount||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==u.node||e.focusOffset!==u.offset)&&((n=n.createRange()).setStart(l.node,l.offset),e.removeAllRanges(),a>r?(e.addRange(n),e.extend(u.node,u.offset)):(n.setEnd(u.node,u.offset),e.addRange(n)))}for(n=[],e=t;e=e.parentNode;)1===e.nodeType&&n.push({element:e,left:e.scrollLeft,top:e.scrollTop});for("function"==typeof t.focus&&t.focus(),t=0;t<n.length;t++)(e=n[t]).element.scrollLeft=e.left,e.element.scrollTop=e.top}}function We(e,n,t){var r=t.window===t?t.document:9===t.nodeType?t:t.ownerDocument;zo||null==xo||xo!==v(r)||(r="selectionStart"in(r=xo)&&Ae(r)?{start:r.selectionStart,end:r.selectionEnd}:{anchorNode:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset},Co&&De(Co,r)||(Co=r,0<(r=en(Eo,"onSelect")).length&&(n=new Au("onSelect","select",null,n,t),e.push({event:n,listeners:r}),n.target=xo)))}function He(e,n){var t={};return t[e.toLowerCase()]=n.toLowerCase(),t["Webkit"+e]="webkit"+n,t["Moz"+e]="moz"+n,t}function Qe(e){if(Po[e])return Po[e];if(!No[e])return e;var n,t=No[e];for(n in t)if(t.hasOwnProperty(n)&&n in _o)return Po[e]=t[n];return e}function je(e,n){Ro.set(e,n),r(n,[e])}function $e(e,n,r){var l=e.type||"unknown-event";e.currentTarget=r,function(e,n,r,l,a,u,o,i,s){if(B.apply(this,arguments),Ga){if(!Ga)throw Error(t(198));var c=Za;Ga=!1,Za=null,Ja||(Ja=!0,eu=c)}}(l,n,void 0,e),e.currentTarget=null}function qe(e,n){n=0!=(4&n);for(var t=0;t<e.length;t++){var r=e[t],l=r.event;r=r.listeners;e:{var a=void 0;if(n)for(var u=r.length-1;0<=u;u--){var o=r[u],i=o.instance,s=o.currentTarget;if(o=o.listener,i!==a&&l.isPropagationStopped())break e;$e(l,o,s),a=i}else for(u=0;u<r.length;u++){if(i=(o=r[u]).instance,s=o.currentTarget,o=o.listener,i!==a&&l.isPropagationStopped())break e;$e(l,o,s),a=i}}}if(Ja)throw e=eu,Ja=!1,eu=null,e}function Ke(e,n){var t=n[Go];void 0===t&&(t=n[Go]=new Set);var r=e+"__bubble";t.has(r)||(Ge(n,e,2,!1),t.add(r))}function Ye(e,n,t){var r=0;n&&(r|=4),Ge(t,e,r,n)}function Xe(e){if(!e[Uo]){e[Uo]=!0,ta.forEach((function(n){"selectionchange"!==n&&(Io.has(n)||Ye(n,!1,e),Ye(n,!0,e))}));var n=9===e.nodeType?e:e.ownerDocument;null===n||n[Uo]||(n[Uo]=!0,Ye("selectionchange",!1,n))}}function Ge(e,n,t,r,l){switch(me(n)){case 1:l=ce;break;case 4:l=fe;break;default:l=de}t=l.bind(null,n,t,e),l=void 0,!ja||"touchstart"!==n&&"touchmove"!==n&&"wheel"!==n||(l=!0),r?void 0!==l?e.addEventListener(n,t,{capture:!0,passive:l}):e.addEventListener(n,t,!0):void 0!==l?e.addEventListener(n,t,{passive:l}):e.addEventListener(n,t,!1)}function Ze(e,n,t,r,l){var a=r;if(0==(1&n)&&0==(2&n)&&null!==r)e:for(;;){if(null===r)return;var u=r.tag;if(3===u||4===u){var o=r.stateNode.containerInfo;if(o===l||8===o.nodeType&&o.parentNode===l)break;if(4===u)for(u=r.return;null!==u;){var i=u.tag;if((3===i||4===i)&&((i=u.stateNode.containerInfo)===l||8===i.nodeType&&i.parentNode===l))return;u=u.return}for(;null!==o;){if(null===(u=dn(o)))return;if(5===(i=u.tag)||6===i){r=a=u;continue e}o=o.parentNode}}r=r.return}V((function(){var r=a,l=D(t),u=[];e:{var o=Ro.get(e);if(void 0!==o){var i=Au,s=e;switch(e){case"keypress":if(0===ge(t))break e;case"keydown":case"keyup":i=to;break;case"focusin":s="focus",i=$u;break;case"focusout":s="blur",i=$u;break;case"beforeblur":case"afterblur":i=$u;break;case"click":if(2===t.button)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":i=Qu;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":i=ju;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":i=lo;break;case Lo:case To:case Mo:i=qu;break;case Fo:i=ao;break;case"scroll":i=Wu;break;case"wheel":i=oo;break;case"copy":case"cut":case"paste":i=Yu;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":i=ro}var c=0!=(4&n),f=!c&&"scroll"===e,d=c?null!==o?o+"Capture":null:o;c=[];for(var p,m=r;null!==m;){var h=(p=m).stateNode;if(5===p.tag&&null!==h&&(p=h,null!==d&&null!=(h=A(m,d))&&c.push(Je(m,h,p))),f)break;m=m.return}0<c.length&&(o=new i(o,s,null,t,l),u.push({event:o,listeners:c}))}}if(0==(7&n)){if(i="mouseout"===e||"pointerout"===e,(!(o="mouseover"===e||"pointerover"===e)||t===Ua||!(s=t.relatedTarget||t.fromElement)||!dn(s)&&!s[Xo])&&(i||o)&&(o=l.window===l?l:(o=l.ownerDocument)?o.defaultView||o.parentWindow:window,i?(i=r,null!==(s=(s=t.relatedTarget||t.toElement)?dn(s):null)&&(s!==(f=W(s))||5!==s.tag&&6!==s.tag)&&(s=null)):(i=null,s=r),i!==s)){if(c=Qu,h="onMouseLeave",d="onMouseEnter",m="mouse","pointerout"!==e&&"pointerover"!==e||(c=ro,h="onPointerLeave",d="onPointerEnter",m="pointer"),f=null==i?o:mn(i),p=null==s?o:mn(s),(o=new c(h,m+"leave",i,t,l)).target=f,o.relatedTarget=p,h=null,dn(l)===r&&((c=new c(d,m+"enter",s,t,l)).target=p,c.relatedTarget=f,h=c),f=h,i&&s)e:{for(d=s,m=0,p=c=i;p;p=nn(p))m++;for(p=0,h=d;h;h=nn(h))p++;for(;0<m-p;)c=nn(c),m--;for(;0<p-m;)d=nn(d),p--;for(;m--;){if(c===d||null!==d&&c===d.alternate)break e;c=nn(c),d=nn(d)}c=null}else c=null;null!==i&&tn(u,o,i,c,!1),null!==s&&null!==f&&tn(u,f,s,c,!0)}if("select"===(i=(o=r?mn(r):window).nodeName&&o.nodeName.toLowerCase())||"input"===i&&"file"===o.type)var g=Pe;else if(Ee(o))if(ko)g=Re;else{g=Me;var v=Te}else(i=o.nodeName)&&"input"===i.toLowerCase()&&("checkbox"===o.type||"radio"===o.type)&&(g=Fe);switch(g&&(g=g(e,r))?Ce(u,g,t,l):(v&&v(e,o,r),"focusout"===e&&(v=o._wrapperState)&&v.controlled&&"number"===o.type&&x(o,"number",o.value)),v=r?mn(r):window,e){case"focusin":(Ee(v)||"true"===v.contentEditable)&&(xo=v,Eo=r,Co=null);break;case"focusout":Co=Eo=xo=null;break;case"mousedown":zo=!0;break;case"contextmenu":case"mouseup":case"dragend":zo=!1,We(u,t,l);break;case"selectionchange":if(So)break;case"keydown":case"keyup":We(u,t,l)}var y;if(so)e:{switch(e){case"compositionstart":var b="onCompositionStart";break e;case"compositionend":b="onCompositionEnd";break e;case"compositionupdate":b="onCompositionUpdate";break e}b=void 0}else go?Se(e,t)&&(b="onCompositionEnd"):"keydown"===e&&229===t.keyCode&&(b="onCompositionStart");b&&(po&&"ko"!==t.locale&&(go||"onCompositionStart"!==b?"onCompositionEnd"===b&&go&&(y=he()):(Iu="value"in(Ou=l)?Ou.value:Ou.textContent,go=!0)),0<(v=en(r,b)).length&&(b=new Xu(b,e,null,t,l),u.push({event:b,listeners:v}),(y||null!==(y=xe(t)))&&(b.data=y))),(y=fo?function(e,n){switch(e){case"compositionend":return xe(n);case"keypress":return 32!==n.which?null:(ho=!0,mo);case"textInput":return(e=n.data)===mo&&ho?null:e;default:return null}}(e,t):function(e,n){if(go)return"compositionend"===e||!so&&Se(e,n)?(e=he(),Uu=Iu=Ou=null,go=!1,e):null;switch(e){case"paste":default:return null;case"keypress":if(!(n.ctrlKey||n.altKey||n.metaKey)||n.ctrlKey&&n.altKey){if(n.char&&1<n.char.length)return n.char;if(n.which)return String.fromCharCode(n.which)}return null;case"compositionend":return po&&"ko"!==n.locale?null:n.data}}(e,t))&&0<(r=en(r,"onBeforeInput")).length&&(l=new Gu("onBeforeInput","beforeinput",null,t,l),u.push({event:l,listeners:r}),l.data=y)}qe(u,n)}))}function Je(e,n,t){return{instance:e,listener:n,currentTarget:t}}function en(e,n){for(var t=n+"Capture",r=[];null!==e;){var l=e,a=l.stateNode;5===l.tag&&null!==a&&(l=a,null!=(a=A(e,t))&&r.unshift(Je(e,a,l)),null!=(a=A(e,n))&&r.push(Je(e,a,l))),e=e.return}return r}function nn(e){if(null===e)return null;do{e=e.return}while(e&&5!==e.tag);return e||null}function tn(e,n,t,r,l){for(var a=n._reactName,u=[];null!==t&&t!==r;){var o=t,i=o.alternate,s=o.stateNode;if(null!==i&&i===r)break;5===o.tag&&null!==s&&(o=s,l?null!=(i=A(t,a))&&u.unshift(Je(t,i,o)):l||null!=(i=A(t,a))&&u.push(Je(t,i,o))),t=t.return}0!==u.length&&e.push({event:n,listeners:u})}function rn(e){return("string"==typeof e?e:""+e).replace(Vo,"\n").replace(Ao,"")}function ln(e,n,r,l){if(n=rn(n),rn(e)!==n&&r)throw Error(t(425))}function an(){}function un(e,n){return"textarea"===e||"noscript"===e||"string"==typeof n.children||"number"==typeof n.children||"object"==typeof n.dangerouslySetInnerHTML&&null!==n.dangerouslySetInnerHTML&&null!=n.dangerouslySetInnerHTML.__html}function on(e){setTimeout((function(){throw e}))}function sn(e,n){var t=n,r=0;do{var l=t.nextSibling;if(e.removeChild(t),l&&8===l.nodeType)if("/$"===(t=l.data)){if(0===r)return e.removeChild(l),void se(n);r--}else"$"!==t&&"$?"!==t&&"$!"!==t||r++;t=l}while(t);se(n)}function cn(e){for(;null!=e;e=e.nextSibling){var n=e.nodeType;if(1===n||3===n)break;if(8===n){if("$"===(n=e.data)||"$!"===n||"$?"===n)break;if("/$"===n)return null}}return e}function fn(e){e=e.previousSibling;for(var n=0;e;){if(8===e.nodeType){var t=e.data;if("$"===t||"$!"===t||"$?"===t){if(0===n)return e;n--}else"/$"===t&&n++}e=e.previousSibling}return null}function dn(e){var n=e[Ko];if(n)return n;for(var t=e.parentNode;t;){if(n=t[Xo]||t[Ko]){if(t=n.alternate,null!==n.child||null!==t&&null!==t.child)for(e=fn(e);null!==e;){if(t=e[Ko])return t;e=fn(e)}return n}t=(e=t).parentNode}return null}function pn(e){return!(e=e[Ko]||e[Xo])||5!==e.tag&&6!==e.tag&&13!==e.tag&&3!==e.tag?null:e}function mn(e){if(5===e.tag||6===e.tag)return e.stateNode;throw Error(t(33))}function hn(e){return e[Yo]||null}function gn(e){return{current:e}}function vn(e,n){0>ni||(e.current=ei[ni],ei[ni]=null,ni--)}function yn(e,n,t){ni++,ei[ni]=e.current,e.current=n}function bn(e,n){var t=e.type.contextTypes;if(!t)return ti;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===n)return r.__reactInternalMemoizedMaskedChildContext;var l,a={};for(l in t)a[l]=n[l];return r&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=n,e.__reactInternalMemoizedMaskedChildContext=a),a}function kn(e){return null!=(e=e.childContextTypes)}function wn(e,n,r){if(ri.current!==ti)throw Error(t(168));yn(ri,n),yn(li,r)}function Sn(e,n,r){var l=e.stateNode;if(n=n.childContextTypes,"function"!=typeof l.getChildContext)return r;for(var a in l=l.getChildContext())if(!(a in n))throw Error(t(108,d(e)||"Unknown",a));return La({},r,l)}function xn(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||ti,ai=ri.current,yn(ri,e),yn(li,li.current),!0}function En(e,n,r){var l=e.stateNode;if(!l)throw Error(t(169));r?(e=Sn(e,n,ai),l.__reactInternalMemoizedMergedChildContext=e,vn(li),vn(ri),yn(ri,e)):vn(li),yn(li,r)}function Cn(e){null===ui?ui=[e]:ui.push(e)}function zn(){if(!ii&&null!==ui){ii=!0;var e=0,n=xu;try{var t=ui;for(xu=1;e<t.length;e++){var r=t[e];do{r=r(!0)}while(null!==r)}ui=null,oi=!1}catch(n){throw null!==ui&&(ui=ui.slice(e+1)),au(fu,zn),n}finally{xu=n,ii=!1}}return null}function Nn(e,n){si[ci++]=di,si[ci++]=fi,fi=e,di=n}function Pn(e,n,t){pi[mi++]=gi,pi[mi++]=vi,pi[mi++]=hi,hi=e;var r=gi;e=vi;var l=32-yu(r)-1;r&=~(1<<l),t+=1;var a=32-yu(n)+l;if(30<a){var u=l-l%5;a=(r&(1<<u)-1).toString(32),r>>=u,l-=u,gi=1<<32-yu(n)+l|t<<l|r,vi=a+e}else gi=1<<a|t<<l|r,vi=e}function _n(e){null!==e.return&&(Nn(e,1),Pn(e,1,0))}function Ln(e){for(;e===fi;)fi=si[--ci],si[ci]=null,di=si[--ci],si[ci]=null;for(;e===hi;)hi=pi[--mi],pi[mi]=null,vi=pi[--mi],pi[mi]=null,gi=pi[--mi],pi[mi]=null}function Tn(e,n){var t=$s(5,null,null,0);t.elementType="DELETED",t.stateNode=n,t.return=e,null===(n=e.deletions)?(e.deletions=[t],e.flags|=16):n.push(t)}function Mn(e,n){switch(e.tag){case 5:var t=e.type;return null!==(n=1!==n.nodeType||t.toLowerCase()!==n.nodeName.toLowerCase()?null:n)&&(e.stateNode=n,yi=e,bi=cn(n.firstChild),!0);case 6:return null!==(n=""===e.pendingProps||3!==n.nodeType?null:n)&&(e.stateNode=n,yi=e,bi=null,!0);case 13:return null!==(n=8!==n.nodeType?null:n)&&(t=null!==hi?{id:gi,overflow:vi}:null,e.memoizedState={dehydrated:n,treeContext:t,retryLane:1073741824},(t=$s(18,null,null,0)).stateNode=n,t.return=e,e.child=t,yi=e,bi=null,!0);default:return!1}}function Fn(e){return 0!=(1&e.mode)&&0==(128&e.flags)}function Rn(e){if(ki){var n=bi;if(n){var r=n;if(!Mn(e,n)){if(Fn(e))throw Error(t(418));n=cn(r.nextSibling);var l=yi;n&&Mn(e,n)?Tn(l,r):(e.flags=-4097&e.flags|2,ki=!1,yi=e)}}else{if(Fn(e))throw Error(t(418));e.flags=-4097&e.flags|2,ki=!1,yi=e}}}function Dn(e){for(e=e.return;null!==e&&5!==e.tag&&3!==e.tag&&13!==e.tag;)e=e.return;yi=e}function On(e){if(e!==yi)return!1;if(!ki)return Dn(e),ki=!0,!1;var n;if((n=3!==e.tag)&&!(n=5!==e.tag)&&(n="head"!==(n=e.type)&&"body"!==n&&!un(e.type,e.memoizedProps)),n&&(n=bi)){if(Fn(e)){for(e=bi;e;)e=cn(e.nextSibling);throw Error(t(418))}for(;n;)Tn(e,n),n=cn(n.nextSibling)}if(Dn(e),13===e.tag){if(!(e=null!==(e=e.memoizedState)?e.dehydrated:null))throw Error(t(317));e:{for(e=e.nextSibling,n=0;e;){if(8===e.nodeType){var r=e.data;if("/$"===r){if(0===n){bi=cn(e.nextSibling);break e}n--}else"$"!==r&&"$!"!==r&&"$?"!==r||n++}e=e.nextSibling}bi=null}}else bi=yi?cn(e.stateNode.nextSibling):null;return!0}function In(){bi=yi=null,ki=!1}function Un(e){null===wi?wi=[e]:wi.push(e)}function Vn(e,n){if(e&&e.defaultProps){for(var t in n=La({},n),e=e.defaultProps)void 0===n[t]&&(n[t]=e[t]);return n}return n}function An(){zi=Ci=Ei=null}function Bn(e,n){n=xi.current,vn(xi),e._currentValue=n}function Wn(e,n,t){for(;null!==e;){var r=e.alternate;if((e.childLanes&n)!==n?(e.childLanes|=n,null!==r&&(r.childLanes|=n)):null!==r&&(r.childLanes&n)!==n&&(r.childLanes|=n),e===t)break;e=e.return}}function Hn(e,n){Ei=e,zi=Ci=null,null!==(e=e.dependencies)&&null!==e.firstContext&&(0!=(e.lanes&n)&&(ts=!0),e.firstContext=null)}function Qn(e){var n=e._currentValue;if(zi!==e)if(e={context:e,memoizedValue:n,next:null},null===Ci){if(null===Ei)throw Error(t(308));Ci=e,Ei.dependencies={lanes:0,firstContext:e}}else Ci=Ci.next=e;return n}function jn(e){null===Ni?Ni=[e]:Ni.push(e)}function $n(e,n,t,r){var l=n.interleaved;return null===l?(t.next=t,jn(n)):(t.next=l.next,l.next=t),n.interleaved=t,qn(e,r)}function qn(e,n){e.lanes|=n;var t=e.alternate;for(null!==t&&(t.lanes|=n),t=e,e=e.return;null!==e;)e.childLanes|=n,null!==(t=e.alternate)&&(t.childLanes|=n),t=e,e=e.return;return 3===t.tag?t.stateNode:null}function Kn(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Yn(e,n){e=e.updateQueue,n.updateQueue===e&&(n.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Xn(e,n){return{eventTime:e,lane:n,tag:0,payload:null,callback:null,next:null}}function Gn(e,n,t){var r=e.updateQueue;if(null===r)return null;if(r=r.shared,0!=(2&bs)){var l=r.pending;return null===l?n.next=n:(n.next=l.next,l.next=n),r.pending=n,Pi(e,t)}return null===(l=r.interleaved)?(n.next=n,jn(r)):(n.next=l.next,l.next=n),r.interleaved=n,qn(e,t)}function Zn(e,n,t){if(null!==(n=n.updateQueue)&&(n=n.shared,0!=(4194240&t))){var r=n.lanes;t|=r&=e.pendingLanes,n.lanes=t,ee(e,t)}}function Jn(e,n){var t=e.updateQueue,r=e.alternate;if(null!==r&&t===(r=r.updateQueue)){var l=null,a=null;if(null!==(t=t.firstBaseUpdate)){do{var u={eventTime:t.eventTime,lane:t.lane,tag:t.tag,payload:t.payload,callback:t.callback,next:null};null===a?l=a=u:a=a.next=u,t=t.next}while(null!==t);null===a?l=a=n:a=a.next=n}else l=a=n;return t={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:a,shared:r.shared,effects:r.effects},void(e.updateQueue=t)}null===(e=t.lastBaseUpdate)?t.firstBaseUpdate=n:e.next=n,t.lastBaseUpdate=n}function et(e,n,t,r){var l=e.updateQueue;_i=!1;var a=l.firstBaseUpdate,u=l.lastBaseUpdate,o=l.shared.pending;if(null!==o){l.shared.pending=null;var i=o,s=i.next;i.next=null,null===u?a=s:u.next=s,u=i;var c=e.alternate;null!==c&&(o=(c=c.updateQueue).lastBaseUpdate)!==u&&(null===o?c.firstBaseUpdate=s:o.next=s,c.lastBaseUpdate=i)}if(null!==a){var f=l.baseState;for(u=0,c=s=i=null,o=a;;){var d=o.lane,p=o.eventTime;if((r&d)===d){null!==c&&(c=c.next={eventTime:p,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var m=e,h=o;switch(d=n,p=t,h.tag){case 1:if("function"==typeof(m=h.payload)){f=m.call(p,f,d);break e}f=m;break e;case 3:m.flags=-65537&m.flags|128;case 0:if(null==(d="function"==typeof(m=h.payload)?m.call(p,f,d):m))break e;f=La({},f,d);break e;case 2:_i=!0}}null!==o.callback&&0!==o.lane&&(e.flags|=64,null===(d=l.effects)?l.effects=[o]:d.push(o))}else p={eventTime:p,lane:d,tag:o.tag,payload:o.payload,callback:o.callback,next:null},null===c?(s=c=p,i=f):c=c.next=p,u|=d;if(null===(o=o.next)){if(null===(o=l.shared.pending))break;o=(d=o).next,d.next=null,l.lastBaseUpdate=d,l.shared.pending=null}}if(null===c&&(i=f),l.baseState=i,l.firstBaseUpdate=s,l.lastBaseUpdate=c,null!==(n=l.shared.interleaved)){l=n;do{u|=l.lane,l=l.next}while(l!==n)}else null===a&&(l.shared.lanes=0);Ns|=u,e.lanes=u,e.memoizedState=f}}function nt(e,n,r){if(e=n.effects,n.effects=null,null!==e)for(n=0;n<e.length;n++){var l=e[n],a=l.callback;if(null!==a){if(l.callback=null,l=r,"function"!=typeof a)throw Error(t(191,a));a.call(l)}}}function tt(e,n,t,r){t=null==(t=t(r,n=e.memoizedState))?n:La({},n,t),e.memoizedState=t,0===e.lanes&&(e.updateQueue.baseState=t)}function rt(e,n,t,r,l,a,u){return"function"==typeof(e=e.stateNode).shouldComponentUpdate?e.shouldComponentUpdate(r,a,u):!(n.prototype&&n.prototype.isPureReactComponent&&De(t,r)&&De(l,a))}function lt(e,n,t){var r=!1,l=ti,a=n.contextType;return"object"==typeof a&&null!==a?a=Qn(a):(l=kn(n)?ai:ri.current,a=(r=null!=(r=n.contextTypes))?bn(e,l):ti),n=new n(t,a),e.memoizedState=null!==n.state&&void 0!==n.state?n.state:null,n.updater=Ti,e.stateNode=n,n._reactInternals=e,r&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=l,e.__reactInternalMemoizedMaskedChildContext=a),n}function at(e,n,t,r){e=n.state,"function"==typeof n.componentWillReceiveProps&&n.componentWillReceiveProps(t,r),"function"==typeof n.UNSAFE_componentWillReceiveProps&&n.UNSAFE_componentWillReceiveProps(t,r),n.state!==e&&Ti.enqueueReplaceState(n,n.state,null)}function ut(e,n,t,r){var l=e.stateNode;l.props=t,l.state=e.memoizedState,l.refs=Li,Kn(e);var a=n.contextType;"object"==typeof a&&null!==a?l.context=Qn(a):(a=kn(n)?ai:ri.current,l.context=bn(e,a)),l.state=e.memoizedState,"function"==typeof(a=n.getDerivedStateFromProps)&&(tt(e,n,a,t),l.state=e.memoizedState),"function"==typeof n.getDerivedStateFromProps||"function"==typeof l.getSnapshotBeforeUpdate||"function"!=typeof l.UNSAFE_componentWillMount&&"function"!=typeof l.componentWillMount||(n=l.state,"function"==typeof l.componentWillMount&&l.componentWillMount(),"function"==typeof l.UNSAFE_componentWillMount&&l.UNSAFE_componentWillMount(),n!==l.state&&Ti.enqueueReplaceState(l,l.state,null),et(e,t,l,r),l.state=e.memoizedState),"function"==typeof l.componentDidMount&&(e.flags|=4194308)}function ot(e,n,r){if(null!==(e=r.ref)&&"function"!=typeof e&&"object"!=typeof e){if(r._owner){if(r=r._owner){if(1!==r.tag)throw Error(t(309));var l=r.stateNode}if(!l)throw Error(t(147,e));var a=l,u=""+e;return null!==n&&null!==n.ref&&"function"==typeof n.ref&&n.ref._stringRef===u?n.ref:(n=function(e){var n=a.refs;n===Li&&(n=a.refs={}),null===e?delete n[u]:n[u]=e},n._stringRef=u,n)}if("string"!=typeof e)throw Error(t(284));if(!r._owner)throw Error(t(290,e))}return e}function it(e,n){throw e=Object.prototype.toString.call(n),Error(t(31,"[object Object]"===e?"object with keys {"+Object.keys(n).join(", ")+"}":e))}function st(e){return(0,e._init)(e._payload)}function ct(e){function n(n,t){if(e){var r=n.deletions;null===r?(n.deletions=[t],n.flags|=16):r.push(t)}}function r(t,r){if(!e)return null;for(;null!==r;)n(t,r),r=r.sibling;return null}function l(e,n){for(e=new Map;null!==n;)null!==n.key?e.set(n.key,n):e.set(n.index,n),n=n.sibling;return e}function a(e,n){return(e=Fl(e,n)).index=0,e.sibling=null,e}function u(n,t,r){return n.index=r,e?null!==(r=n.alternate)?(r=r.index)<t?(n.flags|=2,t):r:(n.flags|=2,t):(n.flags|=1048576,t)}function i(n){return e&&null===n.alternate&&(n.flags|=2),n}function s(e,n,t,r){return null===n||6!==n.tag?((n=Il(t,e.mode,r)).return=e,n):((n=a(n,t)).return=e,n)}function c(e,n,t,r){var l=t.type;return l===ha?d(e,n,t.props.children,r,t.key):null!==n&&(n.elementType===l||"object"==typeof l&&null!==l&&l.$$typeof===Ea&&st(l)===n.type)?((r=a(n,t.props)).ref=ot(e,n,t),r.return=e,r):((r=Rl(t.type,t.key,t.props,null,e.mode,r)).ref=ot(e,n,t),r.return=e,r)}function f(e,n,t,r){return null===n||4!==n.tag||n.stateNode.containerInfo!==t.containerInfo||n.stateNode.implementation!==t.implementation?((n=Ul(t,e.mode,r)).return=e,n):((n=a(n,t.children||[])).return=e,n)}function d(e,n,t,r,l){return null===n||7!==n.tag?((n=Dl(t,e.mode,r,l)).return=e,n):((n=a(n,t)).return=e,n)}function p(e,n,t){if("string"==typeof n&&""!==n||"number"==typeof n)return(n=Il(""+n,e.mode,t)).return=e,n;if("object"==typeof n&&null!==n){switch(n.$$typeof){case pa:return(t=Rl(n.type,n.key,n.props,null,e.mode,t)).ref=ot(e,null,n),t.return=e,t;case ma:return(n=Ul(n,e.mode,t)).return=e,n;case Ea:return p(e,(0,n._init)(n._payload),t)}if(Ma(n)||o(n))return(n=Dl(n,e.mode,t,null)).return=e,n;it(e,n)}return null}function m(e,n,t,r){var l=null!==n?n.key:null;if("string"==typeof t&&""!==t||"number"==typeof t)return null!==l?null:s(e,n,""+t,r);if("object"==typeof t&&null!==t){switch(t.$$typeof){case pa:return t.key===l?c(e,n,t,r):null;case ma:return t.key===l?f(e,n,t,r):null;case Ea:return m(e,n,(l=t._init)(t._payload),r)}if(Ma(t)||o(t))return null!==l?null:d(e,n,t,r,null);it(e,t)}return null}function h(e,n,t,r,l){if("string"==typeof r&&""!==r||"number"==typeof r)return s(n,e=e.get(t)||null,""+r,l);if("object"==typeof r&&null!==r){switch(r.$$typeof){case pa:return c(n,e=e.get(null===r.key?t:r.key)||null,r,l);case ma:return f(n,e=e.get(null===r.key?t:r.key)||null,r,l);case Ea:return h(e,n,t,(0,r._init)(r._payload),l)}if(Ma(r)||o(r))return d(n,e=e.get(t)||null,r,l,null);it(n,r)}return null}function g(t,a,o,i){for(var s=null,c=null,f=a,d=a=0,g=null;null!==f&&d<o.length;d++){f.index>d?(g=f,f=null):g=f.sibling;var v=m(t,f,o[d],i);if(null===v){null===f&&(f=g);break}e&&f&&null===v.alternate&&n(t,f),a=u(v,a,d),null===c?s=v:c.sibling=v,c=v,f=g}if(d===o.length)return r(t,f),ki&&Nn(t,d),s;if(null===f){for(;d<o.length;d++)null!==(f=p(t,o[d],i))&&(a=u(f,a,d),null===c?s=f:c.sibling=f,c=f);return ki&&Nn(t,d),s}for(f=l(t,f);d<o.length;d++)null!==(g=h(f,t,d,o[d],i))&&(e&&null!==g.alternate&&f.delete(null===g.key?d:g.key),a=u(g,a,d),null===c?s=g:c.sibling=g,c=g);return e&&f.forEach((function(e){return n(t,e)})),ki&&Nn(t,d),s}function v(a,i,s,c){var f=o(s);if("function"!=typeof f)throw Error(t(150));if(null==(s=f.call(s)))throw Error(t(151));for(var d=f=null,g=i,v=i=0,y=null,b=s.next();null!==g&&!b.done;v++,b=s.next()){g.index>v?(y=g,g=null):y=g.sibling;var k=m(a,g,b.value,c);if(null===k){null===g&&(g=y);break}e&&g&&null===k.alternate&&n(a,g),i=u(k,i,v),null===d?f=k:d.sibling=k,d=k,g=y}if(b.done)return r(a,g),ki&&Nn(a,v),f;if(null===g){for(;!b.done;v++,b=s.next())null!==(b=p(a,b.value,c))&&(i=u(b,i,v),null===d?f=b:d.sibling=b,d=b);return ki&&Nn(a,v),f}for(g=l(a,g);!b.done;v++,b=s.next())null!==(b=h(g,a,v,b.value,c))&&(e&&null!==b.alternate&&g.delete(null===b.key?v:b.key),i=u(b,i,v),null===d?f=b:d.sibling=b,d=b);return e&&g.forEach((function(e){return n(a,e)})),ki&&Nn(a,v),f}return function e(t,l,u,s){if("object"==typeof u&&null!==u&&u.type===ha&&null===u.key&&(u=u.props.children),"object"==typeof u&&null!==u){switch(u.$$typeof){case pa:e:{for(var c=u.key,f=l;null!==f;){if(f.key===c){if((c=u.type)===ha){if(7===f.tag){r(t,f.sibling),(l=a(f,u.props.children)).return=t,t=l;break e}}else if(f.elementType===c||"object"==typeof c&&null!==c&&c.$$typeof===Ea&&st(c)===f.type){r(t,f.sibling),(l=a(f,u.props)).ref=ot(t,f,u),l.return=t,t=l;break e}r(t,f);break}n(t,f),f=f.sibling}u.type===ha?((l=Dl(u.props.children,t.mode,s,u.key)).return=t,t=l):((s=Rl(u.type,u.key,u.props,null,t.mode,s)).ref=ot(t,l,u),s.return=t,t=s)}return i(t);case ma:e:{for(f=u.key;null!==l;){if(l.key===f){if(4===l.tag&&l.stateNode.containerInfo===u.containerInfo&&l.stateNode.implementation===u.implementation){r(t,l.sibling),(l=a(l,u.children||[])).return=t,t=l;break e}r(t,l);break}n(t,l),l=l.sibling}(l=Ul(u,t.mode,s)).return=t,t=l}return i(t);case Ea:return e(t,l,(f=u._init)(u._payload),s)}if(Ma(u))return g(t,l,u,s);if(o(u))return v(t,l,u,s);it(t,u)}return"string"==typeof u&&""!==u||"number"==typeof u?(u=""+u,null!==l&&6===l.tag?(r(t,l.sibling),(l=a(l,u)).return=t,t=l):(r(t,l),(l=Il(u,t.mode,s)).return=t,t=l),i(t)):r(t,l)}}function ft(e){if(e===Ri)throw Error(t(174));return e}function dt(e,n){switch(yn(Ii,n),yn(Oi,e),yn(Di,Ri),e=n.nodeType){case 9:case 11:n=(n=n.documentElement)?n.namespaceURI:L(null,"");break;default:n=L(n=(e=8===e?n.parentNode:n).namespaceURI||null,e=e.tagName)}vn(Di),yn(Di,n)}function pt(e){vn(Di),vn(Oi),vn(Ii)}function mt(e){ft(Ii.current);var n=ft(Di.current),t=L(n,e.type);n!==t&&(yn(Oi,e),yn(Di,t))}function ht(e){Oi.current===e&&(vn(Di),vn(Oi))}function gt(e){for(var n=e;null!==n;){if(13===n.tag){var t=n.memoizedState;if(null!==t&&(null===(t=t.dehydrated)||"$?"===t.data||"$!"===t.data))return n}else if(19===n.tag&&void 0!==n.memoizedProps.revealOrder){if(0!=(128&n.flags))return n}else if(null!==n.child){n.child.return=n,n=n.child;continue}if(n===e)break;for(;null===n.sibling;){if(null===n.return||n.return===e)return null;n=n.return}n.sibling.return=n.return,n=n.sibling}return null}function vt(){for(var e=0;e<Vi.length;e++)Vi[e]._workInProgressVersionPrimary=null;Vi.length=0}function yt(){throw Error(t(321))}function bt(e,n){if(null===n)return!1;for(var t=0;t<n.length&&t<e.length;t++)if(!wo(e[t],n[t]))return!1;return!0}function kt(e,n,r,l,a,u){if(Wi=u,Hi=n,n.memoizedState=null,n.updateQueue=null,n.lanes=0,Ai.current=null===e||null===e.memoizedState?Gi:Zi,e=r(l,a),qi){u=0;do{if(qi=!1,Ki=0,25<=u)throw Error(t(301));u+=1,ji=Qi=null,n.updateQueue=null,Ai.current=Ji,e=r(l,a)}while(qi)}if(Ai.current=Xi,n=null!==Qi&&null!==Qi.next,Wi=0,ji=Qi=Hi=null,$i=!1,n)throw Error(t(300));return e}function wt(){var e=0!==Ki;return Ki=0,e}function St(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return null===ji?Hi.memoizedState=ji=e:ji=ji.next=e,ji}function xt(){if(null===Qi){var e=Hi.alternate;e=null!==e?e.memoizedState:null}else e=Qi.next;var n=null===ji?Hi.memoizedState:ji.next;if(null!==n)ji=n,Qi=e;else{if(null===e)throw Error(t(310));e={memoizedState:(Qi=e).memoizedState,baseState:Qi.baseState,baseQueue:Qi.baseQueue,queue:Qi.queue,next:null},null===ji?Hi.memoizedState=ji=e:ji=ji.next=e}return ji}function Et(e,n){return"function"==typeof n?n(e):n}function Ct(e,n,r){if(null===(r=(n=xt()).queue))throw Error(t(311));r.lastRenderedReducer=e;var l=Qi,a=l.baseQueue,u=r.pending;if(null!==u){if(null!==a){var o=a.next;a.next=u.next,u.next=o}l.baseQueue=a=u,r.pending=null}if(null!==a){u=a.next,l=l.baseState;var i=o=null,s=null,c=u;do{var f=c.lane;if((Wi&f)===f)null!==s&&(s=s.next={lane:0,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null}),l=c.hasEagerState?c.eagerState:e(l,c.action);else{var d={lane:f,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null};null===s?(i=s=d,o=l):s=s.next=d,Hi.lanes|=f,Ns|=f}c=c.next}while(null!==c&&c!==u);null===s?o=l:s.next=i,wo(l,n.memoizedState)||(ts=!0),n.memoizedState=l,n.baseState=o,n.baseQueue=s,r.lastRenderedState=l}if(null!==(e=r.interleaved)){a=e;do{u=a.lane,Hi.lanes|=u,Ns|=u,a=a.next}while(a!==e)}else null===a&&(r.lanes=0);return[n.memoizedState,r.dispatch]}function zt(e,n,r){if(null===(r=(n=xt()).queue))throw Error(t(311));r.lastRenderedReducer=e;var l=r.dispatch,a=r.pending,u=n.memoizedState;if(null!==a){r.pending=null;var o=a=a.next;do{u=e(u,o.action),o=o.next}while(o!==a);wo(u,n.memoizedState)||(ts=!0),n.memoizedState=u,null===n.baseQueue&&(n.baseState=u),r.lastRenderedState=u}return[u,l]}function Nt(e,n,t){}function Pt(e,n,r){r=Hi;var l=xt(),a=n(),u=!wo(l.memoizedState,a);if(u&&(l.memoizedState=a,ts=!0),l=l.queue,At(Tt.bind(null,r,l,e),[e]),l.getSnapshot!==n||u||null!==ji&&1&ji.memoizedState.tag){if(r.flags|=2048,Dt(9,Lt.bind(null,r,l,a,n),void 0,null),null===ks)throw Error(t(349));0!=(30&Wi)||_t(r,n,a)}return a}function _t(e,n,t){e.flags|=16384,e={getSnapshot:n,value:t},null===(n=Hi.updateQueue)?(n={lastEffect:null,stores:null},Hi.updateQueue=n,n.stores=[e]):null===(t=n.stores)?n.stores=[e]:t.push(e)}function Lt(e,n,t,r){n.value=t,n.getSnapshot=r,Mt(n)&&Ft(e)}function Tt(e,n,t){return t((function(){Mt(n)&&Ft(e)}))}function Mt(e){var n=e.getSnapshot;e=e.value;try{var t=n();return!wo(e,t)}catch(e){return!0}}function Ft(e){var n=qn(e,1);null!==n&&ll(n,e,1,-1)}function Rt(e){var n=St();return"function"==typeof e&&(e=e()),n.memoizedState=n.baseState=e,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Et,lastRenderedState:e},n.queue=e,e=e.dispatch=Zt.bind(null,Hi,e),[n.memoizedState,e]}function Dt(e,n,t,r){return e={tag:e,create:n,destroy:t,deps:r,next:null},null===(n=Hi.updateQueue)?(n={lastEffect:null,stores:null},Hi.updateQueue=n,n.lastEffect=e.next=e):null===(t=n.lastEffect)?n.lastEffect=e.next=e:(r=t.next,t.next=e,e.next=r,n.lastEffect=e),e}function Ot(e){return xt().memoizedState}function It(e,n,t,r){var l=St();Hi.flags|=e,l.memoizedState=Dt(1|n,t,void 0,void 0===r?null:r)}function Ut(e,n,t,r){var l=xt();r=void 0===r?null:r;var a=void 0;if(null!==Qi){var u=Qi.memoizedState;if(a=u.destroy,null!==r&&bt(r,u.deps))return void(l.memoizedState=Dt(n,t,a,r))}Hi.flags|=e,l.memoizedState=Dt(1|n,t,a,r)}function Vt(e,n){return It(8390656,8,e,n)}function At(e,n){return Ut(2048,8,e,n)}function Bt(e,n){return Ut(4,2,e,n)}function Wt(e,n){return Ut(4,4,e,n)}function Ht(e,n){return"function"==typeof n?(e=e(),n(e),function(){n(null)}):null!=n?(e=e(),n.current=e,function(){n.current=null}):void 0}function Qt(e,n,t){return t=null!=t?t.concat([e]):null,Ut(4,4,Ht.bind(null,n,e),t)}function jt(e,n){}function $t(e,n){var t=xt();n=void 0===n?null:n;var r=t.memoizedState;return null!==r&&null!==n&&bt(n,r[1])?r[0]:(t.memoizedState=[e,n],e)}function qt(e,n){var t=xt();n=void 0===n?null:n;var r=t.memoizedState;return null!==r&&null!==n&&bt(n,r[1])?r[0]:(e=e(),t.memoizedState=[e,n],e)}function Kt(e,n,t){return 0==(21&Wi)?(e.baseState&&(e.baseState=!1,ts=!0),e.memoizedState=t):(wo(t,n)||(t=G(),Hi.lanes|=t,Ns|=t,e.baseState=!0),n)}function Yt(e,n,t){xu=0!==(t=xu)&&4>t?t:4,e(!0);var r=Bi.transition;Bi.transition={};try{e(!1),n()}finally{xu=t,Bi.transition=r}}function Xt(){return xt().memoizedState}function Gt(e,n,t){var r=rl(e);t={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null},Jt(e)?er(n,t):null!==(t=$n(e,n,t,r))&&(ll(t,e,r,tl()),nr(t,n,r))}function Zt(e,n,t){var r=rl(e),l={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null};if(Jt(e))er(n,l);else{var a=e.alternate;if(0===e.lanes&&(null===a||0===a.lanes)&&null!==(a=n.lastRenderedReducer))try{var u=n.lastRenderedState,o=a(u,t);if(l.hasEagerState=!0,l.eagerState=o,wo(o,u)){var i=n.interleaved;return null===i?(l.next=l,jn(n)):(l.next=i.next,i.next=l),void(n.interleaved=l)}}catch(e){}null!==(t=$n(e,n,l,r))&&(ll(t,e,r,l=tl()),nr(t,n,r))}}function Jt(e){var n=e.alternate;return e===Hi||null!==n&&n===Hi}function er(e,n){qi=$i=!0;var t=e.pending;null===t?n.next=n:(n.next=t.next,t.next=n),e.pending=n}function nr(e,n,t){if(0!=(4194240&t)){var r=n.lanes;t|=r&=e.pendingLanes,n.lanes=t,ee(e,t)}}function tr(e,n){try{var t="",r=n;do{t+=c(r),r=r.return}while(r);var l=t}catch(e){l="\nError generating stack: "+e.message+"\n"+e.stack}return{value:e,source:n,stack:l,digest:null}}function rr(e,n,t){return{value:e,source:null,stack:null!=t?t:null,digest:null!=n?n:null}}function lr(e,n){try{console.error(n.value)}catch(e){setTimeout((function(){throw e}))}}function ar(e,n,t){(t=Xn(-1,t)).tag=3,t.payload={element:null};var r=n.value;return t.callback=function(){Ds||(Ds=!0,Os=r),lr(0,n)},t}function ur(e,n,t){(t=Xn(-1,t)).tag=3;var r=e.type.getDerivedStateFromError;if("function"==typeof r){var l=n.value;t.payload=function(){return r(l)},t.callback=function(){lr(0,n)}}var a=e.stateNode;return null!==a&&"function"==typeof a.componentDidCatch&&(t.callback=function(){lr(0,n),"function"!=typeof r&&(null===Is?Is=new Set([this]):Is.add(this));var e=n.stack;this.componentDidCatch(n.value,{componentStack:null!==e?e:""})}),t}function or(e,n,t){var r=e.pingCache;if(null===r){r=e.pingCache=new es;var l=new Set;r.set(n,l)}else void 0===(l=r.get(n))&&(l=new Set,r.set(n,l));l.has(t)||(l.add(t),e=zl.bind(null,e,n,t),n.then(e,e))}function ir(e){do{var n;if((n=13===e.tag)&&(n=null===(n=e.memoizedState)||null!==n.dehydrated),n)return e;e=e.return}while(null!==e);return null}function sr(e,n,t,r,l){return 0==(1&e.mode)?(e===n?e.flags|=65536:(e.flags|=128,t.flags|=131072,t.flags&=-52805,1===t.tag&&(null===t.alternate?t.tag=17:((n=Xn(-1,1)).tag=2,Gn(t,n,1))),t.lanes|=1),e):(e.flags|=65536,e.lanes=l,e)}function cr(e,n,t,r){n.child=null===e?Fi(n,null,t,r):Mi(n,e.child,t,r)}function fr(e,n,t,r,l){t=t.render;var a=n.ref;return Hn(n,l),r=kt(e,n,t,r,a,l),t=wt(),null===e||ts?(ki&&t&&_n(n),n.flags|=1,cr(e,n,r,l),n.child):(n.updateQueue=e.updateQueue,n.flags&=-2053,e.lanes&=~l,_r(e,n,l))}function dr(e,n,t,r,l){if(null===e){var a=t.type;return"function"!=typeof a||Ml(a)||void 0!==a.defaultProps||null!==t.compare||void 0!==t.defaultProps?((e=Rl(t.type,null,r,n,n.mode,l)).ref=n.ref,e.return=n,n.child=e):(n.tag=15,n.type=a,pr(e,n,a,r,l))}if(a=e.child,0==(e.lanes&l)){var u=a.memoizedProps;if((t=null!==(t=t.compare)?t:De)(u,r)&&e.ref===n.ref)return _r(e,n,l)}return n.flags|=1,(e=Fl(a,r)).ref=n.ref,e.return=n,n.child=e}function pr(e,n,t,r,l){if(null!==e){var a=e.memoizedProps;if(De(a,r)&&e.ref===n.ref){if(ts=!1,n.pendingProps=r=a,0==(e.lanes&l))return n.lanes=e.lanes,_r(e,n,l);0!=(131072&e.flags)&&(ts=!0)}}return gr(e,n,t,r,l)}function mr(e,n,t){var r=n.pendingProps,l=r.children,a=null!==e?e.memoizedState:null;if("hidden"===r.mode)if(0==(1&n.mode))n.memoizedState={baseLanes:0,cachePool:null,transitions:null},yn(Es,xs),xs|=t;else{if(0==(1073741824&t))return e=null!==a?a.baseLanes|t:t,n.lanes=n.childLanes=1073741824,n.memoizedState={baseLanes:e,cachePool:null,transitions:null},n.updateQueue=null,yn(Es,xs),xs|=e,null;n.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=null!==a?a.baseLanes:t,yn(Es,xs),xs|=r}else null!==a?(r=a.baseLanes|t,n.memoizedState=null):r=t,yn(Es,xs),xs|=r;return cr(e,n,l,t),n.child}function hr(e,n){var t=n.ref;(null===e&&null!==t||null!==e&&e.ref!==t)&&(n.flags|=512,n.flags|=2097152)}function gr(e,n,t,r,l){var a=kn(t)?ai:ri.current;return a=bn(n,a),Hn(n,l),t=kt(e,n,t,r,a,l),r=wt(),null===e||ts?(ki&&r&&_n(n),n.flags|=1,cr(e,n,t,l),n.child):(n.updateQueue=e.updateQueue,n.flags&=-2053,e.lanes&=~l,_r(e,n,l))}function vr(e,n,t,r,l){if(kn(t)){var a=!0;xn(n)}else a=!1;if(Hn(n,l),null===n.stateNode)Pr(e,n),lt(n,t,r),ut(n,t,r,l),r=!0;else if(null===e){var u=n.stateNode,o=n.memoizedProps;u.props=o;var i=u.context,s=t.contextType;s="object"==typeof s&&null!==s?Qn(s):bn(n,s=kn(t)?ai:ri.current);var c=t.getDerivedStateFromProps,f="function"==typeof c||"function"==typeof u.getSnapshotBeforeUpdate;f||"function"!=typeof u.UNSAFE_componentWillReceiveProps&&"function"!=typeof u.componentWillReceiveProps||(o!==r||i!==s)&&at(n,u,r,s),_i=!1;var d=n.memoizedState;u.state=d,et(n,r,u,l),i=n.memoizedState,o!==r||d!==i||li.current||_i?("function"==typeof c&&(tt(n,t,c,r),i=n.memoizedState),(o=_i||rt(n,t,o,r,d,i,s))?(f||"function"!=typeof u.UNSAFE_componentWillMount&&"function"!=typeof u.componentWillMount||("function"==typeof u.componentWillMount&&u.componentWillMount(),"function"==typeof u.UNSAFE_componentWillMount&&u.UNSAFE_componentWillMount()),"function"==typeof u.componentDidMount&&(n.flags|=4194308)):("function"==typeof u.componentDidMount&&(n.flags|=4194308),n.memoizedProps=r,n.memoizedState=i),u.props=r,u.state=i,u.context=s,r=o):("function"==typeof u.componentDidMount&&(n.flags|=4194308),r=!1)}else{u=n.stateNode,Yn(e,n),o=n.memoizedProps,s=n.type===n.elementType?o:Vn(n.type,o),u.props=s,f=n.pendingProps,d=u.context,i="object"==typeof(i=t.contextType)&&null!==i?Qn(i):bn(n,i=kn(t)?ai:ri.current);var p=t.getDerivedStateFromProps;(c="function"==typeof p||"function"==typeof u.getSnapshotBeforeUpdate)||"function"!=typeof u.UNSAFE_componentWillReceiveProps&&"function"!=typeof u.componentWillReceiveProps||(o!==f||d!==i)&&at(n,u,r,i),_i=!1,d=n.memoizedState,u.state=d,et(n,r,u,l);var m=n.memoizedState;o!==f||d!==m||li.current||_i?("function"==typeof p&&(tt(n,t,p,r),m=n.memoizedState),(s=_i||rt(n,t,s,r,d,m,i)||!1)?(c||"function"!=typeof u.UNSAFE_componentWillUpdate&&"function"!=typeof u.componentWillUpdate||("function"==typeof u.componentWillUpdate&&u.componentWillUpdate(r,m,i),"function"==typeof u.UNSAFE_componentWillUpdate&&u.UNSAFE_componentWillUpdate(r,m,i)),"function"==typeof u.componentDidUpdate&&(n.flags|=4),"function"==typeof u.getSnapshotBeforeUpdate&&(n.flags|=1024)):("function"!=typeof u.componentDidUpdate||o===e.memoizedProps&&d===e.memoizedState||(n.flags|=4),"function"!=typeof u.getSnapshotBeforeUpdate||o===e.memoizedProps&&d===e.memoizedState||(n.flags|=1024),n.memoizedProps=r,n.memoizedState=m),u.props=r,u.state=m,u.context=i,r=s):("function"!=typeof u.componentDidUpdate||o===e.memoizedProps&&d===e.memoizedState||(n.flags|=4),"function"!=typeof u.getSnapshotBeforeUpdate||o===e.memoizedProps&&d===e.memoizedState||(n.flags|=1024),r=!1)}return yr(e,n,t,r,a,l)}function yr(e,n,t,r,l,a){hr(e,n);var u=0!=(128&n.flags);if(!r&&!u)return l&&En(n,t,!1),_r(e,n,a);r=n.stateNode,ns.current=n;var o=u&&"function"!=typeof t.getDerivedStateFromError?null:r.render();return n.flags|=1,null!==e&&u?(n.child=Mi(n,e.child,null,a),n.child=Mi(n,null,o,a)):cr(e,n,o,a),n.memoizedState=r.state,l&&En(n,t,!0),n.child}function br(e){var n=e.stateNode;n.pendingContext?wn(0,n.pendingContext,n.pendingContext!==n.context):n.context&&wn(0,n.context,!1),dt(e,n.containerInfo)}function kr(e,n,t,r,l){return In(),Un(l),n.flags|=256,cr(e,n,t,r),n.child}function wr(e){return{baseLanes:e,cachePool:null,transitions:null}}function Sr(e,n,r){var l,a=n.pendingProps,u=Ui.current,o=!1,i=0!=(128&n.flags);if((l=i)||(l=(null===e||null!==e.memoizedState)&&0!=(2&u)),l?(o=!0,n.flags&=-129):null!==e&&null===e.memoizedState||(u|=1),yn(Ui,1&u),null===e)return Rn(n),null!==(e=n.memoizedState)&&null!==(e=e.dehydrated)?(0==(1&n.mode)?n.lanes=1:"$!"===e.data?n.lanes=8:n.lanes=1073741824,null):(i=a.children,e=a.fallback,o?(a=n.mode,o=n.child,i={mode:"hidden",children:i},0==(1&a)&&null!==o?(o.childLanes=0,o.pendingProps=i):o=Ol(i,a,0,null),e=Dl(e,a,r,null),o.return=n,e.return=n,o.sibling=e,n.child=o,n.child.memoizedState=wr(r),n.memoizedState=rs,e):xr(n,i));if(null!==(u=e.memoizedState)&&null!==(l=u.dehydrated))return function(e,n,r,l,a,u,o){if(r)return 256&n.flags?(n.flags&=-257,Er(e,n,o,l=rr(Error(t(422))))):null!==n.memoizedState?(n.child=e.child,n.flags|=128,null):(u=l.fallback,a=n.mode,l=Ol({mode:"visible",children:l.children},a,0,null),(u=Dl(u,a,o,null)).flags|=2,l.return=n,u.return=n,l.sibling=u,n.child=l,0!=(1&n.mode)&&Mi(n,e.child,null,o),n.child.memoizedState=wr(o),n.memoizedState=rs,u);if(0==(1&n.mode))return Er(e,n,o,null);if("$!"===a.data){if(l=a.nextSibling&&a.nextSibling.dataset)var i=l.dgst;return l=i,Er(e,n,o,l=rr(u=Error(t(419)),l,void 0))}if(i=0!=(o&e.childLanes),ts||i){if(null!==(l=ks)){switch(o&-o){case 4:a=2;break;case 16:a=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:a=32;break;case 536870912:a=268435456;break;default:a=0}0!==(a=0!=(a&(l.suspendedLanes|o))?0:a)&&a!==u.retryLane&&(u.retryLane=a,qn(e,a),ll(l,e,a,-1))}return gl(),Er(e,n,o,l=rr(Error(t(421))))}return"$?"===a.data?(n.flags|=128,n.child=e.child,n=Pl.bind(null,e),a._reactRetry=n,null):(e=u.treeContext,bi=cn(a.nextSibling),yi=n,ki=!0,wi=null,null!==e&&(pi[mi++]=gi,pi[mi++]=vi,pi[mi++]=hi,gi=e.id,vi=e.overflow,hi=n),(n=xr(n,l.children)).flags|=4096,n)}(e,n,i,a,l,u,r);if(o){o=a.fallback,i=n.mode,l=(u=e.child).sibling;var s={mode:"hidden",children:a.children};return 0==(1&i)&&n.child!==u?((a=n.child).childLanes=0,a.pendingProps=s,n.deletions=null):(a=Fl(u,s)).subtreeFlags=14680064&u.subtreeFlags,null!==l?o=Fl(l,o):(o=Dl(o,i,r,null)).flags|=2,o.return=n,a.return=n,a.sibling=o,n.child=a,a=o,o=n.child,i=null===(i=e.child.memoizedState)?wr(r):{baseLanes:i.baseLanes|r,cachePool:null,transitions:i.transitions},o.memoizedState=i,o.childLanes=e.childLanes&~r,n.memoizedState=rs,a}return e=(o=e.child).sibling,a=Fl(o,{mode:"visible",children:a.children}),0==(1&n.mode)&&(a.lanes=r),a.return=n,a.sibling=null,null!==e&&(null===(r=n.deletions)?(n.deletions=[e],n.flags|=16):r.push(e)),n.child=a,n.memoizedState=null,a}function xr(e,n,t){return(n=Ol({mode:"visible",children:n},e.mode,0,null)).return=e,e.child=n}function Er(e,n,t,r){return null!==r&&Un(r),Mi(n,e.child,null,t),(e=xr(n,n.pendingProps.children)).flags|=2,n.memoizedState=null,e}function Cr(e,n,t){e.lanes|=n;var r=e.alternate;null!==r&&(r.lanes|=n),Wn(e.return,n,t)}function zr(e,n,t,r,l){var a=e.memoizedState;null===a?e.memoizedState={isBackwards:n,rendering:null,renderingStartTime:0,last:r,tail:t,tailMode:l}:(a.isBackwards=n,a.rendering=null,a.renderingStartTime=0,a.last=r,a.tail=t,a.tailMode=l)}function Nr(e,n,t){var r=n.pendingProps,l=r.revealOrder,a=r.tail;if(cr(e,n,r.children,t),0!=(2&(r=Ui.current)))r=1&r|2,n.flags|=128;else{if(null!==e&&0!=(128&e.flags))e:for(e=n.child;null!==e;){if(13===e.tag)null!==e.memoizedState&&Cr(e,t,n);else if(19===e.tag)Cr(e,t,n);else if(null!==e.child){e.child.return=e,e=e.child;continue}if(e===n)break e;for(;null===e.sibling;){if(null===e.return||e.return===n)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}r&=1}if(yn(Ui,r),0==(1&n.mode))n.memoizedState=null;else switch(l){case"forwards":for(t=n.child,l=null;null!==t;)null!==(e=t.alternate)&&null===gt(e)&&(l=t),t=t.sibling;null===(t=l)?(l=n.child,n.child=null):(l=t.sibling,t.sibling=null),zr(n,!1,l,t,a);break;case"backwards":for(t=null,l=n.child,n.child=null;null!==l;){if(null!==(e=l.alternate)&&null===gt(e)){n.child=l;break}e=l.sibling,l.sibling=t,t=l,l=e}zr(n,!0,t,null,a);break;case"together":zr(n,!1,null,null,void 0);break;default:n.memoizedState=null}return n.child}function Pr(e,n){0==(1&n.mode)&&null!==e&&(e.alternate=null,n.alternate=null,n.flags|=2)}function _r(e,n,r){if(null!==e&&(n.dependencies=e.dependencies),Ns|=n.lanes,0==(r&n.childLanes))return null;if(null!==e&&n.child!==e.child)throw Error(t(153));if(null!==n.child){for(r=Fl(e=n.child,e.pendingProps),n.child=r,r.return=n;null!==e.sibling;)e=e.sibling,(r=r.sibling=Fl(e,e.pendingProps)).return=n;r.sibling=null}return n.child}function Lr(e,n){if(!ki)switch(e.tailMode){case"hidden":n=e.tail;for(var t=null;null!==n;)null!==n.alternate&&(t=n),n=n.sibling;null===t?e.tail=null:t.sibling=null;break;case"collapsed":t=e.tail;for(var r=null;null!==t;)null!==t.alternate&&(r=t),t=t.sibling;null===r?n||null===e.tail?e.tail=null:e.tail.sibling=null:r.sibling=null}}function Tr(e){var n=null!==e.alternate&&e.alternate.child===e.child,t=0,r=0;if(n)for(var l=e.child;null!==l;)t|=l.lanes|l.childLanes,r|=14680064&l.subtreeFlags,r|=14680064&l.flags,l.return=e,l=l.sibling;else for(l=e.child;null!==l;)t|=l.lanes|l.childLanes,r|=l.subtreeFlags,r|=l.flags,l.return=e,l=l.sibling;return e.subtreeFlags|=r,e.childLanes=t,n}function Mr(e,n,r){var l=n.pendingProps;switch(Ln(n),n.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Tr(n),null;case 1:case 17:return kn(n.type)&&(vn(li),vn(ri)),Tr(n),null;case 3:return l=n.stateNode,pt(),vn(li),vn(ri),vt(),l.pendingContext&&(l.context=l.pendingContext,l.pendingContext=null),null!==e&&null!==e.child||(On(n)?n.flags|=4:null===e||e.memoizedState.isDehydrated&&0==(256&n.flags)||(n.flags|=1024,null!==wi&&(il(wi),wi=null))),as(e,n),Tr(n),null;case 5:ht(n);var a=ft(Ii.current);if(r=n.type,null!==e&&null!=n.stateNode)us(e,n,r,l,a),e.ref!==n.ref&&(n.flags|=512,n.flags|=2097152);else{if(!l){if(null===n.stateNode)throw Error(t(166));return Tr(n),null}if(e=ft(Di.current),On(n)){l=n.stateNode,r=n.type;var o=n.memoizedProps;switch(l[Ko]=n,l[Yo]=o,e=0!=(1&n.mode),r){case"dialog":Ke("cancel",l),Ke("close",l);break;case"iframe":case"object":case"embed":Ke("load",l);break;case"video":case"audio":for(a=0;a<Oo.length;a++)Ke(Oo[a],l);break;case"source":Ke("error",l);break;case"img":case"image":case"link":Ke("error",l),Ke("load",l);break;case"details":Ke("toggle",l);break;case"input":b(l,o),Ke("invalid",l);break;case"select":l._wrapperState={wasMultiple:!!o.multiple},Ke("invalid",l);break;case"textarea":z(l,o),Ke("invalid",l)}for(var i in F(r,o),a=null,o)if(o.hasOwnProperty(i)){var s=o[i];"children"===i?"string"==typeof s?l.textContent!==s&&(!0!==o.suppressHydrationWarning&&ln(l.textContent,s,e),a=["children",s]):"number"==typeof s&&l.textContent!==""+s&&(!0!==o.suppressHydrationWarning&&ln(l.textContent,s,e),a=["children",""+s]):ra.hasOwnProperty(i)&&null!=s&&"onScroll"===i&&Ke("scroll",l)}switch(r){case"input":h(l),S(l,o,!0);break;case"textarea":h(l),P(l);break;case"select":case"option":break;default:"function"==typeof o.onClick&&(l.onclick=an)}l=a,n.updateQueue=l,null!==l&&(n.flags|=4)}else{i=9===a.nodeType?a:a.ownerDocument,"http://www.w3.org/1999/xhtml"===e&&(e=_(r)),"http://www.w3.org/1999/xhtml"===e?"script"===r?((e=i.createElement("div")).innerHTML="<script><\/script>",e=e.removeChild(e.firstChild)):"string"==typeof l.is?e=i.createElement(r,{is:l.is}):(e=i.createElement(r),"select"===r&&(i=e,l.multiple?i.multiple=!0:l.size&&(i.size=l.size))):e=i.createElementNS(e,r),e[Ko]=n,e[Yo]=l,ls(e,n,!1,!1),n.stateNode=e;e:{switch(i=R(r,l),r){case"dialog":Ke("cancel",e),Ke("close",e),a=l;break;case"iframe":case"object":case"embed":Ke("load",e),a=l;break;case"video":case"audio":for(a=0;a<Oo.length;a++)Ke(Oo[a],e);a=l;break;case"source":Ke("error",e),a=l;break;case"img":case"image":case"link":Ke("error",e),Ke("load",e),a=l;break;case"details":Ke("toggle",e),a=l;break;case"input":b(e,l),a=y(e,l),Ke("invalid",e);break;case"option":default:a=l;break;case"select":e._wrapperState={wasMultiple:!!l.multiple},a=La({},l,{value:void 0}),Ke("invalid",e);break;case"textarea":z(e,l),a=C(e,l),Ke("invalid",e)}for(o in F(r,a),s=a)if(s.hasOwnProperty(o)){var c=s[o];"style"===o?M(e,c):"dangerouslySetInnerHTML"===o?null!=(c=c?c.__html:void 0)&&Fa(e,c):"children"===o?"string"==typeof c?("textarea"!==r||""!==c)&&Ra(e,c):"number"==typeof c&&Ra(e,""+c):"suppressContentEditableWarning"!==o&&"suppressHydrationWarning"!==o&&"autoFocus"!==o&&(ra.hasOwnProperty(o)?null!=c&&"onScroll"===o&&Ke("scroll",e):null!=c&&u(e,o,c,i))}switch(r){case"input":h(e),S(e,l,!1);break;case"textarea":h(e),P(e);break;case"option":null!=l.value&&e.setAttribute("value",""+p(l.value));break;case"select":e.multiple=!!l.multiple,null!=(o=l.value)?E(e,!!l.multiple,o,!1):null!=l.defaultValue&&E(e,!!l.multiple,l.defaultValue,!0);break;default:"function"==typeof a.onClick&&(e.onclick=an)}switch(r){case"button":case"input":case"select":case"textarea":l=!!l.autoFocus;break e;case"img":l=!0;break e;default:l=!1}}l&&(n.flags|=4)}null!==n.ref&&(n.flags|=512,n.flags|=2097152)}return Tr(n),null;case 6:if(e&&null!=n.stateNode)os(e,n,e.memoizedProps,l);else{if("string"!=typeof l&&null===n.stateNode)throw Error(t(166));if(r=ft(Ii.current),ft(Di.current),On(n)){if(l=n.stateNode,r=n.memoizedProps,l[Ko]=n,(o=l.nodeValue!==r)&&null!==(e=yi))switch(e.tag){case 3:ln(l.nodeValue,r,0!=(1&e.mode));break;case 5:!0!==e.memoizedProps.suppressHydrationWarning&&ln(l.nodeValue,r,0!=(1&e.mode))}o&&(n.flags|=4)}else(l=(9===r.nodeType?r:r.ownerDocument).createTextNode(l))[Ko]=n,n.stateNode=l}return Tr(n),null;case 13:if(vn(Ui),l=n.memoizedState,null===e||null!==e.memoizedState&&null!==e.memoizedState.dehydrated){if(ki&&null!==bi&&0!=(1&n.mode)&&0==(128&n.flags)){for(o=bi;o;)o=cn(o.nextSibling);In(),n.flags|=98560,o=!1}else if(o=On(n),null!==l&&null!==l.dehydrated){if(null===e){if(!o)throw Error(t(318));if(!(o=null!==(o=n.memoizedState)?o.dehydrated:null))throw Error(t(317));o[Ko]=n}else In(),0==(128&n.flags)&&(n.memoizedState=null),n.flags|=4;Tr(n),o=!1}else null!==wi&&(il(wi),wi=null),o=!0;if(!o)return 65536&n.flags?n:null}return 0!=(128&n.flags)?(n.lanes=r,n):((l=null!==l)!=(null!==e&&null!==e.memoizedState)&&l&&(n.child.flags|=8192,0!=(1&n.mode)&&(null===e||0!=(1&Ui.current)?0===Cs&&(Cs=3):gl())),null!==n.updateQueue&&(n.flags|=4),Tr(n),null);case 4:return pt(),as(e,n),null===e&&Xe(n.stateNode.containerInfo),Tr(n),null;case 10:return Bn(n.type._context),Tr(n),null;case 19:if(vn(Ui),null===(o=n.memoizedState))return Tr(n),null;if(l=0!=(128&n.flags),null===(i=o.rendering))if(l)Lr(o,!1);else{if(0!==Cs||null!==e&&0!=(128&e.flags))for(e=n.child;null!==e;){if(null!==(i=gt(e))){for(n.flags|=128,Lr(o,!1),null!==(l=i.updateQueue)&&(n.updateQueue=l,n.flags|=4),n.subtreeFlags=0,l=r,r=n.child;null!==r;)e=l,(o=r).flags&=14680066,null===(i=o.alternate)?(o.childLanes=0,o.lanes=e,o.child=null,o.subtreeFlags=0,o.memoizedProps=null,o.memoizedState=null,o.updateQueue=null,o.dependencies=null,o.stateNode=null):(o.childLanes=i.childLanes,o.lanes=i.lanes,o.child=i.child,o.subtreeFlags=0,o.deletions=null,o.memoizedProps=i.memoizedProps,o.memoizedState=i.memoizedState,o.updateQueue=i.updateQueue,o.type=i.type,e=i.dependencies,o.dependencies=null===e?null:{lanes:e.lanes,firstContext:e.firstContext}),r=r.sibling;return yn(Ui,1&Ui.current|2),n.child}e=e.sibling}null!==o.tail&&su()>Fs&&(n.flags|=128,l=!0,Lr(o,!1),n.lanes=4194304)}else{if(!l)if(null!==(e=gt(i))){if(n.flags|=128,l=!0,null!==(r=e.updateQueue)&&(n.updateQueue=r,n.flags|=4),Lr(o,!0),null===o.tail&&"hidden"===o.tailMode&&!i.alternate&&!ki)return Tr(n),null}else 2*su()-o.renderingStartTime>Fs&&1073741824!==r&&(n.flags|=128,l=!0,Lr(o,!1),n.lanes=4194304);o.isBackwards?(i.sibling=n.child,n.child=i):(null!==(r=o.last)?r.sibling=i:n.child=i,o.last=i)}return null!==o.tail?(n=o.tail,o.rendering=n,o.tail=n.sibling,o.renderingStartTime=su(),n.sibling=null,r=Ui.current,yn(Ui,l?1&r|2:1&r),n):(Tr(n),null);case 22:case 23:return xs=Es.current,vn(Es),l=null!==n.memoizedState,null!==e&&null!==e.memoizedState!==l&&(n.flags|=8192),l&&0!=(1&n.mode)?0!=(1073741824&xs)&&(Tr(n),6&n.subtreeFlags&&(n.flags|=8192)):Tr(n),null;case 24:case 25:return null}throw Error(t(156,n.tag))}function Fr(e,n,r){switch(Ln(n),n.tag){case 1:return kn(n.type)&&(vn(li),vn(ri)),65536&(e=n.flags)?(n.flags=-65537&e|128,n):null;case 3:return pt(),vn(li),vn(ri),vt(),0!=(65536&(e=n.flags))&&0==(128&e)?(n.flags=-65537&e|128,n):null;case 5:return ht(n),null;case 13:if(vn(Ui),null!==(e=n.memoizedState)&&null!==e.dehydrated){if(null===n.alternate)throw Error(t(340));In()}return 65536&(e=n.flags)?(n.flags=-65537&e|128,n):null;case 19:return vn(Ui),null;case 4:return pt(),null;case 10:return Bn(n.type._context),null;case 22:case 23:return xs=Es.current,vn(Es),null;default:return null}}function Rr(e,n){var t=e.ref;if(null!==t)if("function"==typeof t)try{t(null)}catch(t){Cl(e,n,t)}else t.current=null}function Dr(e,n,t){try{t()}catch(t){Cl(e,n,t)}}function Or(e,n,t){var r=n.updateQueue;if(null!==(r=null!==r?r.lastEffect:null)){var l=r=r.next;do{if((l.tag&e)===e){var a=l.destroy;l.destroy=void 0,void 0!==a&&Dr(n,t,a)}l=l.next}while(l!==r)}}function Ir(e,n){if(null!==(n=null!==(n=n.updateQueue)?n.lastEffect:null)){var t=n=n.next;do{if((t.tag&e)===e){var r=t.create;t.destroy=r()}t=t.next}while(t!==n)}}function Ur(e){var n=e.ref;if(null!==n){var t=e.stateNode;e.tag,e=t,"function"==typeof n?n(e):n.current=e}}function Vr(e){var n=e.alternate;null!==n&&(e.alternate=null,Vr(n)),e.child=null,e.deletions=null,e.sibling=null,5===e.tag&&null!==(n=e.stateNode)&&(delete n[Ko],delete n[Yo],delete n[Go],delete n[Zo],delete n[Jo]),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Ar(e){return 5===e.tag||3===e.tag||4===e.tag}function Br(e){e:for(;;){for(;null===e.sibling;){if(null===e.return||Ar(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;5!==e.tag&&6!==e.tag&&18!==e.tag;){if(2&e.flags)continue e;if(null===e.child||4===e.tag)continue e;e.child.return=e,e=e.child}if(!(2&e.flags))return e.stateNode}}function Wr(e,n,t){var r=e.tag;if(5===r||6===r)e=e.stateNode,n?8===t.nodeType?t.parentNode.insertBefore(e,n):t.insertBefore(e,n):(8===t.nodeType?(n=t.parentNode).insertBefore(e,t):(n=t).appendChild(e),null!=(t=t._reactRootContainer)||null!==n.onclick||(n.onclick=an));else if(4!==r&&null!==(e=e.child))for(Wr(e,n,t),e=e.sibling;null!==e;)Wr(e,n,t),e=e.sibling}function Hr(e,n,t){var r=e.tag;if(5===r||6===r)e=e.stateNode,n?t.insertBefore(e,n):t.appendChild(e);else if(4!==r&&null!==(e=e.child))for(Hr(e,n,t),e=e.sibling;null!==e;)Hr(e,n,t),e=e.sibling}function Qr(e,n,t){for(t=t.child;null!==t;)jr(e,n,t),t=t.sibling}function jr(e,n,t){if(vu&&"function"==typeof vu.onCommitFiberUnmount)try{vu.onCommitFiberUnmount(gu,t)}catch(e){}switch(t.tag){case 5:ss||Rr(t,n);case 6:var r=ps,l=ms;ps=null,Qr(e,n,t),ms=l,null!==(ps=r)&&(ms?(e=ps,t=t.stateNode,8===e.nodeType?e.parentNode.removeChild(t):e.removeChild(t)):ps.removeChild(t.stateNode));break;case 18:null!==ps&&(ms?(e=ps,t=t.stateNode,8===e.nodeType?sn(e.parentNode,t):1===e.nodeType&&sn(e,t),se(e)):sn(ps,t.stateNode));break;case 4:r=ps,l=ms,ps=t.stateNode.containerInfo,ms=!0,Qr(e,n,t),ps=r,ms=l;break;case 0:case 11:case 14:case 15:if(!ss&&null!==(r=t.updateQueue)&&null!==(r=r.lastEffect)){l=r=r.next;do{var a=l,u=a.destroy;a=a.tag,void 0!==u&&(0!=(2&a)||0!=(4&a))&&Dr(t,n,u),l=l.next}while(l!==r)}Qr(e,n,t);break;case 1:if(!ss&&(Rr(t,n),"function"==typeof(r=t.stateNode).componentWillUnmount))try{r.props=t.memoizedProps,r.state=t.memoizedState,r.componentWillUnmount()}catch(e){Cl(t,n,e)}Qr(e,n,t);break;case 21:Qr(e,n,t);break;case 22:1&t.mode?(ss=(r=ss)||null!==t.memoizedState,Qr(e,n,t),ss=r):Qr(e,n,t);break;default:Qr(e,n,t)}}function $r(e){var n=e.updateQueue;if(null!==n){e.updateQueue=null;var t=e.stateNode;null===t&&(t=e.stateNode=new cs),n.forEach((function(n){var r=_l.bind(null,e,n);t.has(n)||(t.add(n),n.then(r,r))}))}}function qr(e,n,r){if(null!==(r=n.deletions))for(var l=0;l<r.length;l++){var a=r[l];try{var u=e,o=n,i=o;e:for(;null!==i;){switch(i.tag){case 5:ps=i.stateNode,ms=!1;break e;case 3:case 4:ps=i.stateNode.containerInfo,ms=!0;break e}i=i.return}if(null===ps)throw Error(t(160));jr(u,o,a),ps=null,ms=!1;var s=a.alternate;null!==s&&(s.return=null),a.return=null}catch(e){Cl(a,n,e)}}if(12854&n.subtreeFlags)for(n=n.child;null!==n;)Kr(n,e),n=n.sibling}function Kr(e,n,r){var l=e.alternate;switch(r=e.flags,e.tag){case 0:case 11:case 14:case 15:if(qr(n,e),Yr(e),4&r){try{Or(3,e,e.return),Ir(3,e)}catch(n){Cl(e,e.return,n)}try{Or(5,e,e.return)}catch(n){Cl(e,e.return,n)}}break;case 1:qr(n,e),Yr(e),512&r&&null!==l&&Rr(l,l.return);break;case 5:if(qr(n,e),Yr(e),512&r&&null!==l&&Rr(l,l.return),32&e.flags){var a=e.stateNode;try{Ra(a,"")}catch(n){Cl(e,e.return,n)}}if(4&r&&null!=(a=e.stateNode)){var o=e.memoizedProps,i=null!==l?l.memoizedProps:o,s=e.type,c=e.updateQueue;if(e.updateQueue=null,null!==c)try{"input"===s&&"radio"===o.type&&null!=o.name&&k(a,o),R(s,i);var f=R(s,o);for(i=0;i<c.length;i+=2){var d=c[i],p=c[i+1];"style"===d?M(a,p):"dangerouslySetInnerHTML"===d?Fa(a,p):"children"===d?Ra(a,p):u(a,d,p,f)}switch(s){case"input":w(a,o);break;case"textarea":N(a,o);break;case"select":var m=a._wrapperState.wasMultiple;a._wrapperState.wasMultiple=!!o.multiple;var h=o.value;null!=h?E(a,!!o.multiple,h,!1):m!==!!o.multiple&&(null!=o.defaultValue?E(a,!!o.multiple,o.defaultValue,!0):E(a,!!o.multiple,o.multiple?[]:"",!1))}a[Yo]=o}catch(n){Cl(e,e.return,n)}}break;case 6:if(qr(n,e),Yr(e),4&r){if(null===e.stateNode)throw Error(t(162));a=e.stateNode,o=e.memoizedProps;try{a.nodeValue=o}catch(n){Cl(e,e.return,n)}}break;case 3:if(qr(n,e),Yr(e),4&r&&null!==l&&l.memoizedState.isDehydrated)try{se(n.containerInfo)}catch(n){Cl(e,e.return,n)}break;case 4:default:qr(n,e),Yr(e);break;case 13:qr(n,e),Yr(e),8192&(a=e.child).flags&&(o=null!==a.memoizedState,a.stateNode.isHidden=o,!o||null!==a.alternate&&null!==a.alternate.memoizedState||(Ms=su())),4&r&&$r(e);break;case 22:if(d=null!==l&&null!==l.memoizedState,1&e.mode?(ss=(f=ss)||d,qr(n,e),ss=f):qr(n,e),Yr(e),8192&r){if(f=null!==e.memoizedState,(e.stateNode.isHidden=f)&&!d&&0!=(1&e.mode))for(fs=e,d=e.child;null!==d;){for(p=fs=d;null!==fs;){switch(h=(m=fs).child,m.tag){case 0:case 11:case 14:case 15:Or(4,m,m.return);break;case 1:Rr(m,m.return);var g=m.stateNode;if("function"==typeof g.componentWillUnmount){r=m,n=m.return;try{l=r,g.props=l.memoizedProps,g.state=l.memoizedState,g.componentWillUnmount()}catch(e){Cl(r,n,e)}}break;case 5:Rr(m,m.return);break;case 22:if(null!==m.memoizedState){Jr(p);continue}}null!==h?(h.return=m,fs=h):Jr(p)}d=d.sibling}e:for(d=null,p=e;;){if(5===p.tag){if(null===d){d=p;try{a=p.stateNode,f?"function"==typeof(o=a.style).setProperty?o.setProperty("display","none","important"):o.display="none":(s=p.stateNode,i=null!=(c=p.memoizedProps.style)&&c.hasOwnProperty("display")?c.display:null,s.style.display=T("display",i))}catch(n){Cl(e,e.return,n)}}}else if(6===p.tag){if(null===d)try{p.stateNode.nodeValue=f?"":p.memoizedProps}catch(n){Cl(e,e.return,n)}}else if((22!==p.tag&&23!==p.tag||null===p.memoizedState||p===e)&&null!==p.child){p.child.return=p,p=p.child;continue}if(p===e)break e;for(;null===p.sibling;){if(null===p.return||p.return===e)break e;d===p&&(d=null),p=p.return}d===p&&(d=null),p.sibling.return=p.return,p=p.sibling}}break;case 19:qr(n,e),Yr(e),4&r&&$r(e);case 21:}}function Yr(e){var n=e.flags;if(2&n){try{e:{for(var r=e.return;null!==r;){if(Ar(r)){var l=r;break e}r=r.return}throw Error(t(160))}switch(l.tag){case 5:var a=l.stateNode;32&l.flags&&(Ra(a,""),l.flags&=-33),Hr(e,Br(e),a);break;case 3:case 4:var u=l.stateNode.containerInfo;Wr(e,Br(e),u);break;default:throw Error(t(161))}}catch(n){Cl(e,e.return,n)}e.flags&=-3}4096&n&&(e.flags&=-4097)}function Xr(e,n,t){fs=e,Gr(e,n,t)}function Gr(e,n,t){for(var r=0!=(1&e.mode);null!==fs;){var l=fs,a=l.child;if(22===l.tag&&r){var u=null!==l.memoizedState||is;if(!u){var o=l.alternate,i=null!==o&&null!==o.memoizedState||ss;o=is;var s=ss;if(is=u,(ss=i)&&!s)for(fs=l;null!==fs;)i=(u=fs).child,22===u.tag&&null!==u.memoizedState?el(l):null!==i?(i.return=u,fs=i):el(l);for(;null!==a;)fs=a,Gr(a,n,t),a=a.sibling;fs=l,is=o,ss=s}Zr(e,n,t)}else 0!=(8772&l.subtreeFlags)&&null!==a?(a.return=l,fs=a):Zr(e,n,t)}}function Zr(e,n,r){for(;null!==fs;){if(0!=(8772&(n=fs).flags)){r=n.alternate;try{if(0!=(8772&n.flags))switch(n.tag){case 0:case 11:case 15:ss||Ir(5,n);break;case 1:var l=n.stateNode;if(4&n.flags&&!ss)if(null===r)l.componentDidMount();else{var a=n.elementType===n.type?r.memoizedProps:Vn(n.type,r.memoizedProps);l.componentDidUpdate(a,r.memoizedState,l.__reactInternalSnapshotBeforeUpdate)}var u=n.updateQueue;null!==u&&nt(n,u,l);break;case 3:var o=n.updateQueue;if(null!==o){if(r=null,null!==n.child)switch(n.child.tag){case 5:case 1:r=n.child.stateNode}nt(n,o,r)}break;case 5:var i=n.stateNode;if(null===r&&4&n.flags){r=i;var s=n.memoizedProps;switch(n.type){case"button":case"input":case"select":case"textarea":s.autoFocus&&r.focus();break;case"img":s.src&&(r.src=s.src)}}break;case 6:case 4:case 12:case 19:case 17:case 21:case 22:case 23:case 25:break;case 13:if(null===n.memoizedState){var c=n.alternate;if(null!==c){var f=c.memoizedState;if(null!==f){var d=f.dehydrated;null!==d&&se(d)}}}break;default:throw Error(t(163))}ss||512&n.flags&&Ur(n)}catch(e){Cl(n,n.return,e)}}if(n===e){fs=null;break}if(null!==(r=n.sibling)){r.return=n.return,fs=r;break}fs=n.return}}function Jr(e){for(;null!==fs;){var n=fs;if(n===e){fs=null;break}var t=n.sibling;if(null!==t){t.return=n.return,fs=t;break}fs=n.return}}function el(e){for(;null!==fs;){var n=fs;try{switch(n.tag){case 0:case 11:case 15:var t=n.return;try{Ir(4,n)}catch(e){Cl(n,t,e)}break;case 1:var r=n.stateNode;if("function"==typeof r.componentDidMount){var l=n.return;try{r.componentDidMount()}catch(e){Cl(n,l,e)}}var a=n.return;try{Ur(n)}catch(e){Cl(n,a,e)}break;case 5:var u=n.return;try{Ur(n)}catch(e){Cl(n,u,e)}}}catch(e){Cl(n,n.return,e)}if(n===e){fs=null;break}var o=n.sibling;if(null!==o){o.return=n.return,fs=o;break}fs=n.return}}function nl(){Fs=su()+500}function tl(){return 0!=(6&bs)?su():-1!==Hs?Hs:Hs=su()}function rl(e){return 0==(1&e.mode)?1:0!=(2&bs)&&0!==Ss?Ss&-Ss:null!==Si.transition?(0===Qs&&(Qs=G()),Qs):0!==(e=xu)?e:e=void 0===(e=window.event)?16:me(e.type)}function ll(e,n,r,l){if(50<Bs)throw Bs=0,Ws=null,Error(t(185));J(e,r,l),0!=(2&bs)&&e===ks||(e===ks&&(0==(2&bs)&&(Ps|=r),4===Cs&&sl(e,Ss)),al(e,l),1===r&&0===bs&&0==(1&n.mode)&&(nl(),oi&&zn()))}function al(e,n){var t=e.callbackNode;!function(e,n){for(var t=e.suspendedLanes,r=e.pingedLanes,l=e.expirationTimes,a=e.pendingLanes;0<a;){var u=31-yu(a),o=1<<u,i=l[u];-1===i?0!=(o&t)&&0==(o&r)||(l[u]=Y(o,n)):i<=n&&(e.expiredLanes|=o),a&=~o}}(e,n);var r=K(e,e===ks?Ss:0);if(0===r)null!==t&&uu(t),e.callbackNode=null,e.callbackPriority=0;else if(n=r&-r,e.callbackPriority!==n){if(null!=t&&uu(t),1===n)0===e.tag?function(e){oi=!0,Cn(e)}(cl.bind(null,e)):Cn(cl.bind(null,e)),$o((function(){0==(6&bs)&&zn()})),t=null;else{switch(ne(r)){case 1:t=fu;break;case 4:t=du;break;case 16:default:t=pu;break;case 536870912:t=hu}t=Ll(t,ul.bind(null,e))}e.callbackPriority=n,e.callbackNode=t}}function ul(e,n){if(Hs=-1,Qs=0,0!=(6&bs))throw Error(t(327));var r=e.callbackNode;if(xl()&&e.callbackNode!==r)return null;var l=K(e,e===ks?Ss:0);if(0===l)return null;if(0!=(30&l)||0!=(l&e.expiredLanes)||n)n=vl(e,l);else{n=l;var a=bs;bs|=2;var u=hl();for(ks===e&&Ss===n||(Rs=null,nl(),pl(e,n));;)try{bl();break}catch(n){ml(e,n)}An(),gs.current=u,bs=a,null!==ws?n=0:(ks=null,Ss=0,n=Cs)}if(0!==n){if(2===n&&0!==(a=X(e))&&(l=a,n=ol(e,a)),1===n)throw r=zs,pl(e,0),sl(e,l),al(e,su()),r;if(6===n)sl(e,l);else{if(a=e.current.alternate,0==(30&l)&&!function(e){for(var n=e;;){if(16384&n.flags){var t=n.updateQueue;if(null!==t&&null!==(t=t.stores))for(var r=0;r<t.length;r++){var l=t[r],a=l.getSnapshot;l=l.value;try{if(!wo(a(),l))return!1}catch(e){return!1}}}if(t=n.child,16384&n.subtreeFlags&&null!==t)t.return=n,n=t;else{if(n===e)break;for(;null===n.sibling;){if(null===n.return||n.return===e)return!0;n=n.return}n.sibling.return=n.return,n=n.sibling}}return!0}(a)&&(2===(n=vl(e,l))&&0!==(u=X(e))&&(l=u,n=ol(e,u)),1===n))throw r=zs,pl(e,0),sl(e,l),al(e,su()),r;switch(e.finishedWork=a,e.finishedLanes=l,n){case 0:case 1:throw Error(t(345));case 2:case 5:Sl(e,Ts,Rs);break;case 3:if(sl(e,l),(130023424&l)===l&&10<(n=Ms+500-su())){if(0!==K(e,0))break;if(((a=e.suspendedLanes)&l)!==l){tl(),e.pingedLanes|=e.suspendedLanes&a;break}e.timeoutHandle=Ho(Sl.bind(null,e,Ts,Rs),n);break}Sl(e,Ts,Rs);break;case 4:if(sl(e,l),(4194240&l)===l)break;for(n=e.eventTimes,a=-1;0<l;){var o=31-yu(l);u=1<<o,(o=n[o])>a&&(a=o),l&=~u}if(l=a,10<(l=(120>(l=su()-l)?120:480>l?480:1080>l?1080:1920>l?1920:3e3>l?3e3:4320>l?4320:1960*hs(l/1960))-l)){e.timeoutHandle=Ho(Sl.bind(null,e,Ts,Rs),l);break}Sl(e,Ts,Rs);break;default:throw Error(t(329))}}}return al(e,su()),e.callbackNode===r?ul.bind(null,e):null}function ol(e,n){var t=Ls;return e.current.memoizedState.isDehydrated&&(pl(e,n).flags|=256),2!==(e=vl(e,n))&&(n=Ts,Ts=t,null!==n&&il(n)),e}function il(e){null===Ts?Ts=e:Ts.push.apply(Ts,e)}function sl(e,n){for(n&=~_s,n&=~Ps,e.suspendedLanes|=n,e.pingedLanes&=~n,e=e.expirationTimes;0<n;){var t=31-yu(n),r=1<<t;e[t]=-1,n&=~r}}function cl(e){if(0!=(6&bs))throw Error(t(327));xl();var n=K(e,0);if(0==(1&n))return al(e,su()),null;var r=vl(e,n);if(0!==e.tag&&2===r){var l=X(e);0!==l&&(n=l,r=ol(e,l))}if(1===r)throw r=zs,pl(e,0),sl(e,n),al(e,su()),r;if(6===r)throw Error(t(345));return e.finishedWork=e.current.alternate,e.finishedLanes=n,Sl(e,Ts,Rs),al(e,su()),null}function fl(e,n){var t=bs;bs|=1;try{return e(n)}finally{0===(bs=t)&&(nl(),oi&&zn())}}function dl(e){null!==Vs&&0===Vs.tag&&0==(6&bs)&&xl();var n=bs;bs|=1;var t=ys.transition,r=xu;try{if(ys.transition=null,xu=1,e)return e()}finally{xu=r,ys.transition=t,0==(6&(bs=n))&&zn()}}function pl(e,n){e.finishedWork=null,e.finishedLanes=0;var t=e.timeoutHandle;if(-1!==t&&(e.timeoutHandle=-1,Qo(t)),null!==ws)for(t=ws.return;null!==t;){var r=t;switch(Ln(r),r.tag){case 1:null!=(r=r.type.childContextTypes)&&(vn(li),vn(ri));break;case 3:pt(),vn(li),vn(ri),vt();break;case 5:ht(r);break;case 4:pt();break;case 13:case 19:vn(Ui);break;case 10:Bn(r.type._context);break;case 22:case 23:xs=Es.current,vn(Es)}t=t.return}if(ks=e,ws=e=Fl(e.current,null),Ss=xs=n,Cs=0,zs=null,_s=Ps=Ns=0,Ts=Ls=null,null!==Ni){for(n=0;n<Ni.length;n++)if(null!==(r=(t=Ni[n]).interleaved)){t.interleaved=null;var l=r.next,a=t.pending;if(null!==a){var u=a.next;a.next=l,r.next=u}t.pending=r}Ni=null}return e}function ml(e,n){for(;;){var r=ws;try{if(An(),Ai.current=Xi,$i){for(var l=Hi.memoizedState;null!==l;){var a=l.queue;null!==a&&(a.pending=null),l=l.next}$i=!1}if(Wi=0,ji=Qi=Hi=null,qi=!1,Ki=0,vs.current=null,null===r||null===r.return){Cs=1,zs=n,ws=null;break}e:{var u=e,o=r.return,i=r,s=n;if(n=Ss,i.flags|=32768,null!==s&&"object"==typeof s&&"function"==typeof s.then){var c=s,f=i,d=f.tag;if(0==(1&f.mode)&&(0===d||11===d||15===d)){var p=f.alternate;p?(f.updateQueue=p.updateQueue,f.memoizedState=p.memoizedState,f.lanes=p.lanes):(f.updateQueue=null,f.memoizedState=null)}var m=ir(o);if(null!==m){m.flags&=-257,sr(m,o,i,0,n),1&m.mode&&or(u,c,n),s=c;var h=(n=m).updateQueue;if(null===h){var g=new Set;g.add(s),n.updateQueue=g}else h.add(s);break e}if(0==(1&n)){or(u,c,n),gl();break e}s=Error(t(426))}else if(ki&&1&i.mode){var v=ir(o);if(null!==v){0==(65536&v.flags)&&(v.flags|=256),sr(v,o,i,0,n),Un(tr(s,i));break e}}u=s=tr(s,i),4!==Cs&&(Cs=2),null===Ls?Ls=[u]:Ls.push(u),u=o;do{switch(u.tag){case 3:u.flags|=65536,n&=-n,u.lanes|=n,Jn(u,ar(0,s,n));break e;case 1:i=s;var y=u.type,b=u.stateNode;if(0==(128&u.flags)&&("function"==typeof y.getDerivedStateFromError||null!==b&&"function"==typeof b.componentDidCatch&&(null===Is||!Is.has(b)))){u.flags|=65536,n&=-n,u.lanes|=n,Jn(u,ur(u,i,n));break e}}u=u.return}while(null!==u)}wl(r)}catch(e){n=e,ws===r&&null!==r&&(ws=r=r.return);continue}break}}function hl(){var e=gs.current;return gs.current=Xi,null===e?Xi:e}function gl(){0!==Cs&&3!==Cs&&2!==Cs||(Cs=4),null===ks||0==(268435455&Ns)&&0==(268435455&Ps)||sl(ks,Ss)}function vl(e,n){var r=bs;bs|=2;var l=hl();for(ks===e&&Ss===n||(Rs=null,pl(e,n));;)try{yl();break}catch(n){ml(e,n)}if(An(),bs=r,gs.current=l,null!==ws)throw Error(t(261));return ks=null,Ss=0,Cs}function yl(){for(;null!==ws;)kl(ws)}function bl(){for(;null!==ws&&!ou();)kl(ws)}function kl(e){var n=js(e.alternate,e,xs);e.memoizedProps=e.pendingProps,null===n?wl(e):ws=n,vs.current=null}function wl(e){var n=e;do{var t=n.alternate;if(e=n.return,0==(32768&n.flags)){if(null!==(t=Mr(t,n,xs)))return void(ws=t)}else{if(null!==(t=Fr(t,n)))return t.flags&=32767,void(ws=t);if(null===e)return Cs=6,void(ws=null);e.flags|=32768,e.subtreeFlags=0,e.deletions=null}if(null!==(n=n.sibling))return void(ws=n);ws=n=e}while(null!==n);0===Cs&&(Cs=5)}function Sl(e,n,r){var l=xu,a=ys.transition;try{ys.transition=null,xu=1,function(e,n,r,l){do{xl()}while(null!==Vs);if(0!=(6&bs))throw Error(t(327));r=e.finishedWork;var a=e.finishedLanes;if(null===r)return null;if(e.finishedWork=null,e.finishedLanes=0,r===e.current)throw Error(t(177));e.callbackNode=null,e.callbackPriority=0;var u=r.lanes|r.childLanes;if(function(e,n){var t=e.pendingLanes&~n;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=n,e.mutableReadLanes&=n,e.entangledLanes&=n,n=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0<t;){var l=31-yu(t),a=1<<l;n[l]=0,r[l]=-1,e[l]=-1,t&=~a}}(e,u),e===ks&&(ws=ks=null,Ss=0),0==(2064&r.subtreeFlags)&&0==(2064&r.flags)||Us||(Us=!0,Ll(pu,(function(){return xl(),null}))),u=0!=(15990&r.flags),0!=(15990&r.subtreeFlags)||u){u=ys.transition,ys.transition=null;var o=xu;xu=1;var i=bs;bs|=4,vs.current=null,function(e,n){if(Bo=Ru,Ae(e=Ve())){if("selectionStart"in e)var r={start:e.selectionStart,end:e.selectionEnd};else e:{var l=(r=(r=e.ownerDocument)&&r.defaultView||window).getSelection&&r.getSelection();if(l&&0!==l.rangeCount){r=l.anchorNode;var a=l.anchorOffset,u=l.focusNode;l=l.focusOffset;try{r.nodeType,u.nodeType}catch(e){r=null;break e}var o=0,i=-1,s=-1,c=0,f=0,d=e,p=null;n:for(;;){for(var m;d!==r||0!==a&&3!==d.nodeType||(i=o+a),d!==u||0!==l&&3!==d.nodeType||(s=o+l),3===d.nodeType&&(o+=d.nodeValue.length),null!==(m=d.firstChild);)p=d,d=m;for(;;){if(d===e)break n;if(p===r&&++c===a&&(i=o),p===u&&++f===l&&(s=o),null!==(m=d.nextSibling))break;p=(d=p).parentNode}d=m}r=-1===i||-1===s?null:{start:i,end:s}}else r=null}r=r||{start:0,end:0}}else r=null;for(Wo={focusedElem:e,selectionRange:r},Ru=!1,fs=n;null!==fs;)if(e=(n=fs).child,0!=(1028&n.subtreeFlags)&&null!==e)e.return=n,fs=e;else for(;null!==fs;){n=fs;try{var h=n.alternate;if(0!=(1024&n.flags))switch(n.tag){case 0:case 11:case 15:case 5:case 6:case 4:case 17:break;case 1:if(null!==h){var g=h.memoizedProps,v=h.memoizedState,y=n.stateNode,b=y.getSnapshotBeforeUpdate(n.elementType===n.type?g:Vn(n.type,g),v);y.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var k=n.stateNode.containerInfo;1===k.nodeType?k.textContent="":9===k.nodeType&&k.documentElement&&k.removeChild(k.documentElement);break;default:throw Error(t(163))}}catch(e){Cl(n,n.return,e)}if(null!==(e=n.sibling)){e.return=n.return,fs=e;break}fs=n.return}h=ds,ds=!1}(e,r),Kr(r,e),Be(Wo),Ru=!!Bo,Wo=Bo=null,e.current=r,Xr(r,e,a),iu(),bs=i,xu=o,ys.transition=u}else e.current=r;if(Us&&(Us=!1,Vs=e,As=a),0===(u=e.pendingLanes)&&(Is=null),function(e,n){if(vu&&"function"==typeof vu.onCommitFiberRoot)try{vu.onCommitFiberRoot(gu,e,void 0,128==(128&e.current.flags))}catch(e){}}(r.stateNode),al(e,su()),null!==n)for(l=e.onRecoverableError,r=0;r<n.length;r++)a=n[r],l(a.value,{componentStack:a.stack,digest:a.digest});if(Ds)throw Ds=!1,e=Os,Os=null,e;0!=(1&As)&&0!==e.tag&&xl(),0!=(1&(u=e.pendingLanes))?e===Ws?Bs++:(Bs=0,Ws=e):Bs=0,zn()}(e,n,r,l)}finally{ys.transition=a,xu=l}return null}function xl(){if(null!==Vs){var e=ne(As),n=ys.transition,r=xu;try{if(ys.transition=null,xu=16>e?16:e,null===Vs)var l=!1;else{if(e=Vs,Vs=null,As=0,0!=(6&bs))throw Error(t(331));var a=bs;for(bs|=4,fs=e.current;null!==fs;){var u=fs,o=u.child;if(0!=(16&fs.flags)){var i=u.deletions;if(null!==i){for(var s=0;s<i.length;s++){var c=i[s];for(fs=c;null!==fs;){var f=fs;switch(f.tag){case 0:case 11:case 15:Or(8,f,u)}var d=f.child;if(null!==d)d.return=f,fs=d;else for(;null!==fs;){var p=(f=fs).sibling,m=f.return;if(Vr(f),f===c){fs=null;break}if(null!==p){p.return=m,fs=p;break}fs=m}}}var h=u.alternate;if(null!==h){var g=h.child;if(null!==g){h.child=null;do{var v=g.sibling;g.sibling=null,g=v}while(null!==g)}}fs=u}}if(0!=(2064&u.subtreeFlags)&&null!==o)o.return=u,fs=o;else e:for(;null!==fs;){if(0!=(2048&(u=fs).flags))switch(u.tag){case 0:case 11:case 15:Or(9,u,u.return)}var y=u.sibling;if(null!==y){y.return=u.return,fs=y;break e}fs=u.return}}var b=e.current;for(fs=b;null!==fs;){var k=(o=fs).child;if(0!=(2064&o.subtreeFlags)&&null!==k)k.return=o,fs=k;else e:for(o=b;null!==fs;){if(0!=(2048&(i=fs).flags))try{switch(i.tag){case 0:case 11:case 15:Ir(9,i)}}catch(e){Cl(i,i.return,e)}if(i===o){fs=null;break e}var w=i.sibling;if(null!==w){w.return=i.return,fs=w;break e}fs=i.return}}if(bs=a,zn(),vu&&"function"==typeof vu.onPostCommitFiberRoot)try{vu.onPostCommitFiberRoot(gu,e)}catch(e){}l=!0}return l}finally{xu=r,ys.transition=n}}return!1}function El(e,n,t){e=Gn(e,n=ar(0,n=tr(t,n),1),1),n=tl(),null!==e&&(J(e,1,n),al(e,n))}function Cl(e,n,t){if(3===e.tag)El(e,e,t);else for(;null!==n;){if(3===n.tag){El(n,e,t);break}if(1===n.tag){var r=n.stateNode;if("function"==typeof n.type.getDerivedStateFromError||"function"==typeof r.componentDidCatch&&(null===Is||!Is.has(r))){n=Gn(n,e=ur(n,e=tr(t,e),1),1),e=tl(),null!==n&&(J(n,1,e),al(n,e));break}}n=n.return}}function zl(e,n,t){var r=e.pingCache;null!==r&&r.delete(n),n=tl(),e.pingedLanes|=e.suspendedLanes&t,ks===e&&(Ss&t)===t&&(4===Cs||3===Cs&&(130023424&Ss)===Ss&&500>su()-Ms?pl(e,0):_s|=t),al(e,n)}function Nl(e,n){0===n&&(0==(1&e.mode)?n=1:(n=Su,0==(130023424&(Su<<=1))&&(Su=4194304)));var t=tl();null!==(e=qn(e,n))&&(J(e,n,t),al(e,t))}function Pl(e){var n=e.memoizedState,t=0;null!==n&&(t=n.retryLane),Nl(e,t)}function _l(e,n){var r=0;switch(e.tag){case 13:var l=e.stateNode,a=e.memoizedState;null!==a&&(r=a.retryLane);break;case 19:l=e.stateNode;break;default:throw Error(t(314))}null!==l&&l.delete(n),Nl(e,r)}function Ll(e,n){return au(e,n)}function Tl(e,n,t,r){this.tag=e,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=n,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ml(e){return!(!(e=e.prototype)||!e.isReactComponent)}function Fl(e,n){var t=e.alternate;return null===t?((t=$s(e.tag,n,e.key,e.mode)).elementType=e.elementType,t.type=e.type,t.stateNode=e.stateNode,t.alternate=e,e.alternate=t):(t.pendingProps=n,t.type=e.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=14680064&e.flags,t.childLanes=e.childLanes,t.lanes=e.lanes,t.child=e.child,t.memoizedProps=e.memoizedProps,t.memoizedState=e.memoizedState,t.updateQueue=e.updateQueue,n=e.dependencies,t.dependencies=null===n?null:{lanes:n.lanes,firstContext:n.firstContext},t.sibling=e.sibling,t.index=e.index,t.ref=e.ref,t}function Rl(e,n,r,l,a,u){var o=2;if(l=e,"function"==typeof e)Ml(e)&&(o=1);else if("string"==typeof e)o=5;else e:switch(e){case ha:return Dl(r.children,a,u,n);case ga:o=8,a|=8;break;case va:return(e=$s(12,r,n,2|a)).elementType=va,e.lanes=u,e;case wa:return(e=$s(13,r,n,a)).elementType=wa,e.lanes=u,e;case Sa:return(e=$s(19,r,n,a)).elementType=Sa,e.lanes=u,e;case Ca:return Ol(r,a,u,n);default:if("object"==typeof e&&null!==e)switch(e.$$typeof){case ya:o=10;break e;case ba:o=9;break e;case ka:o=11;break e;case xa:o=14;break e;case Ea:o=16,l=null;break e}throw Error(t(130,null==e?e:typeof e,""))}return(n=$s(o,r,n,a)).elementType=e,n.type=l,n.lanes=u,n}function Dl(e,n,t,r){return(e=$s(7,e,r,n)).lanes=t,e}function Ol(e,n,t,r){return(e=$s(22,e,r,n)).elementType=Ca,e.lanes=t,e.stateNode={isHidden:!1},e}function Il(e,n,t){return(e=$s(6,e,null,n)).lanes=t,e}function Ul(e,n,t){return(n=$s(4,null!==e.children?e.children:[],e.key,n)).lanes=t,n.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},n}function Vl(e,n,t,r,l){this.tag=n,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Z(0),this.expirationTimes=Z(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Z(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function Al(e,n,t,r,l,a,u,o,i,s){return e=new Vl(e,n,t,o,i),1===n?(n=1,!0===a&&(n|=8)):n=0,a=$s(3,null,null,n),e.current=a,a.stateNode=e,a.memoizedState={element:r,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},Kn(a),e}function Bl(e,n,t){var r=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:ma,key:null==r?null:""+r,children:e,containerInfo:n,implementation:t}}function Wl(e){if(!e)return ti;e:{if(W(e=e._reactInternals)!==e||1!==e.tag)throw Error(t(170));var n=e;do{switch(n.tag){case 3:n=n.stateNode.context;break e;case 1:if(kn(n.type)){n=n.stateNode.__reactInternalMemoizedMergedChildContext;break e}}n=n.return}while(null!==n);throw Error(t(171))}if(1===e.tag){var r=e.type;if(kn(r))return Sn(e,r,n)}return n}function Hl(e,n,t,r,l,a,u,o,i,s){return(e=Al(t,r,!0,e,0,a,0,o,i)).context=Wl(null),t=e.current,(a=Xn(r=tl(),l=rl(t))).callback=null!=n?n:null,Gn(t,a,l),e.current.lanes=l,J(e,l,r),al(e,r),e}function Ql(e,n,t,r){var l=n.current,a=tl(),u=rl(l);return t=Wl(t),null===n.context?n.context=t:n.pendingContext=t,(n=Xn(a,u)).payload={element:e},null!==(r=void 0===r?null:r)&&(n.callback=r),null!==(e=Gn(l,n,u))&&(ll(e,l,u,a),Zn(e,l,u)),u}function jl(e){return(e=e.current).child?(e.child.tag,e.child.stateNode):null}function $l(e,n){if(null!==(e=e.memoizedState)&&null!==e.dehydrated){var t=e.retryLane;e.retryLane=0!==t&&t<n?t:n}}function ql(e,n){$l(e,n),(e=e.alternate)&&$l(e,n)}function Kl(e){return null===(e=j(e))?null:e.stateNode}function Yl(e){return null}function Xl(e){this._internalRoot=e}function Gl(e){this._internalRoot=e}function Zl(e){return!(!e||1!==e.nodeType&&9!==e.nodeType&&11!==e.nodeType)}function Jl(e){return!(!e||1!==e.nodeType&&9!==e.nodeType&&11!==e.nodeType&&(8!==e.nodeType||" react-mount-point-unstable "!==e.nodeValue))}function ea(){}function na(e,n,t,r,l){var a=t._reactRootContainer;if(a){var u=a;if("function"==typeof l){var o=l;l=function(){var e=jl(u);o.call(e)}}Ql(n,u,e,l)}else u=function(e,n,t,r,l){if(l){if("function"==typeof r){var a=r;r=function(){var e=jl(u);a.call(e)}}var u=Hl(n,r,e,0,null,!1,0,"",ea);return e._reactRootContainer=u,e[Xo]=u.current,Xe(8===e.nodeType?e.parentNode:e),dl(),u}for(;l=e.lastChild;)e.removeChild(l);if("function"==typeof r){var o=r;r=function(){var e=jl(i);o.call(e)}}var i=Al(e,0,!1,null,0,!1,0,"",ea);return e._reactRootContainer=i,e[Xo]=i.current,Xe(8===e.nodeType?e.parentNode:e),dl((function(){Ql(n,i,t,r)})),i}(t,n,e,l,r);return jl(u)}var ta=new Set,ra={},la=!("undefined"==typeof window||void 0===window.document||void 0===window.document.createElement),aa=Object.prototype.hasOwnProperty,ua=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,oa={},ia={},sa={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach((function(e){sa[e]=new a(e,0,!1,e,null,!1,!1)})),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach((function(e){var n=e[0];sa[n]=new a(n,1,!1,e[1],null,!1,!1)})),["contentEditable","draggable","spellCheck","value"].forEach((function(e){sa[e]=new a(e,2,!1,e.toLowerCase(),null,!1,!1)})),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach((function(e){sa[e]=new a(e,2,!1,e,null,!1,!1)})),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach((function(e){sa[e]=new a(e,3,!1,e.toLowerCase(),null,!1,!1)})),["checked","multiple","muted","selected"].forEach((function(e){sa[e]=new a(e,3,!0,e,null,!1,!1)})),["capture","download"].forEach((function(e){sa[e]=new a(e,4,!1,e,null,!1,!1)})),["cols","rows","size","span"].forEach((function(e){sa[e]=new a(e,6,!1,e,null,!1,!1)})),["rowSpan","start"].forEach((function(e){sa[e]=new a(e,5,!1,e.toLowerCase(),null,!1,!1)}));var ca=/[\-:]([a-z])/g,fa=function(e){return e[1].toUpperCase()};"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach((function(e){var n=e.replace(ca,fa);sa[n]=new a(n,1,!1,e,null,!1,!1)})),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach((function(e){var n=e.replace(ca,fa);sa[n]=new a(n,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)})),["xml:base","xml:lang","xml:space"].forEach((function(e){var n=e.replace(ca,fa);sa[n]=new a(n,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)})),["tabIndex","crossOrigin"].forEach((function(e){sa[e]=new a(e,1,!1,e.toLowerCase(),null,!1,!1)})),sa.xlinkHref=new a("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach((function(e){sa[e]=new a(e,1,!1,e.toLowerCase(),null,!0,!0)}));var da=n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,pa=Symbol.for("react.element"),ma=Symbol.for("react.portal"),ha=Symbol.for("react.fragment"),ga=Symbol.for("react.strict_mode"),va=Symbol.for("react.profiler"),ya=Symbol.for("react.provider"),ba=Symbol.for("react.context"),ka=Symbol.for("react.forward_ref"),wa=Symbol.for("react.suspense"),Sa=Symbol.for("react.suspense_list"),xa=Symbol.for("react.memo"),Ea=Symbol.for("react.lazy");Symbol.for("react.scope"),Symbol.for("react.debug_trace_mode");var Ca=Symbol.for("react.offscreen");Symbol.for("react.legacy_hidden"),Symbol.for("react.cache"),Symbol.for("react.tracing_marker");var za,Na,Pa,_a=Symbol.iterator,La=Object.assign,Ta=!1,Ma=Array.isArray,Fa=(Pa=function(e,n){if("http://www.w3.org/2000/svg"!==e.namespaceURI||"innerHTML"in e)e.innerHTML=n;else{for((Na=Na||document.createElement("div")).innerHTML="<svg>"+n.valueOf().toString()+"</svg>",n=Na.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;n.firstChild;)e.appendChild(n.firstChild)}},"undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction?function(e,n,t,r){MSApp.execUnsafeLocalFunction((function(){return Pa(e,n)}))}:Pa),Ra=function(e,n){if(n){var t=e.firstChild;if(t&&t===e.lastChild&&3===t.nodeType)return void(t.nodeValue=n)}e.textContent=n},Da={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Oa=["Webkit","ms","Moz","O"];Object.keys(Da).forEach((function(e){Oa.forEach((function(n){n=n+e.charAt(0).toUpperCase()+e.substring(1),Da[n]=Da[e]}))}));var Ia=La({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0}),Ua=null,Va=null,Aa=null,Ba=null,Wa=function(e,n){return e(n)},Ha=function(){},Qa=!1,ja=!1;if(la)try{var $a={};Object.defineProperty($a,"passive",{get:function(){ja=!0}}),window.addEventListener("test",$a,$a),window.removeEventListener("test",$a,$a)}catch(Pa){ja=!1}var qa,Ka,Ya,Xa=function(e,n,t,r,l,a,u,o,i){var s=Array.prototype.slice.call(arguments,3);try{n.apply(t,s)}catch(e){this.onError(e)}},Ga=!1,Za=null,Ja=!1,eu=null,nu={onError:function(e){Ga=!0,Za=e}},tu=n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler,ru=tu.unstable_scheduleCallback,lu=tu.unstable_NormalPriority,au=ru,uu=tu.unstable_cancelCallback,ou=tu.unstable_shouldYield,iu=tu.unstable_requestPaint,su=tu.unstable_now,cu=tu.unstable_getCurrentPriorityLevel,fu=tu.unstable_ImmediatePriority,du=tu.unstable_UserBlockingPriority,pu=lu,mu=tu.unstable_LowPriority,hu=tu.unstable_IdlePriority,gu=null,vu=null,yu=Math.clz32?Math.clz32:function(e){return 0==(e>>>=0)?32:31-(bu(e)/ku|0)|0},bu=Math.log,ku=Math.LN2,wu=64,Su=4194304,xu=0,Eu=!1,Cu=[],zu=null,Nu=null,Pu=null,_u=new Map,Lu=new Map,Tu=[],Mu="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" "),Fu=da.ReactCurrentBatchConfig,Ru=!0,Du=null,Ou=null,Iu=null,Uu=null,Vu={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Au=be(Vu),Bu=La({},Vu,{view:0,detail:0}),Wu=be(Bu),Hu=La({},Bu,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:we,button:0,buttons:0,relatedTarget:function(e){return void 0===e.relatedTarget?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==Ya&&(Ya&&"mousemove"===e.type?(qa=e.screenX-Ya.screenX,Ka=e.screenY-Ya.screenY):Ka=qa=0,Ya=e),qa)},movementY:function(e){return"movementY"in e?e.movementY:Ka}}),Qu=be(Hu),ju=be(La({},Hu,{dataTransfer:0})),$u=be(La({},Bu,{relatedTarget:0})),qu=be(La({},Vu,{animationName:0,elapsedTime:0,pseudoElement:0})),Ku=La({},Vu,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),Yu=be(Ku),Xu=be(La({},Vu,{data:0})),Gu=Xu,Zu={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Ju={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},eo={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"},no=La({},Bu,{key:function(e){if(e.key){var n=Zu[e.key]||e.key;if("Unidentified"!==n)return n}return"keypress"===e.type?13===(e=ge(e))?"Enter":String.fromCharCode(e):"keydown"===e.type||"keyup"===e.type?Ju[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:we,charCode:function(e){return"keypress"===e.type?ge(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?ge(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}}),to=be(no),ro=be(La({},Hu,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0})),lo=be(La({},Bu,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:we})),ao=be(La({},Vu,{propertyName:0,elapsedTime:0,pseudoElement:0})),uo=La({},Hu,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0}),oo=be(uo),io=[9,13,27,32],so=la&&"CompositionEvent"in window,co=null;la&&"documentMode"in document&&(co=document.documentMode);var fo=la&&"TextEvent"in window&&!co,po=la&&(!so||co&&8<co&&11>=co),mo=String.fromCharCode(32),ho=!1,go=!1,vo={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0},yo=null,bo=null,ko=!1;la&&(ko=function(e){if(!la)return!1;var n=(e="on"+e)in document;return n||((n=document.createElement("div")).setAttribute(e,"return;"),n="function"==typeof n[e]),n}("input")&&(!document.documentMode||9<document.documentMode));var wo="function"==typeof Object.is?Object.is:function(e,n){return e===n&&(0!==e||1/e==1/n)||e!=e&&n!=n},So=la&&"documentMode"in document&&11>=document.documentMode,xo=null,Eo=null,Co=null,zo=!1,No={animationend:He("Animation","AnimationEnd"),animationiteration:He("Animation","AnimationIteration"),animationstart:He("Animation","AnimationStart"),transitionend:He("Transition","TransitionEnd")},Po={},_o={};la&&(_o=document.createElement("div").style,"AnimationEvent"in window||(delete No.animationend.animation,delete No.animationiteration.animation,delete No.animationstart.animation),"TransitionEvent"in window||delete No.transitionend.transition);var Lo=Qe("animationend"),To=Qe("animationiteration"),Mo=Qe("animationstart"),Fo=Qe("transitionend"),Ro=new Map,Do="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");!function(){for(var e=0;e<Do.length;e++){var n=Do[e];je(n.toLowerCase(),"on"+(n=n[0].toUpperCase()+n.slice(1)))}je(Lo,"onAnimationEnd"),je(To,"onAnimationIteration"),je(Mo,"onAnimationStart"),je("dblclick","onDoubleClick"),je("focusin","onFocus"),je("focusout","onBlur"),je(Fo,"onTransitionEnd")}(),l("onMouseEnter",["mouseout","mouseover"]),l("onMouseLeave",["mouseout","mouseover"]),l("onPointerEnter",["pointerout","pointerover"]),l("onPointerLeave",["pointerout","pointerover"]),r("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),r("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),r("onBeforeInput",["compositionend","keypress","textInput","paste"]),r("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),r("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),r("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Oo="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),Io=new Set("cancel close invalid load scroll toggle".split(" ").concat(Oo)),Uo="_reactListening"+Math.random().toString(36).slice(2),Vo=/\r\n?/g,Ao=/\u0000|\uFFFD/g,Bo=null,Wo=null,Ho="function"==typeof setTimeout?setTimeout:void 0,Qo="function"==typeof clearTimeout?clearTimeout:void 0,jo="function"==typeof Promise?Promise:void 0,$o="function"==typeof queueMicrotask?queueMicrotask:void 0!==jo?function(e){return jo.resolve(null).then(e).catch(on)}:Ho,qo=Math.random().toString(36).slice(2),Ko="__reactFiber$"+qo,Yo="__reactProps$"+qo,Xo="__reactContainer$"+qo,Go="__reactEvents$"+qo,Zo="__reactListeners$"+qo,Jo="__reactHandles$"+qo,ei=[],ni=-1,ti={},ri=gn(ti),li=gn(!1),ai=ti,ui=null,oi=!1,ii=!1,si=[],ci=0,fi=null,di=0,pi=[],mi=0,hi=null,gi=1,vi="",yi=null,bi=null,ki=!1,wi=null,Si=da.ReactCurrentBatchConfig,xi=gn(null),Ei=null,Ci=null,zi=null,Ni=null,Pi=qn,_i=!1,Li=(new n.Component).refs,Ti={isMounted:function(e){return!!(e=e._reactInternals)&&W(e)===e},enqueueSetState:function(e,n,t){e=e._reactInternals;var r=tl(),l=rl(e),a=Xn(r,l);a.payload=n,null!=t&&(a.callback=t),null!==(n=Gn(e,a,l))&&(ll(n,e,l,r),Zn(n,e,l))},enqueueReplaceState:function(e,n,t){e=e._reactInternals;var r=tl(),l=rl(e),a=Xn(r,l);a.tag=1,a.payload=n,null!=t&&(a.callback=t),null!==(n=Gn(e,a,l))&&(ll(n,e,l,r),Zn(n,e,l))},enqueueForceUpdate:function(e,n){e=e._reactInternals;var t=tl(),r=rl(e),l=Xn(t,r);l.tag=2,null!=n&&(l.callback=n),null!==(n=Gn(e,l,r))&&(ll(n,e,r,t),Zn(n,e,r))}},Mi=ct(!0),Fi=ct(!1),Ri={},Di=gn(Ri),Oi=gn(Ri),Ii=gn(Ri),Ui=gn(0),Vi=[],Ai=da.ReactCurrentDispatcher,Bi=da.ReactCurrentBatchConfig,Wi=0,Hi=null,Qi=null,ji=null,$i=!1,qi=!1,Ki=0,Yi=0,Xi={readContext:Qn,useCallback:yt,useContext:yt,useEffect:yt,useImperativeHandle:yt,useInsertionEffect:yt,useLayoutEffect:yt,useMemo:yt,useReducer:yt,useRef:yt,useState:yt,useDebugValue:yt,useDeferredValue:yt,useTransition:yt,useMutableSource:yt,useSyncExternalStore:yt,useId:yt,unstable_isNewReconciler:!1},Gi={readContext:Qn,useCallback:function(e,n){return St().memoizedState=[e,void 0===n?null:n],e},useContext:Qn,useEffect:Vt,useImperativeHandle:function(e,n,t){return t=null!=t?t.concat([e]):null,It(4194308,4,Ht.bind(null,n,e),t)},useLayoutEffect:function(e,n){return It(4194308,4,e,n)},useInsertionEffect:function(e,n){return It(4,2,e,n)},useMemo:function(e,n){var t=St();return n=void 0===n?null:n,e=e(),t.memoizedState=[e,n],e},useReducer:function(e,n,t){var r=St();return n=void 0!==t?t(n):n,r.memoizedState=r.baseState=n,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:n},r.queue=e,e=e.dispatch=Gt.bind(null,Hi,e),[r.memoizedState,e]},useRef:function(e){return e={current:e},St().memoizedState=e},useState:Rt,useDebugValue:jt,useDeferredValue:function(e){return St().memoizedState=e},useTransition:function(){var e=Rt(!1),n=e[0];return e=Yt.bind(null,e[1]),St().memoizedState=e,[n,e]},useMutableSource:function(e,n,t){},useSyncExternalStore:function(e,n,r){var l=Hi,a=St();if(ki){if(void 0===r)throw Error(t(407));r=r()}else{if(r=n(),null===ks)throw Error(t(349));0!=(30&Wi)||_t(l,n,r)}a.memoizedState=r;var u={value:r,getSnapshot:n};return a.queue=u,Vt(Tt.bind(null,l,u,e),[e]),l.flags|=2048,Dt(9,Lt.bind(null,l,u,r,n),void 0,null),r},useId:function(){var e=St(),n=ks.identifierPrefix;if(ki){var t=vi;n=":"+n+"R"+(t=(gi&~(1<<32-yu(gi)-1)).toString(32)+t),0<(t=Ki++)&&(n+="H"+t.toString(32)),n+=":"}else n=":"+n+"r"+(t=Yi++).toString(32)+":";return e.memoizedState=n},unstable_isNewReconciler:!1},Zi={readContext:Qn,useCallback:$t,useContext:Qn,useEffect:At,useImperativeHandle:Qt,useInsertionEffect:Bt,useLayoutEffect:Wt,useMemo:qt,useReducer:Ct,useRef:Ot,useState:function(e){return Ct(Et)},useDebugValue:jt,useDeferredValue:function(e){return Kt(xt(),Qi.memoizedState,e)},useTransition:function(){return[Ct(Et)[0],xt().memoizedState]},useMutableSource:Nt,useSyncExternalStore:Pt,useId:Xt,unstable_isNewReconciler:!1},Ji={readContext:Qn,useCallback:$t,useContext:Qn,useEffect:At,useImperativeHandle:Qt,useInsertionEffect:Bt,useLayoutEffect:Wt,useMemo:qt,useReducer:zt,useRef:Ot,useState:function(e){return zt(Et)},useDebugValue:jt,useDeferredValue:function(e){var n=xt();return null===Qi?n.memoizedState=e:Kt(n,Qi.memoizedState,e)},useTransition:function(){return[zt(Et)[0],xt().memoizedState]},useMutableSource:Nt,useSyncExternalStore:Pt,useId:Xt,unstable_isNewReconciler:!1},es="function"==typeof WeakMap?WeakMap:Map,ns=da.ReactCurrentOwner,ts=!1,rs={dehydrated:null,treeContext:null,retryLane:0},ls=function(e,n,t,r){for(t=n.child;null!==t;){if(5===t.tag||6===t.tag)e.appendChild(t.stateNode);else if(4!==t.tag&&null!==t.child){t.child.return=t,t=t.child;continue}if(t===n)break;for(;null===t.sibling;){if(null===t.return||t.return===n)return;t=t.return}t.sibling.return=t.return,t=t.sibling}},as=function(e,n){},us=function(e,n,t,r,l){var a=e.memoizedProps;if(a!==r){switch(e=n.stateNode,ft(Di.current),l=null,t){case"input":a=y(e,a),r=y(e,r),l=[];break;case"select":a=La({},a,{value:void 0}),r=La({},r,{value:void 0}),l=[];break;case"textarea":a=C(e,a),r=C(e,r),l=[];break;default:"function"!=typeof a.onClick&&"function"==typeof r.onClick&&(e.onclick=an)}var u;for(s in F(t,r),t=null,a)if(!r.hasOwnProperty(s)&&a.hasOwnProperty(s)&&null!=a[s])if("style"===s){var o=a[s];for(u in o)o.hasOwnProperty(u)&&(t||(t={}),t[u]="")}else"dangerouslySetInnerHTML"!==s&&"children"!==s&&"suppressContentEditableWarning"!==s&&"suppressHydrationWarning"!==s&&"autoFocus"!==s&&(ra.hasOwnProperty(s)?l||(l=[]):(l=l||[]).push(s,null));for(s in r){var i=r[s];if(o=null!=a?a[s]:void 0,r.hasOwnProperty(s)&&i!==o&&(null!=i||null!=o))if("style"===s)if(o){for(u in o)!o.hasOwnProperty(u)||i&&i.hasOwnProperty(u)||(t||(t={}),t[u]="");for(u in i)i.hasOwnProperty(u)&&o[u]!==i[u]&&(t||(t={}),t[u]=i[u])}else t||(l||(l=[]),l.push(s,t)),t=i;else"dangerouslySetInnerHTML"===s?(i=i?i.__html:void 0,o=o?o.__html:void 0,null!=i&&o!==i&&(l=l||[]).push(s,i)):"children"===s?"string"!=typeof i&&"number"!=typeof i||(l=l||[]).push(s,""+i):"suppressContentEditableWarning"!==s&&"suppressHydrationWarning"!==s&&(ra.hasOwnProperty(s)?(null!=i&&"onScroll"===s&&Ke("scroll",e),l||o===i||(l=[])):(l=l||[]).push(s,i))}t&&(l=l||[]).push("style",t);var s=l;(n.updateQueue=s)&&(n.flags|=4)}},os=function(e,n,t,r){t!==r&&(n.flags|=4)},is=!1,ss=!1,cs="function"==typeof WeakSet?WeakSet:Set,fs=null,ds=!1,ps=null,ms=!1,hs=Math.ceil,gs=da.ReactCurrentDispatcher,vs=da.ReactCurrentOwner,ys=da.ReactCurrentBatchConfig,bs=0,ks=null,ws=null,Ss=0,xs=0,Es=gn(0),Cs=0,zs=null,Ns=0,Ps=0,_s=0,Ls=null,Ts=null,Ms=0,Fs=1/0,Rs=null,Ds=!1,Os=null,Is=null,Us=!1,Vs=null,As=0,Bs=0,Ws=null,Hs=-1,Qs=0,js=function(e,n,r){if(null!==e)if(e.memoizedProps!==n.pendingProps||li.current)ts=!0;else{if(0==(e.lanes&r)&&0==(128&n.flags))return ts=!1,function(e,n,t){switch(n.tag){case 3:br(n),In();break;case 5:mt(n);break;case 1:kn(n.type)&&xn(n);break;case 4:dt(n,n.stateNode.containerInfo);break;case 10:var r=n.type._context,l=n.memoizedProps.value;yn(xi,r._currentValue),r._currentValue=l;break;case 13:if(null!==(r=n.memoizedState))return null!==r.dehydrated?(yn(Ui,1&Ui.current),n.flags|=128,null):0!=(t&n.child.childLanes)?Sr(e,n,t):(yn(Ui,1&Ui.current),null!==(e=_r(e,n,t))?e.sibling:null);yn(Ui,1&Ui.current);break;case 19:if(r=0!=(t&n.childLanes),0!=(128&e.flags)){if(r)return Nr(e,n,t);n.flags|=128}if(null!==(l=n.memoizedState)&&(l.rendering=null,l.tail=null,l.lastEffect=null),yn(Ui,Ui.current),r)break;return null;case 22:case 23:return n.lanes=0,mr(e,n,t)}return _r(e,n,t)}(e,n,r);ts=0!=(131072&e.flags)}else ts=!1,ki&&0!=(1048576&n.flags)&&Pn(n,di,n.index);switch(n.lanes=0,n.tag){case 2:var l=n.type;Pr(e,n),e=n.pendingProps;var a=bn(n,ri.current);Hn(n,r),a=kt(null,n,l,e,a,r);var u=wt();return n.flags|=1,"object"==typeof a&&null!==a&&"function"==typeof a.render&&void 0===a.$$typeof?(n.tag=1,n.memoizedState=null,n.updateQueue=null,kn(l)?(u=!0,xn(n)):u=!1,n.memoizedState=null!==a.state&&void 0!==a.state?a.state:null,Kn(n),a.updater=Ti,n.stateNode=a,a._reactInternals=n,ut(n,l,e,r),n=yr(null,n,l,!0,u,r)):(n.tag=0,ki&&u&&_n(n),cr(null,n,a,r),n=n.child),n;case 16:l=n.elementType;e:{switch(Pr(e,n),e=n.pendingProps,l=(a=l._init)(l._payload),n.type=l,a=n.tag=function(e){if("function"==typeof e)return Ml(e)?1:0;if(null!=e){if((e=e.$$typeof)===ka)return 11;if(e===xa)return 14}return 2}(l),e=Vn(l,e),a){case 0:n=gr(null,n,l,e,r);break e;case 1:n=vr(null,n,l,e,r);break e;case 11:n=fr(null,n,l,e,r);break e;case 14:n=dr(null,n,l,Vn(l.type,e),r);break e}throw Error(t(306,l,""))}return n;case 0:return l=n.type,a=n.pendingProps,gr(e,n,l,a=n.elementType===l?a:Vn(l,a),r);case 1:return l=n.type,a=n.pendingProps,vr(e,n,l,a=n.elementType===l?a:Vn(l,a),r);case 3:e:{if(br(n),null===e)throw Error(t(387));l=n.pendingProps,a=(u=n.memoizedState).element,Yn(e,n),et(n,l,null,r);var o=n.memoizedState;if(l=o.element,u.isDehydrated){if(u={element:l,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},n.updateQueue.baseState=u,n.memoizedState=u,256&n.flags){n=kr(e,n,l,r,a=tr(Error(t(423)),n));break e}if(l!==a){n=kr(e,n,l,r,a=tr(Error(t(424)),n));break e}for(bi=cn(n.stateNode.containerInfo.firstChild),yi=n,ki=!0,wi=null,r=Fi(n,null,l,r),n.child=r;r;)r.flags=-3&r.flags|4096,r=r.sibling}else{if(In(),l===a){n=_r(e,n,r);break e}cr(e,n,l,r)}n=n.child}return n;case 5:return mt(n),null===e&&Rn(n),l=n.type,a=n.pendingProps,u=null!==e?e.memoizedProps:null,o=a.children,un(l,a)?o=null:null!==u&&un(l,u)&&(n.flags|=32),hr(e,n),cr(e,n,o,r),n.child;case 6:return null===e&&Rn(n),null;case 13:return Sr(e,n,r);case 4:return dt(n,n.stateNode.containerInfo),l=n.pendingProps,null===e?n.child=Mi(n,null,l,r):cr(e,n,l,r),n.child;case 11:return l=n.type,a=n.pendingProps,fr(e,n,l,a=n.elementType===l?a:Vn(l,a),r);case 7:return cr(e,n,n.pendingProps,r),n.child;case 8:case 12:return cr(e,n,n.pendingProps.children,r),n.child;case 10:e:{if(l=n.type._context,a=n.pendingProps,u=n.memoizedProps,o=a.value,yn(xi,l._currentValue),l._currentValue=o,null!==u)if(wo(u.value,o)){if(u.children===a.children&&!li.current){n=_r(e,n,r);break e}}else for(null!==(u=n.child)&&(u.return=n);null!==u;){var i=u.dependencies;if(null!==i){o=u.child;for(var s=i.firstContext;null!==s;){if(s.context===l){if(1===u.tag){(s=Xn(-1,r&-r)).tag=2;var c=u.updateQueue;if(null!==c){var f=(c=c.shared).pending;null===f?s.next=s:(s.next=f.next,f.next=s),c.pending=s}}u.lanes|=r,null!==(s=u.alternate)&&(s.lanes|=r),Wn(u.return,r,n),i.lanes|=r;break}s=s.next}}else if(10===u.tag)o=u.type===n.type?null:u.child;else if(18===u.tag){if(null===(o=u.return))throw Error(t(341));o.lanes|=r,null!==(i=o.alternate)&&(i.lanes|=r),Wn(o,r,n),o=u.sibling}else o=u.child;if(null!==o)o.return=u;else for(o=u;null!==o;){if(o===n){o=null;break}if(null!==(u=o.sibling)){u.return=o.return,o=u;break}o=o.return}u=o}cr(e,n,a.children,r),n=n.child}return n;case 9:return a=n.type,l=n.pendingProps.children,Hn(n,r),l=l(a=Qn(a)),n.flags|=1,cr(e,n,l,r),n.child;case 14:return a=Vn(l=n.type,n.pendingProps),dr(e,n,l,a=Vn(l.type,a),r);case 15:return pr(e,n,n.type,n.pendingProps,r);case 17:return l=n.type,a=n.pendingProps,a=n.elementType===l?a:Vn(l,a),Pr(e,n),n.tag=1,kn(l)?(e=!0,xn(n)):e=!1,Hn(n,r),lt(n,l,a),ut(n,l,a,r),yr(null,n,l,!0,e,r);case 19:return Nr(e,n,r);case 22:return mr(e,n,r)}throw Error(t(156,n.tag))},$s=function(e,n,t,r){return new Tl(e,n,t,r)},qs="function"==typeof reportError?reportError:function(e){console.error(e)};Gl.prototype.render=Xl.prototype.render=function(e){var n=this._internalRoot;if(null===n)throw Error(t(409));Ql(e,n,null,null)},Gl.prototype.unmount=Xl.prototype.unmount=function(){var e=this._internalRoot;if(null!==e){this._internalRoot=null;var n=e.containerInfo;dl((function(){Ql(null,e,null,null)})),n[Xo]=null}},Gl.prototype.unstable_scheduleHydration=function(e){if(e){var n=Gs();e={blockedOn:null,target:e,priority:n};for(var t=0;t<Tu.length&&0!==n&&n<Tu[t].priority;t++);Tu.splice(t,0,e),0===t&&le(e)}};var Ks=function(e){switch(e.tag){case 3:var n=e.stateNode;if(n.current.memoizedState.isDehydrated){var t=q(n.pendingLanes);0!==t&&(ee(n,1|t),al(n,su()),0==(6&bs)&&(nl(),zn()))}break;case 13:dl((function(){var n=qn(e,1);if(null!==n){var t=tl();ll(n,e,1,t)}})),ql(e,1)}},Ys=function(e){if(13===e.tag){var n=qn(e,134217728);null!==n&&ll(n,e,134217728,tl()),ql(e,134217728)}},Xs=function(e){if(13===e.tag){var n=rl(e),t=qn(e,n);null!==t&&ll(t,e,n,tl()),ql(e,n)}},Gs=function(){return xu},Zs=function(e,n){var t=xu;try{return xu=e,n()}finally{xu=t}};Va=function(e,n,r){switch(n){case"input":if(w(e,r),n=r.name,"radio"===r.type&&null!=n){for(r=e;r.parentNode;)r=r.parentNode;for(r=r.querySelectorAll("input[name="+JSON.stringify(""+n)+'][type="radio"]'),n=0;n<r.length;n++){var l=r[n];if(l!==e&&l.form===e.form){var a=hn(l);if(!a)throw Error(t(90));g(l),w(l,a)}}}break;case"textarea":N(e,r);break;case"select":null!=(n=r.value)&&E(e,!!r.multiple,n,!1)}},function(e,n,t){Wa=e,Ha=t}(fl,0,dl);var Js={usingClientEntryPoint:!1,Events:[pn,mn,hn,I,U,fl]};!function(e){if(e={bundleType:e.bundleType,version:e.version,rendererPackageName:e.rendererPackageName,rendererConfig:e.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:da.ReactCurrentDispatcher,findHostInstanceByFiber:Kl,findFiberByHostInstance:e.findFiberByHostInstance||Yl,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.2.0"},"undefined"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__)e=!1;else{var n=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(n.isDisabled||!n.supportsFiber)e=!0;else{try{gu=n.inject(e),vu=n}catch(e){}e=!!n.checkDCE}}}({findFiberByHostInstance:dn,bundleType:0,version:"18.2.0-next-9e3b772b8-20220608",rendererPackageName:"react-dom"}),e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Js,e.createPortal=function(e,n){var r=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!Zl(n))throw Error(t(200));return Bl(e,n,null,r)},e.createRoot=function(e,n){if(!Zl(e))throw Error(t(299));var r=!1,l="",a=qs;return null!=n&&(!0===n.unstable_strictMode&&(r=!0),void 0!==n.identifierPrefix&&(l=n.identifierPrefix),void 0!==n.onRecoverableError&&(a=n.onRecoverableError)),n=Al(e,1,!1,null,0,r,0,l,a),e[Xo]=n.current,Xe(8===e.nodeType?e.parentNode:e),new Xl(n)},e.findDOMNode=function(e){if(null==e)return null;if(1===e.nodeType)return e;var n=e._reactInternals;if(void 0===n){if("function"==typeof e.render)throw Error(t(188));throw e=Object.keys(e).join(","),Error(t(268,e))}return e=null===(e=j(n))?null:e.stateNode},e.flushSync=function(e){return dl(e)},e.hydrate=function(e,n,r){if(!Jl(n))throw Error(t(200));return na(null,e,n,!0,r)},e.hydrateRoot=function(e,n,r){if(!Zl(e))throw Error(t(405));var l=null!=r&&r.hydratedSources||null,a=!1,u="",o=qs;if(null!=r&&(!0===r.unstable_strictMode&&(a=!0),void 0!==r.identifierPrefix&&(u=r.identifierPrefix),void 0!==r.onRecoverableError&&(o=r.onRecoverableError)),n=Hl(n,null,e,1,null!=r?r:null,a,0,u,o),e[Xo]=n.current,Xe(e),l)for(e=0;e<l.length;e++)a=(a=(r=l[e])._getVersion)(r._source),null==n.mutableSourceEagerHydrationData?n.mutableSourceEagerHydrationData=[r,a]:n.mutableSourceEagerHydrationData.push(r,a);return new Gl(n)},e.render=function(e,n,r){if(!Jl(n))throw Error(t(200));return na(null,e,n,!1,r)},e.unmountComponentAtNode=function(e){if(!Jl(e))throw Error(t(40));return!!e._reactRootContainer&&(dl((function(){na(null,null,e,!1,(function(){e._reactRootContainer=null,e[Xo]=null}))})),!0)},e.unstable_batchedUpdates=fl,e.unstable_renderSubtreeIntoContainer=function(e,n,r,l){if(!Jl(r))throw Error(t(200));if(null==e||void 0===e._reactInternals)throw Error(t(38));return na(e,n,r,!1,l)},e.version="18.2.0-next-9e3b772b8-20220608"},"object"==typeof exports&&"undefined"!=typeof module?n(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],n):n((e=e||self).ReactDOM={},e.React)}(); vendor/wp-polyfill-dom-rect.js 0000666 00000003607 15123355174 0012405 0 ustar 00
// DOMRect
(function (global) {
function number(v) {
return v === undefined ? 0 : Number(v);
}
function different(u, v) {
return u !== v && !(isNaN(u) && isNaN(v));
}
function DOMRect(xArg, yArg, wArg, hArg) {
var x, y, width, height, left, right, top, bottom;
x = number(xArg);
y = number(yArg);
width = number(wArg);
height = number(hArg);
Object.defineProperties(this, {
x: {
get: function () { return x; },
set: function (newX) {
if (different(x, newX)) {
x = newX;
left = right = undefined;
}
},
enumerable: true
},
y: {
get: function () { return y; },
set: function (newY) {
if (different(y, newY)) {
y = newY;
top = bottom = undefined;
}
},
enumerable: true
},
width: {
get: function () { return width; },
set: function (newWidth) {
if (different(width, newWidth)) {
width = newWidth;
left = right = undefined;
}
},
enumerable: true
},
height: {
get: function () { return height; },
set: function (newHeight) {
if (different(height, newHeight)) {
height = newHeight;
top = bottom = undefined;
}
},
enumerable: true
},
left: {
get: function () {
if (left === undefined) {
left = x + Math.min(0, width);
}
return left;
},
enumerable: true
},
right: {
get: function () {
if (right === undefined) {
right = x + Math.max(0, width);
}
return right;
},
enumerable: true
},
top: {
get: function () {
if (top === undefined) {
top = y + Math.min(0, height);
}
return top;
},
enumerable: true
},
bottom: {
get: function () {
if (bottom === undefined) {
bottom = y + Math.max(0, height);
}
return bottom;
},
enumerable: true
}
});
}
global.DOMRect = DOMRect;
}(self));
vendor/wp-polyfill-object-fit.min.js 0000666 00000005637 15123355174 0013510 0 ustar 00 !function(){"use strict";if("undefined"!=typeof window){var t=window.navigator.userAgent.match(/Edge\/(\d{2})\./),e=t?parseInt(t[1],10):null,i=!!e&&16<=e&&e<=18;if("objectFit"in document.documentElement.style==0||i){var n=function(t,e,i){var n,o,l,a,d;if((i=i.split(" ")).length<2&&(i[1]=i[0]),"x"===t)n=i[0],o=i[1],l="left",a="right",d=e.clientWidth;else{if("y"!==t)return;n=i[1],o=i[0],l="top",a="bottom",d=e.clientHeight}if(n!==l&&o!==l){if(n!==a&&o!==a)return"center"===n||"50%"===n?(e.style[l]="50%",void(e.style["margin-"+l]=d/-2+"px")):void(0<=n.indexOf("%")?(n=parseInt(n,10))<50?(e.style[l]=n+"%",e.style["margin-"+l]=d*(n/-100)+"px"):(n=100-n,e.style[a]=n+"%",e.style["margin-"+a]=d*(n/-100)+"px"):e.style[l]=n);e.style[a]="0"}else e.style[l]="0"},o=function(t){var e=t.dataset?t.dataset.objectFit:t.getAttribute("data-object-fit"),i=t.dataset?t.dataset.objectPosition:t.getAttribute("data-object-position");e=e||"cover",i=i||"50% 50%";var o=t.parentNode;return function(t){var e=window.getComputedStyle(t,null),i=e.getPropertyValue("position"),n=e.getPropertyValue("overflow"),o=e.getPropertyValue("display");i&&"static"!==i||(t.style.position="relative"),"hidden"!==n&&(t.style.overflow="hidden"),o&&"inline"!==o||(t.style.display="block"),0===t.clientHeight&&(t.style.height="100%"),-1===t.className.indexOf("object-fit-polyfill")&&(t.className=t.className+" object-fit-polyfill")}(o),function(t){var e=window.getComputedStyle(t,null),i={"max-width":"none","max-height":"none","min-width":"0px","min-height":"0px",top:"auto",right:"auto",bottom:"auto",left:"auto","margin-top":"0px","margin-right":"0px","margin-bottom":"0px","margin-left":"0px"};for(var n in i)e.getPropertyValue(n)!==i[n]&&(t.style[n]=i[n])}(t),t.style.position="absolute",t.style.width="auto",t.style.height="auto","scale-down"===e&&(e=t.clientWidth<o.clientWidth&&t.clientHeight<o.clientHeight?"none":"contain"),"none"===e?(n("x",t,i),void n("y",t,i)):"fill"===e?(t.style.width="100%",t.style.height="100%",n("x",t,i),void n("y",t,i)):(t.style.height="100%",void("cover"===e&&t.clientWidth>o.clientWidth||"contain"===e&&t.clientWidth<o.clientWidth?(t.style.top="0",t.style.marginTop="0",n("x",t,i)):(t.style.width="100%",t.style.height="auto",t.style.left="0",t.style.marginLeft="0",n("y",t,i))))},l=function(t){if(void 0===t||t instanceof Event)t=document.querySelectorAll("[data-object-fit]");else if(t&&t.nodeName)t=[t];else if("object"!=typeof t||!t.length||!t[0].nodeName)return!1;for(var e=0;e<t.length;e++)if(t[e].nodeName){var n=t[e].nodeName.toLowerCase();if("img"===n){if(i)continue;t[e].complete?o(t[e]):t[e].addEventListener("load",(function(){o(this)}))}else"video"===n?0<t[e].readyState?o(t[e]):t[e].addEventListener("loadedmetadata",(function(){o(this)})):o(t[e])}return!0};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",l):l(),window.addEventListener("resize",l),window.objectFitPolyfill=l}else window.objectFitPolyfill=function(){return!1}}}(); vendor/regenerator-runtime.js 0000666 00000061162 15123355174 0012415 0 ustar 00 /**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var runtime = (function (exports) {
"use strict";
var Op = Object.prototype;
var hasOwn = Op.hasOwnProperty;
var defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; };
var undefined; // More compressible than void 0.
var $Symbol = typeof Symbol === "function" ? Symbol : {};
var iteratorSymbol = $Symbol.iterator || "@@iterator";
var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
function define(obj, key, value) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
return obj[key];
}
try {
// IE 8 has a broken Object.defineProperty that only works on DOM objects.
define({}, "");
} catch (err) {
define = function(obj, key, value) {
return obj[key] = value;
};
}
function wrap(innerFn, outerFn, self, tryLocsList) {
// If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
var generator = Object.create(protoGenerator.prototype);
var context = new Context(tryLocsList || []);
// The ._invoke method unifies the implementations of the .next,
// .throw, and .return methods.
defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) });
return generator;
}
exports.wrap = wrap;
// Try/catch helper to minimize deoptimizations. Returns a completion
// record like context.tryEntries[i].completion. This interface could
// have been (and was previously) designed to take a closure to be
// invoked without arguments, but in all the cases we care about we
// already have an existing method we want to call, so there's no need
// to create a new function object. We can even get away with assuming
// the method takes exactly one argument, since that happens to be true
// in every case, so we don't have to touch the arguments object. The
// only additional allocation required is the completion record, which
// has a stable shape and so hopefully should be cheap to allocate.
function tryCatch(fn, obj, arg) {
try {
return { type: "normal", arg: fn.call(obj, arg) };
} catch (err) {
return { type: "throw", arg: err };
}
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed";
// Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement.
var ContinueSentinel = {};
// Dummy constructor functions that we use as the .constructor and
// .constructor.prototype properties for functions that return Generator
// objects. For full spec compliance, you may wish to configure your
// minifier not to mangle the names of these two functions.
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
// This is a polyfill for %IteratorPrototype% for environments that
// don't natively support it.
var IteratorPrototype = {};
define(IteratorPrototype, iteratorSymbol, function () {
return this;
});
var getProto = Object.getPrototypeOf;
var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
if (NativeIteratorPrototype &&
NativeIteratorPrototype !== Op &&
hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
// This environment has a native %IteratorPrototype%; use it instead
// of the polyfill.
IteratorPrototype = NativeIteratorPrototype;
}
var Gp = GeneratorFunctionPrototype.prototype =
Generator.prototype = Object.create(IteratorPrototype);
GeneratorFunction.prototype = GeneratorFunctionPrototype;
defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: true });
defineProperty(
GeneratorFunctionPrototype,
"constructor",
{ value: GeneratorFunction, configurable: true }
);
GeneratorFunction.displayName = define(
GeneratorFunctionPrototype,
toStringTagSymbol,
"GeneratorFunction"
);
// Helper for defining the .next, .throw, and .return methods of the
// Iterator interface in terms of a single ._invoke method.
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function(method) {
define(prototype, method, function(arg) {
return this._invoke(method, arg);
});
});
}
exports.isGeneratorFunction = function(genFun) {
var ctor = typeof genFun === "function" && genFun.constructor;
return ctor
? ctor === GeneratorFunction ||
// For the native GeneratorFunction constructor, the best we can
// do is to check its .name property.
(ctor.displayName || ctor.name) === "GeneratorFunction"
: false;
};
exports.mark = function(genFun) {
if (Object.setPrototypeOf) {
Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
} else {
genFun.__proto__ = GeneratorFunctionPrototype;
define(genFun, toStringTagSymbol, "GeneratorFunction");
}
genFun.prototype = Object.create(Gp);
return genFun;
};
// Within the body of any async function, `await x` is transformed to
// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
// `hasOwn.call(value, "__await")` to determine if the yielded value is
// meant to be awaited.
exports.awrap = function(arg) {
return { __await: arg };
};
function AsyncIterator(generator, PromiseImpl) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if (record.type === "throw") {
reject(record.arg);
} else {
var result = record.arg;
var value = result.value;
if (value &&
typeof value === "object" &&
hasOwn.call(value, "__await")) {
return PromiseImpl.resolve(value.__await).then(function(value) {
invoke("next", value, resolve, reject);
}, function(err) {
invoke("throw", err, resolve, reject);
});
}
return PromiseImpl.resolve(value).then(function(unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration.
result.value = unwrapped;
resolve(result);
}, function(error) {
// If a rejected Promise was yielded, throw the rejection back
// into the async generator function so it can be handled there.
return invoke("throw", error, resolve, reject);
});
}
}
var previousPromise;
function enqueue(method, arg) {
function callInvokeWithMethodAndArg() {
return new PromiseImpl(function(resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise =
// If enqueue has been called before, then we want to wait until
// all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially
// important to get this right, even though it requires care.
previousPromise ? previousPromise.then(
callInvokeWithMethodAndArg,
// Avoid propagating failures to Promises returned by later
// invocations of the iterator.
callInvokeWithMethodAndArg
) : callInvokeWithMethodAndArg();
}
// Define the unified helper method that is used to implement .next,
// .throw, and .return (see defineIteratorMethods).
defineProperty(this, "_invoke", { value: enqueue });
}
defineIteratorMethods(AsyncIterator.prototype);
define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
return this;
});
exports.AsyncIterator = AsyncIterator;
// Note that simple async functions are implemented on top of
// AsyncIterator objects; they just return a Promise for the value of
// the final result produced by the iterator.
exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
if (PromiseImpl === void 0) PromiseImpl = Promise;
var iter = new AsyncIterator(
wrap(innerFn, outerFn, self, tryLocsList),
PromiseImpl
);
return exports.isGeneratorFunction(outerFn)
? iter // If outerFn is a generator, return the full iterator.
: iter.next().then(function(result) {
return result.done ? result.value : iter.next();
});
};
function makeInvokeMethod(innerFn, self, context) {
var state = GenStateSuspendedStart;
return function invoke(method, arg) {
if (state === GenStateExecuting) {
throw new Error("Generator is already running");
}
if (state === GenStateCompleted) {
if (method === "throw") {
throw arg;
}
// Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
return doneResult();
}
context.method = method;
context.arg = arg;
while (true) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if (context.method === "next") {
// Setting context._sent for legacy support of Babel's
// function.sent implementation.
context.sent = context._sent = context.arg;
} else if (context.method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw context.arg;
}
context.dispatchException(context.arg);
} else if (context.method === "return") {
context.abrupt("return", context.arg);
}
state = GenStateExecuting;
var record = tryCatch(innerFn, self, context);
if (record.type === "normal") {
// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done
? GenStateCompleted
: GenStateSuspendedYield;
if (record.arg === ContinueSentinel) {
continue;
}
return {
value: record.arg,
done: context.done
};
} else if (record.type === "throw") {
state = GenStateCompleted;
// Dispatch the exception by looping back around to the
// context.dispatchException(context.arg) call above.
context.method = "throw";
context.arg = record.arg;
}
}
};
}
// Call delegate.iterator[context.method](context.arg) and handle the
// result, either by returning a { value, done } result from the
// delegate iterator, or by modifying context.method and context.arg,
// setting context.delegate to null, and returning the ContinueSentinel.
function maybeInvokeDelegate(delegate, context) {
var methodName = context.method;
var method = delegate.iterator[methodName];
if (method === undefined) {
// A .throw or .return when the delegate iterator has no .throw
// method, or a missing .next mehtod, always terminate the
// yield* loop.
context.delegate = null;
// Note: ["return"] must be used for ES3 parsing compatibility.
if (methodName === "throw" && delegate.iterator["return"]) {
// If the delegate iterator has a return method, give it a
// chance to clean up.
context.method = "return";
context.arg = undefined;
maybeInvokeDelegate(delegate, context);
if (context.method === "throw") {
// If maybeInvokeDelegate(context) changed context.method from
// "return" to "throw", let that override the TypeError below.
return ContinueSentinel;
}
}
if (methodName !== "return") {
context.method = "throw";
context.arg = new TypeError(
"The iterator does not provide a '" + methodName + "' method");
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if (record.type === "throw") {
context.method = "throw";
context.arg = record.arg;
context.delegate = null;
return ContinueSentinel;
}
var info = record.arg;
if (! info) {
context.method = "throw";
context.arg = new TypeError("iterator result is not an object");
context.delegate = null;
return ContinueSentinel;
}
if (info.done) {
// Assign the result of the finished delegate to the temporary
// variable specified by delegate.resultName (see delegateYield).
context[delegate.resultName] = info.value;
// Resume execution at the desired location (see delegateYield).
context.next = delegate.nextLoc;
// If context.method was "throw" but the delegate handled the
// exception, let the outer generator proceed normally. If
// context.method was "next", forget context.arg since it has been
// "consumed" by the delegate iterator. If context.method was
// "return", allow the original .return call to continue in the
// outer generator.
if (context.method !== "return") {
context.method = "next";
context.arg = undefined;
}
} else {
// Re-yield the result returned by the delegate method.
return info;
}
// The delegate iterator is finished, so forget it and continue with
// the outer generator.
context.delegate = null;
return ContinueSentinel;
}
// Define Generator.prototype.{next,throw,return} in terms of the
// unified ._invoke helper method.
defineIteratorMethods(Gp);
define(Gp, toStringTagSymbol, "Generator");
// A Generator should always return itself as the iterator object when the
// @@iterator function is called on it. Some browsers' implementations of the
// iterator prototype chain incorrectly implement this, causing the Generator
// object to not be returned from this call. This ensures that doesn't happen.
// See https://github.com/facebook/regenerator/issues/274 for more details.
define(Gp, iteratorSymbol, function() {
return this;
});
define(Gp, "toString", function() {
return "[object Generator]";
});
function pushTryEntry(locs) {
var entry = { tryLoc: locs[0] };
if (1 in locs) {
entry.catchLoc = locs[1];
}
if (2 in locs) {
entry.finallyLoc = locs[2];
entry.afterLoc = locs[3];
}
this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal";
delete record.arg;
entry.completion = record;
}
function Context(tryLocsList) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [{ tryLoc: "root" }];
tryLocsList.forEach(pushTryEntry, this);
this.reset(true);
}
exports.keys = function(val) {
var object = Object(val);
var keys = [];
for (var key in object) {
keys.push(key);
}
keys.reverse();
// Rather than returning an object with a next method, we keep
// things simple and return the next function itself.
return function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
}
// To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
};
};
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
}
if (typeof iterable.next === "function") {
return iterable;
}
if (!isNaN(iterable.length)) {
var i = -1, next = function next() {
while (++i < iterable.length) {
if (hasOwn.call(iterable, i)) {
next.value = iterable[i];
next.done = false;
return next;
}
}
next.value = undefined;
next.done = true;
return next;
};
return next.next = next;
}
}
// Return an iterator with no values.
return { next: doneResult };
}
exports.values = values;
function doneResult() {
return { value: undefined, done: true };
}
Context.prototype = {
constructor: Context,
reset: function(skipTempReset) {
this.prev = 0;
this.next = 0;
// Resetting context._sent for legacy support of Babel's
// function.sent implementation.
this.sent = this._sent = undefined;
this.done = false;
this.delegate = null;
this.method = "next";
this.arg = undefined;
this.tryEntries.forEach(resetTryEntry);
if (!skipTempReset) {
for (var name in this) {
// Not sure about the optimal order of these conditions:
if (name.charAt(0) === "t" &&
hasOwn.call(this, name) &&
!isNaN(+name.slice(1))) {
this[name] = undefined;
}
}
}
},
stop: function() {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") {
throw rootRecord.arg;
}
return this.rval;
},
dispatchException: function(exception) {
if (this.done) {
throw exception;
}
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
if (caught) {
// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
context.method = "next";
context.arg = undefined;
}
return !! caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") {
// Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
}
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
} else if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else if (hasCatch) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
}
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else {
throw new Error("try statement without catch or finally");
}
}
}
},
abrupt: function(type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev &&
hasOwn.call(entry, "finallyLoc") &&
this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
if (finallyEntry &&
(type === "break" ||
type === "continue") &&
finallyEntry.tryLoc <= arg &&
arg <= finallyEntry.finallyLoc) {
// Ignore the finally entry if control is not jumping to a
// location outside the try/catch block.
finallyEntry = null;
}
var record = finallyEntry ? finallyEntry.completion : {};
record.type = type;
record.arg = arg;
if (finallyEntry) {
this.method = "next";
this.next = finallyEntry.finallyLoc;
return ContinueSentinel;
}
return this.complete(record);
},
complete: function(record, afterLoc) {
if (record.type === "throw") {
throw record.arg;
}
if (record.type === "break" ||
record.type === "continue") {
this.next = record.arg;
} else if (record.type === "return") {
this.rval = this.arg = record.arg;
this.method = "return";
this.next = "end";
} else if (record.type === "normal" && afterLoc) {
this.next = afterLoc;
}
return ContinueSentinel;
},
finish: function(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) {
this.complete(entry.completion, entry.afterLoc);
resetTryEntry(entry);
return ContinueSentinel;
}
}
},
"catch": function(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
// The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw new Error("illegal catch attempt");
},
delegateYield: function(iterable, resultName, nextLoc) {
this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
};
if (this.method === "next") {
// Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
this.arg = undefined;
}
return ContinueSentinel;
}
};
// Regardless of whether this script is executing as a CommonJS module
// or not, return the runtime object so that we can declare the variable
// regeneratorRuntime in the outer scope, which allows this module to be
// injected easily by `bin/regenerator --include-runtime script.js`.
return exports;
}(
// If this script is executing as a CommonJS module, use module.exports
// as the regeneratorRuntime namespace. Otherwise create a new empty
// object. Either way, the resulting object will be used to initialize
// the regeneratorRuntime variable at the top of this file.
typeof module === "object" ? module.exports : {}
));
try {
regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
// This module should not be running in strict mode, so the above
// assignment should always work unless something is misconfigured. Just
// in case runtime.js accidentally runs in strict mode, in modern engines
// we can explicitly access globalThis. In older engines we can escape
// strict mode using a global Function call. This could conceivably fail
// if a Content Security Policy forbids using Function, but in that case
// the proper solution is to fix the accidental strict mode problem. If
// you've misconfigured your bundler to force strict mode and applied a
// CSP to forbid Function, and you're not willing to fix either of those
// problems, please detail your unique predicament in a GitHub issue.
if (typeof globalThis === "object") {
globalThis.regeneratorRuntime = runtime;
} else {
Function("r", "regeneratorRuntime = r")(runtime);
}
}
vendor/moment.js 0000666 00000525014 15123355174 0007717 0 ustar 00 //! moment.js
//! version : 2.29.4
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
global.moment = factory()
}(this, (function () { 'use strict';
var hookCallback;
function hooks() {
return hookCallback.apply(null, arguments);
}
// This is done to register the method called with moment()
// without creating circular dependencies.
function setHookCallback(callback) {
hookCallback = callback;
}
function isArray(input) {
return (
input instanceof Array ||
Object.prototype.toString.call(input) === '[object Array]'
);
}
function isObject(input) {
// IE8 will treat undefined and null as object if it wasn't for
// input != null
return (
input != null &&
Object.prototype.toString.call(input) === '[object Object]'
);
}
function hasOwnProp(a, b) {
return Object.prototype.hasOwnProperty.call(a, b);
}
function isObjectEmpty(obj) {
if (Object.getOwnPropertyNames) {
return Object.getOwnPropertyNames(obj).length === 0;
} else {
var k;
for (k in obj) {
if (hasOwnProp(obj, k)) {
return false;
}
}
return true;
}
}
function isUndefined(input) {
return input === void 0;
}
function isNumber(input) {
return (
typeof input === 'number' ||
Object.prototype.toString.call(input) === '[object Number]'
);
}
function isDate(input) {
return (
input instanceof Date ||
Object.prototype.toString.call(input) === '[object Date]'
);
}
function map(arr, fn) {
var res = [],
i,
arrLen = arr.length;
for (i = 0; i < arrLen; ++i) {
res.push(fn(arr[i], i));
}
return res;
}
function extend(a, b) {
for (var i in b) {
if (hasOwnProp(b, i)) {
a[i] = b[i];
}
}
if (hasOwnProp(b, 'toString')) {
a.toString = b.toString;
}
if (hasOwnProp(b, 'valueOf')) {
a.valueOf = b.valueOf;
}
return a;
}
function createUTC(input, format, locale, strict) {
return createLocalOrUTC(input, format, locale, strict, true).utc();
}
function defaultParsingFlags() {
// We need to deep clone this object.
return {
empty: false,
unusedTokens: [],
unusedInput: [],
overflow: -2,
charsLeftOver: 0,
nullInput: false,
invalidEra: null,
invalidMonth: null,
invalidFormat: false,
userInvalidated: false,
iso: false,
parsedDateParts: [],
era: null,
meridiem: null,
rfc2822: false,
weekdayMismatch: false,
};
}
function getParsingFlags(m) {
if (m._pf == null) {
m._pf = defaultParsingFlags();
}
return m._pf;
}
var some;
if (Array.prototype.some) {
some = Array.prototype.some;
} else {
some = function (fun) {
var t = Object(this),
len = t.length >>> 0,
i;
for (i = 0; i < len; i++) {
if (i in t && fun.call(this, t[i], i, t)) {
return true;
}
}
return false;
};
}
function isValid(m) {
if (m._isValid == null) {
var flags = getParsingFlags(m),
parsedParts = some.call(flags.parsedDateParts, function (i) {
return i != null;
}),
isNowValid =
!isNaN(m._d.getTime()) &&
flags.overflow < 0 &&
!flags.empty &&
!flags.invalidEra &&
!flags.invalidMonth &&
!flags.invalidWeekday &&
!flags.weekdayMismatch &&
!flags.nullInput &&
!flags.invalidFormat &&
!flags.userInvalidated &&
(!flags.meridiem || (flags.meridiem && parsedParts));
if (m._strict) {
isNowValid =
isNowValid &&
flags.charsLeftOver === 0 &&
flags.unusedTokens.length === 0 &&
flags.bigHour === undefined;
}
if (Object.isFrozen == null || !Object.isFrozen(m)) {
m._isValid = isNowValid;
} else {
return isNowValid;
}
}
return m._isValid;
}
function createInvalid(flags) {
var m = createUTC(NaN);
if (flags != null) {
extend(getParsingFlags(m), flags);
} else {
getParsingFlags(m).userInvalidated = true;
}
return m;
}
// Plugins that add properties should also add the key here (null value),
// so we can properly clone ourselves.
var momentProperties = (hooks.momentProperties = []),
updateInProgress = false;
function copyConfig(to, from) {
var i,
prop,
val,
momentPropertiesLen = momentProperties.length;
if (!isUndefined(from._isAMomentObject)) {
to._isAMomentObject = from._isAMomentObject;
}
if (!isUndefined(from._i)) {
to._i = from._i;
}
if (!isUndefined(from._f)) {
to._f = from._f;
}
if (!isUndefined(from._l)) {
to._l = from._l;
}
if (!isUndefined(from._strict)) {
to._strict = from._strict;
}
if (!isUndefined(from._tzm)) {
to._tzm = from._tzm;
}
if (!isUndefined(from._isUTC)) {
to._isUTC = from._isUTC;
}
if (!isUndefined(from._offset)) {
to._offset = from._offset;
}
if (!isUndefined(from._pf)) {
to._pf = getParsingFlags(from);
}
if (!isUndefined(from._locale)) {
to._locale = from._locale;
}
if (momentPropertiesLen > 0) {
for (i = 0; i < momentPropertiesLen; i++) {
prop = momentProperties[i];
val = from[prop];
if (!isUndefined(val)) {
to[prop] = val;
}
}
}
return to;
}
// Moment prototype object
function Moment(config) {
copyConfig(this, config);
this._d = new Date(config._d != null ? config._d.getTime() : NaN);
if (!this.isValid()) {
this._d = new Date(NaN);
}
// Prevent infinite loop in case updateOffset creates new moment
// objects.
if (updateInProgress === false) {
updateInProgress = true;
hooks.updateOffset(this);
updateInProgress = false;
}
}
function isMoment(obj) {
return (
obj instanceof Moment || (obj != null && obj._isAMomentObject != null)
);
}
function warn(msg) {
if (
hooks.suppressDeprecationWarnings === false &&
typeof console !== 'undefined' &&
console.warn
) {
console.warn('Deprecation warning: ' + msg);
}
}
function deprecate(msg, fn) {
var firstTime = true;
return extend(function () {
if (hooks.deprecationHandler != null) {
hooks.deprecationHandler(null, msg);
}
if (firstTime) {
var args = [],
arg,
i,
key,
argLen = arguments.length;
for (i = 0; i < argLen; i++) {
arg = '';
if (typeof arguments[i] === 'object') {
arg += '\n[' + i + '] ';
for (key in arguments[0]) {
if (hasOwnProp(arguments[0], key)) {
arg += key + ': ' + arguments[0][key] + ', ';
}
}
arg = arg.slice(0, -2); // Remove trailing comma and space
} else {
arg = arguments[i];
}
args.push(arg);
}
warn(
msg +
'\nArguments: ' +
Array.prototype.slice.call(args).join('') +
'\n' +
new Error().stack
);
firstTime = false;
}
return fn.apply(this, arguments);
}, fn);
}
var deprecations = {};
function deprecateSimple(name, msg) {
if (hooks.deprecationHandler != null) {
hooks.deprecationHandler(name, msg);
}
if (!deprecations[name]) {
warn(msg);
deprecations[name] = true;
}
}
hooks.suppressDeprecationWarnings = false;
hooks.deprecationHandler = null;
function isFunction(input) {
return (
(typeof Function !== 'undefined' && input instanceof Function) ||
Object.prototype.toString.call(input) === '[object Function]'
);
}
function set(config) {
var prop, i;
for (i in config) {
if (hasOwnProp(config, i)) {
prop = config[i];
if (isFunction(prop)) {
this[i] = prop;
} else {
this['_' + i] = prop;
}
}
}
this._config = config;
// Lenient ordinal parsing accepts just a number in addition to
// number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
// TODO: Remove "ordinalParse" fallback in next major release.
this._dayOfMonthOrdinalParseLenient = new RegExp(
(this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +
'|' +
/\d{1,2}/.source
);
}
function mergeConfigs(parentConfig, childConfig) {
var res = extend({}, parentConfig),
prop;
for (prop in childConfig) {
if (hasOwnProp(childConfig, prop)) {
if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
res[prop] = {};
extend(res[prop], parentConfig[prop]);
extend(res[prop], childConfig[prop]);
} else if (childConfig[prop] != null) {
res[prop] = childConfig[prop];
} else {
delete res[prop];
}
}
}
for (prop in parentConfig) {
if (
hasOwnProp(parentConfig, prop) &&
!hasOwnProp(childConfig, prop) &&
isObject(parentConfig[prop])
) {
// make sure changes to properties don't modify parent config
res[prop] = extend({}, res[prop]);
}
}
return res;
}
function Locale(config) {
if (config != null) {
this.set(config);
}
}
var keys;
if (Object.keys) {
keys = Object.keys;
} else {
keys = function (obj) {
var i,
res = [];
for (i in obj) {
if (hasOwnProp(obj, i)) {
res.push(i);
}
}
return res;
};
}
var defaultCalendar = {
sameDay: '[Today at] LT',
nextDay: '[Tomorrow at] LT',
nextWeek: 'dddd [at] LT',
lastDay: '[Yesterday at] LT',
lastWeek: '[Last] dddd [at] LT',
sameElse: 'L',
};
function calendar(key, mom, now) {
var output = this._calendar[key] || this._calendar['sameElse'];
return isFunction(output) ? output.call(mom, now) : output;
}
function zeroFill(number, targetLength, forceSign) {
var absNumber = '' + Math.abs(number),
zerosToFill = targetLength - absNumber.length,
sign = number >= 0;
return (
(sign ? (forceSign ? '+' : '') : '-') +
Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) +
absNumber
);
}
var formattingTokens =
/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,
localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,
formatFunctions = {},
formatTokenFunctions = {};
// token: 'M'
// padded: ['MM', 2]
// ordinal: 'Mo'
// callback: function () { this.month() + 1 }
function addFormatToken(token, padded, ordinal, callback) {
var func = callback;
if (typeof callback === 'string') {
func = function () {
return this[callback]();
};
}
if (token) {
formatTokenFunctions[token] = func;
}
if (padded) {
formatTokenFunctions[padded[0]] = function () {
return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
};
}
if (ordinal) {
formatTokenFunctions[ordinal] = function () {
return this.localeData().ordinal(
func.apply(this, arguments),
token
);
};
}
}
function removeFormattingTokens(input) {
if (input.match(/\[[\s\S]/)) {
return input.replace(/^\[|\]$/g, '');
}
return input.replace(/\\/g, '');
}
function makeFormatFunction(format) {
var array = format.match(formattingTokens),
i,
length;
for (i = 0, length = array.length; i < length; i++) {
if (formatTokenFunctions[array[i]]) {
array[i] = formatTokenFunctions[array[i]];
} else {
array[i] = removeFormattingTokens(array[i]);
}
}
return function (mom) {
var output = '',
i;
for (i = 0; i < length; i++) {
output += isFunction(array[i])
? array[i].call(mom, format)
: array[i];
}
return output;
};
}
// format date using native date object
function formatMoment(m, format) {
if (!m.isValid()) {
return m.localeData().invalidDate();
}
format = expandFormat(format, m.localeData());
formatFunctions[format] =
formatFunctions[format] || makeFormatFunction(format);
return formatFunctions[format](m);
}
function expandFormat(format, locale) {
var i = 5;
function replaceLongDateFormatTokens(input) {
return locale.longDateFormat(input) || input;
}
localFormattingTokens.lastIndex = 0;
while (i >= 0 && localFormattingTokens.test(format)) {
format = format.replace(
localFormattingTokens,
replaceLongDateFormatTokens
);
localFormattingTokens.lastIndex = 0;
i -= 1;
}
return format;
}
var defaultLongDateFormat = {
LTS: 'h:mm:ss A',
LT: 'h:mm A',
L: 'MM/DD/YYYY',
LL: 'MMMM D, YYYY',
LLL: 'MMMM D, YYYY h:mm A',
LLLL: 'dddd, MMMM D, YYYY h:mm A',
};
function longDateFormat(key) {
var format = this._longDateFormat[key],
formatUpper = this._longDateFormat[key.toUpperCase()];
if (format || !formatUpper) {
return format;
}
this._longDateFormat[key] = formatUpper
.match(formattingTokens)
.map(function (tok) {
if (
tok === 'MMMM' ||
tok === 'MM' ||
tok === 'DD' ||
tok === 'dddd'
) {
return tok.slice(1);
}
return tok;
})
.join('');
return this._longDateFormat[key];
}
var defaultInvalidDate = 'Invalid date';
function invalidDate() {
return this._invalidDate;
}
var defaultOrdinal = '%d',
defaultDayOfMonthOrdinalParse = /\d{1,2}/;
function ordinal(number) {
return this._ordinal.replace('%d', number);
}
var defaultRelativeTime = {
future: 'in %s',
past: '%s ago',
s: 'a few seconds',
ss: '%d seconds',
m: 'a minute',
mm: '%d minutes',
h: 'an hour',
hh: '%d hours',
d: 'a day',
dd: '%d days',
w: 'a week',
ww: '%d weeks',
M: 'a month',
MM: '%d months',
y: 'a year',
yy: '%d years',
};
function relativeTime(number, withoutSuffix, string, isFuture) {
var output = this._relativeTime[string];
return isFunction(output)
? output(number, withoutSuffix, string, isFuture)
: output.replace(/%d/i, number);
}
function pastFuture(diff, output) {
var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
return isFunction(format) ? format(output) : format.replace(/%s/i, output);
}
var aliases = {};
function addUnitAlias(unit, shorthand) {
var lowerCase = unit.toLowerCase();
aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
}
function normalizeUnits(units) {
return typeof units === 'string'
? aliases[units] || aliases[units.toLowerCase()]
: undefined;
}
function normalizeObjectUnits(inputObject) {
var normalizedInput = {},
normalizedProp,
prop;
for (prop in inputObject) {
if (hasOwnProp(inputObject, prop)) {
normalizedProp = normalizeUnits(prop);
if (normalizedProp) {
normalizedInput[normalizedProp] = inputObject[prop];
}
}
}
return normalizedInput;
}
var priorities = {};
function addUnitPriority(unit, priority) {
priorities[unit] = priority;
}
function getPrioritizedUnits(unitsObj) {
var units = [],
u;
for (u in unitsObj) {
if (hasOwnProp(unitsObj, u)) {
units.push({ unit: u, priority: priorities[u] });
}
}
units.sort(function (a, b) {
return a.priority - b.priority;
});
return units;
}
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
function absFloor(number) {
if (number < 0) {
// -0 -> 0
return Math.ceil(number) || 0;
} else {
return Math.floor(number);
}
}
function toInt(argumentForCoercion) {
var coercedNumber = +argumentForCoercion,
value = 0;
if (coercedNumber !== 0 && isFinite(coercedNumber)) {
value = absFloor(coercedNumber);
}
return value;
}
function makeGetSet(unit, keepTime) {
return function (value) {
if (value != null) {
set$1(this, unit, value);
hooks.updateOffset(this, keepTime);
return this;
} else {
return get(this, unit);
}
};
}
function get(mom, unit) {
return mom.isValid()
? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]()
: NaN;
}
function set$1(mom, unit, value) {
if (mom.isValid() && !isNaN(value)) {
if (
unit === 'FullYear' &&
isLeapYear(mom.year()) &&
mom.month() === 1 &&
mom.date() === 29
) {
value = toInt(value);
mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](
value,
mom.month(),
daysInMonth(value, mom.month())
);
} else {
mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
}
}
}
// MOMENTS
function stringGet(units) {
units = normalizeUnits(units);
if (isFunction(this[units])) {
return this[units]();
}
return this;
}
function stringSet(units, value) {
if (typeof units === 'object') {
units = normalizeObjectUnits(units);
var prioritized = getPrioritizedUnits(units),
i,
prioritizedLen = prioritized.length;
for (i = 0; i < prioritizedLen; i++) {
this[prioritized[i].unit](units[prioritized[i].unit]);
}
} else {
units = normalizeUnits(units);
if (isFunction(this[units])) {
return this[units](value);
}
}
return this;
}
var match1 = /\d/, // 0 - 9
match2 = /\d\d/, // 00 - 99
match3 = /\d{3}/, // 000 - 999
match4 = /\d{4}/, // 0000 - 9999
match6 = /[+-]?\d{6}/, // -999999 - 999999
match1to2 = /\d\d?/, // 0 - 99
match3to4 = /\d\d\d\d?/, // 999 - 9999
match5to6 = /\d\d\d\d\d\d?/, // 99999 - 999999
match1to3 = /\d{1,3}/, // 0 - 999
match1to4 = /\d{1,4}/, // 0 - 9999
match1to6 = /[+-]?\d{1,6}/, // -999999 - 999999
matchUnsigned = /\d+/, // 0 - inf
matchSigned = /[+-]?\d+/, // -inf - inf
matchOffset = /Z|[+-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, // +00 -00 +00:00 -00:00 +0000 -0000 or Z
matchTimestamp = /[+-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
// any word (or two) characters or numbers including two/three word month in arabic.
// includes scottish gaelic two word and hyphenated months
matchWord =
/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,
regexes;
regexes = {};
function addRegexToken(token, regex, strictRegex) {
regexes[token] = isFunction(regex)
? regex
: function (isStrict, localeData) {
return isStrict && strictRegex ? strictRegex : regex;
};
}
function getParseRegexForToken(token, config) {
if (!hasOwnProp(regexes, token)) {
return new RegExp(unescapeFormat(token));
}
return regexes[token](config._strict, config._locale);
}
// Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
function unescapeFormat(s) {
return regexEscape(
s
.replace('\\', '')
.replace(
/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,
function (matched, p1, p2, p3, p4) {
return p1 || p2 || p3 || p4;
}
)
);
}
function regexEscape(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var tokens = {};
function addParseToken(token, callback) {
var i,
func = callback,
tokenLen;
if (typeof token === 'string') {
token = [token];
}
if (isNumber(callback)) {
func = function (input, array) {
array[callback] = toInt(input);
};
}
tokenLen = token.length;
for (i = 0; i < tokenLen; i++) {
tokens[token[i]] = func;
}
}
function addWeekParseToken(token, callback) {
addParseToken(token, function (input, array, config, token) {
config._w = config._w || {};
callback(input, config._w, config, token);
});
}
function addTimeToArrayFromToken(token, input, config) {
if (input != null && hasOwnProp(tokens, token)) {
tokens[token](input, config._a, config, token);
}
}
var YEAR = 0,
MONTH = 1,
DATE = 2,
HOUR = 3,
MINUTE = 4,
SECOND = 5,
MILLISECOND = 6,
WEEK = 7,
WEEKDAY = 8;
function mod(n, x) {
return ((n % x) + x) % x;
}
var indexOf;
if (Array.prototype.indexOf) {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function (o) {
// I know
var i;
for (i = 0; i < this.length; ++i) {
if (this[i] === o) {
return i;
}
}
return -1;
};
}
function daysInMonth(year, month) {
if (isNaN(year) || isNaN(month)) {
return NaN;
}
var modMonth = mod(month, 12);
year += (month - modMonth) / 12;
return modMonth === 1
? isLeapYear(year)
? 29
: 28
: 31 - ((modMonth % 7) % 2);
}
// FORMATTING
addFormatToken('M', ['MM', 2], 'Mo', function () {
return this.month() + 1;
});
addFormatToken('MMM', 0, 0, function (format) {
return this.localeData().monthsShort(this, format);
});
addFormatToken('MMMM', 0, 0, function (format) {
return this.localeData().months(this, format);
});
// ALIASES
addUnitAlias('month', 'M');
// PRIORITY
addUnitPriority('month', 8);
// PARSING
addRegexToken('M', match1to2);
addRegexToken('MM', match1to2, match2);
addRegexToken('MMM', function (isStrict, locale) {
return locale.monthsShortRegex(isStrict);
});
addRegexToken('MMMM', function (isStrict, locale) {
return locale.monthsRegex(isStrict);
});
addParseToken(['M', 'MM'], function (input, array) {
array[MONTH] = toInt(input) - 1;
});
addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
var month = config._locale.monthsParse(input, token, config._strict);
// if we didn't find a month name, mark the date as invalid.
if (month != null) {
array[MONTH] = month;
} else {
getParsingFlags(config).invalidMonth = input;
}
});
// LOCALES
var defaultLocaleMonths =
'January_February_March_April_May_June_July_August_September_October_November_December'.split(
'_'
),
defaultLocaleMonthsShort =
'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,
defaultMonthsShortRegex = matchWord,
defaultMonthsRegex = matchWord;
function localeMonths(m, format) {
if (!m) {
return isArray(this._months)
? this._months
: this._months['standalone'];
}
return isArray(this._months)
? this._months[m.month()]
: this._months[
(this._months.isFormat || MONTHS_IN_FORMAT).test(format)
? 'format'
: 'standalone'
][m.month()];
}
function localeMonthsShort(m, format) {
if (!m) {
return isArray(this._monthsShort)
? this._monthsShort
: this._monthsShort['standalone'];
}
return isArray(this._monthsShort)
? this._monthsShort[m.month()]
: this._monthsShort[
MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'
][m.month()];
}
function handleStrictParse(monthName, format, strict) {
var i,
ii,
mom,
llc = monthName.toLocaleLowerCase();
if (!this._monthsParse) {
// this is not used
this._monthsParse = [];
this._longMonthsParse = [];
this._shortMonthsParse = [];
for (i = 0; i < 12; ++i) {
mom = createUTC([2000, i]);
this._shortMonthsParse[i] = this.monthsShort(
mom,
''
).toLocaleLowerCase();
this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
}
}
if (strict) {
if (format === 'MMM') {
ii = indexOf.call(this._shortMonthsParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._longMonthsParse, llc);
return ii !== -1 ? ii : null;
}
} else {
if (format === 'MMM') {
ii = indexOf.call(this._shortMonthsParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._longMonthsParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._longMonthsParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._shortMonthsParse, llc);
return ii !== -1 ? ii : null;
}
}
}
function localeMonthsParse(monthName, format, strict) {
var i, mom, regex;
if (this._monthsParseExact) {
return handleStrictParse.call(this, monthName, format, strict);
}
if (!this._monthsParse) {
this._monthsParse = [];
this._longMonthsParse = [];
this._shortMonthsParse = [];
}
// TODO: add sorting
// Sorting makes sure if one month (or abbr) is a prefix of another
// see sorting in computeMonthsParse
for (i = 0; i < 12; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, i]);
if (strict && !this._longMonthsParse[i]) {
this._longMonthsParse[i] = new RegExp(
'^' + this.months(mom, '').replace('.', '') + '$',
'i'
);
this._shortMonthsParse[i] = new RegExp(
'^' + this.monthsShort(mom, '').replace('.', '') + '$',
'i'
);
}
if (!strict && !this._monthsParse[i]) {
regex =
'^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
}
// test the regex
if (
strict &&
format === 'MMMM' &&
this._longMonthsParse[i].test(monthName)
) {
return i;
} else if (
strict &&
format === 'MMM' &&
this._shortMonthsParse[i].test(monthName)
) {
return i;
} else if (!strict && this._monthsParse[i].test(monthName)) {
return i;
}
}
}
// MOMENTS
function setMonth(mom, value) {
var dayOfMonth;
if (!mom.isValid()) {
// No op
return mom;
}
if (typeof value === 'string') {
if (/^\d+$/.test(value)) {
value = toInt(value);
} else {
value = mom.localeData().monthsParse(value);
// TODO: Another silent failure?
if (!isNumber(value)) {
return mom;
}
}
}
dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
return mom;
}
function getSetMonth(value) {
if (value != null) {
setMonth(this, value);
hooks.updateOffset(this, true);
return this;
} else {
return get(this, 'Month');
}
}
function getDaysInMonth() {
return daysInMonth(this.year(), this.month());
}
function monthsShortRegex(isStrict) {
if (this._monthsParseExact) {
if (!hasOwnProp(this, '_monthsRegex')) {
computeMonthsParse.call(this);
}
if (isStrict) {
return this._monthsShortStrictRegex;
} else {
return this._monthsShortRegex;
}
} else {
if (!hasOwnProp(this, '_monthsShortRegex')) {
this._monthsShortRegex = defaultMonthsShortRegex;
}
return this._monthsShortStrictRegex && isStrict
? this._monthsShortStrictRegex
: this._monthsShortRegex;
}
}
function monthsRegex(isStrict) {
if (this._monthsParseExact) {
if (!hasOwnProp(this, '_monthsRegex')) {
computeMonthsParse.call(this);
}
if (isStrict) {
return this._monthsStrictRegex;
} else {
return this._monthsRegex;
}
} else {
if (!hasOwnProp(this, '_monthsRegex')) {
this._monthsRegex = defaultMonthsRegex;
}
return this._monthsStrictRegex && isStrict
? this._monthsStrictRegex
: this._monthsRegex;
}
}
function computeMonthsParse() {
function cmpLenRev(a, b) {
return b.length - a.length;
}
var shortPieces = [],
longPieces = [],
mixedPieces = [],
i,
mom;
for (i = 0; i < 12; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, i]);
shortPieces.push(this.monthsShort(mom, ''));
longPieces.push(this.months(mom, ''));
mixedPieces.push(this.months(mom, ''));
mixedPieces.push(this.monthsShort(mom, ''));
}
// Sorting makes sure if one month (or abbr) is a prefix of another it
// will match the longer piece.
shortPieces.sort(cmpLenRev);
longPieces.sort(cmpLenRev);
mixedPieces.sort(cmpLenRev);
for (i = 0; i < 12; i++) {
shortPieces[i] = regexEscape(shortPieces[i]);
longPieces[i] = regexEscape(longPieces[i]);
}
for (i = 0; i < 24; i++) {
mixedPieces[i] = regexEscape(mixedPieces[i]);
}
this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
this._monthsShortRegex = this._monthsRegex;
this._monthsStrictRegex = new RegExp(
'^(' + longPieces.join('|') + ')',
'i'
);
this._monthsShortStrictRegex = new RegExp(
'^(' + shortPieces.join('|') + ')',
'i'
);
}
// FORMATTING
addFormatToken('Y', 0, 0, function () {
var y = this.year();
return y <= 9999 ? zeroFill(y, 4) : '+' + y;
});
addFormatToken(0, ['YY', 2], 0, function () {
return this.year() % 100;
});
addFormatToken(0, ['YYYY', 4], 0, 'year');
addFormatToken(0, ['YYYYY', 5], 0, 'year');
addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
// ALIASES
addUnitAlias('year', 'y');
// PRIORITIES
addUnitPriority('year', 1);
// PARSING
addRegexToken('Y', matchSigned);
addRegexToken('YY', match1to2, match2);
addRegexToken('YYYY', match1to4, match4);
addRegexToken('YYYYY', match1to6, match6);
addRegexToken('YYYYYY', match1to6, match6);
addParseToken(['YYYYY', 'YYYYYY'], YEAR);
addParseToken('YYYY', function (input, array) {
array[YEAR] =
input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
});
addParseToken('YY', function (input, array) {
array[YEAR] = hooks.parseTwoDigitYear(input);
});
addParseToken('Y', function (input, array) {
array[YEAR] = parseInt(input, 10);
});
// HELPERS
function daysInYear(year) {
return isLeapYear(year) ? 366 : 365;
}
// HOOKS
hooks.parseTwoDigitYear = function (input) {
return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
};
// MOMENTS
var getSetYear = makeGetSet('FullYear', true);
function getIsLeapYear() {
return isLeapYear(this.year());
}
function createDate(y, m, d, h, M, s, ms) {
// can't just apply() to create a date:
// https://stackoverflow.com/q/181348
var date;
// the date constructor remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0) {
// preserve leap years using a full 400 year cycle, then reset
date = new Date(y + 400, m, d, h, M, s, ms);
if (isFinite(date.getFullYear())) {
date.setFullYear(y);
}
} else {
date = new Date(y, m, d, h, M, s, ms);
}
return date;
}
function createUTCDate(y) {
var date, args;
// the Date.UTC function remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0) {
args = Array.prototype.slice.call(arguments);
// preserve leap years using a full 400 year cycle, then reset
args[0] = y + 400;
date = new Date(Date.UTC.apply(null, args));
if (isFinite(date.getUTCFullYear())) {
date.setUTCFullYear(y);
}
} else {
date = new Date(Date.UTC.apply(null, arguments));
}
return date;
}
// start-of-first-week - start-of-year
function firstWeekOffset(year, dow, doy) {
var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
fwd = 7 + dow - doy,
// first-week day local weekday -- which local weekday is fwd
fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
return -fwdlw + fwd - 1;
}
// https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
var localWeekday = (7 + weekday - dow) % 7,
weekOffset = firstWeekOffset(year, dow, doy),
dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
resYear,
resDayOfYear;
if (dayOfYear <= 0) {
resYear = year - 1;
resDayOfYear = daysInYear(resYear) + dayOfYear;
} else if (dayOfYear > daysInYear(year)) {
resYear = year + 1;
resDayOfYear = dayOfYear - daysInYear(year);
} else {
resYear = year;
resDayOfYear = dayOfYear;
}
return {
year: resYear,
dayOfYear: resDayOfYear,
};
}
function weekOfYear(mom, dow, doy) {
var weekOffset = firstWeekOffset(mom.year(), dow, doy),
week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
resWeek,
resYear;
if (week < 1) {
resYear = mom.year() - 1;
resWeek = week + weeksInYear(resYear, dow, doy);
} else if (week > weeksInYear(mom.year(), dow, doy)) {
resWeek = week - weeksInYear(mom.year(), dow, doy);
resYear = mom.year() + 1;
} else {
resYear = mom.year();
resWeek = week;
}
return {
week: resWeek,
year: resYear,
};
}
function weeksInYear(year, dow, doy) {
var weekOffset = firstWeekOffset(year, dow, doy),
weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
}
// FORMATTING
addFormatToken('w', ['ww', 2], 'wo', 'week');
addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
// ALIASES
addUnitAlias('week', 'w');
addUnitAlias('isoWeek', 'W');
// PRIORITIES
addUnitPriority('week', 5);
addUnitPriority('isoWeek', 5);
// PARSING
addRegexToken('w', match1to2);
addRegexToken('ww', match1to2, match2);
addRegexToken('W', match1to2);
addRegexToken('WW', match1to2, match2);
addWeekParseToken(
['w', 'ww', 'W', 'WW'],
function (input, week, config, token) {
week[token.substr(0, 1)] = toInt(input);
}
);
// HELPERS
// LOCALES
function localeWeek(mom) {
return weekOfYear(mom, this._week.dow, this._week.doy).week;
}
var defaultLocaleWeek = {
dow: 0, // Sunday is the first day of the week.
doy: 6, // The week that contains Jan 6th is the first week of the year.
};
function localeFirstDayOfWeek() {
return this._week.dow;
}
function localeFirstDayOfYear() {
return this._week.doy;
}
// MOMENTS
function getSetWeek(input) {
var week = this.localeData().week(this);
return input == null ? week : this.add((input - week) * 7, 'd');
}
function getSetISOWeek(input) {
var week = weekOfYear(this, 1, 4).week;
return input == null ? week : this.add((input - week) * 7, 'd');
}
// FORMATTING
addFormatToken('d', 0, 'do', 'day');
addFormatToken('dd', 0, 0, function (format) {
return this.localeData().weekdaysMin(this, format);
});
addFormatToken('ddd', 0, 0, function (format) {
return this.localeData().weekdaysShort(this, format);
});
addFormatToken('dddd', 0, 0, function (format) {
return this.localeData().weekdays(this, format);
});
addFormatToken('e', 0, 0, 'weekday');
addFormatToken('E', 0, 0, 'isoWeekday');
// ALIASES
addUnitAlias('day', 'd');
addUnitAlias('weekday', 'e');
addUnitAlias('isoWeekday', 'E');
// PRIORITY
addUnitPriority('day', 11);
addUnitPriority('weekday', 11);
addUnitPriority('isoWeekday', 11);
// PARSING
addRegexToken('d', match1to2);
addRegexToken('e', match1to2);
addRegexToken('E', match1to2);
addRegexToken('dd', function (isStrict, locale) {
return locale.weekdaysMinRegex(isStrict);
});
addRegexToken('ddd', function (isStrict, locale) {
return locale.weekdaysShortRegex(isStrict);
});
addRegexToken('dddd', function (isStrict, locale) {
return locale.weekdaysRegex(isStrict);
});
addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
var weekday = config._locale.weekdaysParse(input, token, config._strict);
// if we didn't get a weekday name, mark the date as invalid
if (weekday != null) {
week.d = weekday;
} else {
getParsingFlags(config).invalidWeekday = input;
}
});
addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
week[token] = toInt(input);
});
// HELPERS
function parseWeekday(input, locale) {
if (typeof input !== 'string') {
return input;
}
if (!isNaN(input)) {
return parseInt(input, 10);
}
input = locale.weekdaysParse(input);
if (typeof input === 'number') {
return input;
}
return null;
}
function parseIsoWeekday(input, locale) {
if (typeof input === 'string') {
return locale.weekdaysParse(input) % 7 || 7;
}
return isNaN(input) ? null : input;
}
// LOCALES
function shiftWeekdays(ws, n) {
return ws.slice(n, 7).concat(ws.slice(0, n));
}
var defaultLocaleWeekdays =
'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
defaultWeekdaysRegex = matchWord,
defaultWeekdaysShortRegex = matchWord,
defaultWeekdaysMinRegex = matchWord;
function localeWeekdays(m, format) {
var weekdays = isArray(this._weekdays)
? this._weekdays
: this._weekdays[
m && m !== true && this._weekdays.isFormat.test(format)
? 'format'
: 'standalone'
];
return m === true
? shiftWeekdays(weekdays, this._week.dow)
: m
? weekdays[m.day()]
: weekdays;
}
function localeWeekdaysShort(m) {
return m === true
? shiftWeekdays(this._weekdaysShort, this._week.dow)
: m
? this._weekdaysShort[m.day()]
: this._weekdaysShort;
}
function localeWeekdaysMin(m) {
return m === true
? shiftWeekdays(this._weekdaysMin, this._week.dow)
: m
? this._weekdaysMin[m.day()]
: this._weekdaysMin;
}
function handleStrictParse$1(weekdayName, format, strict) {
var i,
ii,
mom,
llc = weekdayName.toLocaleLowerCase();
if (!this._weekdaysParse) {
this._weekdaysParse = [];
this._shortWeekdaysParse = [];
this._minWeekdaysParse = [];
for (i = 0; i < 7; ++i) {
mom = createUTC([2000, 1]).day(i);
this._minWeekdaysParse[i] = this.weekdaysMin(
mom,
''
).toLocaleLowerCase();
this._shortWeekdaysParse[i] = this.weekdaysShort(
mom,
''
).toLocaleLowerCase();
this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
}
}
if (strict) {
if (format === 'dddd') {
ii = indexOf.call(this._weekdaysParse, llc);
return ii !== -1 ? ii : null;
} else if (format === 'ddd') {
ii = indexOf.call(this._shortWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
}
} else {
if (format === 'dddd') {
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._shortWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else if (format === 'ddd') {
ii = indexOf.call(this._shortWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._minWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._shortWeekdaysParse, llc);
return ii !== -1 ? ii : null;
}
}
}
function localeWeekdaysParse(weekdayName, format, strict) {
var i, mom, regex;
if (this._weekdaysParseExact) {
return handleStrictParse$1.call(this, weekdayName, format, strict);
}
if (!this._weekdaysParse) {
this._weekdaysParse = [];
this._minWeekdaysParse = [];
this._shortWeekdaysParse = [];
this._fullWeekdaysParse = [];
}
for (i = 0; i < 7; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, 1]).day(i);
if (strict && !this._fullWeekdaysParse[i]) {
this._fullWeekdaysParse[i] = new RegExp(
'^' + this.weekdays(mom, '').replace('.', '\\.?') + '$',
'i'
);
this._shortWeekdaysParse[i] = new RegExp(
'^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$',
'i'
);
this._minWeekdaysParse[i] = new RegExp(
'^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$',
'i'
);
}
if (!this._weekdaysParse[i]) {
regex =
'^' +
this.weekdays(mom, '') +
'|^' +
this.weekdaysShort(mom, '') +
'|^' +
this.weekdaysMin(mom, '');
this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
}
// test the regex
if (
strict &&
format === 'dddd' &&
this._fullWeekdaysParse[i].test(weekdayName)
) {
return i;
} else if (
strict &&
format === 'ddd' &&
this._shortWeekdaysParse[i].test(weekdayName)
) {
return i;
} else if (
strict &&
format === 'dd' &&
this._minWeekdaysParse[i].test(weekdayName)
) {
return i;
} else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
return i;
}
}
}
// MOMENTS
function getSetDayOfWeek(input) {
if (!this.isValid()) {
return input != null ? this : NaN;
}
var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
if (input != null) {
input = parseWeekday(input, this.localeData());
return this.add(input - day, 'd');
} else {
return day;
}
}
function getSetLocaleDayOfWeek(input) {
if (!this.isValid()) {
return input != null ? this : NaN;
}
var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
return input == null ? weekday : this.add(input - weekday, 'd');
}
function getSetISODayOfWeek(input) {
if (!this.isValid()) {
return input != null ? this : NaN;
}
// behaves the same as moment#day except
// as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
// as a setter, sunday should belong to the previous week.
if (input != null) {
var weekday = parseIsoWeekday(input, this.localeData());
return this.day(this.day() % 7 ? weekday : weekday - 7);
} else {
return this.day() || 7;
}
}
function weekdaysRegex(isStrict) {
if (this._weekdaysParseExact) {
if (!hasOwnProp(this, '_weekdaysRegex')) {
computeWeekdaysParse.call(this);
}
if (isStrict) {
return this._weekdaysStrictRegex;
} else {
return this._weekdaysRegex;
}
} else {
if (!hasOwnProp(this, '_weekdaysRegex')) {
this._weekdaysRegex = defaultWeekdaysRegex;
}
return this._weekdaysStrictRegex && isStrict
? this._weekdaysStrictRegex
: this._weekdaysRegex;
}
}
function weekdaysShortRegex(isStrict) {
if (this._weekdaysParseExact) {
if (!hasOwnProp(this, '_weekdaysRegex')) {
computeWeekdaysParse.call(this);
}
if (isStrict) {
return this._weekdaysShortStrictRegex;
} else {
return this._weekdaysShortRegex;
}
} else {
if (!hasOwnProp(this, '_weekdaysShortRegex')) {
this._weekdaysShortRegex = defaultWeekdaysShortRegex;
}
return this._weekdaysShortStrictRegex && isStrict
? this._weekdaysShortStrictRegex
: this._weekdaysShortRegex;
}
}
function weekdaysMinRegex(isStrict) {
if (this._weekdaysParseExact) {
if (!hasOwnProp(this, '_weekdaysRegex')) {
computeWeekdaysParse.call(this);
}
if (isStrict) {
return this._weekdaysMinStrictRegex;
} else {
return this._weekdaysMinRegex;
}
} else {
if (!hasOwnProp(this, '_weekdaysMinRegex')) {
this._weekdaysMinRegex = defaultWeekdaysMinRegex;
}
return this._weekdaysMinStrictRegex && isStrict
? this._weekdaysMinStrictRegex
: this._weekdaysMinRegex;
}
}
function computeWeekdaysParse() {
function cmpLenRev(a, b) {
return b.length - a.length;
}
var minPieces = [],
shortPieces = [],
longPieces = [],
mixedPieces = [],
i,
mom,
minp,
shortp,
longp;
for (i = 0; i < 7; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, 1]).day(i);
minp = regexEscape(this.weekdaysMin(mom, ''));
shortp = regexEscape(this.weekdaysShort(mom, ''));
longp = regexEscape(this.weekdays(mom, ''));
minPieces.push(minp);
shortPieces.push(shortp);
longPieces.push(longp);
mixedPieces.push(minp);
mixedPieces.push(shortp);
mixedPieces.push(longp);
}
// Sorting makes sure if one weekday (or abbr) is a prefix of another it
// will match the longer piece.
minPieces.sort(cmpLenRev);
shortPieces.sort(cmpLenRev);
longPieces.sort(cmpLenRev);
mixedPieces.sort(cmpLenRev);
this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
this._weekdaysShortRegex = this._weekdaysRegex;
this._weekdaysMinRegex = this._weekdaysRegex;
this._weekdaysStrictRegex = new RegExp(
'^(' + longPieces.join('|') + ')',
'i'
);
this._weekdaysShortStrictRegex = new RegExp(
'^(' + shortPieces.join('|') + ')',
'i'
);
this._weekdaysMinStrictRegex = new RegExp(
'^(' + minPieces.join('|') + ')',
'i'
);
}
// FORMATTING
function hFormat() {
return this.hours() % 12 || 12;
}
function kFormat() {
return this.hours() || 24;
}
addFormatToken('H', ['HH', 2], 0, 'hour');
addFormatToken('h', ['hh', 2], 0, hFormat);
addFormatToken('k', ['kk', 2], 0, kFormat);
addFormatToken('hmm', 0, 0, function () {
return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
});
addFormatToken('hmmss', 0, 0, function () {
return (
'' +
hFormat.apply(this) +
zeroFill(this.minutes(), 2) +
zeroFill(this.seconds(), 2)
);
});
addFormatToken('Hmm', 0, 0, function () {
return '' + this.hours() + zeroFill(this.minutes(), 2);
});
addFormatToken('Hmmss', 0, 0, function () {
return (
'' +
this.hours() +
zeroFill(this.minutes(), 2) +
zeroFill(this.seconds(), 2)
);
});
function meridiem(token, lowercase) {
addFormatToken(token, 0, 0, function () {
return this.localeData().meridiem(
this.hours(),
this.minutes(),
lowercase
);
});
}
meridiem('a', true);
meridiem('A', false);
// ALIASES
addUnitAlias('hour', 'h');
// PRIORITY
addUnitPriority('hour', 13);
// PARSING
function matchMeridiem(isStrict, locale) {
return locale._meridiemParse;
}
addRegexToken('a', matchMeridiem);
addRegexToken('A', matchMeridiem);
addRegexToken('H', match1to2);
addRegexToken('h', match1to2);
addRegexToken('k', match1to2);
addRegexToken('HH', match1to2, match2);
addRegexToken('hh', match1to2, match2);
addRegexToken('kk', match1to2, match2);
addRegexToken('hmm', match3to4);
addRegexToken('hmmss', match5to6);
addRegexToken('Hmm', match3to4);
addRegexToken('Hmmss', match5to6);
addParseToken(['H', 'HH'], HOUR);
addParseToken(['k', 'kk'], function (input, array, config) {
var kInput = toInt(input);
array[HOUR] = kInput === 24 ? 0 : kInput;
});
addParseToken(['a', 'A'], function (input, array, config) {
config._isPm = config._locale.isPM(input);
config._meridiem = input;
});
addParseToken(['h', 'hh'], function (input, array, config) {
array[HOUR] = toInt(input);
getParsingFlags(config).bigHour = true;
});
addParseToken('hmm', function (input, array, config) {
var pos = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos));
array[MINUTE] = toInt(input.substr(pos));
getParsingFlags(config).bigHour = true;
});
addParseToken('hmmss', function (input, array, config) {
var pos1 = input.length - 4,
pos2 = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos1));
array[MINUTE] = toInt(input.substr(pos1, 2));
array[SECOND] = toInt(input.substr(pos2));
getParsingFlags(config).bigHour = true;
});
addParseToken('Hmm', function (input, array, config) {
var pos = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos));
array[MINUTE] = toInt(input.substr(pos));
});
addParseToken('Hmmss', function (input, array, config) {
var pos1 = input.length - 4,
pos2 = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos1));
array[MINUTE] = toInt(input.substr(pos1, 2));
array[SECOND] = toInt(input.substr(pos2));
});
// LOCALES
function localeIsPM(input) {
// IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
// Using charAt should be more compatible.
return (input + '').toLowerCase().charAt(0) === 'p';
}
var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i,
// Setting the hour should keep the time, because the user explicitly
// specified which hour they want. So trying to maintain the same hour (in
// a new timezone) makes sense. Adding/subtracting hours does not follow
// this rule.
getSetHour = makeGetSet('Hours', true);
function localeMeridiem(hours, minutes, isLower) {
if (hours > 11) {
return isLower ? 'pm' : 'PM';
} else {
return isLower ? 'am' : 'AM';
}
}
var baseConfig = {
calendar: defaultCalendar,
longDateFormat: defaultLongDateFormat,
invalidDate: defaultInvalidDate,
ordinal: defaultOrdinal,
dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
relativeTime: defaultRelativeTime,
months: defaultLocaleMonths,
monthsShort: defaultLocaleMonthsShort,
week: defaultLocaleWeek,
weekdays: defaultLocaleWeekdays,
weekdaysMin: defaultLocaleWeekdaysMin,
weekdaysShort: defaultLocaleWeekdaysShort,
meridiemParse: defaultLocaleMeridiemParse,
};
// internal storage for locale config files
var locales = {},
localeFamilies = {},
globalLocale;
function commonPrefix(arr1, arr2) {
var i,
minl = Math.min(arr1.length, arr2.length);
for (i = 0; i < minl; i += 1) {
if (arr1[i] !== arr2[i]) {
return i;
}
}
return minl;
}
function normalizeLocale(key) {
return key ? key.toLowerCase().replace('_', '-') : key;
}
// pick the locale from the array
// try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
// substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
function chooseLocale(names) {
var i = 0,
j,
next,
locale,
split;
while (i < names.length) {
split = normalizeLocale(names[i]).split('-');
j = split.length;
next = normalizeLocale(names[i + 1]);
next = next ? next.split('-') : null;
while (j > 0) {
locale = loadLocale(split.slice(0, j).join('-'));
if (locale) {
return locale;
}
if (
next &&
next.length >= j &&
commonPrefix(split, next) >= j - 1
) {
//the next array item is better than a shallower substring of this one
break;
}
j--;
}
i++;
}
return globalLocale;
}
function isLocaleNameSane(name) {
// Prevent names that look like filesystem paths, i.e contain '/' or '\'
return name.match('^[^/\\\\]*$') != null;
}
function loadLocale(name) {
var oldLocale = null,
aliasedRequire;
// TODO: Find a better way to register and load all the locales in Node
if (
locales[name] === undefined &&
typeof module !== 'undefined' &&
module &&
module.exports &&
isLocaleNameSane(name)
) {
try {
oldLocale = globalLocale._abbr;
aliasedRequire = require;
aliasedRequire('./locale/' + name);
getSetGlobalLocale(oldLocale);
} catch (e) {
// mark as not found to avoid repeating expensive file require call causing high CPU
// when trying to find en-US, en_US, en-us for every format call
locales[name] = null; // null means not found
}
}
return locales[name];
}
// This function will load locale and then set the global locale. If
// no arguments are passed in, it will simply return the current global
// locale key.
function getSetGlobalLocale(key, values) {
var data;
if (key) {
if (isUndefined(values)) {
data = getLocale(key);
} else {
data = defineLocale(key, values);
}
if (data) {
// moment.duration._locale = moment._locale = data;
globalLocale = data;
} else {
if (typeof console !== 'undefined' && console.warn) {
//warn user if arguments are passed but the locale could not be set
console.warn(
'Locale ' + key + ' not found. Did you forget to load it?'
);
}
}
}
return globalLocale._abbr;
}
function defineLocale(name, config) {
if (config !== null) {
var locale,
parentConfig = baseConfig;
config.abbr = name;
if (locales[name] != null) {
deprecateSimple(
'defineLocaleOverride',
'use moment.updateLocale(localeName, config) to change ' +
'an existing locale. moment.defineLocale(localeName, ' +
'config) should only be used for creating a new locale ' +
'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.'
);
parentConfig = locales[name]._config;
} else if (config.parentLocale != null) {
if (locales[config.parentLocale] != null) {
parentConfig = locales[config.parentLocale]._config;
} else {
locale = loadLocale(config.parentLocale);
if (locale != null) {
parentConfig = locale._config;
} else {
if (!localeFamilies[config.parentLocale]) {
localeFamilies[config.parentLocale] = [];
}
localeFamilies[config.parentLocale].push({
name: name,
config: config,
});
return null;
}
}
}
locales[name] = new Locale(mergeConfigs(parentConfig, config));
if (localeFamilies[name]) {
localeFamilies[name].forEach(function (x) {
defineLocale(x.name, x.config);
});
}
// backwards compat for now: also set the locale
// make sure we set the locale AFTER all child locales have been
// created, so we won't end up with the child locale set.
getSetGlobalLocale(name);
return locales[name];
} else {
// useful for testing
delete locales[name];
return null;
}
}
function updateLocale(name, config) {
if (config != null) {
var locale,
tmpLocale,
parentConfig = baseConfig;
if (locales[name] != null && locales[name].parentLocale != null) {
// Update existing child locale in-place to avoid memory-leaks
locales[name].set(mergeConfigs(locales[name]._config, config));
} else {
// MERGE
tmpLocale = loadLocale(name);
if (tmpLocale != null) {
parentConfig = tmpLocale._config;
}
config = mergeConfigs(parentConfig, config);
if (tmpLocale == null) {
// updateLocale is called for creating a new locale
// Set abbr so it will have a name (getters return
// undefined otherwise).
config.abbr = name;
}
locale = new Locale(config);
locale.parentLocale = locales[name];
locales[name] = locale;
}
// backwards compat for now: also set the locale
getSetGlobalLocale(name);
} else {
// pass null for config to unupdate, useful for tests
if (locales[name] != null) {
if (locales[name].parentLocale != null) {
locales[name] = locales[name].parentLocale;
if (name === getSetGlobalLocale()) {
getSetGlobalLocale(name);
}
} else if (locales[name] != null) {
delete locales[name];
}
}
}
return locales[name];
}
// returns locale data
function getLocale(key) {
var locale;
if (key && key._locale && key._locale._abbr) {
key = key._locale._abbr;
}
if (!key) {
return globalLocale;
}
if (!isArray(key)) {
//short-circuit everything else
locale = loadLocale(key);
if (locale) {
return locale;
}
key = [key];
}
return chooseLocale(key);
}
function listLocales() {
return keys(locales);
}
function checkOverflow(m) {
var overflow,
a = m._a;
if (a && getParsingFlags(m).overflow === -2) {
overflow =
a[MONTH] < 0 || a[MONTH] > 11
? MONTH
: a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH])
? DATE
: a[HOUR] < 0 ||
a[HOUR] > 24 ||
(a[HOUR] === 24 &&
(a[MINUTE] !== 0 ||
a[SECOND] !== 0 ||
a[MILLISECOND] !== 0))
? HOUR
: a[MINUTE] < 0 || a[MINUTE] > 59
? MINUTE
: a[SECOND] < 0 || a[SECOND] > 59
? SECOND
: a[MILLISECOND] < 0 || a[MILLISECOND] > 999
? MILLISECOND
: -1;
if (
getParsingFlags(m)._overflowDayOfYear &&
(overflow < YEAR || overflow > DATE)
) {
overflow = DATE;
}
if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
overflow = WEEK;
}
if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
overflow = WEEKDAY;
}
getParsingFlags(m).overflow = overflow;
}
return m;
}
// iso 8601 regex
// 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
var extendedIsoRegex =
/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,
basicIsoRegex =
/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,
tzRegex = /Z|[+-]\d\d(?::?\d\d)?/,
isoDates = [
['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
['GGGG-[W]WW', /\d{4}-W\d\d/, false],
['YYYY-DDD', /\d{4}-\d{3}/],
['YYYY-MM', /\d{4}-\d\d/, false],
['YYYYYYMMDD', /[+-]\d{10}/],
['YYYYMMDD', /\d{8}/],
['GGGG[W]WWE', /\d{4}W\d{3}/],
['GGGG[W]WW', /\d{4}W\d{2}/, false],
['YYYYDDD', /\d{7}/],
['YYYYMM', /\d{6}/, false],
['YYYY', /\d{4}/, false],
],
// iso time formats and regexes
isoTimes = [
['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
['HH:mm:ss', /\d\d:\d\d:\d\d/],
['HH:mm', /\d\d:\d\d/],
['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
['HHmmss', /\d\d\d\d\d\d/],
['HHmm', /\d\d\d\d/],
['HH', /\d\d/],
],
aspNetJsonRegex = /^\/?Date\((-?\d+)/i,
// RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
rfc2822 =
/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,
obsOffsets = {
UT: 0,
GMT: 0,
EDT: -4 * 60,
EST: -5 * 60,
CDT: -5 * 60,
CST: -6 * 60,
MDT: -6 * 60,
MST: -7 * 60,
PDT: -7 * 60,
PST: -8 * 60,
};
// date from iso format
function configFromISO(config) {
var i,
l,
string = config._i,
match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
allowTime,
dateFormat,
timeFormat,
tzFormat,
isoDatesLen = isoDates.length,
isoTimesLen = isoTimes.length;
if (match) {
getParsingFlags(config).iso = true;
for (i = 0, l = isoDatesLen; i < l; i++) {
if (isoDates[i][1].exec(match[1])) {
dateFormat = isoDates[i][0];
allowTime = isoDates[i][2] !== false;
break;
}
}
if (dateFormat == null) {
config._isValid = false;
return;
}
if (match[3]) {
for (i = 0, l = isoTimesLen; i < l; i++) {
if (isoTimes[i][1].exec(match[3])) {
// match[2] should be 'T' or space
timeFormat = (match[2] || ' ') + isoTimes[i][0];
break;
}
}
if (timeFormat == null) {
config._isValid = false;
return;
}
}
if (!allowTime && timeFormat != null) {
config._isValid = false;
return;
}
if (match[4]) {
if (tzRegex.exec(match[4])) {
tzFormat = 'Z';
} else {
config._isValid = false;
return;
}
}
config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
configFromStringAndFormat(config);
} else {
config._isValid = false;
}
}
function extractFromRFC2822Strings(
yearStr,
monthStr,
dayStr,
hourStr,
minuteStr,
secondStr
) {
var result = [
untruncateYear(yearStr),
defaultLocaleMonthsShort.indexOf(monthStr),
parseInt(dayStr, 10),
parseInt(hourStr, 10),
parseInt(minuteStr, 10),
];
if (secondStr) {
result.push(parseInt(secondStr, 10));
}
return result;
}
function untruncateYear(yearStr) {
var year = parseInt(yearStr, 10);
if (year <= 49) {
return 2000 + year;
} else if (year <= 999) {
return 1900 + year;
}
return year;
}
function preprocessRFC2822(s) {
// Remove comments and folding whitespace and replace multiple-spaces with a single space
return s
.replace(/\([^()]*\)|[\n\t]/g, ' ')
.replace(/(\s\s+)/g, ' ')
.replace(/^\s\s*/, '')
.replace(/\s\s*$/, '');
}
function checkWeekday(weekdayStr, parsedInput, config) {
if (weekdayStr) {
// TODO: Replace the vanilla JS Date object with an independent day-of-week check.
var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
weekdayActual = new Date(
parsedInput[0],
parsedInput[1],
parsedInput[2]
).getDay();
if (weekdayProvided !== weekdayActual) {
getParsingFlags(config).weekdayMismatch = true;
config._isValid = false;
return false;
}
}
return true;
}
function calculateOffset(obsOffset, militaryOffset, numOffset) {
if (obsOffset) {
return obsOffsets[obsOffset];
} else if (militaryOffset) {
// the only allowed military tz is Z
return 0;
} else {
var hm = parseInt(numOffset, 10),
m = hm % 100,
h = (hm - m) / 100;
return h * 60 + m;
}
}
// date and time from ref 2822 format
function configFromRFC2822(config) {
var match = rfc2822.exec(preprocessRFC2822(config._i)),
parsedArray;
if (match) {
parsedArray = extractFromRFC2822Strings(
match[4],
match[3],
match[2],
match[5],
match[6],
match[7]
);
if (!checkWeekday(match[1], parsedArray, config)) {
return;
}
config._a = parsedArray;
config._tzm = calculateOffset(match[8], match[9], match[10]);
config._d = createUTCDate.apply(null, config._a);
config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
getParsingFlags(config).rfc2822 = true;
} else {
config._isValid = false;
}
}
// date from 1) ASP.NET, 2) ISO, 3) RFC 2822 formats, or 4) optional fallback if parsing isn't strict
function configFromString(config) {
var matched = aspNetJsonRegex.exec(config._i);
if (matched !== null) {
config._d = new Date(+matched[1]);
return;
}
configFromISO(config);
if (config._isValid === false) {
delete config._isValid;
} else {
return;
}
configFromRFC2822(config);
if (config._isValid === false) {
delete config._isValid;
} else {
return;
}
if (config._strict) {
config._isValid = false;
} else {
// Final attempt, use Input Fallback
hooks.createFromInputFallback(config);
}
}
hooks.createFromInputFallback = deprecate(
'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +
'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +
'discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.',
function (config) {
config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
}
);
// Pick the first defined of two or three arguments.
function defaults(a, b, c) {
if (a != null) {
return a;
}
if (b != null) {
return b;
}
return c;
}
function currentDateArray(config) {
// hooks is actually the exported moment object
var nowValue = new Date(hooks.now());
if (config._useUTC) {
return [
nowValue.getUTCFullYear(),
nowValue.getUTCMonth(),
nowValue.getUTCDate(),
];
}
return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
}
// convert an array to a date.
// the array should mirror the parameters below
// note: all values past the year are optional and will default to the lowest possible value.
// [year, month, day , hour, minute, second, millisecond]
function configFromArray(config) {
var i,
date,
input = [],
currentDate,
expectedWeekday,
yearToUse;
if (config._d) {
return;
}
currentDate = currentDateArray(config);
//compute day of the year from weeks and weekdays
if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
dayOfYearFromWeekInfo(config);
}
//if the day of the year is set, figure out what it is
if (config._dayOfYear != null) {
yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
if (
config._dayOfYear > daysInYear(yearToUse) ||
config._dayOfYear === 0
) {
getParsingFlags(config)._overflowDayOfYear = true;
}
date = createUTCDate(yearToUse, 0, config._dayOfYear);
config._a[MONTH] = date.getUTCMonth();
config._a[DATE] = date.getUTCDate();
}
// Default to current date.
// * if no year, month, day of month are given, default to today
// * if day of month is given, default month and year
// * if month is given, default only year
// * if year is given, don't default anything
for (i = 0; i < 3 && config._a[i] == null; ++i) {
config._a[i] = input[i] = currentDate[i];
}
// Zero out whatever was not defaulted, including time
for (; i < 7; i++) {
config._a[i] = input[i] =
config._a[i] == null ? (i === 2 ? 1 : 0) : config._a[i];
}
// Check for 24:00:00.000
if (
config._a[HOUR] === 24 &&
config._a[MINUTE] === 0 &&
config._a[SECOND] === 0 &&
config._a[MILLISECOND] === 0
) {
config._nextDay = true;
config._a[HOUR] = 0;
}
config._d = (config._useUTC ? createUTCDate : createDate).apply(
null,
input
);
expectedWeekday = config._useUTC
? config._d.getUTCDay()
: config._d.getDay();
// Apply timezone offset from input. The actual utcOffset can be changed
// with parseZone.
if (config._tzm != null) {
config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
}
if (config._nextDay) {
config._a[HOUR] = 24;
}
// check for mismatching day of week
if (
config._w &&
typeof config._w.d !== 'undefined' &&
config._w.d !== expectedWeekday
) {
getParsingFlags(config).weekdayMismatch = true;
}
}
function dayOfYearFromWeekInfo(config) {
var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek;
w = config._w;
if (w.GG != null || w.W != null || w.E != null) {
dow = 1;
doy = 4;
// TODO: We need to take the current isoWeekYear, but that depends on
// how we interpret now (local, utc, fixed offset). So create
// a now version of current config (take local/utc/offset flags, and
// create now).
weekYear = defaults(
w.GG,
config._a[YEAR],
weekOfYear(createLocal(), 1, 4).year
);
week = defaults(w.W, 1);
weekday = defaults(w.E, 1);
if (weekday < 1 || weekday > 7) {
weekdayOverflow = true;
}
} else {
dow = config._locale._week.dow;
doy = config._locale._week.doy;
curWeek = weekOfYear(createLocal(), dow, doy);
weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
// Default to current week.
week = defaults(w.w, curWeek.week);
if (w.d != null) {
// weekday -- low day numbers are considered next week
weekday = w.d;
if (weekday < 0 || weekday > 6) {
weekdayOverflow = true;
}
} else if (w.e != null) {
// local weekday -- counting starts from beginning of week
weekday = w.e + dow;
if (w.e < 0 || w.e > 6) {
weekdayOverflow = true;
}
} else {
// default to beginning of week
weekday = dow;
}
}
if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
getParsingFlags(config)._overflowWeeks = true;
} else if (weekdayOverflow != null) {
getParsingFlags(config)._overflowWeekday = true;
} else {
temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
config._a[YEAR] = temp.year;
config._dayOfYear = temp.dayOfYear;
}
}
// constant that refers to the ISO standard
hooks.ISO_8601 = function () {};
// constant that refers to the RFC 2822 form
hooks.RFC_2822 = function () {};
// date from string and format string
function configFromStringAndFormat(config) {
// TODO: Move this to another part of the creation flow to prevent circular deps
if (config._f === hooks.ISO_8601) {
configFromISO(config);
return;
}
if (config._f === hooks.RFC_2822) {
configFromRFC2822(config);
return;
}
config._a = [];
getParsingFlags(config).empty = true;
// This array is used to make a Date, either with `new Date` or `Date.UTC`
var string = '' + config._i,
i,
parsedInput,
tokens,
token,
skipped,
stringLength = string.length,
totalParsedInputLength = 0,
era,
tokenLen;
tokens =
expandFormat(config._f, config._locale).match(formattingTokens) || [];
tokenLen = tokens.length;
for (i = 0; i < tokenLen; i++) {
token = tokens[i];
parsedInput = (string.match(getParseRegexForToken(token, config)) ||
[])[0];
if (parsedInput) {
skipped = string.substr(0, string.indexOf(parsedInput));
if (skipped.length > 0) {
getParsingFlags(config).unusedInput.push(skipped);
}
string = string.slice(
string.indexOf(parsedInput) + parsedInput.length
);
totalParsedInputLength += parsedInput.length;
}
// don't parse if it's not a known token
if (formatTokenFunctions[token]) {
if (parsedInput) {
getParsingFlags(config).empty = false;
} else {
getParsingFlags(config).unusedTokens.push(token);
}
addTimeToArrayFromToken(token, parsedInput, config);
} else if (config._strict && !parsedInput) {
getParsingFlags(config).unusedTokens.push(token);
}
}
// add remaining unparsed input length to the string
getParsingFlags(config).charsLeftOver =
stringLength - totalParsedInputLength;
if (string.length > 0) {
getParsingFlags(config).unusedInput.push(string);
}
// clear _12h flag if hour is <= 12
if (
config._a[HOUR] <= 12 &&
getParsingFlags(config).bigHour === true &&
config._a[HOUR] > 0
) {
getParsingFlags(config).bigHour = undefined;
}
getParsingFlags(config).parsedDateParts = config._a.slice(0);
getParsingFlags(config).meridiem = config._meridiem;
// handle meridiem
config._a[HOUR] = meridiemFixWrap(
config._locale,
config._a[HOUR],
config._meridiem
);
// handle era
era = getParsingFlags(config).era;
if (era !== null) {
config._a[YEAR] = config._locale.erasConvertYear(era, config._a[YEAR]);
}
configFromArray(config);
checkOverflow(config);
}
function meridiemFixWrap(locale, hour, meridiem) {
var isPm;
if (meridiem == null) {
// nothing to do
return hour;
}
if (locale.meridiemHour != null) {
return locale.meridiemHour(hour, meridiem);
} else if (locale.isPM != null) {
// Fallback
isPm = locale.isPM(meridiem);
if (isPm && hour < 12) {
hour += 12;
}
if (!isPm && hour === 12) {
hour = 0;
}
return hour;
} else {
// this is not supposed to happen
return hour;
}
}
// date from string and array of format strings
function configFromStringAndArray(config) {
var tempConfig,
bestMoment,
scoreToBeat,
i,
currentScore,
validFormatFound,
bestFormatIsValid = false,
configfLen = config._f.length;
if (configfLen === 0) {
getParsingFlags(config).invalidFormat = true;
config._d = new Date(NaN);
return;
}
for (i = 0; i < configfLen; i++) {
currentScore = 0;
validFormatFound = false;
tempConfig = copyConfig({}, config);
if (config._useUTC != null) {
tempConfig._useUTC = config._useUTC;
}
tempConfig._f = config._f[i];
configFromStringAndFormat(tempConfig);
if (isValid(tempConfig)) {
validFormatFound = true;
}
// if there is any input that was not parsed add a penalty for that format
currentScore += getParsingFlags(tempConfig).charsLeftOver;
//or tokens
currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
getParsingFlags(tempConfig).score = currentScore;
if (!bestFormatIsValid) {
if (
scoreToBeat == null ||
currentScore < scoreToBeat ||
validFormatFound
) {
scoreToBeat = currentScore;
bestMoment = tempConfig;
if (validFormatFound) {
bestFormatIsValid = true;
}
}
} else {
if (currentScore < scoreToBeat) {
scoreToBeat = currentScore;
bestMoment = tempConfig;
}
}
}
extend(config, bestMoment || tempConfig);
}
function configFromObject(config) {
if (config._d) {
return;
}
var i = normalizeObjectUnits(config._i),
dayOrDate = i.day === undefined ? i.date : i.day;
config._a = map(
[i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond],
function (obj) {
return obj && parseInt(obj, 10);
}
);
configFromArray(config);
}
function createFromConfig(config) {
var res = new Moment(checkOverflow(prepareConfig(config)));
if (res._nextDay) {
// Adding is smart enough around DST
res.add(1, 'd');
res._nextDay = undefined;
}
return res;
}
function prepareConfig(config) {
var input = config._i,
format = config._f;
config._locale = config._locale || getLocale(config._l);
if (input === null || (format === undefined && input === '')) {
return createInvalid({ nullInput: true });
}
if (typeof input === 'string') {
config._i = input = config._locale.preparse(input);
}
if (isMoment(input)) {
return new Moment(checkOverflow(input));
} else if (isDate(input)) {
config._d = input;
} else if (isArray(format)) {
configFromStringAndArray(config);
} else if (format) {
configFromStringAndFormat(config);
} else {
configFromInput(config);
}
if (!isValid(config)) {
config._d = null;
}
return config;
}
function configFromInput(config) {
var input = config._i;
if (isUndefined(input)) {
config._d = new Date(hooks.now());
} else if (isDate(input)) {
config._d = new Date(input.valueOf());
} else if (typeof input === 'string') {
configFromString(config);
} else if (isArray(input)) {
config._a = map(input.slice(0), function (obj) {
return parseInt(obj, 10);
});
configFromArray(config);
} else if (isObject(input)) {
configFromObject(config);
} else if (isNumber(input)) {
// from milliseconds
config._d = new Date(input);
} else {
hooks.createFromInputFallback(config);
}
}
function createLocalOrUTC(input, format, locale, strict, isUTC) {
var c = {};
if (format === true || format === false) {
strict = format;
format = undefined;
}
if (locale === true || locale === false) {
strict = locale;
locale = undefined;
}
if (
(isObject(input) && isObjectEmpty(input)) ||
(isArray(input) && input.length === 0)
) {
input = undefined;
}
// object construction must be done this way.
// https://github.com/moment/moment/issues/1423
c._isAMomentObject = true;
c._useUTC = c._isUTC = isUTC;
c._l = locale;
c._i = input;
c._f = format;
c._strict = strict;
return createFromConfig(c);
}
function createLocal(input, format, locale, strict) {
return createLocalOrUTC(input, format, locale, strict, false);
}
var prototypeMin = deprecate(
'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
function () {
var other = createLocal.apply(null, arguments);
if (this.isValid() && other.isValid()) {
return other < this ? this : other;
} else {
return createInvalid();
}
}
),
prototypeMax = deprecate(
'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
function () {
var other = createLocal.apply(null, arguments);
if (this.isValid() && other.isValid()) {
return other > this ? this : other;
} else {
return createInvalid();
}
}
);
// Pick a moment m from moments so that m[fn](other) is true for all
// other. This relies on the function fn to be transitive.
//
// moments should either be an array of moment objects or an array, whose
// first element is an array of moment objects.
function pickBy(fn, moments) {
var res, i;
if (moments.length === 1 && isArray(moments[0])) {
moments = moments[0];
}
if (!moments.length) {
return createLocal();
}
res = moments[0];
for (i = 1; i < moments.length; ++i) {
if (!moments[i].isValid() || moments[i][fn](res)) {
res = moments[i];
}
}
return res;
}
// TODO: Use [].sort instead?
function min() {
var args = [].slice.call(arguments, 0);
return pickBy('isBefore', args);
}
function max() {
var args = [].slice.call(arguments, 0);
return pickBy('isAfter', args);
}
var now = function () {
return Date.now ? Date.now() : +new Date();
};
var ordering = [
'year',
'quarter',
'month',
'week',
'day',
'hour',
'minute',
'second',
'millisecond',
];
function isDurationValid(m) {
var key,
unitHasDecimal = false,
i,
orderLen = ordering.length;
for (key in m) {
if (
hasOwnProp(m, key) &&
!(
indexOf.call(ordering, key) !== -1 &&
(m[key] == null || !isNaN(m[key]))
)
) {
return false;
}
}
for (i = 0; i < orderLen; ++i) {
if (m[ordering[i]]) {
if (unitHasDecimal) {
return false; // only allow non-integers for smallest unit
}
if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
unitHasDecimal = true;
}
}
}
return true;
}
function isValid$1() {
return this._isValid;
}
function createInvalid$1() {
return createDuration(NaN);
}
function Duration(duration) {
var normalizedInput = normalizeObjectUnits(duration),
years = normalizedInput.year || 0,
quarters = normalizedInput.quarter || 0,
months = normalizedInput.month || 0,
weeks = normalizedInput.week || normalizedInput.isoWeek || 0,
days = normalizedInput.day || 0,
hours = normalizedInput.hour || 0,
minutes = normalizedInput.minute || 0,
seconds = normalizedInput.second || 0,
milliseconds = normalizedInput.millisecond || 0;
this._isValid = isDurationValid(normalizedInput);
// representation for dateAddRemove
this._milliseconds =
+milliseconds +
seconds * 1e3 + // 1000
minutes * 6e4 + // 1000 * 60
hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
// Because of dateAddRemove treats 24 hours as different from a
// day when working around DST, we need to store them separately
this._days = +days + weeks * 7;
// It is impossible to translate months into days without knowing
// which months you are are talking about, so we have to store
// it separately.
this._months = +months + quarters * 3 + years * 12;
this._data = {};
this._locale = getLocale();
this._bubble();
}
function isDuration(obj) {
return obj instanceof Duration;
}
function absRound(number) {
if (number < 0) {
return Math.round(-1 * number) * -1;
} else {
return Math.round(number);
}
}
// compare two arrays, return the number of differences
function compareArrays(array1, array2, dontConvert) {
var len = Math.min(array1.length, array2.length),
lengthDiff = Math.abs(array1.length - array2.length),
diffs = 0,
i;
for (i = 0; i < len; i++) {
if (
(dontConvert && array1[i] !== array2[i]) ||
(!dontConvert && toInt(array1[i]) !== toInt(array2[i]))
) {
diffs++;
}
}
return diffs + lengthDiff;
}
// FORMATTING
function offset(token, separator) {
addFormatToken(token, 0, 0, function () {
var offset = this.utcOffset(),
sign = '+';
if (offset < 0) {
offset = -offset;
sign = '-';
}
return (
sign +
zeroFill(~~(offset / 60), 2) +
separator +
zeroFill(~~offset % 60, 2)
);
});
}
offset('Z', ':');
offset('ZZ', '');
// PARSING
addRegexToken('Z', matchShortOffset);
addRegexToken('ZZ', matchShortOffset);
addParseToken(['Z', 'ZZ'], function (input, array, config) {
config._useUTC = true;
config._tzm = offsetFromString(matchShortOffset, input);
});
// HELPERS
// timezone chunker
// '+10:00' > ['10', '00']
// '-1530' > ['-15', '30']
var chunkOffset = /([\+\-]|\d\d)/gi;
function offsetFromString(matcher, string) {
var matches = (string || '').match(matcher),
chunk,
parts,
minutes;
if (matches === null) {
return null;
}
chunk = matches[matches.length - 1] || [];
parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
minutes = +(parts[1] * 60) + toInt(parts[2]);
return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes;
}
// Return a moment from input, that is local/utc/zone equivalent to model.
function cloneWithOffset(input, model) {
var res, diff;
if (model._isUTC) {
res = model.clone();
diff =
(isMoment(input) || isDate(input)
? input.valueOf()
: createLocal(input).valueOf()) - res.valueOf();
// Use low-level api, because this fn is low-level api.
res._d.setTime(res._d.valueOf() + diff);
hooks.updateOffset(res, false);
return res;
} else {
return createLocal(input).local();
}
}
function getDateOffset(m) {
// On Firefox.24 Date#getTimezoneOffset returns a floating point.
// https://github.com/moment/moment/pull/1871
return -Math.round(m._d.getTimezoneOffset());
}
// HOOKS
// This function will be called whenever a moment is mutated.
// It is intended to keep the offset in sync with the timezone.
hooks.updateOffset = function () {};
// MOMENTS
// keepLocalTime = true means only change the timezone, without
// affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
// 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
// +0200, so we adjust the time as needed, to be valid.
//
// Keeping the time actually adds/subtracts (one hour)
// from the actual represented time. That is why we call updateOffset
// a second time. In case it wants us to change the offset again
// _changeInProgress == true case, then we have to adjust, because
// there is no such time in the given timezone.
function getSetOffset(input, keepLocalTime, keepMinutes) {
var offset = this._offset || 0,
localAdjust;
if (!this.isValid()) {
return input != null ? this : NaN;
}
if (input != null) {
if (typeof input === 'string') {
input = offsetFromString(matchShortOffset, input);
if (input === null) {
return this;
}
} else if (Math.abs(input) < 16 && !keepMinutes) {
input = input * 60;
}
if (!this._isUTC && keepLocalTime) {
localAdjust = getDateOffset(this);
}
this._offset = input;
this._isUTC = true;
if (localAdjust != null) {
this.add(localAdjust, 'm');
}
if (offset !== input) {
if (!keepLocalTime || this._changeInProgress) {
addSubtract(
this,
createDuration(input - offset, 'm'),
1,
false
);
} else if (!this._changeInProgress) {
this._changeInProgress = true;
hooks.updateOffset(this, true);
this._changeInProgress = null;
}
}
return this;
} else {
return this._isUTC ? offset : getDateOffset(this);
}
}
function getSetZone(input, keepLocalTime) {
if (input != null) {
if (typeof input !== 'string') {
input = -input;
}
this.utcOffset(input, keepLocalTime);
return this;
} else {
return -this.utcOffset();
}
}
function setOffsetToUTC(keepLocalTime) {
return this.utcOffset(0, keepLocalTime);
}
function setOffsetToLocal(keepLocalTime) {
if (this._isUTC) {
this.utcOffset(0, keepLocalTime);
this._isUTC = false;
if (keepLocalTime) {
this.subtract(getDateOffset(this), 'm');
}
}
return this;
}
function setOffsetToParsedOffset() {
if (this._tzm != null) {
this.utcOffset(this._tzm, false, true);
} else if (typeof this._i === 'string') {
var tZone = offsetFromString(matchOffset, this._i);
if (tZone != null) {
this.utcOffset(tZone);
} else {
this.utcOffset(0, true);
}
}
return this;
}
function hasAlignedHourOffset(input) {
if (!this.isValid()) {
return false;
}
input = input ? createLocal(input).utcOffset() : 0;
return (this.utcOffset() - input) % 60 === 0;
}
function isDaylightSavingTime() {
return (
this.utcOffset() > this.clone().month(0).utcOffset() ||
this.utcOffset() > this.clone().month(5).utcOffset()
);
}
function isDaylightSavingTimeShifted() {
if (!isUndefined(this._isDSTShifted)) {
return this._isDSTShifted;
}
var c = {},
other;
copyConfig(c, this);
c = prepareConfig(c);
if (c._a) {
other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
this._isDSTShifted =
this.isValid() && compareArrays(c._a, other.toArray()) > 0;
} else {
this._isDSTShifted = false;
}
return this._isDSTShifted;
}
function isLocal() {
return this.isValid() ? !this._isUTC : false;
}
function isUtcOffset() {
return this.isValid() ? this._isUTC : false;
}
function isUtc() {
return this.isValid() ? this._isUTC && this._offset === 0 : false;
}
// ASP.NET json date format regex
var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,
// from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
// somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
// and further modified to allow for strings containing both week and day
isoRegex =
/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
function createDuration(input, key) {
var duration = input,
// matching against regexp is expensive, do it on demand
match = null,
sign,
ret,
diffRes;
if (isDuration(input)) {
duration = {
ms: input._milliseconds,
d: input._days,
M: input._months,
};
} else if (isNumber(input) || !isNaN(+input)) {
duration = {};
if (key) {
duration[key] = +input;
} else {
duration.milliseconds = +input;
}
} else if ((match = aspNetRegex.exec(input))) {
sign = match[1] === '-' ? -1 : 1;
duration = {
y: 0,
d: toInt(match[DATE]) * sign,
h: toInt(match[HOUR]) * sign,
m: toInt(match[MINUTE]) * sign,
s: toInt(match[SECOND]) * sign,
ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign, // the millisecond decimal point is included in the match
};
} else if ((match = isoRegex.exec(input))) {
sign = match[1] === '-' ? -1 : 1;
duration = {
y: parseIso(match[2], sign),
M: parseIso(match[3], sign),
w: parseIso(match[4], sign),
d: parseIso(match[5], sign),
h: parseIso(match[6], sign),
m: parseIso(match[7], sign),
s: parseIso(match[8], sign),
};
} else if (duration == null) {
// checks for null or undefined
duration = {};
} else if (
typeof duration === 'object' &&
('from' in duration || 'to' in duration)
) {
diffRes = momentsDifference(
createLocal(duration.from),
createLocal(duration.to)
);
duration = {};
duration.ms = diffRes.milliseconds;
duration.M = diffRes.months;
}
ret = new Duration(duration);
if (isDuration(input) && hasOwnProp(input, '_locale')) {
ret._locale = input._locale;
}
if (isDuration(input) && hasOwnProp(input, '_isValid')) {
ret._isValid = input._isValid;
}
return ret;
}
createDuration.fn = Duration.prototype;
createDuration.invalid = createInvalid$1;
function parseIso(inp, sign) {
// We'd normally use ~~inp for this, but unfortunately it also
// converts floats to ints.
// inp may be undefined, so careful calling replace on it.
var res = inp && parseFloat(inp.replace(',', '.'));
// apply sign while we're at it
return (isNaN(res) ? 0 : res) * sign;
}
function positiveMomentsDifference(base, other) {
var res = {};
res.months =
other.month() - base.month() + (other.year() - base.year()) * 12;
if (base.clone().add(res.months, 'M').isAfter(other)) {
--res.months;
}
res.milliseconds = +other - +base.clone().add(res.months, 'M');
return res;
}
function momentsDifference(base, other) {
var res;
if (!(base.isValid() && other.isValid())) {
return { milliseconds: 0, months: 0 };
}
other = cloneWithOffset(other, base);
if (base.isBefore(other)) {
res = positiveMomentsDifference(base, other);
} else {
res = positiveMomentsDifference(other, base);
res.milliseconds = -res.milliseconds;
res.months = -res.months;
}
return res;
}
// TODO: remove 'name' arg after deprecation is removed
function createAdder(direction, name) {
return function (val, period) {
var dur, tmp;
//invert the arguments, but complain about it
if (period !== null && !isNaN(+period)) {
deprecateSimple(
name,
'moment().' +
name +
'(period, number) is deprecated. Please use moment().' +
name +
'(number, period). ' +
'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'
);
tmp = val;
val = period;
period = tmp;
}
dur = createDuration(val, period);
addSubtract(this, dur, direction);
return this;
};
}
function addSubtract(mom, duration, isAdding, updateOffset) {
var milliseconds = duration._milliseconds,
days = absRound(duration._days),
months = absRound(duration._months);
if (!mom.isValid()) {
// No op
return;
}
updateOffset = updateOffset == null ? true : updateOffset;
if (months) {
setMonth(mom, get(mom, 'Month') + months * isAdding);
}
if (days) {
set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
}
if (milliseconds) {
mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
}
if (updateOffset) {
hooks.updateOffset(mom, days || months);
}
}
var add = createAdder(1, 'add'),
subtract = createAdder(-1, 'subtract');
function isString(input) {
return typeof input === 'string' || input instanceof String;
}
// type MomentInput = Moment | Date | string | number | (number | string)[] | MomentInputObject | void; // null | undefined
function isMomentInput(input) {
return (
isMoment(input) ||
isDate(input) ||
isString(input) ||
isNumber(input) ||
isNumberOrStringArray(input) ||
isMomentInputObject(input) ||
input === null ||
input === undefined
);
}
function isMomentInputObject(input) {
var objectTest = isObject(input) && !isObjectEmpty(input),
propertyTest = false,
properties = [
'years',
'year',
'y',
'months',
'month',
'M',
'days',
'day',
'd',
'dates',
'date',
'D',
'hours',
'hour',
'h',
'minutes',
'minute',
'm',
'seconds',
'second',
's',
'milliseconds',
'millisecond',
'ms',
],
i,
property,
propertyLen = properties.length;
for (i = 0; i < propertyLen; i += 1) {
property = properties[i];
propertyTest = propertyTest || hasOwnProp(input, property);
}
return objectTest && propertyTest;
}
function isNumberOrStringArray(input) {
var arrayTest = isArray(input),
dataTypeTest = false;
if (arrayTest) {
dataTypeTest =
input.filter(function (item) {
return !isNumber(item) && isString(input);
}).length === 0;
}
return arrayTest && dataTypeTest;
}
function isCalendarSpec(input) {
var objectTest = isObject(input) && !isObjectEmpty(input),
propertyTest = false,
properties = [
'sameDay',
'nextDay',
'lastDay',
'nextWeek',
'lastWeek',
'sameElse',
],
i,
property;
for (i = 0; i < properties.length; i += 1) {
property = properties[i];
propertyTest = propertyTest || hasOwnProp(input, property);
}
return objectTest && propertyTest;
}
function getCalendarFormat(myMoment, now) {
var diff = myMoment.diff(now, 'days', true);
return diff < -6
? 'sameElse'
: diff < -1
? 'lastWeek'
: diff < 0
? 'lastDay'
: diff < 1
? 'sameDay'
: diff < 2
? 'nextDay'
: diff < 7
? 'nextWeek'
: 'sameElse';
}
function calendar$1(time, formats) {
// Support for single parameter, formats only overload to the calendar function
if (arguments.length === 1) {
if (!arguments[0]) {
time = undefined;
formats = undefined;
} else if (isMomentInput(arguments[0])) {
time = arguments[0];
formats = undefined;
} else if (isCalendarSpec(arguments[0])) {
formats = arguments[0];
time = undefined;
}
}
// We want to compare the start of today, vs this.
// Getting start-of-today depends on whether we're local/utc/offset or not.
var now = time || createLocal(),
sod = cloneWithOffset(now, this).startOf('day'),
format = hooks.calendarFormat(this, sod) || 'sameElse',
output =
formats &&
(isFunction(formats[format])
? formats[format].call(this, now)
: formats[format]);
return this.format(
output || this.localeData().calendar(format, this, createLocal(now))
);
}
function clone() {
return new Moment(this);
}
function isAfter(input, units) {
var localInput = isMoment(input) ? input : createLocal(input);
if (!(this.isValid() && localInput.isValid())) {
return false;
}
units = normalizeUnits(units) || 'millisecond';
if (units === 'millisecond') {
return this.valueOf() > localInput.valueOf();
} else {
return localInput.valueOf() < this.clone().startOf(units).valueOf();
}
}
function isBefore(input, units) {
var localInput = isMoment(input) ? input : createLocal(input);
if (!(this.isValid() && localInput.isValid())) {
return false;
}
units = normalizeUnits(units) || 'millisecond';
if (units === 'millisecond') {
return this.valueOf() < localInput.valueOf();
} else {
return this.clone().endOf(units).valueOf() < localInput.valueOf();
}
}
function isBetween(from, to, units, inclusivity) {
var localFrom = isMoment(from) ? from : createLocal(from),
localTo = isMoment(to) ? to : createLocal(to);
if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
return false;
}
inclusivity = inclusivity || '()';
return (
(inclusivity[0] === '('
? this.isAfter(localFrom, units)
: !this.isBefore(localFrom, units)) &&
(inclusivity[1] === ')'
? this.isBefore(localTo, units)
: !this.isAfter(localTo, units))
);
}
function isSame(input, units) {
var localInput = isMoment(input) ? input : createLocal(input),
inputMs;
if (!(this.isValid() && localInput.isValid())) {
return false;
}
units = normalizeUnits(units) || 'millisecond';
if (units === 'millisecond') {
return this.valueOf() === localInput.valueOf();
} else {
inputMs = localInput.valueOf();
return (
this.clone().startOf(units).valueOf() <= inputMs &&
inputMs <= this.clone().endOf(units).valueOf()
);
}
}
function isSameOrAfter(input, units) {
return this.isSame(input, units) || this.isAfter(input, units);
}
function isSameOrBefore(input, units) {
return this.isSame(input, units) || this.isBefore(input, units);
}
function diff(input, units, asFloat) {
var that, zoneDelta, output;
if (!this.isValid()) {
return NaN;
}
that = cloneWithOffset(input, this);
if (!that.isValid()) {
return NaN;
}
zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
units = normalizeUnits(units);
switch (units) {
case 'year':
output = monthDiff(this, that) / 12;
break;
case 'month':
output = monthDiff(this, that);
break;
case 'quarter':
output = monthDiff(this, that) / 3;
break;
case 'second':
output = (this - that) / 1e3;
break; // 1000
case 'minute':
output = (this - that) / 6e4;
break; // 1000 * 60
case 'hour':
output = (this - that) / 36e5;
break; // 1000 * 60 * 60
case 'day':
output = (this - that - zoneDelta) / 864e5;
break; // 1000 * 60 * 60 * 24, negate dst
case 'week':
output = (this - that - zoneDelta) / 6048e5;
break; // 1000 * 60 * 60 * 24 * 7, negate dst
default:
output = this - that;
}
return asFloat ? output : absFloor(output);
}
function monthDiff(a, b) {
if (a.date() < b.date()) {
// end-of-month calculations work correct when the start month has more
// days than the end month.
return -monthDiff(b, a);
}
// difference in months
var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()),
// b is in (anchor - 1 month, anchor + 1 month)
anchor = a.clone().add(wholeMonthDiff, 'months'),
anchor2,
adjust;
if (b - anchor < 0) {
anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
// linear across the month
adjust = (b - anchor) / (anchor - anchor2);
} else {
anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
// linear across the month
adjust = (b - anchor) / (anchor2 - anchor);
}
//check for negative zero, return zero if negative zero
return -(wholeMonthDiff + adjust) || 0;
}
hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
function toString() {
return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
}
function toISOString(keepOffset) {
if (!this.isValid()) {
return null;
}
var utc = keepOffset !== true,
m = utc ? this.clone().utc() : this;
if (m.year() < 0 || m.year() > 9999) {
return formatMoment(
m,
utc
? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'
: 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ'
);
}
if (isFunction(Date.prototype.toISOString)) {
// native implementation is ~50x faster, use it when we can
if (utc) {
return this.toDate().toISOString();
} else {
return new Date(this.valueOf() + this.utcOffset() * 60 * 1000)
.toISOString()
.replace('Z', formatMoment(m, 'Z'));
}
}
return formatMoment(
m,
utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ'
);
}
/**
* Return a human readable representation of a moment that can
* also be evaluated to get a new moment which is the same
*
* @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
*/
function inspect() {
if (!this.isValid()) {
return 'moment.invalid(/* ' + this._i + ' */)';
}
var func = 'moment',
zone = '',
prefix,
year,
datetime,
suffix;
if (!this.isLocal()) {
func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
zone = 'Z';
}
prefix = '[' + func + '("]';
year = 0 <= this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY';
datetime = '-MM-DD[T]HH:mm:ss.SSS';
suffix = zone + '[")]';
return this.format(prefix + year + datetime + suffix);
}
function format(inputString) {
if (!inputString) {
inputString = this.isUtc()
? hooks.defaultFormatUtc
: hooks.defaultFormat;
}
var output = formatMoment(this, inputString);
return this.localeData().postformat(output);
}
function from(time, withoutSuffix) {
if (
this.isValid() &&
((isMoment(time) && time.isValid()) || createLocal(time).isValid())
) {
return createDuration({ to: this, from: time })
.locale(this.locale())
.humanize(!withoutSuffix);
} else {
return this.localeData().invalidDate();
}
}
function fromNow(withoutSuffix) {
return this.from(createLocal(), withoutSuffix);
}
function to(time, withoutSuffix) {
if (
this.isValid() &&
((isMoment(time) && time.isValid()) || createLocal(time).isValid())
) {
return createDuration({ from: this, to: time })
.locale(this.locale())
.humanize(!withoutSuffix);
} else {
return this.localeData().invalidDate();
}
}
function toNow(withoutSuffix) {
return this.to(createLocal(), withoutSuffix);
}
// If passed a locale key, it will set the locale for this
// instance. Otherwise, it will return the locale configuration
// variables for this instance.
function locale(key) {
var newLocaleData;
if (key === undefined) {
return this._locale._abbr;
} else {
newLocaleData = getLocale(key);
if (newLocaleData != null) {
this._locale = newLocaleData;
}
return this;
}
}
var lang = deprecate(
'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
function (key) {
if (key === undefined) {
return this.localeData();
} else {
return this.locale(key);
}
}
);
function localeData() {
return this._locale;
}
var MS_PER_SECOND = 1000,
MS_PER_MINUTE = 60 * MS_PER_SECOND,
MS_PER_HOUR = 60 * MS_PER_MINUTE,
MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR;
// actual modulo - handles negative numbers (for dates before 1970):
function mod$1(dividend, divisor) {
return ((dividend % divisor) + divisor) % divisor;
}
function localStartOfDate(y, m, d) {
// the date constructor remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0) {
// preserve leap years using a full 400 year cycle, then reset
return new Date(y + 400, m, d) - MS_PER_400_YEARS;
} else {
return new Date(y, m, d).valueOf();
}
}
function utcStartOfDate(y, m, d) {
// Date.UTC remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0) {
// preserve leap years using a full 400 year cycle, then reset
return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS;
} else {
return Date.UTC(y, m, d);
}
}
function startOf(units) {
var time, startOfDate;
units = normalizeUnits(units);
if (units === undefined || units === 'millisecond' || !this.isValid()) {
return this;
}
startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
switch (units) {
case 'year':
time = startOfDate(this.year(), 0, 1);
break;
case 'quarter':
time = startOfDate(
this.year(),
this.month() - (this.month() % 3),
1
);
break;
case 'month':
time = startOfDate(this.year(), this.month(), 1);
break;
case 'week':
time = startOfDate(
this.year(),
this.month(),
this.date() - this.weekday()
);
break;
case 'isoWeek':
time = startOfDate(
this.year(),
this.month(),
this.date() - (this.isoWeekday() - 1)
);
break;
case 'day':
case 'date':
time = startOfDate(this.year(), this.month(), this.date());
break;
case 'hour':
time = this._d.valueOf();
time -= mod$1(
time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),
MS_PER_HOUR
);
break;
case 'minute':
time = this._d.valueOf();
time -= mod$1(time, MS_PER_MINUTE);
break;
case 'second':
time = this._d.valueOf();
time -= mod$1(time, MS_PER_SECOND);
break;
}
this._d.setTime(time);
hooks.updateOffset(this, true);
return this;
}
function endOf(units) {
var time, startOfDate;
units = normalizeUnits(units);
if (units === undefined || units === 'millisecond' || !this.isValid()) {
return this;
}
startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
switch (units) {
case 'year':
time = startOfDate(this.year() + 1, 0, 1) - 1;
break;
case 'quarter':
time =
startOfDate(
this.year(),
this.month() - (this.month() % 3) + 3,
1
) - 1;
break;
case 'month':
time = startOfDate(this.year(), this.month() + 1, 1) - 1;
break;
case 'week':
time =
startOfDate(
this.year(),
this.month(),
this.date() - this.weekday() + 7
) - 1;
break;
case 'isoWeek':
time =
startOfDate(
this.year(),
this.month(),
this.date() - (this.isoWeekday() - 1) + 7
) - 1;
break;
case 'day':
case 'date':
time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
break;
case 'hour':
time = this._d.valueOf();
time +=
MS_PER_HOUR -
mod$1(
time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),
MS_PER_HOUR
) -
1;
break;
case 'minute':
time = this._d.valueOf();
time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1;
break;
case 'second':
time = this._d.valueOf();
time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1;
break;
}
this._d.setTime(time);
hooks.updateOffset(this, true);
return this;
}
function valueOf() {
return this._d.valueOf() - (this._offset || 0) * 60000;
}
function unix() {
return Math.floor(this.valueOf() / 1000);
}
function toDate() {
return new Date(this.valueOf());
}
function toArray() {
var m = this;
return [
m.year(),
m.month(),
m.date(),
m.hour(),
m.minute(),
m.second(),
m.millisecond(),
];
}
function toObject() {
var m = this;
return {
years: m.year(),
months: m.month(),
date: m.date(),
hours: m.hours(),
minutes: m.minutes(),
seconds: m.seconds(),
milliseconds: m.milliseconds(),
};
}
function toJSON() {
// new Date(NaN).toJSON() === null
return this.isValid() ? this.toISOString() : null;
}
function isValid$2() {
return isValid(this);
}
function parsingFlags() {
return extend({}, getParsingFlags(this));
}
function invalidAt() {
return getParsingFlags(this).overflow;
}
function creationData() {
return {
input: this._i,
format: this._f,
locale: this._locale,
isUTC: this._isUTC,
strict: this._strict,
};
}
addFormatToken('N', 0, 0, 'eraAbbr');
addFormatToken('NN', 0, 0, 'eraAbbr');
addFormatToken('NNN', 0, 0, 'eraAbbr');
addFormatToken('NNNN', 0, 0, 'eraName');
addFormatToken('NNNNN', 0, 0, 'eraNarrow');
addFormatToken('y', ['y', 1], 'yo', 'eraYear');
addFormatToken('y', ['yy', 2], 0, 'eraYear');
addFormatToken('y', ['yyy', 3], 0, 'eraYear');
addFormatToken('y', ['yyyy', 4], 0, 'eraYear');
addRegexToken('N', matchEraAbbr);
addRegexToken('NN', matchEraAbbr);
addRegexToken('NNN', matchEraAbbr);
addRegexToken('NNNN', matchEraName);
addRegexToken('NNNNN', matchEraNarrow);
addParseToken(
['N', 'NN', 'NNN', 'NNNN', 'NNNNN'],
function (input, array, config, token) {
var era = config._locale.erasParse(input, token, config._strict);
if (era) {
getParsingFlags(config).era = era;
} else {
getParsingFlags(config).invalidEra = input;
}
}
);
addRegexToken('y', matchUnsigned);
addRegexToken('yy', matchUnsigned);
addRegexToken('yyy', matchUnsigned);
addRegexToken('yyyy', matchUnsigned);
addRegexToken('yo', matchEraYearOrdinal);
addParseToken(['y', 'yy', 'yyy', 'yyyy'], YEAR);
addParseToken(['yo'], function (input, array, config, token) {
var match;
if (config._locale._eraYearOrdinalRegex) {
match = input.match(config._locale._eraYearOrdinalRegex);
}
if (config._locale.eraYearOrdinalParse) {
array[YEAR] = config._locale.eraYearOrdinalParse(input, match);
} else {
array[YEAR] = parseInt(input, 10);
}
});
function localeEras(m, format) {
var i,
l,
date,
eras = this._eras || getLocale('en')._eras;
for (i = 0, l = eras.length; i < l; ++i) {
switch (typeof eras[i].since) {
case 'string':
// truncate time
date = hooks(eras[i].since).startOf('day');
eras[i].since = date.valueOf();
break;
}
switch (typeof eras[i].until) {
case 'undefined':
eras[i].until = +Infinity;
break;
case 'string':
// truncate time
date = hooks(eras[i].until).startOf('day').valueOf();
eras[i].until = date.valueOf();
break;
}
}
return eras;
}
function localeErasParse(eraName, format, strict) {
var i,
l,
eras = this.eras(),
name,
abbr,
narrow;
eraName = eraName.toUpperCase();
for (i = 0, l = eras.length; i < l; ++i) {
name = eras[i].name.toUpperCase();
abbr = eras[i].abbr.toUpperCase();
narrow = eras[i].narrow.toUpperCase();
if (strict) {
switch (format) {
case 'N':
case 'NN':
case 'NNN':
if (abbr === eraName) {
return eras[i];
}
break;
case 'NNNN':
if (name === eraName) {
return eras[i];
}
break;
case 'NNNNN':
if (narrow === eraName) {
return eras[i];
}
break;
}
} else if ([name, abbr, narrow].indexOf(eraName) >= 0) {
return eras[i];
}
}
}
function localeErasConvertYear(era, year) {
var dir = era.since <= era.until ? +1 : -1;
if (year === undefined) {
return hooks(era.since).year();
} else {
return hooks(era.since).year() + (year - era.offset) * dir;
}
}
function getEraName() {
var i,
l,
val,
eras = this.localeData().eras();
for (i = 0, l = eras.length; i < l; ++i) {
// truncate time
val = this.clone().startOf('day').valueOf();
if (eras[i].since <= val && val <= eras[i].until) {
return eras[i].name;
}
if (eras[i].until <= val && val <= eras[i].since) {
return eras[i].name;
}
}
return '';
}
function getEraNarrow() {
var i,
l,
val,
eras = this.localeData().eras();
for (i = 0, l = eras.length; i < l; ++i) {
// truncate time
val = this.clone().startOf('day').valueOf();
if (eras[i].since <= val && val <= eras[i].until) {
return eras[i].narrow;
}
if (eras[i].until <= val && val <= eras[i].since) {
return eras[i].narrow;
}
}
return '';
}
function getEraAbbr() {
var i,
l,
val,
eras = this.localeData().eras();
for (i = 0, l = eras.length; i < l; ++i) {
// truncate time
val = this.clone().startOf('day').valueOf();
if (eras[i].since <= val && val <= eras[i].until) {
return eras[i].abbr;
}
if (eras[i].until <= val && val <= eras[i].since) {
return eras[i].abbr;
}
}
return '';
}
function getEraYear() {
var i,
l,
dir,
val,
eras = this.localeData().eras();
for (i = 0, l = eras.length; i < l; ++i) {
dir = eras[i].since <= eras[i].until ? +1 : -1;
// truncate time
val = this.clone().startOf('day').valueOf();
if (
(eras[i].since <= val && val <= eras[i].until) ||
(eras[i].until <= val && val <= eras[i].since)
) {
return (
(this.year() - hooks(eras[i].since).year()) * dir +
eras[i].offset
);
}
}
return this.year();
}
function erasNameRegex(isStrict) {
if (!hasOwnProp(this, '_erasNameRegex')) {
computeErasParse.call(this);
}
return isStrict ? this._erasNameRegex : this._erasRegex;
}
function erasAbbrRegex(isStrict) {
if (!hasOwnProp(this, '_erasAbbrRegex')) {
computeErasParse.call(this);
}
return isStrict ? this._erasAbbrRegex : this._erasRegex;
}
function erasNarrowRegex(isStrict) {
if (!hasOwnProp(this, '_erasNarrowRegex')) {
computeErasParse.call(this);
}
return isStrict ? this._erasNarrowRegex : this._erasRegex;
}
function matchEraAbbr(isStrict, locale) {
return locale.erasAbbrRegex(isStrict);
}
function matchEraName(isStrict, locale) {
return locale.erasNameRegex(isStrict);
}
function matchEraNarrow(isStrict, locale) {
return locale.erasNarrowRegex(isStrict);
}
function matchEraYearOrdinal(isStrict, locale) {
return locale._eraYearOrdinalRegex || matchUnsigned;
}
function computeErasParse() {
var abbrPieces = [],
namePieces = [],
narrowPieces = [],
mixedPieces = [],
i,
l,
eras = this.eras();
for (i = 0, l = eras.length; i < l; ++i) {
namePieces.push(regexEscape(eras[i].name));
abbrPieces.push(regexEscape(eras[i].abbr));
narrowPieces.push(regexEscape(eras[i].narrow));
mixedPieces.push(regexEscape(eras[i].name));
mixedPieces.push(regexEscape(eras[i].abbr));
mixedPieces.push(regexEscape(eras[i].narrow));
}
this._erasRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
this._erasNameRegex = new RegExp('^(' + namePieces.join('|') + ')', 'i');
this._erasAbbrRegex = new RegExp('^(' + abbrPieces.join('|') + ')', 'i');
this._erasNarrowRegex = new RegExp(
'^(' + narrowPieces.join('|') + ')',
'i'
);
}
// FORMATTING
addFormatToken(0, ['gg', 2], 0, function () {
return this.weekYear() % 100;
});
addFormatToken(0, ['GG', 2], 0, function () {
return this.isoWeekYear() % 100;
});
function addWeekYearFormatToken(token, getter) {
addFormatToken(0, [token, token.length], 0, getter);
}
addWeekYearFormatToken('gggg', 'weekYear');
addWeekYearFormatToken('ggggg', 'weekYear');
addWeekYearFormatToken('GGGG', 'isoWeekYear');
addWeekYearFormatToken('GGGGG', 'isoWeekYear');
// ALIASES
addUnitAlias('weekYear', 'gg');
addUnitAlias('isoWeekYear', 'GG');
// PRIORITY
addUnitPriority('weekYear', 1);
addUnitPriority('isoWeekYear', 1);
// PARSING
addRegexToken('G', matchSigned);
addRegexToken('g', matchSigned);
addRegexToken('GG', match1to2, match2);
addRegexToken('gg', match1to2, match2);
addRegexToken('GGGG', match1to4, match4);
addRegexToken('gggg', match1to4, match4);
addRegexToken('GGGGG', match1to6, match6);
addRegexToken('ggggg', match1to6, match6);
addWeekParseToken(
['gggg', 'ggggg', 'GGGG', 'GGGGG'],
function (input, week, config, token) {
week[token.substr(0, 2)] = toInt(input);
}
);
addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
week[token] = hooks.parseTwoDigitYear(input);
});
// MOMENTS
function getSetWeekYear(input) {
return getSetWeekYearHelper.call(
this,
input,
this.week(),
this.weekday(),
this.localeData()._week.dow,
this.localeData()._week.doy
);
}
function getSetISOWeekYear(input) {
return getSetWeekYearHelper.call(
this,
input,
this.isoWeek(),
this.isoWeekday(),
1,
4
);
}
function getISOWeeksInYear() {
return weeksInYear(this.year(), 1, 4);
}
function getISOWeeksInISOWeekYear() {
return weeksInYear(this.isoWeekYear(), 1, 4);
}
function getWeeksInYear() {
var weekInfo = this.localeData()._week;
return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
}
function getWeeksInWeekYear() {
var weekInfo = this.localeData()._week;
return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy);
}
function getSetWeekYearHelper(input, week, weekday, dow, doy) {
var weeksTarget;
if (input == null) {
return weekOfYear(this, dow, doy).year;
} else {
weeksTarget = weeksInYear(input, dow, doy);
if (week > weeksTarget) {
week = weeksTarget;
}
return setWeekAll.call(this, input, week, weekday, dow, doy);
}
}
function setWeekAll(weekYear, week, weekday, dow, doy) {
var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
this.year(date.getUTCFullYear());
this.month(date.getUTCMonth());
this.date(date.getUTCDate());
return this;
}
// FORMATTING
addFormatToken('Q', 0, 'Qo', 'quarter');
// ALIASES
addUnitAlias('quarter', 'Q');
// PRIORITY
addUnitPriority('quarter', 7);
// PARSING
addRegexToken('Q', match1);
addParseToken('Q', function (input, array) {
array[MONTH] = (toInt(input) - 1) * 3;
});
// MOMENTS
function getSetQuarter(input) {
return input == null
? Math.ceil((this.month() + 1) / 3)
: this.month((input - 1) * 3 + (this.month() % 3));
}
// FORMATTING
addFormatToken('D', ['DD', 2], 'Do', 'date');
// ALIASES
addUnitAlias('date', 'D');
// PRIORITY
addUnitPriority('date', 9);
// PARSING
addRegexToken('D', match1to2);
addRegexToken('DD', match1to2, match2);
addRegexToken('Do', function (isStrict, locale) {
// TODO: Remove "ordinalParse" fallback in next major release.
return isStrict
? locale._dayOfMonthOrdinalParse || locale._ordinalParse
: locale._dayOfMonthOrdinalParseLenient;
});
addParseToken(['D', 'DD'], DATE);
addParseToken('Do', function (input, array) {
array[DATE] = toInt(input.match(match1to2)[0]);
});
// MOMENTS
var getSetDayOfMonth = makeGetSet('Date', true);
// FORMATTING
addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
// ALIASES
addUnitAlias('dayOfYear', 'DDD');
// PRIORITY
addUnitPriority('dayOfYear', 4);
// PARSING
addRegexToken('DDD', match1to3);
addRegexToken('DDDD', match3);
addParseToken(['DDD', 'DDDD'], function (input, array, config) {
config._dayOfYear = toInt(input);
});
// HELPERS
// MOMENTS
function getSetDayOfYear(input) {
var dayOfYear =
Math.round(
(this.clone().startOf('day') - this.clone().startOf('year')) / 864e5
) + 1;
return input == null ? dayOfYear : this.add(input - dayOfYear, 'd');
}
// FORMATTING
addFormatToken('m', ['mm', 2], 0, 'minute');
// ALIASES
addUnitAlias('minute', 'm');
// PRIORITY
addUnitPriority('minute', 14);
// PARSING
addRegexToken('m', match1to2);
addRegexToken('mm', match1to2, match2);
addParseToken(['m', 'mm'], MINUTE);
// MOMENTS
var getSetMinute = makeGetSet('Minutes', false);
// FORMATTING
addFormatToken('s', ['ss', 2], 0, 'second');
// ALIASES
addUnitAlias('second', 's');
// PRIORITY
addUnitPriority('second', 15);
// PARSING
addRegexToken('s', match1to2);
addRegexToken('ss', match1to2, match2);
addParseToken(['s', 'ss'], SECOND);
// MOMENTS
var getSetSecond = makeGetSet('Seconds', false);
// FORMATTING
addFormatToken('S', 0, 0, function () {
return ~~(this.millisecond() / 100);
});
addFormatToken(0, ['SS', 2], 0, function () {
return ~~(this.millisecond() / 10);
});
addFormatToken(0, ['SSS', 3], 0, 'millisecond');
addFormatToken(0, ['SSSS', 4], 0, function () {
return this.millisecond() * 10;
});
addFormatToken(0, ['SSSSS', 5], 0, function () {
return this.millisecond() * 100;
});
addFormatToken(0, ['SSSSSS', 6], 0, function () {
return this.millisecond() * 1000;
});
addFormatToken(0, ['SSSSSSS', 7], 0, function () {
return this.millisecond() * 10000;
});
addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
return this.millisecond() * 100000;
});
addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
return this.millisecond() * 1000000;
});
// ALIASES
addUnitAlias('millisecond', 'ms');
// PRIORITY
addUnitPriority('millisecond', 16);
// PARSING
addRegexToken('S', match1to3, match1);
addRegexToken('SS', match1to3, match2);
addRegexToken('SSS', match1to3, match3);
var token, getSetMillisecond;
for (token = 'SSSS'; token.length <= 9; token += 'S') {
addRegexToken(token, matchUnsigned);
}
function parseMs(input, array) {
array[MILLISECOND] = toInt(('0.' + input) * 1000);
}
for (token = 'S'; token.length <= 9; token += 'S') {
addParseToken(token, parseMs);
}
getSetMillisecond = makeGetSet('Milliseconds', false);
// FORMATTING
addFormatToken('z', 0, 0, 'zoneAbbr');
addFormatToken('zz', 0, 0, 'zoneName');
// MOMENTS
function getZoneAbbr() {
return this._isUTC ? 'UTC' : '';
}
function getZoneName() {
return this._isUTC ? 'Coordinated Universal Time' : '';
}
var proto = Moment.prototype;
proto.add = add;
proto.calendar = calendar$1;
proto.clone = clone;
proto.diff = diff;
proto.endOf = endOf;
proto.format = format;
proto.from = from;
proto.fromNow = fromNow;
proto.to = to;
proto.toNow = toNow;
proto.get = stringGet;
proto.invalidAt = invalidAt;
proto.isAfter = isAfter;
proto.isBefore = isBefore;
proto.isBetween = isBetween;
proto.isSame = isSame;
proto.isSameOrAfter = isSameOrAfter;
proto.isSameOrBefore = isSameOrBefore;
proto.isValid = isValid$2;
proto.lang = lang;
proto.locale = locale;
proto.localeData = localeData;
proto.max = prototypeMax;
proto.min = prototypeMin;
proto.parsingFlags = parsingFlags;
proto.set = stringSet;
proto.startOf = startOf;
proto.subtract = subtract;
proto.toArray = toArray;
proto.toObject = toObject;
proto.toDate = toDate;
proto.toISOString = toISOString;
proto.inspect = inspect;
if (typeof Symbol !== 'undefined' && Symbol.for != null) {
proto[Symbol.for('nodejs.util.inspect.custom')] = function () {
return 'Moment<' + this.format() + '>';
};
}
proto.toJSON = toJSON;
proto.toString = toString;
proto.unix = unix;
proto.valueOf = valueOf;
proto.creationData = creationData;
proto.eraName = getEraName;
proto.eraNarrow = getEraNarrow;
proto.eraAbbr = getEraAbbr;
proto.eraYear = getEraYear;
proto.year = getSetYear;
proto.isLeapYear = getIsLeapYear;
proto.weekYear = getSetWeekYear;
proto.isoWeekYear = getSetISOWeekYear;
proto.quarter = proto.quarters = getSetQuarter;
proto.month = getSetMonth;
proto.daysInMonth = getDaysInMonth;
proto.week = proto.weeks = getSetWeek;
proto.isoWeek = proto.isoWeeks = getSetISOWeek;
proto.weeksInYear = getWeeksInYear;
proto.weeksInWeekYear = getWeeksInWeekYear;
proto.isoWeeksInYear = getISOWeeksInYear;
proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear;
proto.date = getSetDayOfMonth;
proto.day = proto.days = getSetDayOfWeek;
proto.weekday = getSetLocaleDayOfWeek;
proto.isoWeekday = getSetISODayOfWeek;
proto.dayOfYear = getSetDayOfYear;
proto.hour = proto.hours = getSetHour;
proto.minute = proto.minutes = getSetMinute;
proto.second = proto.seconds = getSetSecond;
proto.millisecond = proto.milliseconds = getSetMillisecond;
proto.utcOffset = getSetOffset;
proto.utc = setOffsetToUTC;
proto.local = setOffsetToLocal;
proto.parseZone = setOffsetToParsedOffset;
proto.hasAlignedHourOffset = hasAlignedHourOffset;
proto.isDST = isDaylightSavingTime;
proto.isLocal = isLocal;
proto.isUtcOffset = isUtcOffset;
proto.isUtc = isUtc;
proto.isUTC = isUtc;
proto.zoneAbbr = getZoneAbbr;
proto.zoneName = getZoneName;
proto.dates = deprecate(
'dates accessor is deprecated. Use date instead.',
getSetDayOfMonth
);
proto.months = deprecate(
'months accessor is deprecated. Use month instead',
getSetMonth
);
proto.years = deprecate(
'years accessor is deprecated. Use year instead',
getSetYear
);
proto.zone = deprecate(
'moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/',
getSetZone
);
proto.isDSTShifted = deprecate(
'isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information',
isDaylightSavingTimeShifted
);
function createUnix(input) {
return createLocal(input * 1000);
}
function createInZone() {
return createLocal.apply(null, arguments).parseZone();
}
function preParsePostFormat(string) {
return string;
}
var proto$1 = Locale.prototype;
proto$1.calendar = calendar;
proto$1.longDateFormat = longDateFormat;
proto$1.invalidDate = invalidDate;
proto$1.ordinal = ordinal;
proto$1.preparse = preParsePostFormat;
proto$1.postformat = preParsePostFormat;
proto$1.relativeTime = relativeTime;
proto$1.pastFuture = pastFuture;
proto$1.set = set;
proto$1.eras = localeEras;
proto$1.erasParse = localeErasParse;
proto$1.erasConvertYear = localeErasConvertYear;
proto$1.erasAbbrRegex = erasAbbrRegex;
proto$1.erasNameRegex = erasNameRegex;
proto$1.erasNarrowRegex = erasNarrowRegex;
proto$1.months = localeMonths;
proto$1.monthsShort = localeMonthsShort;
proto$1.monthsParse = localeMonthsParse;
proto$1.monthsRegex = monthsRegex;
proto$1.monthsShortRegex = monthsShortRegex;
proto$1.week = localeWeek;
proto$1.firstDayOfYear = localeFirstDayOfYear;
proto$1.firstDayOfWeek = localeFirstDayOfWeek;
proto$1.weekdays = localeWeekdays;
proto$1.weekdaysMin = localeWeekdaysMin;
proto$1.weekdaysShort = localeWeekdaysShort;
proto$1.weekdaysParse = localeWeekdaysParse;
proto$1.weekdaysRegex = weekdaysRegex;
proto$1.weekdaysShortRegex = weekdaysShortRegex;
proto$1.weekdaysMinRegex = weekdaysMinRegex;
proto$1.isPM = localeIsPM;
proto$1.meridiem = localeMeridiem;
function get$1(format, index, field, setter) {
var locale = getLocale(),
utc = createUTC().set(setter, index);
return locale[field](utc, format);
}
function listMonthsImpl(format, index, field) {
if (isNumber(format)) {
index = format;
format = undefined;
}
format = format || '';
if (index != null) {
return get$1(format, index, field, 'month');
}
var i,
out = [];
for (i = 0; i < 12; i++) {
out[i] = get$1(format, i, field, 'month');
}
return out;
}
// ()
// (5)
// (fmt, 5)
// (fmt)
// (true)
// (true, 5)
// (true, fmt, 5)
// (true, fmt)
function listWeekdaysImpl(localeSorted, format, index, field) {
if (typeof localeSorted === 'boolean') {
if (isNumber(format)) {
index = format;
format = undefined;
}
format = format || '';
} else {
format = localeSorted;
index = format;
localeSorted = false;
if (isNumber(format)) {
index = format;
format = undefined;
}
format = format || '';
}
var locale = getLocale(),
shift = localeSorted ? locale._week.dow : 0,
i,
out = [];
if (index != null) {
return get$1(format, (index + shift) % 7, field, 'day');
}
for (i = 0; i < 7; i++) {
out[i] = get$1(format, (i + shift) % 7, field, 'day');
}
return out;
}
function listMonths(format, index) {
return listMonthsImpl(format, index, 'months');
}
function listMonthsShort(format, index) {
return listMonthsImpl(format, index, 'monthsShort');
}
function listWeekdays(localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
}
function listWeekdaysShort(localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
}
function listWeekdaysMin(localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
}
getSetGlobalLocale('en', {
eras: [
{
since: '0001-01-01',
until: +Infinity,
offset: 1,
name: 'Anno Domini',
narrow: 'AD',
abbr: 'AD',
},
{
since: '0000-12-31',
until: -Infinity,
offset: 1,
name: 'Before Christ',
narrow: 'BC',
abbr: 'BC',
},
],
dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
ordinal: function (number) {
var b = number % 10,
output =
toInt((number % 100) / 10) === 1
? 'th'
: b === 1
? 'st'
: b === 2
? 'nd'
: b === 3
? 'rd'
: 'th';
return number + output;
},
});
// Side effect imports
hooks.lang = deprecate(
'moment.lang is deprecated. Use moment.locale instead.',
getSetGlobalLocale
);
hooks.langData = deprecate(
'moment.langData is deprecated. Use moment.localeData instead.',
getLocale
);
var mathAbs = Math.abs;
function abs() {
var data = this._data;
this._milliseconds = mathAbs(this._milliseconds);
this._days = mathAbs(this._days);
this._months = mathAbs(this._months);
data.milliseconds = mathAbs(data.milliseconds);
data.seconds = mathAbs(data.seconds);
data.minutes = mathAbs(data.minutes);
data.hours = mathAbs(data.hours);
data.months = mathAbs(data.months);
data.years = mathAbs(data.years);
return this;
}
function addSubtract$1(duration, input, value, direction) {
var other = createDuration(input, value);
duration._milliseconds += direction * other._milliseconds;
duration._days += direction * other._days;
duration._months += direction * other._months;
return duration._bubble();
}
// supports only 2.0-style add(1, 's') or add(duration)
function add$1(input, value) {
return addSubtract$1(this, input, value, 1);
}
// supports only 2.0-style subtract(1, 's') or subtract(duration)
function subtract$1(input, value) {
return addSubtract$1(this, input, value, -1);
}
function absCeil(number) {
if (number < 0) {
return Math.floor(number);
} else {
return Math.ceil(number);
}
}
function bubble() {
var milliseconds = this._milliseconds,
days = this._days,
months = this._months,
data = this._data,
seconds,
minutes,
hours,
years,
monthsFromDays;
// if we have a mix of positive and negative values, bubble down first
// check: https://github.com/moment/moment/issues/2166
if (
!(
(milliseconds >= 0 && days >= 0 && months >= 0) ||
(milliseconds <= 0 && days <= 0 && months <= 0)
)
) {
milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
days = 0;
months = 0;
}
// The following code bubbles up values, see the tests for
// examples of what that means.
data.milliseconds = milliseconds % 1000;
seconds = absFloor(milliseconds / 1000);
data.seconds = seconds % 60;
minutes = absFloor(seconds / 60);
data.minutes = minutes % 60;
hours = absFloor(minutes / 60);
data.hours = hours % 24;
days += absFloor(hours / 24);
// convert days to months
monthsFromDays = absFloor(daysToMonths(days));
months += monthsFromDays;
days -= absCeil(monthsToDays(monthsFromDays));
// 12 months -> 1 year
years = absFloor(months / 12);
months %= 12;
data.days = days;
data.months = months;
data.years = years;
return this;
}
function daysToMonths(days) {
// 400 years have 146097 days (taking into account leap year rules)
// 400 years have 12 months === 4800
return (days * 4800) / 146097;
}
function monthsToDays(months) {
// the reverse of daysToMonths
return (months * 146097) / 4800;
}
function as(units) {
if (!this.isValid()) {
return NaN;
}
var days,
months,
milliseconds = this._milliseconds;
units = normalizeUnits(units);
if (units === 'month' || units === 'quarter' || units === 'year') {
days = this._days + milliseconds / 864e5;
months = this._months + daysToMonths(days);
switch (units) {
case 'month':
return months;
case 'quarter':
return months / 3;
case 'year':
return months / 12;
}
} else {
// handle milliseconds separately because of floating point math errors (issue #1867)
days = this._days + Math.round(monthsToDays(this._months));
switch (units) {
case 'week':
return days / 7 + milliseconds / 6048e5;
case 'day':
return days + milliseconds / 864e5;
case 'hour':
return days * 24 + milliseconds / 36e5;
case 'minute':
return days * 1440 + milliseconds / 6e4;
case 'second':
return days * 86400 + milliseconds / 1000;
// Math.floor prevents floating point math errors here
case 'millisecond':
return Math.floor(days * 864e5) + milliseconds;
default:
throw new Error('Unknown unit ' + units);
}
}
}
// TODO: Use this.as('ms')?
function valueOf$1() {
if (!this.isValid()) {
return NaN;
}
return (
this._milliseconds +
this._days * 864e5 +
(this._months % 12) * 2592e6 +
toInt(this._months / 12) * 31536e6
);
}
function makeAs(alias) {
return function () {
return this.as(alias);
};
}
var asMilliseconds = makeAs('ms'),
asSeconds = makeAs('s'),
asMinutes = makeAs('m'),
asHours = makeAs('h'),
asDays = makeAs('d'),
asWeeks = makeAs('w'),
asMonths = makeAs('M'),
asQuarters = makeAs('Q'),
asYears = makeAs('y');
function clone$1() {
return createDuration(this);
}
function get$2(units) {
units = normalizeUnits(units);
return this.isValid() ? this[units + 's']() : NaN;
}
function makeGetter(name) {
return function () {
return this.isValid() ? this._data[name] : NaN;
};
}
var milliseconds = makeGetter('milliseconds'),
seconds = makeGetter('seconds'),
minutes = makeGetter('minutes'),
hours = makeGetter('hours'),
days = makeGetter('days'),
months = makeGetter('months'),
years = makeGetter('years');
function weeks() {
return absFloor(this.days() / 7);
}
var round = Math.round,
thresholds = {
ss: 44, // a few seconds to seconds
s: 45, // seconds to minute
m: 45, // minutes to hour
h: 22, // hours to day
d: 26, // days to month/week
w: null, // weeks to month
M: 11, // months to year
};
// helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
}
function relativeTime$1(posNegDuration, withoutSuffix, thresholds, locale) {
var duration = createDuration(posNegDuration).abs(),
seconds = round(duration.as('s')),
minutes = round(duration.as('m')),
hours = round(duration.as('h')),
days = round(duration.as('d')),
months = round(duration.as('M')),
weeks = round(duration.as('w')),
years = round(duration.as('y')),
a =
(seconds <= thresholds.ss && ['s', seconds]) ||
(seconds < thresholds.s && ['ss', seconds]) ||
(minutes <= 1 && ['m']) ||
(minutes < thresholds.m && ['mm', minutes]) ||
(hours <= 1 && ['h']) ||
(hours < thresholds.h && ['hh', hours]) ||
(days <= 1 && ['d']) ||
(days < thresholds.d && ['dd', days]);
if (thresholds.w != null) {
a =
a ||
(weeks <= 1 && ['w']) ||
(weeks < thresholds.w && ['ww', weeks]);
}
a = a ||
(months <= 1 && ['M']) ||
(months < thresholds.M && ['MM', months]) ||
(years <= 1 && ['y']) || ['yy', years];
a[2] = withoutSuffix;
a[3] = +posNegDuration > 0;
a[4] = locale;
return substituteTimeAgo.apply(null, a);
}
// This function allows you to set the rounding function for relative time strings
function getSetRelativeTimeRounding(roundingFunction) {
if (roundingFunction === undefined) {
return round;
}
if (typeof roundingFunction === 'function') {
round = roundingFunction;
return true;
}
return false;
}
// This function allows you to set a threshold for relative time strings
function getSetRelativeTimeThreshold(threshold, limit) {
if (thresholds[threshold] === undefined) {
return false;
}
if (limit === undefined) {
return thresholds[threshold];
}
thresholds[threshold] = limit;
if (threshold === 's') {
thresholds.ss = limit - 1;
}
return true;
}
function humanize(argWithSuffix, argThresholds) {
if (!this.isValid()) {
return this.localeData().invalidDate();
}
var withSuffix = false,
th = thresholds,
locale,
output;
if (typeof argWithSuffix === 'object') {
argThresholds = argWithSuffix;
argWithSuffix = false;
}
if (typeof argWithSuffix === 'boolean') {
withSuffix = argWithSuffix;
}
if (typeof argThresholds === 'object') {
th = Object.assign({}, thresholds, argThresholds);
if (argThresholds.s != null && argThresholds.ss == null) {
th.ss = argThresholds.s - 1;
}
}
locale = this.localeData();
output = relativeTime$1(this, !withSuffix, th, locale);
if (withSuffix) {
output = locale.pastFuture(+this, output);
}
return locale.postformat(output);
}
var abs$1 = Math.abs;
function sign(x) {
return (x > 0) - (x < 0) || +x;
}
function toISOString$1() {
// for ISO strings we do not use the normal bubbling rules:
// * milliseconds bubble up until they become hours
// * days do not bubble at all
// * months bubble up until they become years
// This is because there is no context-free conversion between hours and days
// (think of clock changes)
// and also not between days and months (28-31 days per month)
if (!this.isValid()) {
return this.localeData().invalidDate();
}
var seconds = abs$1(this._milliseconds) / 1000,
days = abs$1(this._days),
months = abs$1(this._months),
minutes,
hours,
years,
s,
total = this.asSeconds(),
totalSign,
ymSign,
daysSign,
hmsSign;
if (!total) {
// this is the same as C#'s (Noda) and python (isodate)...
// but not other JS (goog.date)
return 'P0D';
}
// 3600 seconds -> 60 minutes -> 1 hour
minutes = absFloor(seconds / 60);
hours = absFloor(minutes / 60);
seconds %= 60;
minutes %= 60;
// 12 months -> 1 year
years = absFloor(months / 12);
months %= 12;
// inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
totalSign = total < 0 ? '-' : '';
ymSign = sign(this._months) !== sign(total) ? '-' : '';
daysSign = sign(this._days) !== sign(total) ? '-' : '';
hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
return (
totalSign +
'P' +
(years ? ymSign + years + 'Y' : '') +
(months ? ymSign + months + 'M' : '') +
(days ? daysSign + days + 'D' : '') +
(hours || minutes || seconds ? 'T' : '') +
(hours ? hmsSign + hours + 'H' : '') +
(minutes ? hmsSign + minutes + 'M' : '') +
(seconds ? hmsSign + s + 'S' : '')
);
}
var proto$2 = Duration.prototype;
proto$2.isValid = isValid$1;
proto$2.abs = abs;
proto$2.add = add$1;
proto$2.subtract = subtract$1;
proto$2.as = as;
proto$2.asMilliseconds = asMilliseconds;
proto$2.asSeconds = asSeconds;
proto$2.asMinutes = asMinutes;
proto$2.asHours = asHours;
proto$2.asDays = asDays;
proto$2.asWeeks = asWeeks;
proto$2.asMonths = asMonths;
proto$2.asQuarters = asQuarters;
proto$2.asYears = asYears;
proto$2.valueOf = valueOf$1;
proto$2._bubble = bubble;
proto$2.clone = clone$1;
proto$2.get = get$2;
proto$2.milliseconds = milliseconds;
proto$2.seconds = seconds;
proto$2.minutes = minutes;
proto$2.hours = hours;
proto$2.days = days;
proto$2.weeks = weeks;
proto$2.months = months;
proto$2.years = years;
proto$2.humanize = humanize;
proto$2.toISOString = toISOString$1;
proto$2.toString = toISOString$1;
proto$2.toJSON = toISOString$1;
proto$2.locale = locale;
proto$2.localeData = localeData;
proto$2.toIsoString = deprecate(
'toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)',
toISOString$1
);
proto$2.lang = lang;
// FORMATTING
addFormatToken('X', 0, 0, 'unix');
addFormatToken('x', 0, 0, 'valueOf');
// PARSING
addRegexToken('x', matchSigned);
addRegexToken('X', matchTimestamp);
addParseToken('X', function (input, array, config) {
config._d = new Date(parseFloat(input) * 1000);
});
addParseToken('x', function (input, array, config) {
config._d = new Date(toInt(input));
});
//! moment.js
hooks.version = '2.29.4';
setHookCallback(createLocal);
hooks.fn = proto;
hooks.min = min;
hooks.max = max;
hooks.now = now;
hooks.utc = createUTC;
hooks.unix = createUnix;
hooks.months = listMonths;
hooks.isDate = isDate;
hooks.locale = getSetGlobalLocale;
hooks.invalid = createInvalid;
hooks.duration = createDuration;
hooks.isMoment = isMoment;
hooks.weekdays = listWeekdays;
hooks.parseZone = createInZone;
hooks.localeData = getLocale;
hooks.isDuration = isDuration;
hooks.monthsShort = listMonthsShort;
hooks.weekdaysMin = listWeekdaysMin;
hooks.defineLocale = defineLocale;
hooks.updateLocale = updateLocale;
hooks.locales = listLocales;
hooks.weekdaysShort = listWeekdaysShort;
hooks.normalizeUnits = normalizeUnits;
hooks.relativeTimeRounding = getSetRelativeTimeRounding;
hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
hooks.calendarFormat = getCalendarFormat;
hooks.prototype = proto;
// currently HTML5 input type only supports 24-hour formats
hooks.HTML5_FMT = {
DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // <input type="datetime-local" />
DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // <input type="datetime-local" step="1" />
DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // <input type="datetime-local" step="0.001" />
DATE: 'YYYY-MM-DD', // <input type="date" />
TIME: 'HH:mm', // <input type="time" />
TIME_SECONDS: 'HH:mm:ss', // <input type="time" step="1" />
TIME_MS: 'HH:mm:ss.SSS', // <input type="time" step="0.001" />
WEEK: 'GGGG-[W]WW', // <input type="week" />
MONTH: 'YYYY-MM', // <input type="month" />
};
return hooks;
})));
vendor/wp-polyfill-node-contains.js 0000666 00000001203 15123355174 0013422 0 ustar 00
// Node.prototype.contains
(function() {
function contains(node) {
if (!(0 in arguments)) {
throw new TypeError('1 argument is required');
}
do {
if (this === node) {
return true;
}
// eslint-disable-next-line no-cond-assign
} while (node = node && node.parentNode);
return false;
}
// IE
if ('HTMLElement' in self && 'contains' in HTMLElement.prototype) {
try {
delete HTMLElement.prototype.contains;
// eslint-disable-next-line no-empty
} catch (e) {}
}
if ('Node' in self) {
Node.prototype.contains = contains;
} else {
document.contains = Element.prototype.contains = contains;
}
}());
vendor/wp-polyfill-fetch.js 0000666 00000043721 15123355174 0011765 0 ustar 00 (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.WHATWGFetch = {})));
}(this, (function (exports) { 'use strict';
var global =
(typeof globalThis !== 'undefined' && globalThis) ||
(typeof self !== 'undefined' && self) ||
(typeof global !== 'undefined' && global);
var support = {
searchParams: 'URLSearchParams' in global,
iterable: 'Symbol' in global && 'iterator' in Symbol,
blob:
'FileReader' in global &&
'Blob' in global &&
(function() {
try {
new Blob();
return true
} catch (e) {
return false
}
})(),
formData: 'FormData' in global,
arrayBuffer: 'ArrayBuffer' in global
};
function isDataView(obj) {
return obj && DataView.prototype.isPrototypeOf(obj)
}
if (support.arrayBuffer) {
var viewClasses = [
'[object Int8Array]',
'[object Uint8Array]',
'[object Uint8ClampedArray]',
'[object Int16Array]',
'[object Uint16Array]',
'[object Int32Array]',
'[object Uint32Array]',
'[object Float32Array]',
'[object Float64Array]'
];
var isArrayBufferView =
ArrayBuffer.isView ||
function(obj) {
return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1
};
}
function normalizeName(name) {
if (typeof name !== 'string') {
name = String(name);
}
if (/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(name) || name === '') {
throw new TypeError('Invalid character in header field name: "' + name + '"')
}
return name.toLowerCase()
}
function normalizeValue(value) {
if (typeof value !== 'string') {
value = String(value);
}
return value
}
// Build a destructive iterator for the value list
function iteratorFor(items) {
var iterator = {
next: function() {
var value = items.shift();
return {done: value === undefined, value: value}
}
};
if (support.iterable) {
iterator[Symbol.iterator] = function() {
return iterator
};
}
return iterator
}
function Headers(headers) {
this.map = {};
if (headers instanceof Headers) {
headers.forEach(function(value, name) {
this.append(name, value);
}, this);
} else if (Array.isArray(headers)) {
headers.forEach(function(header) {
this.append(header[0], header[1]);
}, this);
} else if (headers) {
Object.getOwnPropertyNames(headers).forEach(function(name) {
this.append(name, headers[name]);
}, this);
}
}
Headers.prototype.append = function(name, value) {
name = normalizeName(name);
value = normalizeValue(value);
var oldValue = this.map[name];
this.map[name] = oldValue ? oldValue + ', ' + value : value;
};
Headers.prototype['delete'] = function(name) {
delete this.map[normalizeName(name)];
};
Headers.prototype.get = function(name) {
name = normalizeName(name);
return this.has(name) ? this.map[name] : null
};
Headers.prototype.has = function(name) {
return this.map.hasOwnProperty(normalizeName(name))
};
Headers.prototype.set = function(name, value) {
this.map[normalizeName(name)] = normalizeValue(value);
};
Headers.prototype.forEach = function(callback, thisArg) {
for (var name in this.map) {
if (this.map.hasOwnProperty(name)) {
callback.call(thisArg, this.map[name], name, this);
}
}
};
Headers.prototype.keys = function() {
var items = [];
this.forEach(function(value, name) {
items.push(name);
});
return iteratorFor(items)
};
Headers.prototype.values = function() {
var items = [];
this.forEach(function(value) {
items.push(value);
});
return iteratorFor(items)
};
Headers.prototype.entries = function() {
var items = [];
this.forEach(function(value, name) {
items.push([name, value]);
});
return iteratorFor(items)
};
if (support.iterable) {
Headers.prototype[Symbol.iterator] = Headers.prototype.entries;
}
function consumed(body) {
if (body.bodyUsed) {
return Promise.reject(new TypeError('Already read'))
}
body.bodyUsed = true;
}
function fileReaderReady(reader) {
return new Promise(function(resolve, reject) {
reader.onload = function() {
resolve(reader.result);
};
reader.onerror = function() {
reject(reader.error);
};
})
}
function readBlobAsArrayBuffer(blob) {
var reader = new FileReader();
var promise = fileReaderReady(reader);
reader.readAsArrayBuffer(blob);
return promise
}
function readBlobAsText(blob) {
var reader = new FileReader();
var promise = fileReaderReady(reader);
reader.readAsText(blob);
return promise
}
function readArrayBufferAsText(buf) {
var view = new Uint8Array(buf);
var chars = new Array(view.length);
for (var i = 0; i < view.length; i++) {
chars[i] = String.fromCharCode(view[i]);
}
return chars.join('')
}
function bufferClone(buf) {
if (buf.slice) {
return buf.slice(0)
} else {
var view = new Uint8Array(buf.byteLength);
view.set(new Uint8Array(buf));
return view.buffer
}
}
function Body() {
this.bodyUsed = false;
this._initBody = function(body) {
/*
fetch-mock wraps the Response object in an ES6 Proxy to
provide useful test harness features such as flush. However, on
ES5 browsers without fetch or Proxy support pollyfills must be used;
the proxy-pollyfill is unable to proxy an attribute unless it exists
on the object before the Proxy is created. This change ensures
Response.bodyUsed exists on the instance, while maintaining the
semantic of setting Request.bodyUsed in the constructor before
_initBody is called.
*/
this.bodyUsed = this.bodyUsed;
this._bodyInit = body;
if (!body) {
this._bodyText = '';
} else if (typeof body === 'string') {
this._bodyText = body;
} else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
this._bodyBlob = body;
} else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
this._bodyFormData = body;
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
this._bodyText = body.toString();
} else if (support.arrayBuffer && support.blob && isDataView(body)) {
this._bodyArrayBuffer = bufferClone(body.buffer);
// IE 10-11 can't handle a DataView body.
this._bodyInit = new Blob([this._bodyArrayBuffer]);
} else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
this._bodyArrayBuffer = bufferClone(body);
} else {
this._bodyText = body = Object.prototype.toString.call(body);
}
if (!this.headers.get('content-type')) {
if (typeof body === 'string') {
this.headers.set('content-type', 'text/plain;charset=UTF-8');
} else if (this._bodyBlob && this._bodyBlob.type) {
this.headers.set('content-type', this._bodyBlob.type);
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
}
}
};
if (support.blob) {
this.blob = function() {
var rejected = consumed(this);
if (rejected) {
return rejected
}
if (this._bodyBlob) {
return Promise.resolve(this._bodyBlob)
} else if (this._bodyArrayBuffer) {
return Promise.resolve(new Blob([this._bodyArrayBuffer]))
} else if (this._bodyFormData) {
throw new Error('could not read FormData body as blob')
} else {
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.text = function() {
var rejected = consumed(this);
if (rejected) {
return rejected
}
if (this._bodyBlob) {
return readBlobAsText(this._bodyBlob)
} else if (this._bodyArrayBuffer) {
return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))
} else if (this._bodyFormData) {
throw new Error('could not read FormData body as text')
} else {
return Promise.resolve(this._bodyText)
}
};
if (support.formData) {
this.formData = function() {
return this.text().then(decode)
};
}
this.json = function() {
return this.text().then(JSON.parse)
};
return this
}
// HTTP methods whose capitalization should be normalized
var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'];
function normalizeMethod(method) {
var upcased = method.toUpperCase();
return methods.indexOf(upcased) > -1 ? upcased : method
}
function Request(input, options) {
if (!(this instanceof Request)) {
throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.')
}
options = options || {};
var body = options.body;
if (input instanceof Request) {
if (input.bodyUsed) {
throw new TypeError('Already read')
}
this.url = input.url;
this.credentials = input.credentials;
if (!options.headers) {
this.headers = new Headers(input.headers);
}
this.method = input.method;
this.mode = input.mode;
this.signal = input.signal;
if (!body && input._bodyInit != null) {
body = input._bodyInit;
input.bodyUsed = true;
}
} else {
this.url = String(input);
}
this.credentials = options.credentials || this.credentials || 'same-origin';
if (options.headers || !this.headers) {
this.headers = new Headers(options.headers);
}
this.method = normalizeMethod(options.method || this.method || 'GET');
this.mode = options.mode || this.mode || null;
this.signal = options.signal || this.signal;
this.referrer = null;
if ((this.method === 'GET' || this.method === 'HEAD') && body) {
throw new TypeError('Body not allowed for GET or HEAD requests')
}
this._initBody(body);
if (this.method === 'GET' || this.method === 'HEAD') {
if (options.cache === 'no-store' || options.cache === 'no-cache') {
// Search for a '_' parameter in the query string
var reParamSearch = /([?&])_=[^&]*/;
if (reParamSearch.test(this.url)) {
// If it already exists then set the value with the current time
this.url = this.url.replace(reParamSearch, '$1_=' + new Date().getTime());
} else {
// Otherwise add a new '_' parameter to the end with the current time
var reQueryString = /\?/;
this.url += (reQueryString.test(this.url) ? '&' : '?') + '_=' + new Date().getTime();
}
}
}
}
Request.prototype.clone = function() {
return new Request(this, {body: this._bodyInit})
};
function decode(body) {
var form = new FormData();
body
.trim()
.split('&')
.forEach(function(bytes) {
if (bytes) {
var split = bytes.split('=');
var name = split.shift().replace(/\+/g, ' ');
var value = split.join('=').replace(/\+/g, ' ');
form.append(decodeURIComponent(name), decodeURIComponent(value));
}
});
return form
}
function parseHeaders(rawHeaders) {
var headers = new Headers();
// Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space
// https://tools.ietf.org/html/rfc7230#section-3.2
var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' ');
// Avoiding split via regex to work around a common IE11 bug with the core-js 3.6.0 regex polyfill
// https://github.com/github/fetch/issues/748
// https://github.com/zloirock/core-js/issues/751
preProcessedHeaders
.split('\r')
.map(function(header) {
return header.indexOf('\n') === 0 ? header.substr(1, header.length) : header
})
.forEach(function(line) {
var parts = line.split(':');
var key = parts.shift().trim();
if (key) {
var value = parts.join(':').trim();
headers.append(key, value);
}
});
return headers
}
Body.call(Request.prototype);
function Response(bodyInit, options) {
if (!(this instanceof Response)) {
throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.')
}
if (!options) {
options = {};
}
this.type = 'default';
this.status = options.status === undefined ? 200 : options.status;
this.ok = this.status >= 200 && this.status < 300;
this.statusText = options.statusText === undefined ? '' : '' + options.statusText;
this.headers = new Headers(options.headers);
this.url = options.url || '';
this._initBody(bodyInit);
}
Body.call(Response.prototype);
Response.prototype.clone = function() {
return new Response(this._bodyInit, {
status: this.status,
statusText: this.statusText,
headers: new Headers(this.headers),
url: this.url
})
};
Response.error = function() {
var response = new Response(null, {status: 0, statusText: ''});
response.type = 'error';
return response
};
var redirectStatuses = [301, 302, 303, 307, 308];
Response.redirect = function(url, status) {
if (redirectStatuses.indexOf(status) === -1) {
throw new RangeError('Invalid status code')
}
return new Response(null, {status: status, headers: {location: url}})
};
exports.DOMException = global.DOMException;
try {
new exports.DOMException();
} catch (err) {
exports.DOMException = function(message, name) {
this.message = message;
this.name = name;
var error = Error(message);
this.stack = error.stack;
};
exports.DOMException.prototype = Object.create(Error.prototype);
exports.DOMException.prototype.constructor = exports.DOMException;
}
function fetch(input, init) {
return new Promise(function(resolve, reject) {
var request = new Request(input, init);
if (request.signal && request.signal.aborted) {
return reject(new exports.DOMException('Aborted', 'AbortError'))
}
var xhr = new XMLHttpRequest();
function abortXhr() {
xhr.abort();
}
xhr.onload = function() {
var options = {
status: xhr.status,
statusText: xhr.statusText,
headers: parseHeaders(xhr.getAllResponseHeaders() || '')
};
options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL');
var body = 'response' in xhr ? xhr.response : xhr.responseText;
setTimeout(function() {
resolve(new Response(body, options));
}, 0);
};
xhr.onerror = function() {
setTimeout(function() {
reject(new TypeError('Network request failed'));
}, 0);
};
xhr.ontimeout = function() {
setTimeout(function() {
reject(new TypeError('Network request failed'));
}, 0);
};
xhr.onabort = function() {
setTimeout(function() {
reject(new exports.DOMException('Aborted', 'AbortError'));
}, 0);
};
function fixUrl(url) {
try {
return url === '' && global.location.href ? global.location.href : url
} catch (e) {
return url
}
}
xhr.open(request.method, fixUrl(request.url), true);
if (request.credentials === 'include') {
xhr.withCredentials = true;
} else if (request.credentials === 'omit') {
xhr.withCredentials = false;
}
if ('responseType' in xhr) {
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
) {
xhr.responseType = 'arraybuffer';
}
}
if (init && typeof init.headers === 'object' && !(init.headers instanceof Headers)) {
Object.getOwnPropertyNames(init.headers).forEach(function(name) {
xhr.setRequestHeader(name, normalizeValue(init.headers[name]));
});
} else {
request.headers.forEach(function(value, name) {
xhr.setRequestHeader(name, value);
});
}
if (request.signal) {
request.signal.addEventListener('abort', abortXhr);
xhr.onreadystatechange = function() {
// DONE (success or failure)
if (xhr.readyState === 4) {
request.signal.removeEventListener('abort', abortXhr);
}
};
}
xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit);
})
}
fetch.polyfill = true;
if (!global.fetch) {
global.fetch = fetch;
global.Headers = Headers;
global.Request = Request;
global.Response = Response;
}
exports.Headers = Headers;
exports.Request = Request;
exports.Response = Response;
exports.fetch = fetch;
Object.defineProperty(exports, '__esModule', { value: true });
})));
vendor/lodash.min.js 0000666 00000212672 15123355174 0010457 0 ustar 00 /**
* @license
* Lodash <https://lodash.com/>
* Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
(function(){function n(n,t,r){switch(r.length){case 0:return n.call(t);case 1:return n.call(t,r[0]);case 2:return n.call(t,r[0],r[1]);case 3:return n.call(t,r[0],r[1],r[2])}return n.apply(t,r)}function t(n,t,r,e){for(var u=-1,i=null==n?0:n.length;++u<i;){var o=n[u];t(e,o,r(o),n)}return e}function r(n,t){for(var r=-1,e=null==n?0:n.length;++r<e&&!1!==t(n[r],r,n););return n}function e(n,t){for(var r=null==n?0:n.length;r--&&!1!==t(n[r],r,n););return n}function u(n,t){for(var r=-1,e=null==n?0:n.length;++r<e;)if(!t(n[r],r,n))return!1;return!0}function i(n,t){for(var r=-1,e=null==n?0:n.length,u=0,i=[];++r<e;){var o=n[r];t(o,r,n)&&(i[u++]=o)}return i}function o(n,t){return!(null==n||!n.length)&&g(n,t,0)>-1}function f(n,t,r){for(var e=-1,u=null==n?0:n.length;++e<u;)if(r(t,n[e]))return!0;return!1}function c(n,t){for(var r=-1,e=null==n?0:n.length,u=Array(e);++r<e;)u[r]=t(n[r],r,n);return u}function a(n,t){for(var r=-1,e=t.length,u=n.length;++r<e;)n[u+r]=t[r];return n}function l(n,t,r,e){var u=-1,i=null==n?0:n.length;for(e&&i&&(r=n[++u]);++u<i;)r=t(r,n[u],u,n);return r}function s(n,t,r,e){var u=null==n?0:n.length;for(e&&u&&(r=n[--u]);u--;)r=t(r,n[u],u,n);return r}function h(n,t){for(var r=-1,e=null==n?0:n.length;++r<e;)if(t(n[r],r,n))return!0;return!1}function p(n){return n.match(Yn)||[]}function _(n,t,r){var e;return r(n,(function(n,r,u){if(t(n,r,u))return e=r,!1})),e}function v(n,t,r,e){for(var u=n.length,i=r+(e?1:-1);e?i--:++i<u;)if(t(n[i],i,n))return i;return-1}function g(n,t,r){return t==t?function(n,t,r){for(var e=r-1,u=n.length;++e<u;)if(n[e]===t)return e;return-1}(n,t,r):v(n,d,r)}function y(n,t,r,e){for(var u=r-1,i=n.length;++u<i;)if(e(n[u],t))return u;return-1}function d(n){return n!=n}function b(n,t){var r=null==n?0:n.length;return r?j(n,t)/r:nn}function w(n){return function(t){return null==t?P:t[n]}}function m(n){return function(t){return null==n?P:n[t]}}function x(n,t,r,e,u){return u(n,(function(n,u,i){r=e?(e=!1,n):t(r,n,u,i)})),r}function j(n,t){for(var r,e=-1,u=n.length;++e<u;){var i=t(n[e]);i!==P&&(r=r===P?i:r+i)}return r}function A(n,t){for(var r=-1,e=Array(n);++r<n;)e[r]=t(r);return e}function k(n){return n?n.slice(0,F(n)+1).replace(Kn,""):n}function O(n){return function(t){return n(t)}}function I(n,t){return c(t,(function(t){return n[t]}))}function R(n,t){return n.has(t)}function z(n,t){for(var r=-1,e=n.length;++r<e&&g(t,n[r],0)>-1;);return r}function E(n,t){for(var r=n.length;r--&&g(t,n[r],0)>-1;);return r}function S(n,t){for(var r=n.length,e=0;r--;)n[r]===t&&++e;return e}function W(n){return"\\"+Jt[n]}function L(n){return qt.test(n)}function C(n){return Zt.test(n)}function U(n){var t=-1,r=Array(n.size);return n.forEach((function(n,e){r[++t]=[e,n]})),r}function B(n,t){return function(r){return n(t(r))}}function T(n,t){for(var r=-1,e=n.length,u=0,i=[];++r<e;){var o=n[r];o!==t&&o!==K||(n[r]=K,i[u++]=r)}return i}function $(n){var t=-1,r=Array(n.size);return n.forEach((function(n){r[++t]=n})),r}function D(n){return L(n)?function(n){for(var t=Nt.lastIndex=0;Nt.test(n);)++t;return t}(n):pr(n)}function M(n){return L(n)?function(n){return n.match(Nt)||[]}(n):function(n){return n.split("")}(n)}function F(n){for(var t=n.length;t--&&Vn.test(n.charAt(t)););return t}function N(n){return n.match(Pt)||[]}var P,q="Expected a function",Z="__lodash_hash_undefined__",K="__lodash_placeholder__",V=16,G=32,H=64,J=128,Y=256,Q=1/0,X=9007199254740991,nn=NaN,tn=4294967295,rn=[["ary",J],["bind",1],["bindKey",2],["curry",8],["curryRight",V],["flip",512],["partial",G],["partialRight",H],["rearg",Y]],en="[object Arguments]",un="[object Array]",on="[object Boolean]",fn="[object Date]",cn="[object Error]",an="[object Function]",ln="[object GeneratorFunction]",sn="[object Map]",hn="[object Number]",pn="[object Object]",_n="[object Promise]",vn="[object RegExp]",gn="[object Set]",yn="[object String]",dn="[object Symbol]",bn="[object WeakMap]",wn="[object ArrayBuffer]",mn="[object DataView]",xn="[object Float32Array]",jn="[object Float64Array]",An="[object Int8Array]",kn="[object Int16Array]",On="[object Int32Array]",In="[object Uint8Array]",Rn="[object Uint8ClampedArray]",zn="[object Uint16Array]",En="[object Uint32Array]",Sn=/\b__p \+= '';/g,Wn=/\b(__p \+=) '' \+/g,Ln=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Cn=/&(?:amp|lt|gt|quot|#39);/g,Un=/[&<>"']/g,Bn=RegExp(Cn.source),Tn=RegExp(Un.source),$n=/<%-([\s\S]+?)%>/g,Dn=/<%([\s\S]+?)%>/g,Mn=/<%=([\s\S]+?)%>/g,Fn=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Nn=/^\w*$/,Pn=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,qn=/[\\^$.*+?()[\]{}|]/g,Zn=RegExp(qn.source),Kn=/^\s+/,Vn=/\s/,Gn=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Hn=/\{\n\/\* \[wrapped with (.+)\] \*/,Jn=/,? & /,Yn=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,Qn=/[()=,{}\[\]\/\s]/,Xn=/\\(\\)?/g,nt=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,tt=/\w*$/,rt=/^[-+]0x[0-9a-f]+$/i,et=/^0b[01]+$/i,ut=/^\[object .+?Constructor\]$/,it=/^0o[0-7]+$/i,ot=/^(?:0|[1-9]\d*)$/,ft=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,ct=/($^)/,at=/['\n\r\u2028\u2029\\]/g,lt="\\ud800-\\udfff",st="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",ht="\\u2700-\\u27bf",pt="a-z\\xdf-\\xf6\\xf8-\\xff",_t="A-Z\\xc0-\\xd6\\xd8-\\xde",vt="\\ufe0e\\ufe0f",gt="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",yt="['’]",dt="["+lt+"]",bt="["+gt+"]",wt="["+st+"]",mt="\\d+",xt="["+ht+"]",jt="["+pt+"]",At="[^"+lt+gt+mt+ht+pt+_t+"]",kt="\\ud83c[\\udffb-\\udfff]",Ot="[^"+lt+"]",It="(?:\\ud83c[\\udde6-\\uddff]){2}",Rt="[\\ud800-\\udbff][\\udc00-\\udfff]",zt="["+_t+"]",Et="\\u200d",St="(?:"+jt+"|"+At+")",Wt="(?:"+zt+"|"+At+")",Lt="(?:['’](?:d|ll|m|re|s|t|ve))?",Ct="(?:['’](?:D|LL|M|RE|S|T|VE))?",Ut="(?:"+wt+"|"+kt+")"+"?",Bt="["+vt+"]?",Tt=Bt+Ut+("(?:\\u200d(?:"+[Ot,It,Rt].join("|")+")"+Bt+Ut+")*"),$t="(?:"+[xt,It,Rt].join("|")+")"+Tt,Dt="(?:"+[Ot+wt+"?",wt,It,Rt,dt].join("|")+")",Mt=RegExp(yt,"g"),Ft=RegExp(wt,"g"),Nt=RegExp(kt+"(?="+kt+")|"+Dt+Tt,"g"),Pt=RegExp([zt+"?"+jt+"+"+Lt+"(?="+[bt,zt,"$"].join("|")+")",Wt+"+"+Ct+"(?="+[bt,zt+St,"$"].join("|")+")",zt+"?"+St+"+"+Lt,zt+"+"+Ct,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",mt,$t].join("|"),"g"),qt=RegExp("["+Et+lt+st+vt+"]"),Zt=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,Kt=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],Vt=-1,Gt={};Gt[xn]=Gt[jn]=Gt[An]=Gt[kn]=Gt[On]=Gt[In]=Gt[Rn]=Gt[zn]=Gt[En]=!0,Gt[en]=Gt[un]=Gt[wn]=Gt[on]=Gt[mn]=Gt[fn]=Gt[cn]=Gt[an]=Gt[sn]=Gt[hn]=Gt[pn]=Gt[vn]=Gt[gn]=Gt[yn]=Gt[bn]=!1;var Ht={};Ht[en]=Ht[un]=Ht[wn]=Ht[mn]=Ht[on]=Ht[fn]=Ht[xn]=Ht[jn]=Ht[An]=Ht[kn]=Ht[On]=Ht[sn]=Ht[hn]=Ht[pn]=Ht[vn]=Ht[gn]=Ht[yn]=Ht[dn]=Ht[In]=Ht[Rn]=Ht[zn]=Ht[En]=!0,Ht[cn]=Ht[an]=Ht[bn]=!1;var Jt={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},Yt=parseFloat,Qt=parseInt,Xt="object"==typeof global&&global&&global.Object===Object&&global,nr="object"==typeof self&&self&&self.Object===Object&&self,tr=Xt||nr||Function("return this")(),rr="object"==typeof exports&&exports&&!exports.nodeType&&exports,er=rr&&"object"==typeof module&&module&&!module.nodeType&&module,ur=er&&er.exports===rr,ir=ur&&Xt.process,or=function(){try{var n=er&&er.require&&er.require("util").types;return n||ir&&ir.binding&&ir.binding("util")}catch(n){}}(),fr=or&&or.isArrayBuffer,cr=or&&or.isDate,ar=or&&or.isMap,lr=or&&or.isRegExp,sr=or&&or.isSet,hr=or&&or.isTypedArray,pr=w("length"),_r=m({"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"}),vr=m({"&":"&","<":"<",">":">",'"':""","'":"'"}),gr=m({"&":"&","<":"<",">":">",""":'"',"'":"'"}),yr=function m(Vn){function Yn(n){if(Mu(n)&&!Sf(n)&&!(n instanceof ht)){if(n instanceof st)return n;if(zi.call(n,"__wrapped__"))return hu(n)}return new st(n)}function lt(){}function st(n,t){this.__wrapped__=n,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=P}function ht(n){this.__wrapped__=n,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=tn,this.__views__=[]}function pt(n){var t=-1,r=null==n?0:n.length;for(this.clear();++t<r;){var e=n[t];this.set(e[0],e[1])}}function _t(n){var t=-1,r=null==n?0:n.length;for(this.clear();++t<r;){var e=n[t];this.set(e[0],e[1])}}function vt(n){var t=-1,r=null==n?0:n.length;for(this.clear();++t<r;){var e=n[t];this.set(e[0],e[1])}}function gt(n){var t=-1,r=null==n?0:n.length;for(this.__data__=new vt;++t<r;)this.add(n[t])}function yt(n){this.size=(this.__data__=new _t(n)).size}function dt(n,t){var r=Sf(n),e=!r&&Ef(n),u=!r&&!e&&Lf(n),i=!r&&!e&&!u&&$f(n),o=r||e||u||i,f=o?A(n.length,xi):[],c=f.length;for(var a in n)!t&&!zi.call(n,a)||o&&("length"==a||u&&("offset"==a||"parent"==a)||i&&("buffer"==a||"byteLength"==a||"byteOffset"==a)||He(a,c))||f.push(a);return f}function bt(n){var t=n.length;return t?n[Wr(0,t-1)]:P}function wt(n,t){return cu(ae(n),zt(t,0,n.length))}function mt(n){return cu(ae(n))}function xt(n,t,r){(r===P||Wu(n[t],r))&&(r!==P||t in n)||It(n,t,r)}function jt(n,t,r){var e=n[t];zi.call(n,t)&&Wu(e,r)&&(r!==P||t in n)||It(n,t,r)}function At(n,t){for(var r=n.length;r--;)if(Wu(n[r][0],t))return r;return-1}function kt(n,t,r,e){return Ro(n,(function(n,u,i){t(e,n,r(n),i)})),e}function Ot(n,t){return n&&le(t,ni(t),n)}function It(n,t,r){"__proto__"==t&&Vi?Vi(n,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):n[t]=r}function Rt(n,t){for(var r=-1,e=t.length,u=vi(e),i=null==n;++r<e;)u[r]=i?P:Qu(n,t[r]);return u}function zt(n,t,r){return n==n&&(r!==P&&(n=n<=r?n:r),t!==P&&(n=n>=t?n:t)),n}function Et(n,t,e,u,i,o){var f,c=1&t,a=2&t,l=4&t;if(e&&(f=i?e(n,u,i,o):e(n)),f!==P)return f;if(!Du(n))return n;var s=Sf(n);if(s){if(f=function(n){var t=n.length,r=new n.constructor(t);return t&&"string"==typeof n[0]&&zi.call(n,"index")&&(r.index=n.index,r.input=n.input),r}(n),!c)return ae(n,f)}else{var h=Mo(n),p=h==an||h==ln;if(Lf(n))return ee(n,c);if(h==pn||h==en||p&&!i){if(f=a||p?{}:Ve(n),!c)return a?function(n,t){return le(n,Do(n),t)}(n,function(n,t){return n&&le(t,ti(t),n)}(f,n)):function(n,t){return le(n,$o(n),t)}(n,Ot(f,n))}else{if(!Ht[h])return i?n:{};f=function(n,t,r){var e=n.constructor;switch(t){case wn:return ue(n);case on:case fn:return new e(+n);case mn:return function(n,t){return new n.constructor(t?ue(n.buffer):n.buffer,n.byteOffset,n.byteLength)}(n,r);case xn:case jn:case An:case kn:case On:case In:case Rn:case zn:case En:return ie(n,r);case sn:return new e;case hn:case yn:return new e(n);case vn:return function(n){var t=new n.constructor(n.source,tt.exec(n));return t.lastIndex=n.lastIndex,t}(n);case gn:return new e;case dn:return function(n){return ko?wi(ko.call(n)):{}}(n)}}(n,h,c)}}o||(o=new yt);var _=o.get(n);if(_)return _;o.set(n,f),Tf(n)?n.forEach((function(r){f.add(Et(r,t,e,r,n,o))})):Uf(n)&&n.forEach((function(r,u){f.set(u,Et(r,t,e,u,n,o))}));var v=s?P:(l?a?De:$e:a?ti:ni)(n);return r(v||n,(function(r,u){v&&(r=n[u=r]),jt(f,u,Et(r,t,e,u,n,o))})),f}function St(n,t,r){var e=r.length;if(null==n)return!e;for(n=wi(n);e--;){var u=r[e],i=t[u],o=n[u];if(o===P&&!(u in n)||!i(o))return!1}return!0}function Wt(n,t,r){if("function"!=typeof n)throw new ji(q);return Po((function(){n.apply(P,r)}),t)}function Lt(n,t,r,e){var u=-1,i=o,a=!0,l=n.length,s=[],h=t.length;if(!l)return s;r&&(t=c(t,O(r))),e?(i=f,a=!1):t.length>=200&&(i=R,a=!1,t=new gt(t));n:for(;++u<l;){var p=n[u],_=null==r?p:r(p);if(p=e||0!==p?p:0,a&&_==_){for(var v=h;v--;)if(t[v]===_)continue n;s.push(p)}else i(t,_,e)||s.push(p)}return s}function Ct(n,t){var r=!0;return Ro(n,(function(n,e,u){return r=!!t(n,e,u)})),r}function Ut(n,t,r){for(var e=-1,u=n.length;++e<u;){var i=n[e],o=t(i);if(null!=o&&(f===P?o==o&&!qu(o):r(o,f)))var f=o,c=i}return c}function Bt(n,t){var r=[];return Ro(n,(function(n,e,u){t(n,e,u)&&r.push(n)})),r}function Tt(n,t,r,e,u){var i=-1,o=n.length;for(r||(r=Ge),u||(u=[]);++i<o;){var f=n[i];t>0&&r(f)?t>1?Tt(f,t-1,r,e,u):a(u,f):e||(u[u.length]=f)}return u}function $t(n,t){return n&&Eo(n,t,ni)}function Dt(n,t){return n&&So(n,t,ni)}function Nt(n,t){return i(t,(function(t){return Bu(n[t])}))}function Pt(n,t){for(var r=0,e=(t=te(t,n)).length;null!=n&&r<e;)n=n[au(t[r++])];return r&&r==e?n:P}function qt(n,t,r){var e=t(n);return Sf(n)?e:a(e,r(n))}function Zt(n){return null==n?n===P?"[object Undefined]":"[object Null]":Ki&&Ki in wi(n)?function(n){var t=zi.call(n,Ki),r=n[Ki];try{n[Ki]=P;var e=!0}catch(n){}var u=Wi.call(n);return e&&(t?n[Ki]=r:delete n[Ki]),u}(n):function(n){return Wi.call(n)}(n)}function Jt(n,t){return n>t}function Xt(n,t){return null!=n&&zi.call(n,t)}function nr(n,t){return null!=n&&t in wi(n)}function rr(n,t,r){for(var e=r?f:o,u=n[0].length,i=n.length,a=i,l=vi(i),s=1/0,h=[];a--;){var p=n[a];a&&t&&(p=c(p,O(t))),s=io(p.length,s),l[a]=!r&&(t||u>=120&&p.length>=120)?new gt(a&&p):P}p=n[0];var _=-1,v=l[0];n:for(;++_<u&&h.length<s;){var g=p[_],y=t?t(g):g;if(g=r||0!==g?g:0,!(v?R(v,y):e(h,y,r))){for(a=i;--a;){var d=l[a];if(!(d?R(d,y):e(n[a],y,r)))continue n}v&&v.push(y),h.push(g)}}return h}function er(t,r,e){var u=null==(t=eu(t,r=te(r,t)))?t:t[au(yu(r))];return null==u?P:n(u,t,e)}function ir(n){return Mu(n)&&Zt(n)==en}function or(n,t,r,e,u){return n===t||(null==n||null==t||!Mu(n)&&!Mu(t)?n!=n&&t!=t:function(n,t,r,e,u,i){var o=Sf(n),f=Sf(t),c=o?un:Mo(n),a=f?un:Mo(t),l=(c=c==en?pn:c)==pn,s=(a=a==en?pn:a)==pn,h=c==a;if(h&&Lf(n)){if(!Lf(t))return!1;o=!0,l=!1}if(h&&!l)return i||(i=new yt),o||$f(n)?Be(n,t,r,e,u,i):function(n,t,r,e,u,i,o){switch(r){case mn:if(n.byteLength!=t.byteLength||n.byteOffset!=t.byteOffset)return!1;n=n.buffer,t=t.buffer;case wn:return!(n.byteLength!=t.byteLength||!i(new $i(n),new $i(t)));case on:case fn:case hn:return Wu(+n,+t);case cn:return n.name==t.name&&n.message==t.message;case vn:case yn:return n==t+"";case sn:var f=U;case gn:var c=1&e;if(f||(f=$),n.size!=t.size&&!c)return!1;var a=o.get(n);if(a)return a==t;e|=2,o.set(n,t);var l=Be(f(n),f(t),e,u,i,o);return o.delete(n),l;case dn:if(ko)return ko.call(n)==ko.call(t)}return!1}(n,t,c,r,e,u,i);if(!(1&r)){var p=l&&zi.call(n,"__wrapped__"),_=s&&zi.call(t,"__wrapped__");if(p||_){var v=p?n.value():n,g=_?t.value():t;return i||(i=new yt),u(v,g,r,e,i)}}return!!h&&(i||(i=new yt),function(n,t,r,e,u,i){var o=1&r,f=$e(n),c=f.length;if(c!=$e(t).length&&!o)return!1;for(var a=c;a--;){var l=f[a];if(!(o?l in t:zi.call(t,l)))return!1}var s=i.get(n),h=i.get(t);if(s&&h)return s==t&&h==n;var p=!0;i.set(n,t),i.set(t,n);for(var _=o;++a<c;){var v=n[l=f[a]],g=t[l];if(e)var y=o?e(g,v,l,t,n,i):e(v,g,l,n,t,i);if(!(y===P?v===g||u(v,g,r,e,i):y)){p=!1;break}_||(_="constructor"==l)}if(p&&!_){var d=n.constructor,b=t.constructor;d!=b&&"constructor"in n&&"constructor"in t&&!("function"==typeof d&&d instanceof d&&"function"==typeof b&&b instanceof b)&&(p=!1)}return i.delete(n),i.delete(t),p}(n,t,r,e,u,i))}(n,t,r,e,or,u))}function pr(n,t,r,e){var u=r.length,i=u,o=!e;if(null==n)return!i;for(n=wi(n);u--;){var f=r[u];if(o&&f[2]?f[1]!==n[f[0]]:!(f[0]in n))return!1}for(;++u<i;){var c=(f=r[u])[0],a=n[c],l=f[1];if(o&&f[2]){if(a===P&&!(c in n))return!1}else{var s=new yt;if(e)var h=e(a,l,c,n,t,s);if(!(h===P?or(l,a,3,e,s):h))return!1}}return!0}function dr(n){return!(!Du(n)||function(n){return!!Si&&Si in n}(n))&&(Bu(n)?Ui:ut).test(lu(n))}function br(n){return"function"==typeof n?n:null==n?ci:"object"==typeof n?Sf(n)?kr(n[0],n[1]):Ar(n):hi(n)}function wr(n){if(!Xe(n))return eo(n);var t=[];for(var r in wi(n))zi.call(n,r)&&"constructor"!=r&&t.push(r);return t}function mr(n){if(!Du(n))return function(n){var t=[];if(null!=n)for(var r in wi(n))t.push(r);return t}(n);var t=Xe(n),r=[];for(var e in n)("constructor"!=e||!t&&zi.call(n,e))&&r.push(e);return r}function xr(n,t){return n<t}function jr(n,t){var r=-1,e=Lu(n)?vi(n.length):[];return Ro(n,(function(n,u,i){e[++r]=t(n,u,i)})),e}function Ar(n){var t=qe(n);return 1==t.length&&t[0][2]?tu(t[0][0],t[0][1]):function(r){return r===n||pr(r,n,t)}}function kr(n,t){return Ye(n)&&nu(t)?tu(au(n),t):function(r){var e=Qu(r,n);return e===P&&e===t?Xu(r,n):or(t,e,3)}}function Or(n,t,r,e,u){n!==t&&Eo(t,(function(i,o){if(u||(u=new yt),Du(i))!function(n,t,r,e,u,i,o){var f=iu(n,r),c=iu(t,r),a=o.get(c);if(a)return xt(n,r,a),P;var l=i?i(f,c,r+"",n,t,o):P,s=l===P;if(s){var h=Sf(c),p=!h&&Lf(c),_=!h&&!p&&$f(c);l=c,h||p||_?Sf(f)?l=f:Cu(f)?l=ae(f):p?(s=!1,l=ee(c,!0)):_?(s=!1,l=ie(c,!0)):l=[]:Nu(c)||Ef(c)?(l=f,Ef(f)?l=Ju(f):Du(f)&&!Bu(f)||(l=Ve(c))):s=!1}s&&(o.set(c,l),u(l,c,e,i,o),o.delete(c)),xt(n,r,l)}(n,t,o,r,Or,e,u);else{var f=e?e(iu(n,o),i,o+"",n,t,u):P;f===P&&(f=i),xt(n,o,f)}}),ti)}function Ir(n,t){var r=n.length;if(r)return He(t+=t<0?r:0,r)?n[t]:P}function Rr(n,t,r){t=t.length?c(t,(function(n){return Sf(n)?function(t){return Pt(t,1===n.length?n[0]:n)}:n})):[ci];var e=-1;return t=c(t,O(Ne())),function(n,t){var r=n.length;for(n.sort(t);r--;)n[r]=n[r].value;return n}(jr(n,(function(n,r,u){return{criteria:c(t,(function(t){return t(n)})),index:++e,value:n}})),(function(n,t){return function(n,t,r){for(var e=-1,u=n.criteria,i=t.criteria,o=u.length,f=r.length;++e<o;){var c=oe(u[e],i[e]);if(c)return e>=f?c:c*("desc"==r[e]?-1:1)}return n.index-t.index}(n,t,r)}))}function zr(n,t,r){for(var e=-1,u=t.length,i={};++e<u;){var o=t[e],f=Pt(n,o);r(f,o)&&Tr(i,te(o,n),f)}return i}function Er(n,t,r,e){var u=e?y:g,i=-1,o=t.length,f=n;for(n===t&&(t=ae(t)),r&&(f=c(n,O(r)));++i<o;)for(var a=0,l=t[i],s=r?r(l):l;(a=u(f,s,a,e))>-1;)f!==n&&Pi.call(f,a,1),Pi.call(n,a,1);return n}function Sr(n,t){for(var r=n?t.length:0,e=r-1;r--;){var u=t[r];if(r==e||u!==i){var i=u;He(u)?Pi.call(n,u,1):Vr(n,u)}}return n}function Wr(n,t){return n+Qi(co()*(t-n+1))}function Lr(n,t){var r="";if(!n||t<1||t>X)return r;do{t%2&&(r+=n),(t=Qi(t/2))&&(n+=n)}while(t);return r}function Cr(n,t){return qo(ru(n,t,ci),n+"")}function Ur(n){return bt(ei(n))}function Br(n,t){var r=ei(n);return cu(r,zt(t,0,r.length))}function Tr(n,t,r,e){if(!Du(n))return n;for(var u=-1,i=(t=te(t,n)).length,o=i-1,f=n;null!=f&&++u<i;){var c=au(t[u]),a=r;if("__proto__"===c||"constructor"===c||"prototype"===c)return n;if(u!=o){var l=f[c];(a=e?e(l,c,f):P)===P&&(a=Du(l)?l:He(t[u+1])?[]:{})}jt(f,c,a),f=f[c]}return n}function $r(n){return cu(ei(n))}function Dr(n,t,r){var e=-1,u=n.length;t<0&&(t=-t>u?0:u+t),(r=r>u?u:r)<0&&(r+=u),u=t>r?0:r-t>>>0,t>>>=0;for(var i=vi(u);++e<u;)i[e]=n[e+t];return i}function Mr(n,t){var r;return Ro(n,(function(n,e,u){return!(r=t(n,e,u))})),!!r}function Fr(n,t,r){var e=0,u=null==n?e:n.length;if("number"==typeof t&&t==t&&u<=2147483647){for(;e<u;){var i=e+u>>>1,o=n[i];null!==o&&!qu(o)&&(r?o<=t:o<t)?e=i+1:u=i}return u}return Nr(n,t,ci,r)}function Nr(n,t,r,e){var u=0,i=null==n?0:n.length;if(0===i)return 0;for(var o=(t=r(t))!=t,f=null===t,c=qu(t),a=t===P;u<i;){var l=Qi((u+i)/2),s=r(n[l]),h=s!==P,p=null===s,_=s==s,v=qu(s);if(o)var g=e||_;else g=a?_&&(e||h):f?_&&h&&(e||!p):c?_&&h&&!p&&(e||!v):!p&&!v&&(e?s<=t:s<t);g?u=l+1:i=l}return io(i,4294967294)}function Pr(n,t){for(var r=-1,e=n.length,u=0,i=[];++r<e;){var o=n[r],f=t?t(o):o;if(!r||!Wu(f,c)){var c=f;i[u++]=0===o?0:o}}return i}function qr(n){return"number"==typeof n?n:qu(n)?nn:+n}function Zr(n){if("string"==typeof n)return n;if(Sf(n))return c(n,Zr)+"";if(qu(n))return Oo?Oo.call(n):"";var t=n+"";return"0"==t&&1/n==-Q?"-0":t}function Kr(n,t,r){var e=-1,u=o,i=n.length,c=!0,a=[],l=a;if(r)c=!1,u=f;else if(i>=200){var s=t?null:Bo(n);if(s)return $(s);c=!1,u=R,l=new gt}else l=t?[]:a;n:for(;++e<i;){var h=n[e],p=t?t(h):h;if(h=r||0!==h?h:0,c&&p==p){for(var _=l.length;_--;)if(l[_]===p)continue n;t&&l.push(p),a.push(h)}else u(l,p,r)||(l!==a&&l.push(p),a.push(h))}return a}function Vr(n,t){return null==(n=eu(n,t=te(t,n)))||delete n[au(yu(t))]}function Gr(n,t,r,e){return Tr(n,t,r(Pt(n,t)),e)}function Hr(n,t,r,e){for(var u=n.length,i=e?u:-1;(e?i--:++i<u)&&t(n[i],i,n););return r?Dr(n,e?0:i,e?i+1:u):Dr(n,e?i+1:0,e?u:i)}function Jr(n,t){var r=n;return r instanceof ht&&(r=r.value()),l(t,(function(n,t){return t.func.apply(t.thisArg,a([n],t.args))}),r)}function Yr(n,t,r){var e=n.length;if(e<2)return e?Kr(n[0]):[];for(var u=-1,i=vi(e);++u<e;)for(var o=n[u],f=-1;++f<e;)f!=u&&(i[u]=Lt(i[u]||o,n[f],t,r));return Kr(Tt(i,1),t,r)}function Qr(n,t,r){for(var e=-1,u=n.length,i=t.length,o={};++e<u;)r(o,n[e],e<i?t[e]:P);return o}function Xr(n){return Cu(n)?n:[]}function ne(n){return"function"==typeof n?n:ci}function te(n,t){return Sf(n)?n:Ye(n,t)?[n]:Zo(Yu(n))}function re(n,t,r){var e=n.length;return r=r===P?e:r,!t&&r>=e?n:Dr(n,t,r)}function ee(n,t){if(t)return n.slice();var r=n.length,e=Di?Di(r):new n.constructor(r);return n.copy(e),e}function ue(n){var t=new n.constructor(n.byteLength);return new $i(t).set(new $i(n)),t}function ie(n,t){return new n.constructor(t?ue(n.buffer):n.buffer,n.byteOffset,n.length)}function oe(n,t){if(n!==t){var r=n!==P,e=null===n,u=n==n,i=qu(n),o=t!==P,f=null===t,c=t==t,a=qu(t);if(!f&&!a&&!i&&n>t||i&&o&&c&&!f&&!a||e&&o&&c||!r&&c||!u)return 1;if(!e&&!i&&!a&&n<t||a&&r&&u&&!e&&!i||f&&r&&u||!o&&u||!c)return-1}return 0}function fe(n,t,r,e){for(var u=-1,i=n.length,o=r.length,f=-1,c=t.length,a=uo(i-o,0),l=vi(c+a),s=!e;++f<c;)l[f]=t[f];for(;++u<o;)(s||u<i)&&(l[r[u]]=n[u]);for(;a--;)l[f++]=n[u++];return l}function ce(n,t,r,e){for(var u=-1,i=n.length,o=-1,f=r.length,c=-1,a=t.length,l=uo(i-f,0),s=vi(l+a),h=!e;++u<l;)s[u]=n[u];for(var p=u;++c<a;)s[p+c]=t[c];for(;++o<f;)(h||u<i)&&(s[p+r[o]]=n[u++]);return s}function ae(n,t){var r=-1,e=n.length;for(t||(t=vi(e));++r<e;)t[r]=n[r];return t}function le(n,t,r,e){var u=!r;r||(r={});for(var i=-1,o=t.length;++i<o;){var f=t[i],c=e?e(r[f],n[f],f,r,n):P;c===P&&(c=n[f]),u?It(r,f,c):jt(r,f,c)}return r}function se(n,r){return function(e,u){var i=Sf(e)?t:kt,o=r?r():{};return i(e,n,Ne(u,2),o)}}function he(n){return Cr((function(t,r){var e=-1,u=r.length,i=u>1?r[u-1]:P,o=u>2?r[2]:P;for(i=n.length>3&&"function"==typeof i?(u--,i):P,o&&Je(r[0],r[1],o)&&(i=u<3?P:i,u=1),t=wi(t);++e<u;){var f=r[e];f&&n(t,f,e,i)}return t}))}function pe(n,t){return function(r,e){if(null==r)return r;if(!Lu(r))return n(r,e);for(var u=r.length,i=t?u:-1,o=wi(r);(t?i--:++i<u)&&!1!==e(o[i],i,o););return r}}function _e(n){return function(t,r,e){for(var u=-1,i=wi(t),o=e(t),f=o.length;f--;){var c=o[n?f:++u];if(!1===r(i[c],c,i))break}return t}}function ve(n){return function(t){var r=L(t=Yu(t))?M(t):P,e=r?r[0]:t.charAt(0),u=r?re(r,1).join(""):t.slice(1);return e[n]()+u}}function ge(n){return function(t){return l(oi(ii(t).replace(Mt,"")),n,"")}}function ye(n){return function(){var t=arguments;switch(t.length){case 0:return new n;case 1:return new n(t[0]);case 2:return new n(t[0],t[1]);case 3:return new n(t[0],t[1],t[2]);case 4:return new n(t[0],t[1],t[2],t[3]);case 5:return new n(t[0],t[1],t[2],t[3],t[4]);case 6:return new n(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new n(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var r=Io(n.prototype),e=n.apply(r,t);return Du(e)?e:r}}function de(t,r,e){var u=ye(t);return function i(){for(var o=arguments.length,f=vi(o),c=o,a=Fe(i);c--;)f[c]=arguments[c];var l=o<3&&f[0]!==a&&f[o-1]!==a?[]:T(f,a);return(o-=l.length)<e?ze(t,r,me,i.placeholder,P,f,l,P,P,e-o):n(this&&this!==tr&&this instanceof i?u:t,this,f)}}function be(n){return function(t,r,e){var u=wi(t);if(!Lu(t)){var i=Ne(r,3);t=ni(t),r=function(n){return i(u[n],n,u)}}var o=n(t,r,e);return o>-1?u[i?t[o]:o]:P}}function we(n){return Te((function(t){var r=t.length,e=r,u=st.prototype.thru;for(n&&t.reverse();e--;){var i=t[e];if("function"!=typeof i)throw new ji(q);if(u&&!o&&"wrapper"==Me(i))var o=new st([],!0)}for(e=o?e:r;++e<r;){var f=Me(i=t[e]),c="wrapper"==f?To(i):P;o=c&&Qe(c[0])&&424==c[1]&&!c[4].length&&1==c[9]?o[Me(c[0])].apply(o,c[3]):1==i.length&&Qe(i)?o[f]():o.thru(i)}return function(){var n=arguments,e=n[0];if(o&&1==n.length&&Sf(e))return o.plant(e).value();for(var u=0,i=r?t[u].apply(this,n):e;++u<r;)i=t[u].call(this,i);return i}}))}function me(n,t,r,e,u,i,o,f,c,a){var l=t&J,s=1&t,h=2&t,p=24&t,_=512&t,v=h?P:ye(n);return function g(){for(var y=arguments.length,d=vi(y),b=y;b--;)d[b]=arguments[b];if(p)var w=Fe(g),m=S(d,w);if(e&&(d=fe(d,e,u,p)),i&&(d=ce(d,i,o,p)),y-=m,p&&y<a)return ze(n,t,me,g.placeholder,r,d,T(d,w),f,c,a-y);var x=s?r:this,j=h?x[n]:n;return y=d.length,f?d=uu(d,f):_&&y>1&&d.reverse(),l&&c<y&&(d.length=c),this&&this!==tr&&this instanceof g&&(j=v||ye(j)),j.apply(x,d)}}function xe(n,t){return function(r,e){return function(n,t,r,e){return $t(n,(function(n,u,i){t(e,r(n),u,i)})),e}(r,n,t(e),{})}}function je(n,t){return function(r,e){var u;if(r===P&&e===P)return t;if(r!==P&&(u=r),e!==P){if(u===P)return e;"string"==typeof r||"string"==typeof e?(r=Zr(r),e=Zr(e)):(r=qr(r),e=qr(e)),u=n(r,e)}return u}}function Ae(t){return Te((function(r){return r=c(r,O(Ne())),Cr((function(e){var u=this;return t(r,(function(t){return n(t,u,e)}))}))}))}function ke(n,t){var r=(t=t===P?" ":Zr(t)).length;if(r<2)return r?Lr(t,n):t;var e=Lr(t,Yi(n/D(t)));return L(t)?re(M(e),0,n).join(""):e.slice(0,n)}function Oe(t,r,e,u){var i=1&r,o=ye(t);return function r(){for(var f=-1,c=arguments.length,a=-1,l=u.length,s=vi(l+c),h=this&&this!==tr&&this instanceof r?o:t;++a<l;)s[a]=u[a];for(;c--;)s[a++]=arguments[++f];return n(h,i?e:this,s)}}function Ie(n){return function(t,r,e){return e&&"number"!=typeof e&&Je(t,r,e)&&(r=e=P),t=Ku(t),r===P?(r=t,t=0):r=Ku(r),function(n,t,r,e){for(var u=-1,i=uo(Yi((t-n)/(r||1)),0),o=vi(i);i--;)o[e?i:++u]=n,n+=r;return o}(t,r,e=e===P?t<r?1:-1:Ku(e),n)}}function Re(n){return function(t,r){return"string"==typeof t&&"string"==typeof r||(t=Hu(t),r=Hu(r)),n(t,r)}}function ze(n,t,r,e,u,i,o,f,c,a){var l=8&t;t|=l?G:H,4&(t&=~(l?H:G))||(t&=-4);var s=[n,t,u,l?i:P,l?o:P,l?P:i,l?P:o,f,c,a],h=r.apply(P,s);return Qe(n)&&No(h,s),h.placeholder=e,ou(h,n,t)}function Ee(n){var t=bi[n];return function(n,r){if(n=Hu(n),(r=null==r?0:io(Vu(r),292))&&to(n)){var e=(Yu(n)+"e").split("e");return+((e=(Yu(t(e[0]+"e"+(+e[1]+r)))+"e").split("e"))[0]+"e"+(+e[1]-r))}return t(n)}}function Se(n){return function(t){var r=Mo(t);return r==sn?U(t):r==gn?function(n){var t=-1,r=Array(n.size);return n.forEach((function(n){r[++t]=[n,n]})),r}(t):function(n,t){return c(t,(function(t){return[t,n[t]]}))}(t,n(t))}}function We(n,t,r,e,u,i,o,f){var c=2&t;if(!c&&"function"!=typeof n)throw new ji(q);var a=e?e.length:0;if(a||(t&=-97,e=u=P),o=o===P?o:uo(Vu(o),0),f=f===P?f:Vu(f),a-=u?u.length:0,t&H){var l=e,s=u;e=u=P}var h=c?P:To(n),p=[n,t,r,e,u,l,s,i,o,f];if(h&&function(n,t){var r=n[1],e=t[1],u=r|e,i=u<131,o=e==J&&8==r||e==J&&r==Y&&n[7].length<=t[8]||384==e&&t[7].length<=t[8]&&8==r;if(!i&&!o)return n;1&e&&(n[2]=t[2],u|=1&r?0:4);var f=t[3];if(f){var c=n[3];n[3]=c?fe(c,f,t[4]):f,n[4]=c?T(n[3],K):t[4]}(f=t[5])&&(c=n[5],n[5]=c?ce(c,f,t[6]):f,n[6]=c?T(n[5],K):t[6]),(f=t[7])&&(n[7]=f),e&J&&(n[8]=null==n[8]?t[8]:io(n[8],t[8])),null==n[9]&&(n[9]=t[9]),n[0]=t[0],n[1]=u}(p,h),n=p[0],t=p[1],r=p[2],e=p[3],u=p[4],!(f=p[9]=p[9]===P?c?0:n.length:uo(p[9]-a,0))&&24&t&&(t&=-25),t&&1!=t)_=8==t||t==V?de(n,t,f):t!=G&&33!=t||u.length?me.apply(P,p):Oe(n,t,r,e);else var _=function(n,t,r){var e=1&t,u=ye(n);return function t(){return(this&&this!==tr&&this instanceof t?u:n).apply(e?r:this,arguments)}}(n,t,r);return ou((h?Wo:No)(_,p),n,t)}function Le(n,t,r,e){return n===P||Wu(n,Oi[r])&&!zi.call(e,r)?t:n}function Ce(n,t,r,e,u,i){return Du(n)&&Du(t)&&(i.set(t,n),Or(n,t,P,Ce,i),i.delete(t)),n}function Ue(n){return Nu(n)?P:n}function Be(n,t,r,e,u,i){var o=1&r,f=n.length,c=t.length;if(f!=c&&!(o&&c>f))return!1;var a=i.get(n),l=i.get(t);if(a&&l)return a==t&&l==n;var s=-1,p=!0,_=2&r?new gt:P;for(i.set(n,t),i.set(t,n);++s<f;){var v=n[s],g=t[s];if(e)var y=o?e(g,v,s,t,n,i):e(v,g,s,n,t,i);if(y!==P){if(y)continue;p=!1;break}if(_){if(!h(t,(function(n,t){if(!R(_,t)&&(v===n||u(v,n,r,e,i)))return _.push(t)}))){p=!1;break}}else if(v!==g&&!u(v,g,r,e,i)){p=!1;break}}return i.delete(n),i.delete(t),p}function Te(n){return qo(ru(n,P,vu),n+"")}function $e(n){return qt(n,ni,$o)}function De(n){return qt(n,ti,Do)}function Me(n){for(var t=n.name+"",r=yo[t],e=zi.call(yo,t)?r.length:0;e--;){var u=r[e],i=u.func;if(null==i||i==n)return u.name}return t}function Fe(n){return(zi.call(Yn,"placeholder")?Yn:n).placeholder}function Ne(){var n=Yn.iteratee||ai;return n=n===ai?br:n,arguments.length?n(arguments[0],arguments[1]):n}function Pe(n,t){var r=n.__data__;return function(n){var t=typeof n;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==n:null===n}(t)?r["string"==typeof t?"string":"hash"]:r.map}function qe(n){for(var t=ni(n),r=t.length;r--;){var e=t[r],u=n[e];t[r]=[e,u,nu(u)]}return t}function Ze(n,t){var r=function(n,t){return null==n?P:n[t]}(n,t);return dr(r)?r:P}function Ke(n,t,r){for(var e=-1,u=(t=te(t,n)).length,i=!1;++e<u;){var o=au(t[e]);if(!(i=null!=n&&r(n,o)))break;n=n[o]}return i||++e!=u?i:!!(u=null==n?0:n.length)&&$u(u)&&He(o,u)&&(Sf(n)||Ef(n))}function Ve(n){return"function"!=typeof n.constructor||Xe(n)?{}:Io(Mi(n))}function Ge(n){return Sf(n)||Ef(n)||!!(qi&&n&&n[qi])}function He(n,t){var r=typeof n;return!!(t=null==t?X:t)&&("number"==r||"symbol"!=r&&ot.test(n))&&n>-1&&n%1==0&&n<t}function Je(n,t,r){if(!Du(r))return!1;var e=typeof t;return!!("number"==e?Lu(r)&&He(t,r.length):"string"==e&&t in r)&&Wu(r[t],n)}function Ye(n,t){if(Sf(n))return!1;var r=typeof n;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=n&&!qu(n))||Nn.test(n)||!Fn.test(n)||null!=t&&n in wi(t)}function Qe(n){var t=Me(n),r=Yn[t];if("function"!=typeof r||!(t in ht.prototype))return!1;if(n===r)return!0;var e=To(r);return!!e&&n===e[0]}function Xe(n){var t=n&&n.constructor;return n===("function"==typeof t&&t.prototype||Oi)}function nu(n){return n==n&&!Du(n)}function tu(n,t){return function(r){return null!=r&&r[n]===t&&(t!==P||n in wi(r))}}function ru(t,r,e){return r=uo(r===P?t.length-1:r,0),function(){for(var u=arguments,i=-1,o=uo(u.length-r,0),f=vi(o);++i<o;)f[i]=u[r+i];i=-1;for(var c=vi(r+1);++i<r;)c[i]=u[i];return c[r]=e(f),n(t,this,c)}}function eu(n,t){return t.length<2?n:Pt(n,Dr(t,0,-1))}function uu(n,t){for(var r=n.length,e=io(t.length,r),u=ae(n);e--;){var i=t[e];n[e]=He(i,r)?u[i]:P}return n}function iu(n,t){if(("constructor"!==t||"function"!=typeof n[t])&&"__proto__"!=t)return n[t]}function ou(n,t,r){var e=t+"";return qo(n,function(n,t){var r=t.length;if(!r)return n;var e=r-1;return t[e]=(r>1?"& ":"")+t[e],t=t.join(r>2?", ":" "),n.replace(Gn,"{\n/* [wrapped with "+t+"] */\n")}(e,su(function(n){var t=n.match(Hn);return t?t[1].split(Jn):[]}(e),r)))}function fu(n){var t=0,r=0;return function(){var e=oo(),u=16-(e-r);if(r=e,u>0){if(++t>=800)return arguments[0]}else t=0;return n.apply(P,arguments)}}function cu(n,t){var r=-1,e=n.length,u=e-1;for(t=t===P?e:t;++r<t;){var i=Wr(r,u),o=n[i];n[i]=n[r],n[r]=o}return n.length=t,n}function au(n){if("string"==typeof n||qu(n))return n;var t=n+"";return"0"==t&&1/n==-Q?"-0":t}function lu(n){if(null!=n){try{return Ri.call(n)}catch(n){}try{return n+""}catch(n){}}return""}function su(n,t){return r(rn,(function(r){var e="_."+r[0];t&r[1]&&!o(n,e)&&n.push(e)})),n.sort()}function hu(n){if(n instanceof ht)return n.clone();var t=new st(n.__wrapped__,n.__chain__);return t.__actions__=ae(n.__actions__),t.__index__=n.__index__,t.__values__=n.__values__,t}function pu(n,t,r){var e=null==n?0:n.length;if(!e)return-1;var u=null==r?0:Vu(r);return u<0&&(u=uo(e+u,0)),v(n,Ne(t,3),u)}function _u(n,t,r){var e=null==n?0:n.length;if(!e)return-1;var u=e-1;return r!==P&&(u=Vu(r),u=r<0?uo(e+u,0):io(u,e-1)),v(n,Ne(t,3),u,!0)}function vu(n){return null!=n&&n.length?Tt(n,1):[]}function gu(n){return n&&n.length?n[0]:P}function yu(n){var t=null==n?0:n.length;return t?n[t-1]:P}function du(n,t){return n&&n.length&&t&&t.length?Er(n,t):n}function bu(n){return null==n?n:ao.call(n)}function wu(n){if(!n||!n.length)return[];var t=0;return n=i(n,(function(n){if(Cu(n))return t=uo(n.length,t),!0})),A(t,(function(t){return c(n,w(t))}))}function mu(t,r){if(!t||!t.length)return[];var e=wu(t);return null==r?e:c(e,(function(t){return n(r,P,t)}))}function xu(n){var t=Yn(n);return t.__chain__=!0,t}function ju(n,t){return t(n)}function Au(n,t){return(Sf(n)?r:Ro)(n,Ne(t,3))}function ku(n,t){return(Sf(n)?e:zo)(n,Ne(t,3))}function Ou(n,t){return(Sf(n)?c:jr)(n,Ne(t,3))}function Iu(n,t,r){return t=r?P:t,t=n&&null==t?n.length:t,We(n,J,P,P,P,P,t)}function Ru(n,t){var r;if("function"!=typeof t)throw new ji(q);return n=Vu(n),function(){return--n>0&&(r=t.apply(this,arguments)),n<=1&&(t=P),r}}function zu(n,t,r){function e(t){var r=a,e=l;return a=l=P,v=t,h=n.apply(e,r)}function u(n){return v=n,p=Po(o,t),g?e(n):h}function i(n){var r=n-_;return _===P||r>=t||r<0||y&&n-v>=s}function o(){var n=bf();return i(n)?f(n):(p=Po(o,function(n){var r=t-(n-_);return y?io(r,s-(n-v)):r}(n)),P)}function f(n){return p=P,d&&a?e(n):(a=l=P,h)}function c(){var n=bf(),r=i(n);if(a=arguments,l=this,_=n,r){if(p===P)return u(_);if(y)return Uo(p),p=Po(o,t),e(_)}return p===P&&(p=Po(o,t)),h}var a,l,s,h,p,_,v=0,g=!1,y=!1,d=!0;if("function"!=typeof n)throw new ji(q);return t=Hu(t)||0,Du(r)&&(g=!!r.leading,s=(y="maxWait"in r)?uo(Hu(r.maxWait)||0,t):s,d="trailing"in r?!!r.trailing:d),c.cancel=function(){p!==P&&Uo(p),v=0,a=_=l=p=P},c.flush=function(){return p===P?h:f(bf())},c}function Eu(n,t){if("function"!=typeof n||null!=t&&"function"!=typeof t)throw new ji(q);var r=function(){var e=arguments,u=t?t.apply(this,e):e[0],i=r.cache;if(i.has(u))return i.get(u);var o=n.apply(this,e);return r.cache=i.set(u,o)||i,o};return r.cache=new(Eu.Cache||vt),r}function Su(n){if("function"!=typeof n)throw new ji(q);return function(){var t=arguments;switch(t.length){case 0:return!n.call(this);case 1:return!n.call(this,t[0]);case 2:return!n.call(this,t[0],t[1]);case 3:return!n.call(this,t[0],t[1],t[2])}return!n.apply(this,t)}}function Wu(n,t){return n===t||n!=n&&t!=t}function Lu(n){return null!=n&&$u(n.length)&&!Bu(n)}function Cu(n){return Mu(n)&&Lu(n)}function Uu(n){if(!Mu(n))return!1;var t=Zt(n);return t==cn||"[object DOMException]"==t||"string"==typeof n.message&&"string"==typeof n.name&&!Nu(n)}function Bu(n){if(!Du(n))return!1;var t=Zt(n);return t==an||t==ln||"[object AsyncFunction]"==t||"[object Proxy]"==t}function Tu(n){return"number"==typeof n&&n==Vu(n)}function $u(n){return"number"==typeof n&&n>-1&&n%1==0&&n<=X}function Du(n){var t=typeof n;return null!=n&&("object"==t||"function"==t)}function Mu(n){return null!=n&&"object"==typeof n}function Fu(n){return"number"==typeof n||Mu(n)&&Zt(n)==hn}function Nu(n){if(!Mu(n)||Zt(n)!=pn)return!1;var t=Mi(n);if(null===t)return!0;var r=zi.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&Ri.call(r)==Li}function Pu(n){return"string"==typeof n||!Sf(n)&&Mu(n)&&Zt(n)==yn}function qu(n){return"symbol"==typeof n||Mu(n)&&Zt(n)==dn}function Zu(n){if(!n)return[];if(Lu(n))return Pu(n)?M(n):ae(n);if(Zi&&n[Zi])return function(n){for(var t,r=[];!(t=n.next()).done;)r.push(t.value);return r}(n[Zi]());var t=Mo(n);return(t==sn?U:t==gn?$:ei)(n)}function Ku(n){return n?(n=Hu(n))===Q||n===-Q?17976931348623157e292*(n<0?-1:1):n==n?n:0:0===n?n:0}function Vu(n){var t=Ku(n),r=t%1;return t==t?r?t-r:t:0}function Gu(n){return n?zt(Vu(n),0,tn):0}function Hu(n){if("number"==typeof n)return n;if(qu(n))return nn;if(Du(n)){var t="function"==typeof n.valueOf?n.valueOf():n;n=Du(t)?t+"":t}if("string"!=typeof n)return 0===n?n:+n;n=k(n);var r=et.test(n);return r||it.test(n)?Qt(n.slice(2),r?2:8):rt.test(n)?nn:+n}function Ju(n){return le(n,ti(n))}function Yu(n){return null==n?"":Zr(n)}function Qu(n,t,r){var e=null==n?P:Pt(n,t);return e===P?r:e}function Xu(n,t){return null!=n&&Ke(n,t,nr)}function ni(n){return Lu(n)?dt(n):wr(n)}function ti(n){return Lu(n)?dt(n,!0):mr(n)}function ri(n,t){if(null==n)return{};var r=c(De(n),(function(n){return[n]}));return t=Ne(t),zr(n,r,(function(n,r){return t(n,r[0])}))}function ei(n){return null==n?[]:I(n,ni(n))}function ui(n){return lc(Yu(n).toLowerCase())}function ii(n){return(n=Yu(n))&&n.replace(ft,_r).replace(Ft,"")}function oi(n,t,r){return n=Yu(n),(t=r?P:t)===P?C(n)?N(n):p(n):n.match(t)||[]}function fi(n){return function(){return n}}function ci(n){return n}function ai(n){return br("function"==typeof n?n:Et(n,1))}function li(n,t,e){var u=ni(t),i=Nt(t,u);null!=e||Du(t)&&(i.length||!u.length)||(e=t,t=n,n=this,i=Nt(t,ni(t)));var o=!(Du(e)&&"chain"in e&&!e.chain),f=Bu(n);return r(i,(function(r){var e=t[r];n[r]=e,f&&(n.prototype[r]=function(){var t=this.__chain__;if(o||t){var r=n(this.__wrapped__);return(r.__actions__=ae(this.__actions__)).push({func:e,args:arguments,thisArg:n}),r.__chain__=t,r}return e.apply(n,a([this.value()],arguments))})})),n}function si(){}function hi(n){return Ye(n)?w(au(n)):function(n){return function(t){return Pt(t,n)}}(n)}function pi(){return[]}function _i(){return!1}var vi=(Vn=null==Vn?tr:yr.defaults(tr.Object(),Vn,yr.pick(tr,Kt))).Array,gi=Vn.Date,yi=Vn.Error,di=Vn.Function,bi=Vn.Math,wi=Vn.Object,mi=Vn.RegExp,xi=Vn.String,ji=Vn.TypeError,Ai=vi.prototype,ki=di.prototype,Oi=wi.prototype,Ii=Vn["__core-js_shared__"],Ri=ki.toString,zi=Oi.hasOwnProperty,Ei=0,Si=function(){var n=/[^.]+$/.exec(Ii&&Ii.keys&&Ii.keys.IE_PROTO||"");return n?"Symbol(src)_1."+n:""}(),Wi=Oi.toString,Li=Ri.call(wi),Ci=tr._,Ui=mi("^"+Ri.call(zi).replace(qn,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Bi=ur?Vn.Buffer:P,Ti=Vn.Symbol,$i=Vn.Uint8Array,Di=Bi?Bi.allocUnsafe:P,Mi=B(wi.getPrototypeOf,wi),Fi=wi.create,Ni=Oi.propertyIsEnumerable,Pi=Ai.splice,qi=Ti?Ti.isConcatSpreadable:P,Zi=Ti?Ti.iterator:P,Ki=Ti?Ti.toStringTag:P,Vi=function(){try{var n=Ze(wi,"defineProperty");return n({},"",{}),n}catch(n){}}(),Gi=Vn.clearTimeout!==tr.clearTimeout&&Vn.clearTimeout,Hi=gi&&gi.now!==tr.Date.now&&gi.now,Ji=Vn.setTimeout!==tr.setTimeout&&Vn.setTimeout,Yi=bi.ceil,Qi=bi.floor,Xi=wi.getOwnPropertySymbols,no=Bi?Bi.isBuffer:P,to=Vn.isFinite,ro=Ai.join,eo=B(wi.keys,wi),uo=bi.max,io=bi.min,oo=gi.now,fo=Vn.parseInt,co=bi.random,ao=Ai.reverse,lo=Ze(Vn,"DataView"),so=Ze(Vn,"Map"),ho=Ze(Vn,"Promise"),po=Ze(Vn,"Set"),_o=Ze(Vn,"WeakMap"),vo=Ze(wi,"create"),go=_o&&new _o,yo={},bo=lu(lo),wo=lu(so),mo=lu(ho),xo=lu(po),jo=lu(_o),Ao=Ti?Ti.prototype:P,ko=Ao?Ao.valueOf:P,Oo=Ao?Ao.toString:P,Io=function(){function n(){}return function(t){if(!Du(t))return{};if(Fi)return Fi(t);n.prototype=t;var r=new n;return n.prototype=P,r}}();Yn.templateSettings={escape:$n,evaluate:Dn,interpolate:Mn,variable:"",imports:{_:Yn}},Yn.prototype=lt.prototype,Yn.prototype.constructor=Yn,st.prototype=Io(lt.prototype),st.prototype.constructor=st,ht.prototype=Io(lt.prototype),ht.prototype.constructor=ht,pt.prototype.clear=function(){this.__data__=vo?vo(null):{},this.size=0},pt.prototype.delete=function(n){var t=this.has(n)&&delete this.__data__[n];return this.size-=t?1:0,t},pt.prototype.get=function(n){var t=this.__data__;if(vo){var r=t[n];return r===Z?P:r}return zi.call(t,n)?t[n]:P},pt.prototype.has=function(n){var t=this.__data__;return vo?t[n]!==P:zi.call(t,n)},pt.prototype.set=function(n,t){var r=this.__data__;return this.size+=this.has(n)?0:1,r[n]=vo&&t===P?Z:t,this},_t.prototype.clear=function(){this.__data__=[],this.size=0},_t.prototype.delete=function(n){var t=this.__data__,r=At(t,n);return!(r<0||(r==t.length-1?t.pop():Pi.call(t,r,1),--this.size,0))},_t.prototype.get=function(n){var t=this.__data__,r=At(t,n);return r<0?P:t[r][1]},_t.prototype.has=function(n){return At(this.__data__,n)>-1},_t.prototype.set=function(n,t){var r=this.__data__,e=At(r,n);return e<0?(++this.size,r.push([n,t])):r[e][1]=t,this},vt.prototype.clear=function(){this.size=0,this.__data__={hash:new pt,map:new(so||_t),string:new pt}},vt.prototype.delete=function(n){var t=Pe(this,n).delete(n);return this.size-=t?1:0,t},vt.prototype.get=function(n){return Pe(this,n).get(n)},vt.prototype.has=function(n){return Pe(this,n).has(n)},vt.prototype.set=function(n,t){var r=Pe(this,n),e=r.size;return r.set(n,t),this.size+=r.size==e?0:1,this},gt.prototype.add=gt.prototype.push=function(n){return this.__data__.set(n,Z),this},gt.prototype.has=function(n){return this.__data__.has(n)},yt.prototype.clear=function(){this.__data__=new _t,this.size=0},yt.prototype.delete=function(n){var t=this.__data__,r=t.delete(n);return this.size=t.size,r},yt.prototype.get=function(n){return this.__data__.get(n)},yt.prototype.has=function(n){return this.__data__.has(n)},yt.prototype.set=function(n,t){var r=this.__data__;if(r instanceof _t){var e=r.__data__;if(!so||e.length<199)return e.push([n,t]),this.size=++r.size,this;r=this.__data__=new vt(e)}return r.set(n,t),this.size=r.size,this};var Ro=pe($t),zo=pe(Dt,!0),Eo=_e(),So=_e(!0),Wo=go?function(n,t){return go.set(n,t),n}:ci,Lo=Vi?function(n,t){return Vi(n,"toString",{configurable:!0,enumerable:!1,value:fi(t),writable:!0})}:ci,Co=Cr,Uo=Gi||function(n){return tr.clearTimeout(n)},Bo=po&&1/$(new po([,-0]))[1]==Q?function(n){return new po(n)}:si,To=go?function(n){return go.get(n)}:si,$o=Xi?function(n){return null==n?[]:(n=wi(n),i(Xi(n),(function(t){return Ni.call(n,t)})))}:pi,Do=Xi?function(n){for(var t=[];n;)a(t,$o(n)),n=Mi(n);return t}:pi,Mo=Zt;(lo&&Mo(new lo(new ArrayBuffer(1)))!=mn||so&&Mo(new so)!=sn||ho&&Mo(ho.resolve())!=_n||po&&Mo(new po)!=gn||_o&&Mo(new _o)!=bn)&&(Mo=function(n){var t=Zt(n),r=t==pn?n.constructor:P,e=r?lu(r):"";if(e)switch(e){case bo:return mn;case wo:return sn;case mo:return _n;case xo:return gn;case jo:return bn}return t});var Fo=Ii?Bu:_i,No=fu(Wo),Po=Ji||function(n,t){return tr.setTimeout(n,t)},qo=fu(Lo),Zo=function(n){var t=Eu(n,(function(n){return 500===r.size&&r.clear(),n})),r=t.cache;return t}((function(n){var t=[];return 46===n.charCodeAt(0)&&t.push(""),n.replace(Pn,(function(n,r,e,u){t.push(e?u.replace(Xn,"$1"):r||n)})),t})),Ko=Cr((function(n,t){return Cu(n)?Lt(n,Tt(t,1,Cu,!0)):[]})),Vo=Cr((function(n,t){var r=yu(t);return Cu(r)&&(r=P),Cu(n)?Lt(n,Tt(t,1,Cu,!0),Ne(r,2)):[]})),Go=Cr((function(n,t){var r=yu(t);return Cu(r)&&(r=P),Cu(n)?Lt(n,Tt(t,1,Cu,!0),P,r):[]})),Ho=Cr((function(n){var t=c(n,Xr);return t.length&&t[0]===n[0]?rr(t):[]})),Jo=Cr((function(n){var t=yu(n),r=c(n,Xr);return t===yu(r)?t=P:r.pop(),r.length&&r[0]===n[0]?rr(r,Ne(t,2)):[]})),Yo=Cr((function(n){var t=yu(n),r=c(n,Xr);return(t="function"==typeof t?t:P)&&r.pop(),r.length&&r[0]===n[0]?rr(r,P,t):[]})),Qo=Cr(du),Xo=Te((function(n,t){var r=null==n?0:n.length,e=Rt(n,t);return Sr(n,c(t,(function(n){return He(n,r)?+n:n})).sort(oe)),e})),nf=Cr((function(n){return Kr(Tt(n,1,Cu,!0))})),tf=Cr((function(n){var t=yu(n);return Cu(t)&&(t=P),Kr(Tt(n,1,Cu,!0),Ne(t,2))})),rf=Cr((function(n){var t=yu(n);return t="function"==typeof t?t:P,Kr(Tt(n,1,Cu,!0),P,t)})),ef=Cr((function(n,t){return Cu(n)?Lt(n,t):[]})),uf=Cr((function(n){return Yr(i(n,Cu))})),of=Cr((function(n){var t=yu(n);return Cu(t)&&(t=P),Yr(i(n,Cu),Ne(t,2))})),ff=Cr((function(n){var t=yu(n);return t="function"==typeof t?t:P,Yr(i(n,Cu),P,t)})),cf=Cr(wu),af=Cr((function(n){var t=n.length,r=t>1?n[t-1]:P;return r="function"==typeof r?(n.pop(),r):P,mu(n,r)})),lf=Te((function(n){var t=n.length,r=t?n[0]:0,e=this.__wrapped__,u=function(t){return Rt(t,n)};return!(t>1||this.__actions__.length)&&e instanceof ht&&He(r)?((e=e.slice(r,+r+(t?1:0))).__actions__.push({func:ju,args:[u],thisArg:P}),new st(e,this.__chain__).thru((function(n){return t&&!n.length&&n.push(P),n}))):this.thru(u)})),sf=se((function(n,t,r){zi.call(n,r)?++n[r]:It(n,r,1)})),hf=be(pu),pf=be(_u),_f=se((function(n,t,r){zi.call(n,r)?n[r].push(t):It(n,r,[t])})),vf=Cr((function(t,r,e){var u=-1,i="function"==typeof r,o=Lu(t)?vi(t.length):[];return Ro(t,(function(t){o[++u]=i?n(r,t,e):er(t,r,e)})),o})),gf=se((function(n,t,r){It(n,r,t)})),yf=se((function(n,t,r){n[r?0:1].push(t)}),(function(){return[[],[]]})),df=Cr((function(n,t){if(null==n)return[];var r=t.length;return r>1&&Je(n,t[0],t[1])?t=[]:r>2&&Je(t[0],t[1],t[2])&&(t=[t[0]]),Rr(n,Tt(t,1),[])})),bf=Hi||function(){return tr.Date.now()},wf=Cr((function(n,t,r){var e=1;if(r.length){var u=T(r,Fe(wf));e|=G}return We(n,e,t,r,u)})),mf=Cr((function(n,t,r){var e=3;if(r.length){var u=T(r,Fe(mf));e|=G}return We(t,e,n,r,u)})),xf=Cr((function(n,t){return Wt(n,1,t)})),jf=Cr((function(n,t,r){return Wt(n,Hu(t)||0,r)}));Eu.Cache=vt;var Af=Co((function(t,r){var e=(r=1==r.length&&Sf(r[0])?c(r[0],O(Ne())):c(Tt(r,1),O(Ne()))).length;return Cr((function(u){for(var i=-1,o=io(u.length,e);++i<o;)u[i]=r[i].call(this,u[i]);return n(t,this,u)}))})),kf=Cr((function(n,t){return We(n,G,P,t,T(t,Fe(kf)))})),Of=Cr((function(n,t){return We(n,H,P,t,T(t,Fe(Of)))})),If=Te((function(n,t){return We(n,Y,P,P,P,t)})),Rf=Re(Jt),zf=Re((function(n,t){return n>=t})),Ef=ir(function(){return arguments}())?ir:function(n){return Mu(n)&&zi.call(n,"callee")&&!Ni.call(n,"callee")},Sf=vi.isArray,Wf=fr?O(fr):function(n){return Mu(n)&&Zt(n)==wn},Lf=no||_i,Cf=cr?O(cr):function(n){return Mu(n)&&Zt(n)==fn},Uf=ar?O(ar):function(n){return Mu(n)&&Mo(n)==sn},Bf=lr?O(lr):function(n){return Mu(n)&&Zt(n)==vn},Tf=sr?O(sr):function(n){return Mu(n)&&Mo(n)==gn},$f=hr?O(hr):function(n){return Mu(n)&&$u(n.length)&&!!Gt[Zt(n)]},Df=Re(xr),Mf=Re((function(n,t){return n<=t})),Ff=he((function(n,t){if(Xe(t)||Lu(t))return le(t,ni(t),n),P;for(var r in t)zi.call(t,r)&&jt(n,r,t[r])})),Nf=he((function(n,t){le(t,ti(t),n)})),Pf=he((function(n,t,r,e){le(t,ti(t),n,e)})),qf=he((function(n,t,r,e){le(t,ni(t),n,e)})),Zf=Te(Rt),Kf=Cr((function(n,t){n=wi(n);var r=-1,e=t.length,u=e>2?t[2]:P;for(u&&Je(t[0],t[1],u)&&(e=1);++r<e;)for(var i=t[r],o=ti(i),f=-1,c=o.length;++f<c;){var a=o[f],l=n[a];(l===P||Wu(l,Oi[a])&&!zi.call(n,a))&&(n[a]=i[a])}return n})),Vf=Cr((function(t){return t.push(P,Ce),n(Qf,P,t)})),Gf=xe((function(n,t,r){null!=t&&"function"!=typeof t.toString&&(t=Wi.call(t)),n[t]=r}),fi(ci)),Hf=xe((function(n,t,r){null!=t&&"function"!=typeof t.toString&&(t=Wi.call(t)),zi.call(n,t)?n[t].push(r):n[t]=[r]}),Ne),Jf=Cr(er),Yf=he((function(n,t,r){Or(n,t,r)})),Qf=he((function(n,t,r,e){Or(n,t,r,e)})),Xf=Te((function(n,t){var r={};if(null==n)return r;var e=!1;t=c(t,(function(t){return t=te(t,n),e||(e=t.length>1),t})),le(n,De(n),r),e&&(r=Et(r,7,Ue));for(var u=t.length;u--;)Vr(r,t[u]);return r})),nc=Te((function(n,t){return null==n?{}:function(n,t){return zr(n,t,(function(t,r){return Xu(n,r)}))}(n,t)})),tc=Se(ni),rc=Se(ti),ec=ge((function(n,t,r){return t=t.toLowerCase(),n+(r?ui(t):t)})),uc=ge((function(n,t,r){return n+(r?"-":"")+t.toLowerCase()})),ic=ge((function(n,t,r){return n+(r?" ":"")+t.toLowerCase()})),oc=ve("toLowerCase"),fc=ge((function(n,t,r){return n+(r?"_":"")+t.toLowerCase()})),cc=ge((function(n,t,r){return n+(r?" ":"")+lc(t)})),ac=ge((function(n,t,r){return n+(r?" ":"")+t.toUpperCase()})),lc=ve("toUpperCase"),sc=Cr((function(t,r){try{return n(t,P,r)}catch(n){return Uu(n)?n:new yi(n)}})),hc=Te((function(n,t){return r(t,(function(t){t=au(t),It(n,t,wf(n[t],n))})),n})),pc=we(),_c=we(!0),vc=Cr((function(n,t){return function(r){return er(r,n,t)}})),gc=Cr((function(n,t){return function(r){return er(n,r,t)}})),yc=Ae(c),dc=Ae(u),bc=Ae(h),wc=Ie(),mc=Ie(!0),xc=je((function(n,t){return n+t}),0),jc=Ee("ceil"),Ac=je((function(n,t){return n/t}),1),kc=Ee("floor"),Oc=je((function(n,t){return n*t}),1),Ic=Ee("round"),Rc=je((function(n,t){return n-t}),0);return Yn.after=function(n,t){if("function"!=typeof t)throw new ji(q);return n=Vu(n),function(){if(--n<1)return t.apply(this,arguments)}},Yn.ary=Iu,Yn.assign=Ff,Yn.assignIn=Nf,Yn.assignInWith=Pf,Yn.assignWith=qf,Yn.at=Zf,Yn.before=Ru,Yn.bind=wf,Yn.bindAll=hc,Yn.bindKey=mf,Yn.castArray=function(){if(!arguments.length)return[];var n=arguments[0];return Sf(n)?n:[n]},Yn.chain=xu,Yn.chunk=function(n,t,r){t=(r?Je(n,t,r):t===P)?1:uo(Vu(t),0);var e=null==n?0:n.length;if(!e||t<1)return[];for(var u=0,i=0,o=vi(Yi(e/t));u<e;)o[i++]=Dr(n,u,u+=t);return o},Yn.compact=function(n){for(var t=-1,r=null==n?0:n.length,e=0,u=[];++t<r;){var i=n[t];i&&(u[e++]=i)}return u},Yn.concat=function(){var n=arguments.length;if(!n)return[];for(var t=vi(n-1),r=arguments[0],e=n;e--;)t[e-1]=arguments[e];return a(Sf(r)?ae(r):[r],Tt(t,1))},Yn.cond=function(t){var r=null==t?0:t.length,e=Ne();return t=r?c(t,(function(n){if("function"!=typeof n[1])throw new ji(q);return[e(n[0]),n[1]]})):[],Cr((function(e){for(var u=-1;++u<r;){var i=t[u];if(n(i[0],this,e))return n(i[1],this,e)}}))},Yn.conforms=function(n){return function(n){var t=ni(n);return function(r){return St(r,n,t)}}(Et(n,1))},Yn.constant=fi,Yn.countBy=sf,Yn.create=function(n,t){var r=Io(n);return null==t?r:Ot(r,t)},Yn.curry=function n(t,r,e){var u=We(t,8,P,P,P,P,P,r=e?P:r);return u.placeholder=n.placeholder,u},Yn.curryRight=function n(t,r,e){var u=We(t,V,P,P,P,P,P,r=e?P:r);return u.placeholder=n.placeholder,u},Yn.debounce=zu,Yn.defaults=Kf,Yn.defaultsDeep=Vf,Yn.defer=xf,Yn.delay=jf,Yn.difference=Ko,Yn.differenceBy=Vo,Yn.differenceWith=Go,Yn.drop=function(n,t,r){var e=null==n?0:n.length;return e?Dr(n,(t=r||t===P?1:Vu(t))<0?0:t,e):[]},Yn.dropRight=function(n,t,r){var e=null==n?0:n.length;return e?Dr(n,0,(t=e-(t=r||t===P?1:Vu(t)))<0?0:t):[]},Yn.dropRightWhile=function(n,t){return n&&n.length?Hr(n,Ne(t,3),!0,!0):[]},Yn.dropWhile=function(n,t){return n&&n.length?Hr(n,Ne(t,3),!0):[]},Yn.fill=function(n,t,r,e){var u=null==n?0:n.length;return u?(r&&"number"!=typeof r&&Je(n,t,r)&&(r=0,e=u),function(n,t,r,e){var u=n.length;for((r=Vu(r))<0&&(r=-r>u?0:u+r),(e=e===P||e>u?u:Vu(e))<0&&(e+=u),e=r>e?0:Gu(e);r<e;)n[r++]=t;return n}(n,t,r,e)):[]},Yn.filter=function(n,t){return(Sf(n)?i:Bt)(n,Ne(t,3))},Yn.flatMap=function(n,t){return Tt(Ou(n,t),1)},Yn.flatMapDeep=function(n,t){return Tt(Ou(n,t),Q)},Yn.flatMapDepth=function(n,t,r){return r=r===P?1:Vu(r),Tt(Ou(n,t),r)},Yn.flatten=vu,Yn.flattenDeep=function(n){return null!=n&&n.length?Tt(n,Q):[]},Yn.flattenDepth=function(n,t){return null!=n&&n.length?Tt(n,t=t===P?1:Vu(t)):[]},Yn.flip=function(n){return We(n,512)},Yn.flow=pc,Yn.flowRight=_c,Yn.fromPairs=function(n){for(var t=-1,r=null==n?0:n.length,e={};++t<r;){var u=n[t];e[u[0]]=u[1]}return e},Yn.functions=function(n){return null==n?[]:Nt(n,ni(n))},Yn.functionsIn=function(n){return null==n?[]:Nt(n,ti(n))},Yn.groupBy=_f,Yn.initial=function(n){return null!=n&&n.length?Dr(n,0,-1):[]},Yn.intersection=Ho,Yn.intersectionBy=Jo,Yn.intersectionWith=Yo,Yn.invert=Gf,Yn.invertBy=Hf,Yn.invokeMap=vf,Yn.iteratee=ai,Yn.keyBy=gf,Yn.keys=ni,Yn.keysIn=ti,Yn.map=Ou,Yn.mapKeys=function(n,t){var r={};return t=Ne(t,3),$t(n,(function(n,e,u){It(r,t(n,e,u),n)})),r},Yn.mapValues=function(n,t){var r={};return t=Ne(t,3),$t(n,(function(n,e,u){It(r,e,t(n,e,u))})),r},Yn.matches=function(n){return Ar(Et(n,1))},Yn.matchesProperty=function(n,t){return kr(n,Et(t,1))},Yn.memoize=Eu,Yn.merge=Yf,Yn.mergeWith=Qf,Yn.method=vc,Yn.methodOf=gc,Yn.mixin=li,Yn.negate=Su,Yn.nthArg=function(n){return n=Vu(n),Cr((function(t){return Ir(t,n)}))},Yn.omit=Xf,Yn.omitBy=function(n,t){return ri(n,Su(Ne(t)))},Yn.once=function(n){return Ru(2,n)},Yn.orderBy=function(n,t,r,e){return null==n?[]:(Sf(t)||(t=null==t?[]:[t]),Sf(r=e?P:r)||(r=null==r?[]:[r]),Rr(n,t,r))},Yn.over=yc,Yn.overArgs=Af,Yn.overEvery=dc,Yn.overSome=bc,Yn.partial=kf,Yn.partialRight=Of,Yn.partition=yf,Yn.pick=nc,Yn.pickBy=ri,Yn.property=hi,Yn.propertyOf=function(n){return function(t){return null==n?P:Pt(n,t)}},Yn.pull=Qo,Yn.pullAll=du,Yn.pullAllBy=function(n,t,r){return n&&n.length&&t&&t.length?Er(n,t,Ne(r,2)):n},Yn.pullAllWith=function(n,t,r){return n&&n.length&&t&&t.length?Er(n,t,P,r):n},Yn.pullAt=Xo,Yn.range=wc,Yn.rangeRight=mc,Yn.rearg=If,Yn.reject=function(n,t){return(Sf(n)?i:Bt)(n,Su(Ne(t,3)))},Yn.remove=function(n,t){var r=[];if(!n||!n.length)return r;var e=-1,u=[],i=n.length;for(t=Ne(t,3);++e<i;){var o=n[e];t(o,e,n)&&(r.push(o),u.push(e))}return Sr(n,u),r},Yn.rest=function(n,t){if("function"!=typeof n)throw new ji(q);return Cr(n,t=t===P?t:Vu(t))},Yn.reverse=bu,Yn.sampleSize=function(n,t,r){return t=(r?Je(n,t,r):t===P)?1:Vu(t),(Sf(n)?wt:Br)(n,t)},Yn.set=function(n,t,r){return null==n?n:Tr(n,t,r)},Yn.setWith=function(n,t,r,e){return e="function"==typeof e?e:P,null==n?n:Tr(n,t,r,e)},Yn.shuffle=function(n){return(Sf(n)?mt:$r)(n)},Yn.slice=function(n,t,r){var e=null==n?0:n.length;return e?(r&&"number"!=typeof r&&Je(n,t,r)?(t=0,r=e):(t=null==t?0:Vu(t),r=r===P?e:Vu(r)),Dr(n,t,r)):[]},Yn.sortBy=df,Yn.sortedUniq=function(n){return n&&n.length?Pr(n):[]},Yn.sortedUniqBy=function(n,t){return n&&n.length?Pr(n,Ne(t,2)):[]},Yn.split=function(n,t,r){return r&&"number"!=typeof r&&Je(n,t,r)&&(t=r=P),(r=r===P?tn:r>>>0)?(n=Yu(n))&&("string"==typeof t||null!=t&&!Bf(t))&&(!(t=Zr(t))&&L(n))?re(M(n),0,r):n.split(t,r):[]},Yn.spread=function(t,r){if("function"!=typeof t)throw new ji(q);return r=null==r?0:uo(Vu(r),0),Cr((function(e){var u=e[r],i=re(e,0,r);return u&&a(i,u),n(t,this,i)}))},Yn.tail=function(n){var t=null==n?0:n.length;return t?Dr(n,1,t):[]},Yn.take=function(n,t,r){return n&&n.length?Dr(n,0,(t=r||t===P?1:Vu(t))<0?0:t):[]},Yn.takeRight=function(n,t,r){var e=null==n?0:n.length;return e?Dr(n,(t=e-(t=r||t===P?1:Vu(t)))<0?0:t,e):[]},Yn.takeRightWhile=function(n,t){return n&&n.length?Hr(n,Ne(t,3),!1,!0):[]},Yn.takeWhile=function(n,t){return n&&n.length?Hr(n,Ne(t,3)):[]},Yn.tap=function(n,t){return t(n),n},Yn.throttle=function(n,t,r){var e=!0,u=!0;if("function"!=typeof n)throw new ji(q);return Du(r)&&(e="leading"in r?!!r.leading:e,u="trailing"in r?!!r.trailing:u),zu(n,t,{leading:e,maxWait:t,trailing:u})},Yn.thru=ju,Yn.toArray=Zu,Yn.toPairs=tc,Yn.toPairsIn=rc,Yn.toPath=function(n){return Sf(n)?c(n,au):qu(n)?[n]:ae(Zo(Yu(n)))},Yn.toPlainObject=Ju,Yn.transform=function(n,t,e){var u=Sf(n),i=u||Lf(n)||$f(n);if(t=Ne(t,4),null==e){var o=n&&n.constructor;e=i?u?new o:[]:Du(n)&&Bu(o)?Io(Mi(n)):{}}return(i?r:$t)(n,(function(n,r,u){return t(e,n,r,u)})),e},Yn.unary=function(n){return Iu(n,1)},Yn.union=nf,Yn.unionBy=tf,Yn.unionWith=rf,Yn.uniq=function(n){return n&&n.length?Kr(n):[]},Yn.uniqBy=function(n,t){return n&&n.length?Kr(n,Ne(t,2)):[]},Yn.uniqWith=function(n,t){return t="function"==typeof t?t:P,n&&n.length?Kr(n,P,t):[]},Yn.unset=function(n,t){return null==n||Vr(n,t)},Yn.unzip=wu,Yn.unzipWith=mu,Yn.update=function(n,t,r){return null==n?n:Gr(n,t,ne(r))},Yn.updateWith=function(n,t,r,e){return e="function"==typeof e?e:P,null==n?n:Gr(n,t,ne(r),e)},Yn.values=ei,Yn.valuesIn=function(n){return null==n?[]:I(n,ti(n))},Yn.without=ef,Yn.words=oi,Yn.wrap=function(n,t){return kf(ne(t),n)},Yn.xor=uf,Yn.xorBy=of,Yn.xorWith=ff,Yn.zip=cf,Yn.zipObject=function(n,t){return Qr(n||[],t||[],jt)},Yn.zipObjectDeep=function(n,t){return Qr(n||[],t||[],Tr)},Yn.zipWith=af,Yn.entries=tc,Yn.entriesIn=rc,Yn.extend=Nf,Yn.extendWith=Pf,li(Yn,Yn),Yn.add=xc,Yn.attempt=sc,Yn.camelCase=ec,Yn.capitalize=ui,Yn.ceil=jc,Yn.clamp=function(n,t,r){return r===P&&(r=t,t=P),r!==P&&(r=(r=Hu(r))==r?r:0),t!==P&&(t=(t=Hu(t))==t?t:0),zt(Hu(n),t,r)},Yn.clone=function(n){return Et(n,4)},Yn.cloneDeep=function(n){return Et(n,5)},Yn.cloneDeepWith=function(n,t){return Et(n,5,t="function"==typeof t?t:P)},Yn.cloneWith=function(n,t){return Et(n,4,t="function"==typeof t?t:P)},Yn.conformsTo=function(n,t){return null==t||St(n,t,ni(t))},Yn.deburr=ii,Yn.defaultTo=function(n,t){return null==n||n!=n?t:n},Yn.divide=Ac,Yn.endsWith=function(n,t,r){n=Yu(n),t=Zr(t);var e=n.length,u=r=r===P?e:zt(Vu(r),0,e);return(r-=t.length)>=0&&n.slice(r,u)==t},Yn.eq=Wu,Yn.escape=function(n){return(n=Yu(n))&&Tn.test(n)?n.replace(Un,vr):n},Yn.escapeRegExp=function(n){return(n=Yu(n))&&Zn.test(n)?n.replace(qn,"\\$&"):n},Yn.every=function(n,t,r){var e=Sf(n)?u:Ct;return r&&Je(n,t,r)&&(t=P),e(n,Ne(t,3))},Yn.find=hf,Yn.findIndex=pu,Yn.findKey=function(n,t){return _(n,Ne(t,3),$t)},Yn.findLast=pf,Yn.findLastIndex=_u,Yn.findLastKey=function(n,t){return _(n,Ne(t,3),Dt)},Yn.floor=kc,Yn.forEach=Au,Yn.forEachRight=ku,Yn.forIn=function(n,t){return null==n?n:Eo(n,Ne(t,3),ti)},Yn.forInRight=function(n,t){return null==n?n:So(n,Ne(t,3),ti)},Yn.forOwn=function(n,t){return n&&$t(n,Ne(t,3))},Yn.forOwnRight=function(n,t){return n&&Dt(n,Ne(t,3))},Yn.get=Qu,Yn.gt=Rf,Yn.gte=zf,Yn.has=function(n,t){return null!=n&&Ke(n,t,Xt)},Yn.hasIn=Xu,Yn.head=gu,Yn.identity=ci,Yn.includes=function(n,t,r,e){n=Lu(n)?n:ei(n),r=r&&!e?Vu(r):0;var u=n.length;return r<0&&(r=uo(u+r,0)),Pu(n)?r<=u&&n.indexOf(t,r)>-1:!!u&&g(n,t,r)>-1},Yn.indexOf=function(n,t,r){var e=null==n?0:n.length;if(!e)return-1;var u=null==r?0:Vu(r);return u<0&&(u=uo(e+u,0)),g(n,t,u)},Yn.inRange=function(n,t,r){return t=Ku(t),r===P?(r=t,t=0):r=Ku(r),function(n,t,r){return n>=io(t,r)&&n<uo(t,r)}(n=Hu(n),t,r)},Yn.invoke=Jf,Yn.isArguments=Ef,Yn.isArray=Sf,Yn.isArrayBuffer=Wf,Yn.isArrayLike=Lu,Yn.isArrayLikeObject=Cu,Yn.isBoolean=function(n){return!0===n||!1===n||Mu(n)&&Zt(n)==on},Yn.isBuffer=Lf,Yn.isDate=Cf,Yn.isElement=function(n){return Mu(n)&&1===n.nodeType&&!Nu(n)},Yn.isEmpty=function(n){if(null==n)return!0;if(Lu(n)&&(Sf(n)||"string"==typeof n||"function"==typeof n.splice||Lf(n)||$f(n)||Ef(n)))return!n.length;var t=Mo(n);if(t==sn||t==gn)return!n.size;if(Xe(n))return!wr(n).length;for(var r in n)if(zi.call(n,r))return!1;return!0},Yn.isEqual=function(n,t){return or(n,t)},Yn.isEqualWith=function(n,t,r){var e=(r="function"==typeof r?r:P)?r(n,t):P;return e===P?or(n,t,P,r):!!e},Yn.isError=Uu,Yn.isFinite=function(n){return"number"==typeof n&&to(n)},Yn.isFunction=Bu,Yn.isInteger=Tu,Yn.isLength=$u,Yn.isMap=Uf,Yn.isMatch=function(n,t){return n===t||pr(n,t,qe(t))},Yn.isMatchWith=function(n,t,r){return r="function"==typeof r?r:P,pr(n,t,qe(t),r)},Yn.isNaN=function(n){return Fu(n)&&n!=+n},Yn.isNative=function(n){if(Fo(n))throw new yi("Unsupported core-js use. Try https://npms.io/search?q=ponyfill.");return dr(n)},Yn.isNil=function(n){return null==n},Yn.isNull=function(n){return null===n},Yn.isNumber=Fu,Yn.isObject=Du,Yn.isObjectLike=Mu,Yn.isPlainObject=Nu,Yn.isRegExp=Bf,Yn.isSafeInteger=function(n){return Tu(n)&&n>=-X&&n<=X},Yn.isSet=Tf,Yn.isString=Pu,Yn.isSymbol=qu,Yn.isTypedArray=$f,Yn.isUndefined=function(n){return n===P},Yn.isWeakMap=function(n){return Mu(n)&&Mo(n)==bn},Yn.isWeakSet=function(n){return Mu(n)&&"[object WeakSet]"==Zt(n)},Yn.join=function(n,t){return null==n?"":ro.call(n,t)},Yn.kebabCase=uc,Yn.last=yu,Yn.lastIndexOf=function(n,t,r){var e=null==n?0:n.length;if(!e)return-1;var u=e;return r!==P&&(u=(u=Vu(r))<0?uo(e+u,0):io(u,e-1)),t==t?function(n,t,r){for(var e=r+1;e--;)if(n[e]===t)return e;return e}(n,t,u):v(n,d,u,!0)},Yn.lowerCase=ic,Yn.lowerFirst=oc,Yn.lt=Df,Yn.lte=Mf,Yn.max=function(n){return n&&n.length?Ut(n,ci,Jt):P},Yn.maxBy=function(n,t){return n&&n.length?Ut(n,Ne(t,2),Jt):P},Yn.mean=function(n){return b(n,ci)},Yn.meanBy=function(n,t){return b(n,Ne(t,2))},Yn.min=function(n){return n&&n.length?Ut(n,ci,xr):P},Yn.minBy=function(n,t){return n&&n.length?Ut(n,Ne(t,2),xr):P},Yn.stubArray=pi,Yn.stubFalse=_i,Yn.stubObject=function(){return{}},Yn.stubString=function(){return""},Yn.stubTrue=function(){return!0},Yn.multiply=Oc,Yn.nth=function(n,t){return n&&n.length?Ir(n,Vu(t)):P},Yn.noConflict=function(){return tr._===this&&(tr._=Ci),this},Yn.noop=si,Yn.now=bf,Yn.pad=function(n,t,r){n=Yu(n);var e=(t=Vu(t))?D(n):0;if(!t||e>=t)return n;var u=(t-e)/2;return ke(Qi(u),r)+n+ke(Yi(u),r)},Yn.padEnd=function(n,t,r){n=Yu(n);var e=(t=Vu(t))?D(n):0;return t&&e<t?n+ke(t-e,r):n},Yn.padStart=function(n,t,r){n=Yu(n);var e=(t=Vu(t))?D(n):0;return t&&e<t?ke(t-e,r)+n:n},Yn.parseInt=function(n,t,r){return r||null==t?t=0:t&&(t=+t),fo(Yu(n).replace(Kn,""),t||0)},Yn.random=function(n,t,r){if(r&&"boolean"!=typeof r&&Je(n,t,r)&&(t=r=P),r===P&&("boolean"==typeof t?(r=t,t=P):"boolean"==typeof n&&(r=n,n=P)),n===P&&t===P?(n=0,t=1):(n=Ku(n),t===P?(t=n,n=0):t=Ku(t)),n>t){var e=n;n=t,t=e}if(r||n%1||t%1){var u=co();return io(n+u*(t-n+Yt("1e-"+((u+"").length-1))),t)}return Wr(n,t)},Yn.reduce=function(n,t,r){var e=Sf(n)?l:x,u=arguments.length<3;return e(n,Ne(t,4),r,u,Ro)},Yn.reduceRight=function(n,t,r){var e=Sf(n)?s:x,u=arguments.length<3;return e(n,Ne(t,4),r,u,zo)},Yn.repeat=function(n,t,r){return t=(r?Je(n,t,r):t===P)?1:Vu(t),Lr(Yu(n),t)},Yn.replace=function(){var n=arguments,t=Yu(n[0]);return n.length<3?t:t.replace(n[1],n[2])},Yn.result=function(n,t,r){var e=-1,u=(t=te(t,n)).length;for(u||(u=1,n=P);++e<u;){var i=null==n?P:n[au(t[e])];i===P&&(e=u,i=r),n=Bu(i)?i.call(n):i}return n},Yn.round=Ic,Yn.runInContext=m,Yn.sample=function(n){return(Sf(n)?bt:Ur)(n)},Yn.size=function(n){if(null==n)return 0;if(Lu(n))return Pu(n)?D(n):n.length;var t=Mo(n);return t==sn||t==gn?n.size:wr(n).length},Yn.snakeCase=fc,Yn.some=function(n,t,r){var e=Sf(n)?h:Mr;return r&&Je(n,t,r)&&(t=P),e(n,Ne(t,3))},Yn.sortedIndex=function(n,t){return Fr(n,t)},Yn.sortedIndexBy=function(n,t,r){return Nr(n,t,Ne(r,2))},Yn.sortedIndexOf=function(n,t){var r=null==n?0:n.length;if(r){var e=Fr(n,t);if(e<r&&Wu(n[e],t))return e}return-1},Yn.sortedLastIndex=function(n,t){return Fr(n,t,!0)},Yn.sortedLastIndexBy=function(n,t,r){return Nr(n,t,Ne(r,2),!0)},Yn.sortedLastIndexOf=function(n,t){if(null!=n&&n.length){var r=Fr(n,t,!0)-1;if(Wu(n[r],t))return r}return-1},Yn.startCase=cc,Yn.startsWith=function(n,t,r){return n=Yu(n),r=null==r?0:zt(Vu(r),0,n.length),t=Zr(t),n.slice(r,r+t.length)==t},Yn.subtract=Rc,Yn.sum=function(n){return n&&n.length?j(n,ci):0},Yn.sumBy=function(n,t){return n&&n.length?j(n,Ne(t,2)):0},Yn.template=function(n,t,r){var e=Yn.templateSettings;r&&Je(n,t,r)&&(t=P),n=Yu(n),t=Pf({},t,e,Le);var u,i,o=Pf({},t.imports,e.imports,Le),f=ni(o),c=I(o,f),a=0,l=t.interpolate||ct,s="__p += '",h=mi((t.escape||ct).source+"|"+l.source+"|"+(l===Mn?nt:ct).source+"|"+(t.evaluate||ct).source+"|$","g"),p="//# sourceURL="+(zi.call(t,"sourceURL")?(t.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++Vt+"]")+"\n";n.replace(h,(function(t,r,e,o,f,c){return e||(e=o),s+=n.slice(a,c).replace(at,W),r&&(u=!0,s+="' +\n__e("+r+") +\n'"),f&&(i=!0,s+="';\n"+f+";\n__p += '"),e&&(s+="' +\n((__t = ("+e+")) == null ? '' : __t) +\n'"),a=c+t.length,t})),s+="';\n";var _=zi.call(t,"variable")&&t.variable;if(_){if(Qn.test(_))throw new yi("Invalid `variable` option passed into `_.template`")}else s="with (obj) {\n"+s+"\n}\n";s=(i?s.replace(Sn,""):s).replace(Wn,"$1").replace(Ln,"$1;"),s="function("+(_||"obj")+") {\n"+(_?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(u?", __e = _.escape":"")+(i?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+s+"return __p\n}";var v=sc((function(){return di(f,p+"return "+s).apply(P,c)}));if(v.source=s,Uu(v))throw v;return v},Yn.times=function(n,t){if((n=Vu(n))<1||n>X)return[];var r=tn,e=io(n,tn);t=Ne(t),n-=tn;for(var u=A(e,t);++r<n;)t(r);return u},Yn.toFinite=Ku,Yn.toInteger=Vu,Yn.toLength=Gu,Yn.toLower=function(n){return Yu(n).toLowerCase()},Yn.toNumber=Hu,Yn.toSafeInteger=function(n){return n?zt(Vu(n),-X,X):0===n?n:0},Yn.toString=Yu,Yn.toUpper=function(n){return Yu(n).toUpperCase()},Yn.trim=function(n,t,r){if((n=Yu(n))&&(r||t===P))return k(n);if(!n||!(t=Zr(t)))return n;var e=M(n),u=M(t);return re(e,z(e,u),E(e,u)+1).join("")},Yn.trimEnd=function(n,t,r){if((n=Yu(n))&&(r||t===P))return n.slice(0,F(n)+1);if(!n||!(t=Zr(t)))return n;var e=M(n);return re(e,0,E(e,M(t))+1).join("")},Yn.trimStart=function(n,t,r){if((n=Yu(n))&&(r||t===P))return n.replace(Kn,"");if(!n||!(t=Zr(t)))return n;var e=M(n);return re(e,z(e,M(t))).join("")},Yn.truncate=function(n,t){var r=30,e="...";if(Du(t)){var u="separator"in t?t.separator:u;r="length"in t?Vu(t.length):r,e="omission"in t?Zr(t.omission):e}var i=(n=Yu(n)).length;if(L(n)){var o=M(n);i=o.length}if(r>=i)return n;var f=r-D(e);if(f<1)return e;var c=o?re(o,0,f).join(""):n.slice(0,f);if(u===P)return c+e;if(o&&(f+=c.length-f),Bf(u)){if(n.slice(f).search(u)){var a,l=c;for(u.global||(u=mi(u.source,Yu(tt.exec(u))+"g")),u.lastIndex=0;a=u.exec(l);)var s=a.index;c=c.slice(0,s===P?f:s)}}else if(n.indexOf(Zr(u),f)!=f){var h=c.lastIndexOf(u);h>-1&&(c=c.slice(0,h))}return c+e},Yn.unescape=function(n){return(n=Yu(n))&&Bn.test(n)?n.replace(Cn,gr):n},Yn.uniqueId=function(n){var t=++Ei;return Yu(n)+t},Yn.upperCase=ac,Yn.upperFirst=lc,Yn.each=Au,Yn.eachRight=ku,Yn.first=gu,li(Yn,function(){var n={};return $t(Yn,(function(t,r){zi.call(Yn.prototype,r)||(n[r]=t)})),n}(),{chain:!1}),Yn.VERSION="4.17.21",r(["bind","bindKey","curry","curryRight","partial","partialRight"],(function(n){Yn[n].placeholder=Yn})),r(["drop","take"],(function(n,t){ht.prototype[n]=function(r){r=r===P?1:uo(Vu(r),0);var e=this.__filtered__&&!t?new ht(this):this.clone();return e.__filtered__?e.__takeCount__=io(r,e.__takeCount__):e.__views__.push({size:io(r,tn),type:n+(e.__dir__<0?"Right":"")}),e},ht.prototype[n+"Right"]=function(t){return this.reverse()[n](t).reverse()}})),r(["filter","map","takeWhile"],(function(n,t){var r=t+1,e=1==r||3==r;ht.prototype[n]=function(n){var t=this.clone();return t.__iteratees__.push({iteratee:Ne(n,3),type:r}),t.__filtered__=t.__filtered__||e,t}})),r(["head","last"],(function(n,t){var r="take"+(t?"Right":"");ht.prototype[n]=function(){return this[r](1).value()[0]}})),r(["initial","tail"],(function(n,t){var r="drop"+(t?"":"Right");ht.prototype[n]=function(){return this.__filtered__?new ht(this):this[r](1)}})),ht.prototype.compact=function(){return this.filter(ci)},ht.prototype.find=function(n){return this.filter(n).head()},ht.prototype.findLast=function(n){return this.reverse().find(n)},ht.prototype.invokeMap=Cr((function(n,t){return"function"==typeof n?new ht(this):this.map((function(r){return er(r,n,t)}))})),ht.prototype.reject=function(n){return this.filter(Su(Ne(n)))},ht.prototype.slice=function(n,t){n=Vu(n);var r=this;return r.__filtered__&&(n>0||t<0)?new ht(r):(n<0?r=r.takeRight(-n):n&&(r=r.drop(n)),t!==P&&(r=(t=Vu(t))<0?r.dropRight(-t):r.take(t-n)),r)},ht.prototype.takeRightWhile=function(n){return this.reverse().takeWhile(n).reverse()},ht.prototype.toArray=function(){return this.take(tn)},$t(ht.prototype,(function(n,t){var r=/^(?:filter|find|map|reject)|While$/.test(t),e=/^(?:head|last)$/.test(t),u=Yn[e?"take"+("last"==t?"Right":""):t],i=e||/^find/.test(t);u&&(Yn.prototype[t]=function(){var t=this.__wrapped__,o=e?[1]:arguments,f=t instanceof ht,c=o[0],l=f||Sf(t),s=function(n){var t=u.apply(Yn,a([n],o));return e&&h?t[0]:t};l&&r&&"function"==typeof c&&1!=c.length&&(f=l=!1);var h=this.__chain__,p=!!this.__actions__.length,_=i&&!h,v=f&&!p;if(!i&&l){t=v?t:new ht(this);var g=n.apply(t,o);return g.__actions__.push({func:ju,args:[s],thisArg:P}),new st(g,h)}return _&&v?n.apply(this,o):(g=this.thru(s),_?e?g.value()[0]:g.value():g)})})),r(["pop","push","shift","sort","splice","unshift"],(function(n){var t=Ai[n],r=/^(?:push|sort|unshift)$/.test(n)?"tap":"thru",e=/^(?:pop|shift)$/.test(n);Yn.prototype[n]=function(){var n=arguments;if(e&&!this.__chain__){var u=this.value();return t.apply(Sf(u)?u:[],n)}return this[r]((function(r){return t.apply(Sf(r)?r:[],n)}))}})),$t(ht.prototype,(function(n,t){var r=Yn[t];if(r){var e=r.name+"";zi.call(yo,e)||(yo[e]=[]),yo[e].push({name:t,func:r})}})),yo[me(P,2).name]=[{name:"wrapper",func:P}],ht.prototype.clone=function(){var n=new ht(this.__wrapped__);return n.__actions__=ae(this.__actions__),n.__dir__=this.__dir__,n.__filtered__=this.__filtered__,n.__iteratees__=ae(this.__iteratees__),n.__takeCount__=this.__takeCount__,n.__views__=ae(this.__views__),n},ht.prototype.reverse=function(){if(this.__filtered__){var n=new ht(this);n.__dir__=-1,n.__filtered__=!0}else(n=this.clone()).__dir__*=-1;return n},ht.prototype.value=function(){var n=this.__wrapped__.value(),t=this.__dir__,r=Sf(n),e=t<0,u=r?n.length:0,i=function(n,t,r){for(var e=-1,u=r.length;++e<u;){var i=r[e],o=i.size;switch(i.type){case"drop":n+=o;break;case"dropRight":t-=o;break;case"take":t=io(t,n+o);break;case"takeRight":n=uo(n,t-o)}}return{start:n,end:t}}(0,u,this.__views__),o=i.start,f=i.end,c=f-o,a=e?f:o-1,l=this.__iteratees__,s=l.length,h=0,p=io(c,this.__takeCount__);if(!r||!e&&u==c&&p==c)return Jr(n,this.__actions__);var _=[];n:for(;c--&&h<p;){for(var v=-1,g=n[a+=t];++v<s;){var y=l[v],d=y.iteratee,b=y.type,w=d(g);if(2==b)g=w;else if(!w){if(1==b)continue n;break n}}_[h++]=g}return _},Yn.prototype.at=lf,Yn.prototype.chain=function(){return xu(this)},Yn.prototype.commit=function(){return new st(this.value(),this.__chain__)},Yn.prototype.next=function(){this.__values__===P&&(this.__values__=Zu(this.value()));var n=this.__index__>=this.__values__.length;return{done:n,value:n?P:this.__values__[this.__index__++]}},Yn.prototype.plant=function(n){for(var t,r=this;r instanceof lt;){var e=hu(r);e.__index__=0,e.__values__=P,t?u.__wrapped__=e:t=e;var u=e;r=r.__wrapped__}return u.__wrapped__=n,t},Yn.prototype.reverse=function(){var n=this.__wrapped__;if(n instanceof ht){var t=n;return this.__actions__.length&&(t=new ht(this)),(t=t.reverse()).__actions__.push({func:ju,args:[bu],thisArg:P}),new st(t,this.__chain__)}return this.thru(bu)},Yn.prototype.toJSON=Yn.prototype.valueOf=Yn.prototype.value=function(){return Jr(this.__wrapped__,this.__actions__)},Yn.prototype.first=Yn.prototype.head,Zi&&(Yn.prototype[Zi]=function(){return this}),Yn}();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(tr._=yr,define((function(){return yr}))):er?((er.exports=yr)._=yr,rr._=yr):tr._=yr}).call(this); vendor/wp-polyfill-element-closest.js 0000666 00000000654 15123355174 0013775 0 ustar 00 !function(e){var t=e.Element.prototype;"function"!=typeof t.matches&&(t.matches=t.msMatchesSelector||t.mozMatchesSelector||t.webkitMatchesSelector||function(e){for(var t=(this.document||this.ownerDocument).querySelectorAll(e),o=0;t[o]&&t[o]!==this;)++o;return Boolean(t[o])}),"function"!=typeof t.closest&&(t.closest=function(e){for(var t=this;t&&1===t.nodeType;){if(t.matches(e))return t;t=t.parentNode}return null})}(window);
vendor/wp-polyfill-object-fit.js 0000666 00000021741 15123355174 0012720 0 ustar 00 /*----------------------------------------
* objectFitPolyfill 2.3.5
*
* Made by Constance Chen
* Released under the ISC license
*
* https://github.com/constancecchen/object-fit-polyfill
*--------------------------------------*/
(function() {
'use strict';
// if the page is being rendered on the server, don't continue
if (typeof window === 'undefined') return;
// Workaround for Edge 16-18, which only implemented object-fit for <img> tags
var edgeMatch = window.navigator.userAgent.match(/Edge\/(\d{2})\./);
var edgeVersion = edgeMatch ? parseInt(edgeMatch[1], 10) : null;
var edgePartialSupport = edgeVersion
? edgeVersion >= 16 && edgeVersion <= 18
: false;
// If the browser does support object-fit, we don't need to continue
var hasSupport = 'objectFit' in document.documentElement.style !== false;
if (hasSupport && !edgePartialSupport) {
window.objectFitPolyfill = function() {
return false;
};
return;
}
/**
* Check the container's parent element to make sure it will
* correctly handle and clip absolutely positioned children
*
* @param {node} $container - parent element
*/
var checkParentContainer = function($container) {
var styles = window.getComputedStyle($container, null);
var position = styles.getPropertyValue('position');
var overflow = styles.getPropertyValue('overflow');
var display = styles.getPropertyValue('display');
if (!position || position === 'static') {
$container.style.position = 'relative';
}
if (overflow !== 'hidden') {
$container.style.overflow = 'hidden';
}
// Guesstimating that people want the parent to act like full width/height wrapper here.
// Mostly attempts to target <picture> elements, which default to inline.
if (!display || display === 'inline') {
$container.style.display = 'block';
}
if ($container.clientHeight === 0) {
$container.style.height = '100%';
}
// Add a CSS class hook, in case people need to override styles for any reason.
if ($container.className.indexOf('object-fit-polyfill') === -1) {
$container.className = $container.className + ' object-fit-polyfill';
}
};
/**
* Check for pre-set max-width/height, min-width/height,
* positioning, or margins, which can mess up image calculations
*
* @param {node} $media - img/video element
*/
var checkMediaProperties = function($media) {
var styles = window.getComputedStyle($media, null);
var constraints = {
'max-width': 'none',
'max-height': 'none',
'min-width': '0px',
'min-height': '0px',
top: 'auto',
right: 'auto',
bottom: 'auto',
left: 'auto',
'margin-top': '0px',
'margin-right': '0px',
'margin-bottom': '0px',
'margin-left': '0px',
};
for (var property in constraints) {
var constraint = styles.getPropertyValue(property);
if (constraint !== constraints[property]) {
$media.style[property] = constraints[property];
}
}
};
/**
* Calculate & set object-position
*
* @param {string} axis - either "x" or "y"
* @param {node} $media - img or video element
* @param {string} objectPosition - e.g. "50% 50%", "top left"
*/
var setPosition = function(axis, $media, objectPosition) {
var position, other, start, end, side;
objectPosition = objectPosition.split(' ');
if (objectPosition.length < 2) {
objectPosition[1] = objectPosition[0];
}
/* istanbul ignore else */
if (axis === 'x') {
position = objectPosition[0];
other = objectPosition[1];
start = 'left';
end = 'right';
side = $media.clientWidth;
} else if (axis === 'y') {
position = objectPosition[1];
other = objectPosition[0];
start = 'top';
end = 'bottom';
side = $media.clientHeight;
} else {
return; // Neither x or y axis specified
}
if (position === start || other === start) {
$media.style[start] = '0';
return;
}
if (position === end || other === end) {
$media.style[end] = '0';
return;
}
if (position === 'center' || position === '50%') {
$media.style[start] = '50%';
$media.style['margin-' + start] = side / -2 + 'px';
return;
}
// Percentage values (e.g., 30% 10%)
if (position.indexOf('%') >= 0) {
position = parseInt(position, 10);
if (position < 50) {
$media.style[start] = position + '%';
$media.style['margin-' + start] = side * (position / -100) + 'px';
} else {
position = 100 - position;
$media.style[end] = position + '%';
$media.style['margin-' + end] = side * (position / -100) + 'px';
}
return;
}
// Length-based values (e.g. 10px / 10em)
else {
$media.style[start] = position;
}
};
/**
* Calculate & set object-fit
*
* @param {node} $media - img/video/picture element
*/
var objectFit = function($media) {
// IE 10- data polyfill
var fit = $media.dataset
? $media.dataset.objectFit
: $media.getAttribute('data-object-fit');
var position = $media.dataset
? $media.dataset.objectPosition
: $media.getAttribute('data-object-position');
// Default fallbacks
fit = fit || 'cover';
position = position || '50% 50%';
// If necessary, make the parent container work with absolutely positioned elements
var $container = $media.parentNode;
checkParentContainer($container);
// Check for any pre-set CSS which could mess up image calculations
checkMediaProperties($media);
// Reset any pre-set width/height CSS and handle fit positioning
$media.style.position = 'absolute';
$media.style.width = 'auto';
$media.style.height = 'auto';
// `scale-down` chooses either `none` or `contain`, whichever is smaller
if (fit === 'scale-down') {
if (
$media.clientWidth < $container.clientWidth &&
$media.clientHeight < $container.clientHeight
) {
fit = 'none';
} else {
fit = 'contain';
}
}
// `none` (width/height auto) and `fill` (100%) and are straightforward
if (fit === 'none') {
setPosition('x', $media, position);
setPosition('y', $media, position);
return;
}
if (fit === 'fill') {
$media.style.width = '100%';
$media.style.height = '100%';
setPosition('x', $media, position);
setPosition('y', $media, position);
return;
}
// `cover` and `contain` must figure out which side needs covering, and add CSS positioning & centering
$media.style.height = '100%';
if (
(fit === 'cover' && $media.clientWidth > $container.clientWidth) ||
(fit === 'contain' && $media.clientWidth < $container.clientWidth)
) {
$media.style.top = '0';
$media.style.marginTop = '0';
setPosition('x', $media, position);
} else {
$media.style.width = '100%';
$media.style.height = 'auto';
$media.style.left = '0';
$media.style.marginLeft = '0';
setPosition('y', $media, position);
}
};
/**
* Initialize plugin
*
* @param {node} media - Optional specific DOM node(s) to be polyfilled
*/
var objectFitPolyfill = function(media) {
if (typeof media === 'undefined' || media instanceof Event) {
// If left blank, or a default event, all media on the page will be polyfilled.
media = document.querySelectorAll('[data-object-fit]');
} else if (media && media.nodeName) {
// If it's a single node, wrap it in an array so it works.
media = [media];
} else if (typeof media === 'object' && media.length && media[0].nodeName) {
// If it's an array of DOM nodes (e.g. a jQuery selector), it's fine as-is.
media = media;
} else {
// Otherwise, if it's invalid or an incorrect type, return false to let people know.
return false;
}
for (var i = 0; i < media.length; i++) {
if (!media[i].nodeName) continue;
var mediaType = media[i].nodeName.toLowerCase();
if (mediaType === 'img') {
if (edgePartialSupport) continue; // Edge supports object-fit for images (but nothing else), so no need to polyfill
if (media[i].complete) {
objectFit(media[i]);
} else {
media[i].addEventListener('load', function() {
objectFit(this);
});
}
} else if (mediaType === 'video') {
if (media[i].readyState > 0) {
objectFit(media[i]);
} else {
media[i].addEventListener('loadedmetadata', function() {
objectFit(this);
});
}
} else {
objectFit(media[i]);
}
}
return true;
};
if (document.readyState === 'loading') {
// Loading hasn't finished yet
document.addEventListener('DOMContentLoaded', objectFitPolyfill);
} else {
// `DOMContentLoaded` has already fired
objectFitPolyfill();
}
window.addEventListener('resize', objectFitPolyfill);
window.objectFitPolyfill = objectFitPolyfill;
})();
shortcode.min.js 0000666 00000006321 15123355174 0007672 0 ustar 00 /*! This file is auto-generated */
!function(){var t={9756:function(t){t.exports=function(t,e){var n,r,s=0;function o(){var o,i,c=n,u=arguments.length;t:for(;c;){if(c.args.length===arguments.length){for(i=0;i<u;i++)if(c.args[i]!==arguments[i]){c=c.next;continue t}return c!==n&&(c===r&&(r=c.prev),c.prev.next=c.next,c.next&&(c.next.prev=c.prev),c.next=n,c.prev=null,n.prev=c,n=c),c.val}c=c.next}for(o=new Array(u),i=0;i<u;i++)o[i]=arguments[i];return c={args:o,val:t.apply(null,o)},n?(n.prev=c,c.next=n):r=c,s===e.maxSize?(r=r.prev).next=null:s++,n=c,c.val}return e=e||{},o.clear=function(){n=null,r=null,s=0},o}}},e={};function n(r){var s=e[r];if(void 0!==s)return s.exports;var o=e[r]={exports:{}};return t[r](o,o.exports,n),o.exports}n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,{a:e}),e},n.d=function(t,e){for(var r in e)n.o(e,r)&&!n.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)};var r={};!function(){"use strict";var t=n(9756);function e(t){return new RegExp("\\[(\\[?)("+t+")(?![\\w-])([^\\]\\/]*(?:\\/(?!\\])[^\\]\\/]*)*?)(?:(\\/)\\]|\\](?:([^\\[]*(?:\\[(?!\\/\\2\\])[^\\[]*)*)(\\[\\/\\2\\]))?)(\\]?)","g")}const s=n.n(t)()((t=>{const e={},n=[],r=/([\w-]+)\s*=\s*"([^"]*)"(?:\s|$)|([\w-]+)\s*=\s*'([^']*)'(?:\s|$)|([\w-]+)\s*=\s*([^\s'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|'([^']*)'(?:\s|$)|(\S+)(?:\s|$)/g;let s;for(t=t.replace(/[\u00a0\u200b]/g," ");s=r.exec(t);)s[1]?e[s[1].toLowerCase()]=s[2]:s[3]?e[s[3].toLowerCase()]=s[4]:s[5]?e[s[5].toLowerCase()]=s[6]:s[7]?n.push(s[7]):s[8]?n.push(s[8]):s[9]&&n.push(s[9]);return{named:e,numeric:n}}));function o(t){let e;return e=t[4]?"self-closing":t[6]?"closed":"single",new i({tag:t[2],attrs:t[3],type:e,content:t[5]})}const i=Object.assign((function(t){const{tag:e,attrs:n,type:r,content:o}=t||{};if(Object.assign(this,{tag:e,type:r,content:o}),this.attrs={named:{},numeric:[]},!n)return;const i=["named","numeric"];"string"==typeof n?this.attrs=s(n):n.length===i.length&&i.every(((t,e)=>t===n[e]))?this.attrs=n:Object.entries(n).forEach((t=>{let[e,n]=t;this.set(e,n)}))}),{next:function t(n,r){let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const i=e(n);i.lastIndex=s;const c=i.exec(r);if(!c)return;if("["===c[1]&&"]"===c[7])return t(n,r,i.lastIndex);const u={index:c.index,content:c[0],shortcode:o(c)};return c[1]&&(u.content=u.content.slice(1),u.index++),c[7]&&(u.content=u.content.slice(0,-1)),u},replace:function(t,n,r){return n.replace(e(t),(function(t,e,n,s,i,c,u,a){if("["===e&&"]"===a)return t;const l=r(o(arguments));return l||""===l?e+l+a:t}))},string:function(t){return new i(t).string()},regexp:e,attrs:s,fromMatch:o});Object.assign(i.prototype,{get(t){return this.attrs["number"==typeof t?"numeric":"named"][t]},set(t,e){return this.attrs["number"==typeof t?"numeric":"named"][t]=e,this},string(){let t="["+this.tag;return this.attrs.numeric.forEach((e=>{/\s/.test(e)?t+=' "'+e+'"':t+=" "+e})),Object.entries(this.attrs.named).forEach((e=>{let[n,r]=e;t+=" "+n+'="'+r+'"'})),"single"===this.type?t+"]":"self-closing"===this.type?t+" /]":(t+="]",this.content&&(t+=this.content),t+"[/"+this.tag+"]")}}),r.default=i}(),(window.wp=window.wp||{}).shortcode=r.default}(); token-list.js 0000666 00000015527 15123355174 0007217 0 ustar 00 /******/ (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); }
/******/ }();
/******/
/************************************************************************/
var __webpack_exports__ = {};
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": function() { return /* binding */ TokenList; }
/* harmony export */ });
/**
* A set of tokens.
*
* @see https://dom.spec.whatwg.org/#domtokenlist
*/
class TokenList {
/**
* Constructs a new instance of TokenList.
*
* @param {string} initialValue Initial value to assign.
*/
constructor() {
let initialValue = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
this.value = initialValue; // Disable reason: These are type hints on the class.
/* eslint-disable no-unused-expressions */
/** @type {string} */
this._currentValue;
/** @type {string[]} */
this._valueAsArray;
/* eslint-enable no-unused-expressions */
}
/**
* @param {Parameters<Array<string>['entries']>} args
*/
entries() {
return this._valueAsArray.entries(...arguments);
}
/**
* @param {Parameters<Array<string>['forEach']>} args
*/
forEach() {
return this._valueAsArray.forEach(...arguments);
}
/**
* @param {Parameters<Array<string>['keys']>} args
*/
keys() {
return this._valueAsArray.keys(...arguments);
}
/**
* @param {Parameters<Array<string>['values']>} args
*/
values() {
return this._valueAsArray.values(...arguments);
}
/**
* Returns the associated set as string.
*
* @see https://dom.spec.whatwg.org/#dom-domtokenlist-value
*
* @return {string} Token set as string.
*/
get value() {
return this._currentValue;
}
/**
* Replaces the associated set with a new string value.
*
* @see https://dom.spec.whatwg.org/#dom-domtokenlist-value
*
* @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.
*
* @see https://dom.spec.whatwg.org/#dom-domtokenlist-length
*
* @return {number} Number of tokens.
*/
get length() {
return this._valueAsArray.length;
}
/**
* Returns the stringified form of the TokenList.
*
* @see https://dom.spec.whatwg.org/#DOMTokenList-stringification-behavior
* @see https://www.ecma-international.org/ecma-262/9.0/index.html#sec-tostring
*
* @return {string} Token set as string.
*/
toString() {
return this.value;
}
/**
* Returns an iterator for the TokenList, iterating items of the set.
*
* @see https://dom.spec.whatwg.org/#domtokenlist
*
* @return {IterableIterator<string>} TokenList iterator.
*/
*[Symbol.iterator]() {
return yield* this._valueAsArray;
}
/**
* Returns the token with index `index`.
*
* @see https://dom.spec.whatwg.org/#dom-domtokenlist-item
*
* @param {number} index Index at which to return token.
*
* @return {string|undefined} Token at index.
*/
item(index) {
return this._valueAsArray[index];
}
/**
* Returns true if `token` is present, and false otherwise.
*
* @see https://dom.spec.whatwg.org/#dom-domtokenlist-contains
*
* @param {string} item Token to test.
*
* @return {boolean} Whether token is present.
*/
contains(item) {
return this._valueAsArray.indexOf(item) !== -1;
}
/**
* Adds all arguments passed, except those already present.
*
* @see https://dom.spec.whatwg.org/#dom-domtokenlist-add
*
* @param {...string} items Items to add.
*/
add() {
for (var _len = arguments.length, items = new Array(_len), _key = 0; _key < _len; _key++) {
items[_key] = arguments[_key];
}
this.value += ' ' + items.join(' ');
}
/**
* Removes arguments passed, if they are present.
*
* @see https://dom.spec.whatwg.org/#dom-domtokenlist-remove
*
* @param {...string} items Items to remove.
*/
remove() {
for (var _len2 = arguments.length, items = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
items[_key2] = arguments[_key2];
}
this.value = this._valueAsArray.filter(val => !items.includes(val)).join(' ');
}
/**
* If `force` is not given, "toggles" `token`, removing it if it’s present
* and adding it if it’s not present. If `force` is true, adds token (same
* as add()). If force is false, removes token (same as remove()). Returns
* true if `token` is now present, and false otherwise.
*
* @see https://dom.spec.whatwg.org/#dom-domtokenlist-toggle
*
* @param {string} token Token to toggle.
* @param {boolean} [force] Presence to force.
*
* @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.
*
* @see https://dom.spec.whatwg.org/#dom-domtokenlist-replace
*
* @param {string} token Token to replace with `newToken`.
* @param {string} newToken Token to use in place of `token`.
*
* @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 attribute’s supported
* tokens. Returns false otherwise.
*
* Always returns `true` in this implementation.
*
* @see https://dom.spec.whatwg.org/#dom-domtokenlist-supports
*
* @return {boolean} Whether token is supported.
*/
supports() {
return true;
}
}
(window.wp = window.wp || {}).tokenList = __webpack_exports__["default"];
/******/ })()
; editor.js 0000666 00001536241 15123355174 0006416 0 ustar 00 /******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 6411:
/***/ (function(module, exports) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
autosize 4.0.4
license: MIT
http://www.jacklmoore.com/autosize
*/
(function (global, factory) {
if (true) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [module, exports], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else { var mod; }
})(this, function (module, exports) {
'use strict';
var map = typeof Map === "function" ? new Map() : function () {
var keys = [];
var values = [];
return {
has: function has(key) {
return keys.indexOf(key) > -1;
},
get: function get(key) {
return values[keys.indexOf(key)];
},
set: function set(key, value) {
if (keys.indexOf(key) === -1) {
keys.push(key);
values.push(value);
}
},
delete: function _delete(key) {
var index = keys.indexOf(key);
if (index > -1) {
keys.splice(index, 1);
values.splice(index, 1);
}
}
};
}();
var createEvent = function createEvent(name) {
return new Event(name, { bubbles: true });
};
try {
new Event('test');
} catch (e) {
// IE does not support `new Event()`
createEvent = function createEvent(name) {
var evt = document.createEvent('Event');
evt.initEvent(name, true, false);
return evt;
};
}
function assign(ta) {
if (!ta || !ta.nodeName || ta.nodeName !== 'TEXTAREA' || map.has(ta)) return;
var heightOffset = null;
var clientWidth = null;
var cachedHeight = null;
function init() {
var style = window.getComputedStyle(ta, null);
if (style.resize === 'vertical') {
ta.style.resize = 'none';
} else if (style.resize === 'both') {
ta.style.resize = 'horizontal';
}
if (style.boxSizing === 'content-box') {
heightOffset = -(parseFloat(style.paddingTop) + parseFloat(style.paddingBottom));
} else {
heightOffset = parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth);
}
// Fix when a textarea is not on document body and heightOffset is Not a Number
if (isNaN(heightOffset)) {
heightOffset = 0;
}
update();
}
function changeOverflow(value) {
{
// Chrome/Safari-specific fix:
// When the textarea y-overflow is hidden, Chrome/Safari do not reflow the text to account for the space
// made available by removing the scrollbar. The following forces the necessary text reflow.
var width = ta.style.width;
ta.style.width = '0px';
// Force reflow:
/* jshint ignore:start */
ta.offsetWidth;
/* jshint ignore:end */
ta.style.width = width;
}
ta.style.overflowY = value;
}
function getParentOverflows(el) {
var arr = [];
while (el && el.parentNode && el.parentNode instanceof Element) {
if (el.parentNode.scrollTop) {
arr.push({
node: el.parentNode,
scrollTop: el.parentNode.scrollTop
});
}
el = el.parentNode;
}
return arr;
}
function resize() {
if (ta.scrollHeight === 0) {
// If the scrollHeight is 0, then the element probably has display:none or is detached from the DOM.
return;
}
var overflows = getParentOverflows(ta);
var docTop = document.documentElement && document.documentElement.scrollTop; // Needed for Mobile IE (ticket #240)
ta.style.height = '';
ta.style.height = ta.scrollHeight + heightOffset + 'px';
// used to check if an update is actually necessary on window.resize
clientWidth = ta.clientWidth;
// prevents scroll-position jumping
overflows.forEach(function (el) {
el.node.scrollTop = el.scrollTop;
});
if (docTop) {
document.documentElement.scrollTop = docTop;
}
}
function update() {
resize();
var styleHeight = Math.round(parseFloat(ta.style.height));
var computed = window.getComputedStyle(ta, null);
// Using offsetHeight as a replacement for computed.height in IE, because IE does not account use of border-box
var actualHeight = computed.boxSizing === 'content-box' ? Math.round(parseFloat(computed.height)) : ta.offsetHeight;
// The actual height not matching the style height (set via the resize method) indicates that
// the max-height has been exceeded, in which case the overflow should be allowed.
if (actualHeight < styleHeight) {
if (computed.overflowY === 'hidden') {
changeOverflow('scroll');
resize();
actualHeight = computed.boxSizing === 'content-box' ? Math.round(parseFloat(window.getComputedStyle(ta, null).height)) : ta.offsetHeight;
}
} else {
// Normally keep overflow set to hidden, to avoid flash of scrollbar as the textarea expands.
if (computed.overflowY !== 'hidden') {
changeOverflow('hidden');
resize();
actualHeight = computed.boxSizing === 'content-box' ? Math.round(parseFloat(window.getComputedStyle(ta, null).height)) : ta.offsetHeight;
}
}
if (cachedHeight !== actualHeight) {
cachedHeight = actualHeight;
var evt = createEvent('autosize:resized');
try {
ta.dispatchEvent(evt);
} catch (err) {
// Firefox will throw an error on dispatchEvent for a detached element
// https://bugzilla.mozilla.org/show_bug.cgi?id=889376
}
}
}
var pageResize = function pageResize() {
if (ta.clientWidth !== clientWidth) {
update();
}
};
var destroy = function (style) {
window.removeEventListener('resize', pageResize, false);
ta.removeEventListener('input', update, false);
ta.removeEventListener('keyup', update, false);
ta.removeEventListener('autosize:destroy', destroy, false);
ta.removeEventListener('autosize:update', update, false);
Object.keys(style).forEach(function (key) {
ta.style[key] = style[key];
});
map.delete(ta);
}.bind(ta, {
height: ta.style.height,
resize: ta.style.resize,
overflowY: ta.style.overflowY,
overflowX: ta.style.overflowX,
wordWrap: ta.style.wordWrap
});
ta.addEventListener('autosize:destroy', destroy, false);
// IE9 does not fire onpropertychange or oninput for deletions,
// so binding to onkeyup to catch most of those events.
// There is no way that I know of to detect something like 'cut' in IE9.
if ('onpropertychange' in ta && 'oninput' in ta) {
ta.addEventListener('keyup', update, false);
}
window.addEventListener('resize', pageResize, false);
ta.addEventListener('input', update, false);
ta.addEventListener('autosize:update', update, false);
ta.style.overflowX = 'hidden';
ta.style.wordWrap = 'break-word';
map.set(ta, {
destroy: destroy,
update: update
});
init();
}
function destroy(ta) {
var methods = map.get(ta);
if (methods) {
methods.destroy();
}
}
function update(ta) {
var methods = map.get(ta);
if (methods) {
methods.update();
}
}
var autosize = null;
// Do nothing in Node.js environment and IE8 (or lower)
if (typeof window === 'undefined' || typeof window.getComputedStyle !== 'function') {
autosize = function autosize(el) {
return el;
};
autosize.destroy = function (el) {
return el;
};
autosize.update = function (el) {
return el;
};
} else {
autosize = function autosize(el, options) {
if (el) {
Array.prototype.forEach.call(el.length ? el : [el], function (x) {
return assign(x, options);
});
}
return el;
};
autosize.destroy = function (el) {
if (el) {
Array.prototype.forEach.call(el.length ? el : [el], destroy);
}
return el;
};
autosize.update = function (el) {
if (el) {
Array.prototype.forEach.call(el.length ? el : [el], update);
}
return el;
};
}
exports.default = autosize;
module.exports = exports['default'];
});
/***/ }),
/***/ 4827:
/***/ (function(module) {
// This code has been refactored for 140 bytes
// You can see the original here: https://github.com/twolfson/computedStyle/blob/04cd1da2e30fa45844f95f5cb1ac898e9b9ef050/lib/computedStyle.js
var computedStyle = function (el, prop, getComputedStyle) {
getComputedStyle = window.getComputedStyle;
// In one fell swoop
return (
// If we have getComputedStyle
getComputedStyle ?
// Query it
// TODO: From CSS-Query notes, we might need (node, null) for FF
getComputedStyle(el) :
// Otherwise, we are in IE and use currentStyle
el.currentStyle
)[
// Switch to camelCase for CSSOM
// DEV: Grabbed from jQuery
// https://github.com/jquery/jquery/blob/1.9-stable/src/css.js#L191-L194
// https://github.com/jquery/jquery/blob/1.9-stable/src/core.js#L593-L597
prop.replace(/-(\w)/gi, function (word, letter) {
return letter.toUpperCase();
})
];
};
module.exports = computedStyle;
/***/ }),
/***/ 3613:
/***/ (function(module) {
"use strict";
/*!
* escape-html
* Copyright(c) 2012-2013 TJ Holowaychuk
* Copyright(c) 2015 Andreas Lubbe
* Copyright(c) 2015 Tiancheng "Timothy" Gu
* MIT Licensed
*/
/**
* Module variables.
* @private
*/
var matchHtmlRegExp = /["'&<>]/;
/**
* Module exports.
* @public
*/
module.exports = escapeHtml;
/**
* Escape special characters in the given string of html.
*
* @param {string} string The string to escape for inserting into HTML
* @return {string}
* @public
*/
function escapeHtml(string) {
var str = '' + string;
var match = matchHtmlRegExp.exec(str);
if (!match) {
return str;
}
var escape;
var html = '';
var index = 0;
var lastIndex = 0;
for (index = match.index; index < str.length; index++) {
switch (str.charCodeAt(index)) {
case 34: // "
escape = '"';
break;
case 38: // &
escape = '&';
break;
case 39: // '
escape = ''';
break;
case 60: // <
escape = '<';
break;
case 62: // >
escape = '>';
break;
default:
continue;
}
if (lastIndex !== index) {
html += str.substring(lastIndex, index);
}
lastIndex = index + 1;
html += escape;
}
return lastIndex !== index
? html + str.substring(lastIndex, index)
: html;
}
/***/ }),
/***/ 9894:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
// Load in dependencies
var computedStyle = __webpack_require__(4827);
/**
* Calculate the `line-height` of a given node
* @param {HTMLElement} node Element to calculate line height of. Must be in the DOM.
* @returns {Number} `line-height` of the element in pixels
*/
function lineHeight(node) {
// Grab the line-height via style
var lnHeightStr = computedStyle(node, 'line-height');
var lnHeight = parseFloat(lnHeightStr, 10);
// If the lineHeight did not contain a unit (i.e. it was numeric), convert it to ems (e.g. '2.3' === '2.3em')
if (lnHeightStr === lnHeight + '') {
// Save the old lineHeight style and update the em unit to the element
var _lnHeightStyle = node.style.lineHeight;
node.style.lineHeight = lnHeightStr + 'em';
// Calculate the em based height
lnHeightStr = computedStyle(node, 'line-height');
lnHeight = parseFloat(lnHeightStr, 10);
// Revert the lineHeight style
if (_lnHeightStyle) {
node.style.lineHeight = _lnHeightStyle;
} else {
delete node.style.lineHeight;
}
}
// If the lineHeight is in `pt`, convert it to pixels (4px for 3pt)
// DEV: `em` units are converted to `pt` in IE6
// Conversion ratio from https://developer.mozilla.org/en-US/docs/Web/CSS/length
if (lnHeightStr.indexOf('pt') !== -1) {
lnHeight *= 4;
lnHeight /= 3;
// Otherwise, if the lineHeight is in `mm`, convert it to pixels (96px for 25.4mm)
} else if (lnHeightStr.indexOf('mm') !== -1) {
lnHeight *= 96;
lnHeight /= 25.4;
// Otherwise, if the lineHeight is in `cm`, convert it to pixels (96px for 2.54cm)
} else if (lnHeightStr.indexOf('cm') !== -1) {
lnHeight *= 96;
lnHeight /= 2.54;
// Otherwise, if the lineHeight is in `in`, convert it to pixels (96px for 1in)
} else if (lnHeightStr.indexOf('in') !== -1) {
lnHeight *= 96;
// Otherwise, if the lineHeight is in `pc`, convert it to pixels (12pt for 1pc)
} else if (lnHeightStr.indexOf('pc') !== -1) {
lnHeight *= 16;
}
// Continue our computation
lnHeight = Math.round(lnHeight);
// If the line-height is "normal", calculate by font-size
if (lnHeightStr === 'normal') {
// Create a temporary node
var nodeName = node.nodeName;
var _node = document.createElement(nodeName);
_node.innerHTML = ' ';
// If we have a text area, reset it to only 1 row
// https://github.com/twolfson/line-height/issues/4
if (nodeName.toUpperCase() === 'TEXTAREA') {
_node.setAttribute('rows', '1');
}
// Set the font-size of the element
var fontSizeStr = computedStyle(node, 'font-size');
_node.style.fontSize = fontSizeStr;
// Remove default padding/border which can affect offset height
// https://github.com/twolfson/line-height/issues/4
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight
_node.style.padding = '0px';
_node.style.border = '0px';
// Append it to the body
var body = document.body;
body.appendChild(_node);
// Assume the line height of the element is the height
var height = _node.offsetHeight;
lnHeight = height;
// Remove our child from the DOM
body.removeChild(_node);
}
// Return the calculated height
return lnHeight;
}
// Export lineHeight
module.exports = lineHeight;
/***/ }),
/***/ 5372:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = __webpack_require__(9567);
function emptyFunction() {}
function emptyFunctionWithReset() {}
emptyFunctionWithReset.resetWarningCache = emptyFunction;
module.exports = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
if (secret === ReactPropTypesSecret) {
// It is still safe when called from React.
return;
}
var err = new Error(
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use PropTypes.checkPropTypes() to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
err.name = 'Invariant Violation';
throw err;
};
shim.isRequired = shim;
function getShim() {
return shim;
};
// Important!
// Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
var ReactPropTypes = {
array: shim,
bigint: shim,
bool: shim,
func: shim,
number: shim,
object: shim,
string: shim,
symbol: shim,
any: shim,
arrayOf: getShim,
element: shim,
elementType: shim,
instanceOf: getShim,
node: shim,
objectOf: getShim,
oneOf: getShim,
oneOfType: getShim,
shape: getShim,
exact: getShim,
checkPropTypes: emptyFunctionWithReset,
resetWarningCache: emptyFunction
};
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
/***/ }),
/***/ 2652:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
if (false) { var throwOnDirectAccess, ReactIs; } else {
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
module.exports = __webpack_require__(5372)();
}
/***/ }),
/***/ 9567:
/***/ (function(module) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
module.exports = ReactPropTypesSecret;
/***/ }),
/***/ 5438:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (this && this.__assign) || Object.assign || function(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;
};
var __rest = (this && this.__rest) || function (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)
t[p[i]] = s[p[i]];
return t;
};
exports.__esModule = true;
var React = __webpack_require__(9196);
var PropTypes = __webpack_require__(2652);
var autosize = __webpack_require__(6411);
var _getLineHeight = __webpack_require__(9894);
var getLineHeight = _getLineHeight;
var RESIZED = "autosize:resized";
/**
* A light replacement for built-in textarea component
* which automaticaly adjusts its height to match the content
*/
var TextareaAutosizeClass = /** @class */ (function (_super) {
__extends(TextareaAutosizeClass, _super);
function TextareaAutosizeClass() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.state = {
lineHeight: null
};
_this.textarea = null;
_this.onResize = function (e) {
if (_this.props.onResize) {
_this.props.onResize(e);
}
};
_this.updateLineHeight = function () {
if (_this.textarea) {
_this.setState({
lineHeight: getLineHeight(_this.textarea)
});
}
};
_this.onChange = function (e) {
var onChange = _this.props.onChange;
_this.currentValue = e.currentTarget.value;
onChange && onChange(e);
};
return _this;
}
TextareaAutosizeClass.prototype.componentDidMount = function () {
var _this = this;
var _a = this.props, maxRows = _a.maxRows, async = _a.async;
if (typeof maxRows === "number") {
this.updateLineHeight();
}
if (typeof maxRows === "number" || async) {
/*
the defer is needed to:
- force "autosize" to activate the scrollbar when this.props.maxRows is passed
- support StyledComponents (see #71)
*/
setTimeout(function () { return _this.textarea && autosize(_this.textarea); });
}
else {
this.textarea && autosize(this.textarea);
}
if (this.textarea) {
this.textarea.addEventListener(RESIZED, this.onResize);
}
};
TextareaAutosizeClass.prototype.componentWillUnmount = function () {
if (this.textarea) {
this.textarea.removeEventListener(RESIZED, this.onResize);
autosize.destroy(this.textarea);
}
};
TextareaAutosizeClass.prototype.render = function () {
var _this = this;
var _a = this, _b = _a.props, onResize = _b.onResize, maxRows = _b.maxRows, onChange = _b.onChange, style = _b.style, innerRef = _b.innerRef, children = _b.children, props = __rest(_b, ["onResize", "maxRows", "onChange", "style", "innerRef", "children"]), lineHeight = _a.state.lineHeight;
var maxHeight = maxRows && lineHeight ? lineHeight * maxRows : null;
return (React.createElement("textarea", __assign({}, props, { onChange: this.onChange, style: maxHeight ? __assign({}, style, { maxHeight: maxHeight }) : style, ref: function (element) {
_this.textarea = element;
if (typeof _this.props.innerRef === 'function') {
_this.props.innerRef(element);
}
else if (_this.props.innerRef) {
_this.props.innerRef.current = element;
}
} }), children));
};
TextareaAutosizeClass.prototype.componentDidUpdate = function () {
this.textarea && autosize.update(this.textarea);
};
TextareaAutosizeClass.defaultProps = {
rows: 1,
async: false
};
TextareaAutosizeClass.propTypes = {
rows: PropTypes.number,
maxRows: PropTypes.number,
onResize: PropTypes.func,
innerRef: PropTypes.any,
async: PropTypes.bool
};
return TextareaAutosizeClass;
}(React.Component));
exports.TextareaAutosize = React.forwardRef(function (props, ref) {
return React.createElement(TextareaAutosizeClass, __assign({}, props, { innerRef: ref }));
});
/***/ }),
/***/ 773:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __webpack_unused_export__;
__webpack_unused_export__ = true;
var TextareaAutosize_1 = __webpack_require__(5438);
exports.Z = TextareaAutosize_1.TextareaAutosize;
/***/ }),
/***/ 4793:
/***/ (function(module) {
var characterMap = {
"À": "A",
"Á": "A",
"Â": "A",
"Ã": "A",
"Ä": "A",
"Å": "A",
"Ấ": "A",
"Ắ": "A",
"Ẳ": "A",
"Ẵ": "A",
"Ặ": "A",
"Æ": "AE",
"Ầ": "A",
"Ằ": "A",
"Ȃ": "A",
"Ç": "C",
"Ḉ": "C",
"È": "E",
"É": "E",
"Ê": "E",
"Ë": "E",
"Ế": "E",
"Ḗ": "E",
"Ề": "E",
"Ḕ": "E",
"Ḝ": "E",
"Ȇ": "E",
"Ì": "I",
"Í": "I",
"Î": "I",
"Ï": "I",
"Ḯ": "I",
"Ȋ": "I",
"Ð": "D",
"Ñ": "N",
"Ò": "O",
"Ó": "O",
"Ô": "O",
"Õ": "O",
"Ö": "O",
"Ø": "O",
"Ố": "O",
"Ṍ": "O",
"Ṓ": "O",
"Ȏ": "O",
"Ù": "U",
"Ú": "U",
"Û": "U",
"Ü": "U",
"Ý": "Y",
"à": "a",
"á": "a",
"â": "a",
"ã": "a",
"ä": "a",
"å": "a",
"ấ": "a",
"ắ": "a",
"ẳ": "a",
"ẵ": "a",
"ặ": "a",
"æ": "ae",
"ầ": "a",
"ằ": "a",
"ȃ": "a",
"ç": "c",
"ḉ": "c",
"è": "e",
"é": "e",
"ê": "e",
"ë": "e",
"ế": "e",
"ḗ": "e",
"ề": "e",
"ḕ": "e",
"ḝ": "e",
"ȇ": "e",
"ì": "i",
"í": "i",
"î": "i",
"ï": "i",
"ḯ": "i",
"ȋ": "i",
"ð": "d",
"ñ": "n",
"ò": "o",
"ó": "o",
"ô": "o",
"õ": "o",
"ö": "o",
"ø": "o",
"ố": "o",
"ṍ": "o",
"ṓ": "o",
"ȏ": "o",
"ù": "u",
"ú": "u",
"û": "u",
"ü": "u",
"ý": "y",
"ÿ": "y",
"Ā": "A",
"ā": "a",
"Ă": "A",
"ă": "a",
"Ą": "A",
"ą": "a",
"Ć": "C",
"ć": "c",
"Ĉ": "C",
"ĉ": "c",
"Ċ": "C",
"ċ": "c",
"Č": "C",
"č": "c",
"C̆": "C",
"c̆": "c",
"Ď": "D",
"ď": "d",
"Đ": "D",
"đ": "d",
"Ē": "E",
"ē": "e",
"Ĕ": "E",
"ĕ": "e",
"Ė": "E",
"ė": "e",
"Ę": "E",
"ę": "e",
"Ě": "E",
"ě": "e",
"Ĝ": "G",
"Ǵ": "G",
"ĝ": "g",
"ǵ": "g",
"Ğ": "G",
"ğ": "g",
"Ġ": "G",
"ġ": "g",
"Ģ": "G",
"ģ": "g",
"Ĥ": "H",
"ĥ": "h",
"Ħ": "H",
"ħ": "h",
"Ḫ": "H",
"ḫ": "h",
"Ĩ": "I",
"ĩ": "i",
"Ī": "I",
"ī": "i",
"Ĭ": "I",
"ĭ": "i",
"Į": "I",
"į": "i",
"İ": "I",
"ı": "i",
"IJ": "IJ",
"ij": "ij",
"Ĵ": "J",
"ĵ": "j",
"Ķ": "K",
"ķ": "k",
"Ḱ": "K",
"ḱ": "k",
"K̆": "K",
"k̆": "k",
"Ĺ": "L",
"ĺ": "l",
"Ļ": "L",
"ļ": "l",
"Ľ": "L",
"ľ": "l",
"Ŀ": "L",
"ŀ": "l",
"Ł": "l",
"ł": "l",
"Ḿ": "M",
"ḿ": "m",
"M̆": "M",
"m̆": "m",
"Ń": "N",
"ń": "n",
"Ņ": "N",
"ņ": "n",
"Ň": "N",
"ň": "n",
"ʼn": "n",
"N̆": "N",
"n̆": "n",
"Ō": "O",
"ō": "o",
"Ŏ": "O",
"ŏ": "o",
"Ő": "O",
"ő": "o",
"Œ": "OE",
"œ": "oe",
"P̆": "P",
"p̆": "p",
"Ŕ": "R",
"ŕ": "r",
"Ŗ": "R",
"ŗ": "r",
"Ř": "R",
"ř": "r",
"R̆": "R",
"r̆": "r",
"Ȓ": "R",
"ȓ": "r",
"Ś": "S",
"ś": "s",
"Ŝ": "S",
"ŝ": "s",
"Ş": "S",
"Ș": "S",
"ș": "s",
"ş": "s",
"Š": "S",
"š": "s",
"ß": "ss",
"Ţ": "T",
"ţ": "t",
"ț": "t",
"Ț": "T",
"Ť": "T",
"ť": "t",
"Ŧ": "T",
"ŧ": "t",
"T̆": "T",
"t̆": "t",
"Ũ": "U",
"ũ": "u",
"Ū": "U",
"ū": "u",
"Ŭ": "U",
"ŭ": "u",
"Ů": "U",
"ů": "u",
"Ű": "U",
"ű": "u",
"Ų": "U",
"ų": "u",
"Ȗ": "U",
"ȗ": "u",
"V̆": "V",
"v̆": "v",
"Ŵ": "W",
"ŵ": "w",
"Ẃ": "W",
"ẃ": "w",
"X̆": "X",
"x̆": "x",
"Ŷ": "Y",
"ŷ": "y",
"Ÿ": "Y",
"Y̆": "Y",
"y̆": "y",
"Ź": "Z",
"ź": "z",
"Ż": "Z",
"ż": "z",
"Ž": "Z",
"ž": "z",
"ſ": "s",
"ƒ": "f",
"Ơ": "O",
"ơ": "o",
"Ư": "U",
"ư": "u",
"Ǎ": "A",
"ǎ": "a",
"Ǐ": "I",
"ǐ": "i",
"Ǒ": "O",
"ǒ": "o",
"Ǔ": "U",
"ǔ": "u",
"Ǖ": "U",
"ǖ": "u",
"Ǘ": "U",
"ǘ": "u",
"Ǚ": "U",
"ǚ": "u",
"Ǜ": "U",
"ǜ": "u",
"Ứ": "U",
"ứ": "u",
"Ṹ": "U",
"ṹ": "u",
"Ǻ": "A",
"ǻ": "a",
"Ǽ": "AE",
"ǽ": "ae",
"Ǿ": "O",
"ǿ": "o",
"Þ": "TH",
"þ": "th",
"Ṕ": "P",
"ṕ": "p",
"Ṥ": "S",
"ṥ": "s",
"X́": "X",
"x́": "x",
"Ѓ": "Г",
"ѓ": "г",
"Ќ": "К",
"ќ": "к",
"A̋": "A",
"a̋": "a",
"E̋": "E",
"e̋": "e",
"I̋": "I",
"i̋": "i",
"Ǹ": "N",
"ǹ": "n",
"Ồ": "O",
"ồ": "o",
"Ṑ": "O",
"ṑ": "o",
"Ừ": "U",
"ừ": "u",
"Ẁ": "W",
"ẁ": "w",
"Ỳ": "Y",
"ỳ": "y",
"Ȁ": "A",
"ȁ": "a",
"Ȅ": "E",
"ȅ": "e",
"Ȉ": "I",
"ȉ": "i",
"Ȍ": "O",
"ȍ": "o",
"Ȑ": "R",
"ȑ": "r",
"Ȕ": "U",
"ȕ": "u",
"B̌": "B",
"b̌": "b",
"Č̣": "C",
"č̣": "c",
"Ê̌": "E",
"ê̌": "e",
"F̌": "F",
"f̌": "f",
"Ǧ": "G",
"ǧ": "g",
"Ȟ": "H",
"ȟ": "h",
"J̌": "J",
"ǰ": "j",
"Ǩ": "K",
"ǩ": "k",
"M̌": "M",
"m̌": "m",
"P̌": "P",
"p̌": "p",
"Q̌": "Q",
"q̌": "q",
"Ř̩": "R",
"ř̩": "r",
"Ṧ": "S",
"ṧ": "s",
"V̌": "V",
"v̌": "v",
"W̌": "W",
"w̌": "w",
"X̌": "X",
"x̌": "x",
"Y̌": "Y",
"y̌": "y",
"A̧": "A",
"a̧": "a",
"B̧": "B",
"b̧": "b",
"Ḑ": "D",
"ḑ": "d",
"Ȩ": "E",
"ȩ": "e",
"Ɛ̧": "E",
"ɛ̧": "e",
"Ḩ": "H",
"ḩ": "h",
"I̧": "I",
"i̧": "i",
"Ɨ̧": "I",
"ɨ̧": "i",
"M̧": "M",
"m̧": "m",
"O̧": "O",
"o̧": "o",
"Q̧": "Q",
"q̧": "q",
"U̧": "U",
"u̧": "u",
"X̧": "X",
"x̧": "x",
"Z̧": "Z",
"z̧": "z",
"й":"и",
"Й":"И",
"ё":"е",
"Ё":"Е",
};
var chars = Object.keys(characterMap).join('|');
var allAccents = new RegExp(chars, 'g');
var firstAccent = new RegExp(chars, '');
function matcher(match) {
return characterMap[match];
}
var removeAccents = function(string) {
return string.replace(allAccents, matcher);
};
var hasAccents = function(string) {
return !!string.match(firstAccent);
};
module.exports = removeAccents;
module.exports.has = hasAccents;
module.exports.remove = removeAccents;
/***/ }),
/***/ 9196:
/***/ (function(module) {
"use strict";
module.exports = window["React"];
/***/ }),
/***/ 7153:
/***/ (function(module, exports) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2018 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
'use strict';
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = '';
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
classes = appendClass(classes, parseValue(arg));
}
}
return classes;
}
function parseValue (arg) {
if (typeof arg === 'string' || typeof arg === 'number') {
return arg;
}
if (typeof arg !== 'object') {
return '';
}
if (Array.isArray(arg)) {
return classNames.apply(null, arg);
}
if (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes('[native code]')) {
return arg.toString();
}
var classes = '';
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes = appendClass(classes, key);
}
}
return classes;
}
function appendClass (value, newClass) {
if (!newClass) {
return value;
}
if (value) {
return value + ' ' + newClass;
}
return value + newClass;
}
if ( true && module.exports) {
classNames.default = classNames;
module.exports = classNames;
} else if (true) {
// register as 'classnames', consistent with npm package name
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () {
return classNames;
}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
}());
/***/ })
/******/ });
/************************************************************************/
/******/ // 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].call(module.exports, 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 in strict mode.
!function() {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
"AlignmentToolbar": function() { return /* reexport */ AlignmentToolbar; },
"Autocomplete": function() { return /* reexport */ Autocomplete; },
"AutosaveMonitor": function() { return /* reexport */ autosave_monitor; },
"BlockAlignmentToolbar": function() { return /* reexport */ BlockAlignmentToolbar; },
"BlockControls": function() { return /* reexport */ BlockControls; },
"BlockEdit": function() { return /* reexport */ BlockEdit; },
"BlockEditorKeyboardShortcuts": function() { return /* reexport */ BlockEditorKeyboardShortcuts; },
"BlockFormatControls": function() { return /* reexport */ BlockFormatControls; },
"BlockIcon": function() { return /* reexport */ BlockIcon; },
"BlockInspector": function() { return /* reexport */ BlockInspector; },
"BlockList": function() { return /* reexport */ BlockList; },
"BlockMover": function() { return /* reexport */ BlockMover; },
"BlockNavigationDropdown": function() { return /* reexport */ BlockNavigationDropdown; },
"BlockSelectionClearer": function() { return /* reexport */ BlockSelectionClearer; },
"BlockSettingsMenu": function() { return /* reexport */ BlockSettingsMenu; },
"BlockTitle": function() { return /* reexport */ BlockTitle; },
"BlockToolbar": function() { return /* reexport */ BlockToolbar; },
"CharacterCount": function() { return /* reexport */ CharacterCount; },
"ColorPalette": function() { return /* reexport */ ColorPalette; },
"ContrastChecker": function() { return /* reexport */ ContrastChecker; },
"CopyHandler": function() { return /* reexport */ CopyHandler; },
"DefaultBlockAppender": function() { return /* reexport */ DefaultBlockAppender; },
"DocumentOutline": function() { return /* reexport */ document_outline; },
"DocumentOutlineCheck": function() { return /* reexport */ check; },
"EditorHistoryRedo": function() { return /* reexport */ editor_history_redo; },
"EditorHistoryUndo": function() { return /* reexport */ editor_history_undo; },
"EditorKeyboardShortcutsRegister": function() { return /* reexport */ register_shortcuts; },
"EditorNotices": function() { return /* reexport */ editor_notices; },
"EditorProvider": function() { return /* reexport */ provider; },
"EditorSnackbars": function() { return /* reexport */ EditorSnackbars; },
"EntitiesSavedStates": function() { return /* reexport */ EntitiesSavedStates; },
"ErrorBoundary": function() { return /* reexport */ error_boundary; },
"FontSizePicker": function() { return /* reexport */ FontSizePicker; },
"InnerBlocks": function() { return /* reexport */ InnerBlocks; },
"Inserter": function() { return /* reexport */ Inserter; },
"InspectorAdvancedControls": function() { return /* reexport */ InspectorAdvancedControls; },
"InspectorControls": function() { return /* reexport */ InspectorControls; },
"LocalAutosaveMonitor": function() { return /* reexport */ local_autosave_monitor; },
"MediaPlaceholder": function() { return /* reexport */ MediaPlaceholder; },
"MediaUpload": function() { return /* reexport */ MediaUpload; },
"MediaUploadCheck": function() { return /* reexport */ MediaUploadCheck; },
"MultiSelectScrollIntoView": function() { return /* reexport */ MultiSelectScrollIntoView; },
"NavigableToolbar": function() { return /* reexport */ NavigableToolbar; },
"ObserveTyping": function() { return /* reexport */ ObserveTyping; },
"PageAttributesCheck": function() { return /* reexport */ page_attributes_check; },
"PageAttributesOrder": function() { return /* reexport */ order; },
"PageAttributesParent": function() { return /* reexport */ page_attributes_parent; },
"PageTemplate": function() { return /* reexport */ post_template; },
"PanelColorSettings": function() { return /* reexport */ PanelColorSettings; },
"PlainText": function() { return /* reexport */ PlainText; },
"PostAuthor": function() { return /* reexport */ post_author; },
"PostAuthorCheck": function() { return /* reexport */ PostAuthorCheck; },
"PostComments": function() { return /* reexport */ post_comments; },
"PostExcerpt": function() { return /* reexport */ post_excerpt; },
"PostExcerptCheck": function() { return /* reexport */ post_excerpt_check; },
"PostFeaturedImage": function() { return /* reexport */ post_featured_image; },
"PostFeaturedImageCheck": function() { return /* reexport */ post_featured_image_check; },
"PostFormat": function() { return /* reexport */ PostFormat; },
"PostFormatCheck": function() { return /* reexport */ post_format_check; },
"PostLastRevision": function() { return /* reexport */ post_last_revision; },
"PostLastRevisionCheck": function() { return /* reexport */ post_last_revision_check; },
"PostLockedModal": function() { return /* reexport */ PostLockedModal; },
"PostPendingStatus": function() { return /* reexport */ post_pending_status; },
"PostPendingStatusCheck": function() { return /* reexport */ post_pending_status_check; },
"PostPingbacks": function() { return /* reexport */ post_pingbacks; },
"PostPreviewButton": function() { return /* reexport */ post_preview_button; },
"PostPublishButton": function() { return /* reexport */ post_publish_button; },
"PostPublishButtonLabel": function() { return /* reexport */ label; },
"PostPublishPanel": function() { return /* reexport */ post_publish_panel; },
"PostSavedState": function() { return /* reexport */ PostSavedState; },
"PostSchedule": function() { return /* reexport */ PostSchedule; },
"PostScheduleCheck": function() { return /* reexport */ post_schedule_check; },
"PostScheduleLabel": function() { return /* reexport */ PostScheduleLabel; },
"PostSlug": function() { return /* reexport */ post_slug; },
"PostSlugCheck": function() { return /* reexport */ PostSlugCheck; },
"PostSticky": function() { return /* reexport */ post_sticky; },
"PostStickyCheck": function() { return /* reexport */ post_sticky_check; },
"PostSwitchToDraftButton": function() { return /* reexport */ post_switch_to_draft_button; },
"PostTaxonomies": function() { return /* reexport */ post_taxonomies; },
"PostTaxonomiesCheck": function() { return /* reexport */ post_taxonomies_check; },
"PostTaxonomiesFlatTermSelector": function() { return /* reexport */ FlatTermSelector; },
"PostTaxonomiesHierarchicalTermSelector": function() { return /* reexport */ HierarchicalTermSelector; },
"PostTextEditor": function() { return /* reexport */ PostTextEditor; },
"PostTitle": function() { return /* reexport */ post_title; },
"PostTrash": function() { return /* reexport */ PostTrash; },
"PostTrashCheck": function() { return /* reexport */ post_trash_check; },
"PostTypeSupportCheck": function() { return /* reexport */ post_type_support_check; },
"PostURL": function() { return /* reexport */ PostURL; },
"PostURLCheck": function() { return /* reexport */ PostURLCheck; },
"PostURLLabel": function() { return /* reexport */ PostURLLabel; },
"PostVisibility": function() { return /* reexport */ PostVisibility; },
"PostVisibilityCheck": function() { return /* reexport */ post_visibility_check; },
"PostVisibilityLabel": function() { return /* reexport */ PostVisibilityLabel; },
"RichText": function() { return /* reexport */ RichText; },
"RichTextShortcut": function() { return /* reexport */ RichTextShortcut; },
"RichTextToolbarButton": function() { return /* reexport */ RichTextToolbarButton; },
"ServerSideRender": function() { return /* reexport */ (external_wp_serverSideRender_default()); },
"SkipToSelectedBlock": function() { return /* reexport */ SkipToSelectedBlock; },
"TableOfContents": function() { return /* reexport */ table_of_contents; },
"TextEditorGlobalKeyboardShortcuts": function() { return /* reexport */ TextEditorGlobalKeyboardShortcuts; },
"ThemeSupportCheck": function() { return /* reexport */ theme_support_check; },
"TimeToRead": function() { return /* reexport */ TimeToRead; },
"URLInput": function() { return /* reexport */ URLInput; },
"URLInputButton": function() { return /* reexport */ URLInputButton; },
"URLPopover": function() { return /* reexport */ URLPopover; },
"UnsavedChangesWarning": function() { return /* reexport */ UnsavedChangesWarning; },
"VisualEditorGlobalKeyboardShortcuts": function() { return /* reexport */ visual_editor_shortcuts; },
"Warning": function() { return /* reexport */ Warning; },
"WordCount": function() { return /* reexport */ WordCount; },
"WritingFlow": function() { return /* reexport */ WritingFlow; },
"__unstableRichTextInputEvent": function() { return /* reexport */ __unstableRichTextInputEvent; },
"cleanForSlug": function() { return /* reexport */ cleanForSlug; },
"createCustomColorsHOC": function() { return /* reexport */ createCustomColorsHOC; },
"getColorClassName": function() { return /* reexport */ getColorClassName; },
"getColorObjectByAttributeValues": function() { return /* reexport */ getColorObjectByAttributeValues; },
"getColorObjectByColorValue": function() { return /* reexport */ getColorObjectByColorValue; },
"getFontSize": function() { return /* reexport */ getFontSize; },
"getFontSizeClass": function() { return /* reexport */ getFontSizeClass; },
"getTemplatePartIcon": function() { return /* reexport */ getTemplatePartIcon; },
"mediaUpload": function() { return /* reexport */ mediaUpload; },
"privateApis": function() { return /* reexport */ privateApis; },
"store": function() { return /* reexport */ store_store; },
"storeConfig": function() { return /* reexport */ storeConfig; },
"transformStyles": function() { return /* reexport */ external_wp_blockEditor_namespaceObject.transformStyles; },
"usePostScheduleLabel": function() { return /* reexport */ usePostScheduleLabel; },
"usePostURLLabel": function() { return /* reexport */ usePostURLLabel; },
"usePostVisibilityLabel": function() { return /* reexport */ usePostVisibilityLabel; },
"userAutocompleter": function() { return /* reexport */ user; },
"withColorContext": function() { return /* reexport */ withColorContext; },
"withColors": function() { return /* reexport */ withColors; },
"withFontSizes": function() { return /* reexport */ withFontSizes; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/editor/build-module/store/selectors.js
var selectors_namespaceObject = {};
__webpack_require__.r(selectors_namespaceObject);
__webpack_require__.d(selectors_namespaceObject, {
"__experimentalGetDefaultTemplatePartAreas": function() { return __experimentalGetDefaultTemplatePartAreas; },
"__experimentalGetDefaultTemplateType": function() { return __experimentalGetDefaultTemplateType; },
"__experimentalGetDefaultTemplateTypes": function() { return __experimentalGetDefaultTemplateTypes; },
"__experimentalGetTemplateInfo": function() { return __experimentalGetTemplateInfo; },
"__unstableIsEditorReady": function() { return __unstableIsEditorReady; },
"canInsertBlockType": function() { return canInsertBlockType; },
"canUserUseUnfilteredHTML": function() { return canUserUseUnfilteredHTML; },
"didPostSaveRequestFail": function() { return didPostSaveRequestFail; },
"didPostSaveRequestSucceed": function() { return didPostSaveRequestSucceed; },
"getActivePostLock": function() { return getActivePostLock; },
"getAdjacentBlockClientId": function() { return getAdjacentBlockClientId; },
"getAutosaveAttribute": function() { return getAutosaveAttribute; },
"getBlock": function() { return getBlock; },
"getBlockAttributes": function() { return getBlockAttributes; },
"getBlockCount": function() { return getBlockCount; },
"getBlockHierarchyRootClientId": function() { return getBlockHierarchyRootClientId; },
"getBlockIndex": function() { return getBlockIndex; },
"getBlockInsertionPoint": function() { return getBlockInsertionPoint; },
"getBlockListSettings": function() { return getBlockListSettings; },
"getBlockMode": function() { return getBlockMode; },
"getBlockName": function() { return getBlockName; },
"getBlockOrder": function() { return getBlockOrder; },
"getBlockRootClientId": function() { return getBlockRootClientId; },
"getBlockSelectionEnd": function() { return getBlockSelectionEnd; },
"getBlockSelectionStart": function() { return getBlockSelectionStart; },
"getBlocks": function() { return getBlocks; },
"getBlocksByClientId": function() { return getBlocksByClientId; },
"getClientIdsOfDescendants": function() { return getClientIdsOfDescendants; },
"getClientIdsWithDescendants": function() { return getClientIdsWithDescendants; },
"getCurrentPost": function() { return getCurrentPost; },
"getCurrentPostAttribute": function() { return getCurrentPostAttribute; },
"getCurrentPostId": function() { return getCurrentPostId; },
"getCurrentPostLastRevisionId": function() { return getCurrentPostLastRevisionId; },
"getCurrentPostRevisionsCount": function() { return getCurrentPostRevisionsCount; },
"getCurrentPostType": function() { return getCurrentPostType; },
"getEditedPostAttribute": function() { return getEditedPostAttribute; },
"getEditedPostContent": function() { return getEditedPostContent; },
"getEditedPostPreviewLink": function() { return getEditedPostPreviewLink; },
"getEditedPostSlug": function() { return getEditedPostSlug; },
"getEditedPostVisibility": function() { return getEditedPostVisibility; },
"getEditorBlocks": function() { return getEditorBlocks; },
"getEditorSelection": function() { return getEditorSelection; },
"getEditorSelectionEnd": function() { return getEditorSelectionEnd; },
"getEditorSelectionStart": function() { return getEditorSelectionStart; },
"getEditorSettings": function() { return getEditorSettings; },
"getFirstMultiSelectedBlockClientId": function() { return getFirstMultiSelectedBlockClientId; },
"getGlobalBlockCount": function() { return getGlobalBlockCount; },
"getInserterItems": function() { return getInserterItems; },
"getLastMultiSelectedBlockClientId": function() { return getLastMultiSelectedBlockClientId; },
"getMultiSelectedBlockClientIds": function() { return getMultiSelectedBlockClientIds; },
"getMultiSelectedBlocks": function() { return getMultiSelectedBlocks; },
"getMultiSelectedBlocksEndClientId": function() { return getMultiSelectedBlocksEndClientId; },
"getMultiSelectedBlocksStartClientId": function() { return getMultiSelectedBlocksStartClientId; },
"getNextBlockClientId": function() { return getNextBlockClientId; },
"getPermalink": function() { return getPermalink; },
"getPermalinkParts": function() { return getPermalinkParts; },
"getPostEdits": function() { return getPostEdits; },
"getPostLockUser": function() { return getPostLockUser; },
"getPostTypeLabel": function() { return getPostTypeLabel; },
"getPreviousBlockClientId": function() { return getPreviousBlockClientId; },
"getSelectedBlock": function() { return getSelectedBlock; },
"getSelectedBlockClientId": function() { return getSelectedBlockClientId; },
"getSelectedBlockCount": function() { return getSelectedBlockCount; },
"getSelectedBlocksInitialCaretPosition": function() { return getSelectedBlocksInitialCaretPosition; },
"getStateBeforeOptimisticTransaction": function() { return getStateBeforeOptimisticTransaction; },
"getSuggestedPostFormat": function() { return getSuggestedPostFormat; },
"getTemplate": function() { return getTemplate; },
"getTemplateLock": function() { return getTemplateLock; },
"hasChangedContent": function() { return hasChangedContent; },
"hasEditorRedo": function() { return hasEditorRedo; },
"hasEditorUndo": function() { return hasEditorUndo; },
"hasInserterItems": function() { return hasInserterItems; },
"hasMultiSelection": function() { return hasMultiSelection; },
"hasNonPostEntityChanges": function() { return hasNonPostEntityChanges; },
"hasSelectedBlock": function() { return hasSelectedBlock; },
"hasSelectedInnerBlock": function() { return hasSelectedInnerBlock; },
"inSomeHistory": function() { return inSomeHistory; },
"isAncestorMultiSelected": function() { return isAncestorMultiSelected; },
"isAutosavingPost": function() { return isAutosavingPost; },
"isBlockInsertionPointVisible": function() { return isBlockInsertionPointVisible; },
"isBlockMultiSelected": function() { return isBlockMultiSelected; },
"isBlockSelected": function() { return isBlockSelected; },
"isBlockValid": function() { return isBlockValid; },
"isBlockWithinSelection": function() { return isBlockWithinSelection; },
"isCaretWithinFormattedText": function() { return isCaretWithinFormattedText; },
"isCleanNewPost": function() { return isCleanNewPost; },
"isCurrentPostPending": function() { return isCurrentPostPending; },
"isCurrentPostPublished": function() { return isCurrentPostPublished; },
"isCurrentPostScheduled": function() { return isCurrentPostScheduled; },
"isDeletingPost": function() { return isDeletingPost; },
"isEditedPostAutosaveable": function() { return isEditedPostAutosaveable; },
"isEditedPostBeingScheduled": function() { return isEditedPostBeingScheduled; },
"isEditedPostDateFloating": function() { return isEditedPostDateFloating; },
"isEditedPostDirty": function() { return isEditedPostDirty; },
"isEditedPostEmpty": function() { return isEditedPostEmpty; },
"isEditedPostNew": function() { return isEditedPostNew; },
"isEditedPostPublishable": function() { return isEditedPostPublishable; },
"isEditedPostSaveable": function() { return isEditedPostSaveable; },
"isFirstMultiSelectedBlock": function() { return isFirstMultiSelectedBlock; },
"isMultiSelecting": function() { return isMultiSelecting; },
"isPermalinkEditable": function() { return isPermalinkEditable; },
"isPostAutosavingLocked": function() { return isPostAutosavingLocked; },
"isPostLockTakeover": function() { return isPostLockTakeover; },
"isPostLocked": function() { return isPostLocked; },
"isPostSavingLocked": function() { return isPostSavingLocked; },
"isPreviewingPost": function() { return isPreviewingPost; },
"isPublishSidebarEnabled": function() { return isPublishSidebarEnabled; },
"isPublishingPost": function() { return isPublishingPost; },
"isSavingNonPostEntityChanges": function() { return isSavingNonPostEntityChanges; },
"isSavingPost": function() { return isSavingPost; },
"isSelectionEnabled": function() { return isSelectionEnabled; },
"isTyping": function() { return isTyping; },
"isValidTemplate": function() { return isValidTemplate; }
});
// NAMESPACE OBJECT: ./node_modules/@wordpress/editor/build-module/store/actions.js
var actions_namespaceObject = {};
__webpack_require__.r(actions_namespaceObject);
__webpack_require__.d(actions_namespaceObject, {
"__experimentalTearDownEditor": function() { return __experimentalTearDownEditor; },
"autosave": function() { return autosave; },
"clearSelectedBlock": function() { return clearSelectedBlock; },
"createUndoLevel": function() { return createUndoLevel; },
"disablePublishSidebar": function() { return disablePublishSidebar; },
"editPost": function() { return editPost; },
"enablePublishSidebar": function() { return enablePublishSidebar; },
"enterFormattedText": function() { return enterFormattedText; },
"exitFormattedText": function() { return exitFormattedText; },
"hideInsertionPoint": function() { return hideInsertionPoint; },
"insertBlock": function() { return insertBlock; },
"insertBlocks": function() { return insertBlocks; },
"insertDefaultBlock": function() { return insertDefaultBlock; },
"lockPostAutosaving": function() { return lockPostAutosaving; },
"lockPostSaving": function() { return lockPostSaving; },
"mergeBlocks": function() { return mergeBlocks; },
"moveBlockToPosition": function() { return moveBlockToPosition; },
"moveBlocksDown": function() { return moveBlocksDown; },
"moveBlocksUp": function() { return moveBlocksUp; },
"multiSelect": function() { return multiSelect; },
"receiveBlocks": function() { return receiveBlocks; },
"redo": function() { return redo; },
"refreshPost": function() { return refreshPost; },
"removeBlock": function() { return removeBlock; },
"removeBlocks": function() { return removeBlocks; },
"replaceBlock": function() { return replaceBlock; },
"replaceBlocks": function() { return replaceBlocks; },
"resetBlocks": function() { return resetBlocks; },
"resetEditorBlocks": function() { return resetEditorBlocks; },
"resetPost": function() { return resetPost; },
"savePost": function() { return savePost; },
"selectBlock": function() { return selectBlock; },
"setTemplateValidity": function() { return setTemplateValidity; },
"setupEditor": function() { return setupEditor; },
"setupEditorState": function() { return setupEditorState; },
"showInsertionPoint": function() { return showInsertionPoint; },
"startMultiSelect": function() { return startMultiSelect; },
"startTyping": function() { return startTyping; },
"stopMultiSelect": function() { return stopMultiSelect; },
"stopTyping": function() { return stopTyping; },
"synchronizeTemplate": function() { return synchronizeTemplate; },
"toggleBlockMode": function() { return toggleBlockMode; },
"toggleSelection": function() { return toggleSelection; },
"trashPost": function() { return trashPost; },
"undo": function() { return undo; },
"unlockPostAutosaving": function() { return unlockPostAutosaving; },
"unlockPostSaving": function() { return unlockPostSaving; },
"updateBlock": function() { return updateBlock; },
"updateBlockAttributes": function() { return updateBlockAttributes; },
"updateBlockListSettings": function() { return updateBlockListSettings; },
"updateEditorSettings": function() { return updateEditorSettings; },
"updatePost": function() { return updatePost; },
"updatePostLock": function() { return updatePostLock; }
});
;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/extends.js
function _extends() {
return _extends = Object.assign ? Object.assign.bind() : function (n) {
for (var e = 1; e < arguments.length; e++) {
var t = arguments[e];
for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
}
return n;
}, _extends.apply(null, arguments);
}
;// CONCATENATED MODULE: external ["wp","element"]
var external_wp_element_namespaceObject = window["wp"]["element"];
;// CONCATENATED MODULE: external "lodash"
var external_lodash_namespaceObject = window["lodash"];
;// CONCATENATED MODULE: external ["wp","blocks"]
var external_wp_blocks_namespaceObject = window["wp"]["blocks"];
;// 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: external ["wp","compose"]
var external_wp_compose_namespaceObject = window["wp"]["compose"];
;// CONCATENATED MODULE: external ["wp","hooks"]
var external_wp_hooks_namespaceObject = window["wp"]["hooks"];
;// CONCATENATED MODULE: external ["wp","blockEditor"]
var external_wp_blockEditor_namespaceObject = window["wp"]["blockEditor"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/store/defaults.js
/**
* WordPress dependencies
*/
/**
* The default post editor settings.
*
* @property {boolean|Array} allowedBlockTypes Allowed block types
* @property {boolean} richEditingEnabled Whether rich editing is enabled or not
* @property {boolean} codeEditingEnabled Whether code editing is enabled or not
* @property {boolean} enableCustomFields Whether the WordPress custom fields are enabled or not.
* true = the user has opted to show the Custom Fields panel at the bottom of the editor.
* false = the user has opted to hide the Custom Fields panel at the bottom of the editor.
* undefined = the current environment does not support Custom Fields, so the option toggle in Preferences -> Panels to enable the Custom Fields panel is not displayed.
* @property {number} autosaveInterval How often in seconds the post will be auto-saved via the REST API.
* @property {number} localAutosaveInterval How often in seconds the post will be backed up to sessionStorage.
* @property {Array?} availableTemplates The available post templates
* @property {boolean} disablePostFormats Whether or not the post formats are disabled
* @property {Array?} allowedMimeTypes List of allowed mime types and file extensions
* @property {number} maxUploadFileSize Maximum upload file size
* @property {boolean} supportsLayout Whether the editor supports layouts.
*/
const EDITOR_SETTINGS_DEFAULTS = { ...external_wp_blockEditor_namespaceObject.SETTINGS_DEFAULTS,
richEditingEnabled: true,
codeEditingEnabled: true,
enableCustomFields: undefined
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/store/reducer.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Returns a post attribute value, flattening nested rendered content using its
* raw value in place of its original object form.
*
* @param {*} value Original value.
*
* @return {*} Raw value.
*/
function getPostRawValue(value) {
if (value && 'object' === typeof value && 'raw' in value) {
return value.raw;
}
return value;
}
/**
* Returns true if the two object arguments have the same keys, or false
* otherwise.
*
* @param {Object} a First object.
* @param {Object} b Second object.
*
* @return {boolean} Whether the two objects have the same keys.
*/
function hasSameKeys(a, b) {
const keysA = Object.keys(a).sort();
const keysB = Object.keys(b).sort();
return keysA.length === keysB.length && keysA.every((key, index) => keysB[index] === key);
}
/**
* Returns true if, given the currently dispatching action and the previously
* dispatched action, the two actions are editing the same post property, or
* false otherwise.
*
* @param {Object} action Currently dispatching action.
* @param {Object} previousAction Previously dispatched action.
*
* @return {boolean} Whether actions are updating the same post property.
*/
function isUpdatingSamePostProperty(action, previousAction) {
return action.type === 'EDIT_POST' && hasSameKeys(action.edits, previousAction.edits);
}
/**
* Returns true if, given the currently dispatching action and the previously
* dispatched action, the two actions are modifying the same property such that
* undo history should be batched.
*
* @param {Object} action Currently dispatching action.
* @param {Object} previousAction Previously dispatched action.
*
* @return {boolean} Whether to overwrite present state.
*/
function shouldOverwriteState(action, previousAction) {
if (action.type === 'RESET_EDITOR_BLOCKS') {
return !action.shouldCreateUndoLevel;
}
if (!previousAction || action.type !== previousAction.type) {
return false;
}
return isUpdatingSamePostProperty(action, previousAction);
}
function postId() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'SETUP_EDITOR_STATE':
return action.post.id;
}
return state;
}
function postType() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'SETUP_EDITOR_STATE':
return action.post.type;
}
return state;
}
/**
* Reducer returning whether the post blocks match the defined template or not.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {boolean} Updated state.
*/
function template() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
isValid: true
};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'SET_TEMPLATE_VALIDITY':
return { ...state,
isValid: action.isValid
};
}
return state;
}
/**
* Reducer returning current network request state (whether a request to
* the WP REST API is in progress, successful, or failed).
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
function saving() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'REQUEST_POST_UPDATE_START':
case 'REQUEST_POST_UPDATE_FINISH':
return {
pending: action.type === 'REQUEST_POST_UPDATE_START',
options: action.options || {}
};
}
return state;
}
/**
* Reducer returning deleting post request state.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
function deleting() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'REQUEST_POST_DELETE_START':
case 'REQUEST_POST_DELETE_FINISH':
return {
pending: action.type === 'REQUEST_POST_DELETE_START'
};
}
return state;
}
/**
* Post Lock State.
*
* @typedef {Object} PostLockState
*
* @property {boolean} isLocked Whether the post is locked.
* @property {?boolean} isTakeover Whether the post editing has been taken over.
* @property {?boolean} activePostLock Active post lock value.
* @property {?Object} user User that took over the post.
*/
/**
* Reducer returning the post lock status.
*
* @param {PostLockState} state Current state.
* @param {Object} action Dispatched action.
*
* @return {PostLockState} Updated state.
*/
function postLock() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
isLocked: false
};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'UPDATE_POST_LOCK':
return action.lock;
}
return state;
}
/**
* Post saving lock.
*
* When post saving is locked, the post cannot be published or updated.
*
* @param {PostLockState} state Current state.
* @param {Object} action Dispatched action.
*
* @return {PostLockState} Updated state.
*/
function postSavingLock() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'LOCK_POST_SAVING':
return { ...state,
[action.lockName]: true
};
case 'UNLOCK_POST_SAVING':
{
const {
[action.lockName]: removedLockName,
...restState
} = state;
return restState;
}
}
return state;
}
/**
* Post autosaving lock.
*
* When post autosaving is locked, the post will not autosave.
*
* @param {PostLockState} state Current state.
* @param {Object} action Dispatched action.
*
* @return {PostLockState} Updated state.
*/
function postAutosavingLock() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'LOCK_POST_AUTOSAVING':
return { ...state,
[action.lockName]: true
};
case 'UNLOCK_POST_AUTOSAVING':
{
const {
[action.lockName]: removedLockName,
...restState
} = state;
return restState;
}
}
return state;
}
/**
* Reducer returning whether the editor is ready to be rendered.
* The editor is considered ready to be rendered once
* the post object is loaded properly and the initial blocks parsed.
*
* @param {boolean} state
* @param {Object} action
*
* @return {boolean} Updated state.
*/
function isReady() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'SETUP_EDITOR_STATE':
return true;
case 'TEAR_DOWN_EDITOR':
return false;
}
return state;
}
/**
* Reducer returning the post editor setting.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {Object} Updated state.
*/
function editorSettings() {
let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : EDITOR_SETTINGS_DEFAULTS;
let action = arguments.length > 1 ? arguments[1] : undefined;
switch (action.type) {
case 'UPDATE_EDITOR_SETTINGS':
return { ...state,
...action.settings
};
}
return state;
}
/* harmony default export */ var reducer = ((0,external_wp_data_namespaceObject.combineReducers)({
postId,
postType,
saving,
deleting,
postLock,
template,
postSavingLock,
isReady,
editorSettings,
postAutosavingLock
}));
;// CONCATENATED MODULE: ./node_modules/rememo/rememo.js
/** @typedef {(...args: any[]) => *[]} GetDependants */
/** @typedef {() => void} Clear */
/**
* @typedef {{
* getDependants: GetDependants,
* clear: Clear
* }} EnhancedSelector
*/
/**
* Internal cache entry.
*
* @typedef CacheNode
*
* @property {?CacheNode|undefined} [prev] Previous node.
* @property {?CacheNode|undefined} [next] Next node.
* @property {*[]} args Function arguments for cache entry.
* @property {*} val Function result.
*/
/**
* @typedef Cache
*
* @property {Clear} clear Function to clear cache.
* @property {boolean} [isUniqueByDependants] Whether dependants are valid in
* considering cache uniqueness. A cache is unique if dependents are all arrays
* or objects.
* @property {CacheNode?} [head] Cache head.
* @property {*[]} [lastDependants] Dependants from previous invocation.
*/
/**
* Arbitrary value used as key for referencing cache object in WeakMap tree.
*
* @type {{}}
*/
var LEAF_KEY = {};
/**
* Returns the first argument as the sole entry in an array.
*
* @template T
*
* @param {T} value Value to return.
*
* @return {[T]} Value returned as entry in array.
*/
function arrayOf(value) {
return [value];
}
/**
* Returns true if the value passed is object-like, or false otherwise. A value
* is object-like if it can support property assignment, e.g. object or array.
*
* @param {*} value Value to test.
*
* @return {boolean} Whether value is object-like.
*/
function isObjectLike(value) {
return !!value && 'object' === typeof value;
}
/**
* Creates and returns a new cache object.
*
* @return {Cache} Cache object.
*/
function createCache() {
/** @type {Cache} */
var cache = {
clear: function () {
cache.head = null;
},
};
return cache;
}
/**
* Returns true if entries within the two arrays are strictly equal by
* reference from a starting index.
*
* @param {*[]} a First array.
* @param {*[]} b Second array.
* @param {number} fromIndex Index from which to start comparison.
*
* @return {boolean} Whether arrays are shallowly equal.
*/
function isShallowEqual(a, b, fromIndex) {
var i;
if (a.length !== b.length) {
return false;
}
for (i = fromIndex; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
/**
* Returns a memoized selector function. The getDependants function argument is
* called before the memoized selector and is expected to return an immutable
* reference or array of references on which the selector depends for computing
* its own return value. The memoize cache is preserved only as long as those
* dependant references remain the same. If getDependants returns a different
* reference(s), the cache is cleared and the selector value regenerated.
*
* @template {(...args: *[]) => *} S
*
* @param {S} selector Selector function.
* @param {GetDependants=} getDependants Dependant getter returning an array of
* references used in cache bust consideration.
*/
/* harmony default export */ function rememo(selector, getDependants) {
/** @type {WeakMap<*,*>} */
var rootCache;
/** @type {GetDependants} */
var normalizedGetDependants = getDependants ? getDependants : arrayOf;
/**
* Returns the cache for a given dependants array. When possible, a WeakMap
* will be used to create a unique cache for each set of dependants. This
* is feasible due to the nature of WeakMap in allowing garbage collection
* to occur on entries where the key object is no longer referenced. Since
* WeakMap requires the key to be an object, this is only possible when the
* dependant is object-like. The root cache is created as a hierarchy where
* each top-level key is the first entry in a dependants set, the value a
* WeakMap where each key is the next dependant, and so on. This continues
* so long as the dependants are object-like. If no dependants are object-
* like, then the cache is shared across all invocations.
*
* @see isObjectLike
*
* @param {*[]} dependants Selector dependants.
*
* @return {Cache} Cache object.
*/
function getCache(dependants) {
var caches = rootCache,
isUniqueByDependants = true,
i,
dependant,
map,
cache;
for (i = 0; i < dependants.length; i++) {
dependant = dependants[i];
// Can only compose WeakMap from object-like key.
if (!isObjectLike(dependant)) {
isUniqueByDependants = false;
break;
}
// Does current segment of cache already have a WeakMap?
if (caches.has(dependant)) {
// Traverse into nested WeakMap.
caches = caches.get(dependant);
} else {
// Create, set, and traverse into a new one.
map = new WeakMap();
caches.set(dependant, map);
caches = map;
}
}
// We use an arbitrary (but consistent) object as key for the last item
// in the WeakMap to serve as our running cache.
if (!caches.has(LEAF_KEY)) {
cache = createCache();
cache.isUniqueByDependants = isUniqueByDependants;
caches.set(LEAF_KEY, cache);
}
return caches.get(LEAF_KEY);
}
/**
* Resets root memoization cache.
*/
function clear() {
rootCache = new WeakMap();
}
/* eslint-disable jsdoc/check-param-names */
/**
* The augmented selector call, considering first whether dependants have
* changed before passing it to underlying memoize function.
*
* @param {*} source Source object for derivation.
* @param {...*} extraArgs Additional arguments to pass to selector.
*
* @return {*} Selector result.
*/
/* eslint-enable jsdoc/check-param-names */
function callSelector(/* source, ...extraArgs */) {
var len = arguments.length,
cache,
node,
i,
args,
dependants;
// Create copy of arguments (avoid leaking deoptimization).
args = new Array(len);
for (i = 0; i < len; i++) {
args[i] = arguments[i];
}
dependants = normalizedGetDependants.apply(null, args);
cache = getCache(dependants);
// If not guaranteed uniqueness by dependants (primitive type), shallow
// compare against last dependants and, if references have changed,
// destroy cache to recalculate result.
if (!cache.isUniqueByDependants) {
if (
cache.lastDependants &&
!isShallowEqual(dependants, cache.lastDependants, 0)
) {
cache.clear();
}
cache.lastDependants = dependants;
}
node = cache.head;
while (node) {
// Check whether node arguments match arguments
if (!isShallowEqual(node.args, args, 1)) {
node = node.next;
continue;
}
// At this point we can assume we've found a match
// Surface matched node to head if not already
if (node !== cache.head) {
// Adjust siblings to point to each other.
/** @type {CacheNode} */ (node.prev).next = node.next;
if (node.next) {
node.next.prev = node.prev;
}
node.next = cache.head;
node.prev = null;
/** @type {CacheNode} */ (cache.head).prev = node;
cache.head = node;
}
// Return immediately
return node.val;
}
// No cached value found. Continue to insertion phase:
node = /** @type {CacheNode} */ ({
// Generate the result from original function
val: selector.apply(null, args),
});
// Avoid including the source object in the cache.
args[0] = null;
node.args = args;
// Don't need to check whether node is already head, since it would
// have been returned above already if it was
// Shift existing head down list
if (cache.head) {
cache.head.prev = node;
node.next = cache.head;
}
cache.head = node;
return node.val;
}
callSelector.getDependants = normalizedGetDependants;
callSelector.clear = clear;
clear();
return /** @type {S & EnhancedSelector} */ (callSelector);
}
;// CONCATENATED MODULE: external ["wp","date"]
var external_wp_date_namespaceObject = window["wp"]["date"];
;// CONCATENATED MODULE: external ["wp","url"]
var external_wp_url_namespaceObject = window["wp"]["url"];
;// CONCATENATED MODULE: external ["wp","deprecated"]
var external_wp_deprecated_namespaceObject = window["wp"]["deprecated"];
var external_wp_deprecated_default = /*#__PURE__*/__webpack_require__.n(external_wp_deprecated_namespaceObject);
;// CONCATENATED MODULE: external ["wp","primitives"]
var external_wp_primitives_namespaceObject = window["wp"]["primitives"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/layout.js
/**
* WordPress dependencies
*/
const layout = (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: "M18 5.5H6a.5.5 0 00-.5.5v3h13V6a.5.5 0 00-.5-.5zm.5 5H10v8h8a.5.5 0 00.5-.5v-7.5zm-10 0h-3V18a.5.5 0 00.5.5h2.5v-8zM6 4h12a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2z"
}));
/* harmony default export */ var library_layout = (layout);
;// CONCATENATED MODULE: external ["wp","preferences"]
var external_wp_preferences_namespaceObject = window["wp"]["preferences"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/store/constants.js
/**
* Set of post properties for which edits should assume a merging behavior,
* assuming an object value.
*
* @type {Set}
*/
const EDIT_MERGE_PROPERTIES = new Set(['meta']);
/**
* Constant for the store module (or reducer) key.
*
* @type {string}
*/
const STORE_NAME = 'core/editor';
const SAVE_POST_NOTICE_ID = 'SAVE_POST_NOTICE_ID';
const TRASH_POST_NOTICE_ID = 'TRASH_POST_NOTICE_ID';
const PERMALINK_POSTNAME_REGEX = /%(?:postname|pagename)%/;
const ONE_MINUTE_IN_MS = 60 * 1000;
const AUTOSAVE_PROPERTIES = ['title', 'excerpt', 'content'];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/header.js
/**
* WordPress dependencies
*/
const header = (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: "M18.5 10.5H10v8h8a.5.5 0 00.5-.5v-7.5zm-10 0h-3V18a.5.5 0 00.5.5h2.5v-8zM6 4h12a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2z"
}));
/* harmony default export */ var library_header = (header);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/footer.js
/**
* WordPress dependencies
*/
const footer = (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, {
fillRule: "evenodd",
d: "M18 5.5h-8v8h8.5V6a.5.5 0 00-.5-.5zm-9.5 8h-3V6a.5.5 0 01.5-.5h2.5v8zM6 4h12a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2z"
}));
/* harmony default export */ var library_footer = (footer);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/sidebar.js
/**
* WordPress dependencies
*/
const sidebar = (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: "M18 5.5H6a.5.5 0 00-.5.5v3h13V6a.5.5 0 00-.5-.5zm.5 5H10v8h8a.5.5 0 00.5-.5v-7.5zM6 4h12a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2z"
}));
/* harmony default export */ var library_sidebar = (sidebar);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/symbol-filled.js
/**
* WordPress dependencies
*/
const symbolFilled = (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-17.6 1L10 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 symbol_filled = (symbolFilled);
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/utils/get-template-part-icon.js
/**
* WordPress dependencies
*/
/**
* Helper function to retrieve the corresponding icon by name.
*
* @param {string} iconName The name of the icon.
*
* @return {Object} The corresponding icon.
*/
function getTemplatePartIcon(iconName) {
if ('header' === iconName) {
return library_header;
} else if ('footer' === iconName) {
return library_footer;
} else if ('sidebar' === iconName) {
return library_sidebar;
}
return symbol_filled;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/store/selectors.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Shared reference to an empty object for cases where it is important to avoid
* returning a new object reference on every invocation, as in a connected or
* other pure component which performs `shouldComponentUpdate` check on props.
* This should be used as a last resort, since the normalized data should be
* maintained by the reducer result in state.
*/
const EMPTY_OBJECT = {};
/**
* 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
* other pure component which performs `shouldComponentUpdate` check on props.
* This should be used as a last resort, since the normalized data should be
* maintained by the reducer result in state.
*/
const EMPTY_ARRAY = [];
/**
* Returns true if any past editor history snapshots exist, or false otherwise.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether undo history exists.
*/
const hasEditorUndo = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => () => {
return select(external_wp_coreData_namespaceObject.store).hasUndo();
});
/**
* Returns true if any future editor history snapshots exist, or false
* otherwise.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether redo history exists.
*/
const hasEditorRedo = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => () => {
return select(external_wp_coreData_namespaceObject.store).hasRedo();
});
/**
* Returns true if the currently edited post is yet to be saved, or false if
* the post has been saved.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the post is new.
*/
function isEditedPostNew(state) {
return getCurrentPost(state).status === 'auto-draft';
}
/**
* Returns true if content includes unsaved changes, or false otherwise.
*
* @param {Object} state Editor state.
*
* @return {boolean} Whether content includes unsaved changes.
*/
function hasChangedContent(state) {
const edits = getPostEdits(state);
return 'content' in edits;
}
/**
* Returns true if there are unsaved values for the current edit session, or
* false if the editing state matches the saved or new post.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether unsaved values exist.
*/
const isEditedPostDirty = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => state => {
// Edits should contain only fields which differ from the saved post (reset
// at initial load and save complete). Thus, a non-empty edits state can be
// inferred to contain unsaved values.
const postType = getCurrentPostType(state);
const postId = getCurrentPostId(state);
if (select(external_wp_coreData_namespaceObject.store).hasEditsForEntityRecord('postType', postType, postId)) {
return true;
}
return false;
});
/**
* Returns true if there are unsaved edits for entities other than
* the editor's post, and false otherwise.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether there are edits or not.
*/
const hasNonPostEntityChanges = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => state => {
const dirtyEntityRecords = select(external_wp_coreData_namespaceObject.store).__experimentalGetDirtyEntityRecords();
const {
type,
id
} = getCurrentPost(state);
return dirtyEntityRecords.some(entityRecord => entityRecord.kind !== 'postType' || entityRecord.name !== type || entityRecord.key !== id);
});
/**
* Returns true if there are no unsaved values for the current edit session and
* if the currently edited post is new (has never been saved before).
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether new post and unsaved values exist.
*/
function isCleanNewPost(state) {
return !isEditedPostDirty(state) && isEditedPostNew(state);
}
/**
* Returns the post currently being edited in its last known saved state, not
* including unsaved edits. Returns an object containing relevant default post
* values if the post has not yet been saved.
*
* @param {Object} state Global application state.
*
* @return {Object} Post object.
*/
const getCurrentPost = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => state => {
const postId = getCurrentPostId(state);
const postType = getCurrentPostType(state);
const post = select(external_wp_coreData_namespaceObject.store).getRawEntityRecord('postType', postType, postId);
if (post) {
return post;
} // This exists for compatibility with the previous selector behavior
// which would guarantee an object return based on the editor reducer's
// default empty object state.
return EMPTY_OBJECT;
});
/**
* Returns the post type of the post currently being edited.
*
* @param {Object} state Global application state.
*
* @return {string} Post type.
*/
function getCurrentPostType(state) {
return state.postType;
}
/**
* Returns the ID of the post currently being edited, or null if the post has
* not yet been saved.
*
* @param {Object} state Global application state.
*
* @return {?number} ID of current post.
*/
function getCurrentPostId(state) {
return state.postId;
}
/**
* Returns the number of revisions of the post currently being edited.
*
* @param {Object} state Global application state.
*
* @return {number} Number of revisions.
*/
function getCurrentPostRevisionsCount(state) {
var _getCurrentPost$_link, _getCurrentPost$_link2, _getCurrentPost$_link3, _getCurrentPost$_link4;
return (_getCurrentPost$_link = (_getCurrentPost$_link2 = getCurrentPost(state)._links) === null || _getCurrentPost$_link2 === void 0 ? void 0 : (_getCurrentPost$_link3 = _getCurrentPost$_link2['version-history']) === null || _getCurrentPost$_link3 === void 0 ? void 0 : (_getCurrentPost$_link4 = _getCurrentPost$_link3[0]) === null || _getCurrentPost$_link4 === void 0 ? void 0 : _getCurrentPost$_link4.count) !== null && _getCurrentPost$_link !== void 0 ? _getCurrentPost$_link : 0;
}
/**
* Returns the last revision ID of the post currently being edited,
* or null if the post has no revisions.
*
* @param {Object} state Global application state.
*
* @return {?number} ID of the last revision.
*/
function getCurrentPostLastRevisionId(state) {
var _getCurrentPost$_link5, _getCurrentPost$_link6, _getCurrentPost$_link7, _getCurrentPost$_link8;
return (_getCurrentPost$_link5 = (_getCurrentPost$_link6 = getCurrentPost(state)._links) === null || _getCurrentPost$_link6 === void 0 ? void 0 : (_getCurrentPost$_link7 = _getCurrentPost$_link6['predecessor-version']) === null || _getCurrentPost$_link7 === void 0 ? void 0 : (_getCurrentPost$_link8 = _getCurrentPost$_link7[0]) === null || _getCurrentPost$_link8 === void 0 ? void 0 : _getCurrentPost$_link8.id) !== null && _getCurrentPost$_link5 !== void 0 ? _getCurrentPost$_link5 : null;
}
/**
* Returns any post values which have been changed in the editor but not yet
* been saved.
*
* @param {Object} state Global application state.
*
* @return {Object} Object of key value pairs comprising unsaved edits.
*/
const getPostEdits = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => state => {
const postType = getCurrentPostType(state);
const postId = getCurrentPostId(state);
return select(external_wp_coreData_namespaceObject.store).getEntityRecordEdits('postType', postType, postId) || EMPTY_OBJECT;
});
/**
* Returns an attribute value of the saved post.
*
* @param {Object} state Global application state.
* @param {string} attributeName Post attribute name.
*
* @return {*} Post attribute value.
*/
function getCurrentPostAttribute(state, attributeName) {
switch (attributeName) {
case 'type':
return getCurrentPostType(state);
case 'id':
return getCurrentPostId(state);
default:
const post = getCurrentPost(state);
if (!post.hasOwnProperty(attributeName)) {
break;
}
return getPostRawValue(post[attributeName]);
}
}
/**
* Returns a single attribute of the post being edited, preferring the unsaved
* edit if one exists, but merging with the attribute value for the last known
* saved state of the post (this is needed for some nested attributes like meta).
*
* @param {Object} state Global application state.
* @param {string} attributeName Post attribute name.
*
* @return {*} Post attribute value.
*/
const getNestedEditedPostProperty = (state, attributeName) => {
const edits = getPostEdits(state);
if (!edits.hasOwnProperty(attributeName)) {
return getCurrentPostAttribute(state, attributeName);
}
return { ...getCurrentPostAttribute(state, attributeName),
...edits[attributeName]
};
};
/**
* Returns a single attribute of the post being edited, preferring the unsaved
* edit if one exists, but falling back to the attribute for the last known
* saved state of the post.
*
* @param {Object} state Global application state.
* @param {string} attributeName Post attribute name.
*
* @return {*} Post attribute value.
*/
function getEditedPostAttribute(state, attributeName) {
// Special cases.
switch (attributeName) {
case 'content':
return getEditedPostContent(state);
} // Fall back to saved post value if not edited.
const edits = getPostEdits(state);
if (!edits.hasOwnProperty(attributeName)) {
return getCurrentPostAttribute(state, attributeName);
} // Merge properties are objects which contain only the patch edit in state,
// and thus must be merged with the current post attribute.
if (EDIT_MERGE_PROPERTIES.has(attributeName)) {
return getNestedEditedPostProperty(state, attributeName);
}
return edits[attributeName];
}
/**
* Returns an attribute value of the current autosave revision for a post, or
* null if there is no autosave for the post.
*
* @deprecated since 5.6. Callers should use the `getAutosave( postType, postId, userId )` selector
* from the '@wordpress/core-data' package and access properties on the returned
* autosave object using getPostRawValue.
*
* @param {Object} state Global application state.
* @param {string} attributeName Autosave attribute name.
*
* @return {*} Autosave attribute value.
*/
const getAutosaveAttribute = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (state, attributeName) => {
var _select$getCurrentUse;
if (!AUTOSAVE_PROPERTIES.includes(attributeName) && attributeName !== 'preview_link') {
return;
}
const postType = getCurrentPostType(state);
const postId = getCurrentPostId(state);
const currentUserId = (_select$getCurrentUse = select(external_wp_coreData_namespaceObject.store).getCurrentUser()) === null || _select$getCurrentUse === void 0 ? void 0 : _select$getCurrentUse.id;
const autosave = select(external_wp_coreData_namespaceObject.store).getAutosave(postType, postId, currentUserId);
if (autosave) {
return getPostRawValue(autosave[attributeName]);
}
});
/**
* Returns the current visibility of the post being edited, preferring the
* unsaved value if different than the saved post. The return value is one of
* "private", "password", or "public".
*
* @param {Object} state Global application state.
*
* @return {string} Post visibility.
*/
function getEditedPostVisibility(state) {
const status = getEditedPostAttribute(state, 'status');
if (status === 'private') {
return 'private';
}
const password = getEditedPostAttribute(state, 'password');
if (password) {
return 'password';
}
return 'public';
}
/**
* Returns true if post is pending review.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether current post is pending review.
*/
function isCurrentPostPending(state) {
return getCurrentPost(state).status === 'pending';
}
/**
* Return true if the current post has already been published.
*
* @param {Object} state Global application state.
* @param {Object?} currentPost Explicit current post for bypassing registry selector.
*
* @return {boolean} Whether the post has been published.
*/
function isCurrentPostPublished(state, currentPost) {
const post = currentPost || getCurrentPost(state);
return ['publish', 'private'].indexOf(post.status) !== -1 || post.status === 'future' && !(0,external_wp_date_namespaceObject.isInTheFuture)(new Date(Number((0,external_wp_date_namespaceObject.getDate)(post.date)) - ONE_MINUTE_IN_MS));
}
/**
* Returns true if post is already scheduled.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether current post is scheduled to be posted.
*/
function isCurrentPostScheduled(state) {
return getCurrentPost(state).status === 'future' && !isCurrentPostPublished(state);
}
/**
* Return true if the post being edited can be published.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the post can been published.
*/
function isEditedPostPublishable(state) {
const post = getCurrentPost(state); // TODO: Post being publishable should be superset of condition of post
// being saveable. Currently this restriction is imposed at UI.
//
// See: <PostPublishButton /> (`isButtonEnabled` assigned by `isSaveable`).
return isEditedPostDirty(state) || ['publish', 'private', 'future'].indexOf(post.status) === -1;
}
/**
* Returns true if the post can be saved, or false otherwise. A post must
* contain a title, an excerpt, or non-empty content to be valid for save.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the post can be saved.
*/
function isEditedPostSaveable(state) {
if (isSavingPost(state)) {
return false;
} // TODO: Post should not be saveable if not dirty. Cannot be added here at
// this time since posts where meta boxes are present can be saved even if
// the post is not dirty. Currently this restriction is imposed at UI, but
// should be moved here.
//
// See: `isEditedPostPublishable` (includes `isEditedPostDirty` condition)
// See: <PostSavedState /> (`forceIsDirty` prop)
// See: <PostPublishButton /> (`forceIsDirty` prop)
// See: https://github.com/WordPress/gutenberg/pull/4184.
return !!getEditedPostAttribute(state, 'title') || !!getEditedPostAttribute(state, 'excerpt') || !isEditedPostEmpty(state) || external_wp_element_namespaceObject.Platform.OS === 'native';
}
/**
* Returns true if the edited post has content. A post has content if it has at
* least one saveable block or otherwise has a non-empty content property
* assigned.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether post has content.
*/
function isEditedPostEmpty(state) {
// While the condition of truthy content string is sufficient to determine
// emptiness, testing saveable blocks length is a trivial operation. Since
// this function can be called frequently, optimize for the fast case as a
// condition of the mere existence of blocks. Note that the value of edited
// content takes precedent over block content, and must fall through to the
// default logic.
const blocks = getEditorBlocks(state);
if (blocks.length) {
// Pierce the abstraction of the serializer in knowing that blocks are
// joined with newlines such that even if every individual block
// produces an empty save result, the serialized content is non-empty.
if (blocks.length > 1) {
return false;
} // There are two conditions under which the optimization cannot be
// assumed, and a fallthrough to getEditedPostContent must occur:
//
// 1. getBlocksForSerialization has special treatment in omitting a
// single unmodified default block.
// 2. Comment delimiters are omitted for a freeform or unregistered
// block in its serialization. The freeform block specifically may
// produce an empty string in its saved output.
//
// For all other content, the single block is assumed to make a post
// non-empty, if only by virtue of its own comment delimiters.
const blockName = blocks[0].name;
if (blockName !== (0,external_wp_blocks_namespaceObject.getDefaultBlockName)() && blockName !== (0,external_wp_blocks_namespaceObject.getFreeformContentHandlerName)()) {
return false;
}
}
return !getEditedPostContent(state);
}
/**
* Returns true if the post can be autosaved, or false otherwise.
*
* @param {Object} state Global application state.
* @param {Object} autosave A raw autosave object from the REST API.
*
* @return {boolean} Whether the post can be autosaved.
*/
const isEditedPostAutosaveable = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => state => {
var _select$getCurrentUse2;
// A post must contain a title, an excerpt, or non-empty content to be valid for autosaving.
if (!isEditedPostSaveable(state)) {
return false;
} // A post is not autosavable when there is a post autosave lock.
if (isPostAutosavingLocked(state)) {
return false;
}
const postType = getCurrentPostType(state);
const postId = getCurrentPostId(state);
const hasFetchedAutosave = select(external_wp_coreData_namespaceObject.store).hasFetchedAutosaves(postType, postId);
const currentUserId = (_select$getCurrentUse2 = select(external_wp_coreData_namespaceObject.store).getCurrentUser()) === null || _select$getCurrentUse2 === void 0 ? void 0 : _select$getCurrentUse2.id; // Disable reason - this line causes the side-effect of fetching the autosave
// via a resolver, moving below the return would result in the autosave never
// being fetched.
// eslint-disable-next-line @wordpress/no-unused-vars-before-return
const autosave = select(external_wp_coreData_namespaceObject.store).getAutosave(postType, postId, currentUserId); // If any existing autosaves have not yet been fetched, this function is
// unable to determine if the post is autosaveable, so return false.
if (!hasFetchedAutosave) {
return false;
} // If we don't already have an autosave, the post is autosaveable.
if (!autosave) {
return true;
} // To avoid an expensive content serialization, use the content dirtiness
// flag in place of content field comparison against the known autosave.
// This is not strictly accurate, and relies on a tolerance toward autosave
// request failures for unnecessary saves.
if (hasChangedContent(state)) {
return true;
} // If the title or excerpt has changed, the post is autosaveable.
return ['title', 'excerpt'].some(field => getPostRawValue(autosave[field]) !== getEditedPostAttribute(state, field));
});
/**
* Return true if the post being edited is being scheduled. Preferring the
* unsaved status values.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the post has been published.
*/
function isEditedPostBeingScheduled(state) {
const date = getEditedPostAttribute(state, 'date'); // Offset the date by one minute (network latency).
const checkedDate = new Date(Number((0,external_wp_date_namespaceObject.getDate)(date)) - ONE_MINUTE_IN_MS);
return (0,external_wp_date_namespaceObject.isInTheFuture)(checkedDate);
}
/**
* Returns whether the current post should be considered to have a "floating"
* date (i.e. that it would publish "Immediately" rather than at a set time).
*
* Unlike in the PHP backend, the REST API returns a full date string for posts
* where the 0000-00-00T00:00:00 placeholder is present in the database. To
* infer that a post is set to publish "Immediately" we check whether the date
* and modified date are the same.
*
* @param {Object} state Editor state.
*
* @return {boolean} Whether the edited post has a floating date value.
*/
function isEditedPostDateFloating(state) {
const date = getEditedPostAttribute(state, 'date');
const modified = getEditedPostAttribute(state, 'modified'); // This should be the status of the persisted post
// It shouldn't use the "edited" status otherwise it breaks the
// inferred post data floating status
// See https://github.com/WordPress/gutenberg/issues/28083.
const status = getCurrentPost(state).status;
if (status === 'draft' || status === 'auto-draft' || status === 'pending') {
return date === modified || date === null;
}
return false;
}
/**
* Returns true if the post is currently being deleted, or false otherwise.
*
* @param {Object} state Editor state.
*
* @return {boolean} Whether post is being deleted.
*/
function isDeletingPost(state) {
return !!state.deleting.pending;
}
/**
* Returns true if the post is currently being saved, or false otherwise.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether post is being saved.
*/
const isSavingPost = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => state => {
const postType = getCurrentPostType(state);
const postId = getCurrentPostId(state);
return select(external_wp_coreData_namespaceObject.store).isSavingEntityRecord('postType', postType, postId);
});
/**
* Returns true if non-post entities are currently being saved, or false otherwise.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether non-post entities are being saved.
*/
const isSavingNonPostEntityChanges = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => state => {
const entitiesBeingSaved = select(external_wp_coreData_namespaceObject.store).__experimentalGetEntitiesBeingSaved();
const {
type,
id
} = getCurrentPost(state);
return entitiesBeingSaved.some(entityRecord => entityRecord.kind !== 'postType' || entityRecord.name !== type || entityRecord.key !== id);
});
/**
* Returns true if a previous post save was attempted successfully, or false
* otherwise.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the post was saved successfully.
*/
const didPostSaveRequestSucceed = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => state => {
const postType = getCurrentPostType(state);
const postId = getCurrentPostId(state);
return !select(external_wp_coreData_namespaceObject.store).getLastEntitySaveError('postType', postType, postId);
});
/**
* Returns true if a previous post save was attempted but failed, or false
* otherwise.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the post save failed.
*/
const didPostSaveRequestFail = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => state => {
const postType = getCurrentPostType(state);
const postId = getCurrentPostId(state);
return !!select(external_wp_coreData_namespaceObject.store).getLastEntitySaveError('postType', postType, postId);
});
/**
* Returns true if the post is autosaving, or false otherwise.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the post is autosaving.
*/
function isAutosavingPost(state) {
var _state$saving$options;
if (!isSavingPost(state)) {
return false;
}
return Boolean((_state$saving$options = state.saving.options) === null || _state$saving$options === void 0 ? void 0 : _state$saving$options.isAutosave);
}
/**
* Returns true if the post is being previewed, or false otherwise.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether the post is being previewed.
*/
function isPreviewingPost(state) {
var _state$saving$options2;
if (!isSavingPost(state)) {
return false;
}
return Boolean((_state$saving$options2 = state.saving.options) === null || _state$saving$options2 === void 0 ? void 0 : _state$saving$options2.isPreview);
}
/**
* Returns the post preview link
*
* @param {Object} state Global application state.
*
* @return {string | undefined} Preview Link.
*/
function getEditedPostPreviewLink(state) {
if (state.saving.pending || isSavingPost(state)) {
return;
}
let previewLink = getAutosaveAttribute(state, 'preview_link'); // Fix for issue: https://github.com/WordPress/gutenberg/issues/33616
// If the post is draft, ignore the preview link from the autosave record,
// because the preview could be a stale autosave if the post was switched from
// published to draft.
// See: https://github.com/WordPress/gutenberg/pull/37952.
if (!previewLink || 'draft' === getCurrentPost(state).status) {
previewLink = getEditedPostAttribute(state, 'link');
if (previewLink) {
previewLink = (0,external_wp_url_namespaceObject.addQueryArgs)(previewLink, {
preview: true
});
}
}
const featuredImageId = getEditedPostAttribute(state, 'featured_media');
if (previewLink && featuredImageId) {
return (0,external_wp_url_namespaceObject.addQueryArgs)(previewLink, {
_thumbnail_id: featuredImageId
});
}
return previewLink;
}
/**
* Returns a suggested post format for the current post, inferred only if there
* is a single block within the post and it is of a type known to match a
* default post format. Returns null if the format cannot be determined.
*
* @param {Object} state Global application state.
*
* @return {?string} Suggested post format.
*/
function getSuggestedPostFormat(state) {
const blocks = getEditorBlocks(state);
if (blocks.length > 2) return null;
let name; // If there is only one block in the content of the post grab its name
// so we can derive a suitable post format from it.
if (blocks.length === 1) {
name = blocks[0].name; // Check for core/embed `video` and `audio` eligible suggestions.
if (name === 'core/embed') {
var _blocks$0$attributes;
const provider = (_blocks$0$attributes = blocks[0].attributes) === null || _blocks$0$attributes === void 0 ? void 0 : _blocks$0$attributes.providerNameSlug;
if (['youtube', 'vimeo'].includes(provider)) {
name = 'core/video';
} else if (['spotify', 'soundcloud'].includes(provider)) {
name = 'core/audio';
}
}
} // If there are two blocks in the content and the last one is a text blocks
// grab the name of the first one to also suggest a post format from it.
if (blocks.length === 2 && blocks[1].name === 'core/paragraph') {
name = blocks[0].name;
} // We only convert to default post formats in core.
switch (name) {
case 'core/image':
return 'image';
case 'core/quote':
case 'core/pullquote':
return 'quote';
case 'core/gallery':
return 'gallery';
case 'core/video':
return 'video';
case 'core/audio':
return 'audio';
default:
return null;
}
}
/**
* Returns the content of the post being edited.
*
* @param {Object} state Global application state.
*
* @return {string} Post content.
*/
const getEditedPostContent = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => state => {
const postId = getCurrentPostId(state);
const postType = getCurrentPostType(state);
const record = select(external_wp_coreData_namespaceObject.store).getEditedEntityRecord('postType', postType, postId);
if (record) {
if (typeof record.content === 'function') {
return record.content(record);
} else if (record.blocks) {
return (0,external_wp_blocks_namespaceObject.__unstableSerializeAndClean)(record.blocks);
} else if (record.content) {
return record.content;
}
}
return '';
});
/**
* Returns true if the post is being published, or false otherwise.
*
* @param {Object} state Global application state.
*
* @return {boolean} Whether post is being published.
*/
function isPublishingPost(state) {
return isSavingPost(state) && !isCurrentPostPublished(state) && getEditedPostAttribute(state, 'status') === 'publish';
}
/**
* Returns whether the permalink is editable or not.
*
* @param {Object} state Editor state.
*
* @return {boolean} Whether or not the permalink is editable.
*/
function isPermalinkEditable(state) {
const permalinkTemplate = getEditedPostAttribute(state, 'permalink_template');
return PERMALINK_POSTNAME_REGEX.test(permalinkTemplate);
}
/**
* Returns the permalink for the post.
*
* @param {Object} state Editor state.
*
* @return {?string} The permalink, or null if the post is not viewable.
*/
function getPermalink(state) {
const permalinkParts = getPermalinkParts(state);
if (!permalinkParts) {
return null;
}
const {
prefix,
postName,
suffix
} = permalinkParts;
if (isPermalinkEditable(state)) {
return prefix + postName + suffix;
}
return prefix;
}
/**
* Returns the slug for the post being edited, preferring a manually edited
* value if one exists, then a sanitized version of the current post title, and
* finally the post ID.
*
* @param {Object} state Editor state.
*
* @return {string} The current slug to be displayed in the editor
*/
function getEditedPostSlug(state) {
return getEditedPostAttribute(state, 'slug') || (0,external_wp_url_namespaceObject.cleanForSlug)(getEditedPostAttribute(state, 'title')) || getCurrentPostId(state);
}
/**
* Returns the permalink for a post, split into it's three parts: the prefix,
* the postName, and the suffix.
*
* @param {Object} state Editor state.
*
* @return {Object} An object containing the prefix, postName, and suffix for
* the permalink, or null if the post is not viewable.
*/
function getPermalinkParts(state) {
const permalinkTemplate = getEditedPostAttribute(state, 'permalink_template');
if (!permalinkTemplate) {
return null;
}
const postName = getEditedPostAttribute(state, 'slug') || getEditedPostAttribute(state, 'generated_slug');
const [prefix, suffix] = permalinkTemplate.split(PERMALINK_POSTNAME_REGEX);
return {
prefix,
postName,
suffix
};
}
/**
* Returns whether the post is locked.
*
* @param {Object} state Global application state.
*
* @return {boolean} Is locked.
*/
function isPostLocked(state) {
return state.postLock.isLocked;
}
/**
* Returns whether post saving is locked.
*
* @param {Object} state Global application state.
*
* @return {boolean} Is locked.
*/
function isPostSavingLocked(state) {
return Object.keys(state.postSavingLock).length > 0;
}
/**
* Returns whether post autosaving is locked.
*
* @param {Object} state Global application state.
*
* @return {boolean} Is locked.
*/
function isPostAutosavingLocked(state) {
return Object.keys(state.postAutosavingLock).length > 0;
}
/**
* Returns whether the edition of the post has been taken over.
*
* @param {Object} state Global application state.
*
* @return {boolean} Is post lock takeover.
*/
function isPostLockTakeover(state) {
return state.postLock.isTakeover;
}
/**
* Returns details about the post lock user.
*
* @param {Object} state Global application state.
*
* @return {Object} A user object.
*/
function getPostLockUser(state) {
return state.postLock.user;
}
/**
* Returns the active post lock.
*
* @param {Object} state Global application state.
*
* @return {Object} The lock object.
*/
function getActivePostLock(state) {
return state.postLock.activePostLock;
}
/**
* Returns whether or not the user has the unfiltered_html capability.
*
* @param {Object} state Editor state.
*
* @return {boolean} Whether the user can or can't post unfiltered HTML.
*/
function canUserUseUnfilteredHTML(state) {
var _getCurrentPost$_link9;
return Boolean((_getCurrentPost$_link9 = getCurrentPost(state)._links) === null || _getCurrentPost$_link9 === void 0 ? void 0 : _getCurrentPost$_link9.hasOwnProperty('wp:action-unfiltered-html'));
}
/**
* Returns whether the pre-publish panel should be shown
* or skipped when the user clicks the "publish" button.
*
* @return {boolean} Whether the pre-publish panel should be shown or not.
*/
const isPublishSidebarEnabled = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => () => !!select(external_wp_preferences_namespaceObject.store).get('core/edit-post', 'isPublishSidebarEnabled'));
/**
* Return the current block list.
*
* @param {Object} state
* @return {Array} Block list.
*/
function getEditorBlocks(state) {
return getEditedPostAttribute(state, 'blocks') || EMPTY_ARRAY;
}
/**
* A block selection object.
*
* @typedef {Object} WPBlockSelection
*
* @property {string} clientId A block client ID.
* @property {string} attributeKey A block attribute key.
* @property {number} offset An attribute value offset, based on the rich
* text value. See `wp.richText.create`.
*/
/**
* Returns the current selection start.
*
* @param {Object} state
* @return {WPBlockSelection} The selection start.
*
* @deprecated since Gutenberg 10.0.0.
*/
function getEditorSelectionStart(state) {
var _getEditedPostAttribu;
external_wp_deprecated_default()("select('core/editor').getEditorSelectionStart", {
since: '5.8',
alternative: "select('core/editor').getEditorSelection"
});
return (_getEditedPostAttribu = getEditedPostAttribute(state, 'selection')) === null || _getEditedPostAttribu === void 0 ? void 0 : _getEditedPostAttribu.selectionStart;
}
/**
* Returns the current selection end.
*
* @param {Object} state
* @return {WPBlockSelection} The selection end.
*
* @deprecated since Gutenberg 10.0.0.
*/
function getEditorSelectionEnd(state) {
var _getEditedPostAttribu2;
external_wp_deprecated_default()("select('core/editor').getEditorSelectionStart", {
since: '5.8',
alternative: "select('core/editor').getEditorSelection"
});
return (_getEditedPostAttribu2 = getEditedPostAttribute(state, 'selection')) === null || _getEditedPostAttribu2 === void 0 ? void 0 : _getEditedPostAttribu2.selectionEnd;
}
/**
* Returns the current selection.
*
* @param {Object} state
* @return {WPBlockSelection} The selection end.
*/
function getEditorSelection(state) {
return getEditedPostAttribute(state, 'selection');
}
/**
* Is the editor ready
*
* @param {Object} state
* @return {boolean} is Ready.
*/
function __unstableIsEditorReady(state) {
return state.isReady;
}
/**
* Returns the post editor settings.
*
* @param {Object} state Editor state.
*
* @return {Object} The editor settings object.
*/
function getEditorSettings(state) {
return state.editorSettings;
}
/*
* Backward compatibility
*/
/**
* Returns state object prior to a specified optimist transaction ID, or `null`
* if the transaction corresponding to the given ID cannot be found.
*
* @deprecated since Gutenberg 9.7.0.
*/
function getStateBeforeOptimisticTransaction() {
external_wp_deprecated_default()("select('core/editor').getStateBeforeOptimisticTransaction", {
since: '5.7',
hint: 'No state history is kept on this store anymore'
});
return null;
}
/**
* Returns true if an optimistic transaction is pending commit, for which the
* before state satisfies the given predicate function.
*
* @deprecated since Gutenberg 9.7.0.
*/
function inSomeHistory() {
external_wp_deprecated_default()("select('core/editor').inSomeHistory", {
since: '5.7',
hint: 'No state history is kept on this store anymore'
});
return false;
}
function getBlockEditorSelector(name) {
return (0,external_wp_data_namespaceObject.createRegistrySelector)(select => function (state) {
external_wp_deprecated_default()("`wp.data.select( 'core/editor' )." + name + '`', {
since: '5.3',
alternative: "`wp.data.select( 'core/block-editor' )." + name + '`',
version: '6.2'
});
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return select(external_wp_blockEditor_namespaceObject.store)[name](...args);
});
}
/**
* @see getBlockName in core/block-editor store.
*/
const getBlockName = getBlockEditorSelector('getBlockName');
/**
* @see isBlockValid in core/block-editor store.
*/
const isBlockValid = getBlockEditorSelector('isBlockValid');
/**
* @see getBlockAttributes in core/block-editor store.
*/
const getBlockAttributes = getBlockEditorSelector('getBlockAttributes');
/**
* @see getBlock in core/block-editor store.
*/
const getBlock = getBlockEditorSelector('getBlock');
/**
* @see getBlocks in core/block-editor store.
*/
const getBlocks = getBlockEditorSelector('getBlocks');
/**
* @see getClientIdsOfDescendants in core/block-editor store.
*/
const getClientIdsOfDescendants = getBlockEditorSelector('getClientIdsOfDescendants');
/**
* @see getClientIdsWithDescendants in core/block-editor store.
*/
const getClientIdsWithDescendants = getBlockEditorSelector('getClientIdsWithDescendants');
/**
* @see getGlobalBlockCount in core/block-editor store.
*/
const getGlobalBlockCount = getBlockEditorSelector('getGlobalBlockCount');
/**
* @see getBlocksByClientId in core/block-editor store.
*/
const getBlocksByClientId = getBlockEditorSelector('getBlocksByClientId');
/**
* @see getBlockCount in core/block-editor store.
*/
const getBlockCount = getBlockEditorSelector('getBlockCount');
/**
* @see getBlockSelectionStart in core/block-editor store.
*/
const getBlockSelectionStart = getBlockEditorSelector('getBlockSelectionStart');
/**
* @see getBlockSelectionEnd in core/block-editor store.
*/
const getBlockSelectionEnd = getBlockEditorSelector('getBlockSelectionEnd');
/**
* @see getSelectedBlockCount in core/block-editor store.
*/
const getSelectedBlockCount = getBlockEditorSelector('getSelectedBlockCount');
/**
* @see hasSelectedBlock in core/block-editor store.
*/
const hasSelectedBlock = getBlockEditorSelector('hasSelectedBlock');
/**
* @see getSelectedBlockClientId in core/block-editor store.
*/
const getSelectedBlockClientId = getBlockEditorSelector('getSelectedBlockClientId');
/**
* @see getSelectedBlock in core/block-editor store.
*/
const getSelectedBlock = getBlockEditorSelector('getSelectedBlock');
/**
* @see getBlockRootClientId in core/block-editor store.
*/
const getBlockRootClientId = getBlockEditorSelector('getBlockRootClientId');
/**
* @see getBlockHierarchyRootClientId in core/block-editor store.
*/
const getBlockHierarchyRootClientId = getBlockEditorSelector('getBlockHierarchyRootClientId');
/**
* @see getAdjacentBlockClientId in core/block-editor store.
*/
const getAdjacentBlockClientId = getBlockEditorSelector('getAdjacentBlockClientId');
/**
* @see getPreviousBlockClientId in core/block-editor store.
*/
const getPreviousBlockClientId = getBlockEditorSelector('getPreviousBlockClientId');
/**
* @see getNextBlockClientId in core/block-editor store.
*/
const getNextBlockClientId = getBlockEditorSelector('getNextBlockClientId');
/**
* @see getSelectedBlocksInitialCaretPosition in core/block-editor store.
*/
const getSelectedBlocksInitialCaretPosition = getBlockEditorSelector('getSelectedBlocksInitialCaretPosition');
/**
* @see getMultiSelectedBlockClientIds in core/block-editor store.
*/
const getMultiSelectedBlockClientIds = getBlockEditorSelector('getMultiSelectedBlockClientIds');
/**
* @see getMultiSelectedBlocks in core/block-editor store.
*/
const getMultiSelectedBlocks = getBlockEditorSelector('getMultiSelectedBlocks');
/**
* @see getFirstMultiSelectedBlockClientId in core/block-editor store.
*/
const getFirstMultiSelectedBlockClientId = getBlockEditorSelector('getFirstMultiSelectedBlockClientId');
/**
* @see getLastMultiSelectedBlockClientId in core/block-editor store.
*/
const getLastMultiSelectedBlockClientId = getBlockEditorSelector('getLastMultiSelectedBlockClientId');
/**
* @see isFirstMultiSelectedBlock in core/block-editor store.
*/
const isFirstMultiSelectedBlock = getBlockEditorSelector('isFirstMultiSelectedBlock');
/**
* @see isBlockMultiSelected in core/block-editor store.
*/
const isBlockMultiSelected = getBlockEditorSelector('isBlockMultiSelected');
/**
* @see isAncestorMultiSelected in core/block-editor store.
*/
const isAncestorMultiSelected = getBlockEditorSelector('isAncestorMultiSelected');
/**
* @see getMultiSelectedBlocksStartClientId in core/block-editor store.
*/
const getMultiSelectedBlocksStartClientId = getBlockEditorSelector('getMultiSelectedBlocksStartClientId');
/**
* @see getMultiSelectedBlocksEndClientId in core/block-editor store.
*/
const getMultiSelectedBlocksEndClientId = getBlockEditorSelector('getMultiSelectedBlocksEndClientId');
/**
* @see getBlockOrder in core/block-editor store.
*/
const getBlockOrder = getBlockEditorSelector('getBlockOrder');
/**
* @see getBlockIndex in core/block-editor store.
*/
const getBlockIndex = getBlockEditorSelector('getBlockIndex');
/**
* @see isBlockSelected in core/block-editor store.
*/
const isBlockSelected = getBlockEditorSelector('isBlockSelected');
/**
* @see hasSelectedInnerBlock in core/block-editor store.
*/
const hasSelectedInnerBlock = getBlockEditorSelector('hasSelectedInnerBlock');
/**
* @see isBlockWithinSelection in core/block-editor store.
*/
const isBlockWithinSelection = getBlockEditorSelector('isBlockWithinSelection');
/**
* @see hasMultiSelection in core/block-editor store.
*/
const hasMultiSelection = getBlockEditorSelector('hasMultiSelection');
/**
* @see isMultiSelecting in core/block-editor store.
*/
const isMultiSelecting = getBlockEditorSelector('isMultiSelecting');
/**
* @see isSelectionEnabled in core/block-editor store.
*/
const isSelectionEnabled = getBlockEditorSelector('isSelectionEnabled');
/**
* @see getBlockMode in core/block-editor store.
*/
const getBlockMode = getBlockEditorSelector('getBlockMode');
/**
* @see isTyping in core/block-editor store.
*/
const isTyping = getBlockEditorSelector('isTyping');
/**
* @see isCaretWithinFormattedText in core/block-editor store.
*/
const isCaretWithinFormattedText = getBlockEditorSelector('isCaretWithinFormattedText');
/**
* @see getBlockInsertionPoint in core/block-editor store.
*/
const getBlockInsertionPoint = getBlockEditorSelector('getBlockInsertionPoint');
/**
* @see isBlockInsertionPointVisible in core/block-editor store.
*/
const isBlockInsertionPointVisible = getBlockEditorSelector('isBlockInsertionPointVisible');
/**
* @see isValidTemplate in core/block-editor store.
*/
const isValidTemplate = getBlockEditorSelector('isValidTemplate');
/**
* @see getTemplate in core/block-editor store.
*/
const getTemplate = getBlockEditorSelector('getTemplate');
/**
* @see getTemplateLock in core/block-editor store.
*/
const getTemplateLock = getBlockEditorSelector('getTemplateLock');
/**
* @see canInsertBlockType in core/block-editor store.
*/
const canInsertBlockType = getBlockEditorSelector('canInsertBlockType');
/**
* @see getInserterItems in core/block-editor store.
*/
const getInserterItems = getBlockEditorSelector('getInserterItems');
/**
* @see hasInserterItems in core/block-editor store.
*/
const hasInserterItems = getBlockEditorSelector('hasInserterItems');
/**
* @see getBlockListSettings in core/block-editor store.
*/
const getBlockListSettings = getBlockEditorSelector('getBlockListSettings');
/**
* Returns the default template types.
*
* @param {Object} state Global application state.
*
* @return {Object} The template types.
*/
function __experimentalGetDefaultTemplateTypes(state) {
var _getEditorSettings;
return (_getEditorSettings = getEditorSettings(state)) === null || _getEditorSettings === void 0 ? void 0 : _getEditorSettings.defaultTemplateTypes;
}
/**
* Returns the default template part areas.
*
* @param {Object} state Global application state.
*
* @return {Array} The template part areas.
*/
const __experimentalGetDefaultTemplatePartAreas = rememo(state => {
var _getEditorSettings2;
const areas = ((_getEditorSettings2 = getEditorSettings(state)) === null || _getEditorSettings2 === void 0 ? void 0 : _getEditorSettings2.defaultTemplatePartAreas) || [];
return areas === null || areas === void 0 ? void 0 : areas.map(item => {
return { ...item,
icon: getTemplatePartIcon(item.icon)
};
});
}, state => {
var _getEditorSettings3;
return [(_getEditorSettings3 = getEditorSettings(state)) === null || _getEditorSettings3 === void 0 ? void 0 : _getEditorSettings3.defaultTemplatePartAreas];
});
/**
* Returns a default template type searched by slug.
*
* @param {Object} state Global application state.
* @param {string} slug The template type slug.
*
* @return {Object} The template type.
*/
const __experimentalGetDefaultTemplateType = rememo((state, slug) => {
var _Object$values$find;
const templateTypes = __experimentalGetDefaultTemplateTypes(state);
if (!templateTypes) {
return EMPTY_OBJECT;
}
return (_Object$values$find = Object.values(templateTypes).find(type => type.slug === slug)) !== null && _Object$values$find !== void 0 ? _Object$values$find : EMPTY_OBJECT;
}, (state, slug) => [__experimentalGetDefaultTemplateTypes(state), slug]);
/**
* Given a template entity, return information about it which is ready to be
* rendered, such as the title, description, and icon.
*
* @param {Object} state Global application state.
* @param {Object} template The template for which we need information.
* @return {Object} Information about the template, including title, description, and icon.
*/
function __experimentalGetTemplateInfo(state, template) {
var _experimentalGetDefa;
if (!template) {
return EMPTY_OBJECT;
}
const {
description,
slug,
title,
area
} = template;
const {
title: defaultTitle,
description: defaultDescription
} = __experimentalGetDefaultTemplateType(state, slug);
const templateTitle = typeof title === 'string' ? title : title === null || title === void 0 ? void 0 : title.rendered;
const templateDescription = typeof description === 'string' ? description : description === null || description === void 0 ? void 0 : description.raw;
const templateIcon = ((_experimentalGetDefa = __experimentalGetDefaultTemplatePartAreas(state).find(item => area === item.area)) === null || _experimentalGetDefa === void 0 ? void 0 : _experimentalGetDefa.icon) || library_layout;
return {
title: templateTitle && templateTitle !== slug ? templateTitle : defaultTitle || slug,
description: templateDescription || defaultDescription,
icon: templateIcon
};
}
/**
* Returns a post type label depending on the current post.
*
* @param {Object} state Global application state.
*
* @return {string|undefined} The post type label if available, otherwise undefined.
*/
const getPostTypeLabel = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => state => {
var _postType$labels;
const currentPostType = getCurrentPostType(state);
const postType = select(external_wp_coreData_namespaceObject.store).getPostType(currentPostType); // Disable reason: Post type labels object is shaped like this.
// eslint-disable-next-line camelcase
return postType === null || postType === void 0 ? void 0 : (_postType$labels = postType.labels) === null || _postType$labels === void 0 ? void 0 : _postType$labels.singular_name;
});
;// CONCATENATED MODULE: external ["wp","apiFetch"]
var external_wp_apiFetch_namespaceObject = window["wp"]["apiFetch"];
var external_wp_apiFetch_default = /*#__PURE__*/__webpack_require__.n(external_wp_apiFetch_namespaceObject);
;// CONCATENATED MODULE: external ["wp","notices"]
var external_wp_notices_namespaceObject = window["wp"]["notices"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/store/local-autosave.js
/**
* Function returning a sessionStorage key to set or retrieve a given post's
* automatic session backup.
*
* Keys are crucially prefixed with 'wp-autosave-' so that wp-login.php's
* `loggedout` handler can clear sessionStorage of any user-private content.
*
* @see https://github.com/WordPress/wordpress-develop/blob/6dad32d2aed47e6c0cf2aee8410645f6d7aba6bd/src/wp-login.php#L103
*
* @param {string} postId Post ID.
* @param {boolean} isPostNew Whether post new.
*
* @return {string} sessionStorage key
*/
function postKey(postId, isPostNew) {
return `wp-autosave-block-editor-post-${isPostNew ? 'auto-draft' : postId}`;
}
function localAutosaveGet(postId, isPostNew) {
return window.sessionStorage.getItem(postKey(postId, isPostNew));
}
function localAutosaveSet(postId, isPostNew, title, content, excerpt) {
window.sessionStorage.setItem(postKey(postId, isPostNew), JSON.stringify({
post_title: title,
content,
excerpt
}));
}
function localAutosaveClear(postId, isPostNew) {
window.sessionStorage.removeItem(postKey(postId, isPostNew));
}
;// CONCATENATED MODULE: external ["wp","i18n"]
var external_wp_i18n_namespaceObject = window["wp"]["i18n"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/store/utils/notice-builder.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* External dependencies
*/
/**
* Builds the arguments for a success notification dispatch.
*
* @param {Object} data Incoming data to build the arguments from.
*
* @return {Array} Arguments for dispatch. An empty array signals no
* notification should be sent.
*/
function getNotificationArgumentsForSaveSuccess(data) {
const {
previousPost,
post,
postType
} = data; // Autosaves are neither shown a notice nor redirected.
if ((0,external_lodash_namespaceObject.get)(data.options, ['isAutosave'])) {
return [];
} // No notice is shown after trashing a post
if (post.status === 'trash' && previousPost.status !== 'trash') {
return [];
}
const publishStatus = ['publish', 'private', 'future'];
const isPublished = publishStatus.includes(previousPost.status);
const willPublish = publishStatus.includes(post.status);
let noticeMessage;
let shouldShowLink = (0,external_lodash_namespaceObject.get)(postType, ['viewable'], false);
let isDraft; // Always should a notice, which will be spoken for accessibility.
if (!isPublished && !willPublish) {
// If saving a non-published post, don't show notice.
noticeMessage = (0,external_wp_i18n_namespaceObject.__)('Draft saved.');
isDraft = true;
} else if (isPublished && !willPublish) {
// If undoing publish status, show specific notice.
noticeMessage = postType.labels.item_reverted_to_draft;
shouldShowLink = false;
} else if (!isPublished && willPublish) {
// If publishing or scheduling a post, show the corresponding
// publish message.
noticeMessage = {
publish: postType.labels.item_published,
private: postType.labels.item_published_privately,
future: postType.labels.item_scheduled
}[post.status];
} else {
// Generic fallback notice.
noticeMessage = postType.labels.item_updated;
}
const actions = [];
if (shouldShowLink) {
actions.push({
label: isDraft ? (0,external_wp_i18n_namespaceObject.__)('View Preview') : postType.labels.view_item,
url: post.link
});
}
return [noticeMessage, {
id: SAVE_POST_NOTICE_ID,
type: 'snackbar',
actions
}];
}
/**
* Builds the fail notification arguments for dispatch.
*
* @param {Object} data Incoming data to build the arguments with.
*
* @return {Array} Arguments for dispatch. An empty array signals no
* notification should be sent.
*/
function getNotificationArgumentsForSaveFail(data) {
const {
post,
edits,
error
} = data;
if (error && 'rest_autosave_no_changes' === error.code) {
// Autosave requested a new autosave, but there were no changes. This shouldn't
// result in an error notice for the user.
return [];
}
const publishStatus = ['publish', 'private', 'future'];
const isPublished = publishStatus.indexOf(post.status) !== -1; // If the post was being published, we show the corresponding publish error message
// Unless we publish an "updating failed" message.
const messages = {
publish: (0,external_wp_i18n_namespaceObject.__)('Publishing failed.'),
private: (0,external_wp_i18n_namespaceObject.__)('Publishing failed.'),
future: (0,external_wp_i18n_namespaceObject.__)('Scheduling failed.')
};
let noticeMessage = !isPublished && publishStatus.indexOf(edits.status) !== -1 ? messages[edits.status] : (0,external_wp_i18n_namespaceObject.__)('Updating failed.'); // Check if message string contains HTML. Notice text is currently only
// supported as plaintext, and stripping the tags may muddle the meaning.
if (error.message && !/<\/?[^>]*>/.test(error.message)) {
noticeMessage = [noticeMessage, error.message].join(' ');
}
return [noticeMessage, {
id: SAVE_POST_NOTICE_ID
}];
}
/**
* Builds the trash fail notification arguments for dispatch.
*
* @param {Object} data
*
* @return {Array} Arguments for dispatch.
*/
function getNotificationArgumentsForTrashFail(data) {
return [data.error.message && data.error.code !== 'unknown_error' ? data.error.message : (0,external_wp_i18n_namespaceObject.__)('Trashing failed'), {
id: TRASH_POST_NOTICE_ID
}];
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/store/actions.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Returns an action generator used in signalling that editor has initialized with
* the specified post object and editor settings.
*
* @param {Object} post Post object.
* @param {Object} edits Initial edited attributes object.
* @param {Array?} template Block Template.
*/
const setupEditor = (post, edits, template) => _ref => {
let {
dispatch
} = _ref;
dispatch.setupEditorState(post); // Apply a template for new posts only, if exists.
const isNewPost = post.status === 'auto-draft';
if (isNewPost && template) {
// In order to ensure maximum of a single parse during setup, edits are
// included as part of editor setup action. Assume edited content as
// canonical if provided, falling back to post.
let content;
if ('content' in edits) {
content = edits.content;
} else {
content = post.content.raw;
}
let blocks = (0,external_wp_blocks_namespaceObject.parse)(content);
blocks = (0,external_wp_blocks_namespaceObject.synchronizeBlocksWithTemplate)(blocks, template);
dispatch.resetEditorBlocks(blocks, {
__unstableShouldCreateUndoLevel: false
});
}
if (edits && Object.values(edits).some(_ref2 => {
var _post$key$raw, _post$key;
let [key, edit] = _ref2;
return edit !== ((_post$key$raw = (_post$key = post[key]) === null || _post$key === void 0 ? void 0 : _post$key.raw) !== null && _post$key$raw !== void 0 ? _post$key$raw : post[key]);
})) {
dispatch.editPost(edits);
}
};
/**
* Returns an action object signalling that the editor is being destroyed and
* that any necessary state or side-effect cleanup should occur.
*
* @return {Object} Action object.
*/
function __experimentalTearDownEditor() {
return {
type: 'TEAR_DOWN_EDITOR'
};
}
/**
* Returns an action object used in signalling that the latest version of the
* post has been received, either by initialization or save.
*
* @deprecated Since WordPress 6.0.
*/
function resetPost() {
external_wp_deprecated_default()("wp.data.dispatch( 'core/editor' ).resetPost", {
since: '6.0',
version: '6.3',
alternative: 'Initialize the editor with the setupEditorState action'
});
return {
type: 'DO_NOTHING'
};
}
/**
* Returns an action object used in signalling that a patch of updates for the
* latest version of the post have been received.
*
* @return {Object} Action object.
* @deprecated since Gutenberg 9.7.0.
*/
function updatePost() {
external_wp_deprecated_default()("wp.data.dispatch( 'core/editor' ).updatePost", {
since: '5.7',
alternative: 'Use the core entities store instead'
});
return {
type: 'DO_NOTHING'
};
}
/**
* Returns an action object used to setup the editor state when first opening
* an editor.
*
* @param {Object} post Post object.
*
* @return {Object} Action object.
*/
function setupEditorState(post) {
return {
type: 'SETUP_EDITOR_STATE',
post
};
}
/**
* Returns an action object used in signalling that attributes of the post have
* been edited.
*
* @param {Object} edits Post attributes to edit.
* @param {Object} options Options for the edit.
*/
const editPost = (edits, options) => _ref3 => {
let {
select,
registry
} = _ref3;
const {
id,
type
} = select.getCurrentPost();
registry.dispatch(external_wp_coreData_namespaceObject.store).editEntityRecord('postType', type, id, edits, options);
};
/**
* Action for saving the current post in the editor.
*
* @param {Object} options
*/
const savePost = function () {
let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return async _ref4 => {
let {
select,
dispatch,
registry
} = _ref4;
if (!select.isEditedPostSaveable()) {
return;
}
const content = select.getEditedPostContent();
if (!options.isAutosave) {
dispatch.editPost({
content
}, {
undoIgnore: true
});
}
const previousRecord = select.getCurrentPost();
const edits = {
id: previousRecord.id,
...registry.select(external_wp_coreData_namespaceObject.store).getEntityRecordNonTransientEdits('postType', previousRecord.type, previousRecord.id),
content
};
dispatch({
type: 'REQUEST_POST_UPDATE_START',
options
});
await registry.dispatch(external_wp_coreData_namespaceObject.store).saveEntityRecord('postType', previousRecord.type, edits, options);
dispatch({
type: 'REQUEST_POST_UPDATE_FINISH',
options
});
const error = registry.select(external_wp_coreData_namespaceObject.store).getLastEntitySaveError('postType', previousRecord.type, previousRecord.id);
if (error) {
const args = getNotificationArgumentsForSaveFail({
post: previousRecord,
edits,
error
});
if (args.length) {
registry.dispatch(external_wp_notices_namespaceObject.store).createErrorNotice(...args);
}
} else {
const updatedRecord = select.getCurrentPost();
const args = getNotificationArgumentsForSaveSuccess({
previousPost: previousRecord,
post: updatedRecord,
postType: await registry.resolveSelect(external_wp_coreData_namespaceObject.store).getPostType(updatedRecord.type),
options
});
if (args.length) {
registry.dispatch(external_wp_notices_namespaceObject.store).createSuccessNotice(...args);
} // Make sure that any edits after saving create an undo level and are
// considered for change detection.
if (!options.isAutosave) {
registry.dispatch(external_wp_blockEditor_namespaceObject.store).__unstableMarkLastChangeAsPersistent();
}
}
};
};
/**
* Action for refreshing the current post.
*
* @deprecated Since WordPress 6.0.
*/
function refreshPost() {
external_wp_deprecated_default()("wp.data.dispatch( 'core/editor' ).refreshPost", {
since: '6.0',
version: '6.3',
alternative: 'Use the core entities store instead'
});
return {
type: 'DO_NOTHING'
};
}
/**
* Action for trashing the current post in the editor.
*/
const trashPost = () => async _ref5 => {
let {
select,
dispatch,
registry
} = _ref5;
const postTypeSlug = select.getCurrentPostType();
const postType = await registry.resolveSelect(external_wp_coreData_namespaceObject.store).getPostType(postTypeSlug);
registry.dispatch(external_wp_notices_namespaceObject.store).removeNotice(TRASH_POST_NOTICE_ID);
const {
rest_base: restBase,
rest_namespace: restNamespace = 'wp/v2'
} = postType;
dispatch({
type: 'REQUEST_POST_DELETE_START'
});
try {
const post = select.getCurrentPost();
await external_wp_apiFetch_default()({
path: `/${restNamespace}/${restBase}/${post.id}`,
method: 'DELETE'
});
await dispatch.savePost();
} catch (error) {
registry.dispatch(external_wp_notices_namespaceObject.store).createErrorNotice(...getNotificationArgumentsForTrashFail({
error
}));
}
dispatch({
type: 'REQUEST_POST_DELETE_FINISH'
});
};
/**
* Action that autosaves the current post. This
* includes server-side autosaving (default) and client-side (a.k.a. local)
* autosaving (e.g. on the Web, the post might be committed to Session
* Storage).
*
* @param {Object?} options Extra flags to identify the autosave.
*/
const autosave = function () {
let {
local = false,
...options
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return async _ref6 => {
let {
select,
dispatch
} = _ref6;
if (local) {
const post = select.getCurrentPost();
const isPostNew = select.isEditedPostNew();
const title = select.getEditedPostAttribute('title');
const content = select.getEditedPostAttribute('content');
const excerpt = select.getEditedPostAttribute('excerpt');
localAutosaveSet(post.id, isPostNew, title, content, excerpt);
} else {
await dispatch.savePost({
isAutosave: true,
...options
});
}
};
};
/**
* Action that restores last popped state in undo history.
*/
const redo = () => _ref7 => {
let {
registry
} = _ref7;
registry.dispatch(external_wp_coreData_namespaceObject.store).redo();
};
/**
* Action that pops a record from undo history and undoes the edit.
*/
const undo = () => _ref8 => {
let {
registry
} = _ref8;
registry.dispatch(external_wp_coreData_namespaceObject.store).undo();
};
/**
* Action that creates an undo history record.
*
* @deprecated Since WordPress 6.0
*/
function createUndoLevel() {
external_wp_deprecated_default()("wp.data.dispatch( 'core/editor' ).createUndoLevel", {
since: '6.0',
version: '6.3',
alternative: 'Use the core entities store instead'
});
return {
type: 'DO_NOTHING'
};
}
/**
* Action that locks the editor.
*
* @param {Object} lock Details about the post lock status, user, and nonce.
* @return {Object} Action object.
*/
function updatePostLock(lock) {
return {
type: 'UPDATE_POST_LOCK',
lock
};
}
/**
* Enable the publish sidebar.
*/
const enablePublishSidebar = () => _ref9 => {
let {
registry
} = _ref9;
registry.dispatch(external_wp_preferences_namespaceObject.store).set('core/edit-post', 'isPublishSidebarEnabled', true);
};
/**
* Disables the publish sidebar.
*/
const disablePublishSidebar = () => _ref10 => {
let {
registry
} = _ref10;
registry.dispatch(external_wp_preferences_namespaceObject.store).set('core/edit-post', 'isPublishSidebarEnabled', false);
};
/**
* Action that locks post saving.
*
* @param {string} lockName The lock name.
*
* @example
* ```
* const { subscribe } = wp.data;
*
* const initialPostStatus = wp.data.select( 'core/editor' ).getEditedPostAttribute( 'status' );
*
* // Only allow publishing posts that are set to a future date.
* if ( 'publish' !== initialPostStatus ) {
*
* // Track locking.
* let locked = false;
*
* // Watch for the publish event.
* let unssubscribe = subscribe( () => {
* const currentPostStatus = wp.data.select( 'core/editor' ).getEditedPostAttribute( 'status' );
* if ( 'publish' !== currentPostStatus ) {
*
* // Compare the post date to the current date, lock the post if the date isn't in the future.
* const postDate = new Date( wp.data.select( 'core/editor' ).getEditedPostAttribute( 'date' ) );
* const currentDate = new Date();
* if ( postDate.getTime() <= currentDate.getTime() ) {
* if ( ! locked ) {
* locked = true;
* wp.data.dispatch( 'core/editor' ).lockPostSaving( 'futurelock' );
* }
* } else {
* if ( locked ) {
* locked = false;
* wp.data.dispatch( 'core/editor' ).unlockPostSaving( 'futurelock' );
* }
* }
* }
* } );
* }
* ```
*
* @return {Object} Action object
*/
function lockPostSaving(lockName) {
return {
type: 'LOCK_POST_SAVING',
lockName
};
}
/**
* Action that unlocks post saving.
*
* @param {string} lockName The lock name.
*
* @example
* ```
* // Unlock post saving with the lock key `mylock`:
* wp.data.dispatch( 'core/editor' ).unlockPostSaving( 'mylock' );
* ```
*
* @return {Object} Action object
*/
function unlockPostSaving(lockName) {
return {
type: 'UNLOCK_POST_SAVING',
lockName
};
}
/**
* Action that locks post autosaving.
*
* @param {string} lockName The lock name.
*
* @example
* ```
* // Lock post autosaving with the lock key `mylock`:
* wp.data.dispatch( 'core/editor' ).lockPostAutosaving( 'mylock' );
* ```
*
* @return {Object} Action object
*/
function lockPostAutosaving(lockName) {
return {
type: 'LOCK_POST_AUTOSAVING',
lockName
};
}
/**
* Action that unlocks post autosaving.
*
* @param {string} lockName The lock name.
*
* @example
* ```
* // Unlock post saving with the lock key `mylock`:
* wp.data.dispatch( 'core/editor' ).unlockPostAutosaving( 'mylock' );
* ```
*
* @return {Object} Action object
*/
function unlockPostAutosaving(lockName) {
return {
type: 'UNLOCK_POST_AUTOSAVING',
lockName
};
}
/**
* Returns an action object used to signal that the blocks have been updated.
*
* @param {Array} blocks Block Array.
* @param {?Object} options Optional options.
*/
const resetEditorBlocks = function (blocks) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return _ref11 => {
let {
select,
dispatch,
registry
} = _ref11;
const {
__unstableShouldCreateUndoLevel,
selection
} = options;
const edits = {
blocks,
selection
};
if (__unstableShouldCreateUndoLevel !== false) {
const {
id,
type
} = select.getCurrentPost();
const noChange = registry.select(external_wp_coreData_namespaceObject.store).getEditedEntityRecord('postType', type, id).blocks === edits.blocks;
if (noChange) {
registry.dispatch(external_wp_coreData_namespaceObject.store).__unstableCreateUndoLevel('postType', type, id);
return;
} // We create a new function here on every persistent edit
// to make sure the edit makes the post dirty and creates
// a new undo level.
edits.content = _ref12 => {
let {
blocks: blocksForSerialization = []
} = _ref12;
return (0,external_wp_blocks_namespaceObject.__unstableSerializeAndClean)(blocksForSerialization);
};
}
dispatch.editPost(edits);
};
};
/*
* Returns an action object used in signalling that the post editor settings have been updated.
*
* @param {Object} settings Updated settings
*
* @return {Object} Action object
*/
function updateEditorSettings(settings) {
return {
type: 'UPDATE_EDITOR_SETTINGS',
settings
};
}
/**
* Backward compatibility
*/
const getBlockEditorAction = name => function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ref13 => {
let {
registry
} = _ref13;
external_wp_deprecated_default()("`wp.data.dispatch( 'core/editor' )." + name + '`', {
since: '5.3',
alternative: "`wp.data.dispatch( 'core/block-editor' )." + name + '`',
version: '6.2'
});
registry.dispatch(external_wp_blockEditor_namespaceObject.store)[name](...args);
};
};
/**
* @see resetBlocks in core/block-editor store.
*/
const resetBlocks = getBlockEditorAction('resetBlocks');
/**
* @see receiveBlocks in core/block-editor store.
*/
const receiveBlocks = getBlockEditorAction('receiveBlocks');
/**
* @see updateBlock in core/block-editor store.
*/
const updateBlock = getBlockEditorAction('updateBlock');
/**
* @see updateBlockAttributes in core/block-editor store.
*/
const updateBlockAttributes = getBlockEditorAction('updateBlockAttributes');
/**
* @see selectBlock in core/block-editor store.
*/
const selectBlock = getBlockEditorAction('selectBlock');
/**
* @see startMultiSelect in core/block-editor store.
*/
const startMultiSelect = getBlockEditorAction('startMultiSelect');
/**
* @see stopMultiSelect in core/block-editor store.
*/
const stopMultiSelect = getBlockEditorAction('stopMultiSelect');
/**
* @see multiSelect in core/block-editor store.
*/
const multiSelect = getBlockEditorAction('multiSelect');
/**
* @see clearSelectedBlock in core/block-editor store.
*/
const clearSelectedBlock = getBlockEditorAction('clearSelectedBlock');
/**
* @see toggleSelection in core/block-editor store.
*/
const toggleSelection = getBlockEditorAction('toggleSelection');
/**
* @see replaceBlocks in core/block-editor store.
*/
const replaceBlocks = getBlockEditorAction('replaceBlocks');
/**
* @see replaceBlock in core/block-editor store.
*/
const replaceBlock = getBlockEditorAction('replaceBlock');
/**
* @see moveBlocksDown in core/block-editor store.
*/
const moveBlocksDown = getBlockEditorAction('moveBlocksDown');
/**
* @see moveBlocksUp in core/block-editor store.
*/
const moveBlocksUp = getBlockEditorAction('moveBlocksUp');
/**
* @see moveBlockToPosition in core/block-editor store.
*/
const moveBlockToPosition = getBlockEditorAction('moveBlockToPosition');
/**
* @see insertBlock in core/block-editor store.
*/
const insertBlock = getBlockEditorAction('insertBlock');
/**
* @see insertBlocks in core/block-editor store.
*/
const insertBlocks = getBlockEditorAction('insertBlocks');
/**
* @see showInsertionPoint in core/block-editor store.
*/
const showInsertionPoint = getBlockEditorAction('showInsertionPoint');
/**
* @see hideInsertionPoint in core/block-editor store.
*/
const hideInsertionPoint = getBlockEditorAction('hideInsertionPoint');
/**
* @see setTemplateValidity in core/block-editor store.
*/
const setTemplateValidity = getBlockEditorAction('setTemplateValidity');
/**
* @see synchronizeTemplate in core/block-editor store.
*/
const synchronizeTemplate = getBlockEditorAction('synchronizeTemplate');
/**
* @see mergeBlocks in core/block-editor store.
*/
const mergeBlocks = getBlockEditorAction('mergeBlocks');
/**
* @see removeBlocks in core/block-editor store.
*/
const removeBlocks = getBlockEditorAction('removeBlocks');
/**
* @see removeBlock in core/block-editor store.
*/
const removeBlock = getBlockEditorAction('removeBlock');
/**
* @see toggleBlockMode in core/block-editor store.
*/
const toggleBlockMode = getBlockEditorAction('toggleBlockMode');
/**
* @see startTyping in core/block-editor store.
*/
const startTyping = getBlockEditorAction('startTyping');
/**
* @see stopTyping in core/block-editor store.
*/
const stopTyping = getBlockEditorAction('stopTyping');
/**
* @see enterFormattedText in core/block-editor store.
*/
const enterFormattedText = getBlockEditorAction('enterFormattedText');
/**
* @see exitFormattedText in core/block-editor store.
*/
const exitFormattedText = getBlockEditorAction('exitFormattedText');
/**
* @see insertDefaultBlock in core/block-editor store.
*/
const insertDefaultBlock = getBlockEditorAction('insertDefaultBlock');
/**
* @see updateBlockListSettings in core/block-editor store.
*/
const updateBlockListSettings = getBlockEditorAction('updateBlockListSettings');
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/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,
selectors: selectors_namespaceObject,
actions: actions_namespaceObject
};
/**
* Store definition for the editor namespace.
*
* @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/data/README.md#createReduxStore
*
* @type {Object}
*/
const store_store = (0,external_wp_data_namespaceObject.createReduxStore)(STORE_NAME, { ...storeConfig
});
(0,external_wp_data_namespaceObject.register)(store_store);
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/hooks/custom-sources-backwards-compatibility.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/** @typedef {import('@wordpress/compose').WPHigherOrderComponent} WPHigherOrderComponent */
/** @typedef {import('@wordpress/blocks').WPBlockSettings} WPBlockSettings */
/**
* Object whose keys are the names of block attributes, where each value
* represents the meta key to which the block attribute is intended to save.
*
* @see https://developer.wordpress.org/reference/functions/register_meta/
*
* @typedef {Object<string,string>} WPMetaAttributeMapping
*/
/**
* Given a mapping of attribute names (meta source attributes) to their
* associated meta key, returns a higher order component that overrides its
* `attributes` and `setAttributes` props to sync any changes with the edited
* post's meta keys.
*
* @param {WPMetaAttributeMapping} metaAttributes Meta attribute mapping.
*
* @return {WPHigherOrderComponent} Higher-order component.
*/
const createWithMetaAttributeSource = metaAttributes => (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(BlockEdit => _ref => {
let {
attributes,
setAttributes,
...props
} = _ref;
const postType = (0,external_wp_data_namespaceObject.useSelect)(select => select(store_store).getCurrentPostType(), []);
const [meta, setMeta] = (0,external_wp_coreData_namespaceObject.useEntityProp)('postType', postType, 'meta');
const mergedAttributes = (0,external_wp_element_namespaceObject.useMemo)(() => ({ ...attributes,
...(0,external_lodash_namespaceObject.mapValues)(metaAttributes, metaKey => meta[metaKey])
}), [attributes, meta]);
return (0,external_wp_element_namespaceObject.createElement)(BlockEdit, _extends({
attributes: mergedAttributes,
setAttributes: nextAttributes => {
const nextMeta = Object.fromEntries(Object.entries(nextAttributes !== null && nextAttributes !== void 0 ? nextAttributes : {}).filter( // Filter to intersection of keys between the updated
// attributes and those with an associated meta key.
_ref2 => {
let [key] = _ref2;
return key in metaAttributes;
}).map(_ref3 => {
let [attributeKey, value] = _ref3;
return [// Rename the keys to the expected meta key name.
metaAttributes[attributeKey], value];
}));
if (!(0,external_lodash_namespaceObject.isEmpty)(nextMeta)) {
setMeta(nextMeta);
}
setAttributes(nextAttributes);
}
}, props));
}, 'withMetaAttributeSource');
/**
* Filters a registered block's settings to enhance a block's `edit` component
* to upgrade meta-sourced attributes to use the post's meta entity property.
*
* @param {WPBlockSettings} settings Registered block settings.
*
* @return {WPBlockSettings} Filtered block settings.
*/
function shimAttributeSource(settings) {
var _settings$attributes;
/** @type {WPMetaAttributeMapping} */
const metaAttributes = (0,external_lodash_namespaceObject.mapValues)(Object.fromEntries(Object.entries((_settings$attributes = settings.attributes) !== null && _settings$attributes !== void 0 ? _settings$attributes : {}).filter(_ref4 => {
let [, {
source
}] = _ref4;
return source === 'meta';
})), 'meta');
if (!(0,external_lodash_namespaceObject.isEmpty)(metaAttributes)) {
settings.edit = createWithMetaAttributeSource(metaAttributes)(settings.edit);
}
return settings;
}
(0,external_wp_hooks_namespaceObject.addFilter)('blocks.registerBlockType', 'core/editor/custom-sources-backwards-compatibility/shim-attribute-source', shimAttributeSource); // The above filter will only capture blocks registered after the filter was
// added. There may already be blocks registered by this point, and those must
// be updated to apply the shim.
//
// The following implementation achieves this, albeit with a couple caveats:
// - Only blocks registered on the global store will be modified.
// - The block settings are directly mutated, since there is currently no
// mechanism to update an existing block registration. This is the reason for
// `getBlockType` separate from `getBlockTypes`, since the latter returns a
// _copy_ of the block registration (i.e. the mutation would not affect the
// actual registered block settings).
//
// `getBlockTypes` or `getBlockType` implementation could change in the future
// in regards to creating settings clones, but the corresponding end-to-end
// tests for meta blocks should cover against any potential regressions.
//
// In the future, we could support updating block settings, at which point this
// implementation could use that mechanism instead.
(0,external_wp_data_namespaceObject.select)(external_wp_blocks_namespaceObject.store).getBlockTypes().map(_ref5 => {
let {
name
} = _ref5;
return (0,external_wp_data_namespaceObject.select)(external_wp_blocks_namespaceObject.store).getBlockType(name);
}).forEach(shimAttributeSource);
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/autocompleters/user.js
/**
* WordPress dependencies
*/
/** @typedef {import('@wordpress/components').WPCompleter} WPCompleter */
function getUserLabel(user) {
const avatar = user.avatar_urls && user.avatar_urls[24] ? (0,external_wp_element_namespaceObject.createElement)("img", {
className: "editor-autocompleters__user-avatar",
alt: "",
src: user.avatar_urls[24]
}) : (0,external_wp_element_namespaceObject.createElement)("span", {
className: "editor-autocompleters__no-avatar"
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, avatar, (0,external_wp_element_namespaceObject.createElement)("span", {
className: "editor-autocompleters__user-name"
}, user.name), (0,external_wp_element_namespaceObject.createElement)("span", {
className: "editor-autocompleters__user-slug"
}, user.slug));
}
/**
* A user mentions completer.
*
* @type {WPCompleter}
*/
/* harmony default export */ var user = ({
name: 'users',
className: 'editor-autocompleters__user',
triggerPrefix: '@',
useItems(filterValue) {
const users = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getUsers
} = select(external_wp_coreData_namespaceObject.store);
return getUsers({
context: 'view',
search: encodeURIComponent(filterValue)
});
}, [filterValue]);
const options = (0,external_wp_element_namespaceObject.useMemo)(() => users ? users.map(user => ({
key: `user-${user.slug}`,
value: user,
label: getUserLabel(user)
})) : [], [users]);
return [options];
},
getOptionCompletion(user) {
return `@${user.slug}`;
}
});
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/hooks/default-autocompleters.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function setDefaultCompleters() {
let completers = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
// Provide copies so filters may directly modify them.
completers.push({ ...user
});
return completers;
}
(0,external_wp_hooks_namespaceObject.addFilter)('editor.Autocomplete.completers', 'editor/autocompleters/set-default-completers', setDefaultCompleters);
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/hooks/index.js
/**
* Internal dependencies
*/
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/autocompleters/index.js
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/autosave-monitor/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* AutosaveMonitor invokes `props.autosave()` within at most `interval` seconds after an unsaved change is detected.
*
* The logic is straightforward: a check is performed every `props.interval` seconds. If any changes are detected, `props.autosave()` is called.
* The time between the change and the autosave varies but is no larger than `props.interval` seconds. Refer to the code below for more details, such as
* the specific way of detecting changes.
*
* There are two caveats:
* * If `props.isAutosaveable` happens to be false at a time of checking for changes, the check is retried every second.
* * The timer may be disabled by setting `props.disableIntervalChecks` to `true`. In that mode, any change will immediately trigger `props.autosave()`.
*/
class AutosaveMonitor extends external_wp_element_namespaceObject.Component {
constructor(props) {
super(props);
this.needsAutosave = !!(props.isDirty && props.isAutosaveable);
}
componentDidMount() {
if (!this.props.disableIntervalChecks) {
this.setAutosaveTimer();
}
}
componentDidUpdate(prevProps) {
if (this.props.disableIntervalChecks) {
if (this.props.editsReference !== prevProps.editsReference) {
this.props.autosave();
}
return;
}
if (this.props.interval !== prevProps.interval) {
clearTimeout(this.timerId);
this.setAutosaveTimer();
}
if (!this.props.isDirty) {
this.needsAutosave = false;
return;
}
if (this.props.isAutosaving && !prevProps.isAutosaving) {
this.needsAutosave = false;
return;
}
if (this.props.editsReference !== prevProps.editsReference) {
this.needsAutosave = true;
}
}
componentWillUnmount() {
clearTimeout(this.timerId);
}
setAutosaveTimer() {
let timeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.props.interval * 1000;
this.timerId = setTimeout(() => {
this.autosaveTimerHandler();
}, timeout);
}
autosaveTimerHandler() {
if (!this.props.isAutosaveable) {
this.setAutosaveTimer(1000);
return;
}
if (this.needsAutosave) {
this.needsAutosave = false;
this.props.autosave();
}
this.setAutosaveTimer();
}
render() {
return null;
}
}
/* harmony default export */ var autosave_monitor = ((0,external_wp_compose_namespaceObject.compose)([(0,external_wp_data_namespaceObject.withSelect)((select, ownProps) => {
const {
getReferenceByDistinctEdits
} = select(external_wp_coreData_namespaceObject.store);
const {
isEditedPostDirty,
isEditedPostAutosaveable,
isAutosavingPost,
getEditorSettings
} = select(store_store);
const {
interval = getEditorSettings().autosaveInterval
} = ownProps;
return {
editsReference: getReferenceByDistinctEdits(),
isDirty: isEditedPostDirty(),
isAutosaveable: isEditedPostAutosaveable(),
isAutosaving: isAutosavingPost(),
interval
};
}), (0,external_wp_data_namespaceObject.withDispatch)((dispatch, ownProps) => ({
autosave() {
const {
autosave = dispatch(store_store).autosave
} = ownProps;
autosave();
}
}))])(AutosaveMonitor));
;// CONCATENATED MODULE: external ["wp","richText"]
var external_wp_richText_namespaceObject = window["wp"]["richText"];
// EXTERNAL MODULE: ./node_modules/classnames/index.js
var classnames = __webpack_require__(7153);
var classnames_default = /*#__PURE__*/__webpack_require__.n(classnames);
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/document-outline/item.js
/**
* External dependencies
*/
const TableOfContentsItem = _ref => {
let {
children,
isValid,
level,
href,
onSelect
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("li", {
className: classnames_default()('document-outline__item', `is-${level.toLowerCase()}`, {
'is-invalid': !isValid
})
}, (0,external_wp_element_namespaceObject.createElement)("a", {
href: href,
className: "document-outline__button",
onClick: onSelect
}, (0,external_wp_element_namespaceObject.createElement)("span", {
className: "document-outline__emdash",
"aria-hidden": "true"
}), (0,external_wp_element_namespaceObject.createElement)("strong", {
className: "document-outline__level"
}, level), (0,external_wp_element_namespaceObject.createElement)("span", {
className: "document-outline__item-content"
}, children)));
};
/* harmony default export */ var document_outline_item = (TableOfContentsItem);
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/document-outline/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Module constants
*/
const emptyHeadingContent = (0,external_wp_element_namespaceObject.createElement)("em", null, (0,external_wp_i18n_namespaceObject.__)('(Empty heading)'));
const incorrectLevelContent = [(0,external_wp_element_namespaceObject.createElement)("br", {
key: "incorrect-break"
}), (0,external_wp_element_namespaceObject.createElement)("em", {
key: "incorrect-message"
}, (0,external_wp_i18n_namespaceObject.__)('(Incorrect heading level)'))];
const singleH1Headings = [(0,external_wp_element_namespaceObject.createElement)("br", {
key: "incorrect-break-h1"
}), (0,external_wp_element_namespaceObject.createElement)("em", {
key: "incorrect-message-h1"
}, (0,external_wp_i18n_namespaceObject.__)('(Your theme may already use a H1 for the post title)'))];
const multipleH1Headings = [(0,external_wp_element_namespaceObject.createElement)("br", {
key: "incorrect-break-multiple-h1"
}), (0,external_wp_element_namespaceObject.createElement)("em", {
key: "incorrect-message-multiple-h1"
}, (0,external_wp_i18n_namespaceObject.__)('(Multiple H1 headings are not recommended)'))];
/**
* Returns an array of heading blocks enhanced with the following properties:
* level - An integer with the heading level.
* isEmpty - Flag indicating if the heading has no content.
*
* @param {?Array} blocks An array of blocks.
*
* @return {Array} An array of heading blocks enhanced with the properties described above.
*/
const computeOutlineHeadings = function () {
let blocks = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
return blocks.flatMap(function () {
let block = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (block.name === 'core/heading') {
return { ...block,
level: block.attributes.level,
isEmpty: isEmptyHeading(block)
};
}
return computeOutlineHeadings(block.innerBlocks);
});
};
const isEmptyHeading = heading => !heading.attributes.content || heading.attributes.content.length === 0;
const DocumentOutline = _ref => {
let {
blocks = [],
title,
onSelect,
isTitleSupported,
hasOutlineItemsDisabled
} = _ref;
const headings = computeOutlineHeadings(blocks);
if (headings.length < 1) {
return null;
}
let prevHeadingLevel = 1; // Not great but it's the simplest way to locate the title right now.
const titleNode = document.querySelector('.editor-post-title__input');
const hasTitle = isTitleSupported && title && titleNode;
const countByLevel = headings.reduce((acc, heading) => ({ ...acc,
[heading.level]: (acc[heading.level] || 0) + 1
}), {});
const hasMultipleH1 = countByLevel[1] > 1;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "document-outline"
}, (0,external_wp_element_namespaceObject.createElement)("ul", null, hasTitle && (0,external_wp_element_namespaceObject.createElement)(document_outline_item, {
level: (0,external_wp_i18n_namespaceObject.__)('Title'),
isValid: true,
onSelect: onSelect,
href: `#${titleNode.id}`,
isDisabled: hasOutlineItemsDisabled
}, title), headings.map((item, index) => {
// Headings remain the same, go up by one, or down by any amount.
// Otherwise there are missing levels.
const isIncorrectLevel = item.level > prevHeadingLevel + 1;
const isValid = !item.isEmpty && !isIncorrectLevel && !!item.level && (item.level !== 1 || !hasMultipleH1 && !hasTitle);
prevHeadingLevel = item.level;
return (0,external_wp_element_namespaceObject.createElement)(document_outline_item, {
key: index,
level: `H${item.level}`,
isValid: isValid,
isDisabled: hasOutlineItemsDisabled,
href: `#block-${item.clientId}`,
onSelect: onSelect
}, item.isEmpty ? emptyHeadingContent : (0,external_wp_richText_namespaceObject.getTextContent)((0,external_wp_richText_namespaceObject.create)({
html: item.attributes.content
})), isIncorrectLevel && incorrectLevelContent, item.level === 1 && hasMultipleH1 && multipleH1Headings, hasTitle && item.level === 1 && !hasMultipleH1 && singleH1Headings);
})));
};
/* harmony default export */ var document_outline = ((0,external_wp_compose_namespaceObject.compose)((0,external_wp_data_namespaceObject.withSelect)(select => {
var _postType$supports$ti, _postType$supports;
const {
getBlocks
} = select(external_wp_blockEditor_namespaceObject.store);
const {
getEditedPostAttribute
} = select(store_store);
const {
getPostType
} = select(external_wp_coreData_namespaceObject.store);
const postType = getPostType(getEditedPostAttribute('type'));
return {
title: getEditedPostAttribute('title'),
blocks: getBlocks(),
isTitleSupported: (_postType$supports$ti = postType === null || postType === void 0 ? void 0 : (_postType$supports = postType.supports) === null || _postType$supports === void 0 ? void 0 : _postType$supports.title) !== null && _postType$supports$ti !== void 0 ? _postType$supports$ti : false
};
}))(DocumentOutline));
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/document-outline/check.js
/**
* WordPress dependencies
*/
function DocumentOutlineCheck(_ref) {
let {
blocks,
children
} = _ref;
const headings = blocks.filter(block => block.name === 'core/heading');
if (headings.length < 1) {
return null;
}
return children;
}
/* harmony default export */ var check = ((0,external_wp_data_namespaceObject.withSelect)(select => ({
blocks: select(external_wp_blockEditor_namespaceObject.store).getBlocks()
}))(DocumentOutlineCheck));
;// CONCATENATED MODULE: external ["wp","keyboardShortcuts"]
var external_wp_keyboardShortcuts_namespaceObject = window["wp"]["keyboardShortcuts"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/global-keyboard-shortcuts/save-shortcut.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function SaveShortcut(_ref) {
let {
resetBlocksOnSave
} = _ref;
const {
resetEditorBlocks,
savePost
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const {
isEditedPostDirty,
getPostEdits,
isPostSavingLocked
} = (0,external_wp_data_namespaceObject.useSelect)(store_store);
(0,external_wp_keyboardShortcuts_namespaceObject.useShortcut)('core/editor/save', event => {
event.preventDefault();
/**
* Do not save the post if post saving is locked.
*/
if (isPostSavingLocked()) {
return;
} // TODO: This should be handled in the `savePost` effect in
// considering `isSaveable`. See note on `isEditedPostSaveable`
// selector about dirtiness and meta-boxes.
//
// See: `isEditedPostSaveable`
if (!isEditedPostDirty()) {
return;
} // The text editor requires that editor blocks are updated for a
// save to work correctly. Usually this happens when the textarea
// for the code editors blurs, but the shortcut can be used without
// blurring the textarea.
if (resetBlocksOnSave) {
const postEdits = getPostEdits();
if (postEdits.content && typeof postEdits.content === 'string') {
const blocks = (0,external_wp_blocks_namespaceObject.parse)(postEdits.content);
resetEditorBlocks(blocks);
}
}
savePost();
});
return null;
}
/* harmony default export */ var save_shortcut = (SaveShortcut);
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/global-keyboard-shortcuts/visual-editor-shortcuts.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function VisualEditorGlobalKeyboardShortcuts() {
const {
redo,
undo
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
(0,external_wp_keyboardShortcuts_namespaceObject.useShortcut)('core/editor/undo', event => {
undo();
event.preventDefault();
});
(0,external_wp_keyboardShortcuts_namespaceObject.useShortcut)('core/editor/redo', event => {
redo();
event.preventDefault();
});
return (0,external_wp_element_namespaceObject.createElement)(save_shortcut, null);
}
/* harmony default export */ var visual_editor_shortcuts = (VisualEditorGlobalKeyboardShortcuts);
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/global-keyboard-shortcuts/text-editor-shortcuts.js
/**
* Internal dependencies
*/
function TextEditorGlobalKeyboardShortcuts() {
return (0,external_wp_element_namespaceObject.createElement)(save_shortcut, {
resetBlocksOnSave: true
});
}
;// CONCATENATED MODULE: external ["wp","keycodes"]
var external_wp_keycodes_namespaceObject = window["wp"]["keycodes"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/global-keyboard-shortcuts/register-shortcuts.js
/**
* WordPress dependencies
*/
function EditorKeyboardShortcutsRegister() {
// Registering the shortcuts.
const {
registerShortcut
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_keyboardShortcuts_namespaceObject.store);
(0,external_wp_element_namespaceObject.useEffect)(() => {
registerShortcut({
name: 'core/editor/save',
category: 'global',
description: (0,external_wp_i18n_namespaceObject.__)('Save your changes.'),
keyCombination: {
modifier: 'primary',
character: 's'
}
});
registerShortcut({
name: 'core/editor/undo',
category: 'global',
description: (0,external_wp_i18n_namespaceObject.__)('Undo your last changes.'),
keyCombination: {
modifier: 'primary',
character: 'z'
}
});
registerShortcut({
name: 'core/editor/redo',
category: 'global',
description: (0,external_wp_i18n_namespaceObject.__)('Redo your last undo.'),
keyCombination: {
modifier: 'primaryShift',
character: 'z'
},
// Disable on Apple OS because it conflicts with the browser's
// history shortcut. It's a fine alias for both Windows and Linux.
// Since there's no conflict for Ctrl+Shift+Z on both Windows and
// Linux, we keep it as the default for consistency.
aliases: (0,external_wp_keycodes_namespaceObject.isAppleOS)() ? [] : [{
modifier: 'primary',
character: 'y'
}]
});
}, [registerShortcut]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.BlockEditorKeyboardShortcuts.Register, null);
}
/* harmony default export */ var register_shortcuts = (EditorKeyboardShortcutsRegister);
;// CONCATENATED MODULE: external ["wp","components"]
var external_wp_components_namespaceObject = window["wp"]["components"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/redo.js
/**
* WordPress dependencies
*/
const redo_redo = (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: "M15.6 6.5l-1.1 1 2.9 3.3H8c-.9 0-1.7.3-2.3.9-1.4 1.5-1.4 4.2-1.4 5.6v.2h1.5v-.3c0-1.1 0-3.5 1-4.5.3-.3.7-.5 1.3-.5h9.2L14.5 15l1.1 1.1 4.6-4.6-4.6-5z"
}));
/* harmony default export */ var library_redo = (redo_redo);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/undo.js
/**
* WordPress dependencies
*/
const undo_undo = (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: "M18.3 11.7c-.6-.6-1.4-.9-2.3-.9H6.7l2.9-3.3-1.1-1-4.5 5L8.5 16l1-1-2.7-2.7H16c.5 0 .9.2 1.3.5 1 1 1 3.4 1 4.5v.3h1.5v-.2c0-1.5 0-4.3-1.5-5.7z"
}));
/* harmony default export */ var library_undo = (undo_undo);
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/editor-history/redo.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function EditorHistoryRedo(props, ref) {
const shortcut = (0,external_wp_keycodes_namespaceObject.isAppleOS)() ? external_wp_keycodes_namespaceObject.displayShortcut.primaryShift('z') : external_wp_keycodes_namespaceObject.displayShortcut.primary('y');
const hasRedo = (0,external_wp_data_namespaceObject.useSelect)(select => select(store_store).hasEditorRedo(), []);
const {
redo
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, _extends({}, props, {
ref: ref,
icon: !(0,external_wp_i18n_namespaceObject.isRTL)() ? library_redo : library_undo
/* translators: button label text should, if possible, be under 16 characters. */
,
label: (0,external_wp_i18n_namespaceObject.__)('Redo'),
shortcut: shortcut // If there are no redo levels we don't want to actually disable this
// button, because it will remove focus for keyboard users.
// See: https://github.com/WordPress/gutenberg/issues/3486
,
"aria-disabled": !hasRedo,
onClick: hasRedo ? redo : undefined,
className: "editor-history__redo"
}));
}
/* harmony default export */ var editor_history_redo = ((0,external_wp_element_namespaceObject.forwardRef)(EditorHistoryRedo));
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/editor-history/undo.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function EditorHistoryUndo(props, ref) {
const hasUndo = (0,external_wp_data_namespaceObject.useSelect)(select => select(store_store).hasEditorUndo(), []);
const {
undo
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, _extends({}, props, {
ref: ref,
icon: !(0,external_wp_i18n_namespaceObject.isRTL)() ? library_undo : library_redo
/* translators: button label text should, if possible, be under 16 characters. */
,
label: (0,external_wp_i18n_namespaceObject.__)('Undo'),
shortcut: external_wp_keycodes_namespaceObject.displayShortcut.primary('z') // If there are no undo levels we don't want to actually disable this
// button, because it will remove focus for keyboard users.
// See: https://github.com/WordPress/gutenberg/issues/3486
,
"aria-disabled": !hasUndo,
onClick: hasUndo ? undo : undefined,
className: "editor-history__undo"
}));
}
/* harmony default export */ var editor_history_undo = ((0,external_wp_element_namespaceObject.forwardRef)(EditorHistoryUndo));
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/template-validation-notice/index.js
/**
* WordPress dependencies
*/
function TemplateValidationNotice(_ref) {
let {
isValid,
...props
} = _ref;
if (isValid) {
return null;
}
const confirmSynchronization = () => {
if ( // eslint-disable-next-line no-alert
window.confirm((0,external_wp_i18n_namespaceObject.__)('Resetting the template may result in loss of content, do you want to continue?'))) {
props.synchronizeTemplate();
}
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Notice, {
className: "editor-template-validation-notice",
isDismissible: false,
status: "warning",
actions: [{
label: (0,external_wp_i18n_namespaceObject.__)('Keep it as is'),
onClick: props.resetTemplateValidity
}, {
label: (0,external_wp_i18n_namespaceObject.__)('Reset the template'),
onClick: confirmSynchronization
}]
}, (0,external_wp_i18n_namespaceObject.__)('The content of your post doesn’t match the template assigned to your post type.'));
}
/* harmony default export */ var template_validation_notice = ((0,external_wp_compose_namespaceObject.compose)([(0,external_wp_data_namespaceObject.withSelect)(select => ({
isValid: select(external_wp_blockEditor_namespaceObject.store).isValidTemplate()
})), (0,external_wp_data_namespaceObject.withDispatch)(dispatch => {
const {
setTemplateValidity,
synchronizeTemplate
} = dispatch(external_wp_blockEditor_namespaceObject.store);
return {
resetTemplateValidity: () => setTemplateValidity(true),
synchronizeTemplate
};
})])(TemplateValidationNotice));
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/editor-notices/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function EditorNotices(_ref) {
let {
notices,
onRemove
} = _ref;
const dismissibleNotices = notices.filter(_ref2 => {
let {
isDismissible,
type
} = _ref2;
return isDismissible && type === 'default';
});
const nonDismissibleNotices = notices.filter(_ref3 => {
let {
isDismissible,
type
} = _ref3;
return !isDismissible && type === 'default';
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.NoticeList, {
notices: nonDismissibleNotices,
className: "components-editor-notices__pinned"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.NoticeList, {
notices: dismissibleNotices,
className: "components-editor-notices__dismissible",
onRemove: onRemove
}, (0,external_wp_element_namespaceObject.createElement)(template_validation_notice, null)));
}
/* harmony default export */ var editor_notices = ((0,external_wp_compose_namespaceObject.compose)([(0,external_wp_data_namespaceObject.withSelect)(select => ({
notices: select(external_wp_notices_namespaceObject.store).getNotices()
})), (0,external_wp_data_namespaceObject.withDispatch)(dispatch => ({
onRemove: dispatch(external_wp_notices_namespaceObject.store).removeNotice
}))])(EditorNotices));
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/editor-snackbars/index.js
/**
* WordPress dependencies
*/
function EditorSnackbars() {
const notices = (0,external_wp_data_namespaceObject.useSelect)(select => select(external_wp_notices_namespaceObject.store).getNotices(), []);
const {
removeNotice
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_notices_namespaceObject.store);
const snackbarNotices = notices.filter(_ref => {
let {
type
} = _ref;
return type === 'snackbar';
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SnackbarList, {
notices: snackbarNotices,
className: "components-editor-notices__snackbar",
onRemove: removeNotice
});
}
;// CONCATENATED MODULE: external ["wp","htmlEntities"]
var external_wp_htmlEntities_namespaceObject = window["wp"]["htmlEntities"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/entities-saved-states/entity-record-item.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function EntityRecordItem(_ref) {
let {
record,
checked,
onChange,
closePanel
} = _ref;
const {
name,
kind,
title,
key
} = record;
const parentBlockId = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _blocks$;
// Get entity's blocks.
const {
blocks = []
} = select(external_wp_coreData_namespaceObject.store).getEditedEntityRecord(kind, name, key); // Get parents of the entity's first block.
const parents = select(external_wp_blockEditor_namespaceObject.store).getBlockParents((_blocks$ = blocks[0]) === null || _blocks$ === void 0 ? void 0 : _blocks$.clientId); // Return closest parent block's clientId.
return parents[parents.length - 1];
}, []); // Handle templates that might use default descriptive titles.
const entityRecordTitle = (0,external_wp_data_namespaceObject.useSelect)(select => {
if ('postType' !== kind || 'wp_template' !== name) {
return title;
}
const template = select(external_wp_coreData_namespaceObject.store).getEditedEntityRecord(kind, name, key);
return select(store_store).__experimentalGetTemplateInfo(template).title;
}, [name, kind, title, key]);
const isSelected = (0,external_wp_data_namespaceObject.useSelect)(select => {
const selectedBlockId = select(external_wp_blockEditor_namespaceObject.store).getSelectedBlockClientId();
return selectedBlockId === parentBlockId;
}, [parentBlockId]);
const isSelectedText = isSelected ? (0,external_wp_i18n_namespaceObject.__)('Selected') : (0,external_wp_i18n_namespaceObject.__)('Select');
const {
selectBlock
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_blockEditor_namespaceObject.store);
const selectParentBlock = (0,external_wp_element_namespaceObject.useCallback)(() => selectBlock(parentBlockId), [parentBlockId]);
const selectAndDismiss = (0,external_wp_element_namespaceObject.useCallback)(() => {
selectBlock(parentBlockId);
closePanel();
}, [parentBlockId]);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelRow, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.CheckboxControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_element_namespaceObject.createElement)("strong", null, (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(entityRecordTitle) || (0,external_wp_i18n_namespaceObject.__)('Untitled')),
checked: checked,
onChange: onChange
}), parentBlockId ? (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
onClick: selectParentBlock,
className: "entities-saved-states__find-entity",
disabled: isSelected
}, isSelectedText), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
onClick: selectAndDismiss,
className: "entities-saved-states__find-entity-small",
disabled: isSelected
}, isSelectedText)) : null);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/entities-saved-states/entity-type-list.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function getEntityDescription(entity, count) {
switch (entity) {
case 'site':
return 1 === count ? (0,external_wp_i18n_namespaceObject.__)('This change will affect your whole site.') : (0,external_wp_i18n_namespaceObject.__)('These changes will affect your whole site.');
case 'wp_template':
return (0,external_wp_i18n_namespaceObject.__)('This change will affect pages and posts that use this template.');
case 'page':
case 'post':
return (0,external_wp_i18n_namespaceObject.__)('The following content has been modified.');
}
}
function EntityTypeList(_ref) {
let {
list,
unselectedEntities,
setUnselectedEntities,
closePanel
} = _ref;
const count = list.length;
const firstRecord = list[0];
const entityConfig = (0,external_wp_data_namespaceObject.useSelect)(select => select(external_wp_coreData_namespaceObject.store).getEntityConfig(firstRecord.kind, firstRecord.name), [firstRecord.kind, firstRecord.name]);
const {
name
} = firstRecord;
let entityLabel = entityConfig.label;
if (name === 'wp_template_part') {
entityLabel = 1 === count ? (0,external_wp_i18n_namespaceObject.__)('Template Part') : (0,external_wp_i18n_namespaceObject.__)('Template Parts');
} // Set description based on type of entity.
const description = getEntityDescription(name, count);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelBody, {
title: entityLabel,
initialOpen: true
}, description && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.PanelRow, null, description), list.map(record => {
return (0,external_wp_element_namespaceObject.createElement)(EntityRecordItem, {
key: record.key || record.property,
record: record,
checked: !unselectedEntities.some(elt => elt.kind === record.kind && elt.name === record.name && elt.key === record.key && elt.property === record.property),
onChange: value => setUnselectedEntities(record, value),
closePanel: closePanel
});
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/entities-saved-states/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const TRANSLATED_SITE_PROPERTIES = {
title: (0,external_wp_i18n_namespaceObject.__)('Title'),
description: (0,external_wp_i18n_namespaceObject.__)('Tagline'),
site_logo: (0,external_wp_i18n_namespaceObject.__)('Logo'),
site_icon: (0,external_wp_i18n_namespaceObject.__)('Icon'),
show_on_front: (0,external_wp_i18n_namespaceObject.__)('Show on front'),
page_on_front: (0,external_wp_i18n_namespaceObject.__)('Page on front')
};
const PUBLISH_ON_SAVE_ENTITIES = [{
kind: 'postType',
name: 'wp_navigation'
}];
function EntitiesSavedStates(_ref) {
let {
close
} = _ref;
const saveButtonRef = (0,external_wp_element_namespaceObject.useRef)();
const {
dirtyEntityRecords
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const dirtyRecords = select(external_wp_coreData_namespaceObject.store).__experimentalGetDirtyEntityRecords(); // Remove site object and decouple into its edited pieces.
const dirtyRecordsWithoutSite = dirtyRecords.filter(record => !(record.kind === 'root' && record.name === 'site'));
const siteEdits = select(external_wp_coreData_namespaceObject.store).getEntityRecordEdits('root', 'site');
const siteEditsAsEntities = [];
for (const property in siteEdits) {
siteEditsAsEntities.push({
kind: 'root',
name: 'site',
title: TRANSLATED_SITE_PROPERTIES[property] || property,
property
});
}
const dirtyRecordsWithSiteItems = [...dirtyRecordsWithoutSite, ...siteEditsAsEntities];
return {
dirtyEntityRecords: dirtyRecordsWithSiteItems
};
}, []);
const {
editEntityRecord,
saveEditedEntityRecord,
__experimentalSaveSpecifiedEntityEdits: saveSpecifiedEntityEdits
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_coreData_namespaceObject.store);
const {
__unstableMarkLastChangeAsPersistent
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_blockEditor_namespaceObject.store);
const {
createSuccessNotice,
createErrorNotice
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_notices_namespaceObject.store); // To group entities by type.
const partitionedSavables = (0,external_lodash_namespaceObject.groupBy)(dirtyEntityRecords, 'name'); // Sort entity groups.
const {
site: siteSavables,
wp_template: templateSavables,
wp_template_part: templatePartSavables,
...contentSavables
} = partitionedSavables;
const sortedPartitionedSavables = [siteSavables, templateSavables, templatePartSavables, ...Object.values(contentSavables)].filter(Array.isArray); // Unchecked entities to be ignored by save function.
const [unselectedEntities, _setUnselectedEntities] = (0,external_wp_element_namespaceObject.useState)([]);
const setUnselectedEntities = (_ref2, checked) => {
let {
kind,
name,
key,
property
} = _ref2;
if (checked) {
_setUnselectedEntities(unselectedEntities.filter(elt => elt.kind !== kind || elt.name !== name || elt.key !== key || elt.property !== property));
} else {
_setUnselectedEntities([...unselectedEntities, {
kind,
name,
key,
property
}]);
}
};
const saveCheckedEntities = () => {
const entitiesToSave = dirtyEntityRecords.filter(_ref3 => {
let {
kind,
name,
key,
property
} = _ref3;
return !unselectedEntities.some(elt => elt.kind === kind && elt.name === name && elt.key === key && elt.property === property);
});
close(entitiesToSave);
const siteItemsToSave = [];
const pendingSavedRecords = [];
entitiesToSave.forEach(_ref4 => {
let {
kind,
name,
key,
property
} = _ref4;
if ('root' === kind && 'site' === name) {
siteItemsToSave.push(property);
} else {
if (PUBLISH_ON_SAVE_ENTITIES.some(typeToPublish => typeToPublish.kind === kind && typeToPublish.name === name)) {
editEntityRecord(kind, name, key, {
status: 'publish'
});
}
pendingSavedRecords.push(saveEditedEntityRecord(kind, name, key));
}
});
if (siteItemsToSave.length) {
pendingSavedRecords.push(saveSpecifiedEntityEdits('root', 'site', undefined, siteItemsToSave));
}
__unstableMarkLastChangeAsPersistent();
Promise.all(pendingSavedRecords).then(values => {
if (values.some(value => typeof value === 'undefined')) {
createErrorNotice((0,external_wp_i18n_namespaceObject.__)('Saving failed.'));
} else {
createSuccessNotice((0,external_wp_i18n_namespaceObject.__)('Site updated.'), {
type: 'snackbar'
});
}
}).catch(error => createErrorNotice(`${(0,external_wp_i18n_namespaceObject.__)('Saving failed.')} ${error}`));
}; // Explicitly define this with no argument passed. Using `close` on
// its own will use the event object in place of the expected saved entities.
const dismissPanel = (0,external_wp_element_namespaceObject.useCallback)(() => close(), [close]);
const [saveDialogRef, saveDialogProps] = (0,external_wp_compose_namespaceObject.__experimentalUseDialog)({
onClose: () => dismissPanel()
});
return (0,external_wp_element_namespaceObject.createElement)("div", _extends({
ref: saveDialogRef
}, saveDialogProps, {
className: "entities-saved-states__panel"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Flex, {
className: "entities-saved-states__panel-header",
gap: 2
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexItem, {
isBlock: true,
as: external_wp_components_namespaceObject.Button,
ref: saveButtonRef,
variant: "primary",
disabled: dirtyEntityRecords.length - unselectedEntities.length === 0,
onClick: saveCheckedEntities,
className: "editor-entities-saved-states__save-button"
}, (0,external_wp_i18n_namespaceObject.__)('Save')), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexItem, {
isBlock: true,
as: external_wp_components_namespaceObject.Button,
variant: "secondary",
onClick: dismissPanel
}, (0,external_wp_i18n_namespaceObject.__)('Cancel'))), (0,external_wp_element_namespaceObject.createElement)("div", {
className: "entities-saved-states__text-prompt"
}, (0,external_wp_element_namespaceObject.createElement)("strong", null, (0,external_wp_i18n_namespaceObject.__)('Are you ready to save?')), (0,external_wp_element_namespaceObject.createElement)("p", null, (0,external_wp_i18n_namespaceObject.__)('The following changes have been made to your site, templates, and content.'))), sortedPartitionedSavables.map(list => {
return (0,external_wp_element_namespaceObject.createElement)(EntityTypeList, {
key: list[0].name,
list: list,
closePanel: dismissPanel,
unselectedEntities: unselectedEntities,
setUnselectedEntities: setUnselectedEntities
});
}));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/error-boundary/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function getContent() {
try {
// While `select` in a component is generally discouraged, it is
// used here because it (a) reduces the chance of data loss in the
// case of additional errors by performing a direct retrieval and
// (b) avoids the performance cost associated with unnecessary
// content serialization throughout the lifetime of a non-erroring
// application.
return (0,external_wp_data_namespaceObject.select)(store_store).getEditedPostContent();
} catch (error) {}
}
function CopyButton(_ref) {
let {
text,
children
} = _ref;
const ref = (0,external_wp_compose_namespaceObject.useCopyToClipboard)(text);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "secondary",
ref: ref
}, children);
}
class ErrorBoundary extends external_wp_element_namespaceObject.Component {
constructor() {
super(...arguments);
this.state = {
error: null
};
}
componentDidCatch(error) {
(0,external_wp_hooks_namespaceObject.doAction)('editor.ErrorBoundary.errorLogged', error);
}
static getDerivedStateFromError(error) {
return {
error
};
}
render() {
const {
error
} = this.state;
if (!error) {
return this.props.children;
}
const actions = [(0,external_wp_element_namespaceObject.createElement)(CopyButton, {
key: "copy-post",
text: getContent
}, (0,external_wp_i18n_namespaceObject.__)('Copy Post Text')), (0,external_wp_element_namespaceObject.createElement)(CopyButton, {
key: "copy-error",
text: error.stack
}, (0,external_wp_i18n_namespaceObject.__)('Copy Error'))];
return (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.Warning, {
className: "editor-error-boundary",
actions: actions
}, (0,external_wp_i18n_namespaceObject.__)('The editor has encountered an unexpected error.'));
}
}
/* harmony default export */ var error_boundary = (ErrorBoundary);
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/local-autosave-monitor/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const requestIdleCallback = window.requestIdleCallback ? window.requestIdleCallback : window.requestAnimationFrame;
let hasStorageSupport;
/**
* Function which returns true if the current environment supports browser
* sessionStorage, or false otherwise. The result of this function is cached and
* reused in subsequent invocations.
*/
const hasSessionStorageSupport = () => {
if (hasStorageSupport !== undefined) {
return hasStorageSupport;
}
try {
// Private Browsing in Safari 10 and earlier will throw an error when
// attempting to set into sessionStorage. The test here is intentional in
// causing a thrown error as condition bailing from local autosave.
window.sessionStorage.setItem('__wpEditorTestSessionStorage', '');
window.sessionStorage.removeItem('__wpEditorTestSessionStorage');
hasStorageSupport = true;
} catch {
hasStorageSupport = false;
}
return hasStorageSupport;
};
/**
* Custom hook which manages the creation of a notice prompting the user to
* restore a local autosave, if one exists.
*/
function useAutosaveNotice() {
const {
postId,
isEditedPostNew,
hasRemoteAutosave
} = (0,external_wp_data_namespaceObject.useSelect)(select => ({
postId: select(store_store).getCurrentPostId(),
isEditedPostNew: select(store_store).isEditedPostNew(),
hasRemoteAutosave: !!select(store_store).getEditorSettings().autosave
}), []);
const {
getEditedPostAttribute
} = (0,external_wp_data_namespaceObject.useSelect)(store_store);
const {
createWarningNotice,
removeNotice
} = (0,external_wp_data_namespaceObject.useDispatch)(external_wp_notices_namespaceObject.store);
const {
editPost,
resetEditorBlocks
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
(0,external_wp_element_namespaceObject.useEffect)(() => {
let localAutosave = localAutosaveGet(postId, isEditedPostNew);
if (!localAutosave) {
return;
}
try {
localAutosave = JSON.parse(localAutosave);
} catch {
// Not usable if it can't be parsed.
return;
}
const {
post_title: title,
content,
excerpt
} = localAutosave;
const edits = {
title,
content,
excerpt
};
{
// Only display a notice if there is a difference between what has been
// saved and that which is stored in sessionStorage.
const hasDifference = Object.keys(edits).some(key => {
return edits[key] !== getEditedPostAttribute(key);
});
if (!hasDifference) {
// If there is no difference, it can be safely ejected from storage.
localAutosaveClear(postId, isEditedPostNew);
return;
}
}
if (hasRemoteAutosave) {
return;
}
const id = 'wpEditorAutosaveRestore';
createWarningNotice((0,external_wp_i18n_namespaceObject.__)('The backup of this post in your browser is different from the version below.'), {
id,
actions: [{
label: (0,external_wp_i18n_namespaceObject.__)('Restore the backup'),
onClick() {
const {
content: editsContent,
...editsWithoutContent
} = edits;
editPost(editsWithoutContent);
resetEditorBlocks((0,external_wp_blocks_namespaceObject.parse)(edits.content));
removeNotice(id);
}
}]
});
}, [isEditedPostNew, postId]);
}
/**
* Custom hook which ejects a local autosave after a successful save occurs.
*/
function useAutosavePurge() {
const {
postId,
isEditedPostNew,
isDirty,
isAutosaving,
didError
} = (0,external_wp_data_namespaceObject.useSelect)(select => ({
postId: select(store_store).getCurrentPostId(),
isEditedPostNew: select(store_store).isEditedPostNew(),
isDirty: select(store_store).isEditedPostDirty(),
isAutosaving: select(store_store).isAutosavingPost(),
didError: select(store_store).didPostSaveRequestFail()
}), []);
const lastIsDirty = (0,external_wp_element_namespaceObject.useRef)(isDirty);
const lastIsAutosaving = (0,external_wp_element_namespaceObject.useRef)(isAutosaving);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (!didError && (lastIsAutosaving.current && !isAutosaving || lastIsDirty.current && !isDirty)) {
localAutosaveClear(postId, isEditedPostNew);
}
lastIsDirty.current = isDirty;
lastIsAutosaving.current = isAutosaving;
}, [isDirty, isAutosaving, didError]); // Once the isEditedPostNew changes from true to false, let's clear the auto-draft autosave.
const wasEditedPostNew = (0,external_wp_compose_namespaceObject.usePrevious)(isEditedPostNew);
const prevPostId = (0,external_wp_compose_namespaceObject.usePrevious)(postId);
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (prevPostId === postId && wasEditedPostNew && !isEditedPostNew) {
localAutosaveClear(postId, true);
}
}, [isEditedPostNew, postId]);
}
function LocalAutosaveMonitor() {
const {
autosave
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const deferredAutosave = (0,external_wp_element_namespaceObject.useCallback)(() => {
requestIdleCallback(() => autosave({
local: true
}));
}, []);
useAutosaveNotice();
useAutosavePurge();
const localAutosaveInterval = (0,external_wp_data_namespaceObject.useSelect)(select => select(store_store).getEditorSettings().localAutosaveInterval, []);
return (0,external_wp_element_namespaceObject.createElement)(autosave_monitor, {
interval: localAutosaveInterval,
autosave: deferredAutosave
});
}
/* harmony default export */ var local_autosave_monitor = ((0,external_wp_compose_namespaceObject.ifCondition)(hasSessionStorageSupport)(LocalAutosaveMonitor));
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/page-attributes/check.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PageAttributesCheck(_ref) {
let {
children
} = _ref;
const postType = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getEditedPostAttribute
} = select(store_store);
const {
getPostType
} = select(external_wp_coreData_namespaceObject.store);
return getPostType(getEditedPostAttribute('type'));
}, []);
const supportsPageAttributes = (0,external_lodash_namespaceObject.get)(postType, ['supports', 'page-attributes'], false); // Only render fields if post type supports page attributes or available templates exist.
if (!supportsPageAttributes) {
return null;
}
return children;
}
/* harmony default export */ var page_attributes_check = (PageAttributesCheck);
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-type-support-check/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* A component which renders its own children only if the current editor post
* type supports one of the given `supportKeys` prop.
*
* @param {Object} props Props.
* @param {string} [props.postType] Current post type.
* @param {WPElement} props.children Children to be rendered if post
* type supports.
* @param {(string|string[])} props.supportKeys String or string array of keys
* to test.
*
* @return {WPComponent} The component to be rendered.
*/
function PostTypeSupportCheck(_ref) {
let {
postType,
children,
supportKeys
} = _ref;
let isSupported = true;
if (postType) {
isSupported = (Array.isArray(supportKeys) ? supportKeys : [supportKeys]).some(key => !!postType.supports[key]);
}
if (!isSupported) {
return null;
}
return children;
}
/* harmony default export */ var post_type_support_check = ((0,external_wp_data_namespaceObject.withSelect)(select => {
const {
getEditedPostAttribute
} = select(store_store);
const {
getPostType
} = select(external_wp_coreData_namespaceObject.store);
return {
postType: getPostType(getEditedPostAttribute('type'))
};
})(PostTypeSupportCheck));
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/page-attributes/order.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const PageAttributesOrder = _ref => {
let {
onUpdateOrder,
order = 0
} = _ref;
const [orderInput, setOrderInput] = (0,external_wp_element_namespaceObject.useState)(null);
const setUpdatedOrder = value => {
var _value$trim;
setOrderInput(value);
const newOrder = Number(value);
if (Number.isInteger(newOrder) && ((_value$trim = value.trim) === null || _value$trim === void 0 ? void 0 : _value$trim.call(value)) !== '') {
onUpdateOrder(Number(value));
}
};
const value = orderInput === null ? order : orderInput;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.TextControl, {
className: "editor-page-attributes__order",
type: "number",
label: (0,external_wp_i18n_namespaceObject.__)('Order'),
value: value,
onChange: setUpdatedOrder,
size: 6,
onBlur: () => {
setOrderInput(null);
}
});
};
function PageAttributesOrderWithChecks(props) {
return (0,external_wp_element_namespaceObject.createElement)(post_type_support_check, {
supportKeys: "page-attributes"
}, (0,external_wp_element_namespaceObject.createElement)(PageAttributesOrder, props));
}
/* harmony default export */ var order = ((0,external_wp_compose_namespaceObject.compose)([(0,external_wp_data_namespaceObject.withSelect)(select => {
return {
order: select(store_store).getEditedPostAttribute('menu_order')
};
}), (0,external_wp_data_namespaceObject.withDispatch)(dispatch => ({
onUpdateOrder(order) {
dispatch(store_store).editPost({
menu_order: order
});
}
}))])(PageAttributesOrderWithChecks));
// EXTERNAL MODULE: ./node_modules/remove-accents/index.js
var remove_accents = __webpack_require__(4793);
var remove_accents_default = /*#__PURE__*/__webpack_require__.n(remove_accents);
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/utils/terms.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Returns terms in a tree form.
*
* @param {Array} flatTerms Array of terms in flat format.
*
* @return {Array} Array of terms in tree format.
*/
function buildTermsTree(flatTerms) {
const flatTermsWithParentAndChildren = flatTerms.map(term => {
return {
children: [],
parent: null,
...term
};
});
const termsByParent = (0,external_lodash_namespaceObject.groupBy)(flatTermsWithParentAndChildren, 'parent');
if (termsByParent.null && termsByParent.null.length) {
return flatTermsWithParentAndChildren;
}
const fillWithChildren = terms => {
return terms.map(term => {
const children = termsByParent[term.id];
return { ...term,
children: children && children.length ? fillWithChildren(children) : []
};
});
};
return fillWithChildren(termsByParent['0'] || []);
}
const unescapeString = arg => {
return (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(arg);
};
/**
* Returns a term object with name unescaped.
*
* @param {Object} term The term object to unescape.
*
* @return {Object} Term object with name property unescaped.
*/
const unescapeTerm = term => {
return { ...term,
name: unescapeString(term.name)
};
};
/**
* Returns an array of term objects with names unescaped.
* The unescape of each term is performed using the unescapeTerm function.
*
* @param {Object[]} terms Array of term objects to unescape.
*
* @return {Object[]} Array of term objects unescaped.
*/
const unescapeTerms = terms => {
return (terms !== null && terms !== void 0 ? terms : []).map(unescapeTerm);
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/page-attributes/parent.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function getTitle(post) {
var _post$title;
return post !== null && post !== void 0 && (_post$title = post.title) !== null && _post$title !== void 0 && _post$title.rendered ? (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(post.title.rendered) : `#${post.id} (${(0,external_wp_i18n_namespaceObject.__)('no title')})`;
}
const getItemPriority = (name, searchValue) => {
const normalizedName = remove_accents_default()(name || '').toLowerCase();
const normalizedSearch = remove_accents_default()(searchValue || '').toLowerCase();
if (normalizedName === normalizedSearch) {
return 0;
}
if (normalizedName.startsWith(normalizedSearch)) {
return normalizedName.length;
}
return Infinity;
};
function PageAttributesParent() {
const {
editPost
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const [fieldValue, setFieldValue] = (0,external_wp_element_namespaceObject.useState)(false);
const {
parentPost,
parentPostId,
items,
postType
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getPostType,
getEntityRecords,
getEntityRecord
} = select(external_wp_coreData_namespaceObject.store);
const {
getCurrentPostId,
getEditedPostAttribute
} = select(store_store);
const postTypeSlug = getEditedPostAttribute('type');
const pageId = getEditedPostAttribute('parent');
const pType = getPostType(postTypeSlug);
const postId = getCurrentPostId();
const isHierarchical = (0,external_lodash_namespaceObject.get)(pType, ['hierarchical'], false);
const query = {
per_page: 100,
exclude: postId,
parent_exclude: postId,
orderby: 'menu_order',
order: 'asc',
_fields: 'id,title,parent'
}; // Perform a search when the field is changed.
if (!!fieldValue) {
query.search = fieldValue;
}
return {
parentPostId: pageId,
parentPost: pageId ? getEntityRecord('postType', postTypeSlug, pageId) : null,
items: isHierarchical ? getEntityRecords('postType', postTypeSlug, query) : [],
postType: pType
};
}, [fieldValue]);
const isHierarchical = (0,external_lodash_namespaceObject.get)(postType, ['hierarchical'], false);
const parentPageLabel = (0,external_lodash_namespaceObject.get)(postType, ['labels', 'parent_item_colon']);
const pageItems = items || [];
const parentOptions = (0,external_wp_element_namespaceObject.useMemo)(() => {
const getOptionsFromTree = function (tree) {
let level = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
const mappedNodes = tree.map(treeNode => [{
value: treeNode.id,
label: '— '.repeat(level) + (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(treeNode.name),
rawName: treeNode.name
}, ...getOptionsFromTree(treeNode.children || [], level + 1)]);
const sortedNodes = mappedNodes.sort((_ref, _ref2) => {
let [a] = _ref;
let [b] = _ref2;
const priorityA = getItemPriority(a.rawName, fieldValue);
const priorityB = getItemPriority(b.rawName, fieldValue);
return priorityA >= priorityB ? 1 : -1;
});
return sortedNodes.flat();
};
let tree = pageItems.map(item => ({
id: item.id,
parent: item.parent,
name: getTitle(item)
})); // Only build a hierarchical tree when not searching.
if (!fieldValue) {
tree = buildTermsTree(tree);
}
const opts = getOptionsFromTree(tree); // Ensure the current parent is in the options list.
const optsHasParent = opts.find(item => item.value === parentPostId);
if (parentPost && !optsHasParent) {
opts.unshift({
value: parentPostId,
label: getTitle(parentPost)
});
}
return opts;
}, [pageItems, fieldValue]);
if (!isHierarchical || !parentPageLabel) {
return null;
}
/**
* Handle user input.
*
* @param {string} inputValue The current value of the input field.
*/
const handleKeydown = inputValue => {
setFieldValue(inputValue);
};
/**
* Handle author selection.
*
* @param {Object} selectedPostId The selected Author.
*/
const handleChange = selectedPostId => {
editPost({
parent: selectedPostId
});
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ComboboxControl, {
__nextHasNoMarginBottom: true,
className: "editor-page-attributes__parent",
label: parentPageLabel,
value: parentPostId,
options: parentOptions,
onFilterValueChange: (0,external_wp_compose_namespaceObject.debounce)(handleKeydown, 300),
onChange: handleChange
});
}
/* harmony default export */ var page_attributes_parent = (PageAttributesParent);
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-template/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PostTemplate() {
const {
availableTemplates,
selectedTemplate,
isViewable
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
var _getPostType$viewable, _getPostType;
const {
getEditedPostAttribute,
getEditorSettings,
getCurrentPostType
} = select(store_store);
const {
getPostType
} = select(external_wp_coreData_namespaceObject.store);
return {
selectedTemplate: getEditedPostAttribute('template'),
availableTemplates: getEditorSettings().availableTemplates,
isViewable: (_getPostType$viewable = (_getPostType = getPostType(getCurrentPostType())) === null || _getPostType === void 0 ? void 0 : _getPostType.viewable) !== null && _getPostType$viewable !== void 0 ? _getPostType$viewable : false
};
}, []);
const {
editPost
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
if (!isViewable || (0,external_lodash_namespaceObject.isEmpty)(availableTemplates)) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SelectControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Template:'),
value: selectedTemplate,
onChange: templateSlug => {
editPost({
template: templateSlug || ''
});
},
options: Object.entries(availableTemplates !== null && availableTemplates !== void 0 ? availableTemplates : {}).map(_ref => {
let [templateSlug, templateName] = _ref;
return {
value: templateSlug,
label: templateName
};
})
});
}
/* harmony default export */ var post_template = (PostTemplate);
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-author/constants.js
const AUTHORS_QUERY = {
who: 'authors',
per_page: 50,
_fields: 'id,name',
context: 'view' // Allows non-admins to perform requests.
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-author/combobox.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PostAuthorCombobox() {
const [fieldValue, setFieldValue] = (0,external_wp_element_namespaceObject.useState)();
const {
authorId,
isLoading,
authors,
postAuthor
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getUser,
getUsers,
isResolving
} = select(external_wp_coreData_namespaceObject.store);
const {
getEditedPostAttribute
} = select(store_store);
const author = getUser(getEditedPostAttribute('author'), {
context: 'view'
});
const query = { ...AUTHORS_QUERY
};
if (fieldValue) {
query.search = fieldValue;
}
return {
authorId: getEditedPostAttribute('author'),
postAuthor: author,
authors: getUsers(query),
isLoading: isResolving('core', 'getUsers', [query])
};
}, [fieldValue]);
const {
editPost
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const authorOptions = (0,external_wp_element_namespaceObject.useMemo)(() => {
const fetchedAuthors = (authors !== null && authors !== void 0 ? authors : []).map(author => {
return {
value: author.id,
label: (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(author.name)
};
}); // Ensure the current author is included in the dropdown list.
const foundAuthor = fetchedAuthors.findIndex(_ref => {
let {
value
} = _ref;
return (postAuthor === null || postAuthor === void 0 ? void 0 : postAuthor.id) === value;
});
if (foundAuthor < 0 && postAuthor) {
return [{
value: postAuthor.id,
label: (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(postAuthor.name)
}, ...fetchedAuthors];
}
return fetchedAuthors;
}, [authors, postAuthor]);
/**
* Handle author selection.
*
* @param {number} postAuthorId The selected Author.
*/
const handleSelect = postAuthorId => {
if (!postAuthorId) {
return;
}
editPost({
author: postAuthorId
});
};
/**
* Handle user input.
*
* @param {string} inputValue The current value of the input field.
*/
const handleKeydown = inputValue => {
setFieldValue(inputValue);
};
if (!postAuthor) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ComboboxControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Author'),
options: authorOptions,
value: authorId,
onFilterValueChange: (0,external_wp_compose_namespaceObject.debounce)(handleKeydown, 300),
onChange: handleSelect,
isLoading: isLoading,
allowReset: false
});
}
/* harmony default export */ var combobox = (PostAuthorCombobox);
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-author/select.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PostAuthorSelect() {
const {
editPost
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const {
postAuthor,
authors
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
return {
postAuthor: select(store_store).getEditedPostAttribute('author'),
authors: select(external_wp_coreData_namespaceObject.store).getUsers(AUTHORS_QUERY)
};
}, []);
const authorOptions = (0,external_wp_element_namespaceObject.useMemo)(() => {
return (authors !== null && authors !== void 0 ? authors : []).map(author => {
return {
value: author.id,
label: (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(author.name)
};
});
}, [authors]);
const setAuthorId = value => {
const author = Number(value);
editPost({
author
});
};
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SelectControl, {
__nextHasNoMarginBottom: true,
className: "post-author-selector",
label: (0,external_wp_i18n_namespaceObject.__)('Author'),
options: authorOptions,
onChange: setAuthorId,
value: postAuthor
});
}
/* harmony default export */ var post_author_select = (PostAuthorSelect);
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-author/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const minimumUsersForCombobox = 25;
function PostAuthor() {
const showCombobox = (0,external_wp_data_namespaceObject.useSelect)(select => {
const authors = select(external_wp_coreData_namespaceObject.store).getUsers(AUTHORS_QUERY);
return (authors === null || authors === void 0 ? void 0 : authors.length) >= minimumUsersForCombobox;
}, []);
if (showCombobox) {
return (0,external_wp_element_namespaceObject.createElement)(combobox, null);
}
return (0,external_wp_element_namespaceObject.createElement)(post_author_select, null);
}
/* harmony default export */ var post_author = (PostAuthor);
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-author/check.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PostAuthorCheck(_ref) {
let {
children
} = _ref;
const {
hasAssignAuthorAction,
hasAuthors
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const post = select(store_store).getCurrentPost();
const authors = select(external_wp_coreData_namespaceObject.store).getUsers(AUTHORS_QUERY);
return {
hasAssignAuthorAction: (0,external_lodash_namespaceObject.get)(post, ['_links', 'wp:action-assign-author'], false),
hasAuthors: (authors === null || authors === void 0 ? void 0 : authors.length) >= 1
};
}, []);
if (!hasAssignAuthorAction || !hasAuthors) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(post_type_support_check, {
supportKeys: "author"
}, children);
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-comments/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PostComments(_ref) {
let {
commentStatus = 'open',
...props
} = _ref;
const onToggleComments = () => props.editPost({
comment_status: commentStatus === 'open' ? 'closed' : 'open'
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.CheckboxControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Allow comments'),
checked: commentStatus === 'open',
onChange: onToggleComments
});
}
/* harmony default export */ var post_comments = ((0,external_wp_compose_namespaceObject.compose)([(0,external_wp_data_namespaceObject.withSelect)(select => {
return {
commentStatus: select(store_store).getEditedPostAttribute('comment_status')
};
}), (0,external_wp_data_namespaceObject.withDispatch)(dispatch => ({
editPost: dispatch(store_store).editPost
}))])(PostComments));
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-excerpt/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PostExcerpt(_ref) {
let {
excerpt,
onUpdateExcerpt
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "editor-post-excerpt"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.TextareaControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Write an excerpt (optional)'),
className: "editor-post-excerpt__textarea",
onChange: value => onUpdateExcerpt(value),
value: excerpt
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ExternalLink, {
href: (0,external_wp_i18n_namespaceObject.__)('https://wordpress.org/support/article/settings-sidebar/#excerpt')
}, (0,external_wp_i18n_namespaceObject.__)('Learn more about manual excerpts')));
}
/* harmony default export */ var post_excerpt = ((0,external_wp_compose_namespaceObject.compose)([(0,external_wp_data_namespaceObject.withSelect)(select => {
return {
excerpt: select(store_store).getEditedPostAttribute('excerpt')
};
}), (0,external_wp_data_namespaceObject.withDispatch)(dispatch => ({
onUpdateExcerpt(excerpt) {
dispatch(store_store).editPost({
excerpt
});
}
}))])(PostExcerpt));
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-excerpt/check.js
/**
* Internal dependencies
*/
function PostExcerptCheck(props) {
return (0,external_wp_element_namespaceObject.createElement)(post_type_support_check, _extends({}, props, {
supportKeys: "excerpt"
}));
}
/* harmony default export */ var post_excerpt_check = (PostExcerptCheck);
;// CONCATENATED MODULE: external ["wp","blob"]
var external_wp_blob_namespaceObject = window["wp"]["blob"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/theme-support-check/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function ThemeSupportCheck(_ref) {
let {
themeSupports,
children,
postType,
supportKeys
} = _ref;
const isSupported = (Array.isArray(supportKeys) ? supportKeys : [supportKeys]).some(key => {
const supported = (0,external_lodash_namespaceObject.get)(themeSupports, [key], false); // 'post-thumbnails' can be boolean or an array of post types.
// In the latter case, we need to verify `postType` exists
// within `supported`. If `postType` isn't passed, then the check
// should fail.
if ('post-thumbnails' === key && Array.isArray(supported)) {
return supported.includes(postType);
}
return supported;
});
if (!isSupported) {
return null;
}
return children;
}
/* harmony default export */ var theme_support_check = ((0,external_wp_data_namespaceObject.withSelect)(select => {
const {
getThemeSupports
} = select(external_wp_coreData_namespaceObject.store);
const {
getEditedPostAttribute
} = select(store_store);
return {
postType: getEditedPostAttribute('type'),
themeSupports: getThemeSupports()
};
})(ThemeSupportCheck));
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-featured-image/check.js
/**
* Internal dependencies
*/
function PostFeaturedImageCheck(props) {
return (0,external_wp_element_namespaceObject.createElement)(theme_support_check, {
supportKeys: "post-thumbnails"
}, (0,external_wp_element_namespaceObject.createElement)(post_type_support_check, _extends({}, props, {
supportKeys: "thumbnail"
})));
}
/* harmony default export */ var post_featured_image_check = (PostFeaturedImageCheck);
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-featured-image/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const ALLOWED_MEDIA_TYPES = ['image']; // Used when labels from post type were not yet loaded or when they are not present.
const DEFAULT_FEATURE_IMAGE_LABEL = (0,external_wp_i18n_namespaceObject.__)('Featured image');
const DEFAULT_SET_FEATURE_IMAGE_LABEL = (0,external_wp_i18n_namespaceObject.__)('Set featured image');
const DEFAULT_REMOVE_FEATURE_IMAGE_LABEL = (0,external_wp_i18n_namespaceObject.__)('Remove image');
const instructions = (0,external_wp_element_namespaceObject.createElement)("p", null, (0,external_wp_i18n_namespaceObject.__)('To edit the featured image, you need permission to upload media.'));
function getMediaDetails(media, postId) {
var _media$media_details$, _media$media_details, _media$media_details$2, _media$media_details2;
if (!media) {
return {};
}
const defaultSize = (0,external_wp_hooks_namespaceObject.applyFilters)('editor.PostFeaturedImage.imageSize', 'large', media.id, postId);
if (defaultSize in ((_media$media_details$ = media === null || media === void 0 ? void 0 : (_media$media_details = media.media_details) === null || _media$media_details === void 0 ? void 0 : _media$media_details.sizes) !== null && _media$media_details$ !== void 0 ? _media$media_details$ : {})) {
return {
mediaWidth: media.media_details.sizes[defaultSize].width,
mediaHeight: media.media_details.sizes[defaultSize].height,
mediaSourceUrl: media.media_details.sizes[defaultSize].source_url
};
} // Use fallbackSize when defaultSize is not available.
const fallbackSize = (0,external_wp_hooks_namespaceObject.applyFilters)('editor.PostFeaturedImage.imageSize', 'thumbnail', media.id, postId);
if (fallbackSize in ((_media$media_details$2 = media === null || media === void 0 ? void 0 : (_media$media_details2 = media.media_details) === null || _media$media_details2 === void 0 ? void 0 : _media$media_details2.sizes) !== null && _media$media_details$2 !== void 0 ? _media$media_details$2 : {})) {
return {
mediaWidth: media.media_details.sizes[fallbackSize].width,
mediaHeight: media.media_details.sizes[fallbackSize].height,
mediaSourceUrl: media.media_details.sizes[fallbackSize].source_url
};
} // Use full image size when fallbackSize and defaultSize are not available.
return {
mediaWidth: media.media_details.width,
mediaHeight: media.media_details.height,
mediaSourceUrl: media.source_url
};
}
function PostFeaturedImage(_ref) {
var _media$media_details$3, _media$media_details$4;
let {
currentPostId,
featuredImageId,
onUpdateImage,
onRemoveImage,
media,
postType,
noticeUI,
noticeOperations
} = _ref;
const [isLoading, setIsLoading] = (0,external_wp_element_namespaceObject.useState)(false);
const mediaUpload = (0,external_wp_data_namespaceObject.useSelect)(select => {
return select(external_wp_blockEditor_namespaceObject.store).getSettings().mediaUpload;
}, []);
const postLabel = (0,external_lodash_namespaceObject.get)(postType, ['labels'], {});
const {
mediaWidth,
mediaHeight,
mediaSourceUrl
} = getMediaDetails(media, currentPostId);
function onDropFiles(filesList) {
mediaUpload({
allowedTypes: ['image'],
filesList,
onFileChange(_ref2) {
let [image] = _ref2;
if ((0,external_wp_blob_namespaceObject.isBlobURL)(image === null || image === void 0 ? void 0 : image.url)) {
setIsLoading(true);
return;
}
onUpdateImage(image);
setIsLoading(false);
},
onError(message) {
noticeOperations.removeAllNotices();
noticeOperations.createErrorNotice(message);
}
});
}
return (0,external_wp_element_namespaceObject.createElement)(post_featured_image_check, null, noticeUI, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "editor-post-featured-image"
}, media && (0,external_wp_element_namespaceObject.createElement)("div", {
id: `editor-post-featured-image-${featuredImageId}-describedby`,
className: "hidden"
}, media.alt_text && (0,external_wp_i18n_namespaceObject.sprintf)( // Translators: %s: The selected image alt text.
(0,external_wp_i18n_namespaceObject.__)('Current image: %s'), media.alt_text), !media.alt_text && (0,external_wp_i18n_namespaceObject.sprintf)( // Translators: %s: The selected image filename.
(0,external_wp_i18n_namespaceObject.__)('The current image has no alternative text. The file name is: %s'), ((_media$media_details$3 = media.media_details.sizes) === null || _media$media_details$3 === void 0 ? void 0 : (_media$media_details$4 = _media$media_details$3.full) === null || _media$media_details$4 === void 0 ? void 0 : _media$media_details$4.file) || media.slug)), (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.MediaUploadCheck, {
fallback: instructions
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.MediaUpload, {
title: postLabel.featured_image || DEFAULT_FEATURE_IMAGE_LABEL,
onSelect: onUpdateImage,
unstableFeaturedImageFlow: true,
allowedTypes: ALLOWED_MEDIA_TYPES,
modalClass: "editor-post-featured-image__media-modal",
render: _ref3 => {
let {
open
} = _ref3;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "editor-post-featured-image__container"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
className: !featuredImageId ? 'editor-post-featured-image__toggle' : 'editor-post-featured-image__preview',
onClick: open,
"aria-label": !featuredImageId ? null : (0,external_wp_i18n_namespaceObject.__)('Edit or update the image'),
"aria-describedby": !featuredImageId ? null : `editor-post-featured-image-${featuredImageId}-describedby`
}, !!featuredImageId && media && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ResponsiveWrapper, {
naturalWidth: mediaWidth,
naturalHeight: mediaHeight,
isInline: true
}, (0,external_wp_element_namespaceObject.createElement)("img", {
src: mediaSourceUrl,
alt: ""
})), isLoading && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Spinner, null), !featuredImageId && !isLoading && (postLabel.set_featured_image || DEFAULT_SET_FEATURE_IMAGE_LABEL)), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.DropZone, {
onFilesDrop: onDropFiles
}));
},
value: featuredImageId
})), !!featuredImageId && (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.MediaUploadCheck, null, media && (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.MediaUpload, {
title: postLabel.featured_image || DEFAULT_FEATURE_IMAGE_LABEL,
onSelect: onUpdateImage,
unstableFeaturedImageFlow: true,
allowedTypes: ALLOWED_MEDIA_TYPES,
modalClass: "editor-post-featured-image__media-modal",
render: _ref4 => {
let {
open
} = _ref4;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
onClick: open,
variant: "secondary"
}, (0,external_wp_i18n_namespaceObject.__)('Replace Image'));
}
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
onClick: onRemoveImage,
variant: "link",
isDestructive: true
}, postLabel.remove_featured_image || DEFAULT_REMOVE_FEATURE_IMAGE_LABEL))));
}
const applyWithSelect = (0,external_wp_data_namespaceObject.withSelect)(select => {
const {
getMedia,
getPostType
} = select(external_wp_coreData_namespaceObject.store);
const {
getCurrentPostId,
getEditedPostAttribute
} = select(store_store);
const featuredImageId = getEditedPostAttribute('featured_media');
return {
media: featuredImageId ? getMedia(featuredImageId, {
context: 'view'
}) : null,
currentPostId: getCurrentPostId(),
postType: getPostType(getEditedPostAttribute('type')),
featuredImageId
};
});
const applyWithDispatch = (0,external_wp_data_namespaceObject.withDispatch)((dispatch, _ref5, _ref6) => {
let {
noticeOperations
} = _ref5;
let {
select
} = _ref6;
const {
editPost
} = dispatch(store_store);
return {
onUpdateImage(image) {
editPost({
featured_media: image.id
});
},
onDropImage(filesList) {
select(external_wp_blockEditor_namespaceObject.store).getSettings().mediaUpload({
allowedTypes: ['image'],
filesList,
onFileChange(_ref7) {
let [image] = _ref7;
editPost({
featured_media: image.id
});
},
onError(message) {
noticeOperations.removeAllNotices();
noticeOperations.createErrorNotice(message);
}
});
},
onRemoveImage() {
editPost({
featured_media: 0
});
}
};
});
/* harmony default export */ var post_featured_image = ((0,external_wp_compose_namespaceObject.compose)(external_wp_components_namespaceObject.withNotices, applyWithSelect, applyWithDispatch, (0,external_wp_components_namespaceObject.withFilters)('editor.PostFeaturedImage'))(PostFeaturedImage));
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-format/check.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PostFormatCheck(_ref) {
let {
disablePostFormats,
...props
} = _ref;
return !disablePostFormats && (0,external_wp_element_namespaceObject.createElement)(post_type_support_check, _extends({}, props, {
supportKeys: "post-formats"
}));
}
/* harmony default export */ var post_format_check = ((0,external_wp_data_namespaceObject.withSelect)(select => {
const editorSettings = select(store_store).getEditorSettings();
return {
disablePostFormats: editorSettings.disablePostFormats
};
})(PostFormatCheck));
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-format/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
// All WP post formats, sorted alphabetically by translated name.
const POST_FORMATS = [{
id: 'aside',
caption: (0,external_wp_i18n_namespaceObject.__)('Aside')
}, {
id: 'audio',
caption: (0,external_wp_i18n_namespaceObject.__)('Audio')
}, {
id: 'chat',
caption: (0,external_wp_i18n_namespaceObject.__)('Chat')
}, {
id: 'gallery',
caption: (0,external_wp_i18n_namespaceObject.__)('Gallery')
}, {
id: 'image',
caption: (0,external_wp_i18n_namespaceObject.__)('Image')
}, {
id: 'link',
caption: (0,external_wp_i18n_namespaceObject.__)('Link')
}, {
id: 'quote',
caption: (0,external_wp_i18n_namespaceObject.__)('Quote')
}, {
id: 'standard',
caption: (0,external_wp_i18n_namespaceObject.__)('Standard')
}, {
id: 'status',
caption: (0,external_wp_i18n_namespaceObject.__)('Status')
}, {
id: 'video',
caption: (0,external_wp_i18n_namespaceObject.__)('Video')
}].sort((a, b) => {
const normalizedA = a.caption.toUpperCase();
const normalizedB = b.caption.toUpperCase();
if (normalizedA < normalizedB) {
return -1;
}
if (normalizedA > normalizedB) {
return 1;
}
return 0;
});
function PostFormat() {
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(PostFormat);
const postFormatSelectorId = `post-format-selector-${instanceId}`;
const {
postFormat,
suggestedFormat,
supportedFormats
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getEditedPostAttribute,
getSuggestedPostFormat
} = select(store_store);
const _postFormat = getEditedPostAttribute('format');
const themeSupports = select(external_wp_coreData_namespaceObject.store).getThemeSupports();
return {
postFormat: _postFormat !== null && _postFormat !== void 0 ? _postFormat : 'standard',
suggestedFormat: getSuggestedPostFormat(),
supportedFormats: themeSupports.formats
};
}, []);
const formats = POST_FORMATS.filter(format => {
// Ensure current format is always in the set.
// The current format may not be a format supported by the theme.
return (supportedFormats === null || supportedFormats === void 0 ? void 0 : supportedFormats.includes(format.id)) || postFormat === format.id;
});
const suggestion = formats.find(format => format.id === suggestedFormat);
const {
editPost
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const onUpdatePostFormat = format => editPost({
format
});
return (0,external_wp_element_namespaceObject.createElement)(post_format_check, null, (0,external_wp_element_namespaceObject.createElement)("div", {
className: "editor-post-format"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SelectControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Post Format'),
value: postFormat,
onChange: format => onUpdatePostFormat(format),
id: postFormatSelectorId,
options: formats.map(format => ({
label: format.caption,
value: format.id
}))
}), suggestion && suggestion.id !== postFormat && (0,external_wp_element_namespaceObject.createElement)("p", {
className: "editor-post-format__suggestion"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "link",
onClick: () => onUpdatePostFormat(suggestion.id)
}, (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: post format */
(0,external_wp_i18n_namespaceObject.__)('Apply suggested format: %s'), suggestion.caption)))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/backup.js
/**
* WordPress dependencies
*/
const backup = (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: "M5.5 12h1.75l-2.5 3-2.5-3H4a8 8 0 113.134 6.35l.907-1.194A6.5 6.5 0 105.5 12zm9.53 1.97l-2.28-2.28V8.5a.75.75 0 00-1.5 0V12a.747.747 0 00.218.529l1.282-.84-1.28.842 2.5 2.5a.75.75 0 101.06-1.061z"
}));
/* harmony default export */ var library_backup = (backup);
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-last-revision/check.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PostLastRevisionCheck(_ref) {
let {
lastRevisionId,
revisionsCount,
children
} = _ref;
if (!lastRevisionId || revisionsCount < 2) {
return null;
}
return (0,external_wp_element_namespaceObject.createElement)(post_type_support_check, {
supportKeys: "revisions"
}, children);
}
/* harmony default export */ var post_last_revision_check = ((0,external_wp_data_namespaceObject.withSelect)(select => {
const {
getCurrentPostLastRevisionId,
getCurrentPostRevisionsCount
} = select(store_store);
return {
lastRevisionId: getCurrentPostLastRevisionId(),
revisionsCount: getCurrentPostRevisionsCount()
};
})(PostLastRevisionCheck));
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-last-revision/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function LastRevision(_ref) {
let {
lastRevisionId,
revisionsCount
} = _ref;
return (0,external_wp_element_namespaceObject.createElement)(post_last_revision_check, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
href: (0,external_wp_url_namespaceObject.addQueryArgs)('revision.php', {
revision: lastRevisionId,
gutenberg: true
}),
className: "editor-post-last-revision__title",
icon: library_backup
}, (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %d: number of revisions */
(0,external_wp_i18n_namespaceObject._n)('%d Revision', '%d Revisions', revisionsCount), revisionsCount)));
}
/* harmony default export */ var post_last_revision = ((0,external_wp_data_namespaceObject.withSelect)(select => {
const {
getCurrentPostLastRevisionId,
getCurrentPostRevisionsCount
} = select(store_store);
return {
lastRevisionId: getCurrentPostLastRevisionId(),
revisionsCount: getCurrentPostRevisionsCount()
};
})(LastRevision));
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-locked-modal/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PostLockedModal() {
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(PostLockedModal);
const hookName = 'core/editor/post-locked-modal-' + instanceId;
const {
autosave,
updatePostLock
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const {
isLocked,
isTakeover,
user,
postId,
postLockUtils,
activePostLock,
postType,
previewLink
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
isPostLocked,
isPostLockTakeover,
getPostLockUser,
getCurrentPostId,
getActivePostLock,
getEditedPostAttribute,
getEditedPostPreviewLink,
getEditorSettings
} = select(store_store);
const {
getPostType
} = select(external_wp_coreData_namespaceObject.store);
return {
isLocked: isPostLocked(),
isTakeover: isPostLockTakeover(),
user: getPostLockUser(),
postId: getCurrentPostId(),
postLockUtils: getEditorSettings().postLockUtils,
activePostLock: getActivePostLock(),
postType: getPostType(getEditedPostAttribute('type')),
previewLink: getEditedPostPreviewLink()
};
}, []);
(0,external_wp_element_namespaceObject.useEffect)(() => {
/**
* Keep the lock refreshed.
*
* When the user does not send a heartbeat in a heartbeat-tick
* the user is no longer editing and another user can start editing.
*
* @param {Object} data Data to send in the heartbeat request.
*/
function sendPostLock(data) {
if (isLocked) {
return;
}
data['wp-refresh-post-lock'] = {
lock: activePostLock,
post_id: postId
};
}
/**
* Refresh post locks: update the lock string or show the dialog if somebody has taken over editing.
*
* @param {Object} data Data received in the heartbeat request
*/
function receivePostLock(data) {
if (!data['wp-refresh-post-lock']) {
return;
}
const received = data['wp-refresh-post-lock'];
if (received.lock_error) {
// Auto save and display the takeover modal.
autosave();
updatePostLock({
isLocked: true,
isTakeover: true,
user: {
name: received.lock_error.name,
avatar: received.lock_error.avatar_src_2x
}
});
} else if (received.new_lock) {
updatePostLock({
isLocked: false,
activePostLock: received.new_lock
});
}
}
/**
* Unlock the post before the window is exited.
*/
function releasePostLock() {
if (isLocked || !activePostLock) {
return;
}
const data = new window.FormData();
data.append('action', 'wp-remove-post-lock');
data.append('_wpnonce', postLockUtils.unlockNonce);
data.append('post_ID', postId);
data.append('active_post_lock', activePostLock);
if (window.navigator.sendBeacon) {
window.navigator.sendBeacon(postLockUtils.ajaxUrl, data);
} else {
const xhr = new window.XMLHttpRequest();
xhr.open('POST', postLockUtils.ajaxUrl, false);
xhr.send(data);
}
} // Details on these events on the Heartbeat API docs
// https://developer.wordpress.org/plugins/javascript/heartbeat-api/
(0,external_wp_hooks_namespaceObject.addAction)('heartbeat.send', hookName, sendPostLock);
(0,external_wp_hooks_namespaceObject.addAction)('heartbeat.tick', hookName, receivePostLock);
window.addEventListener('beforeunload', releasePostLock);
return () => {
(0,external_wp_hooks_namespaceObject.removeAction)('heartbeat.send', hookName);
(0,external_wp_hooks_namespaceObject.removeAction)('heartbeat.tick', hookName);
window.removeEventListener('beforeunload', releasePostLock);
};
}, []);
if (!isLocked) {
return null;
}
const userDisplayName = user.name;
const userAvatar = user.avatar;
const unlockUrl = (0,external_wp_url_namespaceObject.addQueryArgs)('post.php', {
'get-post-lock': '1',
lockKey: true,
post: postId,
action: 'edit',
_wpnonce: postLockUtils.nonce
});
const allPostsUrl = (0,external_wp_url_namespaceObject.addQueryArgs)('edit.php', {
post_type: (0,external_lodash_namespaceObject.get)(postType, ['slug'])
});
const allPostsLabel = (0,external_wp_i18n_namespaceObject.__)('Exit editor');
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Modal, {
title: isTakeover ? (0,external_wp_i18n_namespaceObject.__)('Someone else has taken over this post') : (0,external_wp_i18n_namespaceObject.__)('This post is already being edited'),
focusOnMount: true,
shouldCloseOnClickOutside: false,
shouldCloseOnEsc: false,
isDismissible: false,
className: "editor-post-locked-modal"
}, !!userAvatar && (0,external_wp_element_namespaceObject.createElement)("img", {
src: userAvatar,
alt: (0,external_wp_i18n_namespaceObject.__)('Avatar'),
className: "editor-post-locked-modal__avatar",
width: 64,
height: 64
}), (0,external_wp_element_namespaceObject.createElement)("div", null, !!isTakeover && (0,external_wp_element_namespaceObject.createElement)("p", null, (0,external_wp_element_namespaceObject.createInterpolateElement)(userDisplayName ? (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: user's display name */
(0,external_wp_i18n_namespaceObject.__)('<strong>%s</strong> now has editing control of this post (<PreviewLink />). Don’t worry, your changes up to this moment have been saved.'), userDisplayName) : (0,external_wp_i18n_namespaceObject.__)('Another user now has editing control of this post (<PreviewLink />). Don’t worry, your changes up to this moment have been saved.'), {
strong: (0,external_wp_element_namespaceObject.createElement)("strong", null),
PreviewLink: (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ExternalLink, {
href: previewLink
}, (0,external_wp_i18n_namespaceObject.__)('preview'))
})), !isTakeover && (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)("p", null, (0,external_wp_element_namespaceObject.createInterpolateElement)(userDisplayName ? (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: user's display name */
(0,external_wp_i18n_namespaceObject.__)('<strong>%s</strong> is currently working on this post (<PreviewLink />), which means you cannot make changes, unless you take over.'), userDisplayName) : (0,external_wp_i18n_namespaceObject.__)('Another user is currently working on this post (<PreviewLink />), which means you cannot make changes, unless you take over.'), {
strong: (0,external_wp_element_namespaceObject.createElement)("strong", null),
PreviewLink: (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.ExternalLink, {
href: previewLink
}, (0,external_wp_i18n_namespaceObject.__)('preview'))
})), (0,external_wp_element_namespaceObject.createElement)("p", null, (0,external_wp_i18n_namespaceObject.__)('If you take over, the other user will lose editing control to the post, but their changes will be saved.'))), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Flex, {
className: "editor-post-locked-modal__buttons",
justify: "flex-end",
expanded: false
}, !isTakeover && (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexItem, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "tertiary",
href: unlockUrl
}, (0,external_wp_i18n_namespaceObject.__)('Take over'))), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.FlexItem, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "primary",
href: allPostsUrl
}, allPostsLabel)))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-pending-status/check.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PostPendingStatusCheck(_ref) {
let {
hasPublishAction,
isPublished,
children
} = _ref;
if (isPublished || !hasPublishAction) {
return null;
}
return children;
}
/* harmony default export */ var post_pending_status_check = ((0,external_wp_compose_namespaceObject.compose)((0,external_wp_data_namespaceObject.withSelect)(select => {
const {
isCurrentPostPublished,
getCurrentPostType,
getCurrentPost
} = select(store_store);
return {
hasPublishAction: (0,external_lodash_namespaceObject.get)(getCurrentPost(), ['_links', 'wp:action-publish'], false),
isPublished: isCurrentPostPublished(),
postType: getCurrentPostType()
};
}))(PostPendingStatusCheck));
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-pending-status/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PostPendingStatus(_ref) {
let {
status,
onUpdateStatus
} = _ref;
const togglePendingStatus = () => {
const updatedStatus = status === 'pending' ? 'draft' : 'pending';
onUpdateStatus(updatedStatus);
};
return (0,external_wp_element_namespaceObject.createElement)(post_pending_status_check, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.CheckboxControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Pending review'),
checked: status === 'pending',
onChange: togglePendingStatus
}));
}
/* harmony default export */ var post_pending_status = ((0,external_wp_compose_namespaceObject.compose)((0,external_wp_data_namespaceObject.withSelect)(select => ({
status: select(store_store).getEditedPostAttribute('status')
})), (0,external_wp_data_namespaceObject.withDispatch)(dispatch => ({
onUpdateStatus(status) {
dispatch(store_store).editPost({
status
});
}
})))(PostPendingStatus));
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-pingbacks/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PostPingbacks(_ref) {
let {
pingStatus = 'open',
...props
} = _ref;
const onTogglePingback = () => props.editPost({
ping_status: pingStatus === 'open' ? 'closed' : 'open'
});
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.CheckboxControl, {
__nextHasNoMarginBottom: true,
label: (0,external_wp_i18n_namespaceObject.__)('Allow pingbacks & trackbacks'),
checked: pingStatus === 'open',
onChange: onTogglePingback
});
}
/* harmony default export */ var post_pingbacks = ((0,external_wp_compose_namespaceObject.compose)([(0,external_wp_data_namespaceObject.withSelect)(select => {
return {
pingStatus: select(store_store).getEditedPostAttribute('ping_status')
};
}), (0,external_wp_data_namespaceObject.withDispatch)(dispatch => ({
editPost: dispatch(store_store).editPost
}))])(PostPingbacks));
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-preview-button/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function writeInterstitialMessage(targetDocument) {
let markup = (0,external_wp_element_namespaceObject.renderToString)((0,external_wp_element_namespaceObject.createElement)("div", {
className: "editor-post-preview-button__interstitial-message"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 96 96"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Path, {
className: "outer",
d: "M48 12c19.9 0 36 16.1 36 36S67.9 84 48 84 12 67.9 12 48s16.1-36 36-36",
fill: "none"
}), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Path, {
className: "inner",
d: "M69.5 46.4c0-3.9-1.4-6.7-2.6-8.8-1.6-2.6-3.1-4.9-3.1-7.5 0-2.9 2.2-5.7 5.4-5.7h.4C63.9 19.2 56.4 16 48 16c-11.2 0-21 5.7-26.7 14.4h2.1c3.3 0 8.5-.4 8.5-.4 1.7-.1 1.9 2.4.2 2.6 0 0-1.7.2-3.7.3L40 67.5l7-20.9L42 33c-1.7-.1-3.3-.3-3.3-.3-1.7-.1-1.5-2.7.2-2.6 0 0 5.3.4 8.4.4 3.3 0 8.5-.4 8.5-.4 1.7-.1 1.9 2.4.2 2.6 0 0-1.7.2-3.7.3l11.5 34.3 3.3-10.4c1.6-4.5 2.4-7.8 2.4-10.5zM16.1 48c0 12.6 7.3 23.5 18 28.7L18.8 35c-1.7 4-2.7 8.4-2.7 13zm32.5 2.8L39 78.6c2.9.8 5.9 1.3 9 1.3 3.7 0 7.3-.6 10.6-1.8-.1-.1-.2-.3-.2-.4l-9.8-26.9zM76.2 36c0 3.2-.6 6.9-2.4 11.4L64 75.6c9.5-5.5 15.9-15.8 15.9-27.6 0-5.5-1.4-10.8-3.9-15.3.1 1 .2 2.1.2 3.3z",
fill: "none"
})), (0,external_wp_element_namespaceObject.createElement)("p", null, (0,external_wp_i18n_namespaceObject.__)('Generating preview…'))));
markup += `
<style>
body {
margin: 0;
}
.editor-post-preview-button__interstitial-message {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
width: 100vw;
}
@-webkit-keyframes paint {
0% {
stroke-dashoffset: 0;
}
}
@-moz-keyframes paint {
0% {
stroke-dashoffset: 0;
}
}
@-o-keyframes paint {
0% {
stroke-dashoffset: 0;
}
}
@keyframes paint {
0% {
stroke-dashoffset: 0;
}
}
.editor-post-preview-button__interstitial-message svg {
width: 192px;
height: 192px;
stroke: #555d66;
stroke-width: 0.75;
}
.editor-post-preview-button__interstitial-message svg .outer,
.editor-post-preview-button__interstitial-message svg .inner {
stroke-dasharray: 280;
stroke-dashoffset: 280;
-webkit-animation: paint 1.5s ease infinite alternate;
-moz-animation: paint 1.5s ease infinite alternate;
-o-animation: paint 1.5s ease infinite alternate;
animation: paint 1.5s ease infinite alternate;
}
p {
text-align: center;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
}
</style>
`;
/**
* Filters the interstitial message shown when generating previews.
*
* @param {string} markup The preview interstitial markup.
*/
markup = (0,external_wp_hooks_namespaceObject.applyFilters)('editor.PostPreview.interstitialMarkup', markup);
targetDocument.write(markup);
targetDocument.title = (0,external_wp_i18n_namespaceObject.__)('Generating preview…');
targetDocument.close();
}
class PostPreviewButton extends external_wp_element_namespaceObject.Component {
constructor() {
super(...arguments);
this.buttonRef = (0,external_wp_element_namespaceObject.createRef)();
this.openPreviewWindow = this.openPreviewWindow.bind(this);
}
componentDidUpdate(prevProps) {
const {
previewLink
} = this.props; // This relies on the window being responsible to unset itself when
// navigation occurs or a new preview window is opened, to avoid
// unintentional forceful redirects.
if (previewLink && !prevProps.previewLink) {
this.setPreviewWindowLink(previewLink);
}
}
/**
* Sets the preview window's location to the given URL, if a preview window
* exists and is not closed.
*
* @param {string} url URL to assign as preview window location.
*/
setPreviewWindowLink(url) {
const {
previewWindow
} = this;
if (previewWindow && !previewWindow.closed) {
previewWindow.location = url;
if (this.buttonRef.current) {
this.buttonRef.current.focus();
}
}
}
getWindowTarget() {
const {
postId
} = this.props;
return `wp-preview-${postId}`;
}
openPreviewWindow(event) {
// Our Preview button has its 'href' and 'target' set correctly for a11y
// purposes. Unfortunately, though, we can't rely on the default 'click'
// handler since sometimes it incorrectly opens a new tab instead of reusing
// the existing one.
// https://github.com/WordPress/gutenberg/pull/8330
event.preventDefault(); // Open up a Preview tab if needed. This is where we'll show the preview.
if (!this.previewWindow || this.previewWindow.closed) {
this.previewWindow = window.open('', this.getWindowTarget());
} // Focus the Preview tab. This might not do anything, depending on the browser's
// and user's preferences.
// https://html.spec.whatwg.org/multipage/interaction.html#dom-window-focus
this.previewWindow.focus();
if ( // If we don't need to autosave the post before previewing, then we simply
// load the Preview URL in the Preview tab.
!this.props.isAutosaveable || // Do not save or overwrite the post, if the post is already locked.
this.props.isPostLocked) {
this.setPreviewWindowLink(event.target.href);
return;
} // Request an autosave. This happens asynchronously and causes the component
// to update when finished.
if (this.props.isDraft) {
this.props.savePost({
isPreview: true
});
} else {
this.props.autosave({
isPreview: true
});
} // Display a 'Generating preview' message in the Preview tab while we wait for the
// autosave to finish.
writeInterstitialMessage(this.previewWindow.document);
}
render() {
const {
previewLink,
currentPostLink,
isSaveable,
role
} = this.props; // Link to the `?preview=true` URL if we have it, since this lets us see
// changes that were autosaved since the post was last published. Otherwise,
// just link to the post's URL.
const href = previewLink || currentPostLink;
const classNames = classnames_default()({
'editor-post-preview': !this.props.className
}, this.props.className);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: !this.props.className ? 'tertiary' : undefined,
className: classNames,
href: href,
target: this.getWindowTarget(),
disabled: !isSaveable,
onClick: this.openPreviewWindow,
ref: this.buttonRef,
role: role
}, this.props.textContent ? this.props.textContent : (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_i18n_namespaceObject._x)('Preview', 'imperative verb'), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.VisuallyHidden, {
as: "span"
},
/* translators: accessibility text */
(0,external_wp_i18n_namespaceObject.__)('(opens in a new tab)'))));
}
}
/* harmony default export */ var post_preview_button = ((0,external_wp_compose_namespaceObject.compose)([(0,external_wp_data_namespaceObject.withSelect)((select, _ref) => {
let {
forcePreviewLink,
forceIsAutosaveable
} = _ref;
const {
getCurrentPostId,
getCurrentPostAttribute,
getEditedPostAttribute,
isEditedPostSaveable,
isEditedPostAutosaveable,
getEditedPostPreviewLink,
isPostLocked
} = select(store_store);
const {
getPostType
} = select(external_wp_coreData_namespaceObject.store);
const previewLink = getEditedPostPreviewLink();
const postType = getPostType(getEditedPostAttribute('type'));
return {
postId: getCurrentPostId(),
currentPostLink: getCurrentPostAttribute('link'),
previewLink: forcePreviewLink !== undefined ? forcePreviewLink : previewLink,
isSaveable: isEditedPostSaveable(),
isAutosaveable: forceIsAutosaveable || isEditedPostAutosaveable(),
isViewable: (0,external_lodash_namespaceObject.get)(postType, ['viewable'], false),
isDraft: ['draft', 'auto-draft'].indexOf(getEditedPostAttribute('status')) !== -1,
isPostLocked: isPostLocked()
};
}), (0,external_wp_data_namespaceObject.withDispatch)(dispatch => ({
autosave: dispatch(store_store).autosave,
savePost: dispatch(store_store).savePost
})), (0,external_wp_compose_namespaceObject.ifCondition)(_ref2 => {
let {
isViewable
} = _ref2;
return isViewable;
})])(PostPreviewButton));
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-publish-button/label.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PublishButtonLabel(_ref) {
let {
isPublished,
isBeingScheduled,
isSaving,
isPublishing,
hasPublishAction,
isAutosaving,
hasNonPostEntityChanges
} = _ref;
if (isPublishing) {
/* translators: button label text should, if possible, be under 16 characters. */
return (0,external_wp_i18n_namespaceObject.__)('Publishing…');
} else if (isPublished && isSaving && !isAutosaving) {
/* translators: button label text should, if possible, be under 16 characters. */
return (0,external_wp_i18n_namespaceObject.__)('Updating…');
} else if (isBeingScheduled && isSaving && !isAutosaving) {
/* translators: button label text should, if possible, be under 16 characters. */
return (0,external_wp_i18n_namespaceObject.__)('Scheduling…');
}
if (!hasPublishAction) {
return hasNonPostEntityChanges ? (0,external_wp_i18n_namespaceObject.__)('Submit for Review…') : (0,external_wp_i18n_namespaceObject.__)('Submit for Review');
} else if (isPublished) {
return hasNonPostEntityChanges ? (0,external_wp_i18n_namespaceObject.__)('Update…') : (0,external_wp_i18n_namespaceObject.__)('Update');
} else if (isBeingScheduled) {
return hasNonPostEntityChanges ? (0,external_wp_i18n_namespaceObject.__)('Schedule…') : (0,external_wp_i18n_namespaceObject.__)('Schedule');
}
return (0,external_wp_i18n_namespaceObject.__)('Publish');
}
/* harmony default export */ var label = ((0,external_wp_compose_namespaceObject.compose)([(0,external_wp_data_namespaceObject.withSelect)((select, _ref2) => {
let {
forceIsSaving
} = _ref2;
const {
isCurrentPostPublished,
isEditedPostBeingScheduled,
isSavingPost,
isPublishingPost,
getCurrentPost,
getCurrentPostType,
isAutosavingPost
} = select(store_store);
return {
isPublished: isCurrentPostPublished(),
isBeingScheduled: isEditedPostBeingScheduled(),
isSaving: forceIsSaving || isSavingPost(),
isPublishing: isPublishingPost(),
hasPublishAction: (0,external_lodash_namespaceObject.get)(getCurrentPost(), ['_links', 'wp:action-publish'], false),
postType: getCurrentPostType(),
isAutosaving: isAutosavingPost()
};
})])(PublishButtonLabel));
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-publish-button/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const noop = () => {};
class PostPublishButton extends external_wp_element_namespaceObject.Component {
constructor(props) {
super(props);
this.buttonNode = (0,external_wp_element_namespaceObject.createRef)();
this.createOnClick = this.createOnClick.bind(this);
this.closeEntitiesSavedStates = this.closeEntitiesSavedStates.bind(this);
this.state = {
entitiesSavedStatesCallback: false
};
}
componentDidMount() {
if (this.props.focusOnMount) {
// This timeout is necessary to make sure the `useEffect` hook of
// `useFocusReturn` gets the correct element (the button that opens the
// PostPublishPanel) otherwise it will get this button.
this.timeoutID = setTimeout(() => {
this.buttonNode.current.focus();
}, 0);
}
}
componentWillUnmount() {
clearTimeout(this.timeoutID);
}
createOnClick(callback) {
var _this = this;
return function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
const {
hasNonPostEntityChanges,
setEntitiesSavedStatesCallback
} = _this.props; // If a post with non-post entities is published, but the user
// elects to not save changes to the non-post entities, those
// entities will still be dirty when the Publish button is clicked.
// We also need to check that the `setEntitiesSavedStatesCallback`
// prop was passed. See https://github.com/WordPress/gutenberg/pull/37383
if (hasNonPostEntityChanges && setEntitiesSavedStatesCallback) {
// The modal for multiple entity saving will open,
// hold the callback for saving/publishing the post
// so that we can call it if the post entity is checked.
_this.setState({
entitiesSavedStatesCallback: () => callback(...args)
}); // Open the save panel by setting its callback.
// To set a function on the useState hook, we must set it
// with another function (() => myFunction). Passing the
// function on its own will cause an error when called.
setEntitiesSavedStatesCallback(() => _this.closeEntitiesSavedStates);
return noop;
}
return callback(...args);
};
}
closeEntitiesSavedStates(savedEntities) {
const {
postType,
postId
} = this.props;
const {
entitiesSavedStatesCallback
} = this.state;
this.setState({
entitiesSavedStatesCallback: false
}, () => {
if (savedEntities && savedEntities.some(elt => elt.kind === 'postType' && elt.name === postType && elt.key === postId)) {
// The post entity was checked, call the held callback from `createOnClick`.
entitiesSavedStatesCallback();
}
});
}
render() {
const {
forceIsDirty,
forceIsSaving,
hasPublishAction,
isBeingScheduled,
isOpen,
isPostSavingLocked,
isPublishable,
isPublished,
isSaveable,
isSaving,
isAutoSaving,
isToggle,
onSave,
onStatusChange,
onSubmit = noop,
onToggle,
visibility,
hasNonPostEntityChanges,
isSavingNonPostEntityChanges
} = this.props;
const isButtonDisabled = (isSaving || forceIsSaving || !isSaveable || isPostSavingLocked || !isPublishable && !forceIsDirty) && (!hasNonPostEntityChanges || isSavingNonPostEntityChanges);
const isToggleDisabled = (isPublished || isSaving || forceIsSaving || !isSaveable || !isPublishable && !forceIsDirty) && (!hasNonPostEntityChanges || isSavingNonPostEntityChanges);
let publishStatus;
if (!hasPublishAction) {
publishStatus = 'pending';
} else if (visibility === 'private') {
publishStatus = 'private';
} else if (isBeingScheduled) {
publishStatus = 'future';
} else {
publishStatus = 'publish';
}
const onClickButton = () => {
if (isButtonDisabled) {
return;
}
onSubmit();
onStatusChange(publishStatus);
onSave();
};
const onClickToggle = () => {
if (isToggleDisabled) {
return;
}
onToggle();
};
const buttonProps = {
'aria-disabled': isButtonDisabled,
className: 'editor-post-publish-button',
isBusy: !isAutoSaving && isSaving && isPublished,
variant: 'primary',
onClick: this.createOnClick(onClickButton)
};
const toggleProps = {
'aria-disabled': isToggleDisabled,
'aria-expanded': isOpen,
className: 'editor-post-publish-panel__toggle',
isBusy: isSaving && isPublished,
variant: 'primary',
onClick: this.createOnClick(onClickToggle)
};
const toggleChildren = isBeingScheduled ? (0,external_wp_i18n_namespaceObject.__)('Schedule…') : (0,external_wp_i18n_namespaceObject.__)('Publish');
const buttonChildren = (0,external_wp_element_namespaceObject.createElement)(label, {
forceIsSaving: forceIsSaving,
hasNonPostEntityChanges: hasNonPostEntityChanges
});
const componentProps = isToggle ? toggleProps : buttonProps;
const componentChildren = isToggle ? toggleChildren : buttonChildren;
return (0,external_wp_element_namespaceObject.createElement)(external_wp_element_namespaceObject.Fragment, null, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, _extends({
ref: this.buttonNode
}, componentProps, {
className: classnames_default()(componentProps.className, 'editor-post-publish-button__button', {
'has-changes-dot': hasNonPostEntityChanges
})
}), componentChildren));
}
}
/* harmony default export */ var post_publish_button = ((0,external_wp_compose_namespaceObject.compose)([(0,external_wp_data_namespaceObject.withSelect)(select => {
const {
isSavingPost,
isAutosavingPost,
isEditedPostBeingScheduled,
getEditedPostVisibility,
isCurrentPostPublished,
isEditedPostSaveable,
isEditedPostPublishable,
isPostSavingLocked,
getCurrentPost,
getCurrentPostType,
getCurrentPostId,
hasNonPostEntityChanges,
isSavingNonPostEntityChanges
} = select(store_store);
const _isAutoSaving = isAutosavingPost();
return {
isSaving: isSavingPost() || _isAutoSaving,
isAutoSaving: _isAutoSaving,
isBeingScheduled: isEditedPostBeingScheduled(),
visibility: getEditedPostVisibility(),
isSaveable: isEditedPostSaveable(),
isPostSavingLocked: isPostSavingLocked(),
isPublishable: isEditedPostPublishable(),
isPublished: isCurrentPostPublished(),
hasPublishAction: (0,external_lodash_namespaceObject.get)(getCurrentPost(), ['_links', 'wp:action-publish'], false),
postType: getCurrentPostType(),
postId: getCurrentPostId(),
hasNonPostEntityChanges: hasNonPostEntityChanges(),
isSavingNonPostEntityChanges: isSavingNonPostEntityChanges()
};
}), (0,external_wp_data_namespaceObject.withDispatch)(dispatch => {
const {
editPost,
savePost
} = dispatch(store_store);
return {
onStatusChange: status => editPost({
status
}, {
undoIgnore: true
}),
onSave: savePost
};
})])(PostPublishButton));
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/close-small.js
/**
* WordPress dependencies
*/
const closeSmall = (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: "M12 13.06l3.712 3.713 1.061-1.06L13.061 12l3.712-3.712-1.06-1.06L12 10.938 8.288 7.227l-1.061 1.06L10.939 12l-3.712 3.712 1.06 1.061L12 13.061z"
}));
/* harmony default export */ var close_small = (closeSmall);
;// CONCATENATED MODULE: ./node_modules/@wordpress/icons/build-module/library/wordpress.js
/**
* WordPress dependencies
*/
const wordpress = (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.SVG, {
xmlns: "http://www.w3.org/2000/svg",
viewBox: "-2 -2 24 24"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_primitives_namespaceObject.Path, {
d: "M20 10c0-5.51-4.49-10-10-10C4.48 0 0 4.49 0 10c0 5.52 4.48 10 10 10 5.51 0 10-4.48 10-10zM7.78 15.37L4.37 6.22c.55-.02 1.17-.08 1.17-.08.5-.06.44-1.13-.06-1.11 0 0-1.45.11-2.37.11-.18 0-.37 0-.58-.01C4.12 2.69 6.87 1.11 10 1.11c2.33 0 4.45.87 6.05 2.34-.68-.11-1.65.39-1.65 1.58 0 .74.45 1.36.9 2.1.35.61.55 1.36.55 2.46 0 1.49-1.4 5-1.4 5l-3.03-8.37c.54-.02.82-.17.82-.17.5-.05.44-1.25-.06-1.22 0 0-1.44.12-2.38.12-.87 0-2.33-.12-2.33-.12-.5-.03-.56 1.2-.06 1.22l.92.08 1.26 3.41zM17.41 10c.24-.64.74-1.87.43-4.25.7 1.29 1.05 2.71 1.05 4.25 0 3.29-1.73 6.24-4.4 7.78.97-2.59 1.94-5.2 2.92-7.78zM6.1 18.09C3.12 16.65 1.11 13.53 1.11 10c0-1.3.23-2.48.72-3.59C3.25 10.3 4.67 14.2 6.1 18.09zm4.03-6.63l2.58 6.98c-.86.29-1.76.45-2.71.45-.79 0-1.57-.11-2.29-.33.81-2.38 1.62-4.74 2.42-7.1z"
}));
/* harmony default export */ var library_wordpress = (wordpress);
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-visibility/utils.js
/**
* WordPress dependencies
*/
const visibilityOptions = {
public: {
label: (0,external_wp_i18n_namespaceObject.__)('Public'),
info: (0,external_wp_i18n_namespaceObject.__)('Visible to everyone.')
},
private: {
label: (0,external_wp_i18n_namespaceObject.__)('Private'),
info: (0,external_wp_i18n_namespaceObject.__)('Only visible to site admins and editors.')
},
password: {
label: (0,external_wp_i18n_namespaceObject.__)('Password protected'),
info: (0,external_wp_i18n_namespaceObject.__)('Only those with the password can view this post.')
}
};
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-visibility/index.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PostVisibility(_ref) {
let {
onClose
} = _ref;
const instanceId = (0,external_wp_compose_namespaceObject.useInstanceId)(PostVisibility);
const {
status,
visibility,
password
} = (0,external_wp_data_namespaceObject.useSelect)(select => ({
status: select(store_store).getEditedPostAttribute('status'),
visibility: select(store_store).getEditedPostVisibility(),
password: select(store_store).getEditedPostAttribute('password')
}));
const {
editPost,
savePost
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const [hasPassword, setHasPassword] = (0,external_wp_element_namespaceObject.useState)(!!password);
const [showPrivateConfirmDialog, setShowPrivateConfirmDialog] = (0,external_wp_element_namespaceObject.useState)(false);
const setPublic = () => {
editPost({
status: visibility === 'private' ? 'draft' : status,
password: ''
});
setHasPassword(false);
};
const setPrivate = () => {
setShowPrivateConfirmDialog(true);
};
const confirmPrivate = () => {
editPost({
status: 'private',
password: ''
});
setHasPassword(false);
setShowPrivateConfirmDialog(false);
savePost();
};
const handleDialogCancel = () => {
setShowPrivateConfirmDialog(false);
};
const setPasswordProtected = () => {
editPost({
status: visibility === 'private' ? 'draft' : status,
password: password || ''
});
setHasPassword(true);
};
const updatePassword = event => {
editPost({
password: event.target.value
});
};
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "editor-post-visibility"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.__experimentalInspectorPopoverHeader, {
title: (0,external_wp_i18n_namespaceObject.__)('Visibility'),
help: (0,external_wp_i18n_namespaceObject.__)('Control how this post is viewed.'),
onClose: onClose
}), (0,external_wp_element_namespaceObject.createElement)("fieldset", {
className: "editor-post-visibility__fieldset"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.VisuallyHidden, {
as: "legend"
}, (0,external_wp_i18n_namespaceObject.__)('Visibility')), (0,external_wp_element_namespaceObject.createElement)(PostVisibilityChoice, {
instanceId: instanceId,
value: "public",
label: visibilityOptions["public"].label,
info: visibilityOptions["public"].info,
checked: visibility === 'public' && !hasPassword,
onChange: setPublic
}), (0,external_wp_element_namespaceObject.createElement)(PostVisibilityChoice, {
instanceId: instanceId,
value: "private",
label: visibilityOptions["private"].label,
info: visibilityOptions["private"].info,
checked: visibility === 'private',
onChange: setPrivate
}), (0,external_wp_element_namespaceObject.createElement)(PostVisibilityChoice, {
instanceId: instanceId,
value: "password",
label: visibilityOptions.password.label,
info: visibilityOptions.password.info,
checked: hasPassword,
onChange: setPasswordProtected
}), hasPassword && (0,external_wp_element_namespaceObject.createElement)("div", {
className: "editor-post-visibility__password"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.VisuallyHidden, {
as: "label",
htmlFor: `editor-post-visibility__password-input-${instanceId}`
}, (0,external_wp_i18n_namespaceObject.__)('Create password')), (0,external_wp_element_namespaceObject.createElement)("input", {
className: "editor-post-visibility__password-input",
id: `editor-post-visibility__password-input-${instanceId}`,
type: "text",
onChange: updatePassword,
value: password,
placeholder: (0,external_wp_i18n_namespaceObject.__)('Use a secure password')
}))), (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.__experimentalConfirmDialog, {
isOpen: showPrivateConfirmDialog,
onConfirm: confirmPrivate,
onCancel: handleDialogCancel
}, (0,external_wp_i18n_namespaceObject.__)('Would you like to privately publish this post now?')));
}
function PostVisibilityChoice(_ref2) {
let {
instanceId,
value,
label,
info,
...props
} = _ref2;
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "editor-post-visibility__choice"
}, (0,external_wp_element_namespaceObject.createElement)("input", _extends({
type: "radio",
name: `editor-post-visibility__setting-${instanceId}`,
value: value,
id: `editor-post-${value}-${instanceId}`,
"aria-describedby": `editor-post-${value}-${instanceId}-description`,
className: "editor-post-visibility__radio"
}, props)), (0,external_wp_element_namespaceObject.createElement)("label", {
htmlFor: `editor-post-${value}-${instanceId}`,
className: "editor-post-visibility__label"
}, label), (0,external_wp_element_namespaceObject.createElement)("p", {
id: `editor-post-${value}-${instanceId}-description`,
className: "editor-post-visibility__info"
}, info));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-visibility/label.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PostVisibilityLabel() {
return usePostVisibilityLabel();
}
function usePostVisibilityLabel() {
var _visibilityOptions$vi;
const visibility = (0,external_wp_data_namespaceObject.useSelect)(select => select(store_store).getEditedPostVisibility());
return (_visibilityOptions$vi = visibilityOptions[visibility]) === null || _visibilityOptions$vi === void 0 ? void 0 : _visibilityOptions$vi.label;
}
;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/typeof.js
function _typeof(o) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
return typeof o;
} : function (o) {
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
}, _typeof(o);
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/requiredArgs/index.js
function requiredArgs(required, args) {
if (args.length < required) {
throw new TypeError(required + ' argument' + (required > 1 ? 's' : '') + ' required, but only ' + args.length + ' present');
}
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/toDate/index.js
/**
* @name toDate
* @category Common Helpers
* @summary Convert the given argument to an instance of Date.
*
* @description
* Convert the given argument to an instance of Date.
*
* If the argument is an instance of Date, the function returns its clone.
*
* If the argument is a number, it is treated as a timestamp.
*
* If the argument is none of the above, the function returns Invalid Date.
*
* **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.
*
* @param {Date|Number} argument - the value to convert
* @returns {Date} the parsed date in the local time zone
* @throws {TypeError} 1 argument required
*
* @example
* // Clone the date:
* const result = toDate(new Date(2014, 1, 11, 11, 30, 30))
* //=> Tue Feb 11 2014 11:30:30
*
* @example
* // Convert the timestamp to date:
* const result = toDate(1392098430000)
* //=> Tue Feb 11 2014 11:30:30
*/
function toDate(argument) {
requiredArgs(1, arguments);
var argStr = Object.prototype.toString.call(argument);
// Clone the date
if (argument instanceof Date || _typeof(argument) === 'object' && argStr === '[object Date]') {
// Prevent the date to lose the milliseconds when passed to new Date() in IE10
return new Date(argument.getTime());
} else if (typeof argument === 'number' || argStr === '[object Number]') {
return new Date(argument);
} else {
if ((typeof argument === 'string' || argStr === '[object String]') && typeof console !== 'undefined') {
// eslint-disable-next-line no-console
console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments");
// eslint-disable-next-line no-console
console.warn(new Error().stack);
}
return new Date(NaN);
}
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/startOfMonth/index.js
/**
* @name startOfMonth
* @category Month Helpers
* @summary Return the start of a month for the given date.
*
* @description
* Return the start of a month for the given date.
* The result will be in the local timezone.
*
* @param {Date|Number} date - the original date
* @returns {Date} the start of a month
* @throws {TypeError} 1 argument required
*
* @example
* // The start of a month for 2 September 2014 11:55:00:
* const result = startOfMonth(new Date(2014, 8, 2, 11, 55, 0))
* //=> Mon Sep 01 2014 00:00:00
*/
function startOfMonth(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate(dirtyDate);
date.setDate(1);
date.setHours(0, 0, 0, 0);
return date;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/endOfMonth/index.js
/**
* @name endOfMonth
* @category Month Helpers
* @summary Return the end of a month for the given date.
*
* @description
* Return the end of a month for the given date.
* The result will be in the local timezone.
*
* @param {Date|Number} date - the original date
* @returns {Date} the end of a month
* @throws {TypeError} 1 argument required
*
* @example
* // The end of a month for 2 September 2014 11:55:00:
* const result = endOfMonth(new Date(2014, 8, 2, 11, 55, 0))
* //=> Tue Sep 30 2014 23:59:59.999
*/
function endOfMonth(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate(dirtyDate);
var month = date.getMonth();
date.setFullYear(date.getFullYear(), month + 1, 0);
date.setHours(23, 59, 59, 999);
return date;
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/constants/index.js
/**
* Days in 1 week.
*
* @name daysInWeek
* @constant
* @type {number}
* @default
*/
var daysInWeek = 7;
/**
* Days in 1 year
* One years equals 365.2425 days according to the formula:
*
* > Leap year occures every 4 years, except for years that are divisable by 100 and not divisable by 400.
* > 1 mean year = (365+1/4-1/100+1/400) days = 365.2425 days
*
* @name daysInYear
* @constant
* @type {number}
* @default
*/
var daysInYear = 365.2425;
/**
* Maximum allowed time.
*
* @name maxTime
* @constant
* @type {number}
* @default
*/
var maxTime = Math.pow(10, 8) * 24 * 60 * 60 * 1000;
/**
* Milliseconds in 1 minute
*
* @name millisecondsInMinute
* @constant
* @type {number}
* @default
*/
var millisecondsInMinute = 60000;
/**
* Milliseconds in 1 hour
*
* @name millisecondsInHour
* @constant
* @type {number}
* @default
*/
var millisecondsInHour = 3600000;
/**
* Milliseconds in 1 second
*
* @name millisecondsInSecond
* @constant
* @type {number}
* @default
*/
var millisecondsInSecond = 1000;
/**
* Minimum allowed time.
*
* @name minTime
* @constant
* @type {number}
* @default
*/
var minTime = -maxTime;
/**
* Minutes in 1 hour
*
* @name minutesInHour
* @constant
* @type {number}
* @default
*/
var minutesInHour = 60;
/**
* Months in 1 quarter
*
* @name monthsInQuarter
* @constant
* @type {number}
* @default
*/
var monthsInQuarter = 3;
/**
* Months in 1 year
*
* @name monthsInYear
* @constant
* @type {number}
* @default
*/
var monthsInYear = 12;
/**
* Quarters in 1 year
*
* @name quartersInYear
* @constant
* @type {number}
* @default
*/
var quartersInYear = 4;
/**
* Seconds in 1 hour
*
* @name secondsInHour
* @constant
* @type {number}
* @default
*/
var secondsInHour = 3600;
/**
* Seconds in 1 minute
*
* @name secondsInMinute
* @constant
* @type {number}
* @default
*/
var secondsInMinute = 60;
/**
* Seconds in 1 day
*
* @name secondsInDay
* @constant
* @type {number}
* @default
*/
var secondsInDay = secondsInHour * 24;
/**
* Seconds in 1 week
*
* @name secondsInWeek
* @constant
* @type {number}
* @default
*/
var secondsInWeek = secondsInDay * 7;
/**
* Seconds in 1 year
*
* @name secondsInYear
* @constant
* @type {number}
* @default
*/
var secondsInYear = secondsInDay * daysInYear;
/**
* Seconds in 1 month
*
* @name secondsInMonth
* @constant
* @type {number}
* @default
*/
var secondsInMonth = secondsInYear / 12;
/**
* Seconds in 1 quarter
*
* @name secondsInQuarter
* @constant
* @type {number}
* @default
*/
var secondsInQuarter = secondsInMonth * 3;
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/_lib/toInteger/index.js
function toInteger(dirtyNumber) {
if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) {
return NaN;
}
var number = Number(dirtyNumber);
if (isNaN(number)) {
return number;
}
return number < 0 ? Math.ceil(number) : Math.floor(number);
}
;// CONCATENATED MODULE: ./node_modules/date-fns/esm/parseISO/index.js
/**
* @name parseISO
* @category Common Helpers
* @summary Parse ISO string
*
* @description
* Parse the given string in ISO 8601 format and return an instance of Date.
*
* Function accepts complete ISO 8601 formats as well as partial implementations.
* ISO 8601: http://en.wikipedia.org/wiki/ISO_8601
*
* If the argument isn't a string, the function cannot parse the string or
* the values are invalid, it returns Invalid Date.
*
* @param {String} argument - the value to convert
* @param {Object} [options] - an object with options.
* @param {0|1|2} [options.additionalDigits=2] - the additional number of digits in the extended year format
* @returns {Date} the parsed date in the local time zone
* @throws {TypeError} 1 argument required
* @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2
*
* @example
* // Convert string '2014-02-11T11:30:30' to date:
* const result = parseISO('2014-02-11T11:30:30')
* //=> Tue Feb 11 2014 11:30:30
*
* @example
* // Convert string '+02014101' to date,
* // if the additional number of digits in the extended year format is 1:
* const result = parseISO('+02014101', { additionalDigits: 1 })
* //=> Fri Apr 11 2014 00:00:00
*/
function parseISO(argument, options) {
var _options$additionalDi;
requiredArgs(1, arguments);
var additionalDigits = toInteger((_options$additionalDi = options === null || options === void 0 ? void 0 : options.additionalDigits) !== null && _options$additionalDi !== void 0 ? _options$additionalDi : 2);
if (additionalDigits !== 2 && additionalDigits !== 1 && additionalDigits !== 0) {
throw new RangeError('additionalDigits must be 0, 1 or 2');
}
if (!(typeof argument === 'string' || Object.prototype.toString.call(argument) === '[object String]')) {
return new Date(NaN);
}
var dateStrings = splitDateString(argument);
var date;
if (dateStrings.date) {
var parseYearResult = parseYear(dateStrings.date, additionalDigits);
date = parseDate(parseYearResult.restDateString, parseYearResult.year);
}
if (!date || isNaN(date.getTime())) {
return new Date(NaN);
}
var timestamp = date.getTime();
var time = 0;
var offset;
if (dateStrings.time) {
time = parseTime(dateStrings.time);
if (isNaN(time)) {
return new Date(NaN);
}
}
if (dateStrings.timezone) {
offset = parseTimezone(dateStrings.timezone);
if (isNaN(offset)) {
return new Date(NaN);
}
} else {
var dirtyDate = new Date(timestamp + time);
// js parsed string assuming it's in UTC timezone
// but we need it to be parsed in our timezone
// so we use utc values to build date in our timezone.
// Year values from 0 to 99 map to the years 1900 to 1999
// so set year explicitly with setFullYear.
var result = new Date(0);
result.setFullYear(dirtyDate.getUTCFullYear(), dirtyDate.getUTCMonth(), dirtyDate.getUTCDate());
result.setHours(dirtyDate.getUTCHours(), dirtyDate.getUTCMinutes(), dirtyDate.getUTCSeconds(), dirtyDate.getUTCMilliseconds());
return result;
}
return new Date(timestamp + time + offset);
}
var patterns = {
dateTimeDelimiter: /[T ]/,
timeZoneDelimiter: /[Z ]/i,
timezone: /([Z+-].*)$/
};
var dateRegex = /^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/;
var timeRegex = /^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/;
var timezoneRegex = /^([+-])(\d{2})(?::?(\d{2}))?$/;
function splitDateString(dateString) {
var dateStrings = {};
var array = dateString.split(patterns.dateTimeDelimiter);
var timeString;
// The regex match should only return at maximum two array elements.
// [date], [time], or [date, time].
if (array.length > 2) {
return dateStrings;
}
if (/:/.test(array[0])) {
timeString = array[0];
} else {
dateStrings.date = array[0];
timeString = array[1];
if (patterns.timeZoneDelimiter.test(dateStrings.date)) {
dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0];
timeString = dateString.substr(dateStrings.date.length, dateString.length);
}
}
if (timeString) {
var token = patterns.timezone.exec(timeString);
if (token) {
dateStrings.time = timeString.replace(token[1], '');
dateStrings.timezone = token[1];
} else {
dateStrings.time = timeString;
}
}
return dateStrings;
}
function parseYear(dateString, additionalDigits) {
var regex = new RegExp('^(?:(\\d{4}|[+-]\\d{' + (4 + additionalDigits) + '})|(\\d{2}|[+-]\\d{' + (2 + additionalDigits) + '})$)');
var captures = dateString.match(regex);
// Invalid ISO-formatted year
if (!captures) return {
year: NaN,
restDateString: ''
};
var year = captures[1] ? parseInt(captures[1]) : null;
var century = captures[2] ? parseInt(captures[2]) : null;
// either year or century is null, not both
return {
year: century === null ? year : century * 100,
restDateString: dateString.slice((captures[1] || captures[2]).length)
};
}
function parseDate(dateString, year) {
// Invalid ISO-formatted year
if (year === null) return new Date(NaN);
var captures = dateString.match(dateRegex);
// Invalid ISO-formatted string
if (!captures) return new Date(NaN);
var isWeekDate = !!captures[4];
var dayOfYear = parseDateUnit(captures[1]);
var month = parseDateUnit(captures[2]) - 1;
var day = parseDateUnit(captures[3]);
var week = parseDateUnit(captures[4]);
var dayOfWeek = parseDateUnit(captures[5]) - 1;
if (isWeekDate) {
if (!validateWeekDate(year, week, dayOfWeek)) {
return new Date(NaN);
}
return dayOfISOWeekYear(year, week, dayOfWeek);
} else {
var date = new Date(0);
if (!validateDate(year, month, day) || !validateDayOfYearDate(year, dayOfYear)) {
return new Date(NaN);
}
date.setUTCFullYear(year, month, Math.max(dayOfYear, day));
return date;
}
}
function parseDateUnit(value) {
return value ? parseInt(value) : 1;
}
function parseTime(timeString) {
var captures = timeString.match(timeRegex);
if (!captures) return NaN; // Invalid ISO-formatted time
var hours = parseTimeUnit(captures[1]);
var minutes = parseTimeUnit(captures[2]);
var seconds = parseTimeUnit(captures[3]);
if (!validateTime(hours, minutes, seconds)) {
return NaN;
}
return hours * millisecondsInHour + minutes * millisecondsInMinute + seconds * 1000;
}
function parseTimeUnit(value) {
return value && parseFloat(value.replace(',', '.')) || 0;
}
function parseTimezone(timezoneString) {
if (timezoneString === 'Z') return 0;
var captures = timezoneString.match(timezoneRegex);
if (!captures) return 0;
var sign = captures[1] === '+' ? -1 : 1;
var hours = parseInt(captures[2]);
var minutes = captures[3] && parseInt(captures[3]) || 0;
if (!validateTimezone(hours, minutes)) {
return NaN;
}
return sign * (hours * millisecondsInHour + minutes * millisecondsInMinute);
}
function dayOfISOWeekYear(isoWeekYear, week, day) {
var date = new Date(0);
date.setUTCFullYear(isoWeekYear, 0, 4);
var fourthOfJanuaryDay = date.getUTCDay() || 7;
var diff = (week - 1) * 7 + day + 1 - fourthOfJanuaryDay;
date.setUTCDate(date.getUTCDate() + diff);
return date;
}
// Validation functions
// February is null to handle the leap year (using ||)
var daysInMonths = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function isLeapYearIndex(year) {
return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0;
}
function validateDate(year, month, date) {
return month >= 0 && month <= 11 && date >= 1 && date <= (daysInMonths[month] || (isLeapYearIndex(year) ? 29 : 28));
}
function validateDayOfYearDate(year, dayOfYear) {
return dayOfYear >= 1 && dayOfYear <= (isLeapYearIndex(year) ? 366 : 365);
}
function validateWeekDate(_year, week, day) {
return week >= 1 && week <= 53 && day >= 0 && day <= 6;
}
function validateTime(hours, minutes, seconds) {
if (hours === 24) {
return minutes === 0 && seconds === 0;
}
return seconds >= 0 && seconds < 60 && minutes >= 0 && minutes < 60 && hours >= 0 && hours < 25;
}
function validateTimezone(_hours, minutes) {
return minutes >= 0 && minutes <= 59;
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-schedule/index.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PostSchedule(_ref) {
let {
onClose
} = _ref;
const {
postDate,
postType
} = (0,external_wp_data_namespaceObject.useSelect)(select => ({
postDate: select(store_store).getEditedPostAttribute('date'),
postType: select(store_store).getCurrentPostType()
}), []);
const {
editPost
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
const onUpdateDate = date => editPost({
date
});
const [previewedMonth, setPreviewedMonth] = (0,external_wp_element_namespaceObject.useState)(startOfMonth(new Date(postDate))); // Pick up published and schduled site posts.
const eventsByPostType = (0,external_wp_data_namespaceObject.useSelect)(select => select(external_wp_coreData_namespaceObject.store).getEntityRecords('postType', postType, {
status: 'publish,future',
after: startOfMonth(previewedMonth).toISOString(),
before: endOfMonth(previewedMonth).toISOString(),
exclude: [select(store_store).getCurrentPostId()],
per_page: 100,
_fields: 'id,date'
}), [previewedMonth, postType]);
const events = (0,external_wp_element_namespaceObject.useMemo)(() => (eventsByPostType || []).map(_ref2 => {
let {
date: eventDate
} = _ref2;
return {
date: new Date(eventDate)
};
}), [eventsByPostType]);
const settings = (0,external_wp_date_namespaceObject.getSettings)(); // To know if the current timezone is a 12 hour time with look for "a" in the time format
// We also make sure this a is not escaped by a "/"
const is12HourTime = /a(?!\\)/i.test(settings.formats.time.toLowerCase() // Test only the lower case a.
.replace(/\\\\/g, '') // Replace "//" with empty strings.
.split('').reverse().join('') // Reverse the string and test for "a" not followed by a slash.
);
return (0,external_wp_element_namespaceObject.createElement)(external_wp_blockEditor_namespaceObject.__experimentalPublishDateTimePicker, {
currentDate: postDate,
onChange: onUpdateDate,
is12Hour: is12HourTime,
events: events,
onMonthPreviewed: date => setPreviewedMonth(parseISO(date)),
onClose: onClose
});
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-schedule/label.js
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
function PostScheduleLabel(props) {
return usePostScheduleLabel(props);
}
function usePostScheduleLabel() {
let {
full = false
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const {
date,
isFloating
} = (0,external_wp_data_namespaceObject.useSelect)(select => ({
date: select(store_store).getEditedPostAttribute('date'),
isFloating: select(store_store).isEditedPostDateFloating()
}), []);
return full ? getFullPostScheduleLabel(date) : getPostScheduleLabel(date, {
isFloating
});
}
function getFullPostScheduleLabel(dateAttribute) {
const date = (0,external_wp_date_namespaceObject.getDate)(dateAttribute);
const timezoneAbbreviation = getTimezoneAbbreviation();
const formattedDate = (0,external_wp_date_namespaceObject.dateI18n)( // translators: If using a space between 'g:i' and 'a', use a non-breaking sapce.
(0,external_wp_i18n_namespaceObject._x)('F j, Y g:i\xa0a', 'post schedule full date format'), date);
return (0,external_wp_i18n_namespaceObject.isRTL)() ? `${timezoneAbbreviation} ${formattedDate}` : `${formattedDate} ${timezoneAbbreviation}`;
}
function getPostScheduleLabel(dateAttribute) {
let {
isFloating = false,
now = new Date()
} = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (!dateAttribute || isFloating) {
return (0,external_wp_i18n_namespaceObject.__)('Immediately');
} // If the user timezone does not equal the site timezone then using words
// like 'tomorrow' is confusing, so show the full date.
if (!isTimezoneSameAsSiteTimezone(now)) {
return getFullPostScheduleLabel(dateAttribute);
}
const date = (0,external_wp_date_namespaceObject.getDate)(dateAttribute);
if (isSameDay(date, now)) {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: Time of day the post is scheduled for.
(0,external_wp_i18n_namespaceObject.__)('Today at %s'), // translators: If using a space between 'g:i' and 'a', use a non-breaking sapce.
(0,external_wp_date_namespaceObject.dateI18n)((0,external_wp_i18n_namespaceObject._x)('g:i\xa0a', 'post schedule time format'), date));
}
const tomorrow = new Date(now);
tomorrow.setDate(tomorrow.getDate() + 1);
if (isSameDay(date, tomorrow)) {
return (0,external_wp_i18n_namespaceObject.sprintf)( // translators: %s: Time of day the post is scheduled for.
(0,external_wp_i18n_namespaceObject.__)('Tomorrow at %s'), // translators: If using a space between 'g:i' and 'a', use a non-breaking sapce.
(0,external_wp_date_namespaceObject.dateI18n)((0,external_wp_i18n_namespaceObject._x)('g:i\xa0a', 'post schedule time format'), date));
}
if (date.getFullYear() === now.getFullYear()) {
return (0,external_wp_date_namespaceObject.dateI18n)( // translators: If using a space between 'g:i' and 'a', use a non-breaking sapce.
(0,external_wp_i18n_namespaceObject._x)('F j g:i\xa0a', 'post schedule date format without year'), date);
}
return (0,external_wp_date_namespaceObject.dateI18n)( // translators: Use a non-breaking space between 'g:i' and 'a' if appropriate.
(0,external_wp_i18n_namespaceObject._x)('F j, Y g:i\xa0a', 'post schedule full date format'), date);
}
function getTimezoneAbbreviation() {
const {
timezone
} = (0,external_wp_date_namespaceObject.getSettings)();
if (timezone.abbr && isNaN(Number(timezone.abbr))) {
return timezone.abbr;
}
const symbol = timezone.offset < 0 ? '' : '+';
return `UTC${symbol}${timezone.offset}`;
}
function isTimezoneSameAsSiteTimezone(date) {
const {
timezone
} = (0,external_wp_date_namespaceObject.getSettings)();
const siteOffset = Number(timezone.offset);
const dateOffset = -1 * (date.getTimezoneOffset() / 60);
return siteOffset === dateOffset;
}
function isSameDay(left, right) {
return left.getDate() === right.getDate() && left.getMonth() === right.getMonth() && left.getFullYear() === right.getFullYear();
}
// EXTERNAL MODULE: ./node_modules/escape-html/index.js
var escape_html = __webpack_require__(3613);
var escape_html_default = /*#__PURE__*/__webpack_require__.n(escape_html);
;// CONCATENATED MODULE: external ["wp","a11y"]
var external_wp_a11y_namespaceObject = window["wp"]["a11y"];
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-taxonomies/most-used-terms.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
const MIN_MOST_USED_TERMS = 3;
const DEFAULT_QUERY = {
per_page: 10,
orderby: 'count',
order: 'desc',
hide_empty: true,
_fields: 'id,name,count',
context: 'view'
};
function MostUsedTerms(_ref) {
let {
onSelect,
taxonomy
} = _ref;
const {
_terms,
showTerms
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const mostUsedTerms = select(external_wp_coreData_namespaceObject.store).getEntityRecords('taxonomy', taxonomy.slug, DEFAULT_QUERY);
return {
_terms: mostUsedTerms,
showTerms: (mostUsedTerms === null || mostUsedTerms === void 0 ? void 0 : mostUsedTerms.length) >= MIN_MOST_USED_TERMS
};
}, []);
if (!showTerms) {
return null;
}
const terms = unescapeTerms(_terms);
const label = (0,external_lodash_namespaceObject.get)(taxonomy, ['labels', 'most_used']);
return (0,external_wp_element_namespaceObject.createElement)("div", {
className: "editor-post-taxonomies__flat-term-most-used"
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.BaseControl.VisualLabel, {
as: "h3",
className: "editor-post-taxonomies__flat-term-most-used-label"
}, label), (0,external_wp_element_namespaceObject.createElement)("ul", {
role: "list",
className: "editor-post-taxonomies__flat-term-most-used-list"
}, terms.map(term => (0,external_wp_element_namespaceObject.createElement)("li", {
key: term.id
}, (0,external_wp_element_namespaceObject.createElement)(external_wp_components_namespaceObject.Button, {
variant: "link",
onClick: () => onSelect(term)
}, term.name)))));
}
;// CONCATENATED MODULE: ./node_modules/@wordpress/editor/build-module/components/post-taxonomies/flat-term-selector.js
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Shared reference to an empty array for cases where it is important to avoid
* returning a new array reference on every invocation.
*
* @type {Array<any>}
*/
const flat_term_selector_EMPTY_ARRAY = [];
/**
* Module constants
*/
const MAX_TERMS_SUGGESTIONS = 20;
const flat_term_selector_DEFAULT_QUERY = {
per_page: MAX_TERMS_SUGGESTIONS,
orderby: 'count',
order: 'desc',
_fields: 'id,name',
context: 'view'
};
const isSameTermName = (termA, termB) => unescapeString(termA).toLowerCase() === unescapeString(termB).toLowerCase();
const termNamesToIds = (names, terms) => {
return names.map(termName => terms.find(term => isSameTermName(term.name, termName)).id);
}; // Tries to create a term or fetch it if it already exists.
function findOrCreateTerm(termName, restBase, namespace) {
const escapedTermName = escape_html_default()(termName);
return external_wp_apiFetch_default()({
path: `/${namespace}/${restBase}`,
method: 'POST',
data: {
name: escapedTermName
}
}).catch(error => {
if (error.code !== 'term_exists') {
return Promise.reject(error);
}
return Promise.resolve({
id: error.data.term_id,
name: termName
});
}).then(unescapeTerm);
}
function FlatTermSelector(_ref) {
let {
slug
} = _ref;
const [values, setValues] = (0,external_wp_element_namespaceObject.useState)([]);
const [search, setSearch] = (0,external_wp_element_namespaceObject.useState)('');
const debouncedSearch = (0,external_wp_compose_namespaceObject.useDebounce)(setSearch, 500);
const {
terms,
termIds,
taxonomy,
hasAssignAction,
hasCreateAction,
hasResolvedTerms
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getCurrentPost,
getEditedPostAttribute
} = select(store_store);
const {
getEntityRecords,
getTaxonomy,
hasFinishedResolution
} = select(external_wp_coreData_namespaceObject.store);
const post = getCurrentPost();
const _taxonomy = getTaxonomy(slug);
const _termIds = _taxonomy ? getEditedPostAttribute(_taxonomy.rest_base) : flat_term_selector_EMPTY_ARRAY;
const query = { ...flat_term_selector_DEFAULT_QUERY,
include: _termIds.join(','),
per_page: -1
};
return {
hasCreateAction: _taxonomy ? (0,external_lodash_namespaceObject.get)(post, ['_links', 'wp:action-create-' + _taxonomy.rest_base], false) : false,
hasAssignAction: _taxonomy ? (0,external_lodash_namespaceObject.get)(post, ['_links', 'wp:action-assign-' + _taxonomy.rest_base], false) : false,
taxonomy: _taxonomy,
termIds: _termIds,
terms: _termIds.length ? getEntityRecords('taxonomy', slug, query) : flat_term_selector_EMPTY_ARRAY,
hasResolvedTerms: hasFinishedResolution('getEntityRecords', ['taxonomy', slug, query])
};
}, [slug]);
const {
searchResults
} = (0,external_wp_data_namespaceObject.useSelect)(select => {
const {
getEntityRecords
} = select(external_wp_coreData_namespaceObject.store);
return {
searchResults: !!search ? getEntityRecords('taxonomy', slug, { ...flat_term_selector_DEFAULT_QUERY,
search
}) : flat_term_selector_EMPTY_ARRAY
};
}, [search]); // Update terms state only after the selectors are resolved.
// We're using this to avoid terms temporarily disappearing on slow networks
// while core data makes REST API requests.
(0,external_wp_element_namespaceObject.useEffect)(() => {
if (hasResolvedTerms) {
const newValues = (terms !== null && terms !== void 0 ? terms : []).map(term => unescapeString(term.name));
setValues(newValues);
}
}, [terms, hasResolvedTerms]);
const suggestions = (0,external_wp_element_namespaceObject.useMemo)(() => {
return (searchResults !== null && searchResults !== void 0 ? searchResults : []).map(term => unescapeString(term.name));
}, [searchResults]);
const {
editPost
} = (0,external_wp_data_namespaceObject.useDispatch)(store_store);
if (!hasAssignAction) {
return null;
}
function onUpdateTerms(newTermIds) {
editPost({
[taxonomy.rest_base]: newTermIds
});
}
function onChange(termNames) {
var _taxonomy$rest_namesp;
const availableTerms = [...(terms !== null && terms !== void 0 ? terms : []), ...(searchResults !== null && searchResults !== void 0 ? searchResults : [])];
const uniqueTerms = termNames.reduce((acc, name) => {
if (!acc.some(n => n.toLowerCase() === name.toLowerCase())) {
acc.push(name);
}
return acc;
}, []);
const newTermNames = uniqueTerms.filter(termName => !availableTerms.find(term => isSameTermName(term.name, termName))); // Optimistically update term values.
// The selector will always re-fetch terms later.
setValues(uniqueTerms);
if (newTermNames.length === 0) {
return onUpdateTerms(termNamesToIds(uniqueTerms, availableTerms));
}
if (!hasCreateAction) {
return;
}
const namespace = (_taxonomy$rest_namesp = taxonomy === null || taxonomy === void 0 ? void 0 : taxonomy.rest_namespace) !== null && _taxonomy$rest_namesp !== void 0 ? _taxonomy$rest_namesp : 'wp/v2';
Promise.all(newTermNames.map(termName => findOrCreateTerm(termName, taxonomy.rest_base, namespace))).then(newTerms => {
const newAvailableTerms = availableTerms.concat(newTerms);
return onUpdateTerms(termNamesToIds(uniqueTerms, newAvailableTerms));
});
}
function appendTerm(newTerm) {
if (termIds.includes(newTerm.id)) {
return;
}
const newTermIds = [...termIds, newTerm.id];
const termAddedMessage = (0,external_wp_i18n_namespaceObject.sprintf)(
/* translators: %s: term name. */
(0,external_wp_i18n_namespaceObject._x)('%s added', 'term'), (0,external_lodash_namespaceObject.get)(taxonomy, ['labels', 'singular_name'], slug === 'post_tag' ? (0,external_wp_i18n_namespaceObject.__)('Tag') : (0,external_wp_i18n_namespaceObject.__)('Term')));
(0,external_wp_a11y_namespaceObject.speak)(termAddedMessage, 'assertive');
onUpdateTerms(newTermIds);
}
const newTermLabel = (0,external_lodash_namespaceObject.get)(taxonomy, ['labels', 'add_new_item'], slug === 'post_tag' ? (0,external_wp_i18n_namespaceObject.__)('Add new tag') : (0,external_wp_i18n_namesp